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.
43
44use crate::Nullable;
45use crate::miniextendr;
46use std::collections::hash_map::DefaultHasher;
47use std::fmt::{Debug, Display};
48use std::hash::{Hash, Hasher};
49use std::str::FromStr;
50
51/// Adapter trait for [`std::fmt::Debug`].
52///
53/// Provides string representations for debugging and inspection in R.
54/// Automatically implemented for any type that implements `Debug`.
55///
56/// # Methods
57///
58/// - `debug_str()` - Returns compact debug string (`:?` format)
59/// - `debug_str_pretty()` - Returns pretty-printed debug string (`:#?` format)
60///
61/// # Example
62///
63/// ```rust,ignore
64/// #[derive(Debug, ExternalPtr)]
65/// struct Config { name: String, value: i32 }
66///
67/// #[miniextendr]
68/// impl miniextendr_api::adapter_traits::RDebug for Config {}
69/// ```
70#[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();
                unsafe { ::miniextendr_api::trait_abi::to_sexp(result) }
            })
}
#[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();
                unsafe { ::miniextendr_api::trait_abi::to_sexp(result) }
            })
}
#[doc = "Type tag for runtime identification of the `RDebug` trait."]
#[doc = "Generated from source location line 71, 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 71, 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 71, 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 71, 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) * }
            { fn debug_str(); 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; fn debug_str(& self) -> String; }
            method
            {
                r_name = debug_str_pretty; fn debug_str_pretty(& self) ->
                String;
            }
        }
    };
}
#[doc(hidden)]
#[allow(unused_imports)]
pub use __mx_trait_metadata_RDebug_0 as RDebug;#[miniextendr]
71pub trait RDebug {
72    /// Get a compact debug string representation.
73    fn debug_str(&self) -> String;
74
75    /// Get a pretty-printed debug string with indentation.
76    fn debug_str_pretty(&self) -> String;
77}
78
79impl<T: Debug> RDebug for T {
80    fn debug_str(&self) -> String {
81        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", self))
    })format!("{:?}", self)
82    }
83
84    fn debug_str_pretty(&self) -> String {
85        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:#?}", self))
    })format!("{:#?}", self)
86    }
87}
88
89/// Adapter trait for [`std::fmt::Display`].
90///
91/// Provides user-friendly string conversion for R.
92/// Automatically implemented for any type that implements `Display`.
93///
94/// # Methods
95///
96/// - `as_r_string()` - Returns the Display representation
97///
98/// # Example
99///
100/// ```rust,ignore
101/// struct Version(u32, u32, u32);
102///
103/// impl Display for Version {
104///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
105///         write!(f, "{}.{}.{}", self.0, self.1, self.2)
106///     }
107/// }
108///
109/// #[miniextendr]
110/// impl miniextendr_api::adapter_traits::RDisplay for Version {}
111/// ```
112#[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();
                unsafe { ::miniextendr_api::trait_abi::to_sexp(result) }
            })
}
#[doc = "Type tag for runtime identification of the `RDisplay` trait."]
#[doc = "Generated from source location line 113, 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 113, 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 113, 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 113, 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) * }
            { 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; fn as_r_string(& self) -> String; }
        }
    };
}
#[doc(hidden)]
#[allow(unused_imports)]
pub use __mx_trait_metadata_RDisplay_1 as RDisplay;#[miniextendr]
113pub trait RDisplay {
114    /// Convert to a user-friendly string.
115    fn as_r_string(&self) -> String;
116}
117
118impl<T: Display> RDisplay for T {
119    fn as_r_string(&self) -> String {
120        self.to_string()
121    }
122}
123
124/// Adapter trait for [`std::hash::Hash`].
125///
126/// Provides hashing for deduplication and environment keys in R.
127/// Automatically implemented for any type that implements `Hash`.
128///
129/// # Methods
130///
131/// - `r_hash()` (`hash()` in R) - Returns the 64-bit hash as a 16-character
132///   hex string
133///
134/// # Note
135///
136/// Hash values are deterministic within a single R session but may vary
137/// between sessions due to Rust's hasher implementation.
138///
139/// The hash is returned as a hex `String` (e.g. `"a1b2c3d4e5f60718"`), not a
140/// number. R has no faithful 64-bit integer type, so returning the `u64` as a
141/// numeric would round away its low bits above `2^53` — distinct Rust values
142/// would collide in R — and surface half the range as negative. A hex string
143/// preserves all 64 bits, is directly usable as an R environment key, and
144/// works with `duplicated()` / `match()` for deduplication.
145///
146/// # Example
147///
148/// ```rust,ignore
149/// #[derive(Hash, ExternalPtr)]
150/// struct Record { id: String, value: i64 }
151///
152/// #[miniextendr]
153/// impl miniextendr_api::adapter_traits::RHash for Record {}
154/// ```
155#[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();
                unsafe { ::miniextendr_api::trait_abi::to_sexp(result) }
            })
}
#[doc = "Type tag for runtime identification of the `RHash` trait."]
#[doc = "Generated from source location line 156, 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 156, 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 156, 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 156, 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) * }
            { #[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; fn r_hash(& self) -> String; }
        }
    };
}
#[doc(hidden)]
#[allow(unused_imports)]
pub use __mx_trait_metadata_RHash_2 as RHash;#[miniextendr]
156pub trait RHash {
157    /// Compute a hash of this value.
158    ///
159    /// Returns the [`DefaultHasher`] `u64` output as a 16-character lowercase
160    /// hex string. See the trait-level docs for why a string rather than a
161    /// number.
162    #[miniextendr(r_name = "hash")]
163    fn r_hash(&self) -> String;
164}
165
166impl<T: Hash> RHash for T {
167    fn r_hash(&self) -> String {
168        let mut hasher = DefaultHasher::new();
169        Hash::hash(self, &mut hasher);
170        // R has no faithful 64-bit integer; hex-encode the full u64 so every
171        // bit survives the trip to R (a numeric would round above 2^53).
172        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:016x}", hasher.finish()))
    })format!("{:016x}", hasher.finish())
