refactor read_dynamic_int and tests
@@ -10,7 +10,8 @@ use num_bigint::{BigInt, Sign};
use tvm::bitstring::{Bit, Bitstring};
use tvm::stack::{BuilderData, SliceData};
-pub fn read_dynamic_int(cursor: SliceData, signed_padding: bool) -> Result<(Vec<u8>, SliceData), DeserializationError> {
+pub fn read_dynamic_int(cursor: SliceData, signed_padding: bool)
+-> Result<(Vec<u8>, SliceData), DeserializationError> {
let mut cursor = cursor;
let mut bitstring = Bitstring::new();
@@ -27,24 +28,14 @@ pub fn read_dynamic_int(cursor: SliceData, signed_padding: bool) -> Result<(Vec<
// pad to 8 bits
let padding_count = 8 - ((bitstring.length_in_bits() - 1) % 8 + 1);
-
- let padding: u16 =
- if signed_padding && (bitstring.bits(0..1).data[0] == Bit::One) {
- 0xFFFF
+ let padding_string = if signed_padding && (bitstring.bits(0..1).data[0] == Bit::One) {
+ Bitstring::create(vec![0xFF], padding_count)
} else {
- 0x0
+ Bitstring::create(vec![0], padding_count)
};
-
- let mut padding_string = Bitstring::new();
- padding_string.append_bits(padding, padding_count);
-
bitstring = padding_string + bitstring;
- let mut vec = Vec::<u8>::new();
- bitstring.into_bitstring_with_completion_tag(&mut vec);
- vec.pop();
-
- Ok((vec, cursor))
+ Ok((bitstring.data().to_vec(), cursor))
}
pub type Dint = BigInt;
@@ -123,3 +114,28 @@ impl ABITypeSignature for Dint {
"dint".to_string()
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_read_dynamic_int() {
+ let mut cell = BuilderData::new();
+ cell.update_cell(|data, _, vec| {
+ data.clear();
+ data.extend_from_slice(vec);
+ }, &[0xF8, 0xFF, 0x7F, 0xF8, 0xFF, 0x7F, 0x80]);
+ dbg!(cell.clone());
+ let cursor = cell.into();
+ // check signed
+ let (vec, new_cursor) = read_dynamic_int(cursor, true).unwrap();
+ assert_eq!(vec, vec![0xFF, 0xFF, 0xF8]);
+ assert_eq!(Dint::from_signed_bytes_be(&vec), Dint::from(-8));
+
+ // check unsigned
+ let (vec, _new_cursor) = read_dynamic_int(new_cursor, false).unwrap();
+ assert_eq!(vec, vec![0x1F, 0xFF, 0xF8]);
+ assert_eq!(Dint::from_signed_bytes_be(&vec), Dint::from(0x1FFFF8));
+ }
+}
\ No newline at end of file
