Debian Codegraph @

.cargo/vendor/onenote_parser/src/shared/multi_byte.rs

raw
1 //! Multi-byte encoding/decoding
2 //!
3 //! Following the multi-byte encoding described in [\[MS-ISF\]] (sections _Multi-byte Encoding of
4 //! Signed Numbers_ and _Sizes of Tags and Numbers_).
5 //!
6 //! [\[MS-ISF\]]: https://docs.microsoft.com/en-us/uwp/specifications/ink-serialized-format
7
8 pub(crate) fn decode_signed(input: &[u8]) -> Vec<i64> {
9 decode(input)
10 .into_iter()
11 .map(|value| {
12 let shifted = (value >> 1) as i64;
13
14 if value & 0x1 == 0x1 {
15 -shifted
16 } else {
17 shifted
18 }
19 })
20 .collect()
21 }
22
23 fn decode(input: &[u8]) -> Vec<u64> {
24 let mut output = vec![];
25
26 // Decode the multi-byte data length
27 let (length, offset) = decode_uint(&input);
28
29 // The length is actually a signed value so we need to remove the sign bit
30 // (see also `decode_signed`). This may not be the case for unsigned multi-byte blobs
31 // but for ink data it's always signed so this should be safe for now.
32 let length = length >> 1;
33
34 // Decode the remaining data
35 let mut index = offset;
36 for _ in 0..length {
37 let (value, offset) = decode_uint(&input[index..]);
38
39 output.push(value);
40 index += offset;
41 }
42
43 output
44 }
45
46 fn decode_uint(data: &[u8]) -> (u64, usize) {
47 let mut value: u64 = 0;
48 let mut count = 0;
49
50 for byte in data {
51 let flag = byte & 0x80 == 0x80;
52 value |= (*byte as u64 & 0x7F) << (count * 7);
53
54 count += 1;
55
56 if !flag {
57 break;
58 }
59 }
60
61 (value, count)
62 }