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
//! # Helia DAG-CBOR
//!
//! CBOR (Concise Binary Object Representation) codec for Helia, providing efficient
//! serialization and content addressing for structured data in IPFS.
//!
//! ## Overview
//!
//! DAG-CBOR is a binary format for encoding structured data (objects, arrays, primitives)
//! with content addressing. It's ideal for:
//! - **Structured data storage**: Store complex objects with nested structures
//! - **Efficient serialization**: Binary format is more compact than JSON
//! - **Interoperability**: Works with other IPFS implementations (go-ipfs, js-ipfs)
//! - **Deterministic CIDs**: Same data always produces the same CID
//!
//! ## Core Concepts
//!
//! ### Content Addressing
//! Every piece of CBOR data is identified by a unique **CID** (Content Identifier)
//! derived from the serialized content. This ensures:
//! - Data integrity (tampering changes the CID)
//! - Deduplication (identical data shares the same CID)
//! - Verifiable links between data structures
//!
//! ### CBOR vs JSON
//! - **Binary format**: More compact than text-based JSON
//! - **Faster**: Quicker to serialize/deserialize
//! - **Type-safe**: Preserves numeric types, binary data
//! - **Deterministic**: Canonical encoding ensures reproducible CIDs
//!
//! ## Usage Examples
//!
//! ### Basic Object Storage
//!
//! ```no_run
//! use rust_helia::create_helia_default;
//! use helia_dag_cbor::{DagCbor, DagCborInterface};
//! use serde::{Deserialize, Serialize};
//! use std::sync::Arc;
//!
//! #[derive(Serialize, Deserialize, PartialEq, Debug)]
//! struct Person {
//! name: String,
//! age: u32,
//! email: String,
//! }
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let helia = create_helia_default().await?;
//! let dag = DagCbor::new(Arc::new(helia));
//!
//! let person = Person {
//! name: "Alice".to_string(),
//! age: 30,
//! email: "alice@example.com".to_string(),
//! };
//!
//! // Add object
//! let cid = dag.add(&person, None).await?;
//! println!("Stored person with CID: {}", cid);
//!
//! // Retrieve object
//! let retrieved: Person = dag.get(&cid, None).await?;
//! assert_eq!(person, retrieved);
//!
//! Ok(())
//! }
//! ```
//!
//! ### Nested Structures
//!
//! ```no_run
//! # use rust_helia::create_helia_default;
//! # use helia_dag_cbor::{DagCbor, DagCborInterface, AddOptions};
//! # use serde::{Deserialize, Serialize};
//! # use std::sync::Arc;
//! # use std::collections::HashMap;
//! #
//! #[derive(Serialize, Deserialize, Debug)]
//! struct Organization {
//! name: String,
//! departments: Vec<Department>,
//! metadata: HashMap<String, String>,
//! }
//!
//! #[derive(Serialize, Deserialize, Debug)]
//! struct Department {
//! name: String,
//! employee_count: u32,
//! }
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! # let helia = create_helia_default().await?;
//! # let dag = DagCbor::new(Arc::new(helia));
//! #
//! let org = Organization {
//! name: "Acme Corp".to_string(),
//! departments: vec![
//! Department {
//! name: "Engineering".to_string(),
//! employee_count: 50,
//! },
//! Department {
//! name: "Sales".to_string(),
//! employee_count: 30,
//! },
//! ],
//! metadata: HashMap::from([
//! ("founded".to_string(), "2020".to_string()),
//! ("location".to_string(), "San Francisco".to_string()),
//! ]),
//! };
//!
//! let cid = dag.add(&org, None).await?;
//! let retrieved: Organization = dag.get(&cid, None).await?;
//! # Ok(())
//! # }
//! ```
//!
//! ### Pinning Data
//!
//! Pin important data to prevent garbage collection:
//!
//! ```no_run
//! # use rust_helia::create_helia_default;
//! # use helia_dag_cbor::{DagCbor, DagCborInterface, AddOptions};
//! # use serde::{Deserialize, Serialize};
//! # use std::sync::Arc;
//! #
//! # #[derive(Serialize, Deserialize)]
//! # struct Config { setting: String }
//! #
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! # let helia = create_helia_default().await?;
//! # let dag = DagCbor::new(Arc::new(helia));
//! #
//! let config = Config {
//! setting: "important value".to_string(),
//! };
//!
//! // Pin the configuration
//! let options = AddOptions {
//! pin: true,
//! ..Default::default()
//! };
//!
//! let cid = dag.add(&config, Some(options)).await?;
//! // Data is now pinned and won't be garbage collected
//! # Ok(())
//! # }
//! ```
//!
//! ### Primitive Types
//!
//! DAG-CBOR supports all JSON-compatible types:
//!
//! ```no_run
//! # use rust_helia::create_helia_default;
//! # use helia_dag_cbor::{DagCbor, DagCborInterface};
//! # use std::sync::Arc;
//! # use std::collections::HashMap;
//! #
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! # let helia = create_helia_default().await?;
//! # let dag = DagCbor::new(Arc::new(helia));
//! #
//! // Strings
//! let text_cid = dag.add(&"Hello, IPFS!".to_string(), None).await?;
//!
//! // Numbers
//! let number_cid = dag.add(&42i32, None).await?;
//!
//! // Arrays
//! let array_cid = dag.add(&vec![1, 2, 3], None).await?;
//!
//! // Maps
//! let map = HashMap::from([
//! ("key1".to_string(), "value1".to_string()),
//! ("key2".to_string(), "value2".to_string()),
//! ]);
//! let map_cid = dag.add(&map, None).await?;
//! # Ok(())
//! # }
//! ```
//!
//! ### Thread Safety
//!
//! DagCbor is thread-safe and can be shared across tasks:
//!
//! ```no_run
//! # use rust_helia::create_helia_default;
//! # use helia_dag_cbor::{DagCbor, DagCborInterface};
//! # use std::sync::Arc;
//! # use serde::{Serialize, Deserialize};
//! #
//! # #[derive(Serialize, Deserialize)]
//! # struct Data { value: i32 }
//! #
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let helia = create_helia_default().await?;
//! let dag = Arc::new(DagCbor::new(Arc::new(helia)));
//!
//! // Clone and use in multiple tasks
//! let dag1 = Arc::clone(&dag);
//! let dag2 = Arc::clone(&dag);
//!
//! let handle1 = tokio::spawn(async move {
//! dag1.add(&Data { value: 1 }, None).await
//! });
//!
//! let handle2 = tokio::spawn(async move {
//! dag2.add(&Data { value: 2 }, None).await
//! });
//!
//! let (cid1, cid2) = tokio::join!(handle1, handle2);
//! # Ok(())
//! # }
//! ```
//!
//! ## Performance Characteristics
//!
//! ### Serialization
//! - **Small objects (<1KB)**: ~10-50µs
//! - **Medium objects (1-10KB)**: ~50-200µs
//! - **Large objects (>10KB)**: Linear with size
//!
//! ### Storage
//! - **CBOR overhead**: ~5-15% compared to raw binary
//! - **vs JSON**: 20-40% smaller on average
//! - **Deterministic**: Same input always produces same CID
//!
//! ### Memory Usage
//! - Objects are serialized in memory before storage
//! - Large objects (>1MB) should be chunked or split
//! - Consider using UnixFS for very large binary data
//!
//! ## Error Handling
//!
//! All operations return `Result<T, DagCborError>`:
//!
//! ```no_run
//! # use rust_helia::create_helia_default;
//! # use helia_dag_cbor::{DagCbor, DagCborInterface, DagCborError};
//! # use std::sync::Arc;
//! # use serde::{Serialize, Deserialize};
//! #
//! # #[derive(Serialize, Deserialize)]
//! # struct MyData { value: String }
//! #
//! # async fn example(dag: DagCbor, cid: &cid::Cid) -> Result<(), Box<dyn std::error::Error>> {
//! match dag.get::<MyData>(cid, None).await {
//! Ok(data) => println!("Retrieved: {:?}", data.value),
//! Err(DagCborError::InvalidCodec { codec }) => {
//! eprintln!("Invalid codec: expected DAG-CBOR, got {}", codec);
//! }
//! Err(DagCborError::Cbor(e)) => {
//! eprintln!("CBOR error: {}", e);
//! }
//! Err(e) => eprintln!("Other error: {}", e),
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Limitations
//!
//! ### Current Constraints
//! - **Object size**: Recommended <10MB per object
//! - **Nested depth**: Very deep nesting (>100 levels) may impact performance
//! - **Binary data**: Consider UnixFS for large binary files
//!
//! ### Future Enhancements
//! - Streaming serialization for large objects
//! - Custom codecs support
//! - Advanced CID generation options
//!
//! ## Compatibility
//!
//! This implementation is compatible with:
//! - **IPFS Specification**: Follows DAG-CBOR spec
//! - **Other implementations**: Interoperable with go-ipfs, js-ipfs
//! - **CBOR Standard**: RFC 8949 compliant
//!
//! ## See Also
//!
//! - [`DagCborInterface`] - Main trait for DAG-CBOR operations
//! - [`DagCbor`] - Implementation struct
//! - [`AddOptions`] - Configuration for add operations
//! - [`GetOptions`] - Configuration for get operations
//! - [`DagCborError`] - Error types
use async_trait;
use Cid;
use ;
use AbortOptions;
pub use *;
pub use *;
/// Options for adding CBOR data
/// Options for getting CBOR data
/// DAG-CBOR interface for adding and retrieving CBOR-encoded data