tauq 0.2.0

Token-efficient data notation - 49% fewer tokens than JSON (verified with tiktoken)
Documentation
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
//! Traits for compile-time TBF encoding/decoding
//!
//! These traits enable `#[derive(TbfEncode, TbfDecode)]` to generate
//! optimized binary serialization without type tags.

use super::dictionary::{BorrowedDictionary, StringDictionary};
use super::schema::{Schema, SchemaType};
use super::varint::{decode_signed_varint, decode_varint, encode_signed_varint, encode_varint};
use crate::error::{InterpretError, TauqError};

/// Trait for types that can be encoded to TBF format
///
/// Implement this trait to enable compile-time optimized binary encoding.
/// Use `#[derive(TbfEncode)]` for automatic implementation.
///
/// # Example
///
/// ```ignore
/// use tauq::tbf::TbfEncode;
///
/// #[derive(TbfEncode)]
/// struct User {
///     id: u32,
///     name: String,
/// }
///
/// let user = User { id: 1, name: "Alice".into() };
/// let bytes = user.tbf_encode();
/// ```
pub trait TbfEncode {
    /// Encode this value to the buffer
    fn tbf_encode_to(&self, buf: &mut Vec<u8>, dict: &mut StringDictionary);

    /// Get the schema for this type
    fn tbf_schema() -> Schema
    where
        Self: Sized,
    {
        Schema::new(std::any::type_name::<Self>())
    }

    /// Get the SchemaType for this type (for field type inference)
    fn tbf_schema_type() -> SchemaType
    where
        Self: Sized,
    {
        SchemaType::Map // Default for complex types
    }

    /// Get the number of fields (0 for primitives)
    fn tbf_field_count() -> usize
    where
        Self: Sized,
    {
        0
    }

    /// Encode to a new Vec with header
    fn tbf_encode(&self) -> Vec<u8>
    where
        Self: Sized,
    {
        use super::{FLAG_DICTIONARY, TBF_MAGIC, TBF_VERSION};

        let mut dict = StringDictionary::new();
        let mut data_buf = Vec::with_capacity(256);

        self.tbf_encode_to(&mut data_buf, &mut dict);

        // Encode dictionary
        let mut dict_buf = Vec::new();
        dict.encode(&mut dict_buf);

        // Build final output
        let mut result = Vec::with_capacity(8 + dict_buf.len() + data_buf.len());

        // Header
        result.extend_from_slice(&TBF_MAGIC);
        result.push(TBF_VERSION);
        result.push(FLAG_DICTIONARY);
        result.extend_from_slice(&[0u8; 2]); // Reserved

        // Dictionary
        result.extend_from_slice(&dict_buf);

        // Data
        result.extend_from_slice(&data_buf);

        result
    }

    /// Encode a slice of items with schema optimization
    fn tbf_encode_slice(items: &[Self]) -> Vec<u8>
    where
        Self: Sized,
    {
        use super::{FLAG_DICTIONARY, TBF_MAGIC, TBF_VERSION};

        let mut dict = StringDictionary::new();
        let mut data_buf = Vec::with_capacity(items.len() * 64);

        // Write count
        encode_varint(items.len() as u64, &mut data_buf);

        // Encode all items (schema-based - no type tags)
        for item in items {
            item.tbf_encode_to(&mut data_buf, &mut dict);
        }

        // Build final output
        let mut dict_buf = Vec::new();
        dict.encode(&mut dict_buf);

        let mut result = Vec::with_capacity(8 + dict_buf.len() + data_buf.len());

        // Header
        result.extend_from_slice(&TBF_MAGIC);
        result.push(TBF_VERSION);
        result.push(FLAG_DICTIONARY);
        result.extend_from_slice(&[0u8; 2]);

        // Dictionary and data
        result.extend_from_slice(&dict_buf);
        result.extend_from_slice(&data_buf);

        result
    }
}

/// Trait for types that can be decoded from TBF format
///
/// Implement this trait to enable compile-time optimized binary decoding.
/// Use `#[derive(TbfDecode)]` for automatic implementation.
///
/// # Example
///
/// ```ignore
/// use tauq::tbf::TbfDecode;
///
/// #[derive(TbfDecode)]
/// struct User {
///     id: u32,
///     name: String,
/// }
///
/// let bytes = /* ... */;
/// let user = User::tbf_decode(&bytes).unwrap();
/// ```
pub trait TbfDecode: Sized {
    /// Decode from buffer at position
    fn tbf_decode_from(
        buf: &[u8],
        pos: &mut usize,
        dict: &BorrowedDictionary,
    ) -> Result<Self, TauqError>;

