capnp 0.28.0

runtime library for Cap'n Proto data encoding
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
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

//! # Cap'n Proto Runtime Library
//!
//! This crate contains basic facilities for reading and writing
//! [Cap'n Proto](https://capnproto.org) messages in Rust. It is intended to
//! be used in conjunction with code generated by the
//! [capnpc-rust](https://crates.io/crates/capnpc) crate.

#![cfg_attr(not(test), deny(clippy::cast_possible_truncation))]
#![cfg_attr(not(test), deny(clippy::cast_possible_wrap))]
#![cfg_attr(feature = "rpc_try", feature(try_trait_v2))]
#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(feature = "alloc")]
#[macro_use]
extern crate alloc;

/// Code generated from
/// [schema.capnp](https://github.com/capnproto/capnproto/blob/master/c%2B%2B/src/capnp/schema.capnp).
pub mod schema_capnp;

pub mod any_pointer;
pub mod any_pointer_list;
pub mod capability;
pub mod capability_list;
pub mod constant;
pub mod data;
pub mod data_list;
pub mod dynamic_list;
pub mod dynamic_struct;
pub mod dynamic_value;
pub mod enum_list;
pub mod introspect;
pub mod io;
pub mod list_list;
pub mod message;
pub mod primitive_list;
pub mod private;
pub mod raw;
pub mod schema;
pub mod serialize;
pub mod serialize_packed;
pub(crate) mod stringify;
pub mod struct_list;
pub mod text;
pub mod text_list;
pub mod traits;

/// Macro for importing Rust code that has been generated by `capnpc::CompilerCommand`.
///
/// For example:
/// ```ignore
/// generated_code!(pub mod foo_capnp);
/// ```
/// pulls in the generated code for `foo.capnp` into a module named `foo_capnp`.
/// It expects to find the generated code in a file `$OUT_DIR/foo_capnp.rs`,
/// where `OUT_DIR` is Cargo's standard environment variable giving the
/// location of the output of `build.rs`.
///
/// If the generated code lives in a nonstandard location—perhaps in a subdirectory
/// of `OUT_DIR`—you can specify its path as a second argument:
/// ```ignore
/// generated_code!(pub mod foo_capnp, "some_directory/foo_capnp.rs");
/// ```
#[macro_export]
macro_rules! generated_code {
    ($vis:vis mod $mod_name:ident, $file_name:expr_2021) => {
        $vis mod $mod_name {
            #![allow(clippy::all)]
            include!(concat!(env!("OUT_DIR"), "/", $file_name));
        }
    };

    ($vis:vis mod $mod_name:ident) => {
        $crate::generated_code!($vis mod $mod_name, concat!(stringify!($mod_name), ".rs"));
    };
}

///
/// 8 bytes, aligned to an 8-byte boundary.
///
/// Internally, capnproto-rust allocates message buffers using this type,
/// to guarantee alignment.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(C, align(8))]
pub struct Word {
    raw_content: [u8; 8],
}

///
/// Constructs a word with the given bytes.
///
#[allow(clippy::too_many_arguments)]
pub const fn word(b0: u8, b1: u8, b2: u8, b3: u8, b4: u8, b5: u8, b6: u8, b7: u8) -> Word {
    Word {
        raw_content: [b0, b1, b2, b3, b4, b5, b6, b7],
    }
}

impl Word {
    /// Allocates a vec of `length` words, all set to zero.
    #[cfg(feature = "alloc")]
    pub fn allocate_zeroed_vec(length: usize) -> alloc::vec::Vec<Self> {
        vec![word(0, 0, 0, 0, 0, 0, 0, 0); length]
    }

    pub fn words_to_bytes(words: &[Self]) -> &[u8] {
        unsafe { core::slice::from_raw_parts(words.as_ptr() as *const u8, words.len() * 8) }
    }

    pub fn words_to_bytes_mut(words: &mut [Self]) -> &mut [u8] {
        unsafe { core::slice::from_raw_parts_mut(words.as_mut_ptr() as *mut u8, words.len() * 8) }
    }
}

