- move: null string to utils

This commit is contained in:
2024-12-13 14:32:07 -05:00
parent 51e2fef9df
commit 444e69294c
6 changed files with 5 additions and 4 deletions

View File

@@ -11,3 +11,4 @@ rand = "0.9.0-beta.1"
uuid = { version = "1.11.0", features = ["v4"] }
warp = "0.3.7"
tokio = "1.41.1"
bincode = { version = "2.0.0-rc.3", features = ["derive", "serde"] }

View File

@@ -1,2 +1,3 @@
pub mod consul_registration;
pub mod service_discovery;
pub mod null_string;

43
utils/src/null_string.rs Normal file
View File

@@ -0,0 +1,43 @@
use bincode::{Decode, Encode, de::Decoder, enc::Encoder, error::{DecodeError, EncodeError}};
use std::str;
use bincode::de::read::Reader;
use bincode::enc::write::Writer;
#[derive(Debug)]
pub struct NullTerminatedString(pub String);
impl NullTerminatedString {
pub fn new(string: &str) -> Self {
NullTerminatedString(string.into())
}
}
impl Encode for NullTerminatedString {
fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
let bytes = self.0.as_bytes();
encoder.writer().write(bytes)?; // Write the string bytes
encoder.writer().write(&[0])?; // Add the null terminator
Ok(())
}
}
impl Decode for NullTerminatedString {
fn decode<D: Decoder>(decoder: &mut D) -> Result<Self, DecodeError> {
let mut buffer = Vec::new();
let mut byte = [0u8; 1];
// Read until the null terminator
while decoder.reader().read(&mut byte).is_ok() {
if byte[0] == 0 {
break; // Null terminator found
}
buffer.push(byte[0]);
}
let string = str::from_utf8(&buffer)
.map_err(|e| DecodeError::OtherString(format!("Invalid UTF-8: {}", e)))?
.to_string();
Ok(NullTerminatedString(string))
}
}