From c3d384b8c2a505c903b1925b77d4b8170653dd48 Mon Sep 17 00:00:00 2001 From: Wiktor Kwapisiewicz Date: Wed, 16 Oct 2024 08:50:40 +0200 Subject: [PATCH] Make `encode` more flexible 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 --- src/lib.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index ffc382a..f9ab991 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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); @@ -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()))