Skip to main content

miniextendr_api/
adapter_traits.rs

1//! Built-in adapter traits for common Rust standard library traits.
2//!
3//! These traits provide blanket implementations that allow any Rust type
4//! implementing standard traits to be exposed to R without boilerplate.
5//!
6//! # Example
7//!
8//! ```rust,ignore
9//! use miniextendr_api::prelude::*;
10//!
11//! #[derive(Debug, ExternalPtr)]
12//! struct MyData {
13//!     values: Vec<i32>,
14//! }
15//!
16//! // RDebug is automatically available for any Debug type
17//! #[miniextendr]
18//! impl miniextendr_api::adapter_traits::RDebug for MyData {}
19//! ```
20//!
21//! In R:
22//! ```r
23//! data <- MyData$new(...)
24//! data$RDebug$debug_str()        # "MyData { values: [1, 2, 3] }"
25//! data$RDebug$debug_str_pretty() # Pretty-printed with newlines
26//! ```
27//!
28//! # Rust method names
29//!
30//! A method whose name a std trait or a covered type already uses gets an
31//! `r_` prefix in Rust and keeps the std name in R through
32//! `#[miniextendr(r_name = "...")]`: `RClone::r_clone` is `clone()` in R.
33//! The blanket impls cover every `Clone`, `Default`, `Hash`, `Ord`,
34//! `PartialOrd` and `FromStr` type, and `RToVec` every array and boxed slice,
35//! so with the std names an import of these traits would make the importing
36//! module's own `v.clone()` or `a.cmp(&b)` ambiguous (E0034), and its
37//! `[T; N]::len()` an `i64`.
38//!
39//! Both empty and populated `#[miniextendr] impl` blocks inherit the trait's
40//! R names and skipped methods. This includes generic `RToVec<T>` and
41//! `RExtend<T>` and the associated-type `RIterator`. An explicit impl-level
42//! `r_name` overrides the declaration's name for that implementation. The
43//! methods' docs here document the R wrappers of every implementation whose
44//! method has no doc comment of its own, an empty impl's included, so they are
45//! written for R users.
46
47use crate::Nullable;
48use crate::miniextendr;
49use std::collections::hash_map::DefaultHasher;
50use std::fmt::{Debug, Display};
51use std::hash::{Hash, Hasher};
52use std::str::FromStr;
53
54/// Adapter trait for [`std::fmt::Debug`].
55///
56/// Provides string representations for debugging and inspection in R.
57/// Automatically implemented for any type that implements `Debug`.
58///
59/// # Methods
60///
61/// - `debug_str()` - Returns compact debug string (`:?` format)
62/// - `debug_str_pretty()` - Returns pretty-printed debug string (`:#?` format)
63///
64/// # Example
65///
66/// ```rust,ignore
67/// #[derive(Debug, ExternalPtr)]
68/// struct Config { name: String, value: i32 }
69///
70/// #[miniextendr]
71/// impl miniextendr_api::adapter_traits::RDebug for Config {}
72/// ```
73#[doc = "Method shim for `RDebug::debug_str`."]
#[doc = r""]
#[doc =
r" Converts SEXP arguments, calls the method, and returns SEXP result."]
#[doc =
r" Both Rust panics and R longjmps are caught via `with_r_unwind_protect`."]
#[doc(hidden)]
#[allow(non_snake_case)]
unsafe extern "C" fn __RDebug_debug_str_shim(data:
        *mut ::std::os::raw::c_void, argc: i32,
    argv: *const ::miniextendr_api::SEXP) -> ::miniextendr_api::SEXP where
    Self: ::core::marker::Sized + RDebug {
    ::miniextendr_api::unwind_protect::with_r_unwind_protect_shim(||
            {
                ::miniextendr_api::trait_abi::check_arity(argc, 0i32,
                    "RDebug::debug_str");
                let __mx_cell =
                    unsafe { &*data.cast::<::core::cell::RefCell<Self>>() };
                let __mx_guard =
                    ::miniextendr_api::externalptr::borrow_value(__mx_cell);
                let self_ref = &*__mx_guard;
                let result = self_ref.debug_str();
                match ::miniextendr_api::into_r::IntoR::try_into_sexp(result)
                    {
                    ::core::result::Result::Ok(__mx_sexp) => __mx_sexp,
                    ::core::result::Result::Err(__mx_error) => unsafe {
                        ::miniextendr_api::error_value::result_err_condition_value(::miniextendr_api::condition::into_r_err_parts(&__mx_error),
                            ::core::option::Option::None)
                    },
                }
            })
}
#[doc = "Method shim for `RDebug::debug_str_pretty`."]
#[doc = r""]
#[doc =
r" Converts SEXP arguments, calls the method, and returns SEXP result."]
#[doc =
r" Both Rust panics and R longjmps are caught via `with_r_unwind_protect`."]
#[doc(hidden)]
#[allow(non_snake_case)]
unsafe extern "C" fn __RDebug_debug_str_pretty_shim(data:
        *mut ::std::os::raw::c_void, argc: i32,
    argv: *const ::miniextendr_api::SEXP) -> ::miniextendr_api::SEXP where
    Self: ::core::marker::Sized + RDebug {
    ::miniextendr_api::unwind_protect::with_r_unwind_protect_shim(||
            {
                ::miniextendr_api::trait_abi::check_arity(argc, 0i32,
                    "RDebug::debug_str_pretty");
                let __mx_cell =
                    unsafe { &*data.cast::<::core::cell::RefCell<Self>>() };
                let __mx_guard =
                    ::miniextendr_api::externalptr::borrow_value(__mx_cell);
                let self_ref = &*__mx_guard;
                let result = self_ref.debug_str_pretty();
                match ::miniextendr_api::into_r::IntoR::try_into_sexp(result)
                    {
                    ::core::result::Result::Ok(__mx_sexp) => __mx_sexp,
                    ::core::result::Result::Err(__mx_error) => unsafe {
                        ::miniextendr_api::error_value::result_err_condition_value(::miniextendr_api::condition::into_r_err_parts(&__mx_error),
                            ::core::option::Option::None)
                    },
                }
            })
}
#[doc = "Type tag for runtime identification of the `RDebug` trait."]
#[doc = "Generated from source location line 74, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[allow(non_upper_case_globals)]
pub const TAG_RDebug: ::miniextendr_api::abi::mx_tag =
    ::miniextendr_api::abi::mx_tag_from_path("miniextendr::trait-abi/v2;6:RDebug1:29:debug_str9:debug_str3:ref1:06:String16:debug_str_pretty16:debug_str_pretty3:ref1:06:String");
#[doc = "Vtable for the `RDebug` trait."]
#[doc = "Generated from source location line 74, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[doc = r""]
#[doc = r" Contains one `mx_meth` function pointer per trait method."]
#[repr(C)]
#[doc(hidden)]
#[allow(non_camel_case_types)]
pub struct RDebugVTable {
    pub debug_str: ::miniextendr_api::abi::mx_meth,
    pub debug_str_pretty: ::miniextendr_api::abi::mx_meth,
}
#[doc = "Runtime view for objects implementing `RDebug`."]
#[doc = "Generated from source location line 74, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[doc = r""]
#[doc = r" Keeps the receiver alive for method dispatch. Use `try_from_sexp`"]
#[doc = r" to create a view with its own root for the R external pointer."]
#[doc = r" Construction, use and drop belong on R's main thread."]
#[allow(non_camel_case_types)]
pub struct RDebugView {
    __mx_view: ::miniextendr_api::trait_abi::TraitViewData<RDebugVTable>,
}
impl ::miniextendr_api::TraitView for RDebugView {
    const TAG: ::miniextendr_api::abi::mx_tag = TAG_RDebug;
    #[inline]
    unsafe fn from_raw_parts(data: *mut ::std::os::raw::c_void,
        vtable: *const ::std::os::raw::c_void,
        owner: ::core::option::Option<::miniextendr_api::SEXP>) -> Self {
        Self {
            __mx_view: unsafe {
                ::miniextendr_api::trait_abi::TraitViewData::new(data, vtable,
                    owner)
            },
        }
    }
}
impl RDebugView {
    #[doc = r" Try to create a view from an R SEXP."]
    #[doc = r""]
    #[doc = r" Returns `Some(Self)` if the object implements this trait,"]
    #[doc = r" `None` otherwise."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc = r" - `sexp` must be a valid R external pointer (EXTPTRSXP)"]
    #[doc =
    r" - The object must stay live through construction; the view then roots it"]
    #[doc =
    r" - A call that conflicts with one still running on the same object"]
    #[doc = r"   raises the `miniextendr_borrow_conflict` error"]
    #[doc = r" - Construction, use and drop must all run on R's main thread"]
    #[inline]
    pub unsafe fn try_from_sexp(sexp: ::miniextendr_api::SEXP)
        -> ::core::option::Option<Self> {
        unsafe { <Self as ::miniextendr_api::TraitView>::try_from_sexp(sexp) }
    }
    #[doc =
    r" Try to create a view, panicking with error message on failure."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc = r" Same as `try_from_sexp`."]
    #[inline]
    pub unsafe fn from_sexp(sexp: ::miniextendr_api::SEXP) -> Self {
        unsafe {
                Self::try_from_sexp(sexp)
            }.expect("Object does not implement RDebug trait")
    }
    #[doc = "Call `debug_str` through the vtable."]
    #[inline]
    #[allow(clippy :: duplicate_underscore_argument)]
    pub fn debug_str(&self) -> String {
        unsafe {
            let __mx_roots =
                ::miniextendr_api::gc_protect::ProtectScope::new();
            let result =
                __mx_roots.protect_raw({
                        ((*self.__mx_view.vtable()).debug_str)(self.__mx_view.data(),
                            0, ::std::ptr::null())
                    });
            ::miniextendr_api::trait_abi::repanic_if_rust_error(result);
            ::miniextendr_api::trait_abi::from_sexp::<String>(result)
        }
    }
    #[doc = "Call `debug_str_pretty` through the vtable."]
    #[inline]
    #[allow(clippy :: duplicate_underscore_argument)]
    pub fn debug_str_pretty(&self) -> String {
        unsafe {
            let __mx_roots =
                ::miniextendr_api::gc_protect::ProtectScope::new();
            let result =
                __mx_roots.protect_raw({
                        ((*self.__mx_view.vtable()).debug_str_pretty)(self.__mx_view.data(),
                            0, ::std::ptr::null())
                    });
            ::miniextendr_api::trait_abi::repanic_if_rust_error(result);
            ::miniextendr_api::trait_abi::from_sexp::<String>(result)
        }
    }
}
#[doc = "Build a vtable for a concrete type implementing `RDebug`."]
#[doc = "Generated from source location line 74, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[allow(non_snake_case)]
pub const fn __RDebug_build_vtable<__ImplT: RDebug>() -> RDebugVTable {
    RDebugVTable {
        debug_str: <__ImplT as RDebug>::__RDebug_debug_str_shim,
        debug_str_pretty: <__ImplT as RDebug>::__RDebug_debug_str_pretty_shim,
    }
}
#[macro_export]
#[doc(hidden)]
macro_rules! __mx_trait_metadata_RDebug_0 {
    (@ impl { $ ($attrs : tt) * } { $ ($implementation : tt) * }) =>
    {
        :: miniextendr_api :: __mx_trait_impl_expand!
        {
            @ impl { $ ($attrs) * } { $ ($implementation) * }
            {
                #[doc = " Get a compact debug string representation."] fn
                debug_str();
                #[doc =
                " Get a pretty-printed debug string with indentation."] fn
                debug_str_pretty();
            } {} abi RDebug false
            "miniextendr::trait-abi/v2;6:RDebug1:29:debug_str9:debug_str3:ref1:06:String16:debug_str_pretty16:debug_str_pretty3:ref1:06:String"
            {
                pub debug_str : :: miniextendr_api :: abi :: mx_meth, pub
                debug_str_pretty : :: miniextendr_api :: abi :: mx_meth
            }
        }
    };
    ($concrete_type : ty, $trait_path : path, $class_system : ident, $no_rd :
    tt, $internal : tt, $noexport : tt, $no_preconditions : tt) =>
    {
        :: miniextendr_api :: __mx_trait_impl_expand!
        {
            concrete_type = $concrete_type; trait_path = $trait_path;
            class_system = $class_system; no_rd = $no_rd; internal =
            $internal; noexport = $noexport; no_preconditions =
            $no_preconditions; abi RDebug false
            "miniextendr::trait-abi/v2;6:RDebug1:29:debug_str9:debug_str3:ref1:06:String16:debug_str_pretty16:debug_str_pretty3:ref1:06:String"
            {
                pub debug_str : :: miniextendr_api :: abi :: mx_meth, pub
                debug_str_pretty : :: miniextendr_api :: abi :: mx_meth
            } method
            {
                r_name = debug_str;
                #[doc = " Get a compact debug string representation."] fn
                debug_str(& self) -> String;
            } method
            {
                r_name = debug_str_pretty;
                #[doc =
                " Get a pretty-printed debug string with indentation."] fn
                debug_str_pretty(& self) -> String;
            }
        }
    };
}
#[doc(hidden)]
#[allow(unused_imports)]
pub use __mx_trait_metadata_RDebug_0 as RDebug;#[miniextendr]
74pub trait RDebug {
75    /// Get a compact debug string representation.
76    fn debug_str(&self) -> String;
77
78    /// Get a pretty-printed debug string with indentation.
79    fn debug_str_pretty(&self) -> String;
80}
81
82impl<T: Debug> RDebug for T {
83    fn debug_str(&self) -> String {
84        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", self))
    })format!("{:?}", self)
85    }
86
87    fn debug_str_pretty(&self) -> String {
88        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:#?}", self))
    })format!("{:#?}", self)
89    }
90}
91
92/// Adapter trait for [`std::fmt::Display`].
93///
94/// Provides user-friendly string conversion for R.
95/// Automatically implemented for any type that implements `Display`.
96///
97/// # Methods
98///
99/// - `as_r_string()` - Returns the Display representation
100///
101/// # Example
102///
103/// ```rust,ignore
104/// struct Version(u32, u32, u32);
105///
106/// impl Display for Version {
107///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
108///         write!(f, "{}.{}.{}", self.0, self.1, self.2)
109///     }
110/// }
111///
112/// #[miniextendr]
113/// impl miniextendr_api::adapter_traits::RDisplay for Version {}
114/// ```
115#[doc = "Method shim for `RDisplay::as_r_string`."]
#[doc = r""]
#[doc =
r" Converts SEXP arguments, calls the method, and returns SEXP result."]
#[doc =
r" Both Rust panics and R longjmps are caught via `with_r_unwind_protect`."]
#[doc(hidden)]
#[allow(non_snake_case)]
unsafe extern "C" fn __RDisplay_as_r_string_shim(data:
        *mut ::std::os::raw::c_void, argc: i32,
    argv: *const ::miniextendr_api::SEXP) -> ::miniextendr_api::SEXP where
    Self: ::core::marker::Sized + RDisplay {
    ::miniextendr_api::unwind_protect::with_r_unwind_protect_shim(||
            {
                ::miniextendr_api::trait_abi::check_arity(argc, 0i32,
                    "RDisplay::as_r_string");
                let __mx_cell =
                    unsafe { &*data.cast::<::core::cell::RefCell<Self>>() };
                let __mx_guard =
                    ::miniextendr_api::externalptr::borrow_value(__mx_cell);
                let self_ref = &*__mx_guard;
                let result = self_ref.as_r_string();
                match ::miniextendr_api::into_r::IntoR::try_into_sexp(result)
                    {
                    ::core::result::Result::Ok(__mx_sexp) => __mx_sexp,
                    ::core::result::Result::Err(__mx_error) => unsafe {
                        ::miniextendr_api::error_value::result_err_condition_value(::miniextendr_api::condition::into_r_err_parts(&__mx_error),
                            ::core::option::Option::None)
                    },
                }
            })
}
#[doc = "Type tag for runtime identification of the `RDisplay` trait."]
#[doc = "Generated from source location line 116, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[allow(non_upper_case_globals)]
pub const TAG_RDisplay: ::miniextendr_api::abi::mx_tag =
    ::miniextendr_api::abi::mx_tag_from_path("miniextendr::trait-abi/v2;8:RDisplay1:111:as_r_string11:as_r_string3:ref1:06:String");
