capnp-newtype 0.27.3

runtime library for Cap'n Proto data encoding with newtype support
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
//! Traits and types to support run-time type introspection, i.e. reflection.

use crate::private::layout::ElementSize;
use crate::schema::{EnumSchema, StructSchema};

/// A type that supports reflection. All types that can appear in a Cap'n Proto message
/// implement this trait.
pub trait Introspect {
    /// Retrieves a description of the type.
    fn introspect() -> Type;
}

/// A description of a Cap'n Proto type. The representation is
/// optimized to avoid heap allocation.
///
/// To examine a `Type`, you should call the `which()` method.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct Type {
    /// The type, minus any outer `List( )`.
    base: BaseType,

    /// How many times `base` is wrapped in `List( )`.
    list_count: usize,
}

impl Type {
    /// Constructs a new `Type` that is not a list.
    fn new_base(base: BaseType) -> Self {
        Self {
            base,
            list_count: 0,
        }
    }

    /// Constructs a new `Type` that is a list wrapping some other `Type`.
    pub fn list_of(mut element_type: Type) -> Self {
        element_type.list_count += 1;
        element_type
    }

    /// Unfolds a single layer of the `Type`, to allow for pattern matching.
    pub fn which(&self) -> TypeVariant {
        if self.list_count > 0 {
            TypeVariant::List(Type {
                base: self.base,
                list_count: self.list_count - 1,
            })
        } else {
            match self.base {
                BaseType::Void => TypeVariant::Void,
                BaseType::Bool => TypeVariant::Bool,
                BaseType::Int8 => TypeVariant::Int8,
                BaseType::Int16 => TypeVariant::Int16,
                BaseType::Int32 => TypeVariant::Int32,
                BaseType::Int64 => TypeVariant::Int64,
                BaseType::UInt8 => TypeVariant::UInt8,
                BaseType::UInt16 => TypeVariant::UInt16,
                BaseType::UInt32 => TypeVariant::UInt32,
                BaseType::UInt64 => TypeVariant::UInt64,
                BaseType::Float32 => TypeVariant::Float32,
                BaseType::Float64 => TypeVariant::Float64,
                BaseType::Text => TypeVariant::Text,
                BaseType::Data => TypeVariant::Data,
                BaseType::Enum(re) => TypeVariant::Enum(re),
                BaseType::Struct(rs) => TypeVariant::Struct(rs),
                BaseType::AnyPointer => TypeVariant::AnyPointer,
                BaseType::Capability => TypeVariant::Capability,
            }
        }
    }

    /// If this type T appears as List(T), then what is the expected
    /// element size of the list?
    pub(crate) fn expected_element_size(&self) -> ElementSize {
        if self.list_count > 0 {
            ElementSize::Pointer
        } else {
            match self.base {
                BaseType::Void => ElementSize::Void,
                BaseType::Bool => ElementSize::Bit,
                BaseType::Int8 | BaseType::UInt8 => ElementSize::Byte,
                BaseType::Int16 | BaseType::UInt16 | BaseType::Enum(_) => ElementSize::TwoBytes,
                BaseType::Int32 | BaseType::UInt32 | BaseType::Float32 => ElementSize::FourBytes,
                BaseType::Int64 | BaseType::UInt64 | BaseType::Float64 => ElementSize::EightBytes,
                BaseType::Text | BaseType::Data | BaseType::AnyPointer | BaseType::Capability => {
                    ElementSize::Pointer
                }
                BaseType::Struct(_) => ElementSize::InlineComposite,
            }
        }
    }

    /// Is the `Type` a pointer type?
    pub fn is_pointer_type(&self) -> bool {
        if self.list_count > 0 {
            true
        } else {
            matches!(
                self.base,
                BaseType::Text
                    | BaseType::Data
                    | BaseType::AnyPointer
                    | BaseType::Struct(_)
                    | BaseType::Capability
            )
        }
    }

