boltr 0.1.1

Pure-Rust Bolt v5.x wire protocol library
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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
//! PackStream decoding: bytes → `BoltValue`.

use bytes::Buf;

use super::marker;
use crate::error::BoltError;
use crate::types::{
    BoltDate, BoltDateTime, BoltDateTimeZoneId, BoltDict, BoltDuration, BoltLocalDateTime,
    BoltLocalTime, BoltNode, BoltPath, BoltPoint2D, BoltPoint3D, BoltRelationship, BoltTime,
    BoltUnboundRelationship, BoltValue, tag,
};

/// Decodes a single `BoltValue` from the buffer.
pub fn decode_value(buf: &mut impl Buf) -> Result<BoltValue, BoltError> {
    if !buf.has_remaining() {
        return Err(BoltError::Protocol("unexpected end of data".into()));
    }

    let m = buf.get_u8();
    match m {
        // Null
        marker::NULL => Ok(BoltValue::Null),

        // Boolean
        marker::FALSE => Ok(BoltValue::Boolean(false)),
        marker::TRUE => Ok(BoltValue::Boolean(true)),

        // Float
        marker::FLOAT_64 => {
            ensure_remaining(buf, 8)?;
            Ok(BoltValue::Float(buf.get_f64()))
        }

        // Integer markers
        marker::INT_8 => {
            ensure_remaining(buf, 1)?;
            Ok(BoltValue::Integer(i64::from(buf.get_i8())))
        }
        marker::INT_16 => {
            ensure_remaining(buf, 2)?;
            Ok(BoltValue::Integer(i64::from(buf.get_i16())))
        }
        marker::INT_32 => {
            ensure_remaining(buf, 4)?;
            Ok(BoltValue::Integer(i64::from(buf.get_i32())))
        }
        marker::INT_64 => {
            ensure_remaining(buf, 8)?;
            Ok(BoltValue::Integer(buf.get_i64()))
        }

        // Bytes
        marker::BYTES_8 => {
            ensure_remaining(buf, 1)?;
            let len = buf.get_u8() as usize;
            decode_bytes_data(buf, len)
        }
        marker::BYTES_16 => {
            ensure_remaining(buf, 2)?;
            let len = buf.get_u16() as usize;
            decode_bytes_data(buf, len)
        }
        marker::BYTES_32 => {
            ensure_remaining(buf, 4)?;
            let len = buf.get_u32() as usize;
            decode_bytes_data(buf, len)
        }

        // String (longer)
        marker::STRING_8 => {
            ensure_remaining(buf, 1)?;
            let len = buf.get_u8() as usize;
            decode_string_data(buf, len)
        }
        marker::STRING_16 => {
            ensure_remaining(buf, 2)?;
            let len = buf.get_u16() as usize;
            decode_string_data(buf, len)
        }
        marker::STRING_32 => {
            ensure_remaining(buf, 4)?;
            let len = buf.get_u32() as usize;
            decode_string_data(buf, len)
        }

        // List (longer)
        marker::LIST_8 => {
            ensure_remaining(buf, 1)?;
            let len = buf.get_u8() as usize;
            decode_list_data(buf, len)
        }
        marker::LIST_16 => {
            ensure_remaining(buf, 2)?;
            let len = buf.get_u16() as usize;
            decode_list_data(buf, len)
        }
        marker::LIST_32 => {
            ensure_remaining(buf, 4)?;
            let len = buf.get_u32() as usize;
            decode_list_data(buf, len)
        }

        // Dict (longer)
        marker::DICT_8 => {
            ensure_remaining(buf, 1)?;
            let len = buf.get_u8() as usize;
            decode_dict_data(buf, len)
        }
        marker::DICT_16 => {
            ensure_remaining(buf, 2)?;
            let len = buf.get_u16() as usize;
            decode_dict_data(buf, len)
        }
        marker::DICT_32 => {
            ensure_remaining(buf, 4)?;
            let len = buf.get_u32() as usize;
            decode_dict_data(buf, len)
        }

        // Tiny types and other ranges
        _ => {
            let high = m & 0xF0;
            let low = m & 0x0F;

            match high {
                // TINY_STRING: 0x80..=0x8F
                0x80 => decode_string_data(buf, low as usize),

                // TINY_LIST: 0x90..=0x9F
                0x90 => decode_list_data(buf, low as usize),

                // TINY_DICT: 0xA0..=0xAF
                0xA0 => decode_dict_data(buf, low as usize),

                // TINY_STRUCT: 0xB0..=0xBF
                0xB0 => {
                    ensure_remaining(buf, 1)?;
                    let tag_byte = buf.get_u8();
                    decode_struct(buf, tag_byte, low as usize)
                }

                // TINY_INT positive: 0x00..=0x7F
                _ if m <= 0x7F => Ok(BoltValue::Integer(i64::from(m))),

                // TINY_INT negative: 0xF0..=0xFF (-16..-1)
                _ if m >= 0xF0 => Ok(BoltValue::Integer(i64::from(m as i8))),

                _ => Err(BoltError::Protocol(format!(
                    "unknown PackStream marker: 0x{m:02X}"
                ))),
            }
        }
    }
}

