// @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\]\[\]
    ///   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> AnyView<'a> {
    /// Decode from `buf`, enforcing a recursion depth limit for nested messages.
    ///
    /// Called by [`::buffa::MessageView::decode_view`] with [`::buffa::RECURSION_LIMIT`]
    /// and by generated sub-message decode arms with `depth - 1`.
    ///
    /// **Not part of the public API.** Named with a leading underscore to
    /// signal that it is for generated-code use only.
    #[doc(hidden)]
    pub fn _decode_depth(
        buf: &'a [u8],
        depth: u32,
    ) -> ::core::result::Result<Self, ::buffa::DecodeError> {
        let mut view = Self::default();
        view._merge_into_view(buf, depth)?;
        ::core::result::Result::Ok(view)
    }
    /// Merge fields from `buf` into this view (proto merge semantics).
    ///
    /// Repeated fields append; singular fields last-wins; singular
    /// MESSAGE fields merge recursively. Used by sub-message decode
    /// arms when the same field appears multiple times on the wire.
    ///
    /// **Not part of the public API.**
    #[doc(hidden)]
    pub fn _merge_into_view(
        &mut self,
        buf: &'a [u8],
        depth: u32,
    ) -> ::core::result::Result<(), ::buffa::DecodeError> {
        let _ = depth;
        #[allow(unused_variables)]
        let view = self;
        let mut cur: &'a [u8] = buf;
        while !cur.is_empty() {
            let before_tag = cur;
            let tag = ::buffa::encoding::Tag::decode(&mut cur)?;
            match tag.field_number() {
                1u32 => {
                    if tag.wire_type() != ::buffa::encoding::WireType::LengthDelimited {
                        return ::core::result::Result::Err(::buffa::DecodeError::WireTypeMismatch {
                            field_number: 1u32,
                            expected: 2u8,
                            actual: tag.wire_type() as u8,
                        });
                    }
                    view.type_url = ::buffa::types::borrow_str(&mut cur)?;
                }
                2u32 => {
                    if tag.wire_type() != ::buffa::encoding::WireType::LengthDelimited {
                        return ::core::result::Result::Err(::buffa::DecodeError::WireTypeMismatch {
                            field_number: 2u32,
                            expected: 2u8,
                            actual: tag.wire_type() as u8,
                        });
                    }
                    view.value = ::buffa::types::borrow_bytes(&mut cur)?;
                }
                _ => {
                    ::buffa::encoding::skip_field_depth(tag, &mut cur, depth)?;
                    let span_len = before_tag.len() - cur.len();
                    view.__buffa_unknown_fields.push_raw(&before_tag[..span_len]);
                }
            }
        }
        ::core::result::Result::Ok(())
    }
}
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> {
        Self::_decode_depth(buf, ::buffa::RECURSION_LIMIT)
    }
    fn decode_view_with_limit(
        buf: &'a [u8],
        depth: u32,
    ) -> ::core::result::Result<Self, ::buffa::DecodeError> {
        Self::_decode_depth(buf, depth)
    }
    fn to_owned_message(&self) -> super::super::Any {
        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>,
    ) -> super::super::Any {
        #[allow(unused_imports)]
        use ::buffa::alloc::string::ToString as _;
        let _ = __buffa_src;
        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()
                .unwrap_or_default()
                .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 = 0u32;
        if !self.type_url.is_empty() {
            size += 1u32 + ::buffa::types::string_encoded_len(&self.type_url) as u32;
        }
        if !self.value.is_empty() {
            size += 1u32 + ::buffa::types::bytes_encoded_len(&self.value) as u32;
        }
        size += self.__buffa_unknown_fields.encoded_len() as u32;
        size
    }
    #[allow(clippy::needless_borrow)]
    fn write_to(
        &self,
        _cache: &mut ::buffa::SizeCache,
        buf: &mut impl ::buffa::bytes::BufMut,
    ) {
        #[allow(unused_imports)]
        use ::buffa::Enumeration as _;
        if !self.type_url.is_empty() {
            ::buffa::encoding::Tag::new(
                    1u32,
                    ::buffa::encoding::WireType::LengthDelimited,
                )
                .encode(buf);
            ::buffa::types::encode_string(&self.type_url, buf);
        }
        if !self.value.is_empty() {
            ::buffa::encoding::Tag::new(
                    2u32,
                    ::buffa::encoding::WireType::LengthDelimited,
                )
                .encode(buf);
            ::buffa::types::encode_bytes(&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";
}
impl<'v> ::buffa::DefaultViewInstance for AnyView<'v> {
    fn default_view_instance<'a>() -> &'a Self
    where
        Self: 'a,
    {
        static VALUE: ::buffa::__private::OnceBox<AnyView<'static>> = ::buffa::__private::OnceBox::new();
        VALUE
            .get_or_init(|| ::buffa::alloc::boxed::Box::new(
                <AnyView<'static>>::default(),
            ))
    }
}
impl ::buffa::ViewReborrow for AnyView<'static> {
    type Reborrowed<'b> = AnyView<'b>;
    fn reborrow<'b>(this: &'b Self) -> &'b Self::Reborrowed<'b> {
        this
    }
}
/** 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`] 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.
    #[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\]\[\]
    ///   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);
            ::buffa_descriptor::reflect::DynamicMessage::decode(
                    ::buffa::alloc::sync::Arc::clone(
                        super::super::__buffa::reflect::descriptor_pool(),
                    ),
                    Self::__buffa_reflect_message_index(),
                    &bytes,
                )
                .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",
                        )
                })
        }
    }
};
