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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
use {
    crate::ConstantIndex,
    std::{
        collections::{hash_map::DefaultHasher, HashMap},
        fmt,
        hash::{Hash, Hasher},
        ops::Range,
    },
};

#[derive(Clone, Debug, Hash, PartialEq)]
enum ConstantInfo {
    F64(usize),
    I64(usize),
    Str(Range<usize>),
}

#[derive(Clone, Debug, PartialEq)]
pub enum Constant<'a> {
    F64(f64),
    I64(i64),
    Str(&'a str),
}

#[derive(Clone, Debug)]
pub struct ConstantPool {
    index: Vec<ConstantInfo>,
    // Constant strings concatanated into one
    strings: String,
    floats: Vec<f64>,
    ints: Vec<i64>,
    hash: u64,
}

impl Default for ConstantPool {
    fn default() -> Self {
        Self {
            index: vec![],
            strings: String::default(),
            floats: vec![],
            ints: vec![],
            hash: 0,
        }
    }
}

impl ConstantPool {
    pub fn len(&self) -> usize {
        self.index.len()
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn get(&self, index: ConstantIndex) -> Option<Constant> {
        match self.index.get(index as usize) {
            Some(constant_info) => match constant_info {
                ConstantInfo::F64(index) => Some(Constant::F64(self.floats[*index])),
                ConstantInfo::I64(index) => Some(Constant::I64(self.ints[*index])),
                ConstantInfo::Str(range) => Some(Constant::Str(&self.strings[range.clone()])),
            },
            None => None,
        }
    }

    pub fn string_data(&self) -> &str {
        &self.strings
    }

    #[inline]
    pub fn get_str(&self, index: ConstantIndex) -> &str {
        // Safety: The bounds have already been checked while the pool is being prepared
        unsafe { &self.strings.get_unchecked(self.get_str_bounds(index)) }
    }

    pub fn get_str_bounds(&self, index: ConstantIndex) -> Range<usize> {
        match self.index.get(index as usize) {
            Some(ConstantInfo::Str(range)) => range.clone(),
            _ => panic!("Invalid index"),
        }
    }

    pub fn get_f64(&self, index: ConstantIndex) -> f64 {
        match self.index.get(index as usize) {
            Some(ConstantInfo::F64(index)) => self.floats[*index],
            _ => panic!("Invalid index"),
        }
    }

    pub fn get_i64(&self, index: ConstantIndex) -> i64 {
        match self.index.get(index as usize) {
            Some(ConstantInfo::I64(index)) => self.ints[*index],
            _ => panic!("Invalid index"),
        }
    }

    pub fn iter(&self) -> ConstantPoolIterator {
        ConstantPoolIterator::new(self)
    }
}

pub struct ConstantPoolIterator<'a> {
    pool: &'a ConstantPool,
    index: ConstantIndex,
}

impl<'a> ConstantPoolIterator<'a> {
    fn new(pool: &'a ConstantPool) -> Self {
        Self { pool, index: 0 }
    }
}

impl<'a> Iterator for ConstantPoolIterator<'a> {
    type Item = Constant<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        let result = self.pool.get(self.index);
        self.index += 1;
        result
    }
}

impl fmt::Display for ConstantPool {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (i, constant) in self.iter().enumerate() {
            write!(f, "{}\t", i)?;
            match constant {
                Constant::F64(n) => write!(f, "Float\t{}", n)?,
                Constant::I64(n) => write!(f, "Int\t{}", n)?,
                Constant::Str(s) => write!(f, "String\t{}", s)?,
            }
            writeln!(f)?;
        }
        Ok(())
    }
}

impl PartialEq for ConstantPool {
    fn eq(&self, other: &Self) -> bool {
        self.hash == other.hash
    }
}

impl Hash for ConstantPool {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.hash.hash(state);
    }
}

#[derive(Clone, Debug, Default)]
pub struct ConstantPoolBuilder {
    pool: ConstantPool,
    hasher: DefaultHasher, // Used to incrementally hash the constant pool's contents
    string_map: HashMap<String, ConstantIndex>,
    float_map: HashMap<u64, ConstantIndex>,
    int_map: HashMap<i64, ConstantIndex>,
}

