Skip to main content

buffa_types/generated/
google.protobuf.duration.__view.rs

1// @generated by buffa-codegen. DO NOT EDIT.
2// source: google/protobuf/duration.proto
3
4/// A Duration represents a signed, fixed-length span of time represented
5/// as a count of seconds and fractions of seconds at nanosecond
6/// resolution. It is independent of any calendar and concepts like "day"
7/// or "month". It is related to Timestamp in that the difference between
8/// two Timestamp values is a Duration and it can be added or subtracted
9/// from a Timestamp. Range is approximately +-10,000 years.
10///
11/// # Examples
12///
13/// Example 1: Compute Duration from two Timestamps in pseudo code.
14///
15/// ```text
16/// Timestamp start = ...;
17/// Timestamp end = ...;
18/// Duration duration = ...;
19///
20/// duration.seconds = end.seconds - start.seconds;
21/// duration.nanos = end.nanos - start.nanos;
22///
23/// if (duration.seconds < 0 && duration.nanos > 0) {
24///   duration.seconds += 1;
25///   duration.nanos -= 1000000000;
26/// } else if (duration.seconds > 0 && duration.nanos < 0) {
27///   duration.seconds -= 1;
28///   duration.nanos += 1000000000;
29/// }
30/// ```
31///
32/// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
33///
34/// ```text
35/// Timestamp start = ...;
36/// Duration duration = ...;
37/// Timestamp end = ...;
38///
39/// end.seconds = start.seconds + duration.seconds;
40/// end.nanos = start.nanos + duration.nanos;
41///
42/// if (end.nanos < 0) {
43///   end.seconds -= 1;
44///   end.nanos += 1000000000;
45/// } else if (end.nanos >= 1000000000) {
46///   end.seconds += 1;
47///   end.nanos -= 1000000000;
48/// }
49/// ```
50///
51/// Example 3: Compute Duration from datetime.timedelta in Python.
52///
53/// ```text
54/// td = datetime.timedelta(days=3, minutes=10)
55/// duration = Duration()
56/// duration.FromTimedelta(td)
57/// ```
58///
59/// # JSON Mapping
60///
61/// In JSON format, the Duration type is encoded as a string rather than an
62/// object, where the string ends in the suffix "s" (indicating seconds) and
63/// is preceded by the number of seconds, with nanoseconds expressed as
64/// fractional seconds. For example, 3 seconds with 0 nanoseconds should be
65/// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
66/// be expressed in JSON format as "3.000000001s", and 3 seconds and 1
67/// microsecond should be expressed in JSON format as "3.000001s".
68#[derive(Clone, Debug, Default)]
69pub struct DurationView<'a> {
70    /// Signed seconds of the span of time. Must be from -315,576,000,000
71    /// to +315,576,000,000 inclusive. Note: these bounds are computed from:
72    /// 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
73    ///
74    /// Field 1: `seconds`
75    pub seconds: i64,
76    /// Signed fractions of a second at nanosecond resolution of the span
77    /// of time. Durations less than one second are represented with a 0
78    /// `seconds` field and a positive or negative `nanos` field. For durations
79    /// of one second or more, a non-zero value for the `nanos` field must be
80    /// of the same sign as the `seconds` field. Must be from -999,999,999
81    /// to +999,999,999 inclusive.
82    ///
83    /// Field 2: `nanos`
84    pub nanos: i32,
85    pub __buffa_unknown_fields: ::buffa::UnknownFieldsView<'a>,
86}
87impl<'a> DurationView<'a> {
88    /// Decode from `buf`, enforcing a recursion depth limit for nested messages.
89    ///
90    /// Called by [`::buffa::MessageView::decode_view`] with [`::buffa::RECURSION_LIMIT`]
91    /// and by generated sub-message decode arms with `depth - 1`.
92    ///
93    /// **Not part of the public API.** Named with a leading underscore to
94    /// signal that it is for generated-code use only.
95    #[doc(hidden)]
96    pub fn _decode_depth(
97        buf: &'a [u8],
98        depth: u32,
99    ) -> ::core::result::Result<Self, ::buffa::DecodeError> {
100        let mut view = Self::default();
101        view._merge_into_view(buf, depth)?;
102        ::core::result::Result::Ok(view)
103    }
104    /// Merge fields from `buf` into this view (proto merge semantics).
105    ///
106    /// Repeated fields append; singular fields last-wins; singular
107    /// MESSAGE fields merge recursively. Used by sub-message decode
108    /// arms when the same field appears multiple times on the wire.
109    ///
110    /// **Not part of the public API.**
111    #[doc(hidden)]
112    pub fn _merge_into_view(
113        &mut self,
114        buf: &'a [u8],
115        depth: u32,
116    ) -> ::core::result::Result<(), ::buffa::DecodeError> {
117        let _ = depth;
118        #[allow(unused_variables)]
119        let view = self;
120        let mut cur: &'a [u8] = buf;
121        while !cur.is_empty() {
122            let before_tag = cur;
123            let tag = ::buffa::encoding::Tag::decode(&mut cur)?;
124            match tag.field_number() {
125                1u32 => {
126                    if tag.wire_type() != ::buffa::encoding::WireType::Varint {
127                        return ::core::result::Result::Err(::buffa::DecodeError::WireTypeMismatch {
128                            field_number: 1u32,
129                            expected: 0u8,
130                            actual: tag.wire_type() as u8,
131                        });
132                    }
133                    view.seconds = ::buffa::types::decode_int64(&mut cur)?;
134                }
135                2u32 => {
136                    if tag.wire_type() != ::buffa::encoding::WireType::Varint {
137                        return ::core::result::Result::Err(::buffa::DecodeError::WireTypeMismatch {
138                            field_number: 2u32,
139                            expected: 0u8,
140                            actual: tag.wire_type() as u8,
141                        });
142                    }
143                    view.nanos = ::buffa::types::decode_int32(&mut cur)?;
144                }
145                _ => {
146                    ::buffa::encoding::skip_field_depth(tag, &mut cur, depth)?;
147                    let span_len = before_tag.len() - cur.len();
148                    view.__buffa_unknown_fields.push_raw(&before_tag[..span_len]);
149                }
150            }
151        }
152        ::core::result::Result::Ok(())
153    }
154}
155impl<'a> ::buffa::MessageView<'a> for DurationView<'a> {
156    type Owned = super::super::Duration;
157    fn decode_view(buf: &'a [u8]) -> ::core::result::Result<Self, ::buffa::DecodeError> {
158        Self::_decode_depth(buf, ::buffa::RECURSION_LIMIT)
159    }
160    fn decode_view_with_limit(
161        buf: &'a [u8],
162        depth: u32,
163    ) -> ::core::result::Result<Self, ::buffa::DecodeError> {
164        Self::_decode_depth(buf, depth)
165    }
166    fn to_owned_message(&self) -> super::super::Duration {
167        self.to_owned_from_source(None)
168    }
169    #[allow(clippy::useless_conversion, clippy::needless_update)]
170    fn to_owned_from_source(
171        &self,
172        __buffa_src: ::core::option::Option<&::buffa::bytes::Bytes>,
173    ) -> super::super::Duration {
174        #[allow(unused_imports)]
175        use ::buffa::alloc::string::ToString as _;
176        let _ = __buffa_src;
177        super::super::Duration {
178            seconds: self.seconds,
179            nanos: self.nanos,
180            __buffa_unknown_fields: self
181                .__buffa_unknown_fields
182                .to_owned()
183                .unwrap_or_default()
184                .into(),
185            ..::core::default::Default::default()
186        }
187    }
188}
189impl<'a> ::buffa::ViewEncode<'a> for DurationView<'a> {
190    #[allow(clippy::needless_borrow, clippy::let_and_return)]
191    fn compute_size(&self, _cache: &mut ::buffa::SizeCache) -> u32 {
192        #[allow(unused_imports)]
193        use ::buffa::Enumeration as _;
194        let mut size = 0u32;
195        if self.seconds != 0i64 {
196            size += 1u32 + ::buffa::types::int64_encoded_len(self.seconds) as u32;
197        }
198        if self.nanos != 0i32 {
199            size += 1u32 + ::buffa::types::int32_encoded_len(self.nanos) as u32;
200        }
201        size += self.__buffa_unknown_fields.encoded_len() as u32;
202        size
203    }
204    #[allow(clippy::needless_borrow)]
205    fn write_to(
206        &self,
207        _cache: &mut ::buffa::SizeCache,
208        buf: &mut impl ::buffa::bytes::BufMut,
209    ) {
210        #[allow(unused_imports)]
211        use ::buffa::Enumeration as _;
212        if self.seconds != 0i64 {
213            ::buffa::encoding::Tag::new(1u32, ::buffa::encoding::WireType::Varint)
214                .encode(buf);
215            ::buffa::types::encode_int64(self.seconds, buf);
216        }
217        if self.nanos != 0i32 {
218            ::buffa::encoding::Tag::new(2u32, ::buffa::encoding::WireType::Varint)
219                .encode(buf);
220            ::buffa::types::encode_int32(self.nanos, buf);
221        }
222        self.__buffa_unknown_fields.write_to(buf);
223    }
224}
225impl<'a> ::buffa::MessageName for DurationView<'a> {
226    const PACKAGE: &'static str = "google.protobuf";
227    const NAME: &'static str = "Duration";
228    const FULL_NAME: &'static str = "google.protobuf.Duration";
229    const TYPE_URL: &'static str = "type.googleapis.com/google.protobuf.Duration";
230}
231impl<'v> ::buffa::DefaultViewInstance for DurationView<'v> {
232    fn default_view_instance<'a>() -> &'a Self
233    where
234        Self: 'a,
235    {
236        static VALUE: ::buffa::__private::OnceBox<DurationView<'static>> = ::buffa::__private::OnceBox::new();
237        VALUE
238            .get_or_init(|| ::buffa::alloc::boxed::Box::new(
239                <DurationView<'static>>::default(),
240            ))
241    }
242}
243impl ::buffa::ViewReborrow for DurationView<'static> {
244    type Reborrowed<'b> = DurationView<'b>;
245    fn reborrow<'b>(this: &'b Self) -> &'b Self::Reborrowed<'b> {
246        this
247    }
248}
249/** Self-contained, `'static` owned view of a `Duration` message.
250
251 Wraps [`::buffa::OwnedView`]`<`[`DurationView`]`<'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.
252
253 Field accessors return borrows tied to `&self`. Use [`Self::view`] to get the full [`DurationView`] when you need struct patterns, iteration helpers, or to pass the view to lifetime-parameterised code.*/
254#[derive(Clone, Debug)]
255pub struct DurationOwnedView(::buffa::OwnedView<DurationView<'static>>);
256impl DurationOwnedView {
257    /// Decode an owned view from a [`::buffa::bytes::Bytes`] buffer.
258    ///
259    /// The view borrows directly from the buffer's data; the buffer is
260    /// retained inside the returned handle.
261    ///
262    /// # Errors
263    ///
264    /// Returns [`::buffa::DecodeError`] if the buffer contains invalid
265    /// protobuf data.
266    pub fn decode(
267        bytes: ::buffa::bytes::Bytes,
268    ) -> ::core::result::Result<Self, ::buffa::DecodeError> {
269        ::core::result::Result::Ok(DurationOwnedView(::buffa::OwnedView::decode(bytes)?))
270    }
271    /// Decode with custom [`::buffa::DecodeOptions`] (recursion limit,
272    /// max message size).
273    ///
274    /// # Errors
275    ///
276    /// Returns [`::buffa::DecodeError`] if the buffer is invalid or
277    /// exceeds the configured limits.
278    pub fn decode_with_options(
279        bytes: ::buffa::bytes::Bytes,
280        opts: &::buffa::DecodeOptions,
281    ) -> ::core::result::Result<Self, ::buffa::DecodeError> {
282        ::core::result::Result::Ok(
283            DurationOwnedView(::buffa::OwnedView::decode_with_options(bytes, opts)?),
284        )
285    }
286    /// Build from an owned message via an encode → decode round-trip.
287    ///
288    /// # Errors
289    ///
290    /// Returns [`::buffa::DecodeError`] if the re-encoded bytes are
291    /// somehow invalid (should not happen for well-formed messages).
292    pub fn from_owned(
293        msg: &super::super::Duration,
294    ) -> ::core::result::Result<Self, ::buffa::DecodeError> {
295        ::core::result::Result::Ok(
296            DurationOwnedView(::buffa::OwnedView::from_owned(msg)?),
297        )
298    }
299    /// Borrow the full [`DurationView`] with its lifetime tied to `&self`.
300    #[must_use]
301    pub fn view(&self) -> &DurationView<'_> {
302        self.0.reborrow()
303    }
304    /// Convert to the owned message type.
305    #[must_use]
306    pub fn to_owned_message(&self) -> super::super::Duration {
307        self.0.to_owned_message()
308    }
309    /// The underlying bytes buffer.
310    #[must_use]
311    pub fn bytes(&self) -> &::buffa::bytes::Bytes {
312        self.0.bytes()
313    }
314    /// Consume the handle, returning the underlying bytes buffer.
315    #[must_use]
316    pub fn into_bytes(self) -> ::buffa::bytes::Bytes {
317        self.0.into_bytes()
318    }
319    /// Signed seconds of the span of time. Must be from -315,576,000,000
320    /// to +315,576,000,000 inclusive. Note: these bounds are computed from:
321    /// 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
322    ///
323    /// Field 1: `seconds`
324    #[must_use]
325    pub fn seconds(&self) -> i64 {
326        self.0.reborrow().seconds
327    }
328    /// Signed fractions of a second at nanosecond resolution of the span
329    /// of time. Durations less than one second are represented with a 0
330    /// `seconds` field and a positive or negative `nanos` field. For durations
331    /// of one second or more, a non-zero value for the `nanos` field must be
332    /// of the same sign as the `seconds` field. Must be from -999,999,999
333    /// to +999,999,999 inclusive.
334    ///
335    /// Field 2: `nanos`
336    #[must_use]
337    pub fn nanos(&self) -> i32 {
338        self.0.reborrow().nanos
339    }
340}
341impl ::core::convert::From<::buffa::OwnedView<DurationView<'static>>>
342for DurationOwnedView {
343    fn from(inner: ::buffa::OwnedView<DurationView<'static>>) -> Self {
344        DurationOwnedView(inner)
345    }
346}
347impl ::core::convert::From<DurationOwnedView>
348for ::buffa::OwnedView<DurationView<'static>> {
349    fn from(wrapper: DurationOwnedView) -> Self {
350        wrapper.0
351    }
352}
353impl ::core::convert::AsRef<::buffa::OwnedView<DurationView<'static>>>
354for DurationOwnedView {
355    fn as_ref(&self) -> &::buffa::OwnedView<DurationView<'static>> {
356        &self.0
357    }
358}
359impl ::buffa::HasMessageView for super::super::Duration {
360    type View<'a> = DurationView<'a>;
361    type ViewHandle = DurationOwnedView;
362}
363#[cfg(feature = "reflect")]
364const _: () = {
365    impl<'a> ::buffa_descriptor::reflect::ReflectMessage for DurationView<'a> {
366        fn message_descriptor(&self) -> &::buffa_descriptor::MessageDescriptor {
367            super::super::__buffa::reflect::descriptor_pool()
368                .message(Self::__buffa_reflect_message_index())
369        }
370        fn pool(
371            &self,
372        ) -> &::buffa::alloc::sync::Arc<::buffa_descriptor::DescriptorPool> {
373            super::super::__buffa::reflect::descriptor_pool()
374        }
375        fn get(
376            &self,
377            field: &::buffa_descriptor::FieldDescriptor,
378        ) -> ::buffa_descriptor::reflect::ValueRef<'_> {
379            #[allow(unused_imports)]
380            use ::buffa::Enumeration as _;
381            match field.number() {
382                1u32 => ::buffa_descriptor::reflect::ValueRef::I64(self.seconds),
383                2u32 => ::buffa_descriptor::reflect::ValueRef::I32(self.nanos),
384                _ => {
385                    ::core::debug_assert!(
386                        false,
387                        "field number {} is not a member of this view's reflect get()",
388                        field.number(),
389                    );
390                    ::buffa_descriptor::reflect::ValueRef::Bool(false)
391                }
392            }
393        }
394        fn has(&self, field: &::buffa_descriptor::FieldDescriptor) -> bool {
395            match field.number() {
396                1u32 => self.seconds != 0,
397                2u32 => self.nanos != 0,
398                _ => false,
399            }
400        }
401        fn for_each_set(
402            &self,
403            f: &mut dyn ::core::ops::FnMut(
404                &::buffa_descriptor::FieldDescriptor,
405                ::buffa_descriptor::reflect::ValueRef<'_>,
406            ),
407        ) {
408            let md = ::buffa_descriptor::reflect::ReflectMessage::message_descriptor(
409                self,
410            );
411            for fd in md.fields() {
412                if ::buffa_descriptor::reflect::ReflectMessage::has(self, fd) {
413                    f(fd, ::buffa_descriptor::reflect::ReflectMessage::get(self, fd));
414                }
415            }
416        }
417        fn to_dynamic(&self) -> ::buffa_descriptor::reflect::DynamicMessage {
418            let bytes = ::buffa::ViewEncode::encode_to_vec(self);
419            ::buffa_descriptor::reflect::DynamicMessage::decode(
420                    ::buffa::alloc::sync::Arc::clone(
421                        super::super::__buffa::reflect::descriptor_pool(),
422                    ),
423                    Self::__buffa_reflect_message_index(),
424                    &bytes,
425                )
426                .expect("view re-encodes to bytes decodable against its own descriptor")
427        }
428    }
429    impl<'a> ::buffa_descriptor::reflect::ReflectElement for DurationView<'a> {
430        fn as_value_ref(&self) -> ::buffa_descriptor::reflect::ValueRef<'_> {
431            ::buffa_descriptor::reflect::ValueRef::Message(
432                ::buffa_descriptor::reflect::ReflectCow::Borrowed(self),
433            )
434        }
435    }
436    impl<'a> DurationView<'a> {
437        /// Memoized `MessageIndex` for this view's message type, resolved
438        /// once against the package's embedded descriptor pool. An inherent
439        /// associated fn (not a free fn) so sibling views in the same module
440        /// do not collide.
441        #[doc(hidden)]
442        fn __buffa_reflect_message_index() -> ::buffa_descriptor::MessageIndex {
443            static IDX: ::std::sync::OnceLock<::buffa_descriptor::MessageIndex> = ::std::sync::OnceLock::new();
444            *IDX
445                .get_or_init(|| {
446                    super::super::__buffa::reflect::descriptor_pool()
447                        .message_index(<Self as ::buffa::MessageName>::FULL_NAME)
448                        .expect(
449                            "generated view type is registered in the embedded descriptor pool",
450                        )
451                })
452        }
453    }
454};