#[cfg(any(feature = "quickcheck", test))]
impl quickcheck::Arbitrary for Word {
    fn arbitrary(g: &mut quickcheck::Gen) -> Self {
        crate::word(
            quickcheck::Arbitrary::arbitrary(g),
            quickcheck::Arbitrary::arbitrary(g),
            quickcheck::Arbitrary::arbitrary(g),
            quickcheck::Arbitrary::arbitrary(g),
            quickcheck::Arbitrary::arbitrary(g),
            quickcheck::Arbitrary::arbitrary(g),
            quickcheck::Arbitrary::arbitrary(g),
            quickcheck::Arbitrary::arbitrary(g),
        )
    }
}

/// Size of a message. Every generated struct has a method `.total_size()` that returns this.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MessageSize {
    pub word_count: u64,

    /// Size of the capability table.
    pub cap_count: u32,
}

impl core::ops::AddAssign for MessageSize {
    fn add_assign(&mut self, rhs: Self) {
        self.word_count += rhs.word_count;
        self.cap_count += rhs.cap_count;
    }
}

/// An enum value or union discriminant that was not found among those defined in a schema.
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub struct NotInSchema(pub u16);

impl ::core::fmt::Display for NotInSchema {
    fn fmt(
        &self,
        fmt: &mut ::core::fmt::Formatter,
    ) -> ::core::result::Result<(), ::core::fmt::Error> {
        write!(
            fmt,
            "Enum value or union discriminant {} was not present in the schema.",
            self.0
        )
    }
}

impl ::core::error::Error for NotInSchema {
    fn description(&self) -> &str {
        "Enum value or union discriminant was not present in schema."
    }
}

/// Because messages are lazily validated, the return type of any method that reads a pointer field
/// must be wrapped in a Result.
pub type Result<T> = ::core::result::Result<T, Error>;

/// Arbitrary extra detail attached to an [`Error`].
///
/// Each detail has a unique 64-bit `id` (typically generated with `capnp id`) and a byte `data`
/// payload whose encoding is defined by the application.
#[cfg(feature = "alloc")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ErrorDetail {
    pub id: u64,
    pub data: alloc::vec::Vec<u8>,
}

/// Describes an arbitrary error that prevented an operation from completing.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Error {
    /// The general kind of the error. Code that decides how to respond to an error
    /// should read only this field in making its decision.
    pub kind: ErrorKind,

    #[cfg(feature = "alloc")]
    extra: alloc::string::String,
    // Keep the details vector out of line so errors without details pay for only a pointer.
    #[cfg(feature = "alloc")]
    #[allow(clippy::box_collection)]
    details: Option<alloc::boxed::Box<alloc::vec::Vec<ErrorDetail>>>,
}