fn ensure_remaining(buf: &impl Buf, needed: usize) -> Result<(), BoltError> {
    if buf.remaining() < needed {
        Err(BoltError::Protocol(format!(
            "need {needed} bytes but only {} remaining",
            buf.remaining()
        )))
    } else {
        Ok(())
    }
}

fn decode_bytes_data(buf: &mut impl Buf, len: usize) -> Result<BoltValue, BoltError> {
    ensure_remaining(buf, len)?;
    let mut data = vec![0u8; len];
    buf.copy_to_slice(&mut data);
    Ok(BoltValue::Bytes(data))
}

fn decode_string_data(buf: &mut impl Buf, len: usize) -> Result<BoltValue, BoltError> {
    ensure_remaining(buf, len)?;
    let mut data = vec![0u8; len];
    buf.copy_to_slice(&mut data);
    let s = String::from_utf8(data)
        .map_err(|e| BoltError::Protocol(format!("invalid UTF-8 string: {e}")))?;
    Ok(BoltValue::String(s))
}

fn decode_list_data(buf: &mut impl Buf, len: usize) -> Result<BoltValue, BoltError> {
    let mut items = Vec::with_capacity(len);
    for _ in 0..len {
        items.push(decode_value(buf)?);
    }
    Ok(BoltValue::List(items))
}

fn decode_dict_data(buf: &mut impl Buf, len: usize) -> Result<BoltValue, BoltError> {
    let mut dict = BoltDict::with_capacity(len);
    for _ in 0..len {
        let key = match decode_value(buf)? {
            BoltValue::String(s) => s,
            other => {
                return Err(BoltError::Protocol(format!(
                    "dict key must be a string, got: {other}"
                )));
            }
        };
        let value = decode_value(buf)?;
        dict.insert(key, value);
    }
    Ok(BoltValue::Dict(dict))
}

fn decode_struct(
    buf: &mut impl Buf,
    tag_byte: u8,
    field_count: usize,
) -> Result<BoltValue, BoltError> {
    match tag_byte {
        tag::NODE => decode_node(buf, field_count),
        tag::RELATIONSHIP => decode_relationship(buf, field_count),
        tag::UNBOUND_RELATIONSHIP => decode_unbound_relationship(buf, field_count),
        tag::PATH => decode_path(buf, field_count),
        tag::DATE => decode_date(buf),
        tag::TIME => decode_time(buf),
        tag::LOCAL_TIME => decode_local_time(buf),
        tag::DATE_TIME => decode_datetime(buf),
        tag::DATE_TIME_ZONE_ID => decode_datetime_zone_id(buf),
        tag::LOCAL_DATE_TIME => decode_local_datetime(buf),
        tag::DURATION => decode_duration(buf),
        tag::POINT_2D => decode_point2d(buf),
        tag::POINT_3D => decode_point3d(buf),
        _ => {
            // Unknown struct: skip fields
            for _ in 0..field_count {
                decode_value(buf)?;
            }
            Err(BoltError::Protocol(format!(
                "unknown struct tag: 0x{tag_byte:02X}"
            )))
        }
    }
}

// -- Graph structure decoding --