#[doc = "Vtable for the `RDisplay` trait."]
#[doc = "Generated from source location line 116, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[doc = r""]
#[doc = r" Contains one `mx_meth` function pointer per trait method."]
#[repr(C)]
#[doc(hidden)]
#[allow(non_camel_case_types)]
pub struct RDisplayVTable {
    pub as_r_string: ::miniextendr_api::abi::mx_meth,
}
#[doc = "Runtime view for objects implementing `RDisplay`."]
#[doc = "Generated from source location line 116, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[doc = r""]
#[doc = r" Keeps the receiver alive for method dispatch. Use `try_from_sexp`"]
#[doc = r" to create a view with its own root for the R external pointer."]
#[doc = r" Construction, use and drop belong on R's main thread."]
#[allow(non_camel_case_types)]
pub struct RDisplayView {
    __mx_view: ::miniextendr_api::trait_abi::TraitViewData<RDisplayVTable>,
}
impl ::miniextendr_api::TraitView for RDisplayView {
    const TAG: ::miniextendr_api::abi::mx_tag = TAG_RDisplay;
    #[inline]
    unsafe fn from_raw_parts(data: *mut ::std::os::raw::c_void,
        vtable: *const ::std::os::raw::c_void,
        owner: ::core::option::Option<::miniextendr_api::SEXP>) -> Self {
        Self {
            __mx_view: unsafe {
                ::miniextendr_api::trait_abi::TraitViewData::new(data, vtable,
                    owner)
            },
        }
    }
}
impl RDisplayView {
    #[doc = r" Try to create a view from an R SEXP."]
    #[doc = r""]
    #[doc = r" Returns `Some(Self)` if the object implements this trait,"]
    #[doc = r" `None` otherwise."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc = r" - `sexp` must be a valid R external pointer (EXTPTRSXP)"]
    #[doc =
    r" - The object must stay live through construction; the view then roots it"]
    #[doc =
    r" - A call that conflicts with one still running on the same object"]
    #[doc = r"   raises the `miniextendr_borrow_conflict` error"]
    #[doc = r" - Construction, use and drop must all run on R's main thread"]
    #[inline]
    pub unsafe fn try_from_sexp(sexp: ::miniextendr_api::SEXP)
        -> ::core::option::Option<Self> {
        unsafe { <Self as ::miniextendr_api::TraitView>::try_from_sexp(sexp) }
    }
    #[doc =
    r" Try to create a view, panicking with error message on failure."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc = r" Same as `try_from_sexp`."]
    #[inline]
    pub unsafe fn from_sexp(sexp: ::miniextendr_api::SEXP) -> Self {
        unsafe {
                Self::try_from_sexp(sexp)
            }.expect("Object does not implement RDisplay trait")
    }
    #[doc = "Call `as_r_string` through the vtable."]
    #[inline]
    #[allow(clippy :: duplicate_underscore_argument)]
    pub fn as_r_string(&self) -> String {
        unsafe {
            let __mx_roots =
                ::miniextendr_api::gc_protect::ProtectScope::new();
            let result =
                __mx_roots.protect_raw({
                        ((*self.__mx_view.vtable()).as_r_string)(self.__mx_view.data(),
                            0, ::std::ptr::null())
                    });
            ::miniextendr_api::trait_abi::repanic_if_rust_error(result);
            ::miniextendr_api::trait_abi::from_sexp::<String>(result)
        }
    }
}
#[doc = "Build a vtable for a concrete type implementing `RDisplay`."]
#[doc = "Generated from source location line 116, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[allow(non_snake_case)]
pub const fn __RDisplay_build_vtable<__ImplT: RDisplay>() -> RDisplayVTable {
    RDisplayVTable {
        as_r_string: <__ImplT as RDisplay>::__RDisplay_as_r_string_shim,
    }
}
#[macro_export]
#[doc(hidden)]
macro_rules! __mx_trait_metadata_RDisplay_1 {
    (@ impl { $ ($attrs : tt) * } { $ ($implementation : tt) * }) =>
    {
        :: miniextendr_api :: __mx_trait_impl_expand!
        {
            @ impl { $ ($attrs) * } { $ ($implementation) * }
            {
                #[doc = " Convert to a user-friendly string."] fn
                as_r_string();
            } {} abi RDisplay false
            "miniextendr::trait-abi/v2;8:RDisplay1:111:as_r_string11:as_r_string3:ref1:06:String"
            { pub as_r_string : :: miniextendr_api :: abi :: mx_meth }
        }
    };
    ($concrete_type : ty, $trait_path : path, $class_system : ident, $no_rd :
    tt, $internal : tt, $noexport : tt, $no_preconditions : tt) =>
    {
        :: miniextendr_api :: __mx_trait_impl_expand!
        {
            concrete_type = $concrete_type; trait_path = $trait_path;
            class_system = $class_system; no_rd = $no_rd; internal =
            $internal; noexport = $noexport; no_preconditions =
            $no_preconditions; abi RDisplay false
            "miniextendr::trait-abi/v2;8:RDisplay1:111:as_r_string11:as_r_string3:ref1:06:String"
            { pub as_r_string : :: miniextendr_api :: abi :: mx_meth } method
            {
                r_name = as_r_string;
                #[doc = " Convert to a user-friendly string."] fn
                as_r_string(& self) -> String;
            }
        }
    };
}
#[doc(hidden)]
#[allow(unused_imports)]
pub use __mx_trait_metadata_RDisplay_1 as RDisplay;#[miniextendr]
116pub trait RDisplay {
117    /// Convert to a user-friendly string.
118    fn as_r_string(&self) -> String;
119}
120
121impl<T: Display> RDisplay for T {
122    fn as_r_string(&self) -> String {
123        self.to_string()
124    }
125}
126
127/// Adapter trait for [`std::hash::Hash`].
128///
129/// Provides hashing for deduplication and environment keys in R.
130/// Automatically implemented for any type that implements `Hash`.
131///
132/// # Methods
133///
134/// - `r_hash()` (`hash()` in R) - Returns the 64-bit hash as a 16-character
135///   hex string
136///
137/// # Note
138///
139/// Hash values are deterministic within a single R session but may vary
140/// between sessions due to Rust's hasher implementation.
141///
142/// The hash is returned as a hex `String` (e.g. `"a1b2c3d4e5f60718"`), not a
143/// number. R has no faithful 64-bit integer type, so returning the `u64` as a
144/// numeric would round away its low bits above `2^53` — distinct Rust values
145/// would collide in R — and surface half the range as negative. A hex string
146/// preserves all 64 bits, is directly usable as an R environment key, and
147/// works with `duplicated()` / `match()` for deduplication.
148///
149/// # Example
150///
151/// ```rust,ignore
152/// #[derive(Hash, ExternalPtr)]
153/// struct Record { id: String, value: i64 }
154///
155/// #[miniextendr]
156/// impl miniextendr_api::adapter_traits::RHash for Record {}
157/// ```
158#[doc = "Method shim for `RHash::r_hash`."]
#[doc = r""]
#[doc =
r" Converts SEXP arguments, calls the method, and returns SEXP result."]
#[doc =
r" Both Rust panics and R longjmps are caught via `with_r_unwind_protect`."]
#[doc(hidden)]
#[allow(non_snake_case)]
unsafe extern "C" fn __RHash_r_hash_shim(data: *mut ::std::os::raw::c_void,
    argc: i32, argv: *const ::miniextendr_api::SEXP)
    -> ::miniextendr_api::SEXP where Self: ::core::marker::Sized + RHash {
    ::miniextendr_api::unwind_protect::with_r_unwind_protect_shim(||
            {
                ::miniextendr_api::trait_abi::check_arity(argc, 0i32,
                    "RHash::r_hash");
                let __mx_cell =
                    unsafe { &*data.cast::<::core::cell::RefCell<Self>>() };
                let __mx_guard =
                    ::miniextendr_api::externalptr::borrow_value(__mx_cell);
                let self_ref = &*__mx_guard;
                let result = self_ref.r_hash();
                match ::miniextendr_api::into_r::IntoR::try_into_sexp(result)
                    {
                    ::core::result::Result::Ok(__mx_sexp) => __mx_sexp,
                    ::core::result::Result::Err(__mx_error) => unsafe {
                        ::miniextendr_api::error_value::result_err_condition_value(::miniextendr_api::condition::into_r_err_parts(&__mx_error),
                            ::core::option::Option::None)
                    },
                }
            })
}
#[doc = "Type tag for runtime identification of the `RHash` trait."]
#[doc = "Generated from source location line 159, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[allow(non_upper_case_globals)]
pub const TAG_RHash: ::miniextendr_api::abi::mx_tag =
    ::miniextendr_api::abi::mx_tag_from_path("miniextendr::trait-abi/v2;5:RHash1:16:r_hash4:hash3:ref1:06:String");
#[doc = "Vtable for the `RHash` trait."]
#[doc = "Generated from source location line 159, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[doc = r""]
#[doc = r" Contains one `mx_meth` function pointer per trait method."]
#[repr(C)]
#[doc(hidden)]
#[allow(non_camel_case_types)]
pub struct RHashVTable {
    pub r_hash: ::miniextendr_api::abi::mx_meth,
}
#[doc = "Runtime view for objects implementing `RHash`."]
#[doc = "Generated from source location line 159, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[doc = r""]
#[doc = r" Keeps the receiver alive for method dispatch. Use `try_from_sexp`"]
#[doc = r" to create a view with its own root for the R external pointer."]
#[doc = r" Construction, use and drop belong on R's main thread."]
#[allow(non_camel_case_types)]
pub struct RHashView {
    __mx_view: ::miniextendr_api::trait_abi::TraitViewData<RHashVTable>,
}
impl ::miniextendr_api::TraitView for RHashView {
    const TAG: ::miniextendr_api::abi::mx_tag = TAG_RHash;
    #[inline]
    unsafe fn from_raw_parts(data: *mut ::std::os::raw::c_void,
        vtable: *const ::std::os::raw::c_void,
        owner: ::core::option::Option<::miniextendr_api::SEXP>) -> Self {
        Self {
            __mx_view: unsafe {
                ::miniextendr_api::trait_abi::TraitViewData::new(data, vtable,
                    owner)
            },
        }
    }
}
impl RHashView {
    #[doc = r" Try to create a view from an R SEXP."]
    #[doc = r""]
    #[doc = r" Returns `Some(Self)` if the object implements this trait,"]
    #[doc = r" `None` otherwise."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc = r" - `sexp` must be a valid R external pointer (EXTPTRSXP)"]
    #[doc =
    r" - The object must stay live through construction; the view then roots it"]
    #[doc =
    r" - A call that conflicts with one still running on the same object"]
    #[doc = r"   raises the `miniextendr_borrow_conflict` error"]
    #[doc = r" - Construction, use and drop must all run on R's main thread"]
    #[inline]
    pub unsafe fn try_from_sexp(sexp: ::miniextendr_api::SEXP)
        -> ::core::option::Option<Self> {
        unsafe { <Self as ::miniextendr_api::TraitView>::try_from_sexp(sexp) }
    }
    #[doc =
    r" Try to create a view, panicking with error message on failure."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc = r" Same as `try_from_sexp`."]
    #[inline]
    pub unsafe fn from_sexp(sexp: ::miniextendr_api::SEXP) -> Self {
        unsafe {
                Self::try_from_sexp(sexp)
            }.expect("Object does not implement RHash trait")
    }
    #[doc = "Call `r_hash` through the vtable."]
    #[inline]
    #[allow(clippy :: duplicate_underscore_argument)]
    pub fn r_hash(&self) -> String {
        unsafe {
            let __mx_roots =
                ::miniextendr_api::gc_protect::ProtectScope::new();
            let result =
                __mx_roots.protect_raw({
                        ((*self.__mx_view.vtable()).r_hash)(self.__mx_view.data(),
                            0, ::std::ptr::null())
                    });
            ::miniextendr_api::trait_abi::repanic_if_rust_error(result);
            ::miniextendr_api::trait_abi::from_sexp::<String>(result)
        }
    }
}
#[doc = "Build a vtable for a concrete type implementing `RHash`."]
#[doc = "Generated from source location line 159, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[allow(non_snake_case)]
pub const fn __RHash_build_vtable<__ImplT: RHash>() -> RHashVTable {
    RHashVTable { r_hash: <__ImplT as RHash>::__RHash_r_hash_shim }
}
#[macro_export]
#[doc(hidden)]
macro_rules! __mx_trait_metadata_RHash_2 {
    (@ impl { $ ($attrs : tt) * } { $ ($implementation : tt) * }) =>
    {
        :: miniextendr_api :: __mx_trait_impl_expand!
        {
            @ impl { $ ($attrs) * } { $ ($implementation) * }
            {
                #[doc = " Compute a hash of this value."] #[doc = ""]
                #[doc =
                " Returns the [`DefaultHasher`] `u64` output as a 16-character lowercase"]
                #[doc =
                " hex string, which keeps all 64 bits: R has no 64-bit integer, and a"]
                #[doc = " number would lose the low bits above `2^53`."]
                #[miniextendr(r_name = "hash")] fn r_hash();
            } {} abi RHash false
            "miniextendr::trait-abi/v2;5:RHash1:16:r_hash4:hash3:ref1:06:String"
            { pub r_hash : :: miniextendr_api :: abi :: mx_meth }
        }
    };
    ($concrete_type : ty, $trait_path : path, $class_system : ident, $no_rd :
    tt, $internal : tt, $noexport : tt, $no_preconditions : tt) =>
    {
        :: miniextendr_api :: __mx_trait_impl_expand!
        {
            concrete_type = $concrete_type; trait_path = $trait_path;
            class_system = $class_system; no_rd = $no_rd; internal =
            $internal; noexport = $noexport; no_preconditions =
            $no_preconditions; abi RHash false
            "miniextendr::trait-abi/v2;5:RHash1:16:r_hash4:hash3:ref1:06:String"
            { pub r_hash : :: miniextendr_api :: abi :: mx_meth } method
            {
                r_name = hash; #[doc = " Compute a hash of this value."]
                #[doc = ""]
                #[doc =
                " Returns the [`DefaultHasher`] `u64` output as a 16-character lowercase"]
                #[doc =
                " hex string, which keeps all 64 bits: R has no 64-bit integer, and a"]
                #[doc = " number would lose the low bits above `2^53`."] fn
                r_hash(& self) -> String;
            }
        }
    };
}
#[doc(hidden)]
#[allow(unused_imports)]
pub use __mx_trait_metadata_RHash_2 as RHash;#[miniextendr]
159pub trait RHash {
160    /// Compute a hash of this value.
161    ///
162    /// Returns the [`DefaultHasher`] `u64` output as a 16-character lowercase
163    /// hex string, which keeps all 64 bits: R has no 64-bit integer, and a
164    /// number would lose the low bits above `2^53`.
165    #[miniextendr(r_name = "hash")]
166    fn r_hash(&self) -> String;
167}
168
169impl<T: Hash> RHash for T {
170    fn r_hash(&self) -> String {
171        let mut hasher = DefaultHasher::new();
172        Hash::hash(self, &mut hasher);
173        // R has no faithful 64-bit integer; hex-encode the full u64 so every
174        // bit survives the trip to R (a numeric would round above 2^53).
175        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:016x}", hasher.finish()))
    })format!("{:016x}", hasher.finish())
176    }
177}
178
179/// Adapter trait for [`std::cmp::Ord`].
180///
181/// Provides total ordering comparison for R sorting operations.
182/// Automatically implemented for any type that implements `Ord`.
183///
184/// # Methods
185///
186/// - `r_cmp(&self, other: &Self)` (`cmp()` in R) - Returns -1, 0, or 1
187///
188/// # Example
189///
190/// ```rust,ignore
191/// #[derive(Ord, PartialOrd, Eq, PartialEq, ExternalPtr)]
192/// struct Priority(u32);
193///
194/// #[miniextendr]
195/// impl miniextendr_api::adapter_traits::ROrd for Priority {}
196/// ```
197#[doc = "Method shim for `ROrd::r_cmp`."]
#[doc = r""]
#[doc =
r" Converts SEXP arguments, calls the method, and returns SEXP result."]
#[doc =
r" Both Rust panics and R longjmps are caught via `with_r_unwind_protect`."]
#[doc(hidden)]
#[allow(non_snake_case)]
unsafe extern "C" fn __ROrd_r_cmp_shim(data: *mut ::std::os::raw::c_void,
    argc: i32, argv: *const ::miniextendr_api::SEXP)
    -> ::miniextendr_api::SEXP where Self: ::core::marker::Sized + ROrd +
    ::miniextendr_api::TypedExternal + 'static {
    ::miniextendr_api::unwind_protect::with_r_unwind_protect_shim(||
            {
                ::miniextendr_api::trait_abi::check_arity(argc, 1i32,
                    "ROrd::r_cmp");
                let __mx_cell =
                    unsafe { &*data.cast::<::core::cell::RefCell<Self>>() };
                let __extptr_other: ::miniextendr_api::ExternalPtr<Self> =
                    match <::miniextendr_api::ExternalPtr<Self> as
                                ::miniextendr_api::TryFromSexp>::try_from_sexp(unsafe {
                                *argv.add(0usize)
                            }) {
                        ::core::result::Result::Ok(value) => value,
                        ::core::result::Result::Err(e) =>
                            return unsafe {
                                    {
                                        let __mx_expected:
                                                ::core::option::Option<::std::string::String> =
                                            (<::miniextendr_api::ExternalPtr<Self> as
                                                            ::miniextendr_api::TryFromSexp>::__MX_EXPECTATION.map(::std::string::ToString::to_string)).or_else(||
                                                    {
                                                        #[allow(unused_imports)]
                                                        use crate::condition::{
                                                            ConversionExpectBuiltin as _, ConversionExpectNone as _,
                                                        };
                                                        match &e { __mx_e => __mx_e.__mx_conversion_expectation(), }
                                                    });
                                        ::miniextendr_api::error_value::conversion_condition_value(&::miniextendr_api::condition::conversion_prefix("other",
                                                    false, __mx_expected.as_deref()), "other",
                                            ::core::option::Option::Some("&Self"),
                                            ::miniextendr_api::trait_abi::conversion_error_class(),
                                            {
                                                #[allow(unused_imports)]
                                                use crate::condition::{
                                                    ConversionErrBuiltin as _, ConversionErrClassed as _,
                                                    ConversionErrDisplay as _,
                                                };
                                                match &e {
                                                    __mx_e =>
                                                        __mx_e.__mx_conversion_parts(__mx_expected.is_some()),
                                                }
                                            },
                                            {
                                                #[allow(unused_imports)]
                                                use crate::condition::{
                                                    ConversionArgMessageBuiltin as _,
                                                    ConversionArgMessageClassed as _,
                                                    ConversionArgMessageNone as _,
                                                };
                                                match &e {
                                                    __mx_e => __mx_e.__mx_conversion_arg_message("other"),
                                                }
                                            }, ::core::option::Option::None)
                                    }
                                },
                    };
                let __mx_guard_other = __extptr_other.borrow();
                let other = &*__mx_guard_other;
                let __mx_guard =
                    ::miniextendr_api::externalptr::borrow_value(__mx_cell);
                let self_ref = &*__mx_guard;
                let result = self_ref.r_cmp(other);
                match ::miniextendr_api::into_r::IntoR::try_into_sexp(result)
                    {
                    ::core::result::Result::Ok(__mx_sexp) => __mx_sexp,
                    ::core::result::Result::Err(__mx_error) => unsafe {
                        ::miniextendr_api::error_value::result_err_condition_value(::miniextendr_api::condition::into_r_err_parts(&__mx_error),
                            ::core::option::Option::None)
                    },
                }
            })
}
#[doc = "Type tag for runtime identification of the `ROrd` trait."]
#[doc = "Generated from source location line 198, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[allow(non_upper_case_globals)]
pub const TAG_ROrd: ::miniextendr_api::abi::mx_tag =
    ::miniextendr_api::abi::mx_tag_from_path("miniextendr::trait-abi/v2;4:ROrd1:15:r_cmp3:cmp3:ref1:16:& Self3:i32");
