atom_macho/
string_table.rs

1use std::fmt;
2
3pub struct StringTable {
4    data: Vec<u8>,
5}
6
7impl StringTable {
8    pub fn with_null() -> Self {
9        StringTable { data: vec![0] }
10    }
11
12    pub fn get(&self, idx: usize) -> &str {
13        let bytes = self.data[idx..].split(|n| *n == 0).next().unwrap();
14        std::str::from_utf8(bytes).unwrap()
15    }
16
17    pub fn push_with_null(&mut self, s: &str) {
18        for c in s.chars() {
19            if !c.is_ascii() {
20                panic!("could not push non-ascii char");
21            }
22            self.data.push(c as u8);
23        }
24        self.data.push(0);
25    }
26
27    pub fn len(&self) -> usize {
28        self.data.len()
29    }
30
31    pub fn iter(&self) -> impl Iterator<Item = &str> {
32        self.as_ref()
33            .split(|b| *b == 0)
34            .skip(1)
35            .map(|bytes| std::str::from_utf8(bytes).unwrap())
36    }
37}
38
39impl AsRef<[u8]> for StringTable {
40    fn as_ref(&self) -> &[u8] {
41        self.data.as_ref()
42    }
43}
44
45impl From<Vec<u8>> for StringTable {
46    fn from(data: Vec<u8>) -> Self {
47        assert!(data.starts_with(&[0]));
48        assert!(data.ends_with(&[0]));
49        assert!(data.iter().all(|n| *n == 0 || n.is_ascii()));
50
51        StringTable { data }
52    }
53}
54
55impl fmt::Debug for StringTable {
56    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
57        let mut debug = fmt.debug_list();
58
59        for n in self.data.iter() {
60            match n {
61                0 => {
62                    debug.entry(&"");
63                }
64                _ => {
65                    debug.entry(&char::from(*n));
66                }
67            }
68        }
69
70        debug.finish()
71    }
72}
73
74#[cfg(test)]
75mod tests {
76    use super::*;
77
78    #[test]
79    fn get_index_0_always_return_empty_string() {
80        let data = vec![0x00, 0x5f, 0x6d, 0x61, 0x69, 0x6e, 0x00];
81        let table = StringTable::from(data);
82        assert_eq!(table.get(0), "");
83
84        let mut table = StringTable::with_null();
85        table.push_with_null("hoge");
86        assert_eq!(table.get(0), "");
87    }
88
89    #[test]
90    fn get_string_from_vec() {
91        let data = vec![0x00, 0x5f, 0x6d, 0x61, 0x69, 0x6e, 0x00];
92        let table = StringTable::from(data);
93
94        assert_eq!(table.get(1), "_main");
95        assert_eq!(table.get(2), "main");
96    }
97
98    #[test]
99    fn get_string() {
100        let mut table = StringTable::with_null();
101        table.push_with_null("hoge");
102
103        assert_eq!(table.get(1), "hoge");
104    }
105}