feat: prepare decoding traits and make new Flat trait

This commit is contained in:
rvcas
2022-05-28 20:12:03 -04:00
parent 41487733f7
commit 0a476d0592
6 changed files with 94 additions and 26 deletions

View File

@@ -1,6 +1,10 @@
use anyhow::anyhow;
use flat::en::{Encode, Encoder};
use flat::{
de::{Decode, Decoder},
en::{Encode, Encoder},
Flat,
};
use crate::{
ast::{Constant, Program, Term},
@@ -11,15 +15,17 @@ const BUILTIN_TAG_WIDTH: u32 = 7;
const CONST_TAG_WIDTH: u32 = 4;
const TERM_TAG_WIDTH: u32 = 4;
impl Program {
pub fn flat(&self) -> anyhow::Result<Vec<u8>> {
let bytes = flat::encode(self.clone()).map_err(|err| anyhow!("{}", err))?;
impl<'b> Flat<'b> for Program {}
Ok(bytes)
impl Program {
// convenient so that people don't need to depend on the flat crate
// directly to call programs flat function
pub fn to_flat(&self) -> anyhow::Result<Vec<u8>> {
self.flat().map_err(|err| anyhow!("{}", err))
}
pub fn flat_hex(&self) -> anyhow::Result<String> {
let bytes = self.flat()?;
let bytes = self.flat().map_err(|err| anyhow!("{}", err))?;
let hex = hex::encode(&bytes);
@@ -41,6 +47,12 @@ impl Encode for Program {
}
}
impl<'b> Decode<'b> for Program {
fn decode(_d: &mut Decoder<'b>) -> Result<Self, String> {
todo!()
}
}
impl Encode for Term {
fn encode(&self, e: &mut Encoder) -> Result<(), String> {
// still need annotation but here we have the term tags
@@ -92,6 +104,12 @@ impl Encode for Term {
}
}
impl<'b> Decode<'b> for Term {
fn decode(_d: &mut Decoder<'b>) -> Result<Self, String> {
todo!()
}
}
impl Encode for &Constant {
fn encode(&self, e: &mut Encoder) -> Result<(), String> {
match self {
@@ -128,6 +146,12 @@ impl Encode for &Constant {
}
}
impl<'b> Decode<'b> for Constant {
fn decode(_d: &mut Decoder<'b>) -> Result<Self, String> {
todo!()
}
}
impl Encode for DefaultFunction {
fn encode(&self, e: &mut flat::en::Encoder) -> Result<(), String> {
e.bits(BUILTIN_TAG_WIDTH as i64, self.clone() as u8);
@@ -136,6 +160,12 @@ impl Encode for DefaultFunction {
}
}
impl<'b> Decode<'b> for DefaultFunction {
fn decode(_d: &mut Decoder<'b>) -> Result<Self, String> {
todo!()
}
}
fn encode_term_tag(tag: u8, e: &mut Encoder) -> Result<(), String> {
safe_encode_bits(TERM_TAG_WIDTH, tag, e)
}
@@ -171,7 +201,7 @@ mod test {
term: Term::Constant(Constant::Integer(11)),
};
let bytes = program.flat().unwrap();
let bytes = program.to_flat().unwrap();
assert_eq!(
bytes,