#[doc = "Vtable for the `ROrd` trait."]
#[doc = "Generated from source location line 198, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[doc = r""]
#[doc = r" Contains one `mx_meth` function pointer per trait method."]
#[repr(C)]
#[doc(hidden)]
#[allow(non_camel_case_types)]
pub struct ROrdVTable {
    pub r_cmp: ::miniextendr_api::abi::mx_meth,
}
#[doc = "Runtime view for objects implementing `ROrd`."]
#[doc = "Generated from source location line 198, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[doc = r""]
#[doc = r" Keeps the receiver alive for method dispatch. Use `try_from_sexp`"]
#[doc = r" to create a view with its own root for the R external pointer."]
#[doc = r" Construction, use and drop belong on R's main thread."]
#[allow(non_camel_case_types)]
pub struct ROrdView {
    __mx_view: ::miniextendr_api::trait_abi::TraitViewData<ROrdVTable>,
}
impl ::miniextendr_api::TraitView for ROrdView {
    const TAG: ::miniextendr_api::abi::mx_tag = TAG_ROrd;
    #[inline]
    unsafe fn from_raw_parts(data: *mut ::std::os::raw::c_void,
        vtable: *const ::std::os::raw::c_void,
        owner: ::core::option::Option<::miniextendr_api::SEXP>) -> Self {
        Self {
            __mx_view: unsafe {
                ::miniextendr_api::trait_abi::TraitViewData::new(data, vtable,
                    owner)
            },
        }
    }
}
impl ROrdView {
    #[doc = r" Try to create a view from an R SEXP."]
    #[doc = r""]
    #[doc = r" Returns `Some(Self)` if the object implements this trait,"]
    #[doc = r" `None` otherwise."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc = r" - `sexp` must be a valid R external pointer (EXTPTRSXP)"]
    #[doc =
    r" - The object must stay live through construction; the view then roots it"]
    #[doc =
    r" - A call that conflicts with one still running on the same object"]
    #[doc = r"   raises the `miniextendr_borrow_conflict` error"]
    #[doc = r" - Construction, use and drop must all run on R's main thread"]
    #[inline]
    pub unsafe fn try_from_sexp(sexp: ::miniextendr_api::SEXP)
        -> ::core::option::Option<Self> {
        unsafe { <Self as ::miniextendr_api::TraitView>::try_from_sexp(sexp) }
    }
    #[doc =
    r" Try to create a view, panicking with error message on failure."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc = r" Same as `try_from_sexp`."]
    #[inline]
    pub unsafe fn from_sexp(sexp: ::miniextendr_api::SEXP) -> Self {
        unsafe {
                Self::try_from_sexp(sexp)
            }.expect("Object does not implement ROrd trait")
    }
}
#[doc = "Build a vtable for a concrete type implementing `ROrd`."]
#[doc = "Generated from source location line 198, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[allow(non_snake_case)]
pub const fn __ROrd_build_vtable<__ImplT: ROrd +
    ::miniextendr_api::TypedExternal + 'static>() -> ROrdVTable {
    ROrdVTable { r_cmp: <__ImplT as ROrd>::__ROrd_r_cmp_shim }
}
#[macro_export]
#[doc(hidden)]
macro_rules! __mx_trait_metadata_ROrd_3 {
    (@ impl { $ ($attrs : tt) * } { $ ($implementation : tt) * }) =>
    {
        :: miniextendr_api :: __mx_trait_impl_expand!
        {
            @ impl { $ ($attrs) * } { $ ($implementation) * }
            {
                #[doc = " Compare with another value."] #[doc = ""]
                #[doc = " Returns:"] #[doc = " - `-1` if `self < other`"]
                #[doc = " - `0` if `self == other`"]
                #[doc = " - `1` if `self > other`"]
                #[miniextendr(r_name = "cmp")] fn r_cmp(other : ());
            } {} abi ROrd false
            "miniextendr::trait-abi/v2;4:ROrd1:15:r_cmp3:cmp3:ref1:16:& Self3:i32"
            { pub r_cmp : :: miniextendr_api :: abi :: mx_meth }
        }
    };
    ($concrete_type : ty, $trait_path : path, $class_system : ident, $no_rd :
    tt, $internal : tt, $noexport : tt, $no_preconditions : tt) =>
    {
        :: miniextendr_api :: __mx_trait_impl_expand!
        {
            concrete_type = $concrete_type; trait_path = $trait_path;
            class_system = $class_system; no_rd = $no_rd; internal =
            $internal; noexport = $noexport; no_preconditions =
            $no_preconditions; abi ROrd false
            "miniextendr::trait-abi/v2;4:ROrd1:15:r_cmp3:cmp3:ref1:16:& Self3:i32"
            { pub r_cmp : :: miniextendr_api :: abi :: mx_meth } method
            {
                r_name = cmp; #[doc = " Compare with another value."]
                #[doc = ""] #[doc = " Returns:"]
                #[doc = " - `-1` if `self < other`"]
                #[doc = " - `0` if `self == other`"]
                #[doc = " - `1` if `self > other`"] fn
                r_cmp(& self, other : & Self) -> i32;
            }
        }
    };
}
#[doc(hidden)]
#[allow(unused_imports)]
pub use __mx_trait_metadata_ROrd_3 as ROrd;#[miniextendr]
198pub trait ROrd {
199    /// Compare with another value.
200    ///
201    /// Returns:
202    /// - `-1` if `self < other`
203    /// - `0` if `self == other`
204    /// - `1` if `self > other`
205    #[miniextendr(r_name = "cmp")]
206    fn r_cmp(&self, other: &Self) -> i32;
207}
208
209impl<T: Ord> ROrd for T {
210    fn r_cmp(&self, other: &Self) -> i32 {
211        match Ord::cmp(self, other) {
212            std::cmp::Ordering::Less => -1,
213            std::cmp::Ordering::Equal => 0,
214            std::cmp::Ordering::Greater => 1,
215        }
216    }
217}
218
219/// Adapter trait for [`std::cmp::PartialOrd`].
220///
221/// Provides partial ordering comparison for R, handling incomparable values.
222/// Automatically implemented for any type that implements `PartialOrd`.
223///
224/// # Methods
225///
226/// - `r_partial_cmp(&self, other: &Self)` (`partial_cmp()` in R) - Returns
227///   Some(-1/0/1) or None
228///
229/// # Example
230///
231/// ```rust,ignore
232/// // f64 has partial ordering (NaN is not comparable)
233/// #[derive(PartialOrd, PartialEq, ExternalPtr)]
234/// struct MyFloat(f64);
235///
236/// #[miniextendr]
237/// impl miniextendr_api::adapter_traits::RPartialOrd for MyFloat {}
238/// ```
239#[doc = "Method shim for `RPartialOrd::r_partial_cmp`."]
#[doc = r""]
#[doc =
r" Converts SEXP arguments, calls the method, and returns SEXP result."]
#[doc =
r" Both Rust panics and R longjmps are caught via `with_r_unwind_protect`."]
#[doc(hidden)]
#[allow(non_snake_case)]
unsafe extern "C" fn __RPartialOrd_r_partial_cmp_shim(data:
        *mut ::std::os::raw::c_void, argc: i32,
    argv: *const ::miniextendr_api::SEXP) -> ::miniextendr_api::SEXP where
    Self: ::core::marker::Sized + RPartialOrd +
    ::miniextendr_api::TypedExternal + 'static {
    ::miniextendr_api::unwind_protect::with_r_unwind_protect_shim(||
            {
                ::miniextendr_api::trait_abi::check_arity(argc, 1i32,
                    "RPartialOrd::r_partial_cmp");
                let __mx_cell =
                    unsafe { &*data.cast::<::core::cell::RefCell<Self>>() };
                let __extptr_other: ::miniextendr_api::ExternalPtr<Self> =
                    match <::miniextendr_api::ExternalPtr<Self> as
                                ::miniextendr_api::TryFromSexp>::try_from_sexp(unsafe {
                                *argv.add(0usize)
                            }) {
                        ::core::result::Result::Ok(value) => value,
                        ::core::result::Result::Err(e) =>
                            return unsafe {
                                    {
                                        let __mx_expected:
                                                ::core::option::Option<::std::string::String> =
                                            (<::miniextendr_api::ExternalPtr<Self> as
                                                            ::miniextendr_api::TryFromSexp>::__MX_EXPECTATION.map(::std::string::ToString::to_string)).or_else(||
                                                    {
                                                        #[allow(unused_imports)]
                                                        use crate::condition::{
                                                            ConversionExpectBuiltin as _, ConversionExpectNone as _,
                                                        };
                                                        match &e { __mx_e => __mx_e.__mx_conversion_expectation(), }
                                                    });
                                        ::miniextendr_api::error_value::conversion_condition_value(&::miniextendr_api::condition::conversion_prefix("other",
                                                    false, __mx_expected.as_deref()), "other",
                                            ::core::option::Option::Some("&Self"),
                                            ::miniextendr_api::trait_abi::conversion_error_class(),
                                            {
                                                #[allow(unused_imports)]
                                                use crate::condition::{
                                                    ConversionErrBuiltin as _, ConversionErrClassed as _,
                                                    ConversionErrDisplay as _,
                                                };
                                                match &e {
                                                    __mx_e =>
                                                        __mx_e.__mx_conversion_parts(__mx_expected.is_some()),
                                                }
                                            },
                                            {
                                                #[allow(unused_imports)]
                                                use crate::condition::{
                                                    ConversionArgMessageBuiltin as _,
                                                    ConversionArgMessageClassed as _,
                                                    ConversionArgMessageNone as _,
                                                };
                                                match &e {
                                                    __mx_e => __mx_e.__mx_conversion_arg_message("other"),
                                                }
                                            }, ::core::option::Option::None)
                                    }
                                },
                    };
                let __mx_guard_other = __extptr_other.borrow();
                let other = &*__mx_guard_other;
                let __mx_guard =
                    ::miniextendr_api::externalptr::borrow_value(__mx_cell);
                let self_ref = &*__mx_guard;
                let result = self_ref.r_partial_cmp(other);
                match ::miniextendr_api::into_r::IntoR::try_into_sexp(result)
                    {
                    ::core::result::Result::Ok(__mx_sexp) => __mx_sexp,
                    ::core::result::Result::Err(__mx_error) => unsafe {
                        ::miniextendr_api::error_value::result_err_condition_value(::miniextendr_api::condition::into_r_err_parts(&__mx_error),
                            ::core::option::Option::None)
                    },
                }
            })
}
#[doc = "Type tag for runtime identification of the `RPartialOrd` trait."]
#[doc = "Generated from source location line 240, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[allow(non_upper_case_globals)]
pub const TAG_RPartialOrd: ::miniextendr_api::abi::mx_tag =
    ::miniextendr_api::abi::mx_tag_from_path("miniextendr::trait-abi/v2;11:RPartialOrd1:113:r_partial_cmp11:partial_cmp3:ref1:16:& Self14:Option < i32 >");
#[doc = "Vtable for the `RPartialOrd` trait."]
#[doc = "Generated from source location line 240, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[doc = r""]
#[doc = r" Contains one `mx_meth` function pointer per trait method."]
#[repr(C)]
#[doc(hidden)]
#[allow(non_camel_case_types)]
pub struct RPartialOrdVTable {
    pub r_partial_cmp: ::miniextendr_api::abi::mx_meth,
}
#[doc = "Runtime view for objects implementing `RPartialOrd`."]
#[doc = "Generated from source location line 240, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[doc = r""]
#[doc = r" Keeps the receiver alive for method dispatch. Use `try_from_sexp`"]
#[doc = r" to create a view with its own root for the R external pointer."]
#[doc = r" Construction, use and drop belong on R's main thread."]
#[allow(non_camel_case_types)]
pub struct RPartialOrdView {
    __mx_view: ::miniextendr_api::trait_abi::TraitViewData<RPartialOrdVTable>,
}
impl ::miniextendr_api::TraitView for RPartialOrdView {
    const TAG: ::miniextendr_api::abi::mx_tag = TAG_RPartialOrd;
    #[inline]
    unsafe fn from_raw_parts(data: *mut ::std::os::raw::c_void,
        vtable: *const ::std::os::raw::c_void,
        owner: ::core::option::Option<::miniextendr_api::SEXP>) -> Self {
        Self {
            __mx_view: unsafe {
                ::miniextendr_api::trait_abi::TraitViewData::new(data, vtable,
                    owner)
            },
        }
    }
}
impl RPartialOrdView {
    #[doc = r" Try to create a view from an R SEXP."]
    #[doc = r""]
    #[doc = r" Returns `Some(Self)` if the object implements this trait,"]
    #[doc = r" `None` otherwise."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc = r" - `sexp` must be a valid R external pointer (EXTPTRSXP)"]
    #[doc =
    r" - The object must stay live through construction; the view then roots it"]
    #[doc =
    r" - A call that conflicts with one still running on the same object"]
    #[doc = r"   raises the `miniextendr_borrow_conflict` error"]
    #[doc = r" - Construction, use and drop must all run on R's main thread"]
    #[inline]
    pub unsafe fn try_from_sexp(sexp: ::miniextendr_api::SEXP)
        -> ::core::option::Option<Self> {
        unsafe { <Self as ::miniextendr_api::TraitView>::try_from_sexp(sexp) }
    }
    #[doc =
    r" Try to create a view, panicking with error message on failure."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc = r" Same as `try_from_sexp`."]
    #[inline]
    pub unsafe fn from_sexp(sexp: ::miniextendr_api::SEXP) -> Self {
        unsafe {
                Self::try_from_sexp(sexp)
            }.expect("Object does not implement RPartialOrd trait")
    }
}
#[doc = "Build a vtable for a concrete type implementing `RPartialOrd`."]
#[doc = "Generated from source location line 240, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[allow(non_snake_case)]
pub const fn __RPartialOrd_build_vtable<__ImplT: RPartialOrd +
    ::miniextendr_api::TypedExternal + 'static>() -> RPartialOrdVTable {
    RPartialOrdVTable {
        r_partial_cmp: <__ImplT as
            RPartialOrd>::__RPartialOrd_r_partial_cmp_shim,
    }
}
#[macro_export]
#[doc(hidden)]
macro_rules! __mx_trait_metadata_RPartialOrd_4 {
    (@ impl { $ ($attrs : tt) * } { $ ($implementation : tt) * }) =>
    {
        :: miniextendr_api :: __mx_trait_impl_expand!
        {
            @ impl { $ ($attrs) * } { $ ($implementation) * }
            {
                #[doc =
                " Compare with another value, returning None if incomparable."]
                #[doc = ""] #[doc = " Returns:"]
                #[doc = " - `Some(-1)` if `self < other`"]
                #[doc = " - `Some(0)` if `self == other`"]
                #[doc = " - `Some(1)` if `self > other`"]
                #[doc = " - `None` if values are incomparable (in R, `NA`)"]
                #[miniextendr(r_name = "partial_cmp")] fn
                r_partial_cmp(other : ());
            } {} abi RPartialOrd false
            "miniextendr::trait-abi/v2;11:RPartialOrd1:113:r_partial_cmp11:partial_cmp3:ref1:16:& Self14:Option < i32 >"
            { pub r_partial_cmp : :: miniextendr_api :: abi :: mx_meth }
        }
    };
    ($concrete_type : ty, $trait_path : path, $class_system : ident, $no_rd :
    tt, $internal : tt, $noexport : tt, $no_preconditions : tt) =>
    {
        :: miniextendr_api :: __mx_trait_impl_expand!
        {
            concrete_type = $concrete_type; trait_path = $trait_path;
            class_system = $class_system; no_rd = $no_rd; internal =
            $internal; noexport = $noexport; no_preconditions =
            $no_preconditions; abi RPartialOrd false
            "miniextendr::trait-abi/v2;11:RPartialOrd1:113:r_partial_cmp11:partial_cmp3:ref1:16:& Self14:Option < i32 >"
            { pub r_partial_cmp : :: miniextendr_api :: abi :: mx_meth }
            method
            {
                r_name = partial_cmp;
                #[doc =
                " Compare with another value, returning None if incomparable."]
                #[doc = ""] #[doc = " Returns:"]
                #[doc = " - `Some(-1)` if `self < other`"]
                #[doc = " - `Some(0)` if `self == other`"]
                #[doc = " - `Some(1)` if `self > other`"]
                #[doc = " - `None` if values are incomparable (in R, `NA`)"]
                fn r_partial_cmp(& self, other : & Self) -> Option < i32 > ;
            }
        }
    };
}
#[doc(hidden)]
#[allow(unused_imports)]
pub use __mx_trait_metadata_RPartialOrd_4 as RPartialOrd;#[miniextendr]
240pub trait RPartialOrd {
241    /// Compare with another value, returning None if incomparable.
242    ///
243    /// Returns:
244    /// - `Some(-1)` if `self < other`
245    /// - `Some(0)` if `self == other`
246    /// - `Some(1)` if `self > other`
247    /// - `None` if values are incomparable (in R, `NA`)
248    #[miniextendr(r_name = "partial_cmp")]
249    fn r_partial_cmp(&self, other: &Self) -> Option<i32>;
250}
251
252impl<T: PartialOrd> RPartialOrd for T {
253    fn r_partial_cmp(&self, other: &Self) -> Option<i32> {
254        PartialOrd::partial_cmp(self, other).map(|ord| match ord {
255            std::cmp::Ordering::Less => -1,
256            std::cmp::Ordering::Equal => 0,
257            std::cmp::Ordering::Greater => 1,
258        })
259    }
260}
261
262/// Adapter trait for [`std::error::Error`].
263///
264/// Provides error message extraction and error chain walking for R.
265/// Automatically implemented for any type that implements `Error`.
266///
267/// # Methods
268///
269/// - `error_message()` - Returns the error's display message
270/// - `error_chain()` - Returns all messages in the error chain
271///
272/// # Example
273///
274/// ```rust,ignore
275/// use std::error::Error;
276/// use std::fmt;
277///
278/// #[derive(Debug)]
279/// struct MyError { msg: String, source: Option<Box<dyn Error + Send + Sync>> }
280///
281/// impl fmt::Display for MyError {
282///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
283///         write!(f, "{}", self.msg)
284///     }
285/// }
286///
287/// impl Error for MyError {
288///     fn source(&self) -> Option<&(dyn Error + 'static)> {
289///         self.source.as_ref().map(|e| e.as_ref() as _)
290///     }
291/// }
292///
293/// // Wrap in ExternalPtr for R access
294/// #[derive(ExternalPtr)]
295/// struct MyErrorWrapper(MyError);
296///
297/// #[miniextendr]
298/// impl miniextendr_api::adapter_traits::RError for MyErrorWrapper {}
299/// ```
300#[doc = "Method shim for `RError::error_message`."]
#[doc = r""]
#[doc =
r" Converts SEXP arguments, calls the method, and returns SEXP result."]
#[doc =
r" Both Rust panics and R longjmps are caught via `with_r_unwind_protect`."]
#[doc(hidden)]
#[allow(non_snake_case)]
unsafe extern "C" fn __RError_error_message_shim(data:
        *mut ::std::os::raw::c_void, argc: i32,
    argv: *const ::miniextendr_api::SEXP) -> ::miniextendr_api::SEXP where
    Self: ::core::marker::Sized + RError {
    ::miniextendr_api::unwind_protect::with_r_unwind_protect_shim(||
            {
                ::miniextendr_api::trait_abi::check_arity(argc, 0i32,
                    "RError::error_message");
                let __mx_cell =
                    unsafe { &*data.cast::<::core::cell::RefCell<Self>>() };
                let __mx_guard =
                    ::miniextendr_api::externalptr::borrow_value(__mx_cell);
                let self_ref = &*__mx_guard;
                let result = self_ref.error_message();
                match ::miniextendr_api::into_r::IntoR::try_into_sexp(result)
                    {
                    ::core::result::Result::Ok(__mx_sexp) => __mx_sexp,
                    ::core::result::Result::Err(__mx_error) => unsafe {
                        ::miniextendr_api::error_value::result_err_condition_value(::miniextendr_api::condition::into_r_err_parts(&__mx_error),
                            ::core::option::Option::None)
                    },
                }
            })
}
#[doc = "Method shim for `RError::error_chain`."]
#[doc = r""]
#[doc =
r" Converts SEXP arguments, calls the method, and returns SEXP result."]
#[doc =
r" Both Rust panics and R longjmps are caught via `with_r_unwind_protect`."]
#[doc(hidden)]
#[allow(non_snake_case)]
unsafe extern "C" fn __RError_error_chain_shim(data:
        *mut ::std::os::raw::c_void, argc: i32,
    argv: *const ::miniextendr_api::SEXP) -> ::miniextendr_api::SEXP where
    Self: ::core::marker::Sized + RError {
    ::miniextendr_api::unwind_protect::with_r_unwind_protect_shim(||
            {
                ::miniextendr_api::trait_abi::check_arity(argc, 0i32,
                    "RError::error_chain");
                let __mx_cell =
                    unsafe { &*data.cast::<::core::cell::RefCell<Self>>() };
                let __mx_guard =
                    ::miniextendr_api::externalptr::borrow_value(__mx_cell);
                let self_ref = &*__mx_guard;
                let result = self_ref.error_chain();
                match ::miniextendr_api::into_r::IntoR::try_into_sexp(result)
                    {
                    ::core::result::Result::Ok(__mx_sexp) => __mx_sexp,
                    ::core::result::Result::Err(__mx_error) => unsafe {
                        ::miniextendr_api::error_value::result_err_condition_value(::miniextendr_api::condition::into_r_err_parts(&__mx_error),
                            ::core::option::Option::None)
                    },
                }
            })
}
#[doc = "Method shim for `RError::error_chain_length`."]
#[doc = r""]
#[doc =
r" Converts SEXP arguments, calls the method, and returns SEXP result."]
#[doc =
r" Both Rust panics and R longjmps are caught via `with_r_unwind_protect`."]
#[doc(hidden)]
#[allow(non_snake_case)]
unsafe extern "C" fn __RError_error_chain_length_shim(data:
        *mut ::std::os::raw::c_void, argc: i32,
    argv: *const ::miniextendr_api::SEXP) -> ::miniextendr_api::SEXP where
    Self: ::core::marker::Sized + RError {
    ::miniextendr_api::unwind_protect::with_r_unwind_protect_shim(||
            {
                ::miniextendr_api::trait_abi::check_arity(argc, 0i32,
                    "RError::error_chain_length");
                let __mx_cell =
                    unsafe { &*data.cast::<::core::cell::RefCell<Self>>() };
                let __mx_guard =
                    ::miniextendr_api::externalptr::borrow_value(__mx_cell);
                let self_ref = &*__mx_guard;
                let result = self_ref.error_chain_length();
                match ::miniextendr_api::into_r::IntoR::try_into_sexp(result)
                    {
                    ::core::result::Result::Ok(__mx_sexp) => __mx_sexp,
                    ::core::result::Result::Err(__mx_error) => unsafe {
                        ::miniextendr_api::error_value::result_err_condition_value(::miniextendr_api::condition::into_r_err_parts(&__mx_error),
                            ::core::option::Option::None)
                    },
                }
            })
}
#[doc = "Type tag for runtime identification of the `RError` trait."]
#[doc = "Generated from source location line 301, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[allow(non_upper_case_globals)]
pub const TAG_RError: ::miniextendr_api::abi::mx_tag =
    ::miniextendr_api::abi::mx_tag_from_path("miniextendr::trait-abi/v2;6:RError1:313:error_message13:error_message3:ref1:06:String11:error_chain11:error_chain3:ref1:014:Vec < String >18:error_chain_length18:error_chain_length3:ref1:03:i32");