    /// Returns true if `self` is equal to `other` modulo
    /// type parameters and interface types.
    #[deprecated(
        since = "0.27.0",
        note = "Type now implements Eq. loose_equals ignores generics on structs, while Eq is more precise and most likely the one you want."
    )]
    pub fn loose_equals(&self, other: Self) -> bool {
        match (self.which(), other.which()) {
            (TypeVariant::Void, TypeVariant::Void) => true,
            (TypeVariant::Bool, TypeVariant::Bool) => true,
            (TypeVariant::UInt8, TypeVariant::UInt8) => true,
            (TypeVariant::UInt16, TypeVariant::UInt16) => true,
            (TypeVariant::UInt32, TypeVariant::UInt32) => true,
            (TypeVariant::UInt64, TypeVariant::UInt64) => true,
            (TypeVariant::Int8, TypeVariant::Int8) => true,
            (TypeVariant::Int16, TypeVariant::Int16) => true,
            (TypeVariant::Int32, TypeVariant::Int32) => true,
            (TypeVariant::Int64, TypeVariant::Int64) => true,
            (TypeVariant::Float32, TypeVariant::Float32) => true,
            (TypeVariant::Float64, TypeVariant::Float64) => true,
            (TypeVariant::Text, TypeVariant::Text) => true,
            (TypeVariant::Data, TypeVariant::Data) => true,
            (TypeVariant::Enum(es1), TypeVariant::Enum(es2)) => es1 == es2,
            (TypeVariant::Struct(rbs1), TypeVariant::Struct(rbs2)) => {
                // Ignore any type parameters. The original intent was that
                // we would additionally check that the `field_types` fields
                // were equal function pointers here. However, according to
                // Miri's behavior at least, that check returns `false`
                // more than we would like it to. So we settle for being
                // a bit more accepting.
                core::ptr::eq(rbs1.generic, rbs2.generic)
            }
            (TypeVariant::List(element1), TypeVariant::List(element2)) => {
                element1.loose_equals(element2)
            }
            (TypeVariant::AnyPointer, TypeVariant::AnyPointer) => true,
            (TypeVariant::Capability, TypeVariant::Capability) => true,
            _ => false,
        }
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
/// A `Type` unfolded one level. Suitable for pattern matching. Can be trivially
/// converted to `Type` via the `From`/`Into` traits.
pub enum TypeVariant {
    Void,
    Bool,
    Int8,
    Int16,
    Int32,
    Int64,
    UInt8,
    UInt16,
    UInt32,
    UInt64,
    Float32,
    Float64,
    Text,
    Data,
    Struct(RawBrandedStructSchema),
    AnyPointer,
    Capability,
    Enum(RawEnumSchema),
    List(Type),
}

impl From<TypeVariant> for Type {
    fn from(tv: TypeVariant) -> Type {
        match tv {
            TypeVariant::Void => Type::new_base(BaseType::Void),
            TypeVariant::Bool => Type::new_base(BaseType::Bool),
            TypeVariant::Int8 => Type::new_base(BaseType::Int8),
            TypeVariant::Int16 => Type::new_base(BaseType::Int16),
            TypeVariant::Int32 => Type::new_base(BaseType::Int32),
            TypeVariant::Int64 => Type::new_base(BaseType::Int64),
            TypeVariant::UInt8 => Type::new_base(BaseType::UInt8),
            TypeVariant::UInt16 => Type::new_base(BaseType::UInt16),
            TypeVariant::UInt32 => Type::new_base(BaseType::UInt32),
            TypeVariant::UInt64 => Type::new_base(BaseType::UInt64),
            TypeVariant::Float32 => Type::new_base(BaseType::Float32),
            TypeVariant::Float64 => Type::new_base(BaseType::Float64),
            TypeVariant::Text => Type::new_base(BaseType::Text),
            TypeVariant::Data => Type::new_base(BaseType::Data),
            TypeVariant::Struct(rbs) => Type::new_base(BaseType::Struct(rbs)),
            TypeVariant::AnyPointer => Type::new_base(BaseType::AnyPointer),
            TypeVariant::Capability => Type::new_base(BaseType::Capability),
            TypeVariant::Enum(es) => Type::new_base(BaseType::Enum(es)),
            TypeVariant::List(list) => Type::list_of(list),
        }
    }
}

/// A Cap'n Proto type, excluding `List`.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
enum BaseType {
    Void,
    Bool,
    Int8,
    Int16,
    Int32,
    Int64,
    UInt8,
    UInt16,
    UInt32,
    UInt64,
    Float32,
    Float64,
    Text,
    Data,
    Struct(RawBrandedStructSchema),
    AnyPointer,
    Capability,
    Enum(RawEnumSchema),
}

macro_rules! primitive_introspect(
    ($t:ty, $v:ident) => (
        impl Introspect for $t {
            fn introspect() -> Type { Type::new_base(BaseType::$v) }
        }
    )
);

primitive_introspect!((), Void);
primitive_introspect!(bool, Bool);
primitive_introspect!(i8, Int8);
primitive_introspect!(i16, Int16);
primitive_introspect!(i32, Int32);
primitive_introspect!(i64, Int64);
primitive_introspect!(u8, UInt8);
primitive_introspect!(u16, UInt16);
primitive_introspect!(u32, UInt32);
primitive_introspect!(u64, UInt64);
primitive_introspect!(f32, Float32);
primitive_introspect!(f64, Float64);

/// Type information that gets included in the generated code for every
/// user-defined Cap'n Proto struct.
#[derive(Copy, Clone)]
pub struct RawStructSchema {
    /// The Node (as defined in schema.capnp), as a single segment message.
    pub(crate) arena: &'static crate::private::arena::GeneratedCodeArena,

    /// Indices (not ordinals) of fields that don't have a discriminant value.
    pub(crate) nonunion_members: &'static [u16],

    /// Map from discriminant value to field index.
    pub(crate) members_by_discriminant: &'static [u16],

    /// Indices of fields, sorted by their respective names.
    pub(crate) members_by_name: &'static [u16],

    /// Map from field index to the ids of the `type` newtypes the field was
    /// declared with, nearest first. Empty (the default) when the struct has
    /// no newtype fields, or was generated by an older code generator.
    pub(crate) field_newtypes: &'static [&'static [u64]],

    /// For a group that is a use site of a group or union `type` newtype:
    /// the ids of the newtypes it was declared with, nearest first. Empty
    /// for every other struct or group.
    pub(crate) newtype_ids: &'static [u64],

    /// For such a use site: where each of the newtype's members lives in
    /// the parent's data, in the order the newtype declares them. This is
    /// the table the generated `as_any()` hands to `AnyReader::new`.
    pub(crate) any_offsets: &'static [u32],

    /// For a use site of a union newtype: where its discriminant lives.
    pub(crate) any_discriminant_offset: u32,
}

