oxedyne/fe2o3/fe2o3_text/tests/detect_corpus/rust/traits_generics.txt
2.0 KiB, 1 run
created by r1870400018:12052, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | use std::fmt; |
| 2 | |
| 3 | /// A trait for objects that can be serialised to a compact binary form. |
| 4 | pub trait Encode { |
| 5 | fn encode(&self, buf: &mut Vec<u8>); |
| 6 | fn encoded_len(&self) -> usize; |
| 7 | } |
| 8 | |
| 9 | /// A trait for objects that can be deserialised from bytes. |
| 10 | pub trait Decode: Sized { |
| 11 | fn decode(buf: &[u8]) -> Result<(Self, usize), DecodeError>; |
| 12 | } |
| 13 | |
| 14 | #[derive(Debug)] |
| 15 | pub struct DecodeError { |
| 16 | msg: String, |
| 17 | pos: usize, |
| 18 | } |
| 19 | |
| 20 | impl fmt::Display for DecodeError { |
| 21 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 22 | write!(f, "decode error at byte {}: {}", self.pos, self.msg) |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | /// Encode a slice of encodable items, prefixed by a length varint. |
| 27 | pub fn encode_sequence<T: Encode>(items: &[T], buf: &mut Vec<u8>) { |
| 28 | encode_varint(items.len() as u64, buf); |
| 29 | for item in items { |
| 30 | item.encode(buf); |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | /// Decode a length-prefixed sequence. |
| 35 | pub fn decode_sequence<T: Decode>(buf: &[u8]) -> Result<(Vec<T>, usize), DecodeError> { |
| 36 | let (count, mut offset) = decode_varint(buf)?; |
| 37 | let mut items = Vec::with_capacity(count as usize); |
| 38 | for _ in 0..count { |
| 39 | let (item, consumed) = T::decode(&buf[offset..])?; |
| 40 | items.push(item); |
| 41 | offset += consumed; |
| 42 | } |
| 43 | Ok((items, offset)) |
| 44 | } |
| 45 | |
| 46 | fn encode_varint(mut val: u64, buf: &mut Vec<u8>) { |
| 47 | loop { |
| 48 | let byte = (val & 0x7F) as u8; |
| 49 | val >>= 7; |
| 50 | if val == 0 { |
| 51 | buf.push(byte); |
| 52 | return; |
| 53 | } |
| 54 | buf.push(byte | 0x80); |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | fn decode_varint(buf: &[u8]) -> Result<(u64, usize), DecodeError> { |
| 59 | let mut result: u64 = 0; |
| 60 | let mut shift = 0; |
| 61 | for (i, &byte) in buf.iter().enumerate() { |
| 62 | result |= ((byte & 0x7F) as u64) << shift; |
| 63 | if byte & 0x80 == 0 { |
| 64 | return Ok((result, i + 1)); |
| 65 | } |
| 66 | shift += 7; |
| 67 | if shift >= 64 { |
| 68 | return Err(DecodeError { |
| 69 | msg: "varint too long".to_string(), |
| 70 | pos: i, |
| 71 | }); |
| 72 | } |
| 73 | } |
| 74 | Err(DecodeError { |
| 75 | msg: "unexpected end of input".to_string(), |
| 76 | pos: buf.len(), |
| 77 | }) |
| 78 | } |