1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
use context::varnum::{ReadVaru32, WriteVaru32};

use std::io::{Error, ErrorKind, Read, Write};

/// The magic header for external strings dictionaries.
const DICTIONARY_MAGIC_HEADER: &'static [u8; 7] = b"astdict";

/// A table of strings.
///
/// Generally wrapped either in a StringPrelude (if read as part of a compressed binast
/// file) or in an external `StringDictionary`.
pub struct StringTable {
    strings: Vec<Vec<u8>>,
}

// ---- Reading

impl StringTable {
    /// The strings in the table, in the order in which they appear in the stream.
    pub fn strings(&self) -> &[Vec<u8>] {
        self.strings.as_ref()
    }

    /// Read a string table from a stream.
    ///
    /// Consumes exactly the bytes used to define the string table.
    pub fn read<R: Read>(input: &mut R) -> Result<Self, Error> {
        let string_count = input.read_varu32_no_normalization()?.value;

        // The strings we decode, in the order in which we decode them.
        let mut strings = Vec::new();

        for _ in 0..string_count {
            let mut chars = Vec::new();
            // Read bytes one by one to handle escapes.
            loop {
                let mut buf = [0];
                input.read_exact(&mut buf)?;

                let byte = match buf[0] {
                    0 => {
                        // NUL terminator.
                        break;
                    }
                    1 => {
                        // Escaped char.
                        input.read_exact(&mut buf)?;
                        match buf[0] {
                            0 => 0,
                            1 => 1,
                            _ => return Err(Error::new(ErrorKind::InvalidData, "Invalid escape")),
                        }
                    }
                    byte => byte,
                };
                chars.push(byte);
            }
            // Attempt to decode string as UTF-8.
            strings.push(chars);
        }

        Ok(StringTable { strings })
    }
}

pub struct ExternalStringDictionary {
    strings: StringTable,
}

impl ExternalStringDictionary {
    /// The strings in this dictionary, in the order in which they appear in the stream.
    pub fn strings(&self) -> &[Vec<u8>] {
        self.strings.strings()
    }

    /// Read a string dictionary from a stream.
    ///
    /// Consumes exactly the bytes used to define the string dictionary.
    pub fn read<R: Read>(input: &mut R) -> Result<Self, Error> {
        // Check magic header
        let mut header_bytes = [0; 7];
        assert_eq!(DICTIONARY_MAGIC_HEADER.len(), header_bytes.len());

        input.read_exact(&mut header_bytes)?;
        if &header_bytes != DICTIONARY_MAGIC_HEADER {
            return Err(Error::new(
                ErrorKind::InvalidData,
                "Format error: Not an external strings dictionary",
            ));
        }

        // Read contents
        let strings = StringTable::read(input)?;
        Ok(ExternalStringDictionary { strings })
    }
}

#[test]
fn test_empty_external_string_dictionary() {
    let bytes = b"astdict\0";
    let mut input = std::io::Cursor::new(&bytes);
    let dictionary = ExternalStringDictionary::read(&mut input).unwrap();
    assert_eq!(dictionary.strings().len(), 0);
}

// ----- Writing

impl StringTable {
    pub fn new() -> Self {
        StringTable {
            strings: Vec::new(),
        }
    }
    pub fn with_capacity(capacity: usize) -> Self {
        StringTable {
            strings: Vec::with_capacity(capacity),
        }
    }
    pub fn from_buffers(strings: Vec<Vec<u8>>) -> Self {
        StringTable { strings }
    }
    pub fn add_buffer(&mut self, string: Vec<u8>) {
        self.strings.push(string);
    }
    pub fn write(&self, mut out: &mut dyn Write) -> Result<(), Error> {
        // Write the length.
        out.write_varu32(self.strings.len() as u32)?;

        // Write each string, NUL-terminated.
        for buf in &self.strings {
            // Write bytes one by one to handle escapes.
            for byte in buf {
                match byte {
                    0 | 1 =>
                    /* escape byte */
                    {
                        out.write_all(&[1, *byte])
                    }
                    _ => out.write_all(&[*byte]),
                }?;
            }
            // NUL terminator
            out.write_all(&[0])?;
        }

        Ok(())
    }
}

#[test]
fn test_write_and_read_string_tables() {
    use std::io::Cursor;

    // Generate samples with a few embedded '0's and '1's.
    let samples: Vec<Vec<u8>> = (0..300)
        .map(|len| (0..len).map(|i| (i % 256) as u8).collect())
        .collect();

    let reference = StringTable::from_buffers(samples);

    // Write table, read it back.
    let mut buf = Vec::new();
    reference.write(&mut buf).unwrap();

    let result = StringTable::read(&mut Cursor::new(buf)).unwrap();

    assert_eq!(result.strings(), reference.strings());
}