impl ConstantPoolBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn add_string(&mut self, s: &str) -> ConstantIndex {
        match self.string_map.get(s) {
            Some(index) => *index,
            None => {
                let start = self.pool.strings.len();
                let end = start + s.len();
                self.pool.strings.push_str(s);
                s.hash(&mut self.hasher);

                let result = self.pool.index.len() as ConstantIndex;
                self.pool.index.push(ConstantInfo::Str(start..end));

                self.string_map.insert(s.to_string(), result);

                result
            }
        }
    }

    pub fn add_f64(&mut self, n: f64) -> ConstantIndex {
        let n_u64 = n.to_bits();

        match self.float_map.get(&n_u64) {
            Some(index) => *index,
            None => {
                let number_index = self.pool.floats.len();
                self.pool.floats.push(n);
                n_u64.hash(&mut self.hasher);

                let result = self.pool.index.len() as ConstantIndex;
                self.pool.index.push(ConstantInfo::F64(number_index));

                self.float_map.insert(n_u64, result);

                result
            }
        }
    }

    pub fn add_i64(&mut self, n: i64) -> ConstantIndex {
        match self.int_map.get(&n) {
            Some(index) => *index,
            None => {
                let number_index = self.pool.ints.len();
                self.pool.ints.push(n);
                n.hash(&mut self.hasher);

                let result = self.pool.index.len() as ConstantIndex;
                self.pool.index.push(ConstantInfo::I64(number_index));

                self.int_map.insert(n, result);

                result
            }
        }
    }

    pub fn pool(&self) -> &ConstantPool {
        &self.pool
    }

    pub fn build(mut self) -> ConstantPool {
        self.pool.index.hash(&mut self.hasher);
        self.pool.hash = self.hasher.finish();
        self.pool
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn floats_are_equal(a: f64, b: f64) -> bool {
        (a - b).abs() < f64::EPSILON
    }

    #[test]
    fn test_adding_strings() {
        let mut builder = ConstantPoolBuilder::new();

        let s1 = "test";
        let s2 = "test2";

        // 1 byte for string length
        assert_eq!(0, builder.add_string(s1));
        assert_eq!(1, builder.add_string(s2));

        // don't duplicate strings
        assert_eq!(0, builder.add_string(s1));
        assert_eq!(1, builder.add_string(s2));

        let pool = builder.build();

        assert_eq!(s1, pool.get_str(0));
        assert_eq!(s2, pool.get_str(1));

        assert_eq!(2, pool.len());
    }

    #[test]
    fn test_adding_numbers() {
        let mut builder = ConstantPoolBuilder::new();

        let n1 = 3;
        let n2 = 9.87654321;

        assert_eq!(0, builder.add_i64(n1));
        assert_eq!(1, builder.add_f64(n2));

        // don't duplicate numbers
        assert_eq!(0, builder.add_i64(n1));
        assert_eq!(1, builder.add_f64(n2));

        let pool = builder.build();

        assert_eq!(n1, pool.get_i64(0));
        assert!(floats_are_equal(n2, pool.get_f64(1)));

        assert_eq!(2, pool.len());
    }

    #[test]
    fn test_adding_numbers_and_strings() {
        let mut builder = ConstantPoolBuilder::new();

        let n1 = -1.1;
        let n2 = 99;
        let s1 = "O_o";
        let s2 = "^_^";

        assert_eq!(0, builder.add_f64(n1));
        assert_eq!(1, builder.add_string(s1));
        assert_eq!(2, builder.add_i64(n2));
        assert_eq!(3, builder.add_string(s2));

        let pool = builder.build();

        assert!(floats_are_equal(n1, pool.get_f64(0)));
        assert_eq!(s1, pool.get_str(1));
        assert_eq!(n2, pool.get_i64(2));
        assert_eq!(s2, pool.get_str(3));

        assert_eq!(4, pool.len());
    }

    #[test]
    fn test_iter() {
        let mut builder = ConstantPoolBuilder::new();

        let n1 = -1;
        let n2 = 99.9;
        let s1 = "O_o";
        let s2 = "^_^";

        builder.add_i64(n1);
        builder.add_string(s1);
        builder.add_f64(n2);
        builder.add_string(s2);

        let pool = builder.build();

        let mut iter = pool.iter();
        assert_eq!(iter.next(), Some(Constant::I64(-1)));
        assert_eq!(iter.next(), Some(Constant::Str("O_o")));
        assert_eq!(iter.next(), Some(Constant::F64(99.9)));
        assert_eq!(iter.next(), Some(Constant::Str("^_^")));
        assert_eq!(iter.next(), None);
    }
}