Extract binary merging logic

This commit is contained in:
Andras Schmelczer 2024-12-12 22:07:36 +00:00
parent 7a8cca8fe7
commit 10bc8c7099
No known key found for this signature in database
GPG key ID: FC8F2C3D3D1A718C
9 changed files with 55 additions and 57 deletions

View file

@ -1,16 +1,29 @@
use std::str::Utf8Error;
use base64::DecodeError;
use thiserror::Error;
use wasm_bindgen::JsValue;
#[derive(Error, Debug)]
pub enum SyncLibError {
#[error("Base64 decoding error: {}", .reason)]
DecodingError { reason: String },
#[error("Base64 decoding error because of {}", .reason)]
Base64DecodingError { reason: String },
#[error("Bytes cannot be decoded as UTF-8 string because of {}", .reason)]
StringDecodingError { reason: String },
}
impl From<DecodeError> for SyncLibError {
fn from(e: DecodeError) -> Self {
SyncLibError::DecodingError {
SyncLibError::Base64DecodingError {
reason: e.to_string(),
}
}
}
impl From<Utf8Error> for SyncLibError {
fn from(e: Utf8Error) -> Self {
SyncLibError::StringDecodingError {
reason: e.to_string(),
}
}
@ -18,7 +31,7 @@ impl From<DecodeError> for SyncLibError {
impl From<std::string::FromUtf8Error> for SyncLibError {
fn from(e: std::string::FromUtf8Error) -> Self {
SyncLibError::DecodingError {
SyncLibError::Base64DecodingError {
reason: e.to_string(),
}
}

View file

@ -1,3 +1,5 @@
use core::str;
use base64::{engine::general_purpose::STANDARD_NO_PAD, Engine as _};
use errors::SyncLibError;
use wasm_bindgen::prelude::*;
@ -27,6 +29,20 @@ pub fn base64_to_string(input: &str) -> Result<String, SyncLibError> {
String::from_utf8(bytes).map_err(SyncLibError::from)
}
#[wasm_bindgen]
pub fn merge(parent: &[u8], left: &[u8], right: &[u8]) -> Result<Vec<u8>, SyncLibError> {
Ok(if is_binary(right) {
right.to_vec()
} else {
reconcile::reconcile(
str::from_utf8(parent).map_err(SyncLibError::from)?,
str::from_utf8(left).map_err(SyncLibError::from)?,
str::from_utf8(right).map_err(SyncLibError::from)?,
)
.into_bytes()
})
}
#[wasm_bindgen]
pub fn is_binary(data: &[u8]) -> bool { data.iter().any(|&b| b == 0) }