#[doc = "Vtable for the `RError` trait."]
#[doc = "Generated from source location line 301, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[doc = r""]
#[doc = r" Contains one `mx_meth` function pointer per trait method."]
#[repr(C)]
#[doc(hidden)]
#[allow(non_camel_case_types)]
pub struct RErrorVTable {
    pub error_message: ::miniextendr_api::abi::mx_meth,
    pub error_chain: ::miniextendr_api::abi::mx_meth,
    pub error_chain_length: ::miniextendr_api::abi::mx_meth,
}
#[doc = "Runtime view for objects implementing `RError`."]
#[doc = "Generated from source location line 301, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[doc = r""]
#[doc = r" Keeps the receiver alive for method dispatch. Use `try_from_sexp`"]
#[doc = r" to create a view with its own root for the R external pointer."]
#[doc = r" Construction, use and drop belong on R's main thread."]
#[allow(non_camel_case_types)]
pub struct RErrorView {
    __mx_view: ::miniextendr_api::trait_abi::TraitViewData<RErrorVTable>,
}
impl ::miniextendr_api::TraitView for RErrorView {
    const TAG: ::miniextendr_api::abi::mx_tag = TAG_RError;
    #[inline]
    unsafe fn from_raw_parts(data: *mut ::std::os::raw::c_void,
        vtable: *const ::std::os::raw::c_void,
        owner: ::core::option::Option<::miniextendr_api::SEXP>) -> Self {
        Self {
            __mx_view: unsafe {
                ::miniextendr_api::trait_abi::TraitViewData::new(data, vtable,
                    owner)
            },
        }
    }
}
impl RErrorView {
    #[doc = r" Try to create a view from an R SEXP."]
    #[doc = r""]
    #[doc = r" Returns `Some(Self)` if the object implements this trait,"]
    #[doc = r" `None` otherwise."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc = r" - `sexp` must be a valid R external pointer (EXTPTRSXP)"]
    #[doc =
    r" - The object must stay live through construction; the view then roots it"]
    #[doc =
    r" - A call that conflicts with one still running on the same object"]
    #[doc = r"   raises the `miniextendr_borrow_conflict` error"]
    #[doc = r" - Construction, use and drop must all run on R's main thread"]
    #[inline]
    pub unsafe fn try_from_sexp(sexp: ::miniextendr_api::SEXP)
        -> ::core::option::Option<Self> {
        unsafe { <Self as ::miniextendr_api::TraitView>::try_from_sexp(sexp) }
    }
    #[doc =
    r" Try to create a view, panicking with error message on failure."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc = r" Same as `try_from_sexp`."]
    #[inline]
    pub unsafe fn from_sexp(sexp: ::miniextendr_api::SEXP) -> Self {
        unsafe {
                Self::try_from_sexp(sexp)
            }.expect("Object does not implement RError trait")
    }
    #[doc = "Call `error_message` through the vtable."]
    #[inline]
    #[allow(clippy :: duplicate_underscore_argument)]
    pub fn error_message(&self) -> String {
        unsafe {
            let __mx_roots =
                ::miniextendr_api::gc_protect::ProtectScope::new();
            let result =
                __mx_roots.protect_raw({
                        ((*self.__mx_view.vtable()).error_message)(self.__mx_view.data(),
                            0, ::std::ptr::null())
                    });
            ::miniextendr_api::trait_abi::repanic_if_rust_error(result);
            ::miniextendr_api::trait_abi::from_sexp::<String>(result)
        }
    }
    #[doc = "Call `error_chain` through the vtable."]
    #[inline]
    #[allow(clippy :: duplicate_underscore_argument)]
    pub fn error_chain(&self) -> Vec<String> {
        unsafe {
            let __mx_roots =
                ::miniextendr_api::gc_protect::ProtectScope::new();
            let result =
                __mx_roots.protect_raw({
                        ((*self.__mx_view.vtable()).error_chain)(self.__mx_view.data(),
                            0, ::std::ptr::null())
                    });
            ::miniextendr_api::trait_abi::repanic_if_rust_error(result);
            ::miniextendr_api::trait_abi::from_sexp::<Vec<String>>(result)
        }
    }
    #[doc = "Call `error_chain_length` through the vtable."]
    #[inline]
    #[allow(clippy :: duplicate_underscore_argument)]
    pub fn error_chain_length(&self) -> i32 {
        unsafe {
            let __mx_roots =
                ::miniextendr_api::gc_protect::ProtectScope::new();
            let result =
                __mx_roots.protect_raw({
                        ((*self.__mx_view.vtable()).error_chain_length)(self.__mx_view.data(),
                            0, ::std::ptr::null())
                    });
            ::miniextendr_api::trait_abi::repanic_if_rust_error(result);
            ::miniextendr_api::trait_abi::from_sexp::<i32>(result)
        }
    }
}
#[doc = "Build a vtable for a concrete type implementing `RError`."]
#[doc = "Generated from source location line 301, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[allow(non_snake_case)]
pub const fn __RError_build_vtable<__ImplT: RError>() -> RErrorVTable {
    RErrorVTable {
        error_message: <__ImplT as RError>::__RError_error_message_shim,
        error_chain: <__ImplT as RError>::__RError_error_chain_shim,
        error_chain_length: <__ImplT as
            RError>::__RError_error_chain_length_shim,
    }
}
#[macro_export]
#[doc(hidden)]
macro_rules! __mx_trait_metadata_RError_5 {
    (@ impl { $ ($attrs : tt) * } { $ ($implementation : tt) * }) =>
    {
        :: miniextendr_api :: __mx_trait_impl_expand!
        {
            @ impl { $ ($attrs) * } { $ ($implementation) * }
            {
                #[doc = " Get the error message (Display representation)."] fn
                error_message();
                #[doc =
                " Get all error messages in the chain, from outermost to innermost."]
                fn error_chain();
                #[doc = " Get the number of errors in the chain."] fn
                error_chain_length();
            } {} abi RError false
            "miniextendr::trait-abi/v2;6:RError1:313:error_message13:error_message3:ref1:06:String11:error_chain11:error_chain3:ref1:014:Vec < String >18:error_chain_length18:error_chain_length3:ref1:03:i32"
            {
                pub error_message : :: miniextendr_api :: abi :: mx_meth, pub
                error_chain : :: miniextendr_api :: abi :: mx_meth, pub
                error_chain_length : :: miniextendr_api :: abi :: mx_meth
            }
        }
    };
    ($concrete_type : ty, $trait_path : path, $class_system : ident, $no_rd :
    tt, $internal : tt, $noexport : tt, $no_preconditions : tt) =>
    {
        :: miniextendr_api :: __mx_trait_impl_expand!
        {
            concrete_type = $concrete_type; trait_path = $trait_path;
            class_system = $class_system; no_rd = $no_rd; internal =
            $internal; noexport = $noexport; no_preconditions =
            $no_preconditions; abi RError false
            "miniextendr::trait-abi/v2;6:RError1:313:error_message13:error_message3:ref1:06:String11:error_chain11:error_chain3:ref1:014:Vec < String >18:error_chain_length18:error_chain_length3:ref1:03:i32"
            {
                pub error_message : :: miniextendr_api :: abi :: mx_meth, pub
                error_chain : :: miniextendr_api :: abi :: mx_meth, pub
                error_chain_length : :: miniextendr_api :: abi :: mx_meth
            } method
            {
                r_name = error_message;
                #[doc = " Get the error message (Display representation)."] fn
                error_message(& self) -> String;
            } method
            {
                r_name = error_chain;
                #[doc =
                " Get all error messages in the chain, from outermost to innermost."]
                fn error_chain(& self) -> Vec < String > ;
            } method
            {
                r_name = error_chain_length;
                #[doc = " Get the number of errors in the chain."] fn
                error_chain_length(& self) -> i32;
            }
        }
    };
}
#[doc(hidden)]
#[allow(unused_imports)]
pub use __mx_trait_metadata_RError_5 as RError;#[miniextendr]
301pub trait RError {
302    /// Get the error message (Display representation).
303    fn error_message(&self) -> String;
304
305    /// Get all error messages in the chain, from outermost to innermost.
306    fn error_chain(&self) -> Vec<String>;
307
308    /// Get the number of errors in the chain.
309    fn error_chain_length(&self) -> i32;
310}
311
312impl<T: std::error::Error> RError for T {
313    fn error_message(&self) -> String {
314        self.to_string()
315    }
316
317    fn error_chain(&self) -> Vec<String> {
318        let mut chain = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [self.to_string()]))vec![self.to_string()];
319        let mut current: &dyn std::error::Error = self;
320        while let Some(source) = current.source() {
321            chain.push(source.to_string());
322            current = source;
323        }
324        chain
325    }
326
327    fn error_chain_length(&self) -> i32 {
328        let mut count = 1i32;
329        let mut current: &dyn std::error::Error = self;
330        while let Some(source) = current.source() {
331            count += 1;
332            current = source;
333        }
334        count
335    }
336}
337
338/// Adapter trait for [`std::str::FromStr`].
339///
340/// Provides string parsing for R, allowing R strings to be parsed into Rust types.
341/// Automatically implemented for any type that implements `FromStr`.
342///
343/// # Methods
344///
345/// - `r_from_str(s: &str)` (`from_str()` in R) - Parse a string into this
346///   type, returning None on failure
347///
348/// # Example
349///
350/// ```rust,ignore
351/// use std::net::IpAddr;
352///
353/// // IpAddr implements FromStr
354/// #[derive(ExternalPtr)]
355/// struct IpAddress(IpAddr);
356///
357/// #[miniextendr]
358/// impl miniextendr_api::adapter_traits::RFromStr for IpAddress {}
359/// ```
360///
361/// In R:
362/// ```r
363/// ip <- IpAddress$RFromStr$from_str("192.168.1.1")
364/// ```
365#[doc = "Type tag for runtime identification of the `RFromStr` trait."]
#[doc = "Generated from source location line 366, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[allow(non_upper_case_globals)]
pub const TAG_RFromStr: ::miniextendr_api::abi::mx_tag =
    ::miniextendr_api::abi::mx_tag_from_path("miniextendr::trait-abi/v2;8:RFromStr1:0");
#[doc = "Vtable for the `RFromStr` trait."]
#[doc = "Generated from source location line 366, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[doc = r""]
#[doc = r" Contains one `mx_meth` function pointer per trait method."]
#[repr(C)]
#[doc(hidden)]
#[allow(non_camel_case_types)]
pub struct RFromStrVTable {}
#[doc = "Runtime view for objects implementing `RFromStr`."]
#[doc = "Generated from source location line 366, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[doc = r""]
#[doc = r" Keeps the receiver alive for method dispatch. Use `try_from_sexp`"]
#[doc = r" to create a view with its own root for the R external pointer."]
#[doc = r" Construction, use and drop belong on R's main thread."]
#[allow(non_camel_case_types)]
pub struct RFromStrView {
    __mx_view: ::miniextendr_api::trait_abi::TraitViewData<RFromStrVTable>,
}
impl ::miniextendr_api::TraitView for RFromStrView {
    const TAG: ::miniextendr_api::abi::mx_tag = TAG_RFromStr;
    #[inline]
    unsafe fn from_raw_parts(data: *mut ::std::os::raw::c_void,
        vtable: *const ::std::os::raw::c_void,
        owner: ::core::option::Option<::miniextendr_api::SEXP>) -> Self {
        Self {
            __mx_view: unsafe {
                ::miniextendr_api::trait_abi::TraitViewData::new(data, vtable,
                    owner)
            },
        }
    }
}
impl RFromStrView {
    #[doc = r" Try to create a view from an R SEXP."]
    #[doc = r""]
    #[doc = r" Returns `Some(Self)` if the object implements this trait,"]
    #[doc = r" `None` otherwise."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc = r" - `sexp` must be a valid R external pointer (EXTPTRSXP)"]
    #[doc =
    r" - The object must stay live through construction; the view then roots it"]
    #[doc =
    r" - A call that conflicts with one still running on the same object"]
    #[doc = r"   raises the `miniextendr_borrow_conflict` error"]
    #[doc = r" - Construction, use and drop must all run on R's main thread"]
    #[inline]
    pub unsafe fn try_from_sexp(sexp: ::miniextendr_api::SEXP)
        -> ::core::option::Option<Self> {
        unsafe { <Self as ::miniextendr_api::TraitView>::try_from_sexp(sexp) }
    }
    #[doc =
    r" Try to create a view, panicking with error message on failure."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc = r" Same as `try_from_sexp`."]
    #[inline]
    pub unsafe fn from_sexp(sexp: ::miniextendr_api::SEXP) -> Self {
        unsafe {
                Self::try_from_sexp(sexp)
            }.expect("Object does not implement RFromStr trait")
    }
}
#[doc = "Build a vtable for a concrete type implementing `RFromStr`."]
#[doc = "Generated from source location line 366, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[allow(non_snake_case)]
pub const fn __RFromStr_build_vtable<__ImplT: RFromStr>() -> RFromStrVTable {
    RFromStrVTable {}
}
#[macro_export]
#[doc(hidden)]
macro_rules! __mx_trait_metadata_RFromStr_6 {
    (@ impl { $ ($attrs : tt) * } { $ ($implementation : tt) * }) =>
    {
        :: miniextendr_api :: __mx_trait_impl_expand!
        {
            @ impl { $ ($attrs) * } { $ ($implementation) * }
            {
                #[doc = " Parse a string into this type."] #[doc = ""]
                #[doc =
                " Returns `Some(value)` on success, `None` on parse failure, which R"]
                #[doc = " receives as `NULL`."]
                #[miniextendr(r_name = "from_str")] fn r_from_str(s : ());
            } {} abi RFromStr false "miniextendr::trait-abi/v2;8:RFromStr1:0"
            {}
        }
    };
    ($concrete_type : ty, $trait_path : path, $class_system : ident, $no_rd :
    tt, $internal : tt, $noexport : tt, $no_preconditions : tt) =>
    {
        :: miniextendr_api :: __mx_trait_impl_expand!
        {
            concrete_type = $concrete_type; trait_path = $trait_path;
            class_system = $class_system; no_rd = $no_rd; internal =
            $internal; noexport = $noexport; no_preconditions =
            $no_preconditions; abi RFromStr false
            "miniextendr::trait-abi/v2;8:RFromStr1:0" {} method
            {
                r_name = from_str; #[doc = " Parse a string into this type."]
                #[doc = ""]
                #[doc =
                " Returns `Some(value)` on success, `None` on parse failure, which R"]
                #[doc = " receives as `NULL`."] fn r_from_str(s : & str) ->
                Option < Self > ;
            }
        }
    };
}
#[doc(hidden)]
#[allow(unused_imports)]
pub use __mx_trait_metadata_RFromStr_6 as RFromStr;#[miniextendr]
366pub trait RFromStr: Sized {
367    /// Parse a string into this type.
368    ///
369    /// Returns `Some(value)` on success, `None` on parse failure, which R
370    /// receives as `NULL`.
371    #[miniextendr(r_name = "from_str")]
372    fn r_from_str(s: &str) -> Option<Self>;
373}
374
375impl<T: FromStr> RFromStr for T {
376    fn r_from_str(s: &str) -> Option<Self> {
377        s.parse().ok()
378    }
379}
380
381/// Adapter trait for [`std::clone::Clone`].
382///
383/// Provides explicit deep copying for R. This is useful when R users need
384/// to create independent copies of Rust objects (which normally use reference
385/// semantics via `ExternalPtr`).
386///
387/// # Methods
388///
389/// - `r_clone()` (`clone()` in R) - Create a deep copy of this value
390///
391/// # Example
392///
393/// ```rust,ignore
394/// #[derive(Clone, ExternalPtr)]
395/// struct Buffer { data: Vec<u8> }
396///
397/// #[miniextendr]
398/// impl miniextendr_api::adapter_traits::RClone for Buffer {}
399/// ```
400///
401/// In R:
402/// ```r
403/// buf1 <- Buffer$new(...)
404/// buf2 <- buf1$RClone$clone()  # Independent copy
405/// ```
406#[doc = "Method shim for `RClone::r_clone`."]
#[doc = r""]
#[doc =
r" Converts SEXP arguments, calls the method, and returns SEXP result."]
#[doc =
r" Both Rust panics and R longjmps are caught via `with_r_unwind_protect`."]
#[doc(hidden)]
#[allow(non_snake_case)]
unsafe extern "C" fn __RClone_r_clone_shim(data: *mut ::std::os::raw::c_void,
    argc: i32, argv: *const ::miniextendr_api::SEXP)
    -> ::miniextendr_api::SEXP where Self: ::core::marker::Sized + RClone +
    ::miniextendr_api::IntoR {
    ::miniextendr_api::unwind_protect::with_r_unwind_protect_shim(||
            {
                ::miniextendr_api::trait_abi::check_arity(argc, 0i32,
                    "RClone::r_clone");
                let __mx_cell =
                    unsafe { &*data.cast::<::core::cell::RefCell<Self>>() };
                let __mx_guard =
                    ::miniextendr_api::externalptr::borrow_value(__mx_cell);
                let self_ref = &*__mx_guard;
                let result = self_ref.r_clone();
                match ::miniextendr_api::into_r::IntoR::try_into_sexp(result)
                    {
                    ::core::result::Result::Ok(__mx_sexp) => __mx_sexp,
                    ::core::result::Result::Err(__mx_error) => unsafe {
                        ::miniextendr_api::error_value::result_err_condition_value(::miniextendr_api::condition::into_r_err_parts(&__mx_error),
                            ::core::option::Option::None)
                    },
                }
            })
}
#[doc = "Type tag for runtime identification of the `RClone` trait."]
#[doc = "Generated from source location line 407, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[allow(non_upper_case_globals)]
pub const TAG_RClone: ::miniextendr_api::abi::mx_tag =
    ::miniextendr_api::abi::mx_tag_from_path("miniextendr::trait-abi/v2;6:RClone1:17:r_clone5:clone3:ref1:04:Self");
