Skip to content

Commit

Permalink
lib: refactor Lib to implement strict encoding
Browse files Browse the repository at this point in the history
  • Loading branch information
dr-orlovsky committed Apr 9, 2024
1 parent 9354081 commit 6e6e1d5
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 84 deletions.
70 changes: 1 addition & 69 deletions src/data/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@

//! Helper traits and default implementations for encoding elements of AliVM container types
use core::str::FromStr;
use std::io::{self, Read, Write};
use std::iter::FromIterator;
use std::marker::PhantomData;
Expand All @@ -33,7 +32,7 @@ use amplify::{confinement, IoError, Wrapper};

use crate::data::encoding::DecodeError::InvalidBool;
use crate::data::{ByteStr, FloatLayout, IntLayout, Layout, MaybeNumber, Number, NumberLayout};
use crate::library::{IsaSeg, IsaSegError, Lib, LibId, LibSeg, LibSite, SegmentError};
use crate::library::{IsaSegError, LibId, LibSite, SegmentError};

/// Trait for encodable container data structures used by AluVM and runtime environments
pub trait Encode {
Expand Down Expand Up @@ -615,46 +614,6 @@ impl Decode for LibId {
}
}

impl Encode for IsaSeg {
type Error = EncodeError;

fn encode(&self, writer: impl Write) -> Result<usize, Self::Error> {
self.to_string().encode(writer)
}
}

impl Decode for IsaSeg {
type Error = DecodeError;

fn decode(reader: impl Read) -> Result<Self, Self::Error>
where
Self: Sized,
{
let s = String::decode(reader)?;
IsaSeg::from_str(&s).map_err(DecodeError::from)
}
}

impl Encode for LibSeg {
type Error = EncodeError;

fn encode(&self, writer: impl Write) -> Result<usize, Self::Error> {
MaxLenByte::new(self).encode(writer)
}
}

impl Decode for LibSeg {
type Error = DecodeError;

fn decode(reader: impl Read) -> Result<Self, Self::Error>
where
Self: Sized,
{
let seg: Vec<_> = MaxLenByte::decode(reader)?.release();
Ok(LibSeg::try_from_iter(seg)?)
}
}

impl Encode for LibSite {
type Error = io::Error;

Expand All @@ -675,30 +634,3 @@ impl Decode for LibSite {
Ok(LibSite::with(pos, id))
}
}

impl Encode for Lib {
type Error = EncodeError;

fn encode(&self, mut writer: impl Write) -> Result<usize, Self::Error> {
Ok(self.isae_segment().encode(&mut writer)?
+ self.code.encode(&mut writer)?
+ self.data.encode(&mut writer)?
+ self.libs.encode(&mut writer)?)
}
}

impl Decode for Lib {
type Error = DecodeError;

fn decode(mut reader: impl Read) -> Result<Self, Self::Error>
where
Self: Sized,
{
Ok(Lib::with(
String::decode(&mut reader)?.as_str(),
ByteStr::decode(&mut reader)?.to_vec(),
ByteStr::decode(&mut reader)?.to_vec(),
LibSeg::decode(&mut reader)?,
)?)
}
}
29 changes: 14 additions & 15 deletions src/library/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@ use alloc::string::{String, ToString};
#[cfg(all(feature = "alloc", not(feature = "std")))]
use alloc::vec::Vec;
use core::cmp::Ordering;
use core::convert::TryFrom;
use core::fmt::{self, Display, Formatter};
use core::hash::{Hash as RustHash, Hasher};
use core::str::FromStr;

use amplify::confinement::SmallBlob;
use amplify::{confinement, ByteArray, Bytes32};
use baid58::{Baid58ParseError, FromBaid58, ToBaid58};
use sha2::{Digest, Sha256};
Expand Down Expand Up @@ -122,26 +122,26 @@ impl LibId {

/// AluVM executable code library
#[derive(Clone, Debug, Default)]
// #[derive(StrictType, StrictDecode)]
// #[cfg_attr(feature = "std", derive(StrictEncode))]
// #[strict_type(lib = LIB_NAME_ALUVM)]
#[derive(StrictType, StrictDecode)]
#[cfg_attr(feature = "std", derive(StrictEncode))]
#[strict_type(lib = LIB_NAME_ALUVM)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(crate = "serde_crate"))]
pub struct Lib {
/// ISA segment
pub isae: IsaSeg,
/// Code segment
pub code: ByteStr,
pub code: SmallBlob,
/// Data segment
pub data: ByteStr,
pub data: SmallBlob,
/// Libs segment
pub libs: LibSeg,
}

impl Display for Lib {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
writeln!(f, "ISAE: {}", &self.isae)?;
write!(f, "CODE:\n{:#10}", self.code)?;
write!(f, "DATA:\n{:#10}", self.data)?;
write!(f, "CODE:\n{:#10}", ByteStr::with(self.code.as_ref()))?;
write!(f, "DATA:\n{:#10}", ByteStr::with(self.data.as_ref()))?;
if self.libs.count() > 0 {
write!(f, "LIBS: {:8}", self.libs)
} else {
Expand Down Expand Up @@ -252,13 +252,13 @@ impl Lib {
libs: LibSeg,
) -> Result<Lib, SegmentError> {
let isae = IsaSeg::from_str(isa)?;
let len = bytecode.len();
Ok(Self {
isae,
libs,
code: ByteStr::try_from(bytecode.as_slice())
.map_err(|_| SegmentError::CodeSegmentTooLarge(bytecode.len()))?,
data: ByteStr::try_from(data.as_slice())
.map_err(|_| SegmentError::DataSegmentTooLarge(bytecode.len()))?,
code: SmallBlob::try_from(bytecode)
.map_err(|_| SegmentError::CodeSegmentTooLarge(len))?,
data: SmallBlob::try_from(data).map_err(|_| SegmentError::DataSegmentTooLarge(len))?,
})
}

Expand All @@ -275,9 +275,8 @@ impl Lib {
for instr in code.iter() {
instr.encode(&mut writer)?;
}
let pos = writer.pos();
let data_segment = writer.into_data_segment();
code_segment.adjust_len(pos);
let data_segment = SmallBlob::from_collection_unsafe(writer.into_data_segment().to_vec());
let code_segment = SmallBlob::from_collection_unsafe(code_segment.to_vec());

Ok(Lib { isae: Isa::isa_ids(), libs: libs_segment, code: code_segment, data: data_segment })
}
Expand Down

0 comments on commit 6e6e1d5

Please sign in to comment.