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