-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdag_cbor.rs
More file actions
1266 lines (1110 loc) · 41.9 KB
/
Copy pathdag_cbor.rs
File metadata and controls
1266 lines (1110 loc) · 41.9 KB
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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! DAG-CBOR object encoding/decoding.
//!
//! Represents the data block section of a repository record.
//! Handles converting data between DAG-CBOR binary format and Rust types.
//!
//! Reference: <https://ipld.io/specs/codecs/dag-cbor/spec/>
use std::collections::HashMap;
use std::io::{self, Read, Write, Cursor};
use super::cid::CidV1;
/// CBOR major types.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DagCborMajorType {
UnsignedInt = 0,
NegativeInt = 1,
ByteString = 2,
Text = 3,
Array = 4,
Map = 5,
Tag = 6,
SimpleValue = 7,
}
impl DagCborMajorType {
fn from_value(value: u8) -> Option<Self> {
match value {
0 => Some(DagCborMajorType::UnsignedInt),
1 => Some(DagCborMajorType::NegativeInt),
2 => Some(DagCborMajorType::ByteString),
3 => Some(DagCborMajorType::Text),
4 => Some(DagCborMajorType::Array),
5 => Some(DagCborMajorType::Map),
6 => Some(DagCborMajorType::Tag),
7 => Some(DagCborMajorType::SimpleValue),
_ => None,
}
}
/// Returns a string representation of the major type.
pub fn as_str(&self) -> &'static str {
match self {
DagCborMajorType::UnsignedInt => "TYPE_UNSIGNED_INT",
DagCborMajorType::NegativeInt => "TYPE_NEGATIVE_INT",
DagCborMajorType::ByteString => "TYPE_BYTE_STRING",
DagCborMajorType::Text => "TYPE_TEXT",
DagCborMajorType::Array => "TYPE_ARRAY",
DagCborMajorType::Map => "TYPE_MAP",
DagCborMajorType::Tag => "TYPE_TAG",
DagCborMajorType::SimpleValue => "TYPE_SIMPLE_VALUE",
}
}
}
/// Represents CBOR type information from the first byte.
#[derive(Debug, Clone)]
pub struct DagCborType {
pub major_type: DagCborMajorType,
pub additional_info: u8,
pub original_byte: u8,
}
impl DagCborType {
/// Reads the next CBOR type from a stream.
pub fn read_next_type<R: Read>(reader: &mut R) -> io::Result<Self> {
let mut byte = [0u8; 1];
reader.read_exact(&mut byte)?;
let b = byte[0];
let major_type_val = b >> 5;
let additional_info = b & 0x1F;
let major_type = DagCborMajorType::from_value(major_type_val).ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("Unknown CBOR major type: {}", major_type_val),
)
})?;
Ok(DagCborType {
major_type,
additional_info,
original_byte: b,
})
}
/// Returns a string representation of the major type.
pub fn get_major_type_string(&self) -> &'static str {
self.major_type.as_str()
}
}
impl std::fmt::Display for DagCborType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"CborType -> {} ({}), AdditionalInfo: {}",
self.get_major_type_string(),
self.major_type as u8,
self.additional_info
)
}
}
/// The value stored in a DAG-CBOR object.
#[derive(Debug, Clone)]
pub enum DagCborValue {
/// Unsigned integer
UnsignedInt(i64),
/// Negative integer
NegativeInt(i64),
/// Byte string
ByteString(Vec<u8>),
/// Text string
Text(String),
/// Array of DAG-CBOR objects
Array(Vec<DagCborObject>),
/// Map of string keys to DAG-CBOR objects
Map(HashMap<String, DagCborObject>),
/// CID tag (tag 42)
Cid(CidV1),
/// Boolean value
Bool(bool),
/// Null value
Null,
}
impl DagCborValue {
/// Tries to get the value as a string.
pub fn as_string(&self) -> Option<&str> {
match self {
DagCborValue::Text(s) => Some(s),
_ => None,
}
}
/// Tries to get the value as an integer.
pub fn as_int(&self) -> Option<i64> {
match self {
DagCborValue::UnsignedInt(n) => Some(*n),
DagCborValue::NegativeInt(n) => Some(*n),
_ => None,
}
}
/// Tries to get the value as a map.
pub fn as_map(&self) -> Option<&HashMap<String, DagCborObject>> {
match self {
DagCborValue::Map(m) => Some(m),
_ => None,
}
}
/// Tries to get the value as an array.
pub fn as_array(&self) -> Option<&Vec<DagCborObject>> {
match self {
DagCborValue::Array(arr) => Some(arr),
_ => None,
}
}
/// Tries to get the value as a CID.
pub fn as_cid(&self) -> Option<&CidV1> {
match self {
DagCborValue::Cid(cid) => Some(cid),
_ => None,
}
}
/// Tries to get the value as a byte string.
pub fn as_bytes(&self) -> Option<&Vec<u8>> {
match self {
DagCborValue::ByteString(bytes) => Some(bytes),
_ => None,
}
}
}
/// A DAG-CBOR object representing a data block in a repository record.
#[derive(Debug, Clone)]
pub struct DagCborObject {
pub cbor_type: DagCborType,
pub value: DagCborValue,
}
impl DagCborObject {
/// Reads a DAG-CBOR object from a stream.
pub fn read_from_stream<R: Read>(reader: &mut R) -> io::Result<Self> {
let cbor_type = DagCborType::read_next_type(reader)?;
let value = match cbor_type.major_type {
DagCborMajorType::Map => {
let length = Self::read_length_from_stream(&cbor_type, reader)?;
let mut map = HashMap::new();
for _ in 0..length {
let key_obj = DagCborObject::read_from_stream(reader)?;
let key = key_obj.try_get_string().ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidData, "Map key must be a string")
})?;
let value = DagCborObject::read_from_stream(reader)?;
map.insert(key, value);
}
DagCborValue::Map(map)
}
DagCborMajorType::Array => {
let length = Self::read_length_from_stream(&cbor_type, reader)?;
let mut array = Vec::with_capacity(length);
for _ in 0..length {
array.push(DagCborObject::read_from_stream(reader)?);
}
DagCborValue::Array(array)
}
DagCborMajorType::Text => {
let length = Self::read_length_from_stream(&cbor_type, reader)?;
let mut bytes = vec![0u8; length];
reader.read_exact(&mut bytes)?;
let text = String::from_utf8(bytes).map_err(|e| {
io::Error::new(io::ErrorKind::InvalidData, format!("Invalid UTF-8: {}", e))
})?;
DagCborValue::Text(text)
}
DagCborMajorType::Tag => {
// Read the tag value
let mut tag_byte = [0u8; 1];
reader.read_exact(&mut tag_byte)?;
let tag = tag_byte[0];
if tag != 42 {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("Unknown tag: {}. Only tag 42 (CID) is supported.", tag),
));
}
// Read byte string type
let _byte_string_type = DagCborType::read_next_type(reader)?;
let _length = Self::read_length_from_stream(&_byte_string_type, reader)?;
// Read and discard the multibase prefix (should be 0)
let mut prefix = [0u8; 1];
reader.read_exact(&mut prefix)?;
// Read the CID
let cid = CidV1::read_cid(reader)?;
DagCborValue::Cid(cid)
}
DagCborMajorType::UnsignedInt => {
let value = Self::read_length_from_stream(&cbor_type, reader)? as i64;
DagCborValue::UnsignedInt(value)
}
DagCborMajorType::NegativeInt => {
let value = Self::read_length_from_stream(&cbor_type, reader)? as i64;
// CBOR negative int encoding: -1 - n
DagCborValue::NegativeInt(-1 - value)
}
DagCborMajorType::ByteString => {
let length = Self::read_length_from_stream(&cbor_type, reader)?;
let mut bytes = vec![0u8; length];
reader.read_exact(&mut bytes)?;
DagCborValue::ByteString(bytes)
}
DagCborMajorType::SimpleValue => {
match cbor_type.additional_info {
0x16 => DagCborValue::Null,
0x14 => DagCborValue::Bool(false),
0x15 => DagCborValue::Bool(true),
_ => {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("Unknown simple value: {}", cbor_type.additional_info),
))
}
}
}
};
Ok(DagCborObject { cbor_type, value })
}
/// Reads a DAG-CBOR object from bytes.
pub fn from_bytes(data: &[u8]) -> io::Result<Self> {
let mut cursor = Cursor::new(data);
Self::read_from_stream(&mut cursor)
}
/// Writes this DAG-CBOR object to a stream.
pub fn write_to_stream<W: Write>(&self, writer: &mut W) -> io::Result<()> {
match &self.value {
DagCborValue::Map(map) => {
Self::write_length_to_stream(DagCborMajorType::Map as u8, map.len(), writer)?;
// DAG-CBOR requires map keys to be sorted in canonical order:
// first by byte length, then lexicographically
let mut keys: Vec<_> = map.keys().collect();
keys.sort_by(|a, b| {
let a_len = a.as_bytes().len();
let b_len = b.as_bytes().len();
a_len.cmp(&b_len).then_with(|| a.cmp(b))
});
for key in keys {
// Write key as text string
let key_bytes = key.as_bytes();
Self::write_length_to_stream(DagCborMajorType::Text as u8, key_bytes.len(), writer)?;
writer.write_all(key_bytes)?;
// Write value
map.get(key).unwrap().write_to_stream(writer)?;
}
}
DagCborValue::Array(array) => {
Self::write_length_to_stream(DagCborMajorType::Array as u8, array.len(), writer)?;
for item in array {
item.write_to_stream(writer)?;
}
}
DagCborValue::Text(text) => {
let bytes = text.as_bytes();
Self::write_length_to_stream(DagCborMajorType::Text as u8, bytes.len(), writer)?;
writer.write_all(bytes)?;
}
DagCborValue::Cid(cid) => {
// Write tag type and tag number (42 for CID)
let tag_byte = (DagCborMajorType::Tag as u8) << 5 | 24;
writer.write_all(&[tag_byte, 42])?;
// Calculate CID bytes
let mut cid_bytes = Vec::new();
cid.write_cid(&mut cid_bytes)?;
// Write byte string type for CID (with 0 prefix)
Self::write_length_to_stream(
DagCborMajorType::ByteString as u8,
cid_bytes.len() + 1,
writer,
)?;
writer.write_all(&[0])?; // multibase prefix
writer.write_all(&cid_bytes)?;
}
DagCborValue::UnsignedInt(value) => {
Self::write_length_to_stream(DagCborMajorType::UnsignedInt as u8, *value as usize, writer)?;
}
DagCborValue::NegativeInt(value) => {
// CBOR negative int encoding: store (-1 - n)
let encoded = (-1 - value) as usize;
Self::write_length_to_stream(DagCborMajorType::NegativeInt as u8, encoded, writer)?;
}
DagCborValue::ByteString(bytes) => {
Self::write_length_to_stream(DagCborMajorType::ByteString as u8, bytes.len(), writer)?;
writer.write_all(bytes)?;
}
DagCborValue::Bool(true) => {
let byte = (DagCborMajorType::SimpleValue as u8) << 5 | 0x15;
writer.write_all(&[byte])?;
}
DagCborValue::Bool(false) => {
let byte = (DagCborMajorType::SimpleValue as u8) << 5 | 0x14;
writer.write_all(&[byte])?;
}
DagCborValue::Null => {
let byte = (DagCborMajorType::SimpleValue as u8) << 5 | 0x16;
writer.write_all(&[byte])?;
}
}
Ok(())
}
/// Converts this object to bytes.
pub fn to_bytes(&self) -> io::Result<Vec<u8>> {
let mut buf = Vec::new();
self.write_to_stream(&mut buf)?;
Ok(buf)
}
/// Reads the length value from the stream based on additional info.
fn read_length_from_stream<R: Read>(cbor_type: &DagCborType, reader: &mut R) -> io::Result<usize> {
let info = cbor_type.additional_info;
if info < 24 {
Ok(info as usize)
} else if info == 24 {
let mut byte = [0u8; 1];
reader.read_exact(&mut byte)?;
Ok(byte[0] as usize)
} else if info == 25 {
let mut bytes = [0u8; 2];
reader.read_exact(&mut bytes)?;
Ok(u16::from_be_bytes(bytes) as usize)
} else if info == 26 {
let mut bytes = [0u8; 4];
reader.read_exact(&mut bytes)?;
Ok(u32::from_be_bytes(bytes) as usize)
} else if info == 27 {
let mut bytes = [0u8; 8];
reader.read_exact(&mut bytes)?;
Ok(u64::from_be_bytes(bytes) as usize)
} else {
Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("Unknown additional info: {}", info),
))
}
}
/// Writes the length value to the stream with appropriate encoding.
fn write_length_to_stream<W: Write>(
major_type: u8,
length: usize,
writer: &mut W,
) -> io::Result<()> {
if length < 24 {
let byte = (major_type << 5) | (length as u8);
writer.write_all(&[byte])?;
} else if length < 256 {
let byte = (major_type << 5) | 24;
writer.write_all(&[byte, length as u8])?;
} else if length < 65536 {
let byte = (major_type << 5) | 25;
writer.write_all(&[byte])?;
writer.write_all(&(length as u16).to_be_bytes())?;
} else if length < 0x1_0000_0000 {
let byte = (major_type << 5) | 26;
writer.write_all(&[byte])?;
writer.write_all(&(length as u32).to_be_bytes())?;
} else {
let byte = (major_type << 5) | 27;
writer.write_all(&[byte])?;
writer.write_all(&(length as u64).to_be_bytes())?;
}
Ok(())
}
/// Tries to get the value as a string.
pub fn try_get_string(&self) -> Option<String> {
match &self.value {
DagCborValue::Text(s) => Some(s.clone()),
DagCborValue::UnsignedInt(n) => Some(n.to_string()),
DagCborValue::NegativeInt(n) => Some(n.to_string()),
DagCborValue::Bool(b) => Some(b.to_string()),
DagCborValue::Cid(cid) => Some(cid.get_base32().to_string()),
_ => None,
}
}
/// Selects a string value at the given property path.
pub fn select_string(&self, property_names: &[&str]) -> Option<String> {
let obj = self.select_object(property_names)?;
obj.try_get_string()
}
/// Selects an integer value at the given property path.
pub fn select_int(&self, property_names: &[&str]) -> Option<i64> {
let obj = self.select_object(property_names)?;
obj.value.as_int()
}
/// Selects an array at the given property path.
pub fn select_array(&self, property_names: &[&str]) -> Option<&Vec<DagCborObject>> {
let obj = self.select_object(property_names)?;
obj.value.as_array()
}
/// Selects a byte string at the given property path.
pub fn select_bytes(&self, property_names: &[&str]) -> Option<&Vec<u8>> {
let obj = self.select_object(property_names)?;
obj.value.as_bytes()
}
/// Selects a CID at the given property path.
pub fn select_cid(&self, property_names: &[&str]) -> Option<&CidV1> {
let obj = self.select_object(property_names)?;
obj.value.as_cid()
}
/// Selects an object at the given property path.
pub fn select_object(&self, property_names: &[&str]) -> Option<&DagCborObject> {
let mut current = self;
for name in property_names {
match ¤t.value {
DagCborValue::Map(map) => {
current = map.get(*name)?;
}
_ => return None,
}
}
Some(current)
}
// ==================== CONSTRUCTORS ====================
/// Creates a new DagCborObject containing a map.
pub fn new_map(map: HashMap<String, DagCborObject>) -> Self {
Self {
cbor_type: DagCborType {
major_type: DagCborMajorType::Map,
additional_info: 0,
original_byte: 0,
},
value: DagCborValue::Map(map),
}
}
/// Creates a new DagCborObject containing an array.
pub fn new_array(array: Vec<DagCborObject>) -> Self {
Self {
cbor_type: DagCborType {
major_type: DagCborMajorType::Array,
additional_info: 0,
original_byte: 0,
},
value: DagCborValue::Array(array),
}
}
/// Creates a new DagCborObject containing a CID.
pub fn new_cid(cid: CidV1) -> Self {
Self {
cbor_type: DagCborType {
major_type: DagCborMajorType::Tag,
additional_info: 42,
original_byte: 0,
},
value: DagCborValue::Cid(cid),
}
}
/// Creates a new DagCborObject containing an unsigned integer.
pub fn new_unsigned_int(value: i64) -> Self {
Self {
cbor_type: DagCborType {
major_type: DagCborMajorType::UnsignedInt,
additional_info: 0,
original_byte: 0,
},
value: DagCborValue::UnsignedInt(value),
}
}
/// Creates a new DagCborObject containing a byte string.
pub fn new_byte_string(bytes: Vec<u8>) -> Self {
Self {
cbor_type: DagCborType {
major_type: DagCborMajorType::ByteString,
additional_info: 0,
original_byte: 0,
},
value: DagCborValue::ByteString(bytes),
}
}
/// Creates a new DagCborObject containing a text string.
pub fn new_text(text: String) -> Self {
Self {
cbor_type: DagCborType {
major_type: DagCborMajorType::Text,
additional_info: 0,
original_byte: 0,
},
value: DagCborValue::Text(text),
}
}
/// Creates a new DagCborObject containing null.
pub fn new_null() -> Self {
Self {
cbor_type: DagCborType {
major_type: DagCborMajorType::SimpleValue,
additional_info: 0x16,
original_byte: 0,
},
value: DagCborValue::Null,
}
}
/// Converts this DAG-CBOR object to a JSON-compatible value for display.
pub fn to_json_value(&self) -> serde_json::Value {
match &self.value {
DagCborValue::Text(s) => serde_json::Value::String(s.clone()),
DagCborValue::UnsignedInt(n) => serde_json::Value::Number((*n).into()),
DagCborValue::NegativeInt(n) => serde_json::Value::Number((*n).into()),
DagCborValue::Bool(b) => serde_json::Value::Bool(*b),
DagCborValue::Null => serde_json::Value::Null,
DagCborValue::ByteString(bytes) => {
// Encode bytes as base64 for JSON
serde_json::Value::String(format!("base64:{}", base64_encode(bytes)))
}
DagCborValue::Cid(cid) => {
// Return CID as a "$link" object (AT Protocol convention)
serde_json::json!({ "$link": cid.get_base32() })
}
DagCborValue::Array(arr) => {
serde_json::Value::Array(arr.iter().map(|item| item.to_json_value()).collect())
}
DagCborValue::Map(map) => {
let mut json_map = serde_json::Map::new();
for (key, value) in map {
json_map.insert(key.clone(), value.to_json_value());
}
serde_json::Value::Object(json_map)
}
}
}
/// Converts this DAG-CBOR object to a JSON string.
pub fn to_json_string(&self) -> String {
let json_value = self.to_json_value();
serde_json::to_string_pretty(&json_value).unwrap_or_else(|_| "{}".to_string())
}
/// Returns a recursive debug string showing the structure and types of this object.
pub fn get_recursive_debug_string(&self, indent: usize) -> String {
let indent_str = " ".repeat(indent);
let mut result = format!(
"{}Type: {}, Value: {:?}\n",
indent_str,
self.cbor_type.get_major_type_string(),
self.get_value_summary()
);
match &self.value {
DagCborValue::Map(map) => {
for (key, value) in map {
result.push_str(&format!("{}Key: {}\n", indent_str, key));
result.push_str(&value.get_recursive_debug_string(indent + 1));
}
}
DagCborValue::Array(arr) => {
for (i, item) in arr.iter().enumerate() {
result.push_str(&format!("{}Index: {}\n", indent_str, i));
result.push_str(&item.get_recursive_debug_string(indent + 1));
}
}
_ => {}
}
result
}
/// Returns a summary of the value for debug display.
fn get_value_summary(&self) -> String {
match &self.value {
DagCborValue::Text(s) => {
if s.len() > 50 {
format!("\"{}...\"", &s[..50])
} else {
format!("\"{}\"", s)
}
}
DagCborValue::UnsignedInt(n) => n.to_string(),
DagCborValue::NegativeInt(n) => n.to_string(),
DagCborValue::Bool(b) => b.to_string(),
DagCborValue::Null => "null".to_string(),
DagCborValue::ByteString(bytes) => format!("<{} bytes>", bytes.len()),
DagCborValue::Cid(cid) => cid.get_base32().to_string(),
DagCborValue::Map(map) => format!("<map with {} entries>", map.len()),
DagCborValue::Array(arr) => format!("<array with {} items>", arr.len()),
}
}
}
impl std::fmt::Display for DagCborObject {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "DagCborObject -> {:?}", self.value)
}
}
/// Simple base64 encoding for byte strings.
fn base64_encode(bytes: &[u8]) -> String {
const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut result = String::new();
for chunk in bytes.chunks(3) {
let mut buf = [0u8; 3];
buf[..chunk.len()].copy_from_slice(chunk);
let n = (buf[0] as u32) << 16 | (buf[1] as u32) << 8 | buf[2] as u32;
result.push(ALPHABET[(n >> 18) as usize & 63] as char);
result.push(ALPHABET[(n >> 12) as usize & 63] as char);
if chunk.len() > 1 {
result.push(ALPHABET[(n >> 6) as usize & 63] as char);
} else {
result.push('=');
}
if chunk.len() > 2 {
result.push(ALPHABET[n as usize & 63] as char);
} else {
result.push('=');
}
}
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_read_simple_text() {
// CBOR encoding of the string "hello"
let data = vec![0x65, b'h', b'e', b'l', b'l', b'o'];
let obj = DagCborObject::from_bytes(&data).unwrap();
assert_eq!(obj.try_get_string(), Some("hello".to_string()));
}
#[test]
fn test_read_unsigned_int() {
// CBOR encoding of the integer 42
let data = vec![0x18, 42];
let obj = DagCborObject::from_bytes(&data).unwrap();
match obj.value {
DagCborValue::UnsignedInt(n) => assert_eq!(n, 42),
_ => panic!("Expected UnsignedInt"),
}
}
#[test]
fn test_read_simple_map() {
// CBOR encoding of {"a": 1}
// a1 (map with 1 item) 61 (text, 1 char) 61 (ASCII 'a') 01 (unsigned int 1)
let data = vec![0xA1, 0x61, b'a', 0x01];
let obj = DagCborObject::from_bytes(&data).unwrap();
match &obj.value {
DagCborValue::Map(map) => {
assert_eq!(map.len(), 1);
let a = map.get("a").unwrap();
match a.value {
DagCborValue::UnsignedInt(n) => assert_eq!(n, 1),
_ => panic!("Expected UnsignedInt"),
}
}
_ => panic!("Expected Map"),
}
}
#[test]
fn test_roundtrip() {
// Create a simple map and verify roundtrip
let data = vec![0xA1, 0x61, b'a', 0x01]; // {"a": 1}
let obj = DagCborObject::from_bytes(&data).unwrap();
let encoded = obj.to_bytes().unwrap();
let obj2 = DagCborObject::from_bytes(&encoded).unwrap();
assert_eq!(obj.to_json_string(), obj2.to_json_string());
}
// ========== Round-trip tests for each DAG-CBOR type ==========
#[test]
fn test_roundtrip_unsigned_int_small() {
// Small unsigned integers (0-23) encode in single byte
for n in 0..24i64 {
let obj = DagCborObject {
cbor_type: DagCborType {
major_type: DagCborMajorType::UnsignedInt,
additional_info: n as u8,
original_byte: 0,
},
value: DagCborValue::UnsignedInt(n),
};
let encoded = obj.to_bytes().unwrap();
let decoded = DagCborObject::from_bytes(&encoded).unwrap();
match decoded.value {
DagCborValue::UnsignedInt(v) => assert_eq!(v, n, "Failed for {}", n),
_ => panic!("Expected UnsignedInt for {}", n),
}
}
}
#[test]
fn test_roundtrip_unsigned_int_large() {
// Test various sizes of unsigned integers
let values = [24, 100, 255, 256, 1000, 65535, 65536, 1_000_000, i64::MAX / 2];
for &n in &values {
let obj = DagCborObject {
cbor_type: DagCborType {
major_type: DagCborMajorType::UnsignedInt,
additional_info: 0,
original_byte: 0,
},
value: DagCborValue::UnsignedInt(n),
};
let encoded = obj.to_bytes().unwrap();
let decoded = DagCborObject::from_bytes(&encoded).unwrap();
match decoded.value {
DagCborValue::UnsignedInt(v) => assert_eq!(v, n, "Failed for {}", n),
_ => panic!("Expected UnsignedInt for {}", n),
}
}
}
#[test]
fn test_roundtrip_negative_int() {
// Test negative integers
let values = [-1, -10, -100, -1000, -1_000_000];
for &n in &values {
let obj = DagCborObject {
cbor_type: DagCborType {
major_type: DagCborMajorType::NegativeInt,
additional_info: 0,
original_byte: 0,
},
value: DagCborValue::NegativeInt(n),
};
let encoded = obj.to_bytes().unwrap();
let decoded = DagCborObject::from_bytes(&encoded).unwrap();
match decoded.value {
DagCborValue::NegativeInt(v) => assert_eq!(v, n, "Failed for {}", n),
_ => panic!("Expected NegativeInt for {}", n),
}
}
}
#[test]
fn test_roundtrip_text() {
let texts = ["", "a", "hello", "Hello, World!", "こんにちは", "🚀"];
for text in &texts {
let obj = DagCborObject {
cbor_type: DagCborType {
major_type: DagCborMajorType::Text,
additional_info: 0,
original_byte: 0,
},
value: DagCborValue::Text(text.to_string()),
};
let encoded = obj.to_bytes().unwrap();
let decoded = DagCborObject::from_bytes(&encoded).unwrap();
match &decoded.value {
DagCborValue::Text(v) => assert_eq!(v, *text, "Failed for {}", text),
_ => panic!("Expected Text for {}", text),
}
}
}
#[test]
fn test_roundtrip_byte_string() {
let byte_arrays: Vec<Vec<u8>> = vec![
vec![],
vec![0],
vec![1, 2, 3, 4, 5],
vec![0xFF; 100],
(0..256).map(|i| i as u8).collect(),
];
for bytes in &byte_arrays {
let obj = DagCborObject {
cbor_type: DagCborType {
major_type: DagCborMajorType::ByteString,
additional_info: 0,
original_byte: 0,
},
value: DagCborValue::ByteString(bytes.clone()),
};
let encoded = obj.to_bytes().unwrap();
let decoded = DagCborObject::from_bytes(&encoded).unwrap();
match &decoded.value {
DagCborValue::ByteString(v) => assert_eq!(v, bytes, "Failed for {:?}", bytes),
_ => panic!("Expected ByteString for {:?}", bytes),
}
}
}
#[test]
fn test_roundtrip_bool() {
for b in [true, false] {
let obj = DagCborObject {
cbor_type: DagCborType {
major_type: DagCborMajorType::SimpleValue,
additional_info: if b { 0x15 } else { 0x14 },
original_byte: 0,
},
value: DagCborValue::Bool(b),
};
let encoded = obj.to_bytes().unwrap();
let decoded = DagCborObject::from_bytes(&encoded).unwrap();
match decoded.value {
DagCborValue::Bool(v) => assert_eq!(v, b, "Failed for {}", b),
_ => panic!("Expected Bool for {}", b),
}
}
}
#[test]
fn test_roundtrip_null() {
let obj = DagCborObject {
cbor_type: DagCborType {
major_type: DagCborMajorType::SimpleValue,
additional_info: 0x16,
original_byte: 0,
},
value: DagCborValue::Null,
};
let encoded = obj.to_bytes().unwrap();
let decoded = DagCborObject::from_bytes(&encoded).unwrap();
match decoded.value {
DagCborValue::Null => {},
_ => panic!("Expected Null"),
}
}
#[test]
fn test_roundtrip_array() {
// Empty array
let obj = DagCborObject {
cbor_type: DagCborType {
major_type: DagCborMajorType::Array,
additional_info: 0,
original_byte: 0,
},
value: DagCborValue::Array(vec![]),
};
let encoded = obj.to_bytes().unwrap();
let decoded = DagCborObject::from_bytes(&encoded).unwrap();
match &decoded.value {
DagCborValue::Array(arr) => assert_eq!(arr.len(), 0),
_ => panic!("Expected Array"),
}
// Array with mixed types
let items = vec![
DagCborObject {
cbor_type: DagCborType {
major_type: DagCborMajorType::UnsignedInt,
additional_info: 0,
original_byte: 0,
},
value: DagCborValue::UnsignedInt(42),
},
DagCborObject {
cbor_type: DagCborType {
major_type: DagCborMajorType::Text,
additional_info: 0,
original_byte: 0,
},
value: DagCborValue::Text("hello".to_string()),
},
DagCborObject {
cbor_type: DagCborType {
major_type: DagCborMajorType::SimpleValue,
additional_info: 0x15,
original_byte: 0,
},
value: DagCborValue::Bool(true),
},
];
let obj = DagCborObject {
cbor_type: DagCborType {
major_type: DagCborMajorType::Array,