#[doc = "Vtable for the `RClone` trait."]
#[doc = "Generated from source location line 407, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[doc = r""]
#[doc = r" Contains one `mx_meth` function pointer per trait method."]
#[repr(C)]
#[doc(hidden)]
#[allow(non_camel_case_types)]
pub struct RCloneVTable {
    pub r_clone: ::miniextendr_api::abi::mx_meth,
}
#[doc = "Runtime view for objects implementing `RClone`."]
#[doc = "Generated from source location line 407, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[doc = r""]
#[doc = r" Keeps the receiver alive for method dispatch. Use `try_from_sexp`"]
#[doc = r" to create a view with its own root for the R external pointer."]
#[doc = r" Construction, use and drop belong on R's main thread."]
#[allow(non_camel_case_types)]
pub struct RCloneView {
    __mx_view: ::miniextendr_api::trait_abi::TraitViewData<RCloneVTable>,
}
impl ::miniextendr_api::TraitView for RCloneView {
    const TAG: ::miniextendr_api::abi::mx_tag = TAG_RClone;
    #[inline]
    unsafe fn from_raw_parts(data: *mut ::std::os::raw::c_void,
        vtable: *const ::std::os::raw::c_void,
        owner: ::core::option::Option<::miniextendr_api::SEXP>) -> Self {
        Self {
            __mx_view: unsafe {
                ::miniextendr_api::trait_abi::TraitViewData::new(data, vtable,
                    owner)
            },
        }
    }
}
impl RCloneView {
    #[doc = r" Try to create a view from an R SEXP."]
    #[doc = r""]
    #[doc = r" Returns `Some(Self)` if the object implements this trait,"]
    #[doc = r" `None` otherwise."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc = r" - `sexp` must be a valid R external pointer (EXTPTRSXP)"]
    #[doc =
    r" - The object must stay live through construction; the view then roots it"]
    #[doc =
    r" - A call that conflicts with one still running on the same object"]
    #[doc = r"   raises the `miniextendr_borrow_conflict` error"]
    #[doc = r" - Construction, use and drop must all run on R's main thread"]
    #[inline]
    pub unsafe fn try_from_sexp(sexp: ::miniextendr_api::SEXP)
        -> ::core::option::Option<Self> {
        unsafe { <Self as ::miniextendr_api::TraitView>::try_from_sexp(sexp) }
    }
    #[doc =
    r" Try to create a view, panicking with error message on failure."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc = r" Same as `try_from_sexp`."]
    #[inline]
    pub unsafe fn from_sexp(sexp: ::miniextendr_api::SEXP) -> Self {
        unsafe {
                Self::try_from_sexp(sexp)
            }.expect("Object does not implement RClone trait")
    }
}
#[doc = "Build a vtable for a concrete type implementing `RClone`."]
#[doc = "Generated from source location line 407, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[allow(non_snake_case)]
pub const fn __RClone_build_vtable<__ImplT: RClone +
    ::miniextendr_api::IntoR>() -> RCloneVTable {
    RCloneVTable { r_clone: <__ImplT as RClone>::__RClone_r_clone_shim }
}
#[macro_export]
#[doc(hidden)]
macro_rules! __mx_trait_metadata_RClone_7 {
    (@ impl { $ ($attrs : tt) * } { $ ($implementation : tt) * }) =>
    {
        :: miniextendr_api :: __mx_trait_impl_expand!
        {
            @ impl { $ ($attrs) * } { $ ($implementation) * }
            {
                #[doc = " Create a deep copy of this value."]
                #[miniextendr(r_name = "clone")] fn r_clone();
            } {} abi RClone false
            "miniextendr::trait-abi/v2;6:RClone1:17:r_clone5:clone3:ref1:04:Self"
            { pub r_clone : :: miniextendr_api :: abi :: mx_meth }
        }
    };
    ($concrete_type : ty, $trait_path : path, $class_system : ident, $no_rd :
    tt, $internal : tt, $noexport : tt, $no_preconditions : tt) =>
    {
        :: miniextendr_api :: __mx_trait_impl_expand!
        {
            concrete_type = $concrete_type; trait_path = $trait_path;
            class_system = $class_system; no_rd = $no_rd; internal =
            $internal; noexport = $noexport; no_preconditions =
            $no_preconditions; abi RClone false
            "miniextendr::trait-abi/v2;6:RClone1:17:r_clone5:clone3:ref1:04:Self"
            { pub r_clone : :: miniextendr_api :: abi :: mx_meth } method
            {
                r_name = clone; #[doc = " Create a deep copy of this value."]
                fn r_clone(& self) -> Self;
            }
        }
    };
}
#[doc(hidden)]
#[allow(unused_imports)]
pub use __mx_trait_metadata_RClone_7 as RClone;#[miniextendr]
407pub trait RClone {
408    /// Create a deep copy of this value.
409    #[miniextendr(r_name = "clone")]
410    fn r_clone(&self) -> Self;
411}
412
413impl<T: Clone> RClone for T {
414    fn r_clone(&self) -> Self {
415        Clone::clone(self)
416    }
417}
418
419/// Adapter trait for [`std::default::Default`].
420///
421/// Provides default value construction for R. This allows R users to create
422/// instances with default values without needing to specify all parameters.
423///
424/// # Methods
425///
426/// - `r_default()` (`default()` in R) - Create a new instance with default
427///   values
428///
429/// # Example
430///
431/// ```rust,ignore
432/// #[derive(Default, ExternalPtr)]
433/// struct Config {
434///     timeout: u32,     // defaults to 0
435///     retries: u32,     // defaults to 0
436///     verbose: bool,    // defaults to false
437/// }
438///
439/// #[miniextendr]
440/// impl miniextendr_api::adapter_traits::RDefault for Config {}
441/// ```
442///
443/// In R:
444/// ```r
445/// config <- Config$RDefault$default()  # All fields have default values
446/// ```
447#[doc = "Type tag for runtime identification of the `RDefault` trait."]
#[doc = "Generated from source location line 448, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[allow(non_upper_case_globals)]
pub const TAG_RDefault: ::miniextendr_api::abi::mx_tag =
    ::miniextendr_api::abi::mx_tag_from_path("miniextendr::trait-abi/v2;8:RDefault1:0");
#[doc = "Vtable for the `RDefault` trait."]
#[doc = "Generated from source location line 448, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[doc = r""]
#[doc = r" Contains one `mx_meth` function pointer per trait method."]
#[repr(C)]
#[doc(hidden)]
#[allow(non_camel_case_types)]
pub struct RDefaultVTable {}
#[doc = "Runtime view for objects implementing `RDefault`."]
#[doc = "Generated from source location line 448, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[doc = r""]
#[doc = r" Keeps the receiver alive for method dispatch. Use `try_from_sexp`"]
#[doc = r" to create a view with its own root for the R external pointer."]
#[doc = r" Construction, use and drop belong on R's main thread."]
#[allow(non_camel_case_types)]
pub struct RDefaultView {
    __mx_view: ::miniextendr_api::trait_abi::TraitViewData<RDefaultVTable>,
}
impl ::miniextendr_api::TraitView for RDefaultView {
    const TAG: ::miniextendr_api::abi::mx_tag = TAG_RDefault;
    #[inline]
    unsafe fn from_raw_parts(data: *mut ::std::os::raw::c_void,
        vtable: *const ::std::os::raw::c_void,
        owner: ::core::option::Option<::miniextendr_api::SEXP>) -> Self {
        Self {
            __mx_view: unsafe {
                ::miniextendr_api::trait_abi::TraitViewData::new(data, vtable,
                    owner)
            },
        }
    }
}
impl RDefaultView {
    #[doc = r" Try to create a view from an R SEXP."]
    #[doc = r""]
    #[doc = r" Returns `Some(Self)` if the object implements this trait,"]
    #[doc = r" `None` otherwise."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc = r" - `sexp` must be a valid R external pointer (EXTPTRSXP)"]
    #[doc =
    r" - The object must stay live through construction; the view then roots it"]
    #[doc =
    r" - A call that conflicts with one still running on the same object"]
    #[doc = r"   raises the `miniextendr_borrow_conflict` error"]
    #[doc = r" - Construction, use and drop must all run on R's main thread"]
    #[inline]
    pub unsafe fn try_from_sexp(sexp: ::miniextendr_api::SEXP)
        -> ::core::option::Option<Self> {
        unsafe { <Self as ::miniextendr_api::TraitView>::try_from_sexp(sexp) }
    }
    #[doc =
    r" Try to create a view, panicking with error message on failure."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc = r" Same as `try_from_sexp`."]
    #[inline]
    pub unsafe fn from_sexp(sexp: ::miniextendr_api::SEXP) -> Self {
        unsafe {
                Self::try_from_sexp(sexp)
            }.expect("Object does not implement RDefault trait")
    }
}
#[doc = "Build a vtable for a concrete type implementing `RDefault`."]
#[doc = "Generated from source location line 448, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[allow(non_snake_case)]
pub const fn __RDefault_build_vtable<__ImplT: RDefault>() -> RDefaultVTable {
    RDefaultVTable {}
}
#[macro_export]
#[doc(hidden)]
macro_rules! __mx_trait_metadata_RDefault_8 {
    (@ impl { $ ($attrs : tt) * } { $ ($implementation : tt) * }) =>
    {
        :: miniextendr_api :: __mx_trait_impl_expand!
        {
            @ impl { $ ($attrs) * } { $ ($implementation) * }
            {
                #[doc = " Create a new instance with default values."]
                #[miniextendr(r_name = "default")] fn r_default();
            } {} abi RDefault false "miniextendr::trait-abi/v2;8:RDefault1:0"
            {}
        }
    };
    ($concrete_type : ty, $trait_path : path, $class_system : ident, $no_rd :
    tt, $internal : tt, $noexport : tt, $no_preconditions : tt) =>
    {
        :: miniextendr_api :: __mx_trait_impl_expand!
        {
            concrete_type = $concrete_type; trait_path = $trait_path;
            class_system = $class_system; no_rd = $no_rd; internal =
            $internal; noexport = $noexport; no_preconditions =
            $no_preconditions; abi RDefault false
            "miniextendr::trait-abi/v2;8:RDefault1:0" {} method
            {
                r_name = default;
                #[doc = " Create a new instance with default values."] fn
                r_default() -> Self;
            }
        }
    };
}
#[doc(hidden)]
#[allow(unused_imports)]
pub use __mx_trait_metadata_RDefault_8 as RDefault;#[miniextendr]
448pub trait RDefault {
449    /// Create a new instance with default values.
450    #[miniextendr(r_name = "default")]
451    fn r_default() -> Self;
452}
453
454impl<T: Default> RDefault for T {
455    fn r_default() -> Self {
456        <T as Default>::default()
457    }
458}
459
460/// Adapter trait for [`std::marker::Copy`].
461///
462/// Indicates that a type can be cheaply copied (bitwise copy, no heap allocation).
463/// This is useful for R users to know that copying is O(1) and doesn't involve
464/// deep cloning of heap data.
465///
466/// # Methods
467///
468/// - `copy()` - Create a bitwise copy of this value
469/// - `is_copy()` - Returns true (useful for runtime type checking in R)
470///
471/// # Difference from RClone
472///
473/// Both `RCopy` and `RClone` create copies, but:
474/// - `RCopy`: Only for types where copying is cheap (stack-only, no heap)
475/// - `RClone`: For any clonable type (may involve heap allocation)
476///
477/// If a type implements both, prefer `copy()` when you know copies are frequent.
478///
479/// # Example
480///
481/// ```rust,ignore
482/// #[derive(Copy, Clone, ExternalPtr)]
483/// struct Point { x: f64, y: f64 }
484///
485/// #[miniextendr]
486/// impl miniextendr_api::adapter_traits::RCopy for Point {}
487/// ```
488///
489/// In R:
490/// ```r
491/// p1 <- Point$new(1.0, 2.0)
492/// p2 <- p1$RCopy$copy()  # Cheap bitwise copy
493/// p1$RCopy$is_copy()       # TRUE
494/// ```
495#[doc = "Method shim for `RCopy::copy`."]
#[doc = r""]
#[doc =
r" Converts SEXP arguments, calls the method, and returns SEXP result."]
#[doc =
r" Both Rust panics and R longjmps are caught via `with_r_unwind_protect`."]
#[doc(hidden)]
#[allow(non_snake_case)]
unsafe extern "C" fn __RCopy_copy_shim(data: *mut ::std::os::raw::c_void,
    argc: i32, argv: *const ::miniextendr_api::SEXP)
    -> ::miniextendr_api::SEXP where Self: ::core::marker::Sized + RCopy +
    ::miniextendr_api::IntoR {
    ::miniextendr_api::unwind_protect::with_r_unwind_protect_shim(||
            {
                ::miniextendr_api::trait_abi::check_arity(argc, 0i32,
                    "RCopy::copy");
                let __mx_cell =
                    unsafe { &*data.cast::<::core::cell::RefCell<Self>>() };
                let __mx_guard =
                    ::miniextendr_api::externalptr::borrow_value(__mx_cell);
                let self_ref = &*__mx_guard;
                let result = self_ref.copy();
                match ::miniextendr_api::into_r::IntoR::try_into_sexp(result)
                    {
                    ::core::result::Result::Ok(__mx_sexp) => __mx_sexp,
                    ::core::result::Result::Err(__mx_error) => unsafe {
                        ::miniextendr_api::error_value::result_err_condition_value(::miniextendr_api::condition::into_r_err_parts(&__mx_error),
                            ::core::option::Option::None)
                    },
                }
            })
}
#[doc = "Method shim for `RCopy::is_copy`."]
#[doc = r""]
#[doc =
r" Converts SEXP arguments, calls the method, and returns SEXP result."]
#[doc =
r" Both Rust panics and R longjmps are caught via `with_r_unwind_protect`."]
#[doc(hidden)]
#[allow(non_snake_case)]
unsafe extern "C" fn __RCopy_is_copy_shim(data: *mut ::std::os::raw::c_void,
    argc: i32, argv: *const ::miniextendr_api::SEXP)
    -> ::miniextendr_api::SEXP where Self: ::core::marker::Sized + RCopy +
    ::miniextendr_api::IntoR {
    ::miniextendr_api::unwind_protect::with_r_unwind_protect_shim(||
            {
                ::miniextendr_api::trait_abi::check_arity(argc, 0i32,
                    "RCopy::is_copy");
                let __mx_cell =
                    unsafe { &*data.cast::<::core::cell::RefCell<Self>>() };
                let __mx_guard =
                    ::miniextendr_api::externalptr::borrow_value(__mx_cell);
                let self_ref = &*__mx_guard;
                let result = self_ref.is_copy();
                match ::miniextendr_api::into_r::IntoR::try_into_sexp(result)
                    {
                    ::core::result::Result::Ok(__mx_sexp) => __mx_sexp,
                    ::core::result::Result::Err(__mx_error) => unsafe {
                        ::miniextendr_api::error_value::result_err_condition_value(::miniextendr_api::condition::into_r_err_parts(&__mx_error),
                            ::core::option::Option::None)
                    },
                }
            })
}
#[doc = "Type tag for runtime identification of the `RCopy` trait."]
#[doc = "Generated from source location line 496, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[allow(non_upper_case_globals)]
pub const TAG_RCopy: ::miniextendr_api::abi::mx_tag =
    ::miniextendr_api::abi::mx_tag_from_path("miniextendr::trait-abi/v2;5:RCopy1:24:copy4:copy3:ref1:04:Self7:is_copy7:is_copy3:ref1:04:bool");
