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
//! A binary codec framework for encoding and decoding Rust types to and from byte slices.
//!
//! It provides traits and implementations for codecs, encoders, decoders,
//! measurers, and fixed-size measurers.
//!
//! The library is designed to be extensible and efficient, allowing users to define
//! custom codecs for their types while leveraging existing implementations for common types.
//!
//! # Features
//! - `std`: Enables standard library support (enabled by default). Disable for `no_std` environments.
//! - `alloc`: Enables types that require allocation (`Vec`, `Box`, `String`). Enabled by default via `std`, but can be used independently in `no_std` environments with an allocator.
//! - `anyhow`: Integration with the `anyhow` error handling crate (enabled by default, requires `std`).
//! - `derive`: Enables procedural macros for deriving self-coded trait implementations for structs and enums (enabled by default).
//!
//! # Built-in Codecs
//! | Codec Type | Default for | #[byten(...)] | Codes |
//! |-----------------------|-------------|-----------------------------------------|-----------------------------------------------------------------------|
//! | [`U8Codec`] | `u8` | `u8` | `u8` type |
//! | [`I8Codec`] | `i8` | `i8` | `i8` type |
//! | [`U8ArrayCodec`] | `[u8; N]` | `[u8; N]` | fixed-size arrays of `u8` of size `N` |
//! | [`U8ArrayRefCodec`] | `&[u8; N]` | `&[u8; N]` | references to fixed-size arrays of `u8` of size `N` |
//! | [`BoolCodec`] | `bool` | `bool` | `bool` type |
//! | [`BoxCodec`] | `Box<T>` | `Box<T>` or `... box` | `Box<T>` where `t_codec` is the codec for `T` |
//! | [`ArrayCodec`] | | `... []` | fixed-size arrays, `[Item; N]` |
//! | [`EndianCodec`] | | `... $be` or `... $le` | primitive types with little/big endian byte orders |
//! | [`SelfCoded`] | | `{SelfCoded::<T>::new()}` | derived type `T` |
//! | [`UTF8Codec`] | | `$utf8` | `&str` type using the provided bytes codec |
//! | [`CStrCodec`] | `CStr` | `CStr` or `&CStr` | C-style strings (`CStr` and `&CStr`) |
//! | [`OwnedCodec`] | | `... $own` | owned data by cloning from borrowed data |
//! | [`PrefixedCodec`] | | `... for[len]` | Collections of `Item`s using the provided item and length codecs |
//! | [`RemainingCodec`] | | `..` | all remaining bytes in the input |
//! | [`UVarBECodec`] | | `... $uvarbe` | unsigned variable-length big-endian integers |
//! | [`OptionCodec`] | `Option<T>` | `... ?` | `Option<T>` using the provided codec for `T` |
//! | [`BytesCodec`] | | `$bytes[len]` | byte slices with length prefixed by the provided codec |
//! | [`PhantomCodec`] | | `= expr` | phantom codec with 0 size, codes the given constant value |
//! | `TupleNCodec` | `(a, ...N)` | `(a, ...N)` | tuple codecs for tuples of size N |
//!
//! # Usage in `no_std` Environments
//!
//! ## Core only (no allocator)
//! ```toml
//! [dependencies]
//! byten = { version = "0.0", default-features = false }
//! ```
//! Provides: primitives, arrays, slices, borrowed data (`&str`, `&[u8]`, `&CStr`)
//!
//! ## With allocator
//! ```toml
//! [dependencies]
//! byten = { version = "0.0", default-features = false, features = ["alloc"] }
//! ```
//! Adds: `Vec<T>`, `Box<T>`, owned strings, variable-length encoding
//!
extern crate alloc;
use Box;
use ;
pub use ;
pub use *;
pub use *;
pub use *;
pub use *;
pub use *;
pub use *;
pub use *;
pub use str::*;
pub use *;
pub use *;
pub use *;
pub use *;
// codec traits
/// A codec that can encode values of type `Decoded` into a byte slice.
/// It returns a result indicating success or failure but never panics.
///
/// It takes a reference to the value to be encoded, a mutable byte slice to write the encoded data into and an offset
/// indicating the current position in the byte slice.
/// The offset is updated to point to the next position after the encoded data.
///
/// # Examples
/// ## Simple u32-big-endian encoder
/// ```
/// use byten::{Encoder, EncodeError};
///
/// // Define a simple encoder for u32 in big-endian format
/// struct U32BigEndianCodec;
/// impl Encoder for U32BigEndianCodec {
/// type Decoded = u32;
/// fn encode(&self, decoded: &Self::Decoded, encoded: &mut [u8], offset: &mut usize) -> Result<(), EncodeError> {
/// // Check if there is enough space in the buffer to avoid panicking
/// if *offset + 4 > encoded.len() {
/// return Err(EncodeError::BufferTooSmall);
/// }
/// // Encode the u32 in big-endian format and write it to the buffer at the current offset
/// let [b0, b1, b2, b3] = decoded.to_be_bytes();
/// encoded[*offset] = b0;
/// encoded[*offset + 1] = b1;
/// encoded[*offset + 2] = b2;
/// encoded[*offset + 3] = b3;
/// // Update the offset to point to the next position
/// *offset += 4;
/// Ok(())
/// }
/// }
///
/// let codec = U32BigEndianCodec;
/// let mut buffer = [0xFFu8; 6];
/// let mut offset = 1; // start encoding into at index 1
/// codec.encode(&0x12345678, &mut buffer, &mut offset).unwrap();
/// assert_eq!(buffer, [
/// 0xFF, // stays unchanged
/// 0x12, 0x34, 0x56, 0x78, // encoded u32
/// 0xFF, // stays unchanged
/// ]);
/// assert_eq!(offset, 5); // offset updated correctly
/// ```
/// A codec that can decode values of type `Decoded` from a byte slice.
/// It returns a result containing the decoded value or an error if decoding fails.
///
/// It takes a byte slice containing the encoded data and a mutable offset indicating the current position in
/// the byte slice.
/// The offset is updated to point to the next position after the decoded data.
///
/// The decoded value has a lifetime tied to the lifetime of the encoded byte slice.
/// It is important to ensure that the byte slice remains valid for the duration of the decoded value's usage.
/// This is not relevant for types that own their data (e.g., `Vec<u8>`, `String`), but is crucial for
/// types that borrow data from the byte slice (e.g., `&[u8]`, `&str`).
///
/// # Examples
/// ## Owned decoded value
/// ```
/// use byten::{Decoder, DecodeError};
///
/// // Define a simple decoder for u32 in big-endian format
/// struct U32BigEndianCodec;
/// impl Decoder<'_, '_> for U32BigEndianCodec {
/// type Decoded = u32;
/// fn decode(&self, encoded: &[u8], offset: &mut usize) -> Result<Self::Decoded, DecodeError> {
/// // Check if there is enough data in the buffer to avoid panicking
/// if *offset + 4 > encoded.len() {
/// return Err(DecodeError::EOF);
/// }
/// // Decode the u32 from big-endian format from the buffer at the current offset
/// let value = u32::from_be_bytes([
/// encoded[*offset],
/// encoded[*offset + 1],
/// encoded[*offset + 2],
/// encoded[*offset + 3],
/// ]);
/// // Update the offset to point to the next position
/// *offset += 4;
/// Ok(value)
/// }
/// }
///
/// let codec = U32BigEndianCodec;
/// let buffer = [0xFFu8, 0x12, 0x34, 0x56, 0x78, 0xFF];
/// let mut offset = 1; // start decoding from index 1
/// let value = codec.decode(&buffer, &mut offset).unwrap();
/// assert_eq!(value, 0x12345678);
/// assert_eq!(offset, 5); // offset updated correctly
/// ```
///
/// ## Borrowed decoded value
/// ```
/// use byten::{Decoder, DecodeError};
///
/// // Define a simple decoder for &str assuming UTF-8 encoding
/// struct StrCodec;
/// impl<'encoded: 'decoded, 'decoded> Decoder<'encoded, 'decoded> for StrCodec {
/// type Decoded = &'decoded str;
/// fn decode(&self, encoded: &'encoded [u8], offset: &mut usize) -> Result<Self::Decoded, DecodeError> {
/// // For simplicity, assume the string is null-terminated
/// let end = encoded[*offset..]
/// .iter()
/// .position(|&b| b == 0)
/// .ok_or(DecodeError::InvalidData)?
/// + *offset;
/// let s = std::str::from_utf8(&encoded[*offset..end]).map_err(|_| DecodeError::InvalidData)?;
/// *offset = end + 1; // move past the null terminator
/// Ok(s)
/// }
/// }
///
/// let codec = StrCodec;
/// let buffer = [b'H', b'e', b'l', b'l', b'o', 0, b'W', b'o', b'r', b'l', b'd', b'!', 0];
/// let mut offset = 0;
/// let first = codec.decode(&buffer, &mut offset).unwrap();
/// assert_eq!(first, "Hello");
/// assert_eq!(offset, 6);
/// let second = codec.decode(&buffer, &mut offset).unwrap();
/// assert_eq!(second, "World!");
/// assert_eq!(offset, 13);
/// ```
/// A codec that can measure the size in bytes required to encode a value of type `Decoded`.
/// It returns a result containing the size in bytes or an error if measurement fails.
///
/// It takes a reference to the value to be measured.
///
/// This is particularly useful for types with variable-length encoding
/// where the size cannot be determined statically.
/// This is also useful for pre-allocating buffers of the correct size before encoding.
///
/// # Examples
/// ## Simple variable-length string measurer
/// ```
/// use byten::{Measurer, EncodeError};
///
/// // Define a simple measurer for strings that encodes the length as a u8 prefix
/// struct VarLenStrMeasurer;
/// impl Measurer for VarLenStrMeasurer {
/// type Decoded = str;
/// fn measure(&self, decoded: &Self::Decoded) -> Result<usize, EncodeError> {
/// let len = decoded.len();
/// if len > 255 {
/// return Err(EncodeError::InvalidData);
/// }
/// Ok(1 + len) // 1 byte for length prefix + string bytes
/// }
/// }
///
/// let measurer = VarLenStrMeasurer;
/// let size = measurer.measure("Hello").unwrap();
/// assert_eq!(size, 6); // 1 byte for length + 5 bytes for "Hello"
/// ```
/// A codec that can measure the size in bytes required to encode a value of type `Decoded`
/// where the size is fixed and does not depend on the actual value.
/// It provides a method to get the fixed size directly without needing a value.
///
/// It is expected to return the same size for any value of type `Decoded`
/// unless the internal configuration of the codec changes.
///
/// This is particularly useful for types with fixed-length encoding
/// where the size is known at compile time.
///
/// This can improve performance by avoiding the need to pass a value
/// when the size is constant by allowing the compiler to optimize for it.
///
/// # Examples
/// ## Simple fixed-length u32 measurer
/// ```
/// use byten::{FixedMeasurer, Measurer, EncodeError};
///
/// // Define a simple fixed-length measurer for u32
/// struct U32FixedMeasurer;
/// impl FixedMeasurer for U32FixedMeasurer {
/// fn measure_fixed(&self) -> usize {
/// 4 // u32 is always 4 bytes regardless of its value or endianness
/// }
/// }
///
/// // FixedMeasurer also requires Measurer implementation
/// impl Measurer for U32FixedMeasurer {
/// type Decoded = u32;
/// fn measure(&self, _decoded: &Self::Decoded) -> Result<usize, EncodeError> {
/// // For fixed-length types, the measured size is always the fixed size
/// Ok(self.measure_fixed())
/// }
/// }
///
/// let measurer = U32FixedMeasurer;
/// let size = measurer.measure_fixed();
/// assert_eq!(size, 4);
/// ```
// default codec
/// A trait for types that have a default codec associated with them.
/// This allows for easy retrieval of the default codec for a type
/// without needing to specify the codec explicitly each time.
///
/// # Examples
/// ```
/// use byten::{DefaultCodec, U8Codec};
///
/// struct MyType {
/// // ..
/// };
///
/// struct MyCodec;
///
/// impl DefaultCodec for MyType {
/// type Codec = MyCodec;
/// fn default_codec() -> Self::Codec { MyCodec }
/// }
///
/// let codec = MyType::default_codec();
/// // codec is of type MyCodec
/// ```
// defaults
}
};
}
tuple_selfcoded!;
tuple_selfcoded!;
tuple_selfcoded!;
tuple_selfcoded!;
tuple_selfcoded!;
tuple_selfcoded!;
tuple_selfcoded!;