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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
//! Encoder for DX Machine format
//!
//! Converts Rust data structures into highly optimized DX bytecode.
//! Automatically uses aliases, ditto marks, and compression.
//! DX ∞: Base62 encoding for integers, auto-increment detection.
use crate::base62::encode_base62;
use crate::error::Result;
use crate::schema::TypeHint;
use crate::types::{DxArray, DxObject, DxTable, DxValue};
use rustc_hash::FxHashMap;
use std::io::Write;
/// Encoder configuration
#[derive(Debug, Clone)]
pub struct EncoderConfig {
/// Enable alias generation for repeated keys
pub use_aliases: bool,
/// Enable ditto marks for repeated values
pub use_ditto: bool,
/// Minimum key length to create alias
pub alias_min_length: usize,
/// Pretty print (adds spacing)
pub pretty: bool,
}
impl Default for EncoderConfig {
fn default() -> Self {
Self {
use_aliases: true,
use_ditto: true,
alias_min_length: 6,
pretty: false,
}
}
}
/// DX encoder
pub struct Encoder {
config: EncoderConfig,
/// Generated aliases (full_key -> alias)
aliases: FxHashMap<String, String>,
/// Next alias id
next_alias: usize,
/// Previous row values for ditto detection
prev_row: Option<Vec<DxValue>>,
}
impl Encoder {
/// Create an encoder with an explicit configuration.
pub fn new(config: EncoderConfig) -> Self {
Self {
config,
aliases: FxHashMap::default(),
next_alias: 0,
prev_row: None,
}
}
/// Create an encoder with default production settings.
pub fn with_defaults() -> Self {
Self::new(EncoderConfig::default())
}
/// Encode a value to bytes
pub fn encode(&mut self, value: &DxValue) -> Result<Vec<u8>> {
let mut output = Vec::new();
self.encode_to_writer(value, &mut output)?;
Ok(output)
}
/// Encode to a writer
pub fn encode_to_writer<W: Write>(&mut self, value: &DxValue, writer: &mut W) -> Result<()> {
match value {
DxValue::Object(obj) => self.encode_object(obj, writer, ""),
_ => {
// Single value - wrap in object
let mut obj = DxObject::new();
obj.insert("value".to_string(), value.clone());
self.encode_object(&obj, writer, "")
}
}
}
/// Encode an object
fn encode_object<W: Write>(
&mut self,
obj: &DxObject,
writer: &mut W,
prefix: &str,
) -> Result<()> {
// First pass: find keys to alias
if self.config.use_aliases {
self.generate_aliases(obj);
}
// Second pass: write aliases
for (alias, full_key) in &self.aliases {
writeln!(writer, "${}={}", alias, full_key)?;
}
// Third pass: write values
for (key, value) in obj.iter() {
let full_key = if prefix.is_empty() {
key.clone()
} else {
format!("{}.{}", prefix, key)
};
self.encode_field(&full_key, value, writer)?;
}
Ok(())
}
/// Generate aliases for repeated/long keys
fn generate_aliases(&mut self, obj: &DxObject) {
let mut key_freq: FxHashMap<String, usize> = FxHashMap::default();
for (key, _) in obj.iter() {
if key.len() >= self.config.alias_min_length {
*key_freq.entry(key.clone()).or_insert(0) += 1;
}
}
// Create aliases for frequent/long keys
for (key, _count) in key_freq.iter() {
if !self.aliases.contains_key(key) {
let alias = format!("k{}", self.next_alias);
self.next_alias += 1;
self.aliases.insert(alias, key.clone());
}
}
}
/// Encode a field
fn encode_field<W: Write>(&mut self, key: &str, value: &DxValue, writer: &mut W) -> Result<()> {
// Write key (with alias if available)
let key_to_write = self
.aliases
.iter()
.find(|(_, v)| v.as_str() == key)
.map(|(k, _)| format!("${}", k))
.unwrap_or_else(|| key.to_string());
match value {
DxValue::Table(table) => {
// Table with schema
write!(writer, "{}=", key_to_write)?;
self.encode_table(table, writer)?;
}
DxValue::Array(arr) if arr.is_stream => {
// Stream array
write!(writer, "{}> ", key_to_write)?;
self.encode_stream_array(arr, writer)?;
writeln!(writer)?;
}
DxValue::Bool(true) => {
// Shorthand: key!
writeln!(writer, "{}!", key_to_write)?;
}
DxValue::Null => {
// Shorthand: key?
writeln!(writer, "{}?", key_to_write)?;
}
_ => {
// Standard key:value
write!(writer, "{}:", key_to_write)?;
self.encode_value(value, writer)?;
writeln!(writer)?;
}
}
Ok(())
}
/// Encode a table
fn encode_table<W: Write>(&mut self, table: &DxTable, writer: &mut W) -> Result<()> {
// Write schema
for (i, col) in table.schema.columns.iter().enumerate() {
if i > 0 {
write!(writer, " ")?;
}
write!(writer, "{}", col.name)?;
if col.type_hint != TypeHint::Auto {
write!(writer, "%{}", col.type_hint.to_byte() as char)?;
}
}
writeln!(writer)?;
// Write rows
self.prev_row = None;
for row in &table.rows {
self.encode_row(row, &table.schema, writer)?;
self.prev_row = Some(row.clone());
}
Ok(())
}
/// Encode a table row
fn encode_row<W: Write>(
&mut self,
row: &[DxValue],
schema: &crate::schema::Schema,
writer: &mut W,
) -> Result<()> {
for (i, value) in row.iter().enumerate() {
// Skip auto-increment columns (they're generated on parse)
if i < schema.columns.len() && schema.columns[i].type_hint == TypeHint::AutoIncrement {
continue;
}
if i > 0 {
write!(writer, " ")?;
}
// Use ditto if value matches previous row
if self.config.use_ditto {
if let Some(prev) = &self.prev_row {
if i < prev.len() && &prev[i] == value {
write!(writer, "_")?;
continue;
}
}
}
// Use Base62 encoding if column type is Base62
if i < schema.columns.len() && schema.columns[i].type_hint == TypeHint::Base62 {
if let DxValue::Int(n) = value {
if *n >= 0 {
write!(writer, "{}", encode_base62(*n as u64))?;
continue;
}
}
}
self.encode_value(value, writer)?;
}
writeln!(writer)?;
Ok(())
}
/// Encode stream array
fn encode_stream_array<W: Write>(&mut self, arr: &DxArray, writer: &mut W) -> Result<()> {
for (i, value) in arr.values.iter().enumerate() {
if i > 0 {
write!(writer, "|")?;
}
self.encode_value(value, writer)?;
}
Ok(())
}
/// Encode a value
fn encode_value<W: Write>(&mut self, value: &DxValue, writer: &mut W) -> Result<()> {
match value {
DxValue::Null => write!(writer, "~")?,
DxValue::Bool(true) => write!(writer, "+")?,
DxValue::Bool(false) => write!(writer, "-")?,
DxValue::Int(i) => write!(writer, "{}", i)?,
DxValue::Float(f) => write!(writer, "{}", f)?,
DxValue::String(s) => {
// No quotes in machine format
write!(writer, "{}", s)?;
}
DxValue::Array(arr) => {
if arr.is_stream {
self.encode_stream_array(arr, writer)?;
} else {
// Vertical array - not supported in inline
write!(writer, "[]")?;
}
}
DxValue::Object(_) => write!(writer, "{{}}")?,
DxValue::Table(_) => write!(writer, "[[]]")?,
DxValue::Ref(id) => write!(writer, "@{}", id)?,
}
Ok(())
}
}
/// Encode a value with default config
///
/// Converts a [`DxValue`] into DX machine format bytes using default settings.
/// This is the inverse of [`parse()`].
///
/// # Example
///
/// ```rust
/// use serializer::{encode, DxValue, DxObject};
///
/// let mut obj = DxObject::new();
/// obj.insert("name".to_string(), DxValue::String("Alice".to_string()));
/// obj.insert("age".to_string(), DxValue::Int(30));
///
/// let bytes = encode(&DxValue::Object(obj)).unwrap();
/// ```
///
/// # Errors
///
/// Returns a `DxError` in the following cases:
///
/// - `DxError::Io` - Failed to write to the internal buffer. This is rare
/// since encoding writes to an in-memory `Vec<u8>`, but can occur if
/// memory allocation fails.
///
/// # Note
///
/// The encoding process is generally infallible for valid `DxValue` inputs.
/// The `Result` return type is used for consistency with the streaming
/// `encode_to_writer()` function and to handle potential I/O errors.
///
/// [`DxValue`]: crate::types::DxValue
/// [`parse()`]: crate::parser::parse
#[must_use = "encoding result should be used"]
pub fn encode(value: &DxValue) -> Result<Vec<u8>> {
let mut encoder = Encoder::with_defaults();
encoder.encode(value)
}
/// Encode to a writer with default config
///
/// Writes the encoded DX machine format directly to any [`Write`] implementor.
/// This is more efficient than `encode()` when writing to files or network
/// streams, as it avoids an intermediate buffer.
///
/// # Example
///
/// ```rust
/// use serializer::{encode_to_writer, DxValue, DxObject};
/// use std::io::Cursor;
///
/// let mut obj = DxObject::new();
/// obj.insert("name".to_string(), DxValue::String("Test".to_string()));
///
/// let mut buffer = Vec::new();
/// encode_to_writer(&DxValue::Object(obj), &mut buffer).unwrap();
/// ```
///
/// # Errors
///
/// Returns a `DxError` in the following cases:
///
/// - `DxError::Io` - Failed to write to the output stream. This can occur
/// when writing to files (disk full, permission denied), network streams
/// (connection closed), or any other I/O operation that fails.
///
/// [`Write`]: std::io::Write
pub fn encode_to_writer<W: Write>(value: &DxValue, writer: &mut W) -> Result<()> {
let mut encoder = Encoder::with_defaults();
encoder.encode_to_writer(value, writer)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::parser::parse;
#[test]
fn test_encode_simple() {
let mut obj = DxObject::new();
obj.insert("name".to_string(), DxValue::String("Alice".to_string()));
obj.insert("age".to_string(), DxValue::Int(30));
obj.insert("active".to_string(), DxValue::Bool(true));
let value = DxValue::Object(obj);
let encoded = encode(&value).unwrap();
let encoded_str = std::str::from_utf8(&encoded).unwrap();
assert!(encoded_str.contains("name:Alice"));
assert!(encoded_str.contains("age:30"));
// active is aliased to $k0 because it's >= 6 chars
// Check that either active! or $k0! is present (aliased form)
assert!(
encoded_str.contains("!"),
"Expected boolean true to be encoded with !"
);
}
#[test]
fn test_round_trip() {
// Use short key names to avoid aliasing (alias_min_length is 6)
let input = b"name:Test
score:9.5
ok:+";
let parsed = parse(input).unwrap();
let encoded = encode(&parsed).unwrap();
let reparsed = parse(&encoded).unwrap();
assert_eq!(parsed, reparsed);
}
}