#[doc = "Vtable for the `RCopy` trait."]
#[doc = "Generated from source location line 496, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[doc = r""]
#[doc = r" Contains one `mx_meth` function pointer per trait method."]
#[repr(C)]
#[doc(hidden)]
#[allow(non_camel_case_types)]
pub struct RCopyVTable {
    pub copy: ::miniextendr_api::abi::mx_meth,
    pub is_copy: ::miniextendr_api::abi::mx_meth,
}
#[doc = "Runtime view for objects implementing `RCopy`."]
#[doc = "Generated from source location line 496, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[doc = r""]
#[doc = r" Keeps the receiver alive for method dispatch. Use `try_from_sexp`"]
#[doc = r" to create a view with its own root for the R external pointer."]
#[doc = r" Construction, use and drop belong on R's main thread."]
#[allow(non_camel_case_types)]
pub struct RCopyView {
    __mx_view: ::miniextendr_api::trait_abi::TraitViewData<RCopyVTable>,
}
impl ::miniextendr_api::TraitView for RCopyView {
    const TAG: ::miniextendr_api::abi::mx_tag = TAG_RCopy;
    #[inline]
    unsafe fn from_raw_parts(data: *mut ::std::os::raw::c_void,
        vtable: *const ::std::os::raw::c_void,
        owner: ::core::option::Option<::miniextendr_api::SEXP>) -> Self {
        Self {
            __mx_view: unsafe {
                ::miniextendr_api::trait_abi::TraitViewData::new(data, vtable,
                    owner)
            },
        }
    }
}
impl RCopyView {
    #[doc = r" Try to create a view from an R SEXP."]
    #[doc = r""]
    #[doc = r" Returns `Some(Self)` if the object implements this trait,"]
    #[doc = r" `None` otherwise."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc = r" - `sexp` must be a valid R external pointer (EXTPTRSXP)"]
    #[doc =
    r" - The object must stay live through construction; the view then roots it"]
    #[doc =
    r" - A call that conflicts with one still running on the same object"]
    #[doc = r"   raises the `miniextendr_borrow_conflict` error"]
    #[doc = r" - Construction, use and drop must all run on R's main thread"]
    #[inline]
    pub unsafe fn try_from_sexp(sexp: ::miniextendr_api::SEXP)
        -> ::core::option::Option<Self> {
        unsafe { <Self as ::miniextendr_api::TraitView>::try_from_sexp(sexp) }
    }
    #[doc =
    r" Try to create a view, panicking with error message on failure."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc = r" Same as `try_from_sexp`."]
    #[inline]
    pub unsafe fn from_sexp(sexp: ::miniextendr_api::SEXP) -> Self {
        unsafe {
                Self::try_from_sexp(sexp)
            }.expect("Object does not implement RCopy trait")
    }
    #[doc = "Call `is_copy` through the vtable."]
    #[inline]
    #[allow(clippy :: duplicate_underscore_argument)]
    pub fn is_copy(&self) -> bool {
        unsafe {
            let __mx_roots =
                ::miniextendr_api::gc_protect::ProtectScope::new();
            let result =
                __mx_roots.protect_raw({
                        ((*self.__mx_view.vtable()).is_copy)(self.__mx_view.data(),
                            0, ::std::ptr::null())
                    });
            ::miniextendr_api::trait_abi::repanic_if_rust_error(result);
            ::miniextendr_api::trait_abi::from_sexp::<bool>(result)
        }
    }
}
#[doc = "Build a vtable for a concrete type implementing `RCopy`."]
#[doc = "Generated from source location line 496, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[allow(non_snake_case)]
pub const fn __RCopy_build_vtable<__ImplT: RCopy + ::miniextendr_api::IntoR>()
    -> RCopyVTable {
    RCopyVTable {
        copy: <__ImplT as RCopy>::__RCopy_copy_shim,
        is_copy: <__ImplT as RCopy>::__RCopy_is_copy_shim,
    }
}
#[macro_export]
#[doc(hidden)]
macro_rules! __mx_trait_metadata_RCopy_9 {
    (@ impl { $ ($attrs : tt) * } { $ ($implementation : tt) * }) =>
    {
        :: miniextendr_api :: __mx_trait_impl_expand!
        {
            @ impl { $ ($attrs) * } { $ ($implementation) * }
            {
                #[doc = " Create a bitwise copy of this value."] #[doc = ""]
                #[doc =
                " For Copy types, this is always cheap (O(1), no heap allocation)."]
                fn copy(); #[doc = " Check if this type implements Copy."]
                #[doc = ""]
                #[doc =
                " Always returns true for types implementing this trait."]
                #[doc = " Useful for runtime type checking in R."] fn
                is_copy();
            } {} abi RCopy false
            "miniextendr::trait-abi/v2;5:RCopy1:24:copy4:copy3:ref1:04:Self7:is_copy7:is_copy3:ref1:04:bool"
            {
                pub copy : :: miniextendr_api :: abi :: mx_meth, pub is_copy :
                :: miniextendr_api :: abi :: mx_meth
            }
        }
    };
    ($concrete_type : ty, $trait_path : path, $class_system : ident, $no_rd :
    tt, $internal : tt, $noexport : tt, $no_preconditions : tt) =>
    {
        :: miniextendr_api :: __mx_trait_impl_expand!
        {
            concrete_type = $concrete_type; trait_path = $trait_path;
            class_system = $class_system; no_rd = $no_rd; internal =
            $internal; noexport = $noexport; no_preconditions =
            $no_preconditions; abi RCopy false
            "miniextendr::trait-abi/v2;5:RCopy1:24:copy4:copy3:ref1:04:Self7:is_copy7:is_copy3:ref1:04:bool"
            {
                pub copy : :: miniextendr_api :: abi :: mx_meth, pub is_copy :
                :: miniextendr_api :: abi :: mx_meth
            } method
            {
                r_name = copy;
                #[doc = " Create a bitwise copy of this value."] #[doc = ""]
                #[doc =
                " For Copy types, this is always cheap (O(1), no heap allocation)."]
                fn copy(& self) -> Self;
            } method
            {
                r_name = is_copy;
                #[doc = " Check if this type implements Copy."] #[doc = ""]
                #[doc =
                " Always returns true for types implementing this trait."]
                #[doc = " Useful for runtime type checking in R."] fn
                is_copy(& self) -> bool;
            }
        }
    };
}
#[doc(hidden)]
#[allow(unused_imports)]
pub use __mx_trait_metadata_RCopy_9 as RCopy;#[miniextendr]
496pub trait RCopy {
497    /// Create a bitwise copy of this value.
498    ///
499    /// For Copy types, this is always cheap (O(1), no heap allocation).
500    fn copy(&self) -> Self;
501
502    /// Check if this type implements Copy.
503    ///
504    /// Always returns true for types implementing this trait.
505    /// Useful for runtime type checking in R.
506    fn is_copy(&self) -> bool;
507}
508
509impl<T: Copy> RCopy for T {
510    fn copy(&self) -> Self {
511        *self
512    }
513
514    fn is_copy(&self) -> bool {
515        true
516    }
517}
518
519/// Adapter trait for [`std::iter::Iterator`].
520///
521/// Provides iterator operations for R, allowing Rust iterators to be consumed
522/// element-by-element from R code. Since iterators are stateful, the wrapper
523/// type should use interior mutability (e.g., `RefCell`).
524///
525/// # Methods
526///
527/// - `next()` (`next_item()` in R) - Get the next element, or None if exhausted
528/// - `size_hint()` - Get estimated remaining elements as `list(lower, upper)`
529/// - `count()` - Consume and count remaining elements
530/// - `collect_n(n)` - Collect up to n elements into a vector
531/// - `skip(n)` - Skip n elements
532/// - `nth(n)` - Get the nth element (0-indexed)
533///
534/// # Example
535///
536/// ```rust,ignore
537/// use miniextendr_api::Nullable;
538/// use miniextendr_api::adapter_traits::RIterator;
539/// use std::cell::RefCell;
540///
541/// #[derive(ExternalPtr)]
542/// struct MyIter(RefCell<std::vec::IntoIter<i32>>);
543///
544/// #[miniextendr(env)]
545/// impl MyIter {
546///     fn new(data: Vec<i32>) -> Self {
547///         Self(RefCell::new(data.into_iter()))
548///     }
549/// }
550///
551/// // An impl with a body inherits the trait's R names; each method here
552/// // forwards to the cell.
553/// #[miniextendr(env)]
554/// impl miniextendr_api::adapter_traits::RIterator for MyIter {
555///     type Item = i32;
556///
557///     fn next(&self) -> Nullable<i32> {
558///         self.0.next()
559///     }
560///
561///     fn size_hint(&self) -> (i64, Option<i64>) {
562///         self.0.size_hint()
563///     }
564///
565///     fn count(&self) -> i64 {
566///         self.0.count()
567///     }
568///
569///     fn collect_n(&self, n: i32) -> Vec<i32> {
570///         self.0.collect_n(n)
571///     }
572///
573///     fn skip(&self, n: i32) -> i32 {
574///         self.0.skip(n)
575///     }
576///
577///     fn nth(&self, n: i32) -> Nullable<i32> {
578///         self.0.nth(n)
579///     }
580/// }
581/// ```
582///
583/// In R (`next` is a reserved word, so the method is `next_item`):
584/// ```r
585/// it <- MyIter$new(c(1L, 2L, 3L))
586/// it$RIterator$next_item()   # 1L
587/// it$RIterator$next_item()   # 2L
588/// it$RIterator$size_hint()   # list(1L, 1L) - one element remaining
589/// it$RIterator$collect_n(5L) # 3L
590/// it$RIterator$next_item()   # NULL (exhausted)
591/// ```
592///
593/// # Design Note
594///
595/// Every `RefCell<I>` with `I: Iterator` implements this trait. The cell
596/// supplies mutable access without erasing the iterator or restricting its item
597/// type. A concrete ExternalPtr class can delegate to its cell. This also covers
598/// standard-library adapters, `itertools` adapters and distribution iterators.
599///
600/// The blanket implementation forwards `nth` to the iterator, retaining its
601/// specialized implementation. It follows the source's
602/// exhaustion behavior; use `Iterator::fuse` when `None` must be permanent.
603#[doc = "Method shim for `RIterator::next`."]
#[doc = r""]
#[doc =
r" Converts SEXP arguments, calls the method, and returns SEXP result."]
#[doc =
r" Both Rust panics and R longjmps are caught via `with_r_unwind_protect`."]
#[doc(hidden)]
#[allow(non_snake_case)]
unsafe extern "C" fn __RIterator_next_shim(data: *mut ::std::os::raw::c_void,
    argc: i32, argv: *const ::miniextendr_api::SEXP)
    -> ::miniextendr_api::SEXP where
    Nullable<<Self as RIterator>::Item>: ::miniextendr_api::IntoR,
    Vec<<Self as RIterator>::Item>: ::miniextendr_api::IntoR,
    Self: ::core::marker::Sized + RIterator + ::miniextendr_api::IntoR {
    ::miniextendr_api::unwind_protect::with_r_unwind_protect_shim(||
            {
                ::miniextendr_api::trait_abi::check_arity(argc, 0i32,
                    "RIterator::next");
                let __mx_cell =
                    unsafe { &*data.cast::<::core::cell::RefCell<Self>>() };
                let __mx_guard =
                    ::miniextendr_api::externalptr::borrow_value(__mx_cell);
                let self_ref = &*__mx_guard;
                let result = self_ref.next();
                match ::miniextendr_api::into_r::IntoR::try_into_sexp(result)
                    {
                    ::core::result::Result::Ok(__mx_sexp) => __mx_sexp,
                    ::core::result::Result::Err(__mx_error) => unsafe {
                        ::miniextendr_api::error_value::result_err_condition_value(::miniextendr_api::condition::into_r_err_parts(&__mx_error),
                            ::core::option::Option::None)
                    },
                }
            })
}
#[doc = "Method shim for `RIterator::size_hint`."]
#[doc = r""]
#[doc =
r" Converts SEXP arguments, calls the method, and returns SEXP result."]
#[doc =
r" Both Rust panics and R longjmps are caught via `with_r_unwind_protect`."]
#[doc(hidden)]
#[allow(non_snake_case)]
unsafe extern "C" fn __RIterator_size_hint_shim(data:
        *mut ::std::os::raw::c_void, argc: i32,
    argv: *const ::miniextendr_api::SEXP) -> ::miniextendr_api::SEXP where
    Nullable<<Self as RIterator>::Item>: ::miniextendr_api::IntoR,
    Vec<<Self as RIterator>::Item>: ::miniextendr_api::IntoR,
    Self: ::core::marker::Sized + RIterator + ::miniextendr_api::IntoR {
    ::miniextendr_api::unwind_protect::with_r_unwind_protect_shim(||
            {
                ::miniextendr_api::trait_abi::check_arity(argc, 0i32,
                    "RIterator::size_hint");
                let __mx_cell =
                    unsafe { &*data.cast::<::core::cell::RefCell<Self>>() };
                let __mx_guard =
                    ::miniextendr_api::externalptr::borrow_value(__mx_cell);
                let self_ref = &*__mx_guard;
                let result = self_ref.size_hint();
                match ::miniextendr_api::into_r::IntoR::try_into_sexp(result)
                    {
                    ::core::result::Result::Ok(__mx_sexp) => __mx_sexp,
                    ::core::result::Result::Err(__mx_error) => unsafe {
                        ::miniextendr_api::error_value::result_err_condition_value(::miniextendr_api::condition::into_r_err_parts(&__mx_error),
                            ::core::option::Option::None)
                    },
                }
            })
}
#[doc = "Method shim for `RIterator::count`."]
#[doc = r""]
#[doc =
r" Converts SEXP arguments, calls the method, and returns SEXP result."]
#[doc =
r" Both Rust panics and R longjmps are caught via `with_r_unwind_protect`."]
#[doc(hidden)]
#[allow(non_snake_case)]
unsafe extern "C" fn __RIterator_count_shim(data: *mut ::std::os::raw::c_void,
    argc: i32, argv: *const ::miniextendr_api::SEXP)
    -> ::miniextendr_api::SEXP where
    Nullable<<Self as RIterator>::Item>: ::miniextendr_api::IntoR,
    Vec<<Self as RIterator>::Item>: ::miniextendr_api::IntoR,
    Self: ::core::marker::Sized + RIterator + ::miniextendr_api::IntoR {
    ::miniextendr_api::unwind_protect::with_r_unwind_protect_shim(||
            {
                ::miniextendr_api::trait_abi::check_arity(argc, 0i32,
                    "RIterator::count");
                let __mx_cell =
                    unsafe { &*data.cast::<::core::cell::RefCell<Self>>() };
                let __mx_guard =
                    ::miniextendr_api::externalptr::borrow_value(__mx_cell);
                let self_ref = &*__mx_guard;
                let result = self_ref.count();
                match ::miniextendr_api::into_r::IntoR::try_into_sexp(result)
                    {
                    ::core::result::Result::Ok(__mx_sexp) => __mx_sexp,
                    ::core::result::Result::Err(__mx_error) => unsafe {
                        ::miniextendr_api::error_value::result_err_condition_value(::miniextendr_api::condition::into_r_err_parts(&__mx_error),
                            ::core::option::Option::None)
                    },
                }
            })
}
#[doc = "Method shim for `RIterator::collect_n`."]
#[doc = r""]
#[doc =
r" Converts SEXP arguments, calls the method, and returns SEXP result."]
#[doc =
r" Both Rust panics and R longjmps are caught via `with_r_unwind_protect`."]
#[doc(hidden)]
#[allow(non_snake_case)]
unsafe extern "C" fn __RIterator_collect_n_shim(data:
        *mut ::std::os::raw::c_void, argc: i32,
    argv: *const ::miniextendr_api::SEXP) -> ::miniextendr_api::SEXP where
    Nullable<<Self as RIterator>::Item>: ::miniextendr_api::IntoR,
    Vec<<Self as RIterator>::Item>: ::miniextendr_api::IntoR,
    Self: ::core::marker::Sized + RIterator + ::miniextendr_api::IntoR {
    ::miniextendr_api::unwind_protect::with_r_unwind_protect_shim(||
            {
                ::miniextendr_api::trait_abi::check_arity(argc, 1i32,
                    "RIterator::collect_n");
                let __mx_cell =
                    unsafe { &*data.cast::<::core::cell::RefCell<Self>>() };
                let mut __mx_prepared_0 =
                    ::miniextendr_api::from_r::prepared::Prepared::Unprepared;
                {
                    let mut __miniextendr_native_borrows =
                        [<i32 as ::miniextendr_api::TryFromSexp>::NATIVE_BORROW];
                    if ::miniextendr_api::from_r::borrow::needs_check(&__miniextendr_native_borrows)
                        {
                        let __miniextendr_native_args =
                            [(unsafe { *argv.add(0usize) }, "n")];
                        if ::miniextendr_api::from_r::NativeBorrow::selects(<i32 as
                                    ::miniextendr_api::TryFromSexp>::NATIVE_BORROW) {
                            let __miniextendr_select =
                                unsafe {
                                    ::miniextendr_api::from_r::borrow::assert_or_select(__miniextendr_native_args,
                                        __miniextendr_native_borrows)
                                };
                            if <[bool]>::contains(&__miniextendr_select, &true) {
                                if ::miniextendr_api::from_r::NativeBorrow::selects(<i32 as
                                                ::miniextendr_api::TryFromSexp>::NATIVE_BORROW) &&
                                        __miniextendr_select[0usize] {
                                    __mx_prepared_0 =
                                        <i32 as
                                                ::miniextendr_api::TryFromSexp>::__mx_prepare(unsafe {
                                                *argv.add(0usize)
                                            });
                                    __miniextendr_native_borrows[0usize] =
                                        ::miniextendr_api::from_r::prepared::Prepared::borrow(&__mx_prepared_0,
                                            __miniextendr_native_borrows[0usize]);
                                }
                                unsafe {
                                    ::miniextendr_api::from_r::borrow::assert_no_aliases(__miniextendr_native_args,
                                        __miniextendr_native_borrows);
                                }
                            }
                        } else {
                            unsafe {
                                ::miniextendr_api::from_r::borrow::assert_no_aliases(__miniextendr_native_args,
                                    __miniextendr_native_borrows);
                            }
                        }
                    }
                }
                let n: i32 =
                    match ::miniextendr_api::from_r::prepared::convert::<i32>(__mx_prepared_0,
                            unsafe { *argv.add(0usize) }) {
                        ::core::result::Result::Ok(value) => value,
                        ::core::result::Result::Err(e) =>
                            return unsafe {
                                    ::miniextendr_api::error_value::conversion_condition_value("'n' must be a single integer",
                                        "n", ::core::option::Option::Some("i32"),
                                        ::miniextendr_api::trait_abi::conversion_error_class(),
                                        {
                                            #[allow(unused_imports)]
                                            use crate::condition::{
                                                ConversionErrBuiltin as _, ConversionErrClassed as _,
                                                ConversionErrDisplay as _,
                                            };
                                            match &e { __mx_e => __mx_e.__mx_conversion_parts(true), }
                                        }, ::core::option::Option::None,
                                        ::core::option::Option::None)
                                },
                    };
                let __mx_guard =
                    ::miniextendr_api::externalptr::borrow_value(__mx_cell);
                let self_ref = &*__mx_guard;
                let result = self_ref.collect_n(n);
                match ::miniextendr_api::into_r::IntoR::try_into_sexp(result)
                    {
                    ::core::result::Result::Ok(__mx_sexp) => __mx_sexp,
                    ::core::result::Result::Err(__mx_error) => unsafe {
                        ::miniextendr_api::error_value::result_err_condition_value(::miniextendr_api::condition::into_r_err_parts(&__mx_error),
                            ::core::option::Option::None)
                    },
                }
            })
}
#[doc = "Method shim for `RIterator::skip`."]
#[doc = r""]
#[doc =
r" Converts SEXP arguments, calls the method, and returns SEXP result."]
#[doc =
r" Both Rust panics and R longjmps are caught via `with_r_unwind_protect`."]
#[doc(hidden)]
#[allow(non_snake_case)]
unsafe extern "C" fn __RIterator_skip_shim(data: *mut ::std::os::raw::c_void,
    argc: i32, argv: *const ::miniextendr_api::SEXP)
    -> ::miniextendr_api::SEXP where
    Nullable<<Self as RIterator>::Item>: ::miniextendr_api::IntoR,
    Vec<<Self as RIterator>::Item>: ::miniextendr_api::IntoR,
    Self: ::core::marker::Sized + RIterator + ::miniextendr_api::IntoR {
    ::miniextendr_api::unwind_protect::with_r_unwind_protect_shim(||
            {
                ::miniextendr_api::trait_abi::check_arity(argc, 1i32,
                    "RIterator::skip");
                let __mx_cell =
                    unsafe { &*data.cast::<::core::cell::RefCell<Self>>() };
                let mut __mx_prepared_0 =
                    ::miniextendr_api::from_r::prepared::Prepared::Unprepared;
                {
                    let mut __miniextendr_native_borrows =
                        [<i32 as ::miniextendr_api::TryFromSexp>::NATIVE_BORROW];
                    if ::miniextendr_api::from_r::borrow::needs_check(&__miniextendr_native_borrows)
                        {
                        let __miniextendr_native_args =
                            [(unsafe { *argv.add(0usize) }, "n")];
                        if ::miniextendr_api::from_r::NativeBorrow::selects(<i32 as
                                    ::miniextendr_api::TryFromSexp>::NATIVE_BORROW) {
                            let __miniextendr_select =
                                unsafe {
                                    ::miniextendr_api::from_r::borrow::assert_or_select(__miniextendr_native_args,
                                        __miniextendr_native_borrows)
                                };
                            if <[bool]>::contains(&__miniextendr_select, &true) {
                                if ::miniextendr_api::from_r::NativeBorrow::selects(<i32 as
                                                ::miniextendr_api::TryFromSexp>::NATIVE_BORROW) &&
                                        __miniextendr_select[0usize] {
                                    __mx_prepared_0 =
                                        <i32 as
                                                ::miniextendr_api::TryFromSexp>::__mx_prepare(unsafe {
                                                *argv.add(0usize)
                                            });
                                    __miniextendr_native_borrows[0usize] =
                                        ::miniextendr_api::from_r::prepared::Prepared::borrow(&__mx_prepared_0,
                                            __miniextendr_native_borrows[0usize]);
                                }
                                unsafe {
                                    ::miniextendr_api::from_r::borrow::assert_no_aliases(__miniextendr_native_args,
                                        __miniextendr_native_borrows);
                                }
                            }
                        } else {
                            unsafe {
                                ::miniextendr_api::from_r::borrow::assert_no_aliases(__miniextendr_native_args,
                                    __miniextendr_native_borrows);
                            }
                        }
                    }
                }
                let n: i32 =
                    match ::miniextendr_api::from_r::prepared::convert::<i32>(__mx_prepared_0,
                            unsafe { *argv.add(0usize) }) {
                        ::core::result::Result::Ok(value) => value,
                        ::core::result::Result::Err(e) =>
                            return unsafe {
                                    ::miniextendr_api::error_value::conversion_condition_value("'n' must be a single integer",
                                        "n", ::core::option::Option::Some("i32"),
                                        ::miniextendr_api::trait_abi::conversion_error_class(),
                                        {
                                            #[allow(unused_imports)]
                                            use crate::condition::{
                                                ConversionErrBuiltin as _, ConversionErrClassed as _,
                                                ConversionErrDisplay as _,
                                            };
                                            match &e { __mx_e => __mx_e.__mx_conversion_parts(true), }
                                        }, ::core::option::Option::None,
                                        ::core::option::Option::None)
                                },
                    };
                let __mx_guard =
                    ::miniextendr_api::externalptr::borrow_value(__mx_cell);
                let self_ref = &*__mx_guard;
                let result = self_ref.skip(n);
                match ::miniextendr_api::into_r::IntoR::try_into_sexp(result)
                    {
                    ::core::result::Result::Ok(__mx_sexp) => __mx_sexp,
                    ::core::result::Result::Err(__mx_error) => unsafe {
                        ::miniextendr_api::error_value::result_err_condition_value(::miniextendr_api::condition::into_r_err_parts(&__mx_error),
                            ::core::option::Option::None)
                    },
                }
            })
}
#[doc = "Method shim for `RIterator::nth`."]
#[doc = r""]
#[doc =
r" Converts SEXP arguments, calls the method, and returns SEXP result."]
#[doc =
r" Both Rust panics and R longjmps are caught via `with_r_unwind_protect`."]
#[doc(hidden)]
#[allow(non_snake_case)]
unsafe extern "C" fn __RIterator_nth_shim(data: *mut ::std::os::raw::c_void,
    argc: i32, argv: *const ::miniextendr_api::SEXP)
    -> ::miniextendr_api::SEXP where
    Nullable<<Self as RIterator>::Item>: ::miniextendr_api::IntoR,
    Vec<<Self as RIterator>::Item>: ::miniextendr_api::IntoR,
    Self: ::core::marker::Sized + RIterator + ::miniextendr_api::IntoR {
    ::miniextendr_api::unwind_protect::with_r_unwind_protect_shim(||
            {
                ::miniextendr_api::trait_abi::check_arity(argc, 1i32,
                    "RIterator::nth");
                let __mx_cell =
                    unsafe { &*data.cast::<::core::cell::RefCell<Self>>() };
                let mut __mx_prepared_0 =
                    ::miniextendr_api::from_r::prepared::Prepared::Unprepared;
                {
                    let mut __miniextendr_native_borrows =
                        [<i32 as ::miniextendr_api::TryFromSexp>::NATIVE_BORROW];
                    if ::miniextendr_api::from_r::borrow::needs_check(&__miniextendr_native_borrows)
                        {
                        let __miniextendr_native_args =
                            [(unsafe { *argv.add(0usize) }, "n")];
                        if ::miniextendr_api::from_r::NativeBorrow::selects(<i32 as
                                    ::miniextendr_api::TryFromSexp>::NATIVE_BORROW) {
                            let __miniextendr_select =
                                unsafe {
                                    ::miniextendr_api::from_r::borrow::assert_or_select(__miniextendr_native_args,
                                        __miniextendr_native_borrows)
                                };
                            if <[bool]>::contains(&__miniextendr_select, &true) {
                                if ::miniextendr_api::from_r::NativeBorrow::selects(<i32 as
                                                ::miniextendr_api::TryFromSexp>::NATIVE_BORROW) &&
                                        __miniextendr_select[0usize] {
                                    __mx_prepared_0 =
                                        <i32 as
                                                ::miniextendr_api::TryFromSexp>::__mx_prepare(unsafe {
                                                *argv.add(0usize)
                                            });
                                    __miniextendr_native_borrows[0usize] =
                                        ::miniextendr_api::from_r::prepared::Prepared::borrow(&__mx_prepared_0,
                                            __miniextendr_native_borrows[0usize]);
                                }
                                unsafe {
                                    ::miniextendr_api::from_r::borrow::assert_no_aliases(__miniextendr_native_args,
                                        __miniextendr_native_borrows);
                                }
                            }
                        } else {
                            unsafe {
                                ::miniextendr_api::from_r::borrow::assert_no_aliases(__miniextendr_native_args,
                                    __miniextendr_native_borrows);
                            }
                        }
                    }
                }
                let n: i32 =
                    match ::miniextendr_api::from_r::prepared::convert::<i32>(__mx_prepared_0,
                            unsafe { *argv.add(0usize) }) {
                        ::core::result::Result::Ok(value) => value,
                        ::core::result::Result::Err(e) =>
                            return unsafe {
                                    ::miniextendr_api::error_value::conversion_condition_value("'n' must be a single integer",
                                        "n", ::core::option::Option::Some("i32"),
                                        ::miniextendr_api::trait_abi::conversion_error_class(),
                                        {
                                            #[allow(unused_imports)]
                                            use crate::condition::{
                                                ConversionErrBuiltin as _, ConversionErrClassed as _,
                                                ConversionErrDisplay as _,
                                            };
                                            match &e { __mx_e => __mx_e.__mx_conversion_parts(true), }
                                        }, ::core::option::Option::None,
                                        ::core::option::Option::None)
                                },
                    };
                let __mx_guard =
                    ::miniextendr_api::externalptr::borrow_value(__mx_cell);
                let self_ref = &*__mx_guard;
                let result = self_ref.nth(n);
                match ::miniextendr_api::into_r::IntoR::try_into_sexp(result)
                    {
                    ::core::result::Result::Ok(__mx_sexp) => __mx_sexp,
                    ::core::result::Result::Err(__mx_error) => unsafe {
                        ::miniextendr_api::error_value::result_err_condition_value(::miniextendr_api::condition::into_r_err_parts(&__mx_error),
                            ::core::option::Option::None)
                    },
                }
            })
}
#[doc = "Type tag for runtime identification of the `RIterator` trait."]
#[doc = "Generated from source location line 604, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[allow(non_upper_case_globals)]
pub const TAG_RIterator: ::miniextendr_api::abi::mx_tag =
    ::miniextendr_api::abi::mx_tag_from_path("miniextendr::trait-abi/v2;9:RIterator1:64:next9:next_item3:ref1:025:Nullable < Self :: Item >9:size_hint9:size_hint3:ref1:021:(i64, Option < i64 >)5:count5:count3:ref1:03:i649:collect_n9:collect_n3:ref1:13:i3220:Vec < Self :: Item >4:skip4:skip3:ref1:13:i323:i323:nth3:nth3:ref1:13:i3225:Nullable < Self :: Item >");
