buffa-types 0.9.2

Protobuf well-known types for buffa
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
// @generated by buffa-codegen. DO NOT EDIT.
// source: google/protobuf/any.proto

/// `Any` contains an arbitrary serialized protocol buffer message along with a
/// URL that describes the type of the serialized message.
///
/// Protobuf library provides support to pack/unpack Any values in the form
/// of utility functions or additional generated methods of the Any type.
///
/// Example 1: Pack and unpack a message in C++.
///
/// ```text
/// Foo foo = ...;
/// Any any;
/// any.PackFrom(foo);
/// ...
/// if (any.UnpackTo(&foo)) {
///   ...
/// }
/// ```
///
/// Example 2: Pack and unpack a message in Java.
///
/// ```text
/// Foo foo = ...;
/// Any any = Any.pack(foo);
/// ...
/// if (any.is(Foo.class)) {
///   foo = any.unpack(Foo.class);
/// }
/// // or ...
/// if (any.isSameTypeAs(Foo.getDefaultInstance())) {
///   foo = any.unpack(Foo.getDefaultInstance());
/// }
/// ```
///
///  Example 3: Pack and unpack a message in Python.
///
/// ```text
/// foo = Foo(...)
/// any = Any()
/// any.Pack(foo)
/// ...
/// if any.Is(Foo.DESCRIPTOR):
///   any.Unpack(foo)
///   ...
/// ```
///
///  Example 4: Pack and unpack a message in Go
///
/// ```text
///  foo := &pb.Foo{...}
///  any, err := anypb.New(foo)
///  if err != nil {
///    ...
///  }
///  ...
///  foo := &pb.Foo{}
///  if err := any.UnmarshalTo(foo); err != nil {
///    ...
///  }
/// ```
///
/// The pack methods provided by protobuf library will by default use
/// 'type.googleapis.com/full.type.name' as the type URL and the unpack
/// methods only use the fully qualified type name after the last '/'
/// in the type URL, for example "foo.bar.com/x/y.z" will yield type
/// name "y.z".
///
/// JSON
/// ====
/// The JSON representation of an `Any` value uses the regular
/// representation of the deserialized, embedded message, with an
/// additional field `@type` which contains the type URL. Example:
///
/// ```text
/// package google.profile;
/// message Person {
///   string first_name = 1;
///   string last_name = 2;
/// }
///
/// {
///   "@type": "type.googleapis.com/google.profile.Person",
///   "firstName": <string>,
///   "lastName": <string>
/// }
/// ```
///
/// If the embedded message type is well-known and has a custom JSON
/// representation, that representation will be embedded adding a field
/// `value` which holds the custom JSON in addition to the `@type`
/// field. Example (for message [google.protobuf.Duration](crate::google::protobuf::Duration)):
///
/// ```text
/// {
///   "@type": "type.googleapis.com/google.protobuf.Duration",
///   "value": "1.212s"
/// }
/// ```
#[derive(Clone, Debug, Default)]
pub struct AnyView<'a> {
    /// A URL/resource name that uniquely identifies the type of the serialized
    /// protocol buffer message. This string must contain at least
    /// one "/" character. The last segment of the URL's path must represent
    /// the fully qualified name of the type (as in
    /// `path/google.protobuf.Duration`). The name should be in a canonical form
    /// (e.g., leading "." is not accepted).
    ///
    /// In practice, teams usually precompile into the binary all types that they
    /// expect it to use in the context of Any. However, for URLs which use the
    /// scheme `http`, `https`, or no scheme, one can optionally set up a type
    /// server that maps type URLs to message definitions as follows:
    ///
    /// * If no scheme is provided, `https` is assumed.
    /// * An HTTP GET on the URL must yield a [google.protobuf.Type](crate::google::protobuf::Type)
    ///   value in binary format, or produce an error.
    /// * Applications are allowed to cache lookup results based on the
    ///   URL, or have them precompiled into a binary to avoid any
    ///   lookup. Therefore, binary compatibility needs to be preserved
    ///   on changes to types. (Use versioned type names to manage
    ///   breaking changes.)
    ///
    /// Note: this functionality is not currently available in the official
    /// protobuf release, and it is not used for type URLs beginning with
    /// type.googleapis.com. As of May 2023, there are no widely used type server
    /// implementations and no plans to implement one.
    ///
    /// Schemes other than `http`, `https` (or the empty scheme) might be
    /// used with implementation specific semantics.
    ///
    /// Field 1: `type_url`
    pub type_url: &'a str,
    /// Must be a valid serialized protocol buffer of the above specified type.
    ///
    /// Field 2: `value`
    pub value: &'a [u8],
    pub __buffa_unknown_fields: ::buffa::UnknownFieldsView<'a>,
}
impl<'a> ::buffa::MessageView<'a> for AnyView<'a> {
    type Owned = super::super::Any;
    fn decode_view(buf: &'a [u8]) -> ::core::result::Result<Self, ::buffa::DecodeError> {
        let __limit = ::core::cell::Cell::new(::buffa::DEFAULT_UNKNOWN_FIELD_LIMIT);
        let __elem = ::core::cell::Cell::new(::buffa::DEFAULT_ELEMENT_MEMORY_LIMIT);
        <Self as ::buffa::MessageView>::decode_view_ctx(
            buf,
            ::buffa::DecodeContext::new(::buffa::RECURSION_LIMIT, &__limit)
                .with_element_memory(&__elem),
        )
    }
    fn decode_view_with_ctx(
        buf: &'a [u8],
        ctx: ::buffa::DecodeContext<'_>,
    ) -> ::core::result::Result<Self, ::buffa::DecodeError> {
        <Self as ::buffa::MessageView>::decode_view_ctx(buf, ctx)
    }
    #[inline]
    fn merge_view_field(
        &mut self,
        tag: ::buffa::encoding::Tag,
        cur: &'a [u8],
        before_tag: &'a [u8],
        ctx: ::buffa::DecodeContext<'_>,
    ) -> ::core::result::Result<&'a [u8], ::buffa::DecodeError> {
        let _ = ctx;
        #[allow(unused_variables)]
        let view = self;
        let mut cur = cur;
        match tag.field_number() {
            1u32 => {
                ::buffa::encoding::check_wire_type(
                    tag,
                    ::buffa::encoding::WireType::LengthDelimited,
                )?;
                view.type_url = ::buffa::types::borrow_str(&mut cur)?;
            }
            2u32 => {
                ::buffa::encoding::check_wire_type(
                    tag,
                    ::buffa::encoding::WireType::LengthDelimited,
                )?;
                view.value = ::buffa::types::borrow_bytes(&mut cur)?;
            }
            _ => {
                ::buffa::encoding::skip_field_depth(tag, &mut cur, ctx.depth())?;
                let span_len = before_tag.len() - cur.len();
                view.__buffa_unknown_fields.push_record(before_tag, span_len, ctx)?;
            }
        }
        ::core::result::Result::Ok(cur)
    }
    fn to_owned_message(
        &self,
    ) -> ::core::result::Result<super::super::Any, ::buffa::DecodeError> {
        self.to_owned_from_source(None)
    }
    #[allow(clippy::useless_conversion, clippy::needless_update)]
    fn to_owned_from_source(
        &self,
        __buffa_src: ::core::option::Option<&::buffa::bytes::Bytes>,
    ) -> ::core::result::Result<super::super::Any, ::buffa::DecodeError> {
        #[allow(unused_imports)]
        use ::buffa::alloc::string::ToString as _;
        let _ = __buffa_src;
        ::core::result::Result::Ok(super::super::Any {
            type_url: self.type_url.to_string(),
            value: ::buffa::view::bytes_from_source(__buffa_src, self.value),
            __buffa_unknown_fields: self.__buffa_unknown_fields.to_owned()?.into(),
            ..::core::default::Default::default()
        })
    }
}
impl<'a> ::buffa::ViewEncode<'a> for AnyView<'a> {
    #[allow(clippy::needless_borrow, clippy::let_and_return)]
    fn compute_size(&self, _cache: &mut ::buffa::SizeCache) -> u32 {
        #[allow(unused_imports)]
        use ::buffa::Enumeration as _;
        let mut size = 0u64;
        if !self.type_url.is_empty() {
            size += 1u64 + ::buffa::types::string_encoded_len(&self.type_url) as u64;
        }
        if !self.value.is_empty() {
            size += 1u64 + ::buffa::types::bytes_encoded_len(&self.value) as u64;
        }
        size += self.__buffa_unknown_fields.encoded_len() as u64;
        ::buffa::saturate_size(size)
    }
    #[allow(clippy::needless_borrow)]
    fn write_to(
        &self,
        _cache: &mut ::buffa::SizeCache,
        buf: &mut impl ::buffa::EncodeSink,
    ) {
        #[allow(unused_imports)]
        use ::buffa::Enumeration as _;
        if !self.type_url.is_empty() {
            ::buffa::types::put_string_field(1u32, &self.type_url, buf);
        }
        if !self.value.is_empty() {
            ::buffa::types::put_shared_bytes_field(2u32, &self.value, buf);
        }
        self.__buffa_unknown_fields.write_to(buf);
    }
}
impl<'a> ::buffa::MessageName for AnyView<'a> {
    const PACKAGE: &'static str = "google.protobuf";
    const NAME: &'static str = "Any";
    const FULL_NAME: &'static str = "google.protobuf.Any";
    const TYPE_URL: &'static str = "type.googleapis.com/google.protobuf.Any";
}
::buffa::impl_default_view_instance!(AnyView);
::buffa::impl_view_reborrow!(AnyView);
/** Self-contained, `'static` owned view of a `Any` message.

 Wraps [`::buffa::OwnedView`]`<`[`AnyView`]`<'static>>`: the decoded view and the [`::buffa::bytes::Bytes`] buffer it borrows from travel together, so the handle is `'static` and `Send + Sync` — suitable for async handlers, spawned tasks, and anywhere a `'static` bound is required.

 Field accessors return borrows tied to `&self`. Use [`Self::view`] to get the full [`AnyView`] when you need struct patterns, iteration helpers, or to pass the view to lifetime-parameterised code.*/