/// The general nature of an error. The purpose of this enum is not to describe the error itself,
/// but rather to describe how the client might want to respond to the error.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ErrorKind {
    /// Something went wrong
    Failed,

    /// The call failed because of a temporary lack of resources. This could be space resources
    /// (out of memory, out of disk space) or time resources (request queue overflow, operation
    /// timed out).
    ///
    /// The operation might work if tried again, but it should NOT be repeated immediately as this
    /// may simply exacerbate the problem.
    Overloaded,

    /// The call required communication over a connection that has been lost. The caller will need
    /// to re-establish connections and try again.
    Disconnected,

    /// The requested method is not implemented. The caller may wish to revert to a fallback
    /// approach based on other methods.
    Unimplemented,

    /// Buffer is not large enough
    BufferNotLargeEnough,

    /// Cannot create a canonical message with a capability
    CannotCreateACanonicalMessageWithACapability,

    /// Cannot set AnyPointer field to a primitive value
    CannotSetAnyPointerFieldToAPrimitiveValue,

    /// Don't know how to handle non-STRUCT inline composite.
    CantHandleNonStructInlineComposite,

    /// Empty buffer
    EmptyBuffer,

    /// Empty slice
    EmptySlice,

    /// Enum value or union discriminant {} was not present in schema
    EnumValueOrUnionDiscriminantNotPresent(NotInSchema),

    /// Called get_writable_{data|text}_pointer() but existing list pointer is not byte-sized.
    ExistingListPointerIsNotByteSized,

    /// Existing list value is incompatible with expected type.
    ExistingListValueIsIncompatibleWithExpectedType,

    /// Called get_writable_{data|text|list|struct_list}_pointer() but existing pointer is not a list.
    ExistingPointerIsNotAList,

    /// Expected a list or blob.
    ExpectedAListOrBlob,

    /// Expected a pointer list, but got a list of data-only structs
    ExpectedAPointerListButGotAListOfDataOnlyStructs,

    /// Expected a primitive list, but got a list of pointer-only structs
    ExpectedAPrimitiveListButGotAListOfPointerOnlyStructs,

    /// failed to fill the whole buffer
    FailedToFillTheWholeBuffer,

    /// field and default mismatch
    FieldAndDefaultMismatch,

    /// field not found
    FieldNotFound,

    /// Found bit list where struct list was expected; upgrading boolean lists to struct lists is no longer supported
    FoundBitListWhereStructListWasExpected,

    /// Found struct list where bit list was expected.
    FoundStructListWhereBitListWasExpected,

    /// 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.
    FourByteLengthTooBigForUSize,

    /// 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
    FourByteSegmentLengthTooBigForUSize,

    /// group field but type is not Struct
    GroupFieldButTypeIsNotStruct,

    /// init() is only valid for struct and AnyPointer fields
    InitIsOnlyValidForStructAndAnyPointerFields,

    /// initn() is only valid for list, text, or data fields
    InitnIsOnlyValidForListTextOrDataFields,

    /// InlineComposite list with non-STRUCT elements not supported.
    InlineCompositeListWithNonStructElementsNotSupported,

    /// InlineComposite list's elements overrun its word count.
    InlineCompositeListsElementsOverrunItsWordCount,

    /// InlineComposite lists of non-STRUCT type are not supported.
    InlineCompositeListsOfNonStructTypeAreNotSupported,

    /// Too many or too few segments {segment_count}
    InvalidNumberOfSegments(usize),

    /// Invalid segment id {id}
    InvalidSegmentId(u32),

    /// List(AnyPointer) not supported.
    ListAnyPointerNotSupported,

    /// List(Capability) not supported
    ListCapabilityNotSupported,

    /// Malformed double-far pointer.
    MalformedDoubleFarPointer,

    /// Message contains invalid capability pointer.
    MessageContainsInvalidCapabilityPointer,

    /// Message contains list pointer of non-bytes where data was expected.
    MessageContainsListPointerOfNonBytesWhereDataWasExpected,

    /// Message contains list pointer of non-bytes where text was expected.
    MessageContainsListPointerOfNonBytesWhereTextWasExpected,

    /// Message contains list with incompatible element type.
    MessageContainsListWithIncompatibleElementType,

    /// Message contains non-capability pointer where capability pointer was expected.
    MessageContainsNonCapabilityPointerWhereCapabilityPointerWasExpected,

    /// Message contains non-struct pointer where struct pointer was expected.
    MessageContainsNonStructPointerWhereStructPointerWasExpected,

    /// Message contains non-list pointer where data was expected.
    MessageContainsNonListPointerWhereDataWasExpected,

    /// Message contains non-list pointer where list pointer was expected
    MessageContainsNonListPointerWhereListPointerWasExpected,

    /// Message contains non-list pointer where text was expected.
    MessageContainsNonListPointerWhereTextWasExpected,

    /// Message contains null capability pointer.
    MessageContainsNullCapabilityPointer,

    /// Message contains out-of-bounds pointer,
    MessageContainsOutOfBoundsPointer,

    /// Message contains text that is not NUL-terminated
    MessageContainsTextThatIsNotNULTerminated,

    /// Message ends prematurely. Header claimed {header} words, but message only has {body} words,
    MessageEndsPrematurely(usize, usize),

    /// Message is too deeply nested.
    MessageIsTooDeeplyNested,

    /// Message is too deeply-nested or contains cycles.
    MessageIsTooDeeplyNestedOrContainsCycles,

    /// Message was not aligned by 8 bytes boundary. Either ensure that message is properly aligned or compile `capnp` crate with \"unaligned\" feature enabled.
    MessageNotAlignedBy8BytesBoundary,

    /// Message's size cannot be represented in usize
    MessageSizeOverflow,

    /// Message is too large
    MessageTooLarge(usize),

    /// Nesting limit exceeded
    NestingLimitExceeded,

    /// Not a struct
    NotAStruct,

    /// Only one of the section pointers is pointing to ourself
    OnlyOneOfTheSectionPointersIsPointingToOurself,

    /// Packed input did not end cleanly on a segment boundary.
    PackedInputDidNotEndCleanlyOnASegmentBoundary,

    /// Premature end of file
    PrematureEndOfFile,

    /// Premature end of packed input.
    PrematureEndOfPackedInput,

    /// Read limit exceeded
    ReadLimitExceeded,

    /// setting dynamic capabilities is unsupported
    SettingDynamicCapabilitiesIsUnsupported,

    /// Struct reader had bitwidth other than 1
    StructReaderHadBitwidthOtherThan1,

    /// Text blob missing NUL terminator.
    TextBlobMissingNULTerminator,

    /// Text contains non-utf8 data
    TextContainsNonUtf8Data(core::str::Utf8Error),

    /// Tried to read from null arena
    TriedToReadFromNullArena,

    /// type mismatch
    TypeMismatch,

    /// 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
    UnalignedSegment,

    /// Unexpected far pointer
    UnexpectedFarPointer,

    /// Unknown pointer type.
    UnknownPointerType,
}

