From bf21ebaaae44b267cfefc87eee9608c09aab96b7 Mon Sep 17 00:00:00 2001 From: Will Dillon Date: Thu, 4 Dec 2025 17:07:12 +0000 Subject: Getting closer to no-std being done --- src/string_helper.rs | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 src/string_helper.rs (limited to 'src/string_helper.rs') diff --git a/src/string_helper.rs b/src/string_helper.rs new file mode 100644 index 0000000..e5af42b --- /dev/null +++ b/src/string_helper.rs @@ -0,0 +1,70 @@ +#[cfg(not(feature = "std"))] +use arraystring::{ArrayString, typenum::{U32, U160}}; + +#[cfg(feature = "std")] +pub(crate) type NameString = String; + +#[cfg(feature = "std")] +pub(crate) fn name_string_from_slice(s: &[u8]) -> NameString { + match String::from_utf8(s.to_vec()) { + Ok(s) => s, + Err(_) => "Unable to create string".to_string() + } +} + +#[cfg(not(feature = "std"))] +pub(crate) type NameString = ArrayString; + +#[cfg(not(feature = "std"))] +pub(crate) fn name_string_from_slice(s: &[u8]) -> NameString { + NameString::from_str_truncate(s) +} + +#[cfg(feature = "std")] +pub(crate) type MessageString = String; + +#[cfg(not(feature = "std"))] +pub(crate) type MessageString = ArrayString; + +#[cfg(feature = "std")] +pub(crate) fn message_string_from_slice(s: &[u8]) -> MessageString { + let mut split = s.split(|c| *c == 0); + + if let Some(s) = split.next() { + match String::from_utf8(s.to_vec()) { + Ok(s) => { + s.trim().to_string() + } + Err(_) => "Unable to create string".to_string() + } + } else { + "".to_string() + } +} + +#[cfg(not(feature = "std"))] +pub(crate) fn message_string_from_slice(s: &[u8]) -> MessageString { + MessageString::from_str_truncate(s) +} + +#[cfg(feature = "std")] +pub(crate) type PasswordString = String; + +// I believe that a password can only be 141 characters, +// but given it's close enough to 160, let's just round +// up so it's the same as MessageString. +#[cfg(not(feature = "std"))] +pub(crate) type PasswordString = ArrayString; + +#[cfg(feature = "std")] +pub(crate) fn password_string_from_slice(s: &[u8]) -> PasswordString { + match String::from_utf8(s.to_vec()) { + Ok(s) => s, + Err(_) => "".to_string() + } +} + +#[cfg(not(feature = "std"))] +pub(crate) fn password_string_from_slice(s: &[u8]) -> PasswordString { + PasswordString::from_str_truncate(s) +} -- cgit v1.2.3