#[doc = "Vtable for the `RIterator` trait."]
#[doc = "Generated from source location line 604, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[doc = r""]
#[doc = r" Contains one `mx_meth` function pointer per trait method."]
#[repr(C)]
#[doc(hidden)]
#[allow(non_camel_case_types)]
pub struct RIteratorVTable {
    pub next: ::miniextendr_api::abi::mx_meth,
    pub size_hint: ::miniextendr_api::abi::mx_meth,
    pub count: ::miniextendr_api::abi::mx_meth,
    pub collect_n: ::miniextendr_api::abi::mx_meth,
    pub skip: ::miniextendr_api::abi::mx_meth,
    pub nth: ::miniextendr_api::abi::mx_meth,
}
#[doc = "Runtime view for objects implementing `RIterator`."]
#[doc = "Generated from source location line 604, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[doc = r""]
#[doc = r" Keeps the receiver alive for method dispatch. Use `try_from_sexp`"]
#[doc = r" to create a view with its own root for the R external pointer."]
#[doc = r" Construction, use and drop belong on R's main thread."]
#[allow(non_camel_case_types)]
pub struct RIteratorView {
    __mx_view: ::miniextendr_api::trait_abi::TraitViewData<RIteratorVTable>,
}
impl ::miniextendr_api::TraitView for RIteratorView {
    const TAG: ::miniextendr_api::abi::mx_tag = TAG_RIterator;
    #[inline]
    unsafe fn from_raw_parts(data: *mut ::std::os::raw::c_void,
        vtable: *const ::std::os::raw::c_void,
        owner: ::core::option::Option<::miniextendr_api::SEXP>) -> Self {
        Self {
            __mx_view: unsafe {
                ::miniextendr_api::trait_abi::TraitViewData::new(data, vtable,
                    owner)
            },
        }
    }
}
impl RIteratorView {
    #[doc = r" Try to create a view from an R SEXP."]
    #[doc = r""]
    #[doc = r" Returns `Some(Self)` if the object implements this trait,"]
    #[doc = r" `None` otherwise."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc = r" - `sexp` must be a valid R external pointer (EXTPTRSXP)"]
    #[doc =
    r" - The object must stay live through construction; the view then roots it"]
    #[doc =
    r" - A call that conflicts with one still running on the same object"]
    #[doc = r"   raises the `miniextendr_borrow_conflict` error"]
    #[doc = r" - Construction, use and drop must all run on R's main thread"]
    #[inline]
    pub unsafe fn try_from_sexp(sexp: ::miniextendr_api::SEXP)
        -> ::core::option::Option<Self> {
        unsafe { <Self as ::miniextendr_api::TraitView>::try_from_sexp(sexp) }
    }
    #[doc =
    r" Try to create a view, panicking with error message on failure."]
    #[doc = r""]
    #[doc = r" # Safety"]
    #[doc = r""]
    #[doc = r" Same as `try_from_sexp`."]
    #[inline]
    pub unsafe fn from_sexp(sexp: ::miniextendr_api::SEXP) -> Self {
        unsafe {
                Self::try_from_sexp(sexp)
            }.expect("Object does not implement RIterator trait")
    }
    #[doc = "Call `size_hint` through the vtable."]
    #[inline]
    #[allow(clippy :: duplicate_underscore_argument)]
    pub fn size_hint(&self) -> (i64, Option<i64>) {
        unsafe {
            let __mx_roots =
                ::miniextendr_api::gc_protect::ProtectScope::new();
            let result =
                __mx_roots.protect_raw({
                        ((*self.__mx_view.vtable()).size_hint)(self.__mx_view.data(),
                            0, ::std::ptr::null())
                    });
            ::miniextendr_api::trait_abi::repanic_if_rust_error(result);
            ::miniextendr_api::trait_abi::from_sexp::<(i64,
                    Option<i64>)>(result)
        }
    }
    #[doc = "Call `count` through the vtable."]
    #[inline]
    #[allow(clippy :: duplicate_underscore_argument)]
    pub fn count(&self) -> i64 {
        unsafe {
            let __mx_roots =
                ::miniextendr_api::gc_protect::ProtectScope::new();
            let result =
                __mx_roots.protect_raw({
                        ((*self.__mx_view.vtable()).count)(self.__mx_view.data(), 0,
                            ::std::ptr::null())
                    });
            ::miniextendr_api::trait_abi::repanic_if_rust_error(result);
            ::miniextendr_api::trait_abi::from_sexp::<i64>(result)
        }
    }
    #[doc = "Call `skip` through the vtable."]
    #[inline]
    #[allow(clippy :: duplicate_underscore_argument)]
    pub fn skip(&self, n: i32) -> i32 {
        unsafe {
            let __mx_roots =
                ::miniextendr_api::gc_protect::ProtectScope::new();
            let result =
                __mx_roots.protect_raw({
                        let args: [::miniextendr_api::SEXP; 1i32 as usize] =
                            [__mx_roots.protect_raw(::miniextendr_api::trait_abi::to_sexp(n))];
                        ((*self.__mx_view.vtable()).skip)(self.__mx_view.data(),
                            1i32, args.as_ptr())
                    });
            ::miniextendr_api::trait_abi::repanic_if_rust_error(result);
            ::miniextendr_api::trait_abi::from_sexp::<i32>(result)
        }
    }
}
#[doc = "Build a vtable for a concrete type implementing `RIterator`."]
#[doc = "Generated from source location line 604, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[allow(non_snake_case)]
pub const fn __RIterator_build_vtable<__ImplT: RIterator +
    ::miniextendr_api::IntoR>() -> RIteratorVTable where
    Nullable<<__ImplT as RIterator>::Item>: ::miniextendr_api::IntoR,
    Vec<<__ImplT as RIterator>::Item>: ::miniextendr_api::IntoR {
    RIteratorVTable {
        next: <__ImplT as RIterator>::__RIterator_next_shim,
        size_hint: <__ImplT as RIterator>::__RIterator_size_hint_shim,
        count: <__ImplT as RIterator>::__RIterator_count_shim,
        collect_n: <__ImplT as RIterator>::__RIterator_collect_n_shim,
        skip: <__ImplT as RIterator>::__RIterator_skip_shim,
        nth: <__ImplT as RIterator>::__RIterator_nth_shim,
    }
}
#[macro_export]
#[doc(hidden)]
macro_rules! __mx_trait_metadata_RIterator_10 {
    (@ impl { $ ($attrs : tt) * } { $ ($implementation : tt) * }) =>
    {
        :: miniextendr_api :: __mx_trait_impl_expand!
        {
            @ impl { $ ($attrs) * } { $ ($implementation) * }
            {
                #[doc = " Get the next element from the iterator."]
                #[doc = ""]
                #[doc =
                " Returns `Nullable(Some(item))` while there are elements, and"]
                #[doc =
                " `Nullable(None)` once exhausted, which R receives as `NULL` whatever"]
                #[doc =
                " the item type: an `NA` could be an item, `NULL` never is."]
                #[miniextendr(r_name = "next_item")] fn next();
                #[doc = " Get the estimated number of remaining elements."]
                #[doc = ""]
                #[doc =
                " Returns `(lower_bound, upper_bound)` where upper_bound is None if unknown."]
                #[doc =
                " In R, this becomes `list(lower, upper)` where upper is NA if unknown."]
                fn size_hint();
                #[doc = " Consume the iterator and count remaining elements."]
                #[doc = ""]
                #[doc = " **Warning:** This exhausts the iterator."] fn
                count(& self) -> i64 {}
                #[doc = " Collect up to `n` elements into a vector."]
                #[doc = ""]
                #[doc =
                " Returns fewer than `n` elements if the iterator is exhausted first."]
                fn collect_n(& self, n : i32) -> Vec < Self :: Item > {}
                #[doc = " Skip `n` elements from the iterator."] #[doc = ""]
                #[doc =
                " Returns the number of elements actually skipped (may be less than `n`"]
                #[doc = " if the iterator is exhausted)."] fn
                skip(& self, n : i32) -> i32 {}
                #[doc =
                " Get the `n`th element (0-indexed), consuming elements up to and including it."]
                #[doc = ""]
                #[doc =
                " Returns `Nullable(None)` (`NULL` in R) if `n` is negative or the"]
                #[doc = " iterator has fewer than `n + 1` elements."] fn
                nth(& self, n : i32) -> Nullable < Self :: Item > {}
            } {} abi RIterator false
            "miniextendr::trait-abi/v2;9:RIterator1:64:next9:next_item3:ref1:025:Nullable < Self :: Item >9:size_hint9:size_hint3:ref1:021:(i64, Option < i64 >)5:count5:count3:ref1:03:i649:collect_n9:collect_n3:ref1:13:i3220:Vec < Self :: Item >4:skip4:skip3:ref1:13:i323:i323:nth3:nth3:ref1:13:i3225:Nullable < Self :: Item >"
            {
                pub next : :: miniextendr_api :: abi :: mx_meth, pub size_hint
                : :: miniextendr_api :: abi :: mx_meth, pub count : ::
                miniextendr_api :: abi :: mx_meth, pub collect_n : ::
                miniextendr_api :: abi :: mx_meth, pub skip : ::
                miniextendr_api :: abi :: mx_meth, pub nth : ::
                miniextendr_api :: abi :: mx_meth
            }
        }
    };
}
#[doc(hidden)]
#[allow(unused_imports)]
pub use __mx_trait_metadata_RIterator_10 as RIterator;#[miniextendr]
604pub trait RIterator {
605    /// The type of elements yielded by this iterator.
606    type Item;
607
608    /// Get the next element from the iterator.
609    ///
610    /// Returns `Nullable(Some(item))` while there are elements, and
611    /// `Nullable(None)` once exhausted, which R receives as `NULL` whatever
612    /// the item type: an `NA` could be an item, `NULL` never is.
613    #[miniextendr(r_name = "next_item")]
614    fn next(&self) -> Nullable<Self::Item>;
615
616    /// Get the estimated number of remaining elements.
617    ///
618    /// Returns `(lower_bound, upper_bound)` where upper_bound is None if unknown.
619    /// In R, this becomes `list(lower, upper)` where upper is NA if unknown.
620    fn size_hint(&self) -> (i64, Option<i64>);
621
622    /// Consume the iterator and count remaining elements.
623    ///
624    /// **Warning:** This exhausts the iterator.
625    fn count(&self) -> i64 {
626        let mut count = 0i64;
627        while self.next().0.is_some() {
628            count += 1;
629        }
630        count
631    }
632
633    /// Collect up to `n` elements into a vector.
634    ///
635    /// Returns fewer than `n` elements if the iterator is exhausted first.
636    fn collect_n(&self, n: i32) -> Vec<Self::Item> {
637        let mut result = Vec::with_capacity(n.max(0) as usize);
638        for _ in 0..n {
639            match self.next().0 {
640                Some(item) => result.push(item),
641                None => break,
642            }
643        }
644        result
645    }
646
647    /// Skip `n` elements from the iterator.
648    ///
649    /// Returns the number of elements actually skipped (may be less than `n`
650    /// if the iterator is exhausted).
651    fn skip(&self, n: i32) -> i32 {
652        let mut skipped = 0i32;
653        for _ in 0..n {
654            if self.next().0.is_none() {
655                break;
656            }
657            skipped += 1;
658        }
659        skipped
660    }
661
662    /// Get the `n`th element (0-indexed), consuming elements up to and including it.
663    ///
664    /// Returns `Nullable(None)` (`NULL` in R) if `n` is negative or the
665    /// iterator has fewer than `n + 1` elements.
666    fn nth(&self, n: i32) -> Nullable<Self::Item> {
667        if n < 0 {
668            return Nullable(None);
669        }
670        for _ in 0..n {
671            if self.next().0.is_none() {
672                return Nullable(None);
673            }
674        }
675        self.next()
676    }
677}
678
679impl<I: Iterator> RIterator for std::cell::RefCell<I> {
680    type Item = I::Item;
681
682    fn next(&self) -> Nullable<Self::Item> {
683        Nullable(self.borrow_mut().next())
684    }
685
686    fn size_hint(&self) -> (i64, Option<i64>) {
687        let (lower, upper) = self.borrow().size_hint();
688        // An unbounded iterator may report usize::MAX as its lower bound.
689        // Saturating the lower bound and omitting an unrepresentable upper
690        // bound keeps both valid in this trait's signed representation.
691        (
692            i64::try_from(lower).unwrap_or(i64::MAX),
693            upper.and_then(|value| i64::try_from(value).ok()),
694        )
695    }
696
697    fn count(&self) -> i64 {
698        i64::try_from(self.borrow_mut().by_ref().count()).expect("iterator count exceeds i64::MAX")
699    }
700
701    fn collect_n(&self, n: i32) -> Vec<Self::Item> {
702        let n = usize::try_from(n.max(0)).expect("nonnegative i32 fits usize");
703        self.borrow_mut().by_ref().take(n).collect()
704    }
705
706    fn skip(&self, n: i32) -> i32 {
707        let n = usize::try_from(n.max(0)).expect("nonnegative i32 fits usize");
708        i32::try_from(self.borrow_mut().by_ref().take(n).count())
709            .expect("skipped count is bounded by n")
710    }
711
712    fn nth(&self, n: i32) -> Nullable<Self::Item> {
713        Nullable(
714            usize::try_from(n)
715                .ok()
716                .and_then(|n| self.borrow_mut().nth(n)),
717        )
718    }
719}
720
721/// Adapter trait for [`std::iter::Extend`].
722///
723/// Provides collection extension operations for R, allowing Rust collections
724/// to be extended with R vectors. Since extension requires mutation, the
725/// wrapper type should use interior mutability (e.g., `RefCell`).
726///
727/// # Methods
728///
729/// - `extend_from_vec(items)` - Extend the collection with items from a vector
730/// - `extend_from_slice(items)` - Extend from a slice (for Clone items)
731/// - `r_len()` (`len()` in R) - Get the current length, or -1 if unknown
732/// - `r_is_empty()` (`is_empty()` in R) - Check if the collection is empty
733///
734/// # Example
735///
736/// ```rust,ignore
737/// use std::cell::RefCell;
738///
739/// #[derive(ExternalPtr)]
740/// struct MyVec(RefCell<Vec<i32>>);
741///
742/// #[miniextendr(env)]
743/// impl MyVec {
744///     fn new() -> Self {
745///         Self(RefCell::new(Vec::new()))
746///     }
747/// }
748///
749/// // The trait is generic, so the impl spells out each exported method and
750/// // repeats the R names of the renamed ones.
751/// #[miniextendr(env)]
752/// impl miniextendr_api::adapter_traits::RExtend<i32> for MyVec {
753///     fn extend_from_vec(&self, items: Vec<i32>) {
754///         self.0.borrow_mut().extend(items);
755///     }
756///
757///     fn r_len(&self) -> i64 {
758///         i64::try_from(self.0.borrow().len()).expect("length fits i64")
759///     }
760///
761///     fn r_is_empty(&self) -> bool {
762///         self.0.borrow().is_empty()
763///     }
764/// }
765/// ```
766///
767/// In R:
768/// ```r
769/// v <- MyVec$new()
770/// v$RExtend$extend_from_vec(c(1L, 2L, 3L))  # Add items
771/// v$RExtend$extend_from_vec(c(4L, 5L))      # Add more items
772/// v$RExtend$len()                           # 5
773/// ```
774///
775/// # Design Note
776///
777/// Like `RIterator`, `RExtend` does NOT have a blanket impl because `Extend::extend()`
778/// requires `&mut self`, but R's ExternalPtr pattern provides `&self`. Users must
779/// implement this trait manually using interior mutability (RefCell, Mutex, etc.).
780#[doc = "Type tag for runtime identification of the `RExtend` trait."]
#[doc = "Generated from source location line 781, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[allow(non_upper_case_globals)]
pub const TAG_RExtend: ::miniextendr_api::abi::mx_tag =
    ::miniextendr_api::abi::mx_tag_from_path("miniextendr::trait-abi/v2;7:RExtend1:315:extend_from_vec15:extend_from_vec3:ref1:19:Vec < T >2:()5:r_len3:len3:ref1:03:i6410:r_is_empty8:is_empty3:ref1:04:bool");