fn decode_node(buf: &mut impl Buf, field_count: usize) -> Result<BoltValue, BoltError> {
    // Node v5: id, labels, properties, element_id (4 fields)
    // Node v4: id, labels, properties (3 fields)
    let id = require_int(decode_value(buf)?)?;
    let labels = require_string_list(decode_value(buf)?)?;
    let properties = require_dict(decode_value(buf)?)?;
    let element_id = if field_count >= 4 {
        require_string(decode_value(buf)?)?
    } else {
        id.to_string()
    };
    Ok(BoltValue::Node(BoltNode {
        id,
        labels,
        properties,
        element_id,
    }))
}

fn decode_relationship(buf: &mut impl Buf, field_count: usize) -> Result<BoltValue, BoltError> {
    let id = require_int(decode_value(buf)?)?;
    let start_node_id = require_int(decode_value(buf)?)?;
    let end_node_id = require_int(decode_value(buf)?)?;
    let rel_type = require_string(decode_value(buf)?)?;
    let properties = require_dict(decode_value(buf)?)?;
    let (element_id, start_element_id, end_element_id) = if field_count >= 8 {
        (
            require_string(decode_value(buf)?)?,
            require_string(decode_value(buf)?)?,
            require_string(decode_value(buf)?)?,
        )
    } else {
        (
            id.to_string(),
            start_node_id.to_string(),
            end_node_id.to_string(),
        )
    };
    Ok(BoltValue::Relationship(BoltRelationship {
        id,
        start_node_id,
        end_node_id,
        rel_type,
        properties,
        element_id,
        start_element_id,
        end_element_id,
    }))
}

fn decode_unbound_relationship(
    buf: &mut impl Buf,
    field_count: usize,
) -> Result<BoltValue, BoltError> {
    let id = require_int(decode_value(buf)?)?;
    let rel_type = require_string(decode_value(buf)?)?;
    let properties = require_dict(decode_value(buf)?)?;
    let element_id = if field_count >= 4 {
        require_string(decode_value(buf)?)?
    } else {
        id.to_string()
    };
    Ok(BoltValue::UnboundRelationship(BoltUnboundRelationship {
        id,
        rel_type,
        properties,
        element_id,
    }))
}

fn decode_path(buf: &mut impl Buf, _field_count: usize) -> Result<BoltValue, BoltError> {
    let nodes_val = decode_value(buf)?;
    let nodes = match nodes_val {
        BoltValue::List(items) => items
            .into_iter()
            .map(|v| match v {
                BoltValue::Node(n) => Ok(n),
                other => Err(BoltError::Protocol(format!(
                    "path nodes must be Node, got: {other}"
                ))),
            })
            .collect::<Result<Vec<_>, _>>()?,
        _ => return Err(BoltError::Protocol("path nodes must be a list".into())),
    };

    let rels_val = decode_value(buf)?;
    let rels = match rels_val {
        BoltValue::List(items) => items
            .into_iter()
            .map(|v| match v {
                BoltValue::UnboundRelationship(r) => Ok(r),
                other => Err(BoltError::Protocol(format!(
                    "path rels must be UnboundRelationship, got: {other}"
                ))),
            })
            .collect::<Result<Vec<_>, _>>()?,
        _ => return Err(BoltError::Protocol("path rels must be a list".into())),
    };

    let indices_val = decode_value(buf)?;
    let indices = match indices_val {
        BoltValue::List(items) => items
            .into_iter()
            .map(require_int)
            .collect::<Result<Vec<_>, _>>()?,
        _ => return Err(BoltError::Protocol("path indices must be a list".into())),
    };

    Ok(BoltValue::Path(BoltPath {
        nodes,
        rels,
        indices,
    }))
}

// -- Temporal decoding --

fn decode_date(buf: &mut impl Buf) -> Result<BoltValue, BoltError> {
    let days = require_int(decode_value(buf)?)?;
    Ok(BoltValue::Date(BoltDate { days }))
}

fn decode_time(buf: &mut impl Buf) -> Result<BoltValue, BoltError> {
    let nanoseconds = require_int(decode_value(buf)?)?;
    let tz_offset_seconds = require_int(decode_value(buf)?)?;
    Ok(BoltValue::Time(BoltTime {
        nanoseconds,
        tz_offset_seconds,
    }))
}

fn decode_local_time(buf: &mut impl Buf) -> Result<BoltValue, BoltError> {
    let nanoseconds = require_int(decode_value(buf)?)?;
    Ok(BoltValue::LocalTime(BoltLocalTime { nanoseconds }))
}

