feat(proto): add protocol primitives

This commit is contained in:
Jindřich Moravec 2023-12-11 16:36:52 +01:00
parent f70fd6250b
commit aa649769d2
7 changed files with 173 additions and 0 deletions

View file

@ -0,0 +1,54 @@
use bincode::de::Decoder;
use bincode::enc::write::Writer;
use bincode::enc::Encoder;
use bincode::error::{DecodeError, EncodeError};
use bincode::{BorrowDecode, Decode, Encode};
#[derive(Debug, Clone, BorrowDecode)]
pub struct PgString(String);
impl PgString {
pub fn as_str(&self) -> &str {
&self.0
}
}
impl From<&str> for PgString {
fn from(string: &str) -> Self {
PgString(string.to_string())
}
}
impl From<PgString> for String {
fn from(pg_string: PgString) -> Self {
pg_string.0
}
}
impl From<String> for PgString {
fn from(string: String) -> Self {
PgString(string)
}
}
impl Encode for PgString {
fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
encoder.writer().write(self.0.as_bytes())?;
encoder.writer().write(b"\0")
}
}
impl Decode for PgString {
fn decode<D: Decoder>(decoder: &mut D) -> Result<Self, DecodeError> {
let mut string = String::new();
loop {
let byte = u8::decode(decoder)?;
if byte == 0 {
break;
}
string.push(byte as char);
}
Ok(PgString(string))
}
}