-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconstant_pool.rs
More file actions
31 lines (27 loc) · 928 Bytes
/
Copy pathconstant_pool.rs
File metadata and controls
31 lines (27 loc) · 928 Bytes
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
use serde::{Deserialize, Serialize};
use techscript_ast::LiteralVal;
/// Deduplicated storage for literal constants, strings, integers, and floats.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ConstantPool {
pub constants: Vec<LiteralVal>,
}
impl ConstantPool {
/// Creates an empty ConstantPool.
pub fn new() -> Self {
Self::default()
}
/// Adds a constant value to the pool and returns its index. Reuses matches.
pub fn add(&mut self, val: LiteralVal) -> u32 {
if let Some(pos) = self.constants.iter().position(|c| c == &val) {
pos as u32
} else {
let idx = self.constants.len() as u32;
self.constants.push(val);
idx
}
}
/// Retrieves a constant from the pool by index.
pub fn get(&self, idx: u32) -> Option<&LiteralVal> {
self.constants.get(idx as usize)
}
}