fn decode_datetime(buf: &mut impl Buf) -> Result<BoltValue, BoltError> {
    let seconds = require_int(decode_value(buf)?)?;
    let nanoseconds = require_int(decode_value(buf)?)?;
    let tz_offset_seconds = require_int(decode_value(buf)?)?;
    Ok(BoltValue::DateTime(BoltDateTime {
        seconds,
        nanoseconds,
        tz_offset_seconds,
    }))
}

fn decode_datetime_zone_id(buf: &mut impl Buf) -> Result<BoltValue, BoltError> {
    let seconds = require_int(decode_value(buf)?)?;
    let nanoseconds = require_int(decode_value(buf)?)?;
    let tz_id = require_string(decode_value(buf)?)?;
    Ok(BoltValue::DateTimeZoneId(BoltDateTimeZoneId {
        seconds,
        nanoseconds,
        tz_id,
    }))
}

fn decode_local_datetime(buf: &mut impl Buf) -> Result<BoltValue, BoltError> {
    let seconds = require_int(decode_value(buf)?)?;
    let nanoseconds = require_int(decode_value(buf)?)?;
    Ok(BoltValue::LocalDateTime(BoltLocalDateTime {
        seconds,
        nanoseconds,
    }))
}

fn decode_duration(buf: &mut impl Buf) -> Result<BoltValue, BoltError> {
    let months = require_int(decode_value(buf)?)?;
    let days = require_int(decode_value(buf)?)?;
    let seconds = require_int(decode_value(buf)?)?;
    let nanoseconds = require_int(decode_value(buf)?)?;
    Ok(BoltValue::Duration(BoltDuration {
        months,
        days,
        seconds,
        nanoseconds,
    }))
}

fn decode_point2d(buf: &mut impl Buf) -> Result<BoltValue, BoltError> {
    let srid = require_int(decode_value(buf)?)?;
    let x = require_float(decode_value(buf)?)?;
    let y = require_float(decode_value(buf)?)?;
    Ok(BoltValue::Point2D(BoltPoint2D { srid, x, y }))
}

fn decode_point3d(buf: &mut impl Buf) -> Result<BoltValue, BoltError> {
    let srid = require_int(decode_value(buf)?)?;
    let x = require_float(decode_value(buf)?)?;
    let y = require_float(decode_value(buf)?)?;
    let z = require_float(decode_value(buf)?)?;
    Ok(BoltValue::Point3D(BoltPoint3D { srid, x, y, z }))
}

// -- Value extraction helpers --

fn require_int(v: BoltValue) -> Result<i64, BoltError> {
    match v {
        BoltValue::Integer(i) => Ok(i),
        other => Err(BoltError::Protocol(format!("expected int, got: {other}"))),
    }
}

fn require_float(v: BoltValue) -> Result<f64, BoltError> {
    match v {
        BoltValue::Float(f) => Ok(f),
        other => Err(BoltError::Protocol(format!("expected float, got: {other}"))),
    }
}

fn require_string(v: BoltValue) -> Result<String, BoltError> {
    match v {
        BoltValue::String(s) => Ok(s),
        other => Err(BoltError::Protocol(format!(
            "expected string, got: {other}"
        ))),
    }
}

fn require_dict(v: BoltValue) -> Result<BoltDict, BoltError> {
    match v {
        BoltValue::Dict(d) => Ok(d),
        other => Err(BoltError::Protocol(format!("expected dict, got: {other}"))),
    }
}

