use crate::shared::datum::{write_json, Datum};
use crate::shared::error::Fail;
use crate::shared::limits::NODE_BYTES;
use crate::shared::number::number_text;
#[derive(Clone, Debug, PartialEq)]
pub struct RecordsSpec {
pub document: Box<str>,
pub record: Box<str>,
pub cell: Box<str>,
pub empty: Option<Box<str>>,
pub fill: Datum,
pub header: bool,
pub unnamed: Box<str>,
pub max_state_bytes: usize,
}
impl RecordsSpec {
pub fn new(document: &str, record: &str, cell: &str) -> RecordsSpec {
RecordsSpec {
document: document.into(),
record: record.into(),
cell: cell.into(),
empty: None,
fill: Datum::String("".into()),
header: false,
unnamed: "".into(),
max_state_bytes: usize::MAX,
}
}
pub fn with_max_state_bytes(mut self, max: usize) -> RecordsSpec {
self.max_state_bytes = max;
self
}
pub fn with_empty(mut self, group: &str) -> RecordsSpec {
self.empty = Some(group.into());
self
}
pub fn with_header(mut self, unnamed: &str) -> RecordsSpec {
self.header = true;
self.unnamed = unnamed.into();
self
}
pub fn with_fill(mut self, fill: Datum) -> RecordsSpec {
self.fill = fill;
self
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RecordsPhase {
Before,
Header,
Row,
Done,
}
impl RecordsPhase {
pub fn word(self) -> &'static str {
match self {
RecordsPhase::Before => "before",
RecordsPhase::Header => "header",
RecordsPhase::Row => "row",
RecordsPhase::Done => "done",
}
}
}
pub fn records_state_bytes<'n>(
phase: RecordsPhase,
names: impl IntoIterator<Item = &'n str>,
cells: usize,
) -> u64 {
let node = NODE_BYTES as u64;
let mut bytes = node * 4 + phase.word().len() as u64 + node * cells as u64;
for name in names {
bytes = bytes.saturating_add(node + name.len() as u64);
}
bytes
}
pub fn records_state_refusal(max: usize) -> Fail {
Fail::limit(
"max_metadata_bytes",
max as u64,
format!("the scan-emit state holds more than {max} bytes"),
)
}
pub fn records_name(value: &Datum) -> Result<String, Fail> {
match value {
Datum::String(s) => Ok(s.to_string()),
Datum::Null => Ok("null".into()),
Datum::Bool(true) => Ok("true".into()),
Datum::Bool(false) => Ok("false".into()),
Datum::Number { value, lexeme } => number_text(*value, lexeme.as_deref()),
Datum::Array(_) | Datum::Object(_) => {
let mut text = String::new();
write_json(value, &mut text);
Ok(text)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_state_is_measured_as_the_scan_measures_it() {
assert_eq!(records_state_bytes(RecordsPhase::Before, [], 0), 70);
assert_eq!(
records_state_bytes(RecordsPhase::Row, ["a", "bc"], 1),
7 * 16 + 3 + 3
);
}
#[test]
fn a_header_cell_is_named_by_its_text() {
assert_eq!(records_name(&Datum::String("id".into())).unwrap(), "id");
assert_eq!(records_name(&Datum::Null).unwrap(), "null");
assert_eq!(records_name(&Datum::Bool(false)).unwrap(), "false");
let n = Datum::Number {
value: 1.5,
lexeme: Some("1.50".into()),
};
assert_eq!(records_name(&n).unwrap(), "1.50");
let n = Datum::Number {
value: 1e21,
lexeme: None,
};
assert_eq!(records_name(&n).unwrap(), "1e21");
}
}