#[doc = "Vtable for the `RExtend` trait."]
#[doc = "Generated from source location line 781, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[doc = r""]
#[doc = r" Contains one `mx_meth` function pointer per trait method."]
#[repr(C)]
#[doc(hidden)]
#[allow(non_camel_case_types)]
pub struct RExtendVTable {
    pub extend_from_vec: ::miniextendr_api::abi::mx_meth,
    pub r_len: ::miniextendr_api::abi::mx_meth,
    pub r_is_empty: ::miniextendr_api::abi::mx_meth,
}
#[macro_export]
#[doc(hidden)]
macro_rules! __mx_trait_metadata_RExtend_11 {
    (@ impl { $ ($attrs : tt) * } { $ ($implementation : tt) * }) =>
    {
        :: miniextendr_api :: __mx_trait_impl_expand!
        {
            @ impl { $ ($attrs) * } { $ ($implementation) * }
            {
                #[doc = " Extend the collection with items from a vector."]
                #[doc = ""]
                #[doc = " The items are moved into the collection."] fn
                extend_from_vec(items : ());
                #[doc =
                " Extend the collection with cloned items from a slice."]
                #[doc = ""]
                #[doc =
                " Default implementation clones items into a Vec and calls `extend_from_vec`."]
                #[doc = ""]
                #[doc =
                " Skipped from trait ABI because `&[T]` doesn\'t have TryFromSexp."]
                #[miniextendr(skip)] fn
                extend_from_slice(& self, items : & [T]) where T : Clone, {}
                #[doc = " Get the current length of the collection."]
                #[doc = ""]
                #[doc = " Optional - returns -1 if not implemented."]
                #[miniextendr(r_name = "len")] fn r_len(& self) -> i64 {}
                #[doc = " Check if the collection is empty."] #[doc = ""]
                #[doc = " Returns false when length is unknown."]
                #[miniextendr(r_name = "is_empty")] fn r_is_empty(& self) ->
                bool {}
            } { < T > } abi RExtend true
            "miniextendr::trait-abi/v2;7:RExtend1:315:extend_from_vec15:extend_from_vec3:ref1:19:Vec < T >2:()5:r_len3:len3:ref1:03:i6410:r_is_empty8:is_empty3:ref1:04:bool"
            {
                pub extend_from_vec : :: miniextendr_api :: abi :: mx_meth,
                pub r_len : :: miniextendr_api :: abi :: mx_meth, pub
                r_is_empty : :: miniextendr_api :: abi :: mx_meth
            }
        }
    };
}
#[doc(hidden)]
#[allow(unused_imports)]
pub use __mx_trait_metadata_RExtend_11 as RExtend;#[miniextendr]
781pub trait RExtend<T> {
782    /// Extend the collection with items from a vector.
783    ///
784    /// The items are moved into the collection.
785    fn extend_from_vec(&self, items: Vec<T>);
786
787    /// Extend the collection with cloned items from a slice.
788    ///
789    /// Default implementation clones items into a Vec and calls `extend_from_vec`.
790    ///
791    /// Skipped from trait ABI because `&[T]` doesn't have TryFromSexp.
792    #[miniextendr(skip)]
793    fn extend_from_slice(&self, items: &[T])
794    where
795        T: Clone,
796    {
797        self.extend_from_vec(items.to_vec());
798    }
799
800    /// Get the current length of the collection.
801    ///
802    /// Optional - returns -1 if not implemented.
803    #[miniextendr(r_name = "len")]
804    fn r_len(&self) -> i64 {
805        -1 // Indicates "unknown" - implementers can override
806    }
807
808    /// Check if the collection is empty.
809    ///
810    /// Returns false when length is unknown.
811    #[miniextendr(r_name = "is_empty")]
812    fn r_is_empty(&self) -> bool {
813        self.r_len() == 0
814    }
815}
816
817// Note: No blanket impl because Extend::extend() requires &mut self,
818// but ExternalPtr methods receive &self. Users must use interior mutability.
819
820/// Adapter trait for [`std::iter::FromIterator`].
821///
822/// Provides collection construction from iterators/vectors for R.
823/// Unlike `RExtend`, this creates a new collection from items.
824///
825/// # Methods
826///
827/// - `from_vec(items)` - Create a new collection from a vector
828///
829/// # Example
830///
831/// ```rust,ignore
832/// #[derive(ExternalPtr)]
833/// struct MySet(std::collections::HashSet<i32>);
834///
835/// #[miniextendr(env)]
836/// impl miniextendr_api::adapter_traits::RFromIter<i32> for MySet {
837///     fn from_vec(items: Vec<i32>) -> Self {
838///         Self(items.into_iter().collect())
839///     }
840/// }
841/// ```
842///
843/// In R:
844/// ```r
845/// set <- MySet$RFromIter$from_vec(c(1L, 2L, 2L, 3L))  # Creates {1, 2, 3}
846/// ```
847#[doc = "Type tag for runtime identification of the `RFromIter` trait."]
#[doc = "Generated from source location line 848, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[allow(non_upper_case_globals)]
pub const TAG_RFromIter: ::miniextendr_api::abi::mx_tag =
    ::miniextendr_api::abi::mx_tag_from_path("miniextendr::trait-abi/v2;9:RFromIter1:0");
#[doc = "Vtable for the `RFromIter` trait."]
#[doc = "Generated from source location line 848, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[doc = r""]
#[doc = r" Contains one `mx_meth` function pointer per trait method."]
#[repr(C)]
#[doc(hidden)]
#[allow(non_camel_case_types)]
pub struct RFromIterVTable {}
#[macro_export]
#[doc(hidden)]
macro_rules! __mx_trait_metadata_RFromIter_12 {
    (@ impl { $ ($attrs : tt) * } { $ ($implementation : tt) * }) =>
    {
        :: miniextendr_api :: __mx_trait_impl_expand!
        {
            @ impl { $ ($attrs) * } { $ ($implementation) * }
            {
                #[doc = " Create a new collection from a vector of items."] fn
                from_vec(items : ());
            } { < T > } abi RFromIter true
            "miniextendr::trait-abi/v2;9:RFromIter1:0" {}
        }
    };
}
#[doc(hidden)]
#[allow(unused_imports)]
pub use __mx_trait_metadata_RFromIter_12 as RFromIter;#[miniextendr]
848pub trait RFromIter<T>: Sized {
849    /// Create a new collection from a vector of items.
850    fn from_vec(items: Vec<T>) -> Self;
851}
852
853impl<C, T> RFromIter<T> for C
854where
855    C: FromIterator<T>,
856{
857    fn from_vec(items: Vec<T>) -> Self {
858        items.into_iter().collect()
859    }
860}
861
862/// Adapter trait for collections that can be converted to vectors.
863///
864/// This is the complement to [`RFromIter`]: while `RFromIter` creates collections
865/// from vectors, `RToVec` extracts vectors from collections.
866///
867/// # Methods
868///
869/// - `r_to_vec()` (`to_vec()` in R) - Collect all elements into a vector
870///   (cloning elements)
871/// - `r_len()` (`len()` in R) - Get the number of elements
872/// - `r_is_empty()` (`is_empty()` in R) - Check if the collection is empty
873///
874/// # Design Note
875///
876/// Unlike Rust's `IntoIterator::into_iter()` which consumes the collection,
877/// this trait borrows the collection and clones elements. This is necessary
878/// because R's `ExternalPtr` pattern provides `&self`, not owned `self`.
879///
880/// For consuming iteration, use [`RIterator`] with interior mutability.
881///
882/// # Example
883///
884/// ```rust,ignore
885/// use miniextendr_api::adapter_traits::RToVec;
886/// use std::collections::HashSet;
887///
888/// #[derive(ExternalPtr)]
889/// struct MySet(HashSet<i32>);
890///
891/// // `&MySet` doesn't iterate, so the blanket impl doesn't cover the wrapper:
892/// // the impl forwards to the set, which it does cover. The trait is generic,
893/// // so the impl spells out each method; R names come from the trait.
894/// #[miniextendr(env)]
895/// impl miniextendr_api::adapter_traits::RToVec<i32> for MySet {
896///     fn r_to_vec(&self) -> Vec<i32> {
897///         self.0.r_to_vec()
898///     }
899///
900///     fn r_len(&self) -> i64 {
901///         self.0.r_len()
902///     }
903///
904///     fn r_is_empty(&self) -> bool {
905///         self.0.is_empty()
906///     }
907/// }
908/// ```
909///
910/// In R:
911/// ```r
912/// set <- MySet$new(...)
913/// vec <- set$RToVec$to_vec()    # Get all elements as vector
914/// set$RToVec$len()              # Number of elements
915/// set$RToVec$is_empty()         # Check if empty
916/// ```
917#[doc = "Type tag for runtime identification of the `RToVec` trait."]
#[doc = "Generated from source location line 918, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[allow(non_upper_case_globals)]
pub const TAG_RToVec: ::miniextendr_api::abi::mx_tag =
    ::miniextendr_api::abi::mx_tag_from_path("miniextendr::trait-abi/v2;6:RToVec1:38:r_to_vec6:to_vec3:ref1:09:Vec < T >5:r_len3:len3:ref1:03:i6410:r_is_empty8:is_empty3:ref1:04:bool");
#[doc = "Vtable for the `RToVec` trait."]
#[doc = "Generated from source location line 918, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[doc = r""]
#[doc = r" Contains one `mx_meth` function pointer per trait method."]
#[repr(C)]
#[doc(hidden)]
#[allow(non_camel_case_types)]
pub struct RToVecVTable {
    pub r_to_vec: ::miniextendr_api::abi::mx_meth,
    pub r_len: ::miniextendr_api::abi::mx_meth,
    pub r_is_empty: ::miniextendr_api::abi::mx_meth,
}
#[macro_export]
#[doc(hidden)]
macro_rules! __mx_trait_metadata_RToVec_13 {
    (@ impl { $ ($attrs : tt) * } { $ ($implementation : tt) * }) =>
    {
        :: miniextendr_api :: __mx_trait_impl_expand!
        {
            @ impl { $ ($attrs) * } { $ ($implementation) * }
            {
                #[doc = " Collect all elements into a vector."] #[doc = ""]
                #[doc = " Elements are cloned from the collection."]
                #[miniextendr(r_name = "to_vec")] fn r_to_vec();
                #[doc = " Get the number of elements in the collection."]
                #[miniextendr(r_name = "len")] fn r_len();
                #[doc = " Check if the collection is empty."]
                #[miniextendr(r_name = "is_empty")] fn r_is_empty(& self) ->
                bool {}
            } { < T > } abi RToVec true
            "miniextendr::trait-abi/v2;6:RToVec1:38:r_to_vec6:to_vec3:ref1:09:Vec < T >5:r_len3:len3:ref1:03:i6410:r_is_empty8:is_empty3:ref1:04:bool"
            {
                pub r_to_vec : :: miniextendr_api :: abi :: mx_meth, pub r_len
                : :: miniextendr_api :: abi :: mx_meth, pub r_is_empty : ::
                miniextendr_api :: abi :: mx_meth
            }
        }
    };
}
#[doc(hidden)]
#[allow(unused_imports)]
pub use __mx_trait_metadata_RToVec_13 as RToVec;#[miniextendr]
918pub trait RToVec<T> {
919    /// Collect all elements into a vector.
920    ///
921    /// Elements are cloned from the collection.
922    #[miniextendr(r_name = "to_vec")]
923    fn r_to_vec(&self) -> Vec<T>;
924
925    /// Get the number of elements in the collection.
926    #[miniextendr(r_name = "len")]
927    fn r_len(&self) -> i64;
928
929    /// Check if the collection is empty.
930    #[miniextendr(r_name = "is_empty")]
931    fn r_is_empty(&self) -> bool {
932        self.r_len() == 0
933    }
934}
935
936// Blanket impl for any collection where:
937// - &C can be iterated over (yielding &T references)
938// - T: Clone (so we can clone elements into the Vec)
939// - The iterator knows its exact size
940//
941// Note: Using HRTB (higher-ranked trait bounds) to express that &C
942// can be iterated for any lifetime.
943impl<C, T> RToVec<T> for C
944where
945    T: Clone,
946    for<'a> &'a C: IntoIterator<Item = &'a T>,
947    for<'a> <&'a C as IntoIterator>::IntoIter: ExactSizeIterator,
948{
949    fn r_to_vec(&self) -> Vec<T> {
950        self.into_iter().cloned().collect()
951    }
952
953    fn r_len(&self) -> i64 {
954        i64::try_from(self.into_iter().len()).expect("collection length exceeds i64::MAX")
955    }
956}
957
958/// Adapter trait for creating iterator wrappers from collections.
959///
960/// This trait provides a way to create an [`RIterator`] wrapper from a collection.
961/// Since `ExternalPtr` methods receive `&self`, this trait clones the underlying
962/// data to create an independent iterator.
963///
964/// # Type Parameters
965///
966/// - `T`: The element type yielded by the iterator
967/// - `I`: The iterator type returned (must implement [`RIterator`])
968///
969/// # Design Note
970///
971/// The returned iterator is independent from the source collection. Modifications
972/// to the original collection after calling `make_iter()` won't affect the
973/// iterator's output.
974///
975/// # Example
976///
977/// ```rust,ignore
978/// use std::cell::RefCell;
979///
980/// #[derive(ExternalPtr)]
981/// struct MyVec(Vec<i32>);
982///
983/// #[derive(ExternalPtr)]
984/// struct MyVecIter(RefCell<std::vec::IntoIter<i32>>);
985///
986/// // `MyVecIter` implements `RIterator` as in the `RIterator` example.
987///
988/// #[miniextendr(env)]
989/// impl miniextendr_api::adapter_traits::RMakeIter<i32, MyVecIter> for MyVec {
990///     fn make_iter(&self) -> MyVecIter {
991///         MyVecIter(RefCell::new(self.0.clone().into_iter()))
992///     }
993/// }
994/// ```
995///
996/// In R (`next` is a reserved word, so the method is `next_item`):
997/// ```r
998/// v <- MyVec$new(c(1L, 2L, 3L))
999/// it <- v$RMakeIter$make_iter()   # Create iterator
1000/// it$RIterator$next_item()        # 1L
1001/// it$RIterator$next_item()        # 2L
1002/// ```
1003#[doc = "Type tag for runtime identification of the `RMakeIter` trait."]
#[doc = "Generated from source location line 1004, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[allow(non_upper_case_globals)]
pub const TAG_RMakeIter: ::miniextendr_api::abi::mx_tag =
    ::miniextendr_api::abi::mx_tag_from_path("miniextendr::trait-abi/v2;9:RMakeIter1:19:make_iter9:make_iter3:ref1:01:I");
#[doc = "Vtable for the `RMakeIter` trait."]
#[doc = "Generated from source location line 1004, column 11."]
#[doc = "Generated from source file `miniextendr-api/src/adapter_traits.rs`."]
#[doc = r""]
#[doc = r" Contains one `mx_meth` function pointer per trait method."]
#[repr(C)]
#[doc(hidden)]
#[allow(non_camel_case_types)]
pub struct RMakeIterVTable {
    pub make_iter: ::miniextendr_api::abi::mx_meth,
}
#[macro_export]
#[doc(hidden)]
macro_rules! __mx_trait_metadata_RMakeIter_14 {
    (@ impl { $ ($attrs : tt) * } { $ ($implementation : tt) * }) =>
    {
        :: miniextendr_api :: __mx_trait_impl_expand!
        {
            @ impl { $ ($attrs) * } { $ ($implementation) * }
            {
                #[doc = " Create a new iterator wrapper."] #[doc = ""]
                #[doc =
                " The iterator is independent from this collection (typically by cloning"]
                #[doc = " the underlying data)."] fn make_iter();
            } { < T, I > } abi RMakeIter true
            "miniextendr::trait-abi/v2;9:RMakeIter1:19:make_iter9:make_iter3:ref1:01:I"
            { pub make_iter : :: miniextendr_api :: abi :: mx_meth }
        }
    };
}
#[doc(hidden)]
#[allow(unused_imports)]
pub use __mx_trait_metadata_RMakeIter_14 as RMakeIter;#[miniextendr]
1004pub trait RMakeIter<T, I>
1005where
1006    I: RIterator<Item = T>,
1007{
1008    /// Create a new iterator wrapper.
1009    ///
1010    /// The iterator is independent from this collection (typically by cloning
1011    /// the underlying data).
1012    fn make_iter(&self) -> I;
1013}
1014
1015// Note: No blanket impl because:
1016// 1. The iterator type I must be a concrete type that implements RIterator
1017// 2. RIterator requires interior mutability (RefCell/Mutex)
1018// 3. Users must define their own iterator wrapper type
1019
1020#[cfg(test)]
1021mod tests;