fn require_string_list(v: BoltValue) -> Result<Vec<String>, BoltError> {
    match v {
        BoltValue::List(items) => items.into_iter().map(require_string).collect(),
        other => Err(BoltError::Protocol(format!(
            "expected string list, got: {other}"
        ))),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::packstream::encode;
    use bytes::BytesMut;

    /// Encode then decode a value and verify round-trip.
    fn round_trip(value: &BoltValue) -> BoltValue {
        let mut buf = BytesMut::new();
        encode::encode_value(&mut buf, value);
        let mut cursor = &buf[..];
        decode_value(&mut cursor).expect("decode failed")
    }

    #[test]
    fn round_trip_null() {
        assert_eq!(round_trip(&BoltValue::Null), BoltValue::Null);
    }

    #[test]
    fn round_trip_bool() {
        assert_eq!(
            round_trip(&BoltValue::Boolean(true)),
            BoltValue::Boolean(true)
        );
        assert_eq!(
            round_trip(&BoltValue::Boolean(false)),
            BoltValue::Boolean(false)
        );
    }

    #[test]
    fn round_trip_integers() {
        // TINY_INT boundaries
        for i in [-16, -1, 0, 1, 42, 127] {
            assert_eq!(
                round_trip(&BoltValue::Integer(i)),
                BoltValue::Integer(i),
                "failed for {i}"
            );
        }
        // INT_8
        for i in [-128, -17] {
            assert_eq!(
                round_trip(&BoltValue::Integer(i)),
                BoltValue::Integer(i),
                "failed for {i}"
            );
        }
        // INT_16
        for i in [-129, 128, -32768, 32767] {
            assert_eq!(
                round_trip(&BoltValue::Integer(i)),
                BoltValue::Integer(i),
                "failed for {i}"
            );
        }
        // INT_32
        for i in [-32769, 32768, i64::from(i32::MIN), i64::from(i32::MAX)] {
            assert_eq!(
                round_trip(&BoltValue::Integer(i)),
                BoltValue::Integer(i),
                "failed for {i}"
            );
        }
        // INT_64
        for i in [
            i64::from(i32::MAX) + 1,
            i64::from(i32::MIN) - 1,
            i64::MAX,
            i64::MIN,
        ] {
            assert_eq!(
                round_trip(&BoltValue::Integer(i)),
                BoltValue::Integer(i),
                "failed for {i}"
            );
        }
    }

    #[test]
    fn round_trip_float() {
        let val = BoltValue::Float(std::f64::consts::PI);
        assert_eq!(round_trip(&val), val);
    }

    #[test]
    fn round_trip_strings() {
        // Empty
        assert_eq!(
            round_trip(&BoltValue::String(String::new())),
            BoltValue::String(String::new()),
        );
        // Tiny (1..15 bytes)
        assert_eq!(
            round_trip(&BoltValue::String("hello".into())),
            BoltValue::String("hello".into()),
        );
        // STRING_8 (16+ bytes)
        let s: String = "a".repeat(200);
        assert_eq!(
            round_trip(&BoltValue::String(s.clone())),
            BoltValue::String(s),
        );
    }

    #[test]
    fn round_trip_bytes() {
        let val = BoltValue::Bytes(vec![0xDE, 0xAD, 0xBE, 0xEF]);
        assert_eq!(round_trip(&val), val);
    }

    #[test]
    fn round_trip_list() {
        let val = BoltValue::List(vec![
            BoltValue::Integer(1),
            BoltValue::String("two".into()),
            BoltValue::Boolean(true),
        ]);
        assert_eq!(round_trip(&val), val);
    }

    #[test]
    fn round_trip_dict() {
        let val = BoltValue::Dict(BoltDict::from([
            ("name".to_string(), BoltValue::String("Alice".into())),
            ("age".to_string(), BoltValue::Integer(30)),
        ]));
        assert_eq!(round_trip(&val), val);
    }

    #[test]
    fn round_trip_node() {
        let node = BoltNode {
            id: 42,
            labels: vec!["Person".into()],
            properties: BoltDict::from([("name".to_string(), BoltValue::String("Alice".into()))]),
            element_id: "42".into(),
        };
        assert_eq!(
            round_trip(&BoltValue::Node(node.clone())),
            BoltValue::Node(node)
        );
    }

    #[test]
    fn round_trip_date() {
        let val = BoltValue::Date(BoltDate { days: 19000 });
        assert_eq!(round_trip(&val), val);
    }

    #[test]
    fn round_trip_duration() {
        let val = BoltValue::Duration(BoltDuration {
            months: 12,
            days: 30,
            seconds: 3600,
            nanoseconds: 500,
        });
        assert_eq!(round_trip(&val), val);
    }

    #[test]
    fn round_trip_point2d() {
        let val = BoltValue::Point2D(BoltPoint2D {
            srid: 4326,
            x: 12.5,
            y: 55.7,
        });
        assert_eq!(round_trip(&val), val);
    }
}