diff --git a/backend/sync_lib/Cargo.toml b/backend/sync_lib/Cargo.toml new file mode 100644 index 00000000..1e1b048a --- /dev/null +++ b/backend/sync_lib/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "sync_lib" +version = "0.1.0" +edition = "2024" + +[dependencies] +base64 = "0.22.1" + +thiserror = {workspace = true} diff --git a/backend/sync_lib/src/errors.rs b/backend/sync_lib/src/errors.rs new file mode 100644 index 00000000..acc865e1 --- /dev/null +++ b/backend/sync_lib/src/errors.rs @@ -0,0 +1,24 @@ +use base64::DecodeError; +use thiserror::Error; + +#[derive(Error, Debug)] +pub enum SyncLibError { + #[error("Base64 decoding error: {}", .reason)] + DecodingError { reason: String }, +} + +impl From for SyncLibError { + fn from(e: DecodeError) -> Self { + SyncLibError::DecodingError { + reason: e.to_string(), + } + } +} + +impl From for SyncLibError { + fn from(e: std::string::FromUtf8Error) -> Self { + SyncLibError::DecodingError { + reason: e.to_string(), + } + } +} diff --git a/backend/sync_lib/src/lib.rs b/backend/sync_lib/src/lib.rs new file mode 100644 index 00000000..5e42e905 --- /dev/null +++ b/backend/sync_lib/src/lib.rs @@ -0,0 +1,25 @@ +use base64::{Engine as _, engine::general_purpose::STANDARD_NO_PAD}; +use errors::SyncLibError; + +pub mod errors; + +pub fn bytes_to_base64(input: &[u8]) -> String { + STANDARD_NO_PAD.encode(input) +} + +pub fn string_to_base64(input: &str) -> String { + bytes_to_base64(input.as_bytes()) +} + +pub fn base64_to_bytes(input: &str) -> Result, SyncLibError> { + STANDARD_NO_PAD.decode(input).map_err(SyncLibError::from) +} + +pub fn base64_to_string(input: &str) -> Result { + let bytes = base64_to_bytes(input)?; + String::from_utf8(bytes).map_err(SyncLibError::from) +} + +pub fn is_binary(data: &[u8]) -> bool { + data.iter().any(|&b| b == 0) +}