    /// Decode from a complete TBF buffer (with header)
    fn tbf_decode(bytes: &[u8]) -> Result<Self, TauqError> {
        use super::{TBF_MAGIC, TBF_VERSION};

        // Verify header
        if bytes.len() < 8 {
            return Err(TauqError::Interpret(InterpretError::new(
                "Buffer too small for TBF header",
            )));
        }

        if bytes[0..4] != TBF_MAGIC {
            return Err(TauqError::Interpret(InterpretError::new(
                "Invalid TBF magic bytes",
            )));
        }

        if bytes[4] != TBF_VERSION {
            return Err(TauqError::Interpret(InterpretError::new(format!(
                "Unsupported TBF version: {}",
                bytes[4]
            ))));
        }

        let mut pos = 8;

        // Decode dictionary
        let (dict, dict_len) = BorrowedDictionary::decode(&bytes[pos..])?;
        pos += dict_len;

        // Decode value
        Self::tbf_decode_from(bytes, &mut pos, &dict)
    }

    /// Decode a slice of items
    fn tbf_decode_slice(bytes: &[u8]) -> Result<Vec<Self>, TauqError> {
        use super::{TBF_MAGIC, TBF_VERSION};

        // Verify header
        if bytes.len() < 8 {
            return Err(TauqError::Interpret(InterpretError::new(
                "Buffer too small for TBF header",
            )));
        }

        if bytes[0..4] != TBF_MAGIC {
            return Err(TauqError::Interpret(InterpretError::new(
                "Invalid TBF magic bytes",
            )));
        }

        if bytes[4] != TBF_VERSION {
            return Err(TauqError::Interpret(InterpretError::new(format!(
                "Unsupported TBF version: {}",
                bytes[4]
            ))));
        }

        let mut pos = 8;

        // Decode dictionary
        let (dict, dict_len) = BorrowedDictionary::decode(&bytes[pos..])?;
        pos += dict_len;

        // Read count
        let (count, len) = decode_varint(&bytes[pos..])?;
        pos += len;

        // Decode items
        let mut items = Vec::with_capacity(count as usize);
        for _ in 0..count {
            items.push(Self::tbf_decode_from(bytes, &mut pos, &dict)?);
        }

        Ok(items)
    }
}

// =============================================================================
// Primitive Implementations
// =============================================================================

impl TbfEncode for bool {
    fn tbf_encode_to(&self, buf: &mut Vec<u8>, _dict: &mut StringDictionary) {
        buf.push(if *self { 1 } else { 0 });
    }

    fn tbf_schema_type() -> SchemaType {
        SchemaType::Bool
    }
}

impl TbfDecode for bool {
    fn tbf_decode_from(
        buf: &[u8],
        pos: &mut usize,
        _dict: &BorrowedDictionary,
    ) -> Result<Self, TauqError> {
        if *pos >= buf.len() {
            return Err(TauqError::Interpret(InterpretError::new(
                "Unexpected end of buffer",
            )));
        }
        let value = buf[*pos] != 0;
        *pos += 1;
        Ok(value)
    }
}

macro_rules! impl_unsigned {
    ($($ty:ty),*) => {
        $(
            impl TbfEncode for $ty {
                fn tbf_encode_to(&self, buf: &mut Vec<u8>, _dict: &mut StringDictionary) {
                    encode_varint(*self as u64, buf);
                }

                fn tbf_schema_type() -> SchemaType {
                    SchemaType::UInt
                }
            }

            impl TbfDecode for $ty {
                fn tbf_decode_from(buf: &[u8], pos: &mut usize, _dict: &BorrowedDictionary) -> Result<Self, TauqError> {
                    let (value, len) = decode_varint(&buf[*pos..])?;
                    *pos += len;
                    Ok(value as $ty)
                }
            }
        )*
    };
}

macro_rules! impl_signed {
    ($($ty:ty),*) => {
        $(
            impl TbfEncode for $ty {
                fn tbf_encode_to(&self, buf: &mut Vec<u8>, _dict: &mut StringDictionary) {
                    encode_signed_varint(*self as i64, buf);
                }

                fn tbf_schema_type() -> SchemaType {
                    SchemaType::Int
                }
            }

            impl TbfDecode for $ty {
                fn tbf_decode_from(buf: &[u8], pos: &mut usize, _dict: &BorrowedDictionary) -> Result<Self, TauqError> {
                    let (value, len) = decode_signed_varint(&buf[*pos..])?;
                    *pos += len;
                    Ok(value as $ty)
                }
            }
        )*
    };
}

