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> ::buffa::MessageView<'a> for DurationView<'a> {
88    type Owned = super::super::Duration;
89    fn decode_view(buf: &'a [u8]) -> ::core::result::Result<Self, ::buffa::DecodeError> {
90        let __limit = ::core::cell::Cell::new(::buffa::DEFAULT_UNKNOWN_FIELD_LIMIT);
91        let __elem = ::core::cell::Cell::new(::buffa::DEFAULT_ELEMENT_MEMORY_LIMIT);
92        <Self as ::buffa::MessageView>::decode_view_ctx(
93            buf,
94            ::buffa::DecodeContext::new(::buffa::RECURSION_LIMIT, &__limit)
95                .with_element_memory(&__elem),
96        )
97    }
98    fn decode_view_with_ctx(
99        buf: &'a [u8],
100        ctx: ::buffa::DecodeContext<'_>,
101    ) -> ::core::result::Result<Self, ::buffa::DecodeError> {
102        <Self as ::buffa::MessageView>::decode_view_ctx(buf, ctx)
103    }
104    #[inline]
105    fn merge_view_field(
106        &mut self,
107        tag: ::buffa::encoding::Tag,
108        cur: &'a [u8],
109        before_tag: &'a [u8],
110        ctx: ::buffa::DecodeContext<'_>,
111    ) -> ::core::result::Result<&'a [u8], ::buffa::DecodeError> {
112        let _ = ctx;
113        #[allow(unused_variables)]
114        let view = self;
115        let mut cur = cur;
116        match tag.field_number() {
117            1u32 => {
118                ::buffa::encoding::check_wire_type(
119                    tag,
120                    ::buffa::encoding::WireType::Varint,
121                )?;
122                view.seconds = ::buffa::types::decode_int64(&mut cur)?;
123            }
124            2u32 => {
125                ::buffa::encoding::check_wire_type(
126                    tag,
127                    ::buffa::encoding::WireType::Varint,
128                )?;
129                view.nanos = ::buffa::types::decode_int32(&mut cur)?;
130            }
131            _ => {
132                ::buffa::encoding::skip_field_depth(tag, &mut cur, ctx.depth())?;
133                let span_len = before_tag.len() - cur.len();
134                view.__buffa_unknown_fields.push_record(before_tag, span_len, ctx)?;
135            }
136        }
137        ::core::result::Result::Ok(cur)
138    }
139    fn to_owned_message(
140        &self,
141    ) -> ::core::result::Result<super::super::Duration, ::buffa::DecodeError> {
142        self.to_owned_from_source(None)
143    }
144    #[allow(clippy::useless_conversion, clippy::needless_update)]
145    fn to_owned_from_source(
146        &self,
147        __buffa_src: ::core::option::Option<&::buffa::bytes::Bytes>,
148    ) -> ::core::result::Result<super::super::Duration, ::buffa::DecodeError> {
149        #[allow(unused_imports)]
150        use ::buffa::alloc::string::ToString as _;
151        let _ = __buffa_src;
152        ::core::result::Result::Ok(super::super::Duration {
153            seconds: self.seconds,
154            nanos: self.nanos,
155            __buffa_unknown_fields: self.__buffa_unknown_fields.to_owned()?.into(),
156            ..::core::default::Default::default()
157        })
158    }
159}
160impl<'a> ::buffa::ViewEncode<'a> for DurationView<'a> {
161    #[allow(clippy::needless_borrow, clippy::let_and_return)]
162    fn compute_size(&self, _cache: &mut ::buffa::SizeCache) -> u32 {
163        #[allow(unused_imports)]
164        use ::buffa::Enumeration as _;
165        let mut size = 0u64;
166        if self.seconds != 0i64 {
167            size += 1u64 + ::buffa::types::int64_encoded_len(self.seconds) as u64;
168        }
169        if self.nanos != 0i32 {
170            size += 1u64 + ::buffa::types::int32_encoded_len(self.nanos) as u64;
171        }
172        size += self.__buffa_unknown_fields.encoded_len() as u64;
173        ::buffa::saturate_size(size)
174    }
175    #[allow(clippy::needless_borrow)]
176    fn write_to(
177        &self,
178        _cache: &mut ::buffa::SizeCache,
179        buf: &mut impl ::buffa::EncodeSink,
180    ) {
181        #[allow(unused_imports)]
182        use ::buffa::Enumeration as _;
183        if self.seconds != 0i64 {
184            ::buffa::types::put_int64_field(1u32, self.seconds, buf);
185        }
186        if self.nanos != 0i32 {
187            ::buffa::types::put_int32_field(2u32, self.nanos, buf);
188        }
189        self.__buffa_unknown_fields.write_to(buf);
190    }
191}
192impl<'a> ::buffa::MessageName for DurationView<'a> {
193    const PACKAGE: &'static str = "google.protobuf";
194    const NAME: &'static str = "Duration";
195    const FULL_NAME: &'static str = "google.protobuf.Duration";
196    const TYPE_URL: &'static str = "type.googleapis.com/google.protobuf.Duration";
197}
198::buffa::impl_default_view_instance!(DurationView);
199::buffa::impl_view_reborrow!(DurationView);
200/** Self-contained, `'static` owned view of a `Duration` message.
201
202 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.
203
204 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.*/
205#[derive(Clone, Debug)]
206pub struct DurationOwnedView(::buffa::OwnedView<DurationView<'static>>);
207impl DurationOwnedView {
208    /// Decode an owned view from a [`::buffa::bytes::Bytes`] buffer.
209    ///
210    /// The view borrows directly from the buffer's data; the buffer is
211    /// retained inside the returned handle.
212    ///
213    /// # Errors
214    ///
215    /// Returns [`::buffa::DecodeError`] if the buffer contains invalid
216    /// protobuf data.
217    pub fn decode(
218        bytes: ::buffa::bytes::Bytes,
219    ) -> ::core::result::Result<Self, ::buffa::DecodeError> {
220        ::core::result::Result::Ok(DurationOwnedView(::buffa::OwnedView::decode(bytes)?))
221    }
222    /// Decode with custom [`::buffa::DecodeOptions`] (recursion limit,
223    /// max message size).
224    ///
225    /// # Errors
226    ///
227    /// Returns [`::buffa::DecodeError`] if the buffer is invalid or
228    /// exceeds the configured limits.
229    pub fn decode_with_options(
230        bytes: ::buffa::bytes::Bytes,
231        opts: &::buffa::DecodeOptions,
232    ) -> ::core::result::Result<Self, ::buffa::DecodeError> {
233        ::core::result::Result::Ok(
234            DurationOwnedView(::buffa::OwnedView::decode_with_options(bytes, opts)?),
235        )
236    }
237    /// Build from an owned message via an encode → decode round-trip.
238    ///
239    /// # Errors
240    ///
241    /// Returns [`::buffa::DecodeError::MessageTooLarge`] if the
242    /// message's encoded size exceeds the 2 GiB protobuf limit, or
243    /// another [`::buffa::DecodeError`] if the re-encoded bytes are
244    /// somehow invalid (should not happen for well-formed messages).
245    pub fn from_owned(
246        msg: &super::super::Duration,
247    ) -> ::core::result::Result<Self, ::buffa::DecodeError> {
248        ::core::result::Result::Ok(
249            DurationOwnedView(::buffa::OwnedView::from_owned(msg)?),
250        )
251    }
252    /// Borrow the full [`DurationView`] with its lifetime tied to `&self`.
253    #[must_use]
254    pub fn view(&self) -> &DurationView<'_> {
255        self.0.reborrow()
256    }
257    /// Convert to the owned message type.
258    ///
259    /// Infallible: this type's constructors wire-decode their
260    /// buffer, and a view produced by wire decoding always
261    /// converts. Delegates to [`::buffa::OwnedView::to_owned_message`],
262    /// whose contract also governs handles converted from a raw
263    /// [`::buffa::OwnedView`].
264    #[must_use]
265    pub fn to_owned_message(&self) -> super::super::Duration {
266        self.0.to_owned_message()
267    }
268    /// The underlying bytes buffer.
269    #[must_use]
270    pub fn bytes(&self) -> &::buffa::bytes::Bytes {
271        self.0.bytes()
272    }
273    /// Consume the handle, returning the underlying bytes buffer.
274    #[must_use]
275    pub fn into_bytes(self) -> ::buffa::bytes::Bytes {
276        self.0.into_bytes()
277    }
278    /// Signed seconds of the span of time. Must be from -315,576,000,000
279    /// to +315,576,000,000 inclusive. Note: these bounds are computed from:
280    /// 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
281    ///
282    /// Field 1: `seconds`
283    #[must_use]
284    pub fn seconds(&self) -> i64 {
285        self.0.reborrow().seconds
286    }
287    /// Signed fractions of a second at nanosecond resolution of the span
288    /// of time. Durations less than one second are represented with a 0
289    /// `seconds` field and a positive or negative `nanos` field. For durations
290    /// of one second or more, a non-zero value for the `nanos` field must be
291    /// of the same sign as the `seconds` field. Must be from -999,999,999
292    /// to +999,999,999 inclusive.
293    ///
294    /// Field 2: `nanos`
295    #[must_use]
296    pub fn nanos(&self) -> i32 {
297        self.0.reborrow().nanos
298    }
299}
300impl ::core::convert::From<::buffa::OwnedView<DurationView<'static>>>
301for DurationOwnedView {
302    fn from(inner: ::buffa::OwnedView<DurationView<'static>>) -> Self {
303        DurationOwnedView(inner)
304    }
305}
306impl ::core::convert::From<DurationOwnedView>
307for ::buffa::OwnedView<DurationView<'static>> {
308    fn from(wrapper: DurationOwnedView) -> Self {
309        wrapper.0
310    }
311}
312impl ::core::convert::AsRef<::buffa::OwnedView<DurationView<'static>>>
313for DurationOwnedView {
314    fn as_ref(&self) -> &::buffa::OwnedView<DurationView<'static>> {
315        &self.0
316    }
317}
318impl ::buffa::HasMessageView for super::super::Duration {
319    type View<'a> = DurationView<'a>;
320    type ViewHandle = DurationOwnedView;
321}
322#[cfg(feature = "reflect")]
323const _: () = {
324    impl<'a> ::buffa_descriptor::reflect::ReflectMessage for DurationView<'a> {
325        fn message_descriptor(&self) -> &::buffa_descriptor::MessageDescriptor {
326            super::super::__buffa::reflect::descriptor_pool()
327                .message(Self::__buffa_reflect_message_index())
328        }
329        fn pool(
330            &self,
331        ) -> &::buffa::alloc::sync::Arc<::buffa_descriptor::DescriptorPool> {
332            super::super::__buffa::reflect::descriptor_pool()
333        }
334        fn get(
335            &self,
336            field: &::buffa_descriptor::FieldDescriptor,
337        ) -> ::buffa_descriptor::reflect::ValueRef<'_> {
338            #[allow(unused_imports)]
339            use ::buffa::Enumeration as _;
340            match field.number() {
341                1u32 => ::buffa_descriptor::reflect::ValueRef::I64(self.seconds),
342                2u32 => ::buffa_descriptor::reflect::ValueRef::I32(self.nanos),
343                _ => {
344                    ::core::debug_assert!(
345                        false,
346                        "field number {} is not a member of this view's reflect get()",
347                        field.number(),
348                    );
349                    ::buffa_descriptor::reflect::ValueRef::Bool(false)
350                }
351            }
352        }
353        fn has(&self, field: &::buffa_descriptor::FieldDescriptor) -> bool {
354            match field.number() {
355                1u32 => self.seconds != 0,
356                2u32 => self.nanos != 0,
357                _ => false,
358            }
359        }
360        fn for_each_set(
361            &self,
362            f: &mut dyn ::core::ops::FnMut(
363                &::buffa_descriptor::FieldDescriptor,
364                ::buffa_descriptor::reflect::ValueRef<'_>,
365            ),
366        ) {
367            let md = ::buffa_descriptor::reflect::ReflectMessage::message_descriptor(
368                self,
369            );
370            for fd in md.fields() {
371                if ::buffa_descriptor::reflect::ReflectMessage::has(self, fd) {
372                    f(fd, ::buffa_descriptor::reflect::ReflectMessage::get(self, fd));
373                }
374            }
375        }
376        fn to_dynamic(&self) -> ::buffa_descriptor::reflect::DynamicMessage {
377            let bytes = ::buffa::ViewEncode::encode_to_vec(self);
378            let options = ::buffa::DecodeOptions::new()
379                .with_element_memory_limit(
380                    bytes
381                        .len()
382                        .saturating_mul(128)
383                        .max(::buffa::DEFAULT_ELEMENT_MEMORY_LIMIT),
384                )
385                .with_unknown_field_limit(
386                    bytes.len().max(::buffa::DEFAULT_UNKNOWN_FIELD_LIMIT),
387                );
388            ::buffa_descriptor::reflect::DynamicMessage::decode_with_options(
389                    ::buffa::alloc::sync::Arc::clone(
390                        super::super::__buffa::reflect::descriptor_pool(),
391                    ),
392                    Self::__buffa_reflect_message_index(),
393                    &bytes,
394                    &options,
395                )
396                .expect("view re-encodes to bytes decodable against its own descriptor")
397        }
398    }
399    impl<'a> ::buffa_descriptor::reflect::ReflectElement for DurationView<'a> {
400        fn as_value_ref(&self) -> ::buffa_descriptor::reflect::ValueRef<'_> {
401            ::buffa_descriptor::reflect::ValueRef::Message(
402                ::buffa_descriptor::reflect::ReflectCow::Borrowed(self),
403            )
404        }
405    }
406    impl<'a> DurationView<'a> {
407        /// Memoized `MessageIndex` for this view's message type, resolved
408        /// once against the package's embedded descriptor pool. An inherent
409        /// associated fn (not a free fn) so sibling views in the same module
410        /// do not collide.
411        #[doc(hidden)]
412        fn __buffa_reflect_message_index() -> ::buffa_descriptor::MessageIndex {
413            static IDX: ::std::sync::OnceLock<::buffa_descriptor::MessageIndex> = ::std::sync::OnceLock::new();
414            *IDX
415                .get_or_init(|| {
416                    super::super::__buffa::reflect::descriptor_pool()
417                        .message_index(<Self as ::buffa::MessageName>::FULL_NAME)
418                        .expect(
419                            "generated view type is registered in the embedded descriptor pool",
420                        )
421                })
422        }
423    }
424};