impl RawStructSchema {
    /// Constructs a new `RawStructSchema`.
    pub const fn new(
        arena: &'static crate::private::arena::GeneratedCodeArena,
        nonunion_members: &'static [u16],
        members_by_discriminant: &'static [u16],
        members_by_name: &'static [u16],
    ) -> Self {
        Self {
            arena,
            nonunion_members,
            members_by_discriminant,
            members_by_name,
            field_newtypes: &[],
            newtype_ids: &[],
            any_offsets: &[],
            any_discriminant_offset: 0,
        }
    }

    /// Sets the per-field newtype ids; see [`crate::schema::Field::get_newtype_ids`].
    pub const fn with_field_newtypes(mut self, field_newtypes: &'static [&'static [u64]]) -> Self {
        self.field_newtypes = field_newtypes;
        self
    }

    /// Marks this group as a use site of a group or union newtype, so the
    /// dynamic API can `downcast` it to the newtype's `AnyReader` /
    /// `AnyBuilder`. See [`crate::traits::AnyReader`].
    pub const fn with_any_layout(
        mut self,
        newtype_ids: &'static [u64],
        offsets: &'static [u32],
        discriminant_offset: u32,
    ) -> Self {
        self.newtype_ids = newtype_ids;
        self.any_offsets = offsets;
        self.any_discriminant_offset = discriminant_offset;
        self
    }
}

