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
//! `Inline<S>` (32-byte stored payload), `Encoded<V>` (the
//! Inline-or-Blob sum that `entity!{}` builds), and the conversion
//! traits between them. For a deeper look at portability goals,
//! common formats, and schema design, refer to the "Portability &
//! Common Formats" chapter in the project book.
//!
//! # Example
//!
//! ```
//! use triblespace_core::inline::{Inline, InlineEncoding, IntoInline, TryFromInline};
//! use triblespace_core::metadata::{self, MetaDescribe};
//! use triblespace_core::trible::Fragment;
//! use triblespace_core::id::{ExclusiveId, Id};
//! use triblespace_core::macros::{id_hex, entity};
//! use std::convert::{TryInto, Infallible};
//!
//! // Define a new schema type.
//! // We're going to define an unsigned integer type that is stored as a little-endian 32-byte array.
//! // Note that makes our example easier, as we don't have to worry about sign-extension or padding bytes.
//! pub struct MyNumber;
//!
//! // The schema's identity hex lives inline in its describe body — that's
//! // the only place it appears; callers reach the id via MyNumber::id().
//! // `entity!{ &id @ ... }` returns a Fragment already rooted at `id` with
//! // the listed facts; auto-puts any blob-source values into its local
//! // store. The `metadata::tag` annotation lets schema registries discover
//! // this entity as an inline encoding.
//! impl MetaDescribe for MyNumber {
//! fn describe() -> Fragment {
//! let id: Id = id_hex!("345EAC0C5B5D7D034C87777280B88AE2");
//! entity! { ExclusiveId::force_ref(&id) @
//! metadata::name: "my_number",
//! metadata::tag: metadata::KIND_INLINE_ENCODING,
//! }
//! }
//! }
//! impl InlineEncoding for MyNumber {
//! type ValidationError = ();
//! type Encoding = Self;
//! // Every bit pattern is valid for this schema.
//! }
//!
//! // Implement conversion functions for the schema type.
//! // Use `Error = Infallible` when the conversion cannot fail.
//! impl TryFromInline<'_, MyNumber> for u32 {
//! type Error = Infallible;
//! fn try_from_inline(v: &Inline<MyNumber>) -> Result<Self, Infallible> {
//! Ok(u32::from_le_bytes(v.raw[0..4].try_into().unwrap()))
//! }
//! }
//!
//! impl triblespace_core::inline::IntoEncoded<MyNumber> for u32 {
//! type Output = Inline<MyNumber>;
//! fn into_encoded(self) -> Inline<MyNumber> {
//! // Convert the Rust type to the schema type, i.e. a 32-byte array.
//! let mut bytes = [0; 32];
//! bytes[0..4].copy_from_slice(&self.to_le_bytes());
//! Inline::new(bytes)
//! }
//! }
//!
//! // Use the schema type to store and retrieve a Rust type.
//! let value: Inline<MyNumber> = MyNumber::inline_from(42u32);
//! let i: u32 = value.from_inline();
//! assert_eq!(i, 42);
//!
//! // You can also implement conversion functions for other Rust types.
//! impl TryFromInline<'_, MyNumber> for u64 {
//! type Error = Infallible;
//! fn try_from_inline(v: &Inline<MyNumber>) -> Result<Self, Infallible> {
//! Ok(u64::from_le_bytes(v.raw[0..8].try_into().unwrap()))
//! }
//! }
//!
//! impl triblespace_core::inline::IntoEncoded<MyNumber> for u64 {
//! type Output = Inline<MyNumber>;
//! fn into_encoded(self) -> Inline<MyNumber> {
//! let mut bytes = [0; 32];
//! bytes[0..8].copy_from_slice(&self.to_le_bytes());
//! Inline::new(bytes)
//! }
//! }
//!
//! let value: Inline<MyNumber> = MyNumber::inline_from(42u64);
//! let i: u64 = value.from_inline();
//! assert_eq!(i, 42);
//!
//! // And use a value round-trip to convert between Rust types.
//! let value: Inline<MyNumber> = MyNumber::inline_from(42u32);
//! let i: u64 = value.from_inline();
//! assert_eq!(i, 42);
//! ```
/// Built-in inline encoding types and their conversion implementations.
use crateMetaDescribe;
use fmt;
use Borrow;
use Ordering;
use Debug;
use Hash;
use PhantomData;
use ToHex;
use Immutable;
use IntoBytes;
use KnownLayout;
use TryFromBytes;
use Unaligned;
/// The length of a value in bytes.
pub const INLINE_LEN: usize = 32;
/// A raw value is simply a 32-byte array.
pub type RawInline = ;
/// A value is a 32-byte array that can be (de)serialized as a Rust type.
/// The schema type parameter is an abstract type that represents the meaning
/// and valid bit patterns of the bytes.
///
/// # Example
///
/// ```
/// use triblespace_core::prelude::*;
/// use inlineencodings::R256;
/// use num_rational::Ratio;
///
/// let ratio = Ratio::new(1, 2);
/// let value: Inline<R256> = R256::inline_from(ratio);
/// let ratio2: Ratio<i128> = value.try_from_inline().unwrap();
/// assert_eq!(ratio, ratio2);
/// ```
/// A trait that represents an abstract schema type that can be (de)serialized as a [Inline].
///
/// This trait is usually implemented on a type-level empty struct,
/// but may contain additional information about the schema type as associated constants or types.
/// The [Handle](crate::inline::encodings::hash::Handle) type for example contains type information about the hash algorithm,
/// and the schema of the referenced blob.
///
/// See the [value](crate::value) module for more information.
/// See the [BlobEncoding](crate::blob::BlobEncoding) trait for the counterpart trait for blobs.
/// Fallible variant of value conversion — `T → Result<Inline<S>, Error>`.
///
/// Kept as a standalone trait (not folded into [`IntoEncoded`])
/// because the error type is part of the per-source/per-target contract.
/// Used for parses that can fail (e.g. `&str → Hash<Blake3>` via
/// hex-decoding).
/// User-implemented schema-side encoding trait, in the `From`
/// direction: **the schema is the impl target**, the source is the
/// trait parameter.
///
/// ```ignore
/// impl Encodes<&str> for LongString {
/// type Output = Blob<LongString>;
/// fn encode(s: &str) -> Blob<LongString> { Blob::new(s.into()) }
/// }
/// ```
///
/// This is the canonical orphan-rule shape (mirroring `From<T>` in
/// std): downstream that defines a local `MyBlobEncoding` writes
/// `impl Encodes<ForeignType> for MyBlobEncoding` — the local encoding
/// sits at the impl-target position so Rust's orphan checker
/// trivially accepts the impl, no matter how foreign the source
/// type is.
///
/// The user-facing source-side ergonomic — `source.into_encoded()` /
/// `source.to_inline()` / `source.to_blob()` — is blanket-derived
/// from this trait via [`IntoEncoded`].
/// Source-side ergonomic counterpart of [`Encodes`], in the `Into`
/// direction: methods like `42u32.to_inline()` resolve here.
///
/// Blanket-derived from every `Encodes` impl — users never implement
/// `IntoEncoded` directly. The split mirrors std's `From`/`Into`:
/// implement `From`, get `Into` for free.
/// Shorthand bound for `IntoEncoded<S, Output = Inline<S>>` — "this
/// source produces a directly-encoded `Inline<S>`, no side-blob."
///
/// `IntoInline` is a supertrait alias over [`IntoEncoded`]: any type
/// that implements `IntoEncoded<S>` with `Output = Inline<S>`
/// automatically becomes `IntoInline<S>`, and gains the
/// `to_inline(self) -> Inline<S>` convenience method.
/// The two-shape sum an attribute's value can take when an
/// `entity!{}` field is encoded: either a 32-byte [`Inline<V>`]
/// payload that lives directly in the trible, or a [`Blob`] holding
/// the heavy content with a derivable handle.
///
/// Replaces the older `(Inline<V>, Option<Blob>)` pair that carried
/// an implicit "Option is Some iff V is a Handle schema" invariant.
/// Encoding the split as a sum makes the invariant structural — a
/// `Encoded::Inline` never has a stored blob; a `Encoded::Blob` always
/// does — and drops the redundant handle that used to be carried
/// alongside its own blob.
/// Lift an [`IntoEncoded::Output`] into the [`Encoded`] sum the
/// `entity!{}` macro folds into a Fragment.
///
/// `V` is the *attribute's* inline encoding. Two impls cover everything:
/// - `Inline<V>` delegates to [`InlineEncoding::to_encoded`] — inline
/// path, yields `Encoded::Inline(form)`.
/// - `Blob<T>` targeting `Handle<T>` delegates to
/// [`BlobEncoding::to_encoded`](crate::blob::BlobEncoding::to_encoded) —
/// handle path, yields `Encoded::Blob(form.transmute())`.
///
/// This trait is the **dispatch shim** for the macro layer; the
/// actual logic lives on the schema traits so users (and overriding
/// schemas) can call it directly without going through the trait.
/// `to_encoded` matches the `to_inline`/`to_blob` style of the
/// supertrait aliases.
/// A trait for converting a [Inline] with a specific schema type to a Rust type.
/// This trait is implemented on the concrete Rust type.
///
/// Values are 32-byte arrays that represent data at a deserialization boundary.
/// Conversions may fail depending on the schema and target type. Use
/// `Error = Infallible` for conversions that genuinely cannot fail (e.g.
/// `ethnum::U256` from `U256BE`), and a real error type for narrowing
/// conversions (e.g. `u64` from `U256BE`).
///
/// This is the counterpart to the [TryToInline] trait.
///
/// See [TryFromBlob](crate::blob::TryFromBlob) for the counterpart trait for blobs.