impl Error {
    #[cfg(feature = "alloc")]
    pub fn new(kind: ErrorKind, extra: alloc::string::String) -> Self {
        Self {
            kind,
            extra,
            details: None,
        }
    }

    pub fn from_kind(kind: ErrorKind) -> Self {
        Self {
            kind,
            #[cfg(feature = "alloc")]
            extra: alloc::string::String::new(),
            #[cfg(feature = "alloc")]
            details: None,
        }
    }

    #[cfg(feature = "alloc")]
    pub fn failed(description: alloc::string::String) -> Self {
        Self::new(ErrorKind::Failed, description)
    }

    #[cfg(feature = "alloc")]
    pub fn overloaded(description: alloc::string::String) -> Self {
        Self::new(ErrorKind::Overloaded, description)
    }

    #[cfg(feature = "alloc")]
    pub fn disconnected(description: alloc::string::String) -> Self {
        Self::new(ErrorKind::Disconnected, description)
    }

    #[cfg(feature = "alloc")]
    pub fn unimplemented(description: alloc::string::String) -> Self {
        Self::new(ErrorKind::Unimplemented, description)
    }

    /// Returns any extra human-readable context attached to this error, or `""` if none.
    pub fn extra(&self) -> &str {
        #[cfg(feature = "alloc")]
        {
            &self.extra
        }
        #[cfg(not(feature = "alloc"))]
        {
            ""
        }
    }

    /// Appends formatted text to this error's `extra` context. Does nothing if the `"alloc"`
    /// feature is not enabled. This is intended to be used with the `write!()` macro from `core`.
    pub fn write_fmt(&mut self, fmt: core::fmt::Arguments<'_>) {
        #[cfg(feature = "alloc")]
        {
            use core::fmt::Write;
            let _ = self.extra.write_fmt(fmt);
        }
        #[cfg(not(feature = "alloc"))]
        {
            let _ = fmt;
        }
    }

    /// Returns the detail payload associated with `detail_id`, if present.
    ///
    /// Details can be attached to an error returned by an RPC server method and retrieved on the
    /// client after awaiting the call. Each detail type should use a unique 64-bit ID (typically
    /// generated with `capnp id`).
    #[cfg(feature = "alloc")]
    pub fn get_detail(&self, detail_id: u64) -> Option<&[u8]> {
        let details = self.details.as_ref()?;
        details
            .iter()
            .find(|detail| detail.id == detail_id)
            .map(|detail| detail.data.as_slice())
    }

    /// Returns all [`ErrorDetail`] entries attached to this error.
    #[cfg(feature = "alloc")]
    pub fn get_details(&self) -> &[ErrorDetail] {
        match &self.details {
            Some(details) => details.as_slice(),
            None => &[],
        }
    }

