Skip to content

Commit

Permalink
Make encode more flexible
Browse files Browse the repository at this point in the history
By using `impl AsRef<[u8]>` instead of raw `&[u8]` encode may be used
with Strings and string slices directly. This is also important for
foreign types as they can implement `AsRef<[u8]>` and be directly
usable by `encode`.

Signed-off-by: Wiktor Kwapisiewicz <[email protected]>
  • Loading branch information
wiktor-k committed Oct 16, 2024
1 parent b95ebc3 commit 1243383
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ cargo add z-base-32
The library exposes two functions with the following signatures and an error type:

```rs
pub fn encode(input: &[u8]) -> String;
pub fn encode(input: impl AsRef<[u8]>) -> String;

pub fn decode(input: &str) -> Result<Vec<u8>, DecodeError>;

Expand Down
14 changes: 13 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ impl fmt::Display for DecodeError {
}
}

pub fn encode(input: &[u8]) -> String {
pub fn encode(input: impl AsRef<[u8]>) -> String {
let input = input.as_ref();
let mut result = Vec::new();
let chunks = input.chunks(5);

Expand Down Expand Up @@ -92,6 +93,17 @@ mod tests {
assert_eq!(encode(b"asdasd"), "cf3seamuco".to_string());
}

#[test]
fn encode_str() {
assert_eq!(encode("asdasd"), "cf3seamuco".to_string());
}

#[test]
fn encode_string() {
let string = String::from("asdasd");
assert_eq!(encode(string), "cf3seamuco".to_string());
}

#[test]
fn simple_decode() {
assert_eq!(decode("cf3seamu"), Ok(b"asdas".to_vec()))
Expand Down

0 comments on commit 1243383

Please sign in to comment.