impl_unsigned!(u8, u16, u32, u64, usize);
impl_signed!(i8, i16, i32, i64, isize);

impl TbfEncode for f32 {
    fn tbf_encode_to(&self, buf: &mut Vec<u8>, _dict: &mut StringDictionary) {
        buf.extend_from_slice(&self.to_le_bytes());
    }

    fn tbf_schema_type() -> SchemaType {
        SchemaType::F32
    }
}

impl TbfDecode for f32 {
    fn tbf_decode_from(
        buf: &[u8],
        pos: &mut usize,
        _dict: &BorrowedDictionary,
    ) -> Result<Self, TauqError> {
        if *pos + 4 > buf.len() {
            return Err(TauqError::Interpret(InterpretError::new(
                "Unexpected end of buffer",
            )));
        }
        let bytes: [u8; 4] = buf[*pos..*pos + 4].try_into().unwrap();
        *pos += 4;
        Ok(f32::from_le_bytes(bytes))
    }
}

impl TbfEncode for f64 {
    fn tbf_encode_to(&self, buf: &mut Vec<u8>, _dict: &mut StringDictionary) {
        buf.extend_from_slice(&self.to_le_bytes());
    }

    fn tbf_schema_type() -> SchemaType {
        SchemaType::F64
    }
}

impl TbfDecode for f64 {
    fn tbf_decode_from(
        buf: &[u8],
        pos: &mut usize,
        _dict: &BorrowedDictionary,
    ) -> Result<Self, TauqError> {
        if *pos + 8 > buf.len() {
            return Err(TauqError::Interpret(InterpretError::new(
                "Unexpected end of buffer",
            )));
        }
        let bytes: [u8; 8] = buf[*pos..*pos + 8].try_into().unwrap();
        *pos += 8;
        Ok(f64::from_le_bytes(bytes))
    }
}

impl TbfEncode for String {
    fn tbf_encode_to(&self, buf: &mut Vec<u8>, dict: &mut StringDictionary) {
        let idx = dict.intern(self);
        encode_varint(idx as u64, buf);
    }

    fn tbf_schema_type() -> SchemaType {
        SchemaType::String
    }
}

impl TbfDecode for String {
    fn tbf_decode_from(
        buf: &[u8],
        pos: &mut usize,
        dict: &BorrowedDictionary,
    ) -> Result<Self, TauqError> {
        let (idx, len) = decode_varint(&buf[*pos..])?;
        *pos += len;
        dict.get(idx as u32)
            .map(|s| s.to_string())
            .ok_or_else(|| TauqError::Interpret(InterpretError::new("Invalid string index")))
    }
}

impl TbfEncode for &str {
    fn tbf_encode_to(&self, buf: &mut Vec<u8>, dict: &mut StringDictionary) {
        let idx = dict.intern(self);
        encode_varint(idx as u64, buf);
    }

    fn tbf_schema_type() -> SchemaType {
        SchemaType::String
    }
}

// =============================================================================
// Container Implementations
// =============================================================================

impl<T: TbfEncode> TbfEncode for Vec<T> {
    fn tbf_encode_to(&self, buf: &mut Vec<u8>, dict: &mut StringDictionary) {
        encode_varint(self.len() as u64, buf);
        for item in self {
            item.tbf_encode_to(buf, dict);
        }
    }

    fn tbf_schema_type() -> SchemaType {
        SchemaType::Seq
    }
}

impl<T: TbfDecode> TbfDecode for Vec<T> {
    fn tbf_decode_from(
        buf: &[u8],
        pos: &mut usize,
        dict: &BorrowedDictionary,
    ) -> Result<Self, TauqError> {
        let (count, len) = decode_varint(&buf[*pos..])?;
        *pos += len;

        let mut items = Vec::with_capacity(count as usize);
        for _ in 0..count {
            items.push(T::tbf_decode_from(buf, pos, dict)?);
        }
        Ok(items)
    }
}

impl<T: TbfEncode> TbfEncode for Option<T> {
    fn tbf_encode_to(&self, buf: &mut Vec<u8>, dict: &mut StringDictionary) {
        match self {
            None => buf.push(0),
            Some(v) => {
                buf.push(1);
                v.tbf_encode_to(buf, dict);
            }
        }
    }

    fn tbf_schema_type() -> SchemaType {
        SchemaType::Option
    }
}