    /// Attaches a detail payload keyed by `detail_id` to this error, replacing any
    /// existing payload with the same `detail_id`.
    ///
    /// Each detail type should use a unique 64-bit ID (typically generated with `capnp id`).
    ///
    /// ```
    /// const VALIDATION_ERROR: u64 = 0x9935_c2b4_7d94_809c;
    /// let mut err = capnp::Error::failed("invalid".into());
    /// err.set_detail(VALIDATION_ERROR, b"field x must be positive".to_vec());
    /// assert_eq!(err.get_detail(VALIDATION_ERROR), Some(&b"field x must be positive"[..]));
    /// ```
    #[cfg(feature = "alloc")]
    pub fn set_detail(&mut self, detail_id: u64, data: alloc::vec::Vec<u8>) {
        let details = self.details.get_or_insert_with(Default::default);
        if let Some(existing) = details.iter_mut().find(|detail| detail.id == detail_id) {
            existing.data = data;
        } else {
            details.push(ErrorDetail {
                id: detail_id,
                data,
            });
        }
    }

    /// Removes and returns the detail payload associated with `detail_id`, if present.
    #[cfg(feature = "alloc")]
    pub fn release_detail(&mut self, detail_id: u64) -> Option<alloc::vec::Vec<u8>> {
        let details = self.details.as_mut()?;
        let idx = details.iter().position(|detail| detail.id == detail_id)?;
        let detail = details.remove(idx);
        if details.is_empty() {
            self.details = None;
        }
        Some(detail.data)
    }
}

#[cfg(feature = "std")]
impl core::convert::From<::std::io::Error> for Error {
    fn from(err: ::std::io::Error) -> Self {
        use std::io;
        let kind = match err.kind() {
            io::ErrorKind::TimedOut => ErrorKind::Overloaded,
            io::ErrorKind::BrokenPipe
            | io::ErrorKind::ConnectionRefused
            | io::ErrorKind::ConnectionReset
            | io::ErrorKind::ConnectionAborted
            | io::ErrorKind::NotConnected => ErrorKind::Disconnected,
            io::ErrorKind::UnexpectedEof => ErrorKind::PrematureEndOfFile,
            _ => ErrorKind::Failed,
        };
        #[cfg(feature = "alloc")]
        return Self::new(kind, format!("{err}"));
        #[cfg(not(feature = "alloc"))]
        return Self::from_kind(kind);
    }
}

#[cfg(feature = "embedded-io")]
impl From<embedded_io::ErrorKind> for ErrorKind {
    fn from(value: embedded_io::ErrorKind) -> Self {
        match value {
            embedded_io::ErrorKind::Other => Self::Failed,
            embedded_io::ErrorKind::NotFound => Self::Failed,
            embedded_io::ErrorKind::PermissionDenied => Self::Failed,
            embedded_io::ErrorKind::ConnectionRefused => Self::Failed,
            embedded_io::ErrorKind::ConnectionReset => Self::Failed,
            embedded_io::ErrorKind::ConnectionAborted => Self::Failed,
            embedded_io::ErrorKind::NotConnected => Self::Failed,
            embedded_io::ErrorKind::AddrInUse => Self::Failed,
            embedded_io::ErrorKind::AddrNotAvailable => Self::Failed,
            embedded_io::ErrorKind::BrokenPipe => Self::Failed,
            embedded_io::ErrorKind::AlreadyExists => Self::Failed,
            embedded_io::ErrorKind::InvalidInput => Self::Failed,
            embedded_io::ErrorKind::InvalidData => Self::Failed,
            embedded_io::ErrorKind::TimedOut => Self::Failed,
            embedded_io::ErrorKind::Interrupted => Self::Failed,
            embedded_io::ErrorKind::Unsupported => Self::Failed,
            embedded_io::ErrorKind::OutOfMemory => Self::Failed,
            _ => Self::Failed,
        }
    }
}

#[cfg(feature = "alloc")]
impl core::convert::From<alloc::string::FromUtf8Error> for Error {
    fn from(err: alloc::string::FromUtf8Error) -> Self {
        Self::failed(format!("{err}"))
    }
}

impl core::convert::From<core::str::Utf8Error> for Error {
    fn from(err: core::str::Utf8Error) -> Self {
        Self::from_kind(ErrorKind::TextContainsNonUtf8Data(err))
    }
}

impl core::convert::From<NotInSchema> for Error {
    fn from(e: NotInSchema) -> Self {
        Self::from_kind(ErrorKind::EnumValueOrUnionDiscriminantNotPresent(e))
    }
}