#[derive(Clone, Debug)]
pub struct AnyOwnedView(::buffa::OwnedView<AnyView<'static>>);
impl AnyOwnedView {
    /// Decode an owned view from a [`::buffa::bytes::Bytes`] buffer.
    ///
    /// The view borrows directly from the buffer's data; the buffer is
    /// retained inside the returned handle.
    ///
    /// # Errors
    ///
    /// Returns [`::buffa::DecodeError`] if the buffer contains invalid
    /// protobuf data.
    pub fn decode(
        bytes: ::buffa::bytes::Bytes,
    ) -> ::core::result::Result<Self, ::buffa::DecodeError> {
        ::core::result::Result::Ok(AnyOwnedView(::buffa::OwnedView::decode(bytes)?))
    }
    /// Decode with custom [`::buffa::DecodeOptions`] (recursion limit,
    /// max message size).
    ///
    /// # Errors
    ///
    /// Returns [`::buffa::DecodeError`] if the buffer is invalid or
    /// exceeds the configured limits.
    pub fn decode_with_options(
        bytes: ::buffa::bytes::Bytes,
        opts: &::buffa::DecodeOptions,
    ) -> ::core::result::Result<Self, ::buffa::DecodeError> {
        ::core::result::Result::Ok(
            AnyOwnedView(::buffa::OwnedView::decode_with_options(bytes, opts)?),
        )
    }
    /// Build from an owned message via an encode → decode round-trip.
    ///
    /// # Errors
    ///
    /// Returns [`::buffa::DecodeError::MessageTooLarge`] if the
    /// message's encoded size exceeds the 2 GiB protobuf limit, or
    /// another [`::buffa::DecodeError`] if the re-encoded bytes are
    /// somehow invalid (should not happen for well-formed messages).
    pub fn from_owned(
        msg: &super::super::Any,
    ) -> ::core::result::Result<Self, ::buffa::DecodeError> {
        ::core::result::Result::Ok(AnyOwnedView(::buffa::OwnedView::from_owned(msg)?))
    }
    /// Borrow the full [`AnyView`] with its lifetime tied to `&self`.
    #[must_use]
    pub fn view(&self) -> &AnyView<'_> {
        self.0.reborrow()
    }
    /// Convert to the owned message type.
    ///
    /// Infallible: this type's constructors wire-decode their
    /// buffer, and a view produced by wire decoding always
    /// converts. Delegates to [`::buffa::OwnedView::to_owned_message`],
    /// whose contract also governs handles converted from a raw
    /// [`::buffa::OwnedView`].
    #[must_use]
    pub fn to_owned_message(&self) -> super::super::Any {
        self.0.to_owned_message()
    }
    /// The underlying bytes buffer.
    #[must_use]
    pub fn bytes(&self) -> &::buffa::bytes::Bytes {
        self.0.bytes()
    }
    /// Consume the handle, returning the underlying bytes buffer.
    #[must_use]
    pub fn into_bytes(self) -> ::buffa::bytes::Bytes {
        self.0.into_bytes()
    }
    /// A URL/resource name that uniquely identifies the type of the serialized
    /// protocol buffer message. This string must contain at least
    /// one "/" character. The last segment of the URL's path must represent
    /// the fully qualified name of the type (as in
    /// `path/google.protobuf.Duration`). The name should be in a canonical form
    /// (e.g., leading "." is not accepted).
    ///
    /// In practice, teams usually precompile into the binary all types that they
    /// expect it to use in the context of Any. However, for URLs which use the
    /// scheme `http`, `https`, or no scheme, one can optionally set up a type
    /// server that maps type URLs to message definitions as follows:
    ///
    /// * If no scheme is provided, `https` is assumed.
    /// * An HTTP GET on the URL must yield a [google.protobuf.Type](crate::google::protobuf::Type)
    ///   value in binary format, or produce an error.
    /// * Applications are allowed to cache lookup results based on the
    ///   URL, or have them precompiled into a binary to avoid any
    ///   lookup. Therefore, binary compatibility needs to be preserved
    ///   on changes to types. (Use versioned type names to manage
    ///   breaking changes.)
    ///
    /// Note: this functionality is not currently available in the official
    /// protobuf release, and it is not used for type URLs beginning with
    /// type.googleapis.com. As of May 2023, there are no widely used type server
    /// implementations and no plans to implement one.
    ///
    /// Schemes other than `http`, `https` (or the empty scheme) might be
    /// used with implementation specific semantics.
    ///
    /// Field 1: `type_url`
    #[must_use]
    pub fn type_url(&self) -> &'_ str {
        self.0.reborrow().type_url
    }
    /// Must be a valid serialized protocol buffer of the above specified type.
    ///
    /// Field 2: `value`
    #[must_use]
    pub fn value(&self) -> &'_ [u8] {
        self.0.reborrow().value
    }
}
impl ::core::convert::From<::buffa::OwnedView<AnyView<'static>>> for AnyOwnedView {
    fn from(inner: ::buffa::OwnedView<AnyView<'static>>) -> Self {
        AnyOwnedView(inner)
    }
}
impl ::core::convert::From<AnyOwnedView> for ::buffa::OwnedView<AnyView<'static>> {
    fn from(wrapper: AnyOwnedView) -> Self {
        wrapper.0
    }
}
impl ::core::convert::AsRef<::buffa::OwnedView<AnyView<'static>>> for AnyOwnedView {
    fn as_ref(&self) -> &::buffa::OwnedView<AnyView<'static>> {
        &self.0
    }
}
impl ::buffa::HasMessageView for super::super::Any {
    type View<'a> = AnyView<'a>;
    type ViewHandle = AnyOwnedView;
}
#[cfg(feature = "reflect")]
const _: () = {
    impl<'a> ::buffa_descriptor::reflect::ReflectMessage for AnyView<'a> {
        fn message_descriptor(&self) -> &::buffa_descriptor::MessageDescriptor {
            super::super::__buffa::reflect::descriptor_pool()
                .message(Self::__buffa_reflect_message_index())
        }
        fn pool(
            &self,
        ) -> &::buffa::alloc::sync::Arc<::buffa_descriptor::DescriptorPool> {
            super::super::__buffa::reflect::descriptor_pool()
        }
        fn get(
            &self,
            field: &::buffa_descriptor::FieldDescriptor,
        ) -> ::buffa_descriptor::reflect::ValueRef<'_> {
            #[allow(unused_imports)]
            use ::buffa::Enumeration as _;
            match field.number() {
                1u32 => ::buffa_descriptor::reflect::ValueRef::String(self.type_url),
                2u32 => ::buffa_descriptor::reflect::ValueRef::Bytes(self.value),
                _ => {
                    ::core::debug_assert!(
                        false,
                        "field number {} is not a member of this view's reflect get()",
                        field.number(),
                    );
                    ::buffa_descriptor::reflect::ValueRef::Bool(false)
                }
            }
        }
        fn has(&self, field: &::buffa_descriptor::FieldDescriptor) -> bool {
            match field.number() {
                1u32 => !self.type_url.is_empty(),
                2u32 => !self.value.is_empty(),
                _ => false,
            }
        }
        fn for_each_set(
            &self,
            f: &mut dyn ::core::ops::FnMut(
                &::buffa_descriptor::FieldDescriptor,
                ::buffa_descriptor::reflect::ValueRef<'_>,
            ),
        ) {
            let md = ::buffa_descriptor::reflect::ReflectMessage::message_descriptor(
                self,
            );
            for fd in md.fields() {
                if ::buffa_descriptor::reflect::ReflectMessage::has(self, fd) {
                    f(fd, ::buffa_descriptor::reflect::ReflectMessage::get(self, fd));
                }
            }
        }
        fn to_dynamic(&self) -> ::buffa_descriptor::reflect::DynamicMessage {
            let bytes = ::buffa::ViewEncode::encode_to_vec(self);
            let options = ::buffa::DecodeOptions::new()
                .with_element_memory_limit(
                    bytes
                        .len()
                        .saturating_mul(128)
                        .max(::buffa::DEFAULT_ELEMENT_MEMORY_LIMIT),
                )
                .with_unknown_field_limit(
                    bytes.len().max(::buffa::DEFAULT_UNKNOWN_FIELD_LIMIT),
                );
            ::buffa_descriptor::reflect::DynamicMessage::decode_with_options(
                    ::buffa::alloc::sync::Arc::clone(
                        super::super::__buffa::reflect::descriptor_pool(),
                    ),
                    Self::__buffa_reflect_message_index(),
                    &bytes,
                    &options,
                )
                .expect("view re-encodes to bytes decodable against its own descriptor")
        }
    }
    impl<'a> ::buffa_descriptor::reflect::ReflectElement for AnyView<'a> {
        fn as_value_ref(&self) -> ::buffa_descriptor::reflect::ValueRef<'_> {
            ::buffa_descriptor::reflect::ValueRef::Message(
                ::buffa_descriptor::reflect::ReflectCow::Borrowed(self),
            )
        }
    }
    impl<'a> AnyView<'a> {
        /// Memoized `MessageIndex` for this view's message type, resolved
        /// once against the package's embedded descriptor pool. An inherent
        /// associated fn (not a free fn) so sibling views in the same module
        /// do not collide.
        #[doc(hidden)]
        fn __buffa_reflect_message_index() -> ::buffa_descriptor::MessageIndex {
            static IDX: ::std::sync::OnceLock<::buffa_descriptor::MessageIndex> = ::std::sync::OnceLock::new();
            *IDX
                .get_or_init(|| {
                    super::super::__buffa::reflect::descriptor_pool()
                        .message_index(<Self as ::buffa::MessageName>::FULL_NAME)
                        .expect(
                            "generated view type is registered in the embedded descriptor pool",
                        )
                })
        }
    }
};