feat: spec complaint program encoding
Co-authored-by: rvcas <x@rvcas.dev>
This commit is contained in:
@@ -28,6 +28,14 @@ impl Encode for isize {
|
||||
}
|
||||
}
|
||||
|
||||
impl Encode for usize {
|
||||
fn encode(&self, e: &mut Encoder) -> Result<(), String> {
|
||||
e.word(*self);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Encode for char {
|
||||
fn encode(&self, e: &mut Encoder) -> Result<(), String> {
|
||||
e.char(*self)?;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::encode::Encode;
|
||||
use crate::{encode::Encode, zigzag};
|
||||
|
||||
pub struct Encoder {
|
||||
pub buffer: Vec<u8>,
|
||||
@@ -66,12 +66,13 @@ impl Encoder {
|
||||
}
|
||||
|
||||
pub fn integer(&mut self, i: isize) -> Result<&mut Self, String> {
|
||||
let i = zigzag::to_usize(i);
|
||||
self.word(i);
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
pub fn char(&mut self, c: char) -> Result<&mut Self, String> {
|
||||
self.word(c as isize);
|
||||
self.word(c as usize);
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
@@ -132,7 +133,7 @@ impl Encoder {
|
||||
self.write_blk(arr, src_ptr);
|
||||
}
|
||||
|
||||
fn word(&mut self, c: isize) {
|
||||
pub fn word(&mut self, c: usize) {
|
||||
loop {
|
||||
let mut w = (c & 127) as u8;
|
||||
let c = c >> 7;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
mod encode;
|
||||
mod encoder;
|
||||
mod filler;
|
||||
mod zigzag;
|
||||
|
||||
pub mod en {
|
||||
pub use super::encode::*;
|
||||
|
||||
27
crates/flat/src/zigzag.rs
Normal file
27
crates/flat/src/zigzag.rs
Normal file
@@ -0,0 +1,27 @@
|
||||
pub fn to_usize(x: isize) -> usize {
|
||||
let double_x = x << 1;
|
||||
|
||||
if x >= 0 {
|
||||
double_x as usize
|
||||
} else {
|
||||
(-double_x - 1) as usize
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_isize(u: usize) -> isize {
|
||||
let s = u as isize;
|
||||
|
||||
(s >> 1) ^ -(s & 1)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
#[test]
|
||||
fn convert() {
|
||||
let n = -12;
|
||||
let unsigned = super::to_usize(n);
|
||||
let signed = super::to_isize(unsigned);
|
||||
|
||||
assert_eq!(n, signed)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user