impl core::fmt::Display for ErrorKind {
    fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::result::Result<(), core::fmt::Error> {
        match self {
            Self::Failed => write!(fmt, "Failed"),
            Self::Overloaded => write!(fmt, "Overloaded"),
            Self::Disconnected => write!(fmt, "Disconnected"),
            Self::Unimplemented => write!(fmt, "Unimplemented"),
            Self::BufferNotLargeEnough => write!(fmt, "buffer is not large enough"),
            Self::ExistingListPointerIsNotByteSized => write!(
                fmt,
                "Called get_writable_{{data|text}}_pointer() but existing list pointer is not byte-sized."
            ),
            Self::ExistingPointerIsNotAList => write!(
                fmt,
                "Called get_writable_{{data|text|list|struct_list}}_pointer() but existing pointer is not a list."
            ),
            Self::CannotCreateACanonicalMessageWithACapability => {
                write!(fmt, "Cannot create a canonical message with a capability")
            }
            Self::FourByteLengthTooBigForUSize => write!(
                fmt,
                "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."
            ),
            Self::FourByteSegmentLengthTooBigForUSize => write!(
                fmt,
                "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"
            ),
            Self::CannotSetAnyPointerFieldToAPrimitiveValue => {
                write!(fmt, "cannot set AnyPointer field to a primitive value")
            }
            Self::CantHandleNonStructInlineComposite => {
                write!(fmt, "Don't know how to handle non-STRUCT inline composite.")
            }
            Self::EmptyBuffer => write!(fmt, "empty buffer"),
            Self::EmptySlice => write!(fmt, "empty slice"),
            Self::EnumValueOrUnionDiscriminantNotPresent(val) => write!(
                fmt,
                "Enum value or union discriminant {val} was not present in schema"
            ),
            Self::ExistingListValueIsIncompatibleWithExpectedType => write!(
                fmt,
                "Existing list value is incompatible with expected type."
            ),
            Self::ExpectedAListOrBlob => write!(fmt, "Expected a list or blob."),
            Self::ExpectedAPointerListButGotAListOfDataOnlyStructs => write!(
                fmt,
                "Expected a pointer list, but got a list of data-only structs"
            ),
            Self::ExpectedAPrimitiveListButGotAListOfPointerOnlyStructs => write!(
                fmt,
                "Expected a primitive list, but got a list of pointer-only structs"
            ),
            Self::FailedToFillTheWholeBuffer => write!(fmt, "failed to fill the whole buffer"),
            Self::FieldAndDefaultMismatch => write!(fmt, "field and default mismatch"),
            Self::FieldNotFound => write!(fmt, "field not found"),
            Self::FoundBitListWhereStructListWasExpected => write!(
                fmt,
                "Found bit list where struct list was expected; upgrading boolean lists to struct lists is no longer supported."
            ),
            Self::FoundStructListWhereBitListWasExpected => {
                write!(fmt, "Found struct list where bit list was expected.")
            }
            Self::GroupFieldButTypeIsNotStruct => write!(fmt, "group field but type is not Struct"),
            Self::InitIsOnlyValidForStructAndAnyPointerFields => {
                write!(fmt, "init() is only valid for struct and AnyPointer fields")
            }
            Self::InitnIsOnlyValidForListTextOrDataFields => {
                write!(fmt, "initn() is only valid for list, text, or data fields")
            }
            Self::InlineCompositeListWithNonStructElementsNotSupported => write!(
                fmt,
                "InlineComposite list with non-STRUCT elements not supported."
            ),
            Self::InlineCompositeListsElementsOverrunItsWordCount => write!(
                fmt,
                "InlineComposite list's elements overrun its word count."
            ),
            Self::InlineCompositeListsOfNonStructTypeAreNotSupported => write!(
                fmt,
                "InlineComposite lists of non-STRUCT type are not supported."
            ),
            Self::InvalidNumberOfSegments(segment_count) => {
                write!(fmt, "Too many or too few segments {segment_count}")
            }
            Self::InvalidSegmentId(id) => write!(fmt, "Invalid segment id {id}"),
            Self::ListAnyPointerNotSupported => write!(fmt, "List(AnyPointer) not supported."),
            Self::ListCapabilityNotSupported => write!(fmt, "List(Capability) not supported"),
            Self::MalformedDoubleFarPointer => write!(fmt, "Malformed double-far pointer."),
            Self::MessageContainsInvalidCapabilityPointer => {
                write!(fmt, "Message contained invalid capability pointer.")
            }
            Self::MessageContainsListPointerOfNonBytesWhereDataWasExpected => write!(
                fmt,
                "Message contains list pointer of non-bytes where data was expected."
            ),
            Self::MessageContainsListPointerOfNonBytesWhereTextWasExpected => write!(
                fmt,
                "Message contains list pointer of non-bytes where text was expected."
            ),
            Self::MessageContainsListWithIncompatibleElementType => {
                write!(fmt, "Message contains list with incompatible element type.")
            }
            Self::MessageContainsNonCapabilityPointerWhereCapabilityPointerWasExpected => write!(
                fmt,
                "Message contains non-capability pointer where capability pointer was expected."
            ),
            Self::MessageContainsNonListPointerWhereDataWasExpected => write!(
                fmt,
                "Message contains non-list pointer where data was expected."
            ),
            Self::MessageContainsNonListPointerWhereListPointerWasExpected => write!(
                fmt,
                "Message contains non-list pointer where list pointer was expected"
            ),
            Self::MessageContainsNonListPointerWhereTextWasExpected => write!(
                fmt,
                "Message contains non-list pointer where text was expected."
            ),
            Self::MessageContainsNonStructPointerWhereStructPointerWasExpected => write!(
                fmt,
                "Message contains non-struct pointer where struct pointer was expected."
            ),
            Self::MessageContainsNullCapabilityPointer => {
                write!(fmt, "Message contains null capability pointer.")
            }
            Self::MessageContainsOutOfBoundsPointer => {
                write!(fmt, "Message contains out-of-bounds pointer")
            }
            Self::MessageContainsTextThatIsNotNULTerminated => {
                write!(fmt, "Message contains text that is not NUL-terminated")
            }
            Self::MessageEndsPrematurely(header, body) => write!(
                fmt,
                "Message ends prematurely. Header claimed {header} words, but message only has {body} words"
            ),
            Self::MessageIsTooDeeplyNested => write!(fmt, "Message is too deeply nested."),
            Self::MessageIsTooDeeplyNestedOrContainsCycles => {
                write!(fmt, "Message is too deeply-nested or contains cycles.")
            }
            Self::MessageSizeOverflow => {
                write!(fmt, "Message's size cannot be represented in usize")
            }
            Self::MessageTooLarge(val) => write!(fmt, "Message is too large: {val}"),
            Self::MessageNotAlignedBy8BytesBoundary => write!(
                fmt,
                "Message was not aligned by 8 bytes boundary. Either ensure that message is properly aligned or compile `capnp` crate with \"unaligned\" feature enabled."
            ),
            Self::NestingLimitExceeded => write!(fmt, "nesting limit exceeded"),
            Self::NotAStruct => write!(fmt, "not a struct"),
            Self::OnlyOneOfTheSectionPointersIsPointingToOurself => write!(
                fmt,
                "Only one of the section pointers is pointing to ourself"
            ),
            Self::PackedInputDidNotEndCleanlyOnASegmentBoundary => write!(
                fmt,
                "Packed input did not end cleanly on a segment boundary."
            ),
            Self::PrematureEndOfFile => write!(fmt, "Premature end of file"),
            Self::PrematureEndOfPackedInput => write!(fmt, "Premature end of packed input."),
            Self::ReadLimitExceeded => write!(fmt, "Read limit exceeded"),
            Self::SettingDynamicCapabilitiesIsUnsupported => {
                write!(fmt, "setting dynamic capabilities is unsupported")
            }
            Self::StructReaderHadBitwidthOtherThan1 => {
                write!(fmt, "struct reader had bitwidth other than 1")
            }
            Self::TextBlobMissingNULTerminator => write!(fmt, "Text blob missing NUL terminator."),
            Self::TextContainsNonUtf8Data(e) => write!(fmt, "Text contains non-utf8 data: {e}"),
            Self::TriedToReadFromNullArena => write!(fmt, "Tried to read from null arena"),
            Self::TypeMismatch => write!(fmt, "type mismatch"),
            Self::UnalignedSegment => write!(
                fmt,
                "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"
            ),
            Self::UnexpectedFarPointer => write!(fmt, "Unexpected far pointer"),
            Self::UnknownPointerType => write!(fmt, "Unknown pointer type."),
        }
    }
}

