85 lines
1.8 KiB
Rust
Raw Normal View History

2017-05-02 08:01:57 +03:00
use elements;
use super::invoke::{Invoke, Identity};
2018-01-10 11:41:52 +04:00
/// Table definition
#[derive(Debug)]
2017-05-02 08:01:57 +03:00
pub struct TableDefinition {
2018-01-23 22:47:20 +03:00
/// Minimum length
pub min: u32,
/// Maximum length, if any
pub max: Option<u32>,
/// Element segments, if any
pub elements: Vec<TableEntryDefinition>,
2017-05-02 08:01:57 +03:00
}
2018-01-10 11:41:52 +04:00
/// Table elements entry definition
#[derive(Debug)]
2017-05-02 08:01:57 +03:00
pub struct TableEntryDefinition {
2018-01-23 22:47:20 +03:00
/// Offset initialization expression
pub offset: elements::InitExpr,
/// Values of initialization
pub values: Vec<u32>,
2017-05-02 08:01:57 +03:00
}
2018-01-10 11:41:52 +04:00
/// Table builder
2017-05-02 08:01:57 +03:00
pub struct TableBuilder<F=Identity> {
2018-01-23 22:47:20 +03:00
callback: F,
table: TableDefinition,
2017-05-02 08:01:57 +03:00
}
impl TableBuilder {
2018-01-23 22:47:20 +03:00
/// New table builder
pub fn new() -> Self {
TableBuilder::with_callback(Identity)
}
2017-05-02 08:01:57 +03:00
}
impl<F> TableBuilder<F> where F: Invoke<TableDefinition> {
2018-01-23 22:47:20 +03:00
/// New table builder with callback in chained context
pub fn with_callback(callback: F) -> Self {
TableBuilder {
callback: callback,
table: Default::default(),
}
}
2017-05-02 08:01:57 +03:00
2018-01-23 22:47:20 +03:00
/// Set/override minimum length
pub fn with_min(mut self, min: u32) -> Self {
self.table.min = min;
self
}
2017-05-02 08:01:57 +03:00
2018-01-23 22:47:20 +03:00
/// Set/override maximum length
pub fn with_max(mut self, max: Option<u32>) -> Self {
self.table.max = max;
self
}
2018-01-23 22:47:20 +03:00
/// Generate initialization expression and element values on specified index
pub fn with_element(mut self, index: u32, values: Vec<u32>) -> Self {
self.table.elements.push(TableEntryDefinition {
offset: elements::InitExpr::new(vec![
elements::Opcode::I32Const(index as i32),
elements::Opcode::End,
]),
values: values,
});
self
}
2017-05-02 08:01:57 +03:00
2018-01-23 22:47:20 +03:00
/// Finalize current builder spawning resulting struct
pub fn build(self) -> F::Result {
self.callback.invoke(self.table)
}
2017-05-02 08:01:57 +03:00
}
impl Default for TableDefinition {
2018-01-23 22:47:20 +03:00
fn default() -> Self {
TableDefinition {
min: 0,
max: None,
elements: Vec::new(),
}
}
2017-05-02 08:01:57 +03:00
}