Skip to main content

capnp/
traits.rs

1// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
2// Licensed under the MIT License:
3//
4// Permission is hereby granted, free of charge, to any person obtaining a copy
5// of this software and associated documentation files (the "Software"), to deal
6// in the Software without restriction, including without limitation the rights
7// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8// copies of the Software, and to permit persons to whom the Software is
9// furnished to do so, subject to the following conditions:
10//
11// The above copyright notice and this permission notice shall be included in
12// all copies or substantial portions of the Software.
13//
14// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20// THE SOFTWARE.
21
22use crate::private::layout::CapTable;
23use crate::private::layout::{
24    ListReader, PointerBuilder, PointerReader, StructBuilder, StructReader, StructSize,
25};
26use crate::Result;
27
28use core::marker::PhantomData;
29
30pub trait HasStructSize {
31    const STRUCT_SIZE: StructSize;
32}
33
34/// Trait for all types that can be converted to a low-level `StructReader`.
35pub trait IntoInternalStructReader<'a> {
36    fn into_internal_struct_reader(self) -> StructReader<'a>;
37}
38
39/// Trait for all types that can be converted to a low-level `StructBuilder`.
40pub trait IntoInternalStructBuilder<'a> {
41    fn into_internal_struct_builder(self) -> StructBuilder<'a>;
42}
43
44/// The reader every group or union `type` newtype generates: one type that
45/// reads the newtype at any of its use sites.
46///
47/// Inlining lets each struct place a newtype's members wherever they fit,
48/// so a use site is described by the parent's raw reader plus an offset
49/// table saying where each member lives. Typed code gets one from a use
50/// site's `as_any()`. Dynamic code gets one with
51/// `dynamic_value::Reader::downcast::<vec3::AnyReader>()` on the group,
52/// which reads the same table from the schema.
53pub trait AnyReader<'a>: Sized {
54    /// The id of the `type` declaration this reads (not of an alias of it).
55    const TYPE_ID: u64;
56
57    /// How many entries a use site's offset table has.
58    const LEAF_COUNT: usize;
59
60    /// Builds the reader over one use site. `discriminant_offset` is used
61    /// only by union newtypes. Generated code and `downcast` call this;
62    /// other code normally doesn't.
63    fn from_use_site(
64        reader: StructReader<'a>,
65        offsets: &'a [u32],
66        discriminant_offset: u32,
67    ) -> Self;
68}
69
70/// The builder counterpart of [`AnyReader`].
71pub trait AnyBuilder<'a>: Sized {
72    /// The id of the `type` declaration this writes (not of an alias of it).
73    const TYPE_ID: u64;
74
75    /// How many entries a use site's offset table has.
76    const LEAF_COUNT: usize;
77
78    /// Builds the builder over one use site; see
79    /// [`AnyReader::from_use_site`].
80    fn from_use_site(
81        builder: StructBuilder<'a>,
82        offsets: &'a [u32],
83        discriminant_offset: u32,
84    ) -> Self;
85}
86
87/// Trait for all types that can be converted to a low-level `ListReader`.
88pub trait IntoInternalListReader<'a> {
89    fn into_internal_list_reader(self) -> ListReader<'a>;
90}
91
92pub trait FromPointerReader<'a>: Sized {
93    fn get_from_pointer(
94        reader: &PointerReader<'a>,
95        default: Option<&'a [crate::Word]>,
96    ) -> Result<Self>;
97}
98
99/// A trait to encode relationships between readers and builders.
100///
101/// If `Foo` is a Cap'n Proto struct and `Bar` is a Rust-native struct, then
102/// `foo::Reader<'a>` is to `foo::Owned` as `&'a Bar` is to `Bar`, and
103/// `foo::Builder<'a>` is to `foo::Owned` as `&'a mut Bar` is to `Bar`.
104/// The relationship is formalized by an `impl capnp::traits::Owned for foo::Owned`.
105/// Because Cap'n Proto struct layout differs from Rust struct layout, a `foo::Owned` value
106/// cannot be used for anything interesting on its own; the `foo::Owned` type is useful
107/// nonetheless as a type parameter, e.g. for a generic container that owns a Cap'n Proto
108/// message of type `T: capnp::traits::Owned`.
109pub trait Owned: crate::introspect::Introspect {
110    type Reader<'a>: FromPointerReader<'a> + SetterInput<Self>;
111    type Builder<'a>: FromPointerBuilder<'a>;
112}
113
114pub trait OwnedStruct: crate::introspect::Introspect {
115    type Reader<'a>: From<StructReader<'a>> + SetterInput<Self> + IntoInternalStructReader<'a>;
116    type Builder<'a>: From<StructBuilder<'a>> + HasStructSize;
117}
118
119pub trait Pipelined {
120    type Pipeline;
121}
122
123pub trait FromPointerBuilder<'a>: Sized {
124    fn init_pointer(builder: PointerBuilder<'a>, length: u32) -> Self;
125    fn get_from_pointer(
126        builder: PointerBuilder<'a>,
127        default: Option<&'a [crate::Word]>,
128    ) -> Result<Self>;
129}
130
131/// A trait marking types that can be passed as inputs to setter methods.
132/// `Receiver` is intended to be an `Owned`, representing the destination type.
133///
134/// This trait allows setters to support multiple types of input. For example,
135/// a text field setter accepts values of type `&str` and of type `text::Reader`.
136pub trait SetterInput<Receiver: ?Sized> {
137    /// Copies the values from `input` into `builder`, where `builder`
138    /// represents the backing memory of a `<Receiver as Owned>::Builder`.
139    ///
140    /// End user code should never need to call this method directly.
141    fn set_pointer_builder(
142        builder: PointerBuilder<'_>,
143        input: Self,
144        canonicalize: bool,
145    ) -> Result<()>;
146}
147
148/// A trait for types that can be "imbued" with capabilities.
149///
150/// A newly-read message from the network might contain capability pointers
151/// but until the message has been imbued with the actual capabilities,
152/// those pointers will not be usable.
153pub trait Imbue<'a> {
154    fn imbue(&mut self, caps: &'a CapTable);
155}
156
157/// Like `Imbue`, but the capability table is mutable.
158pub trait ImbueMut<'a> {
159    fn imbue_mut(&mut self, caps: &'a mut CapTable);
160}
161
162/// User-defined Cap'n Proto structs and interfaces are statically assigned a
163/// 64-bit type ID. This trait allows the ID to be retrieved.
164pub trait HasTypeId {
165    const TYPE_ID: u64;
166}
167
168pub trait IndexMove<I, T> {
169    fn index_move(&self, index: I) -> T;
170}
171
172pub struct ListIter<T, U> {
173    marker: PhantomData<U>,
174    list: T,
175    index: u32,
176    size: u32,
177}
178
179impl<T, U> ListIter<T, U> {
180    pub fn new(list: T, size: u32) -> Self {
181        Self {
182            list,
183            index: 0,
184            size,
185            marker: PhantomData,
186        }
187    }
188}
189
190impl<U, T: IndexMove<u32, U>> ::core::iter::Iterator for ListIter<T, U> {
191    type Item = U;
192    fn next(&mut self) -> ::core::option::Option<U> {
193        if self.index < self.size {
194            let result = self.list.index_move(self.index);
195            self.index += 1;
196            Some(result)
197        } else {
198            None
199        }
200    }
201
202    fn size_hint(&self) -> (usize, Option<usize>) {
203        let remaining = self.size as usize - self.index as usize;
204        (remaining, Some(remaining))
205    }
206
207    fn nth(&mut self, p: usize) -> Option<U> {
208        let Some(p) = p.try_into().ok() else {
209            self.index = self.size;
210            return None;
211        };
212        let Some(nth_index) = self.index.checked_add(p) else {
213            self.index = self.size;
214            return None;
215        };
216        if nth_index < self.size {
217            self.index = nth_index;
218            let result = self.list.index_move(self.index);
219            self.index += 1;
220            Some(result)
221        } else {
222            self.index = self.size;
223            None
224        }
225    }
226}
227
228impl<U, T: IndexMove<u32, U>> ::core::iter::ExactSizeIterator for ListIter<T, U> {
229    fn len(&self) -> usize {
230        self.size as usize - self.index as usize
231    }
232}
233
234impl<U, T: IndexMove<u32, U>> ::core::iter::DoubleEndedIterator for ListIter<T, U> {
235    fn next_back(&mut self) -> ::core::option::Option<U> {
236        if self.size > self.index {
237            self.size -= 1;
238            Some(self.list.index_move(self.size))
239        } else {
240            None
241        }
242    }
243}
244
245/// Iterator for a list whose indices are of type `u16`.
246pub struct ShortListIter<T, U> {
247    marker: PhantomData<U>,
248    list: T,
249    index: u16,
250    size: u16,
251}
252
253impl<T, U> ShortListIter<T, U> {
254    pub fn new(list: T, size: u16) -> Self {
255        Self {
256            list,
257            index: 0,
258            size,
259            marker: PhantomData,
260        }
261    }
262}
263
264impl<U, T: IndexMove<u16, U>> ::core::iter::Iterator for ShortListIter<T, U> {
265    type Item = U;
266    fn next(&mut self) -> ::core::option::Option<U> {
267        if self.index < self.size {
268            let result = self.list.index_move(self.index);
269            self.index += 1;
270            Some(result)
271        } else {
272            None
273        }
274    }
275
276    fn size_hint(&self) -> (usize, Option<usize>) {
277        let remaining = self.size as usize - self.index as usize;
278        (remaining, Some(remaining))
279    }
280
281    fn nth(&mut self, p: usize) -> Option<U> {
282        let Some(p) = p.try_into().ok() else {
283            self.index = self.size;
284            return None;
285        };
286        let Some(nth_index) = self.index.checked_add(p) else {
287            self.index = self.size;
288            return None;
289        };
290        if nth_index < self.size {
291            self.index = nth_index;
292            let result = self.list.index_move(self.index);
293            self.index += 1;
294            Some(result)
295        } else {
296            self.index = self.size;
297            None
298        }
299    }
300}
301
302impl<U, T: IndexMove<u16, U>> ::core::iter::ExactSizeIterator for ShortListIter<T, U> {
303    fn len(&self) -> usize {
304        self.size as usize - self.index as usize
305    }
306}
307
308impl<U, T: IndexMove<u16, U>> ::core::iter::DoubleEndedIterator for ShortListIter<T, U> {
309    fn next_back(&mut self) -> ::core::option::Option<U> {
310        if self.size > self.index {
311            self.size -= 1;
312            Some(self.list.index_move(self.size))
313        } else {
314            None
315        }
316    }
317}