/// A RawStructSchema with branding information, i.e. resolution of type parameters.
/// To use one of this, you will usually want to convert it to a `schema::StructSchema`,
/// which can be done via `into()`.
#[derive(Copy, Clone)]
pub struct RawBrandedStructSchema {
    /// The unbranded base schema.
    pub generic: &'static RawStructSchema,

    /// Map from field index (not ordinal) to Type.
    pub field_types: fn(u16) -> Type,

    /// Map from (maybe field index, annotation index) to the Type
    /// of the value held by that annotation.
    pub annotation_types: fn(Option<u16>, u32) -> Type,

    /// Used to compare schemas at runtime - the TypeId of the Owned struct that
    /// this schema describes, including its branding.
    pub type_id: ::core::any::TypeId,
}

impl ::core::cmp::PartialEq for RawBrandedStructSchema {
    fn eq(&self, other: &Self) -> bool {
        self.type_id == other.type_id
    }
}
impl ::core::cmp::Eq for RawBrandedStructSchema {}
impl ::core::hash::Hash for RawBrandedStructSchema {
    fn hash<H: ::core::hash::Hasher>(&self, state: &mut H) {
        self.type_id.hash(state);
    }
}

impl core::fmt::Debug for RawBrandedStructSchema {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::result::Result<(), core::fmt::Error> {
        write!(
            f,
            "RawBrandedStructSchema({:?}, {:?})",
            self.generic as *const _, self.field_types as *const fn(u16) -> Type
        )
    }
}

impl From<StructSchema> for RawBrandedStructSchema {
    fn from(value: StructSchema) -> Self {
        value.raw
    }
}

/// Type information that gets included in the generated code for every
/// user-defined Cap'n Proto enum.
///
/// To use one of these, you will usually want to convert it to a `schema::EnumSchema`,
/// which can be done via `into()`.
#[derive(Clone, Copy)]
pub struct RawEnumSchema {
    /// The Node (as defined in schema.capnp), as a single segment message.
    pub(crate) arena: &'static crate::private::arena::GeneratedCodeArena,

    /// Map from (maybe enumerant index, annotation index) to the Type
    /// of the value held by that annotation.
    pub(crate) annotation_types: fn(Option<u16>, u32) -> Type,
}

impl core::cmp::PartialEq for RawEnumSchema {
    fn eq(&self, other: &Self) -> bool {
        ::core::ptr::eq(self.arena, other.arena)
    }
}

impl core::cmp::Eq for RawEnumSchema {}
impl core::hash::Hash for RawEnumSchema {
    fn hash<H: ::core::hash::Hasher>(&self, state: &mut H) {
        (self.arena as *const crate::private::arena::GeneratedCodeArena).hash(state);
    }
}

impl core::fmt::Debug for RawEnumSchema {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::result::Result<(), core::fmt::Error> {
        write!(f, "RawEnumSchema({:?})", self.arena as *const _)
    }
}

impl RawEnumSchema {
    /// Constructs a new `RawEnumSchema`.
    pub const fn new(
        arena: &'static crate::private::arena::GeneratedCodeArena,
        annotation_types: fn(Option<u16>, u32) -> Type,
    ) -> Self {
        Self {
            arena,
            annotation_types,
        }
    }
}

impl From<EnumSchema> for RawEnumSchema {
    fn from(value: EnumSchema) -> Self {
        value.raw
    }
}

/**
Function intended to be called by generated `get_field_types()` methods.
Defined here so that we can use inline format args syntax, which did
not exist before Rust edition 2021. Not intended to be called directly by
end users.
 */
pub fn panic_invalid_field_index(index: u16) -> ! {
    panic!("invalid field index {index}")
}

/**
Function intended to be called by generated `get_annotation_types()` methods.
Defined here so that we can use inline format args syntax, which did
not exist before Rust edition 2021. Not intended to be called directly by
end users.
 */
pub fn panic_invalid_annotation_indices(child_index: Option<u16>, index: u32) -> ! {
    panic!("invalid annotation indices ({child_index:?}, {index})")
}