Skip to main content

capnp/
lib.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
22//! # Cap'n Proto Runtime Library
23//!
24//! This crate contains basic facilities for reading and writing
25//! [Cap'n Proto](https://capnproto.org) messages in Rust. It is intended to
26//! be used in conjunction with code generated by the
27//! [capnpc-rust](https://crates.io/crates/capnpc) crate.
28//!
29//! ## `type` newtypes
30//!
31//! A schema `type` declaration is a *newtype*. A scalar newtype (`type Uuid = Data`) generates a
32//! module of transparent `Reader`/`Builder`/`Owned` aliases -- wire-identical to the underlying
33//! type, preserving only the name. An inline *group* or *union* newtype
34//! (`type Vec3 = group { x @0 :Float32; ... }`, stamped into a struct at explicit `@[...]` ordinals
35//! so it shares the parent's space with no pointer indirection) generates a module containing:
36//!
37//! - **`Reader` / `Builder` traits** -- the newtype's shared interface. Each use site is a distinct
38//!   concrete type (with its offsets baked in), and all of them implement these traits, so an
39//!   `impl vec3::Reader` / `impl vec3::Builder` bound lets you write code generic over every use
40//!   site. A union newtype's `Reader` additionally has `which()`, returning a shared `Which` enum.
41//! - **`AnyReader` / `AnyBuilder`** -- a single *erased* type spanning use sites, reading field
42//!   offsets from a runtime table (built with a concrete accessor's `as_any()`). Use them where one
43//!   type must span use sites -- a `Vec`, a return type, a struct field. A per-use-site concrete
44//!   type can't do that, and neither can `&dyn` once the newtype nests another newtype or is a
45//!   union (those need associated types, which are not object-safe). The erased carriers mirror
46//!   Cap'n Proto's C++ `AnyReader`/`AnyBuilder`, keeping the two languages' generated APIs
47//!   consistent -- a primary motivation for this design.
48//!
49//! An incomplete `@[...]` mapping may leave trailing fields unmapped; an unmapped field reads its
50//! default, and setting one panics (`"... is not mapped at this use site"`) -- mirroring the C++
51//! codegen's behavior.
52
53#![cfg_attr(not(test), deny(clippy::cast_possible_truncation))]
54#![cfg_attr(not(test), deny(clippy::cast_possible_wrap))]
55#![cfg_attr(feature = "rpc_try", feature(try_trait_v2))]
56#![cfg_attr(not(feature = "std"), no_std)]
57
58#[cfg(feature = "alloc")]
59#[macro_use]
60extern crate alloc;
61
62/// Code generated from
63/// [schema.capnp](https://github.com/capnproto/capnproto/blob/master/c%2B%2B/src/capnp/schema.capnp).
64pub mod schema_capnp;
65
66pub mod any_pointer;
67pub mod any_pointer_list;
68pub mod capability;
69pub mod capability_list;
70pub mod constant;
71pub mod data;
72pub mod data_list;
73pub mod dynamic_list;
74pub mod dynamic_struct;
75pub mod dynamic_value;
76pub mod enum_list;
77pub mod introspect;
78pub mod io;
79pub mod list_list;
80pub mod message;
81pub mod primitive_list;
82pub mod private;
83pub mod raw;
84pub mod schema;
85pub mod serialize;
86pub mod serialize_packed;
87pub(crate) mod stringify;
88pub mod struct_list;
89pub mod text;
90pub mod text_list;
91pub mod traits;
92
93/// Macro for importing Rust code that has been generated by `capnpc::CompilerCommand`.
94///
95/// For example:
96/// ```ignore
97/// generated_code!(pub mod foo_capnp);
98/// ```
99/// pulls in the generated code for `foo.capnp` into a module named `foo_capnp`.
100/// It expects to find the generated code in a file `$OUT_DIR/foo_capnp.rs`,
101/// where `OUT_DIR` is Cargo's standard environment variable giving the
102/// location of the output of `build.rs`.
103///
104/// If the generated code lives in a nonstandard location—perhaps in a subdirectory
105/// of `OUT_DIR`—you can specify its path as a second argument:
106/// ```ignore
107/// generated_code!(pub mod foo_capnp, "some_directory/foo_capnp.rs");
108/// ```
109#[macro_export]
110macro_rules! generated_code {
111    ($vis:vis mod $mod_name:ident, $file_name:expr_2021) => {
112        $vis mod $mod_name {
113            #![allow(clippy::all)]
114            include!(concat!(env!("OUT_DIR"), "/", $file_name));
115        }
116    };
117
118    ($vis:vis mod $mod_name:ident) => {
119        $crate::generated_code!($vis mod $mod_name, concat!(stringify!($mod_name), ".rs"));
120    };
121}
122
123///
124/// 8 bytes, aligned to an 8-byte boundary.
125///
126/// Internally, capnproto-rust allocates message buffers using this type,
127/// to guarantee alignment.
128#[derive(Clone, Copy, Debug, PartialEq, Eq)]
129#[repr(C, align(8))]
130pub struct Word {
131    raw_content: [u8; 8],
132}
133
134///
135/// Constructs a word with the given bytes.
136///
137#[allow(clippy::too_many_arguments)]
138pub const fn word(b0: u8, b1: u8, b2: u8, b3: u8, b4: u8, b5: u8, b6: u8, b7: u8) -> Word {
139    Word {
140        raw_content: [b0, b1, b2, b3, b4, b5, b6, b7],
141    }
142}
143
144impl Word {
145    /// Allocates a vec of `length` words, all set to zero.
146    #[cfg(feature = "alloc")]
147    pub fn allocate_zeroed_vec(length: usize) -> alloc::vec::Vec<Self> {
148        vec![word(0, 0, 0, 0, 0, 0, 0, 0); length]
149    }
150
151    pub fn words_to_bytes(words: &[Self]) -> &[u8] {
152        unsafe { core::slice::from_raw_parts(words.as_ptr() as *const u8, words.len() * 8) }
153    }
154
155    pub fn words_to_bytes_mut(words: &mut [Self]) -> &mut [u8] {
156        unsafe { core::slice::from_raw_parts_mut(words.as_mut_ptr() as *mut u8, words.len() * 8) }
157    }
158}
159
160#[cfg(any(feature = "quickcheck", test))]
161impl quickcheck::Arbitrary for Word {
162    fn arbitrary(g: &mut quickcheck::Gen) -> Self {
163        crate::word(
164            quickcheck::Arbitrary::arbitrary(g),
165            quickcheck::Arbitrary::arbitrary(g),
166            quickcheck::Arbitrary::arbitrary(g),
167            quickcheck::Arbitrary::arbitrary(g),
168            quickcheck::Arbitrary::arbitrary(g),
169            quickcheck::Arbitrary::arbitrary(g),
170            quickcheck::Arbitrary::arbitrary(g),
171            quickcheck::Arbitrary::arbitrary(g),
172        )
173    }
174}
175
176/// Size of a message. Every generated struct has a method `.total_size()` that returns this.
177#[derive(Clone, Copy, Debug, PartialEq)]
178pub struct MessageSize {
179    pub word_count: u64,
180
181    /// Size of the capability table.
182    pub cap_count: u32,
183}
184
185impl core::ops::AddAssign for MessageSize {
186    fn add_assign(&mut self, rhs: Self) {
187        self.word_count += rhs.word_count;
188        self.cap_count += rhs.cap_count;
189    }
190}
191
192/// An enum value or union discriminant that was not found among those defined in a schema.
193#[derive(PartialEq, Eq, Clone, Copy, Debug)]
194pub struct NotInSchema(pub u16);
195
196impl ::core::fmt::Display for NotInSchema {
197    fn fmt(
198        &self,
199        fmt: &mut ::core::fmt::Formatter,
200    ) -> ::core::result::Result<(), ::core::fmt::Error> {
201        write!(
202            fmt,
203            "Enum value or union discriminant {} was not present in the schema.",
204            self.0
205        )
206    }
207}
208
209impl ::core::error::Error for NotInSchema {
210    fn description(&self) -> &str {
211        "Enum value or union discriminant was not present in schema."
212    }
213}
214
215/// Because messages are lazily validated, the return type of any method that reads a pointer field
216/// must be wrapped in a Result.
217pub type Result<T> = ::core::result::Result<T, Error>;
218
219/// Arbitrary extra detail attached to an [`Error`].
220///
221/// Each detail has a unique 64-bit `id` (typically generated with `capnp id`) and a byte `data`
222/// payload whose encoding is defined by the application.
223#[cfg(feature = "alloc")]
224#[derive(Debug, Clone, PartialEq, Eq)]
225pub struct ErrorDetail {
226    pub id: u64,
227    pub data: alloc::vec::Vec<u8>,
228}
229
230/// Describes an arbitrary error that prevented an operation from completing.
231#[derive(Debug, Clone)]
232#[non_exhaustive]
233pub struct Error {
234    /// The general kind of the error. Code that decides how to respond to an error
235    /// should read only this field in making its decision.
236    pub kind: ErrorKind,
237
238    #[cfg(feature = "alloc")]
239    extra: alloc::string::String,
240    // Keep the details vector out of line so errors without details pay for only a pointer.
241    #[cfg(feature = "alloc")]
242    #[allow(clippy::box_collection)]
243    details: Option<alloc::boxed::Box<alloc::vec::Vec<ErrorDetail>>>,
244}
245
246/// The general nature of an error. The purpose of this enum is not to describe the error itself,
247/// but rather to describe how the client might want to respond to the error.
248#[derive(Debug, Clone, Copy, PartialEq, Eq)]
249#[non_exhaustive]
250pub enum ErrorKind {
251    /// Something went wrong
252    Failed,
253
254    /// The call failed because of a temporary lack of resources. This could be space resources
255    /// (out of memory, out of disk space) or time resources (request queue overflow, operation
256    /// timed out).
257    ///
258    /// The operation might work if tried again, but it should NOT be repeated immediately as this
259    /// may simply exacerbate the problem.
260    Overloaded,
261
262    /// The call required communication over a connection that has been lost. The caller will need
263    /// to re-establish connections and try again.
264    Disconnected,
265
266    /// The requested method is not implemented. The caller may wish to revert to a fallback
267    /// approach based on other methods.
268    Unimplemented,
269
270    /// Buffer is not large enough
271    BufferNotLargeEnough,
272
273    /// Cannot create a canonical message with a capability
274    CannotCreateACanonicalMessageWithACapability,
275
276    /// Cannot set AnyPointer field to a primitive value
277    CannotSetAnyPointerFieldToAPrimitiveValue,
278
279    /// Don't know how to handle non-STRUCT inline composite.
280    CantHandleNonStructInlineComposite,
281
282    /// Empty buffer
283    EmptyBuffer,
284
285    /// Empty slice
286    EmptySlice,
287
288    /// Enum value or union discriminant {} was not present in schema
289    EnumValueOrUnionDiscriminantNotPresent(NotInSchema),
290
291    /// Called get_writable_{data|text}_pointer() but existing list pointer is not byte-sized.
292    ExistingListPointerIsNotByteSized,
293
294    /// Existing list value is incompatible with expected type.
295    ExistingListValueIsIncompatibleWithExpectedType,
296
297    /// Called get_writable_{data|text|list|struct_list}_pointer() but existing pointer is not a list.
298    ExistingPointerIsNotAList,
299
300    /// Expected a list or blob.
301    ExpectedAListOrBlob,
302
303    /// Expected a pointer list, but got a list of data-only structs
304    ExpectedAPointerListButGotAListOfDataOnlyStructs,
305
306    /// Expected a primitive list, but got a list of pointer-only structs
307    ExpectedAPrimitiveListButGotAListOfPointerOnlyStructs,
308
309    /// failed to fill the whole buffer
310    FailedToFillTheWholeBuffer,
311
312    /// field and default mismatch
313    FieldAndDefaultMismatch,
314
315    /// field not found
316    FieldNotFound,
317
318    /// Found bit list where struct list was expected; upgrading boolean lists to struct lists is no longer supported
319    FoundBitListWhereStructListWasExpected,
320
321    /// Found struct list where bit list was expected.
322    FoundStructListWhereBitListWasExpected,
323
324    /// Cannot represent 4 byte length as `usize`. This may indicate that you are running on 8 or 16 bit platform or message is too large.
325    FourByteLengthTooBigForUSize,
326
327    /// Cannot represent 4 byte segment length as usize. This may indicate that you are running on 8 or 16 bit platform or segment is too large
328    FourByteSegmentLengthTooBigForUSize,
329
330    /// group field but type is not Struct
331    GroupFieldButTypeIsNotStruct,
332
333    /// init() is only valid for struct and AnyPointer fields
334    InitIsOnlyValidForStructAndAnyPointerFields,
335
336    /// initn() is only valid for list, text, or data fields
337    InitnIsOnlyValidForListTextOrDataFields,
338
339    /// InlineComposite list with non-STRUCT elements not supported.
340    InlineCompositeListWithNonStructElementsNotSupported,
341
342    /// InlineComposite list's elements overrun its word count.
343    InlineCompositeListsElementsOverrunItsWordCount,
344
345    /// InlineComposite lists of non-STRUCT type are not supported.
346    InlineCompositeListsOfNonStructTypeAreNotSupported,
347
348    /// Too many or too few segments {segment_count}
349    InvalidNumberOfSegments(usize),
350
351    /// Invalid segment id {id}
352    InvalidSegmentId(u32),
353
354    /// List(AnyPointer) not supported.
355    ListAnyPointerNotSupported,
356
357    /// List(Capability) not supported
358    ListCapabilityNotSupported,
359
360    /// Malformed double-far pointer.
361    MalformedDoubleFarPointer,
362
363    /// Message contains invalid capability pointer.
364    MessageContainsInvalidCapabilityPointer,
365
366    /// Message contains list pointer of non-bytes where data was expected.
367    MessageContainsListPointerOfNonBytesWhereDataWasExpected,
368
369    /// Message contains list pointer of non-bytes where text was expected.
370    MessageContainsListPointerOfNonBytesWhereTextWasExpected,
371
372    /// Message contains list with incompatible element type.
373    MessageContainsListWithIncompatibleElementType,
374
375    /// Message contains non-capability pointer where capability pointer was expected.
376    MessageContainsNonCapabilityPointerWhereCapabilityPointerWasExpected,
377
378    /// Message contains non-struct pointer where struct pointer was expected.
379    MessageContainsNonStructPointerWhereStructPointerWasExpected,
380
381    /// Message contains non-list pointer where data was expected.
382    MessageContainsNonListPointerWhereDataWasExpected,
383
384    /// Message contains non-list pointer where list pointer was expected
385    MessageContainsNonListPointerWhereListPointerWasExpected,
386
387    /// Message contains non-list pointer where text was expected.
388    MessageContainsNonListPointerWhereTextWasExpected,
389
390    /// Message contains null capability pointer.
391    MessageContainsNullCapabilityPointer,
392
393    /// Message contains out-of-bounds pointer,
394    MessageContainsOutOfBoundsPointer,
395
396    /// Message contains text that is not NUL-terminated
397    MessageContainsTextThatIsNotNULTerminated,
398
399    /// Message ends prematurely. Header claimed {header} words, but message only has {body} words,
400    MessageEndsPrematurely(usize, usize),
401
402    /// Message is too deeply nested.
403    MessageIsTooDeeplyNested,
404
405    /// Message is too deeply-nested or contains cycles.
406    MessageIsTooDeeplyNestedOrContainsCycles,
407
408    /// Message was not aligned by 8 bytes boundary. Either ensure that message is properly aligned or compile `capnp` crate with \"unaligned\" feature enabled.
409    MessageNotAlignedBy8BytesBoundary,
410
411    /// Message's size cannot be represented in usize
412    MessageSizeOverflow,
413
414    /// Message is too large
415    MessageTooLarge(usize),
416
417    /// Nesting limit exceeded
418    NestingLimitExceeded,
419
420    /// Not a struct
421    NotAStruct,
422
423    /// Only one of the section pointers is pointing to ourself
424    OnlyOneOfTheSectionPointersIsPointingToOurself,
425
426    /// Packed input did not end cleanly on a segment boundary.
427    PackedInputDidNotEndCleanlyOnASegmentBoundary,
428
429    /// Premature end of file
430    PrematureEndOfFile,
431
432    /// Premature end of packed input.
433    PrematureEndOfPackedInput,
434
435    /// Read limit exceeded
436    ReadLimitExceeded,
437
438    /// setting dynamic capabilities is unsupported
439    SettingDynamicCapabilitiesIsUnsupported,
440
441    /// Struct reader had bitwidth other than 1
442    StructReaderHadBitwidthOtherThan1,
443
444    /// Text blob missing NUL terminator.
445    TextBlobMissingNULTerminator,
446
447    /// Text contains non-utf8 data
448    TextContainsNonUtf8Data(core::str::Utf8Error),
449
450    /// Tried to read from null arena
451    TriedToReadFromNullArena,
452
453    /// type mismatch
454    TypeMismatch,
455
456    /// Detected unaligned segment. You must either ensure all of your segments are 8-byte aligned,
457    /// or you must enable the "unaligned" feature in the capnp crate
458    UnalignedSegment,
459
460    /// Unexpected far pointer
461    UnexpectedFarPointer,
462
463    /// Unknown pointer type.
464    UnknownPointerType,
465}
466
467impl Error {
468    #[cfg(feature = "alloc")]
469    pub fn new(kind: ErrorKind, extra: alloc::string::String) -> Self {
470        Self {
471            kind,
472            extra,
473            details: None,
474        }
475    }
476
477    pub fn from_kind(kind: ErrorKind) -> Self {
478        Self {
479            kind,
480            #[cfg(feature = "alloc")]
481            extra: alloc::string::String::new(),
482            #[cfg(feature = "alloc")]
483            details: None,
484        }
485    }
486
487    #[cfg(feature = "alloc")]
488    pub fn failed(description: alloc::string::String) -> Self {
489        Self::new(ErrorKind::Failed, description)
490    }
491
492    #[cfg(feature = "alloc")]
493    pub fn overloaded(description: alloc::string::String) -> Self {
494        Self::new(ErrorKind::Overloaded, description)
495    }
496
497    #[cfg(feature = "alloc")]
498    pub fn disconnected(description: alloc::string::String) -> Self {
499        Self::new(ErrorKind::Disconnected, description)
500    }
501
502    #[cfg(feature = "alloc")]
503    pub fn unimplemented(description: alloc::string::String) -> Self {
504        Self::new(ErrorKind::Unimplemented, description)
505    }
506
507    /// Returns any extra human-readable context attached to this error, or `""` if none.
508    pub fn extra(&self) -> &str {
509        #[cfg(feature = "alloc")]
510        {
511            &self.extra
512        }
513        #[cfg(not(feature = "alloc"))]
514        {
515            ""
516        }
517    }
518
519    /// Appends formatted text to this error's `extra` context. Does nothing if the `"alloc"`
520    /// feature is not enabled. This is intended to be used with the `write!()` macro from `core`.
521    pub fn write_fmt(&mut self, fmt: core::fmt::Arguments<'_>) {
522        #[cfg(feature = "alloc")]
523        {
524            use core::fmt::Write;
525            let _ = self.extra.write_fmt(fmt);
526        }
527        #[cfg(not(feature = "alloc"))]
528        {
529            let _ = fmt;
530        }
531    }
532
533    /// Returns the detail payload associated with `detail_id`, if present.
534    ///
535    /// Details can be attached to an error returned by an RPC server method and retrieved on the
536    /// client after awaiting the call. Each detail type should use a unique 64-bit ID (typically
537    /// generated with `capnp id`).
538    #[cfg(feature = "alloc")]
539    pub fn get_detail(&self, detail_id: u64) -> Option<&[u8]> {
540        let details = self.details.as_ref()?;
541        details
542            .iter()
543            .find(|detail| detail.id == detail_id)
544            .map(|detail| detail.data.as_slice())
545    }
546
547    /// Returns all [`ErrorDetail`] entries attached to this error.
548    #[cfg(feature = "alloc")]
549    pub fn get_details(&self) -> &[ErrorDetail] {
550        match &self.details {
551            Some(details) => details.as_slice(),
552            None => &[],
553        }
554    }
555
556    /// Attaches a detail payload keyed by `detail_id` to this error, replacing any
557    /// existing payload with the same `detail_id`.
558    ///
559    /// Each detail type should use a unique 64-bit ID (typically generated with `capnp id`).
560    ///
561    /// ```
562    /// const VALIDATION_ERROR: u64 = 0x9935_c2b4_7d94_809c;
563    /// let mut err = capnp::Error::failed("invalid".into());
564    /// err.set_detail(VALIDATION_ERROR, b"field x must be positive".to_vec());
565    /// assert_eq!(err.get_detail(VALIDATION_ERROR), Some(&b"field x must be positive"[..]));
566    /// ```
567    #[cfg(feature = "alloc")]
568    pub fn set_detail(&mut self, detail_id: u64, data: alloc::vec::Vec<u8>) {
569        let details = self.details.get_or_insert_with(Default::default);
570        if let Some(existing) = details.iter_mut().find(|detail| detail.id == detail_id) {
571            existing.data = data;
572        } else {
573            details.push(ErrorDetail {
574                id: detail_id,
575                data,
576            });
577        }
578    }
579
580    /// Removes and returns the detail payload associated with `detail_id`, if present.
581    #[cfg(feature = "alloc")]
582    pub fn release_detail(&mut self, detail_id: u64) -> Option<alloc::vec::Vec<u8>> {
583        let details = self.details.as_mut()?;
584        let idx = details.iter().position(|detail| detail.id == detail_id)?;
585        let detail = details.remove(idx);
586        if details.is_empty() {
587            self.details = None;
588        }
589        Some(detail.data)
590    }
591}
592
593#[cfg(feature = "std")]
594impl core::convert::From<::std::io::Error> for Error {
595    fn from(err: ::std::io::Error) -> Self {
596        use std::io;
597        let kind = match err.kind() {
598            io::ErrorKind::TimedOut => ErrorKind::Overloaded,
599            io::ErrorKind::BrokenPipe
600            | io::ErrorKind::ConnectionRefused
601            | io::ErrorKind::ConnectionReset
602            | io::ErrorKind::ConnectionAborted
603            | io::ErrorKind::NotConnected => ErrorKind::Disconnected,
604            io::ErrorKind::UnexpectedEof => ErrorKind::PrematureEndOfFile,
605            _ => ErrorKind::Failed,
606        };
607        #[cfg(feature = "alloc")]
608        return Self::new(kind, format!("{err}"));
609        #[cfg(not(feature = "alloc"))]
610        return Self::from_kind(kind);
611    }
612}
613
614#[cfg(feature = "embedded-io")]
615impl From<embedded_io::ErrorKind> for ErrorKind {
616    fn from(value: embedded_io::ErrorKind) -> Self {
617        match value {
618            embedded_io::ErrorKind::Other => Self::Failed,
619            embedded_io::ErrorKind::NotFound => Self::Failed,
620            embedded_io::ErrorKind::PermissionDenied => Self::Failed,
621            embedded_io::ErrorKind::ConnectionRefused => Self::Failed,
622            embedded_io::ErrorKind::ConnectionReset => Self::Failed,
623            embedded_io::ErrorKind::ConnectionAborted => Self::Failed,
624            embedded_io::ErrorKind::NotConnected => Self::Failed,
625            embedded_io::ErrorKind::AddrInUse => Self::Failed,
626            embedded_io::ErrorKind::AddrNotAvailable => Self::Failed,
627            embedded_io::ErrorKind::BrokenPipe => Self::Failed,
628            embedded_io::ErrorKind::AlreadyExists => Self::Failed,
629            embedded_io::ErrorKind::InvalidInput => Self::Failed,
630            embedded_io::ErrorKind::InvalidData => Self::Failed,
631            embedded_io::ErrorKind::TimedOut => Self::Failed,
632            embedded_io::ErrorKind::Interrupted => Self::Failed,
633            embedded_io::ErrorKind::Unsupported => Self::Failed,
634            embedded_io::ErrorKind::OutOfMemory => Self::Failed,
635            _ => Self::Failed,
636        }
637    }
638}
639
640#[cfg(feature = "alloc")]
641impl core::convert::From<alloc::string::FromUtf8Error> for Error {
642    fn from(err: alloc::string::FromUtf8Error) -> Self {
643        Self::failed(format!("{err}"))
644    }
645}
646
647impl core::convert::From<core::str::Utf8Error> for Error {
648    fn from(err: core::str::Utf8Error) -> Self {
649        Self::from_kind(ErrorKind::TextContainsNonUtf8Data(err))
650    }
651}
652
653impl core::convert::From<NotInSchema> for Error {
654    fn from(e: NotInSchema) -> Self {
655        Self::from_kind(ErrorKind::EnumValueOrUnionDiscriminantNotPresent(e))
656    }
657}
658
659impl core::fmt::Display for ErrorKind {
660    fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::result::Result<(), core::fmt::Error> {
661        match self {
662            Self::Failed => write!(fmt, "Failed"),
663            Self::Overloaded => write!(fmt, "Overloaded"),
664            Self::Disconnected => write!(fmt, "Disconnected"),
665            Self::Unimplemented => write!(fmt, "Unimplemented"),
666            Self::BufferNotLargeEnough => write!(fmt, "buffer is not large enough"),
667            Self::ExistingListPointerIsNotByteSized => write!(
668                fmt,
669                "Called get_writable_{{data|text}}_pointer() but existing list pointer is not byte-sized."
670            ),
671            Self::ExistingPointerIsNotAList => write!(
672                fmt,
673                "Called get_writable_{{data|text|list|struct_list}}_pointer() but existing pointer is not a list."
674            ),
675            Self::CannotCreateACanonicalMessageWithACapability => {
676                write!(fmt, "Cannot create a canonical message with a capability")
677            }
678            Self::FourByteLengthTooBigForUSize => write!(
679                fmt,
680                "Cannot represent 4 byte length as `usize`. This may indicate that you are running on 8 or 16 bit platform or message is too large."
681            ),
682            Self::FourByteSegmentLengthTooBigForUSize => write!(
683                fmt,
684                "Cannot represent 4 byte segment length as usize. This may indicate that you are running on 8 or 16 bit platform or segment is too large"
685            ),
686            Self::CannotSetAnyPointerFieldToAPrimitiveValue => {
687                write!(fmt, "cannot set AnyPointer field to a primitive value")
688            }
689            Self::CantHandleNonStructInlineComposite => {
690                write!(fmt, "Don't know how to handle non-STRUCT inline composite.")
691            }
692            Self::EmptyBuffer => write!(fmt, "empty buffer"),
693            Self::EmptySlice => write!(fmt, "empty slice"),
694            Self::EnumValueOrUnionDiscriminantNotPresent(val) => write!(
695                fmt,
696                "Enum value or union discriminant {val} was not present in schema"
697            ),
698            Self::ExistingListValueIsIncompatibleWithExpectedType => write!(
699                fmt,
700                "Existing list value is incompatible with expected type."
701            ),
702            Self::ExpectedAListOrBlob => write!(fmt, "Expected a list or blob."),
703            Self::ExpectedAPointerListButGotAListOfDataOnlyStructs => write!(
704                fmt,
705                "Expected a pointer list, but got a list of data-only structs"
706            ),
707            Self::ExpectedAPrimitiveListButGotAListOfPointerOnlyStructs => write!(
708                fmt,
709                "Expected a primitive list, but got a list of pointer-only structs"
710            ),
711            Self::FailedToFillTheWholeBuffer => write!(fmt, "failed to fill the whole buffer"),
712            Self::FieldAndDefaultMismatch => write!(fmt, "field and default mismatch"),
713            Self::FieldNotFound => write!(fmt, "field not found"),
714            Self::FoundBitListWhereStructListWasExpected => write!(
715                fmt,
716                "Found bit list where struct list was expected; upgrading boolean lists to struct lists is no longer supported."
717            ),
718            Self::FoundStructListWhereBitListWasExpected => {
719                write!(fmt, "Found struct list where bit list was expected.")
720            }
721            Self::GroupFieldButTypeIsNotStruct => write!(fmt, "group field but type is not Struct"),
722            Self::InitIsOnlyValidForStructAndAnyPointerFields => {
723                write!(fmt, "init() is only valid for struct and AnyPointer fields")
724            }
725            Self::InitnIsOnlyValidForListTextOrDataFields => {
726                write!(fmt, "initn() is only valid for list, text, or data fields")
727            }
728            Self::InlineCompositeListWithNonStructElementsNotSupported => write!(
729                fmt,
730                "InlineComposite list with non-STRUCT elements not supported."
731            ),
732            Self::InlineCompositeListsElementsOverrunItsWordCount => write!(
733                fmt,
734                "InlineComposite list's elements overrun its word count."
735            ),
736            Self::InlineCompositeListsOfNonStructTypeAreNotSupported => write!(
737                fmt,
738                "InlineComposite lists of non-STRUCT type are not supported."
739            ),
740            Self::InvalidNumberOfSegments(segment_count) => {
741                write!(fmt, "Too many or too few segments {segment_count}")
742            }
743            Self::InvalidSegmentId(id) => write!(fmt, "Invalid segment id {id}"),
744            Self::ListAnyPointerNotSupported => write!(fmt, "List(AnyPointer) not supported."),
745            Self::ListCapabilityNotSupported => write!(fmt, "List(Capability) not supported"),
746            Self::MalformedDoubleFarPointer => write!(fmt, "Malformed double-far pointer."),
747            Self::MessageContainsInvalidCapabilityPointer => {
748                write!(fmt, "Message contained invalid capability pointer.")
749            }
750            Self::MessageContainsListPointerOfNonBytesWhereDataWasExpected => write!(
751                fmt,
752                "Message contains list pointer of non-bytes where data was expected."
753            ),
754            Self::MessageContainsListPointerOfNonBytesWhereTextWasExpected => write!(
755                fmt,
756                "Message contains list pointer of non-bytes where text was expected."
757            ),
758            Self::MessageContainsListWithIncompatibleElementType => {
759                write!(fmt, "Message contains list with incompatible element type.")
760            }
761            Self::MessageContainsNonCapabilityPointerWhereCapabilityPointerWasExpected => write!(
762                fmt,
763                "Message contains non-capability pointer where capability pointer was expected."
764            ),
765            Self::MessageContainsNonListPointerWhereDataWasExpected => write!(
766                fmt,
767                "Message contains non-list pointer where data was expected."
768            ),
769            Self::MessageContainsNonListPointerWhereListPointerWasExpected => write!(
770                fmt,
771                "Message contains non-list pointer where list pointer was expected"
772            ),
773            Self::MessageContainsNonListPointerWhereTextWasExpected => write!(
774                fmt,
775                "Message contains non-list pointer where text was expected."
776            ),
777            Self::MessageContainsNonStructPointerWhereStructPointerWasExpected => write!(
778                fmt,
779                "Message contains non-struct pointer where struct pointer was expected."
780            ),
781            Self::MessageContainsNullCapabilityPointer => {
782                write!(fmt, "Message contains null capability pointer.")
783            }
784            Self::MessageContainsOutOfBoundsPointer => {
785                write!(fmt, "Message contains out-of-bounds pointer")
786            }
787            Self::MessageContainsTextThatIsNotNULTerminated => {
788                write!(fmt, "Message contains text that is not NUL-terminated")
789            }
790            Self::MessageEndsPrematurely(header, body) => write!(
791                fmt,
792                "Message ends prematurely. Header claimed {header} words, but message only has {body} words"
793            ),
794            Self::MessageIsTooDeeplyNested => write!(fmt, "Message is too deeply nested."),
795            Self::MessageIsTooDeeplyNestedOrContainsCycles => {
796                write!(fmt, "Message is too deeply-nested or contains cycles.")
797            }
798            Self::MessageSizeOverflow => {
799                write!(fmt, "Message's size cannot be represented in usize")
800            }
801            Self::MessageTooLarge(val) => write!(fmt, "Message is too large: {val}"),
802            Self::MessageNotAlignedBy8BytesBoundary => write!(
803                fmt,
804                "Message was not aligned by 8 bytes boundary. Either ensure that message is properly aligned or compile `capnp` crate with \"unaligned\" feature enabled."
805            ),
806            Self::NestingLimitExceeded => write!(fmt, "nesting limit exceeded"),
807            Self::NotAStruct => write!(fmt, "not a struct"),
808            Self::OnlyOneOfTheSectionPointersIsPointingToOurself => write!(
809                fmt,
810                "Only one of the section pointers is pointing to ourself"
811            ),
812            Self::PackedInputDidNotEndCleanlyOnASegmentBoundary => write!(
813                fmt,
814                "Packed input did not end cleanly on a segment boundary."
815            ),
816            Self::PrematureEndOfFile => write!(fmt, "Premature end of file"),
817            Self::PrematureEndOfPackedInput => write!(fmt, "Premature end of packed input."),
818            Self::ReadLimitExceeded => write!(fmt, "Read limit exceeded"),
819            Self::SettingDynamicCapabilitiesIsUnsupported => {
820                write!(fmt, "setting dynamic capabilities is unsupported")
821            }
822            Self::StructReaderHadBitwidthOtherThan1 => {
823                write!(fmt, "struct reader had bitwidth other than 1")
824            }
825            Self::TextBlobMissingNULTerminator => write!(fmt, "Text blob missing NUL terminator."),
826            Self::TextContainsNonUtf8Data(e) => write!(fmt, "Text contains non-utf8 data: {e}"),
827            Self::TriedToReadFromNullArena => write!(fmt, "Tried to read from null arena"),
828            Self::TypeMismatch => write!(fmt, "type mismatch"),
829            Self::UnalignedSegment => write!(
830                fmt,
831                "Detected unaligned segment. You must either ensure all of your segments are 8-byte aligned, or you must enable the \"unaligned\" feature in the capnp crate"
832            ),
833            Self::UnexpectedFarPointer => write!(fmt, "Unexpected far pointer"),
834            Self::UnknownPointerType => write!(fmt, "Unknown pointer type."),
835        }
836    }
837}
838
839impl core::fmt::Display for Error {
840    fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::result::Result<(), core::fmt::Error> {
841        let extra = self.extra();
842        if extra.is_empty() {
843            write!(fmt, "{}", self.kind)
844        } else {
845            write!(fmt, "{}: {extra}", self.kind)
846        }
847    }
848}
849
850impl core::error::Error for Error {
851    fn description(&self) -> &str {
852        self.extra()
853    }
854    fn cause(&self) -> Option<&dyn ::core::error::Error> {
855        None
856    }
857}
858
859/// Helper struct that allows `MessageBuilder::get_segments_for_output()` to avoid heap allocations
860/// in the single-segment case.
861pub enum OutputSegments<'a> {
862    SingleSegment([&'a [u8]; 1]),
863
864    #[cfg(feature = "alloc")]
865    MultiSegment(alloc::vec::Vec<&'a [u8]>),
866}
867
868impl<'a> core::ops::Deref for OutputSegments<'a> {
869    type Target = [&'a [u8]];
870    fn deref(&self) -> &[&'a [u8]] {
871        match self {
872            OutputSegments::SingleSegment(s) => s,
873
874            #[cfg(feature = "alloc")]
875            OutputSegments::MultiSegment(v) => v,
876        }
877    }
878}
879
880impl message::ReaderSegments for OutputSegments<'_> {
881    fn get_segment(&self, id: u32) -> Option<&[u8]> {
882        match self {
883            OutputSegments::SingleSegment(s) => s.get(id as usize).copied(),
884
885            #[cfg(feature = "alloc")]
886            OutputSegments::MultiSegment(v) => v.get(id as usize).copied(),
887        }
888    }
889}
890
891#[cfg(test)]
892mod tests {
893    use super::*;
894
895    #[test]
896    #[cfg(target_pointer_width = "64")]
897    fn error_size() {
898        assert_eq!(core::mem::size_of::<ErrorKind>(), 24);
899        #[cfg(feature = "alloc")]
900        assert_eq!(core::mem::size_of::<Error>(), 56);
901        #[cfg(not(feature = "alloc"))]
902        assert_eq!(core::mem::size_of::<Error>(), 24);
903    }
904
905    #[test]
906    fn error_from_kind_extra_is_empty() {
907        let e = Error::from_kind(ErrorKind::NotAStruct);
908        assert_eq!(e.extra(), "");
909    }
910
911    #[test]
912    #[cfg(feature = "alloc")]
913    fn error_details() {
914        let mut e = Error::failed("foo".into());
915        assert_eq!(e.extra(), "foo");
916        assert!(e.get_details().is_empty());
917        assert_eq!(e.get_detail(123), None);
918
919        e.set_detail(123, b"foo".to_vec());
920        e.set_detail(456, b"bar".to_vec());
921        assert_eq!(e.get_detail(123), Some(&b"foo"[..]));
922        assert_eq!(e.get_detail(456), Some(&b"bar"[..]));
923        assert_eq!(e.get_detail(789), None);
924        assert_eq!(e.get_details().len(), 2);
925
926        // Overwriting an existing detail ID updates it in place without duplicating.
927        e.set_detail(123, b"baz".to_vec());
928        assert_eq!(e.get_detail(123), Some(&b"baz"[..]));
929        assert_eq!(
930            e.get_details(),
931            &[
932                ErrorDetail {
933                    id: 123,
934                    data: b"baz".to_vec(),
935                },
936                ErrorDetail {
937                    id: 456,
938                    data: b"bar".to_vec(),
939                },
940            ]
941        );
942
943        let mut e2 = e.clone();
944        assert_eq!(e2.extra(), "foo");
945        assert_eq!(e2.get_detail(123), Some(&b"baz"[..]));
946        assert_eq!(e2.get_detail(456), Some(&b"bar"[..]));
947
948        assert_eq!(e2.release_detail(123), Some(b"baz".to_vec()));
949        assert_eq!(e2.get_detail(123), None);
950        assert_eq!(e2.get_detail(456), Some(&b"bar"[..]));
951        assert_eq!(e2.release_detail(123), None);
952
953        // Releasing the last detail frees its box while preserving the textual context.
954        assert_eq!(e2.release_detail(456), Some(b"bar".to_vec()));
955        assert!(e2.details.is_none());
956        assert_eq!(e2.extra(), "foo");
957
958        // Details on a `from_kind` error also clean up the box when released.
959        let mut e3 = Error::from_kind(ErrorKind::NotAStruct);
960        e3.set_detail(1, vec![]);
961        assert_eq!(e3.get_detail(1), Some(&b""[..]));
962        assert_eq!(e3.release_detail(1), Some(vec![]));
963        assert!(e3.details.is_none());
964    }
965}