173    }
174}
175
176/// Adapter trait for [`std::cmp::Ord`].
177///
178/// Provides total ordering comparison for R sorting operations.
179/// Automatically implemented for any type that implements `Ord`.
180///
181/// # Methods
182///
183/// - `r_cmp(&self, other: &Self)` (`cmp()` in R) - Returns -1, 0, or 1
184///
185/// # Example
186///
187/// ```rust,ignore
188/// #[derive(Ord, PartialOrd, Eq, PartialEq, ExternalPtr)]
189/// struct Priority(u32);
190///
191/// #[miniextendr]
192/// impl miniextendr_api::adapter_traits::ROrd for Priority {}
193/// ```
194#[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 + ::core::marker::Send + '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"), &[],
                                            {
                                                #[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);
                unsafe { ::miniextendr_api::trait_abi::to_sexp(result) }
            })
}
#[doc = "Type tag for runtime identification of the `ROrd` trait."]
#[doc = "Generated from source location line 195, 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 195, 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 195, 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 195, 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 + ::core::marker::Send + '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) * }
            { #[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; fn r_cmp(& self, other : & Self) -> i32; }
        }
    };
}
#[doc(hidden)]
#[allow(unused_imports)]
pub use __mx_trait_metadata_ROrd_3 as ROrd;#[miniextendr]
195pub trait ROrd {
196    /// Compare with another value.
197    ///
198    /// Returns:
199    /// - `-1` if `self < other`
200    /// - `0` if `self == other`
201    /// - `1` if `self > other`
202    #[miniextendr(r_name = "cmp")]
203    fn r_cmp(&self, other: &Self) -> i32;
204}
205
206impl<T: Ord> ROrd for T {
207    fn r_cmp(&self, other: &Self) -> i32 {
208        match Ord::cmp(self, other) {
209            std::cmp::Ordering::Less => -1,
210            std::cmp::Ordering::Equal => 0,
211            std::cmp::Ordering::Greater => 1,
212        }
213    }
214}
215
216/// Adapter trait for [`std::cmp::PartialOrd`].
217///
218/// Provides partial ordering comparison for R, handling incomparable values.
219/// Automatically implemented for any type that implements `PartialOrd`.
220///
221/// # Methods
222///
223/// - `r_partial_cmp(&self, other: &Self)` (`partial_cmp()` in R) - Returns
224///   Some(-1/0/1) or None
225///
226/// # Example
227///
228/// ```rust,ignore
229/// // f64 has partial ordering (NaN is not comparable)
230/// #[derive(PartialOrd, PartialEq, ExternalPtr)]
231/// struct MyFloat(f64);
232///
233/// #[miniextendr]
234/// impl miniextendr_api::adapter_traits::RPartialOrd for MyFloat {}
235/// ```
236#[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 + ::core::marker::Send + '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"), &[],
                                            {
                                                #[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);
                unsafe { ::miniextendr_api::trait_abi::to_sexp(result) }
            })
}
#[doc = "Type tag for runtime identification of the `RPartialOrd` trait."]
#[doc = "Generated from source location line 237, 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 237, 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 237, 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 237, 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 + ::core::marker::Send + '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) * }
            {
                #[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; fn r_partial_cmp(& self, other : & Self)
                -> Option < i32 > ;
            }
        }
    };
}
#[doc(hidden)]
#[allow(unused_imports)]
pub use __mx_trait_metadata_RPartialOrd_4 as RPartialOrd;#[miniextendr]
237pub trait RPartialOrd {
238    /// Compare with another value, returning None if incomparable.
239    ///
240    /// Returns:
241    /// - `Some(-1)` if `self < other`
242    /// - `Some(0)` if `self == other`
243    /// - `Some(1)` if `self > other`
244    /// - `None` if values are incomparable (in R, `NA`)
245    #[miniextendr(r_name = "partial_cmp")]
246    fn r_partial_cmp(&self, other: &Self) -> Option<i32>;
247}
248
249impl<T: PartialOrd> RPartialOrd for T {
250    fn r_partial_cmp(&self, other: &Self) -> Option<i32> {
251        PartialOrd::partial_cmp(self, other).map(|ord| match ord {
252            std::cmp::Ordering::Less => -1,
253            std::cmp::Ordering::Equal => 0,
254            std::cmp::Ordering::Greater => 1,
255        })
256    }
257}
258
259/// Adapter trait for [`std::error::Error`].
260///
261/// Provides error message extraction and error chain walking for R.
262/// Automatically implemented for any type that implements `Error`.
263///
264/// # Methods
265///
266/// - `error_message()` - Returns the error's display message
267/// - `error_chain()` - Returns all messages in the error chain
268///
269/// # Example
270///
271/// ```rust,ignore
272/// use std::error::Error;
273/// use std::fmt;
274///
275/// #[derive(Debug)]
276/// struct MyError { msg: String, source: Option<Box<dyn Error + Send + Sync>> }
277///
278/// impl fmt::Display for MyError {
279///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
280///         write!(f, "{}", self.msg)
281///     }
282/// }
283///
284/// impl Error for MyError {
285///     fn source(&self) -> Option<&(dyn Error + 'static)> {
286///         self.source.as_ref().map(|e| e.as_ref() as _)
287///     }
288/// }
289///
290/// // Wrap in ExternalPtr for R access
291/// #[derive(ExternalPtr)]
292/// struct MyErrorWrapper(MyError);
293///
294/// #[miniextendr]
295/// impl miniextendr_api::adapter_traits::RError for MyErrorWrapper {}
296/// ```
297#[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();
                unsafe { ::miniextendr_api::trait_abi::to_sexp(result) }
            })
}
#[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();
                unsafe { ::miniextendr_api::trait_abi::to_sexp(result) }
            })
}
#[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();
                unsafe { ::miniextendr_api::trait_abi::to_sexp(result) }
            })
}
#[doc = "Type tag for runtime identification of the `RError` trait."]
#[doc = "Generated from source location line 298, 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 298, 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 298, 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 298, 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) * }
            { fn error_message(); fn error_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; fn error_message(& self) -> String; }
            method
            {
                r_name = error_chain; fn error_chain(& self) -> Vec < String >
                ;
            } method
            {
                r_name = error_chain_length; fn error_chain_length(& self) ->
                i32;
            }
        }
    };
}
#[doc(hidden)]
#[allow(unused_imports)]
pub use __mx_trait_metadata_RError_5 as RError;#[miniextendr]
298pub trait RError {
299    /// Get the error message (Display representation).
300    fn error_message(&self) -> String;
301
302    /// Get all error messages in the chain, from outermost to innermost.
303    fn error_chain(&self) -> Vec<String>;
304
305    /// Get the number of errors in the chain.
306    fn error_chain_length(&self) -> i32;
307}
308
309impl<T: std::error::Error> RError for T {
310    fn error_message(&self) -> String {
311        self.to_string()
312    }
313
314    fn error_chain(&self) -> Vec<String> {
315        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()];
316        let mut current: &dyn std::error::Error = self;
317        while let Some(source) = current.source() {
318            chain.push(source.to_string());
319            current = source;
320        }
321        chain
322    }
323
324    fn error_chain_length(&self) -> i32 {
325        let mut count = 1i32;
326        let mut current: &dyn std::error::Error = self;
327        while let Some(source) = current.source() {
328            count += 1;
329            current = source;
330        }
331        count
332    }
333}
334
335/// Adapter trait for [`std::str::FromStr`].
336///
337/// Provides string parsing for R, allowing R strings to be parsed into Rust types.
338/// Automatically implemented for any type that implements `FromStr`.
339///
340/// # Methods
341///
342/// - `r_from_str(s: &str)` (`from_str()` in R) - Parse a string into this
343///   type, returning None on failure
344///
345/// # Example
346///
347/// ```rust,ignore
348/// use std::net::IpAddr;
349///
350/// // IpAddr implements FromStr
351/// #[derive(ExternalPtr)]
352/// struct IpAddress(IpAddr);
353///
354/// #[miniextendr]
355/// impl miniextendr_api::adapter_traits::RFromStr for IpAddress {}
356/// ```
357///
358/// In R:
359/// ```r
360/// ip <- IpAddress$RFromStr$from_str("192.168.1.1")
361/// ```
362#[doc = "Type tag for runtime identification of the `RFromStr` trait."]
#[doc = "Generated from source location line 363, 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 363, 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 363, 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 363, 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) * }
            { #[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; fn r_from_str(s : & str) -> Option < Self >
                ;
            }
        }
    };
}
#[doc(hidden)]
#[allow(unused_imports)]
pub use __mx_trait_metadata_RFromStr_6 as RFromStr;#[miniextendr]
363pub trait RFromStr: Sized {
364    /// Parse a string into this type.
365    ///
366    /// Returns `Some(value)` on success, `None` on parse failure, which R
367    /// receives as `NULL`.
368    #[miniextendr(r_name = "from_str")]
369    fn r_from_str(s: &str) -> Option<Self>;
370}
371
372impl<T: FromStr> RFromStr for T {
373    fn r_from_str(s: &str) -> Option<Self> {
374        s.parse().ok()
375    }
376}
377
378/// Adapter trait for [`std::clone::Clone`].
379///
380/// Provides explicit deep copying for R. This is useful when R users need
381/// to create independent copies of Rust objects (which normally use reference
382/// semantics via `ExternalPtr`).
383///
384/// # Methods
385///
386/// - `r_clone()` (`clone()` in R) - Create a deep copy of this value
387///
388/// # Example
389///
390/// ```rust,ignore
391/// #[derive(Clone, ExternalPtr)]
392/// struct Buffer { data: Vec<u8> }
393///
394/// #[miniextendr]
395/// impl miniextendr_api::adapter_traits::RClone for Buffer {}
396/// ```
397///
398/// In R:
399/// ```r
400/// buf1 <- Buffer$new(...)
401/// buf2 <- buf1$RClone$clone()  # Independent copy
402/// ```
403#[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();
                unsafe { ::miniextendr_api::trait_abi::to_sexp(result) }
            })
}
#[doc = "Type tag for runtime identification of the `RClone` trait."]
#[doc = "Generated from source location line 404, 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 404, 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 404, 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 404, 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) * }
            { #[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; fn r_clone(& self) -> Self; }
        }
    };
}
#[doc(hidden)]
#[allow(unused_imports)]
pub use __mx_trait_metadata_RClone_7 as RClone;#[miniextendr]
404pub trait RClone {
405    /// Create a deep copy of this value.
406    #[miniextendr(r_name = "clone")]
407    fn r_clone(&self) -> Self;
408}
409
410impl<T: Clone> RClone for T {
411    fn r_clone(&self) -> Self {
412        Clone::clone(self)
413    }
414}
415
416/// Adapter trait for [`std::default::Default`].
417///
418/// Provides default value construction for R. This allows R users to create
419/// instances with default values without needing to specify all parameters.
420///
421/// # Methods
422///
423/// - `r_default()` (`default()` in R) - Create a new instance with default
424///   values
425///
426/// # Example
427///
428/// ```rust,ignore
429/// #[derive(Default, ExternalPtr)]
430/// struct Config {
431///     timeout: u32,     // defaults to 0
432///     retries: u32,     // defaults to 0
433///     verbose: bool,    // defaults to false
434/// }
435///
436/// #[miniextendr]
437/// impl miniextendr_api::adapter_traits::RDefault for Config {}
438/// ```
439///
440/// In R:
441/// ```r
442/// config <- Config$RDefault$default()  # All fields have default values
443/// ```
444#[doc = "Type tag for runtime identification of the `RDefault` trait."]
#[doc = "Generated from source location line 445, 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 445, 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 445, 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 445, 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) * }
            { #[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; fn r_default() -> Self; }
        }
    };
}
#[doc(hidden)]
#[allow(unused_imports)]
pub use __mx_trait_metadata_RDefault_8 as RDefault;#[miniextendr]
445pub trait RDefault {
446    /// Create a new instance with default values.
447    #[miniextendr(r_name = "default")]
448    fn r_default() -> Self;
449}
450
451impl<T: Default> RDefault for T {
452    fn r_default() -> Self {
453        <T as Default>::default()
454    }
455}
456
457/// Adapter trait for [`std::marker::Copy`].
458///
459/// Indicates that a type can be cheaply copied (bitwise copy, no heap allocation).
460/// This is useful for R users to know that copying is O(1) and doesn't involve
461/// deep cloning of heap data.
462///
463/// # Methods
464///
465/// - `copy()` - Create a bitwise copy of this value
466/// - `is_copy()` - Returns true (useful for runtime type checking in R)
467///
468/// # Difference from RClone
469///
470/// Both `RCopy` and `RClone` create copies, but:
471/// - `RCopy`: Only for types where copying is cheap (stack-only, no heap)
472/// - `RClone`: For any clonable type (may involve heap allocation)
473///
474/// If a type implements both, prefer `copy()` when you know copies are frequent.
475///
476/// # Example
477///
478/// ```rust,ignore
479/// #[derive(Copy, Clone, ExternalPtr)]
480/// struct Point { x: f64, y: f64 }
481///
482/// #[miniextendr]
483/// impl miniextendr_api::adapter_traits::RCopy for Point {}
484/// ```
485///
486/// In R:
487/// ```r
488/// p1 <- Point$new(1.0, 2.0)
489/// p2 <- p1$RCopy$copy()  # Cheap bitwise copy
490/// p1$RCopy$is_copy()       # TRUE
491/// ```
492#[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();
                unsafe { ::miniextendr_api::trait_abi::to_sexp(result) }
            })
}
#[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();
                unsafe { ::miniextendr_api::trait_abi::to_sexp(result) }
            })
}
#[doc = "Type tag for runtime identification of the `RCopy` trait."]
#[doc = "Generated from source location line 493, 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 493, 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 493, 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 493, 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) * }
            { fn copy(); 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; fn copy(& self) -> Self; } method
            { r_name = is_copy; fn is_copy(& self) -> bool; }
        }
    };
}
#[doc(hidden)]
#[allow(unused_imports)]
pub use __mx_trait_metadata_RCopy_9 as RCopy;#[miniextendr]
493pub trait RCopy {
494    /// Create a bitwise copy of this value.
495    ///
496    /// For Copy types, this is always cheap (O(1), no heap allocation).
497    fn copy(&self) -> Self;
498
499    /// Check if this type implements Copy.
500    ///
501    /// Always returns true for types implementing this trait.
502    /// Useful for runtime type checking in R.
503    fn is_copy(&self) -> bool;
504}
505
506impl<T: Copy> RCopy for T {
507    fn copy(&self) -> Self {
508        *self
509    }
510
511    fn is_copy(&self) -> bool {
512        true
513    }
514}
515
516/// Adapter trait for [`std::iter::Iterator`].
517///
518/// Provides iterator operations for R, allowing Rust iterators to be consumed
519/// element-by-element from R code. Since iterators are stateful, the wrapper
520/// type should use interior mutability (e.g., `RefCell`).
521///
522/// # Methods
523///
524/// - `next()` (`next_item()` in R) - Get the next element, or None if exhausted
525/// - `size_hint()` - Get estimated remaining elements as `list(lower, upper)`
526/// - `count()` - Consume and count remaining elements
527/// - `collect_n(n)` - Collect up to n elements into a vector
528/// - `skip(n)` - Skip n elements
529/// - `nth(n)` - Get the nth element (0-indexed)
530///
531/// # Example
532///
533/// ```rust,ignore
534/// use miniextendr_api::Nullable;
535/// use miniextendr_api::adapter_traits::RIterator;
536/// use std::cell::RefCell;
537///
538/// #[derive(ExternalPtr)]
539/// struct MyIter(RefCell<std::vec::IntoIter<i32>>);
540///
541/// #[miniextendr(env)]
542/// impl MyIter {
543///     fn new(data: Vec<i32>) -> Self {
544///         Self(RefCell::new(data.into_iter()))
545///     }
546/// }
547///
548/// // An impl with a body inherits the trait's R names; each method here
549/// // forwards to the cell.
550/// #[miniextendr(env)]
551/// impl miniextendr_api::adapter_traits::RIterator for MyIter {
552///     type Item = i32;
553///
554///     fn next(&self) -> Nullable<i32> {
555///         self.0.next()
556///     }
557///
558///     fn size_hint(&self) -> (i64, Option<i64>) {
559///         self.0.size_hint()
560///     }
561///
562///     fn count(&self) -> i64 {
563///         self.0.count()
564///     }
565///
566///     fn collect_n(&self, n: i32) -> Vec<i32> {
567///         self.0.collect_n(n)
568///     }
569///
570///     fn skip(&self, n: i32) -> i32 {
571///         self.0.skip(n)
572///     }
573///
574///     fn nth(&self, n: i32) -> Nullable<i32> {
575///         self.0.nth(n)
576///     }
577/// }
578/// ```
579///
580/// In R (`next` is a reserved word, so the method is `next_item`):
581/// ```r
582/// it <- MyIter$new(c(1L, 2L, 3L))
583/// it$RIterator$next_item()   # 1L
584/// it$RIterator$next_item()   # 2L
585/// it$RIterator$size_hint()   # list(1L, 1L) - one element remaining
586/// it$RIterator$collect_n(5L) # 3L
587/// it$RIterator$next_item()   # NULL (exhausted)
588/// ```
589///
590/// # Design Note
591///
592/// Every `RefCell<I>` with `I: Iterator` implements this trait. The cell
593/// supplies mutable access without erasing the iterator or restricting its item
594/// type. A concrete ExternalPtr class can delegate to its cell. This also covers
595/// standard-library adapters, `itertools` adapters and distribution iterators.
596///
597/// The blanket implementation forwards `nth` to the iterator, retaining its
598/// specialized implementation. It follows the source's
599/// exhaustion behavior; use `Iterator::fuse` when `None` must be permanent.
600#[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();
                unsafe { ::miniextendr_api::trait_abi::to_sexp(result) }
            })
}
#[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();
                unsafe { ::miniextendr_api::trait_abi::to_sexp(result) }
            })
}
#[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();
                unsafe { ::miniextendr_api::trait_abi::to_sexp(result) }
            })
}
#[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 __miniextendr_native_borrows =
                        [<i32 as ::miniextendr_api::TryFromSexp>::NATIVE_BORROW];
                    if ::miniextendr_api::from_r::borrow::needs_check(&__miniextendr_native_borrows)
                        {
                        unsafe {
                            ::miniextendr_api::from_r::borrow::assert_no_aliases([(*argv.add(0usize),
                                            "n")], __miniextendr_native_borrows);
                        }
                    }
                }
                let n: i32 =
                    match <i32 as
                                ::miniextendr_api::TryFromSexp>::try_from_sexp(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"), &[],
                                        {
                                            #[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);
                unsafe { ::miniextendr_api::trait_abi::to_sexp(result) }
            })
}
#[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 __miniextendr_native_borrows =
                        [<i32 as ::miniextendr_api::TryFromSexp>::NATIVE_BORROW];
                    if ::miniextendr_api::from_r::borrow::needs_check(&__miniextendr_native_borrows)
                        {
                        unsafe {
                            ::miniextendr_api::from_r::borrow::assert_no_aliases([(*argv.add(0usize),
                                            "n")], __miniextendr_native_borrows);
                        }
                    }
                }
                let n: i32 =
                    match <i32 as
                                ::miniextendr_api::TryFromSexp>::try_from_sexp(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"), &[],
                                        {
                                            #[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);
                unsafe { ::miniextendr_api::trait_abi::to_sexp(result) }
            })
}
#[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 __miniextendr_native_borrows =
                        [<i32 as ::miniextendr_api::TryFromSexp>::NATIVE_BORROW];
                    if ::miniextendr_api::from_r::borrow::needs_check(&__miniextendr_native_borrows)
                        {
                        unsafe {
                            ::miniextendr_api::from_r::borrow::assert_no_aliases([(*argv.add(0usize),
                                            "n")], __miniextendr_native_borrows);
                        }
                    }
                }
                let n: i32 =
                    match <i32 as
                                ::miniextendr_api::TryFromSexp>::try_from_sexp(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"), &[],
                                        {
                                            #[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);
                unsafe { ::miniextendr_api::trait_abi::to_sexp(result) }
            })
}
#[doc = "Type tag for runtime identification of the `RIterator` trait."]
#[doc = "Generated from source location line 601, 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 601, 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 601, 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 601, 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) * }
            {
                #[miniextendr(r_name = "next_item")] fn next(); 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]
601pub trait RIterator {
602    /// The type of elements yielded by this iterator.
603    type Item;
604
605    /// Get the next element from the iterator.
606    ///
607    /// Returns `Nullable(Some(item))` while there are elements, and
608    /// `Nullable(None)` once exhausted, which R receives as `NULL` whatever
609    /// the item type: an `NA` could be an item, `NULL` never is.
610    #[miniextendr(r_name = "next_item")]
611    fn next(&self) -> Nullable<Self::Item>;
612
613    /// Get the estimated number of remaining elements.
614    ///
615    /// Returns `(lower_bound, upper_bound)` where upper_bound is None if unknown.
616    /// In R, this becomes `list(lower, upper)` where upper is NA if unknown.
617    fn size_hint(&self) -> (i64, Option<i64>);
618
619    /// Consume the iterator and count remaining elements.
620    ///
621    /// **Warning:** This exhausts the iterator.
622    fn count(&self) -> i64 {
623        let mut count = 0i64;
624        while self.next().0.is_some() {
625            count += 1;
626        }
627        count
628    }
629
630    /// Collect up to `n` elements into a vector.
631    ///
632    /// Returns fewer than `n` elements if the iterator is exhausted first.
633    fn collect_n(&self, n: i32) -> Vec<Self::Item> {
634        let mut result = Vec::with_capacity(n.max(0) as usize);
635        for _ in 0..n {
636            match self.next().0 {
637                Some(item) => result.push(item),
638                None => break,
639            }
640        }
641        result
642    }
643
644    /// Skip `n` elements from the iterator.
645    ///
646    /// Returns the number of elements actually skipped (may be less than `n`
647    /// if the iterator is exhausted).
648    fn skip(&self, n: i32) -> i32 {
649        let mut skipped = 0i32;
650        for _ in 0..n {
651            if self.next().0.is_none() {
652                break;
653            }
654            skipped += 1;
655        }
656        skipped
657    }
658
659    /// Get the `n`th element (0-indexed), consuming elements up to and including it.
660    ///
661    /// Returns `Nullable(None)` (`NULL` in R) if `n` is negative or the
662    /// iterator has fewer than `n + 1` elements.
663    fn nth(&self, n: i32) -> Nullable<Self::Item> {
664        if n < 0 {
665            return Nullable(None);
666        }
667        for _ in 0..n {
668            if self.next().0.is_none() {
669                return Nullable(None);
670            }
671        }
672        self.next()
673    }
674}
675
676impl<I: Iterator> RIterator for std::cell::RefCell<I> {
677    type Item = I::Item;
678
679    fn next(&self) -> Nullable<Self::Item> {
680        Nullable(self.borrow_mut().next())
681    }
682
683    fn size_hint(&self) -> (i64, Option<i64>) {
684        let (lower, upper) = self.borrow().size_hint();
685        // An unbounded iterator may report usize::MAX as its lower bound.
686        // Saturating the lower bound and omitting an unrepresentable upper
687        // bound keeps both valid in this trait's signed representation.
688        (
689            i64::try_from(lower).unwrap_or(i64::MAX),
690            upper.and_then(|value| i64::try_from(value).ok()),
691        )
692    }
693
694    fn count(&self) -> i64 {
695        i64::try_from(self.borrow_mut().by_ref().count()).expect("iterator count exceeds i64::MAX")
696    }
697
698    fn collect_n(&self, n: i32) -> Vec<Self::Item> {
699        let n = usize::try_from(n.max(0)).expect("nonnegative i32 fits usize");
700        self.borrow_mut().by_ref().take(n).collect()
701    }
702
703    fn skip(&self, n: i32) -> i32 {
704        let n = usize::try_from(n.max(0)).expect("nonnegative i32 fits usize");
705        i32::try_from(self.borrow_mut().by_ref().take(n).count())
706            .expect("skipped count is bounded by n")
707    }
708
709    fn nth(&self, n: i32) -> Nullable<Self::Item> {
710        Nullable(
711            usize::try_from(n)
712                .ok()
713                .and_then(|n| self.borrow_mut().nth(n)),
714        )
715    }
716}
717
718/// Adapter trait for [`std::iter::Extend`].
719///
720/// Provides collection extension operations for R, allowing Rust collections
721/// to be extended with R vectors. Since extension requires mutation, the
722/// wrapper type should use interior mutability (e.g., `RefCell`).
723///
724/// # Methods
725///
726/// - `extend_from_vec(items)` - Extend the collection with items from a vector
727/// - `extend_from_slice(items)` - Extend from a slice (for Clone items)
728/// - `r_len()` (`len()` in R) - Get the current length, or -1 if unknown
729/// - `r_is_empty()` (`is_empty()` in R) - Check if the collection is empty
730///
731/// # Example
732///
733/// ```rust,ignore
734/// use std::cell::RefCell;
735///
736/// #[derive(ExternalPtr)]
737/// struct MyVec(RefCell<Vec<i32>>);
738///
739/// #[miniextendr(env)]
740/// impl MyVec {
741///     fn new() -> Self {
742///         Self(RefCell::new(Vec::new()))
743///     }
744/// }
745///
746/// // The trait is generic, so the impl spells out each exported method and
747/// // repeats the R names of the renamed ones.
748/// #[miniextendr(env)]
749/// impl miniextendr_api::adapter_traits::RExtend<i32> for MyVec {
750///     fn extend_from_vec(&self, items: Vec<i32>) {
751///         self.0.borrow_mut().extend(items);
752///     }
753///
754///     fn r_len(&self) -> i64 {
755///         i64::try_from(self.0.borrow().len()).expect("length fits i64")
756///     }
757///
758///     fn r_is_empty(&self) -> bool {
759///         self.0.borrow().is_empty()
760///     }
761/// }
762/// ```
763///
764/// In R:
765/// ```r
766/// v <- MyVec$new()
767/// v$RExtend$extend_from_vec(c(1L, 2L, 3L))  # Add items
768/// v$RExtend$extend_from_vec(c(4L, 5L))      # Add more items
769/// v$RExtend$len()                           # 5
770/// ```
771///
772/// # Design Note
773///
774/// Like `RIterator`, `RExtend` does NOT have a blanket impl because `Extend::extend()`
775/// requires `&mut self`, but R's ExternalPtr pattern provides `&self`. Users must
776/// implement this trait manually using interior mutability (RefCell, Mutex, etc.).
777#[doc = "Type tag for runtime identification of the `RExtend` trait."]
#[doc = "Generated from source location line 778, 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 778, 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) * }
            {
                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]
778pub trait RExtend<T> {
779    /// Extend the collection with items from a vector.
780    ///
781    /// The items are moved into the collection.
782    fn extend_from_vec(&self, items: Vec<T>);
783
784    /// Extend the collection with cloned items from a slice.
785    ///
786    /// Default implementation clones items into a Vec and calls `extend_from_vec`.
787    ///
788    /// Skipped from trait ABI because `&[T]` doesn't have TryFromSexp.
789    #[miniextendr(skip)]
790    fn extend_from_slice(&self, items: &[T])
791    where
792        T: Clone,
793    {
794        self.extend_from_vec(items.to_vec());
795    }
796
797    /// Get the current length of the collection.
798    ///
799    /// Optional - returns -1 if not implemented.
800    #[miniextendr(r_name = "len")]
801    fn r_len(&self) -> i64 {
802        -1 // Indicates "unknown" - implementers can override
803    }
804
805    /// Check if the collection is empty.
806    ///
807    /// Returns false when length is unknown.
808    #[miniextendr(r_name = "is_empty")]
809    fn r_is_empty(&self) -> bool {
810        self.r_len() == 0
811    }
812}
813
814// Note: No blanket impl because Extend::extend() requires &mut self,
815// but ExternalPtr methods receive &self. Users must use interior mutability.
816
817/// Adapter trait for [`std::iter::FromIterator`].
818///
819/// Provides collection construction from iterators/vectors for R.
820/// Unlike `RExtend`, this creates a new collection from items.
821///
822/// # Methods
823///
824/// - `from_vec(items)` - Create a new collection from a vector
825///
826/// # Example
827///
828/// ```rust,ignore
829/// #[derive(ExternalPtr)]
830/// struct MySet(std::collections::HashSet<i32>);
831///
832/// #[miniextendr(env)]
833/// impl miniextendr_api::adapter_traits::RFromIter<i32> for MySet {
834///     fn from_vec(items: Vec<i32>) -> Self {
835///         Self(items.into_iter().collect())
836///     }
837/// }
838/// ```
839///
840/// In R:
841/// ```r
842/// set <- MySet$RFromIter$from_vec(c(1L, 2L, 2L, 3L))  # Creates {1, 2, 3}
843/// ```
844#[doc = "Type tag for runtime identification of the `RFromIter` trait."]
#[doc = "Generated from source location line 845, 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 845, 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) * }
            { 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]
845pub trait RFromIter<T>: Sized {
846    /// Create a new collection from a vector of items.
847    fn from_vec(items: Vec<T>) -> Self;
848}
849
850impl<C, T> RFromIter<T> for C
851where
852    C: FromIterator<T>,
853{
854    fn from_vec(items: Vec<T>) -> Self {
855        items.into_iter().collect()
856    }
857}
858
859/// Adapter trait for collections that can be converted to vectors.
860///
861/// This is the complement to [`RFromIter`]: while `RFromIter` creates collections
862/// from vectors, `RToVec` extracts vectors from collections.
863///
864/// # Methods
865///
866/// - `r_to_vec()` (`to_vec()` in R) - Collect all elements into a vector
867///   (cloning elements)
868/// - `r_len()` (`len()` in R) - Get the number of elements
869/// - `r_is_empty()` (`is_empty()` in R) - Check if the collection is empty
870///
871/// # Design Note
872///
873/// Unlike Rust's `IntoIterator::into_iter()` which consumes the collection,
874/// this trait borrows the collection and clones elements. This is necessary
875/// because R's `ExternalPtr` pattern provides `&self`, not owned `self`.
876///
877/// For consuming iteration, use [`RIterator`] with interior mutability.
878///
879/// # Example
880///
881/// ```rust,ignore
882/// use miniextendr_api::adapter_traits::RToVec;
883/// use std::collections::HashSet;
884///
885/// #[derive(ExternalPtr)]
886/// struct MySet(HashSet<i32>);
887///
888/// // `&MySet` doesn't iterate, so the blanket impl doesn't cover the wrapper:
889/// // the impl forwards to the set, which it does cover. The trait is generic,
890/// // so the impl spells out each method; R names come from the trait.
891/// #[miniextendr(env)]
892/// impl miniextendr_api::adapter_traits::RToVec<i32> for MySet {
893///     fn r_to_vec(&self) -> Vec<i32> {
894///         self.0.r_to_vec()
895///     }
896///
897///     fn r_len(&self) -> i64 {
898///         self.0.r_len()
899///     }
900///
901///     fn r_is_empty(&self) -> bool {
902///         self.0.is_empty()
903///     }
904/// }
905/// ```
906///
907/// In R:
908/// ```r
909/// set <- MySet$new(...)
910/// vec <- set$RToVec$to_vec()    # Get all elements as vector
911/// set$RToVec$len()              # Number of elements
912/// set$RToVec$is_empty()         # Check if empty
913/// ```
914#[doc = "Type tag for runtime identification of the `RToVec` trait."]
#[doc = "Generated from source location line 915, 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 915, 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) * }
            {
                #[miniextendr(r_name = "to_vec")] fn r_to_vec();
                #[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]
915pub trait RToVec<T> {
916    /// Collect all elements into a vector.
917    ///
918    /// Elements are cloned from the collection.
919    #[miniextendr(r_name = "to_vec")]
920    fn r_to_vec(&self) -> Vec<T>;
921
922    /// Get the number of elements in the collection.
923    #[miniextendr(r_name = "len")]
924    fn r_len(&self) -> i64;
925
926    /// Check if the collection is empty.
927    #[miniextendr(r_name = "is_empty")]
928    fn r_is_empty(&self) -> bool {
929        self.r_len() == 0
930    }
931}
932
933// Blanket impl for any collection where:
934// - &C can be iterated over (yielding &T references)
935// - T: Clone (so we can clone elements into the Vec)
936// - The iterator knows its exact size
937//
938// Note: Using HRTB (higher-ranked trait bounds) to express that &C
939// can be iterated for any lifetime.
940impl<C, T> RToVec<T> for C
941where
942    T: Clone,
943    for<'a> &'a C: IntoIterator<Item = &'a T>,
944    for<'a> <&'a C as IntoIterator>::IntoIter: ExactSizeIterator,
945{
946    fn r_to_vec(&self) -> Vec<T> {
947        self.into_iter().cloned().collect()
948    }
949
950    fn r_len(&self) -> i64 {
951        i64::try_from(self.into_iter().len()).expect("collection length exceeds i64::MAX")
952    }
953}
954
955/// Adapter trait for creating iterator wrappers from collections.
956///
957/// This trait provides a way to create an [`RIterator`] wrapper from a collection.
958/// Since `ExternalPtr` methods receive `&self`, this trait clones the underlying
959/// data to create an independent iterator.
960///
961/// # Type Parameters
962///
963/// - `T`: The element type yielded by the iterator
964/// - `I`: The iterator type returned (must implement [`RIterator`])
965///
966/// # Design Note
967///
968/// The returned iterator is independent from the source collection. Modifications
969/// to the original collection after calling `make_iter()` won't affect the
970/// iterator's output.
971///
972/// # Example
973///
974/// ```rust,ignore
975/// use std::cell::RefCell;
976///
977/// #[derive(ExternalPtr)]
978/// struct MyVec(Vec<i32>);
979///
980/// #[derive(ExternalPtr)]
981/// struct MyVecIter(RefCell<std::vec::IntoIter<i32>>);
982///
983/// // `MyVecIter` implements `RIterator` as in the `RIterator` example.
984///
985/// #[miniextendr(env)]
986/// impl miniextendr_api::adapter_traits::RMakeIter<i32, MyVecIter> for MyVec {
987///     fn make_iter(&self) -> MyVecIter {
988///         MyVecIter(RefCell::new(self.0.clone().into_iter()))
989///     }
990/// }
991/// ```
992///
993/// In R (`next` is a reserved word, so the method is `next_item`):
994/// ```r
995/// v <- MyVec$new(c(1L, 2L, 3L))
996/// it <- v$RMakeIter$make_iter()   # Create iterator
997/// it$RIterator$next_item()        # 1L
998/// it$RIterator$next_item()        # 2L
999/// ```
1000#[doc = "Type tag for runtime identification of the `RMakeIter` trait."]
#[doc = "Generated from source location line 1001, 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 1001, 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) * }
            { 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]
1001pub trait RMakeIter<T, I>
1002where
1003    I: RIterator<Item = T>,
1004{
1005    /// Create a new iterator wrapper.
1006    ///
1007    /// The iterator is independent from this collection (typically by cloning
1008    /// the underlying data).
1009    fn make_iter(&self) -> I;
1010}
1011
1012// Note: No blanket impl because:
1013// 1. The iterator type I must be a concrete type that implements RIterator
1014// 2. RIterator requires interior mutability (RefCell/Mutex)
1015// 3. Users must define their own iterator wrapper type
1016
1017#[cfg(test)]
1018mod tests {
1019    use super::*;
1020
1021    #[test]
1022    fn test_rdebug() {
1023        let v = vec![1, 2, 3];
1024        assert_eq!(v.debug_str(), "[1, 2, 3]");
1025        assert!(v.debug_str_pretty().contains('\n') || v.debug_str_pretty() == "[1, 2, 3]");
1026    }
1027
1028    #[test]
1029    fn test_rdisplay() {
1030        let s = "hello";
1031        assert_eq!(s.as_r_string(), "hello");
1032
1033        let n = 42i32;
1034        assert_eq!(n.as_r_string(), "42");
1035    }
1036
1037    #[test]
1038    fn test_rhash() {
1039        let a = "test";
1040        let b = "test";
1041        let c = "other";
1042
1043        assert_eq!(a.r_hash(), b.r_hash());
1044        assert_ne!(a.r_hash(), c.r_hash());
1045    }
1046
1047    #[test]
1048    fn test_rord() {
1049        assert_eq!(1i32.r_cmp(&2), -1);
1050        assert_eq!(2i32.r_cmp(&2), 0);
1051        assert_eq!(3i32.r_cmp(&2), 1);
1052    }
1053
1054    #[test]
1055    fn test_rpartialord() {
1056        assert_eq!(1.0f64.r_partial_cmp(&2.0), Some(-1));
1057        assert_eq!(2.0f64.r_partial_cmp(&2.0), Some(0));
1058        assert_eq!(3.0f64.r_partial_cmp(&2.0), Some(1));
1059        assert_eq!(f64::NAN.r_partial_cmp(&1.0), None);
1060    }
1061
1062    #[test]
1063    fn test_rerror_simple() {
1064        use std::io;
1065        let err = io::Error::new(io::ErrorKind::NotFound, "file not found");
1066        assert_eq!(err.error_message(), "file not found");
1067        assert_eq!(err.error_chain().len(), 1);
1068        assert_eq!(err.error_chain_length(), 1);
1069    }
1070
1071    #[test]
1072    fn test_rerror_chain() {
1073        use std::fmt;
1074
1075        #[derive(Debug)]
1076        struct OuterError {
1077            msg: &'static str,
1078            source: InnerError,
1079        }
1080
1081        #[derive(Debug)]
1082        struct InnerError {
1083            msg: &'static str,
1084        }
1085
1086        impl fmt::Display for OuterError {
1087            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1088                write!(f, "{}", self.msg)
1089            }
1090        }
1091
1092        impl fmt::Display for InnerError {
1093            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1094                write!(f, "{}", self.msg)
1095            }
1096        }
1097
1098        impl std::error::Error for InnerError {}
1099
1100        impl std::error::Error for OuterError {
1101            fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1102                Some(&self.source)
1103            }
1104        }
1105
1106        let err = OuterError {
1107            msg: "outer error",
1108            source: InnerError { msg: "inner error" },
1109        };
1110
1111        assert_eq!(err.error_message(), "outer error");
1112        let chain = err.error_chain();
1113        assert_eq!(chain.len(), 2);
1114        assert_eq!(chain[0], "outer error");
1115        assert_eq!(chain[1], "inner error");
1116        assert_eq!(err.error_chain_length(), 2);
1117    }
1118
1119    #[test]
1120    fn test_rfromstr_success() {
1121        assert_eq!(i32::r_from_str("42"), Some(42));
1122        assert_eq!(
1123            f64::r_from_str("3.141592653589793"),
1124            Some(std::f64::consts::PI)
1125        );
1126        assert_eq!(bool::r_from_str("true"), Some(true));
1127    }
1128
1129    #[test]
1130    fn test_rfromstr_failure() {
1131        assert_eq!(i32::r_from_str("not a number"), None);
1132        assert_eq!(f64::r_from_str("abc"), None);
1133    }
1134
1135    #[test]
1136    fn test_rclone() {
1137        let v = vec![1, 2, 3];
1138        let cloned = v.r_clone();
1139        assert_eq!(v, cloned);
1140
1141        // Verify it's a deep copy
1142        let s = String::from("hello");
1143        let cloned_s = s.r_clone();
1144        assert_eq!(s, cloned_s);
1145    }
1146
1147    #[test]
1148    fn test_rdefault() {
1149        assert_eq!(i32::r_default(), 0);
1150        assert!(Vec::<i32>::r_default().is_empty());
1151        assert_eq!(String::r_default(), "");
1152        assert!(!bool::r_default());
1153    }
1154
1155    #[test]
1156    fn test_rcopy() {
1157        // Primitives are Copy
1158        let x = 42i32;
1159        let y = RCopy::copy(&x);
1160        assert_eq!(x, y);
1161        assert!(x.is_copy());
1162
1163        // Tuples of Copy types are Copy
1164        let point = (1.0f64, 2.0f64);
1165        let point2 = RCopy::copy(&point);
1166        assert_eq!(point, point2);
1167        assert!(point.is_copy());
1168
1169        // Arrays of Copy types are Copy
1170        let arr = [1, 2, 3];
1171        let arr2 = RCopy::copy(&arr);
1172        assert_eq!(arr, arr2);
1173    }
1174
1175    // Tests for RIterator
1176    use std::cell::RefCell;
1177
1178    /// Test iterator wrapper using RefCell for interior mutability.
1179    struct TestIter(RefCell<std::vec::IntoIter<i32>>);
1180
1181    impl TestIter {
1182        fn new(data: Vec<i32>) -> Self {
1183            Self(RefCell::new(data.into_iter()))
1184        }
1185    }
1186
1187    impl RIterator for TestIter {
1188        type Item = i32;
1189
1190        fn next(&self) -> Nullable<Self::Item> {
1191            Nullable(self.0.borrow_mut().next())
1192        }
1193
1194        fn size_hint(&self) -> (i64, Option<i64>) {
1195            let (lo, hi) = self.0.borrow().size_hint();
1196            (lo as i64, hi.map(|h| h as i64))
1197        }
1198    }
1199
1200    #[test]
1201    fn test_riterator_next() {
1202        let it = TestIter::new(vec![1, 2, 3]);
1203        assert_eq!(it.next().0, Some(1));
1204        assert_eq!(it.next().0, Some(2));
1205        assert_eq!(it.next().0, Some(3));
1206        assert_eq!(it.next().0, None);
1207        assert_eq!(it.next().0, None); // Stays exhausted
1208    }
1209
1210    #[test]
1211    fn test_riterator_size_hint() {
1212        let it = TestIter::new(vec![1, 2, 3, 4, 5]);
1213        assert_eq!(it.size_hint(), (5, Some(5)));
1214        it.next();
1215        assert_eq!(it.size_hint(), (4, Some(4)));
1216        it.next();
1217        it.next();
1218        assert_eq!(it.size_hint(), (2, Some(2)));
1219    }
1220
1221    #[test]
1222    fn test_riterator_count() {
1223        let it = TestIter::new(vec![1, 2, 3, 4, 5]);
1224        assert_eq!(it.count(), 5);
1225        // Iterator is now exhausted
1226        assert_eq!(it.next().0, None);
1227    }
1228
1229    #[test]
1230    fn test_riterator_collect_n() {
1231        let it = TestIter::new(vec![1, 2, 3, 4, 5]);
1232        let first_three = it.collect_n(3);
1233        assert_eq!(first_three, vec![1, 2, 3]);
1234        let remaining = it.collect_n(10); // Ask for more than available
1235        assert_eq!(remaining, vec![4, 5]);
1236    }
1237
1238    #[test]
1239    fn test_riterator_skip() {
1240        let it = TestIter::new(vec![1, 2, 3, 4, 5]);
1241        let skipped = it.skip(2);
1242        assert_eq!(skipped, 2);
1243        assert_eq!(it.next().0, Some(3));
1244
1245        // Skip more than remaining
1246        let skipped = it.skip(10);
1247        assert_eq!(skipped, 2); // Only 2 elements were left
1248    }
1249
1250    #[test]
1251    fn test_riterator_nth() {
1252        let it = TestIter::new(vec![10, 20, 30, 40, 50]);
1253        // Get element at index 2 (third element)
1254        assert_eq!(it.nth(2).0, Some(30));
1255        // Iterator has consumed 0, 1, 2 - next is index 3
1256        assert_eq!(it.next().0, Some(40));
1257
1258        // Negative index returns None
1259        let it2 = TestIter::new(vec![1, 2, 3]);
1260        assert_eq!(it2.nth(-1).0, None);
1261    }
1262
1263    #[test]
1264    fn test_riterator_empty() {
1265        let it = TestIter::new(vec![]);
1266        assert_eq!(it.next().0, None);
1267        assert_eq!(it.size_hint(), (0, Some(0)));
1268        assert_eq!(it.count(), 0);
1269        assert_eq!(it.collect_n(5), Vec::<i32>::new());
1270        assert_eq!(it.skip(5), 0);
1271        assert_eq!(it.nth(0).0, None);
1272    }
1273
1274    // Tests for RExtend
1275    struct TestExtendVec(RefCell<Vec<i32>>);
1276
1277    impl TestExtendVec {
1278        fn new() -> Self {
1279            Self(RefCell::new(Vec::new()))
1280        }
1281
1282        fn get(&self) -> Vec<i32> {
1283            Clone::clone(&*self.0.borrow())
1284        }
1285    }
1286
1287    impl RExtend<i32> for TestExtendVec {
1288        fn extend_from_vec(&self, items: Vec<i32>) {
1289            self.0.borrow_mut().extend(items);
1290        }
1291
1292        fn r_len(&self) -> i64 {
1293            i64::try_from(self.0.borrow().len()).expect("length fits i64")
1294        }
1295    }
1296
1297    #[test]
1298    fn test_rextend_basic() {
1299        let v = TestExtendVec::new();
1300        assert_eq!(v.get(), Vec::<i32>::new());
1301        assert_eq!(v.r_len(), 0);
1302        assert!(v.r_is_empty());
1303
1304        v.extend_from_vec(vec![1, 2, 3]);
1305        assert_eq!(v.get(), vec![1, 2, 3]);
1306        assert_eq!(v.r_len(), 3);
1307        assert!(!v.r_is_empty());
1308
1309        v.extend_from_vec(vec![4, 5]);
1310        assert_eq!(v.get(), vec![1, 2, 3, 4, 5]);
1311        assert_eq!(v.r_len(), 5);
1312    }
1313
1314    #[test]
1315    fn test_rextend_empty() {
1316        let v = TestExtendVec::new();
1317        v.extend_from_vec(vec![]);
1318        assert_eq!(v.get(), Vec::<i32>::new());
1319        assert_eq!(v.r_len(), 0);
1320    }
1321
1322    /// The default `r_len` reports an unknown length, which isn't empty.
1323    #[test]
1324    fn test_rextend_unknown_len() {
1325        struct Sink;
1326        impl RExtend<i32> for Sink {
1327            fn extend_from_vec(&self, _items: Vec<i32>) {}
1328        }
1329        assert_eq!(Sink.r_len(), -1);
1330        assert!(!Sink.r_is_empty());
1331    }
1332
1333    #[test]
1334    fn test_rextend_from_slice() {
1335        let v = TestExtendVec::new();
1336        let data = [1, 2, 3];
1337        v.extend_from_slice(&data);
1338        assert_eq!(v.get(), vec![1, 2, 3]);
1339    }
1340
1341    // Tests for RFromIter
1342    #[test]
1343    fn test_rfromiter_vec() {
1344        let v: Vec<i32> = RFromIter::from_vec(vec![1, 2, 3]);
1345        assert_eq!(v, vec![1, 2, 3]);
1346    }
1347
1348    #[test]
1349    fn test_rfromiter_hashset() {
1350        use std::collections::HashSet;
1351        let set: HashSet<i32> = RFromIter::from_vec(vec![1, 2, 2, 3, 3, 3]);
1352        assert_eq!(set.len(), 3);
1353        assert!(set.contains(&1));
1354        assert!(set.contains(&2));
1355        assert!(set.contains(&3));
1356    }
1357
1358    #[test]
1359    fn test_rfromiter_string() {
1360        let s: String = RFromIter::from_vec(vec!['h', 'e', 'l', 'l', 'o']);
1361        assert_eq!(s, "hello");
1362    }
1363
1364    #[test]
1365    fn test_rfromiter_empty() {
1366        let v: Vec<i32> = RFromIter::from_vec(vec![]);
1367        assert!(v.is_empty());
1368    }
1369
1370    // Tests for RToVec
1371    #[test]
1372    fn test_rtovec_vec() {
1373        let v = vec![1, 2, 3];
1374        assert_eq!(v.r_to_vec(), vec![1, 2, 3]);
1375        assert_eq!(v.r_len(), 3);
1376        assert!(!v.r_is_empty());
1377    }
1378
1379    #[test]
1380    fn test_rtovec_empty() {
1381        let v: Vec<i32> = vec![];
1382        assert!(v.r_to_vec().is_empty());
1383        assert_eq!(v.r_len(), 0);
1384        assert!(v.r_is_empty());
1385    }
1386
1387    #[test]
1388    fn test_rtovec_hashset() {
1389        use std::collections::HashSet;
1390        let mut set = HashSet::new();
1391        set.insert(1);
1392        set.insert(2);
1393        set.insert(3);
1394
1395        let mut collected = set.r_to_vec();
1396        collected.sort();
1397        assert_eq!(collected, vec![1, 2, 3]);
1398        assert_eq!(set.r_len(), 3);
1399    }
1400
1401    #[test]
1402    fn test_rtovec_slice() {
1403        let arr = [10, 20, 30];
1404        assert_eq!(arr.r_to_vec(), vec![10, 20, 30]);
1405        assert_eq!(arr.r_len(), 3);
1406    }
1407
1408    /// With every adapter trait in scope (`use super::*`), the std methods of
1409    /// the types their blanket impls cover still resolve to std, with std's
1410    /// result types.
1411    #[test]
1412    fn test_std_methods_resolve_with_adapters_in_scope() {
1413        use std::hash::DefaultHasher;
1414
1415        let v = vec![1, 2, 3];
1416        let cloned: Vec<i32> = v.clone();
1417        assert_eq!(cloned, v);
1418        assert_eq!(String::default(), "");
1419        assert_eq!(1.cmp(&2), std::cmp::Ordering::Less);
1420        assert_eq!(1.0f64.partial_cmp(&2.0), Some(std::cmp::Ordering::Less));
1421        let mut hasher = DefaultHasher::new();
1422        v.hash(&mut hasher);
1423        let _: u64 = hasher.finish();
1424        assert_eq!(i32::from_str("7"), Ok(7));
1425
1426        let arr = [10, 20, 30];
1427        let len: usize = arr.len();
1428        assert_eq!(len, 3);
1429        assert!(!arr.is_empty());
1430        let boxed: Box<[i32]> = vec![1, 2].into_boxed_slice();
1431        let boxed_len: usize = boxed.len();
1432        assert_eq!(boxed_len, 2);
1433        assert_eq!(boxed.to_vec(), vec![1, 2]);
1434    }
1435
1436    // Tests for RMakeIter
1437    struct TestCollection(Vec<i32>);
1438
1439    struct TestCollectionIter(RefCell<std::vec::IntoIter<i32>>);
1440
1441    impl RIterator for TestCollectionIter {
1442        type Item = i32;
1443
1444        fn next(&self) -> Nullable<i32> {
1445            Nullable(self.0.borrow_mut().next())
1446        }
1447
1448        fn size_hint(&self) -> (i64, Option<i64>) {
1449            let (lo, hi) = self.0.borrow().size_hint();
1450            (lo as i64, hi.map(|h| h as i64))
1451        }
1452    }
1453
1454    impl RMakeIter<i32, TestCollectionIter> for TestCollection {
1455        fn make_iter(&self) -> TestCollectionIter {
1456            TestCollectionIter(RefCell::new(Clone::clone(&self.0).into_iter()))
1457        }
1458    }
1459
1460    #[test]
1461    fn test_rmakeiter_basic() {
1462        let coll = TestCollection(vec![1, 2, 3]);
1463        let iter = coll.make_iter();
1464
1465        assert_eq!(iter.next().0, Some(1));
1466        assert_eq!(iter.next().0, Some(2));
1467        assert_eq!(iter.next().0, Some(3));
1468        assert_eq!(iter.next().0, None);
1469    }
1470
1471    #[test]
1472    fn test_rmakeiter_independent() {
1473        let coll = TestCollection(vec![1, 2, 3]);
1474
1475        // Create two independent iterators
1476        let iter1 = coll.make_iter();
1477        let iter2 = coll.make_iter();
1478
1479        // Consuming one doesn't affect the other
1480        assert_eq!(iter1.next().0, Some(1));
1481        assert_eq!(iter1.next().0, Some(2));
1482
1483        assert_eq!(iter2.next().0, Some(1)); // iter2 starts fresh
1484        assert_eq!(iter2.size_hint(), (2, Some(2))); // 2 remaining in iter2
1485    }
1486}