1 | use super::*; |
2 | use std::collections::hash_map::*; |
3 | |
4 | pub struct Strings { |
5 | map: HashMap<String, u32>, |
6 | stream: Vec<u8>, |
7 | } |
8 | |
9 | impl Default for Strings { |
10 | fn default() -> Self { |
11 | Self { map: Default::default(), stream: vec![0] } |
12 | } |
13 | } |
14 | |
15 | impl Strings { |
16 | pub fn insert(&mut self, value: &str) -> u32 { |
17 | if value.is_empty() { |
18 | return 0; |
19 | } |
20 | |
21 | match self.map.entry(key:value.to_string()) { |
22 | Entry::Vacant(entry: VacantEntry<'_, String, u32>) => { |
23 | let offset: u32 = *entry.insert(self.stream.len() as u32); |
24 | self.stream.extend_from_slice(value.as_bytes()); |
25 | self.stream.push(0); |
26 | offset |
27 | } |
28 | Entry::Occupied(entry: OccupiedEntry<'_, String, …>) => *entry.get(), |
29 | } |
30 | } |
31 | |
32 | pub fn into_stream(self) -> Vec<u8> { |
33 | self.stream.into_stream() |
34 | } |
35 | } |
36 | |