Deserialize from bytes. Returns `None` if the buffer is malformed.
(buf: &[u8])
| 93 | |
| 94 | /// Deserialize from bytes. Returns `None` if the buffer is malformed. |
| 95 | pub fn from_bytes(buf: &[u8]) -> Option<Self> { |
| 96 | if buf.len() < 4 { |
| 97 | return None; |
| 98 | } |
| 99 | let count = u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]) as usize; |
| 100 | let mut pos = 4; |
| 101 | let mut forward = HashMap::with_capacity(count); |
| 102 | let mut reverse = Vec::with_capacity(count); |
| 103 | |
| 104 | for i in 0..count { |
| 105 | if pos + 2 > buf.len() { |
| 106 | return None; |
| 107 | } |
| 108 | let len = u16::from_le_bytes([buf[pos], buf[pos + 1]]) as usize; |
| 109 | pos += 2; |
| 110 | if pos + len > buf.len() { |
| 111 | return None; |
| 112 | } |
| 113 | let s = std::str::from_utf8(&buf[pos..pos + len]).ok()?; |
| 114 | pos += len; |
| 115 | |
| 116 | if !s.is_empty() { |
| 117 | forward.insert(s.to_string(), i as u32); |
| 118 | } |
| 119 | reverse.push(s.to_string()); |
| 120 | } |
| 121 | |
| 122 | Some(Self { forward, reverse }) |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | #[cfg(test)] |