impl core::fmt::Display for Error {
    fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::result::Result<(), core::fmt::Error> {
        let extra = self.extra();
        if extra.is_empty() {
            write!(fmt, "{}", self.kind)
        } else {
            write!(fmt, "{}: {extra}", self.kind)
        }
    }
}

impl core::error::Error for Error {
    fn description(&self) -> &str {
        self.extra()
    }
    fn cause(&self) -> Option<&dyn ::core::error::Error> {
        None
    }
}

/// Helper struct that allows `MessageBuilder::get_segments_for_output()` to avoid heap allocations
/// in the single-segment case.
pub enum OutputSegments<'a> {
    SingleSegment([&'a [u8]; 1]),

    #[cfg(feature = "alloc")]
    MultiSegment(alloc::vec::Vec<&'a [u8]>),
}

impl<'a> core::ops::Deref for OutputSegments<'a> {
    type Target = [&'a [u8]];
    fn deref(&self) -> &[&'a [u8]] {
        match self {
            OutputSegments::SingleSegment(s) => s,

            #[cfg(feature = "alloc")]
            OutputSegments::MultiSegment(v) => v,
        }
    }
}

impl message::ReaderSegments for OutputSegments<'_> {
    fn get_segment(&self, id: u32) -> Option<&[u8]> {
        match self {
            OutputSegments::SingleSegment(s) => s.get(id as usize).copied(),

            #[cfg(feature = "alloc")]
            OutputSegments::MultiSegment(v) => v.get(id as usize).copied(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[cfg(target_pointer_width = "64")]
    fn error_size() {
        assert_eq!(core::mem::size_of::<ErrorKind>(), 24);
        #[cfg(feature = "alloc")]
        assert_eq!(core::mem::size_of::<Error>(), 56);
        #[cfg(not(feature = "alloc"))]
        assert_eq!(core::mem::size_of::<Error>(), 24);
    }

    #[test]
    fn error_from_kind_extra_is_empty() {
        let e = Error::from_kind(ErrorKind::NotAStruct);
        assert_eq!(e.extra(), "");
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn error_details() {
        let mut e = Error::failed("foo".into());
        assert_eq!(e.extra(), "foo");
        assert!(e.get_details().is_empty());
        assert_eq!(e.get_detail(123), None);

        e.set_detail(123, b"foo".to_vec());
        e.set_detail(456, b"bar".to_vec());
        assert_eq!(e.get_detail(123), Some(&b"foo"[..]));
        assert_eq!(e.get_detail(456), Some(&b"bar"[..]));
        assert_eq!(e.get_detail(789), None);
        assert_eq!(e.get_details().len(), 2);

        // Overwriting an existing detail ID updates it in place without duplicating.
        e.set_detail(123, b"baz".to_vec());
        assert_eq!(e.get_detail(123), Some(&b"baz"[..]));
        assert_eq!(
            e.get_details(),
            &[
                ErrorDetail {
                    id: 123,
                    data: b"baz".to_vec(),
                },
                ErrorDetail {
                    id: 456,
                    data: b"bar".to_vec(),
                },
            ]
        );

        let mut e2 = e.clone();
        assert_eq!(e2.extra(), "foo");
        assert_eq!(e2.get_detail(123), Some(&b"baz"[..]));
        assert_eq!(e2.get_detail(456), Some(&b"bar"[..]));

        assert_eq!(e2.release_detail(123), Some(b"baz".to_vec()));
        assert_eq!(e2.get_detail(123), None);
        assert_eq!(e2.get_detail(456), Some(&b"bar"[..]));
        assert_eq!(e2.release_detail(123), None);

        // Releasing the last detail frees its box while preserving the textual context.
        assert_eq!(e2.release_detail(456), Some(b"bar".to_vec()));
        assert!(e2.details.is_none());
        assert_eq!(e2.extra(), "foo");

        // Details on a `from_kind` error also clean up the box when released.
        let mut e3 = Error::from_kind(ErrorKind::NotAStruct);
        e3.set_detail(1, vec![]);
        assert_eq!(e3.get_detail(1), Some(&b""[..]));
        assert_eq!(e3.release_detail(1), Some(vec![]));
        assert!(e3.details.is_none());
    }
}