impl<T: TbfDecode> TbfDecode for Option<T> {
    fn tbf_decode_from(
        buf: &[u8],
        pos: &mut usize,
        dict: &BorrowedDictionary,
    ) -> Result<Self, TauqError> {
        if *pos >= buf.len() {
            return Err(TauqError::Interpret(InterpretError::new(
                "Unexpected end of buffer",
            )));
        }

        let tag = buf[*pos];
        *pos += 1;

        match tag {
            0 => Ok(None),
            1 => Ok(Some(T::tbf_decode_from(buf, pos, dict)?)),
            _ => Err(TauqError::Interpret(InterpretError::new(
                "Invalid Option tag",
            ))),
        }
    }
}

impl<T: TbfEncode> TbfEncode for Box<T> {
    fn tbf_encode_to(&self, buf: &mut Vec<u8>, dict: &mut StringDictionary) {
        (**self).tbf_encode_to(buf, dict);
    }

    fn tbf_schema_type() -> SchemaType {
        T::tbf_schema_type()
    }
}

impl<T: TbfDecode> TbfDecode for Box<T> {
    fn tbf_decode_from(
        buf: &[u8],
        pos: &mut usize,
        dict: &BorrowedDictionary,
    ) -> Result<Self, TauqError> {
        Ok(Box::new(T::tbf_decode_from(buf, pos, dict)?))
    }
}

// =============================================================================
// Tuple Implementations
// =============================================================================

impl TbfEncode for () {
    fn tbf_encode_to(&self, _buf: &mut Vec<u8>, _dict: &mut StringDictionary) {}
}

impl TbfDecode for () {
    fn tbf_decode_from(
        _buf: &[u8],
        _pos: &mut usize,
        _dict: &BorrowedDictionary,
    ) -> Result<Self, TauqError> {
        Ok(())
    }
}

macro_rules! impl_tuple {
    ($($idx:tt: $T:ident),+) => {
        impl<$($T: TbfEncode),+> TbfEncode for ($($T,)+) {
            fn tbf_encode_to(&self, buf: &mut Vec<u8>, dict: &mut StringDictionary) {
                $(self.$idx.tbf_encode_to(buf, dict);)+
            }
        }

        impl<$($T: TbfDecode),+> TbfDecode for ($($T,)+) {
            fn tbf_decode_from(buf: &[u8], pos: &mut usize, dict: &BorrowedDictionary) -> Result<Self, TauqError> {
                Ok(($($T::tbf_decode_from(buf, pos, dict)?,)+))
            }
        }
    };
}

impl_tuple!(0: T0);
impl_tuple!(0: T0, 1: T1);
impl_tuple!(0: T0, 1: T1, 2: T2);
impl_tuple!(0: T0, 1: T1, 2: T2, 3: T3);
impl_tuple!(0: T0, 1: T1, 2: T2, 3: T3, 4: T4);
impl_tuple!(0: T0, 1: T1, 2: T2, 3: T3, 4: T4, 5: T5);

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_primitive_roundtrip() {
        // Bool
        let v = true;
        let bytes = v.tbf_encode();
        assert_eq!(bool::tbf_decode(&bytes).unwrap(), v);

        // Integers
        let v: u32 = 12345;
        let bytes = v.tbf_encode();
        assert_eq!(u32::tbf_decode(&bytes).unwrap(), v);

        let v: i64 = -987654321;
        let bytes = v.tbf_encode();
        assert_eq!(i64::tbf_decode(&bytes).unwrap(), v);

        // Floats
        let v: f64 = 1.234567890123;
        let bytes = v.tbf_encode();
        assert_eq!(f64::tbf_decode(&bytes).unwrap(), v);
    }

    #[test]
    fn test_string_roundtrip() {
        let v = String::from("Hello, TBF!");
        let bytes = v.tbf_encode();
        assert_eq!(String::tbf_decode(&bytes).unwrap(), v);
    }

    #[test]
    fn test_vec_roundtrip() {
        let v: Vec<u32> = vec![1, 2, 3, 4, 5];
        let bytes = v.tbf_encode();
        assert_eq!(Vec::<u32>::tbf_decode(&bytes).unwrap(), v);
    }

    #[test]
    fn test_option_roundtrip() {
        let some: Option<i32> = Some(42);
        let none: Option<i32> = None;

        let bytes = some.tbf_encode();
        assert_eq!(Option::<i32>::tbf_decode(&bytes).unwrap(), some);

        let bytes = none.tbf_encode();
        assert_eq!(Option::<i32>::tbf_decode(&bytes).unwrap(), none);
    }

    #[test]
    fn test_tuple_roundtrip() {
        let v = (1u32, String::from("test"), true);
        let bytes = v.tbf_encode();
        let decoded: (u32, String, bool) = TbfDecode::tbf_decode(&bytes).unwrap();
        assert_eq!(decoded, v);
    }
}