From eb701329fae8666862839063bfbd2f232b97a368 Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Sun, 3 Oct 2021 18:48:37 -0300 Subject: [PATCH 01/32] Added example for `declare_root_module_statics` Added doctest-based tests to ensure that `declare_root_module_statics!(Self);` doesn't work. Added example for `RootModule` Added more links to mentioned items in docs. --- abi_stable/src/library.rs | 82 ++++++++++++++++++++++-- abi_stable/src/library/root_mod_trait.rs | 55 ++++++++++++---- abi_stable/src/sabi_types/version.rs | 2 +- 3 files changed, 121 insertions(+), 18 deletions(-) diff --git a/abi_stable/src/library.rs b/abi_stable/src/library.rs index 0fbcdbcb..3dc0befe 100644 --- a/abi_stable/src/library.rs +++ b/abi_stable/src/library.rs @@ -110,13 +110,14 @@ impl IsLayoutChecked{ ////////////////////////////////////////////////////////////////////// /// The return type of the function that the -/// `#[export_root_module]` attribute outputs. +/// [`#[export_root_module]`](../attr.export_root_module.html) attribute outputs. pub type RootModuleResult = RResult, RootModuleError>; ////////////////////////////////////////////////////////////////////// -/// The static variables declared for some `RootModule` implementor. +/// The static variables declared for some [`RootModule`] implementor. +/// [`RootModule`]: ./trait.RootModule.html #[doc(hidden)] pub struct RootModuleStatics{ root_mod:LateStaticRef, @@ -135,16 +136,88 @@ impl RootModuleStatics{ } -/// Implements the `RootModule::root_module_statics` associated function. +/// Implements the [`RootModule::root_module_statics`] associated function. /// /// To define the associated function use: /// `abi_stable::declare_root_module_statics!{TypeOfSelf}`. /// Passing `Self` instead of `TypeOfSelf` won't work. +/// +/// # Example +/// +/// ```rust +/// use abi_stable::{ +/// library::RootModule, +/// sabi_types::VersionStrings, +/// StableAbi, +/// }; +/// +/// #[repr(C)] +/// #[derive(StableAbi)] +/// #[sabi(kind(Prefix(prefix_ref = "Module_Ref", prefix_fields = "Module_Prefix")))] +/// pub struct Module{ +/// pub first: u8, +/// #[sabi(last_prefix_field)] +/// pub second: u16, +/// pub third: u32, +/// } +/// impl RootModule for Module_Ref { +/// abi_stable::declare_root_module_statics!{Module_Ref} +/// const BASE_NAME: &'static str = "example_root_module"; +/// const NAME: &'static str = "example_root_module"; +/// const VERSION_STRINGS: VersionStrings = abi_stable::package_version_strings!(); +/// } +/// +/// # fn main(){} +/// ``` +/// +#[cfg_attr(doctest, doc = r###" + +```rust +struct Foo; +impl Foo { + abi_stable::declare_root_module_statics!{Foo} +} +``` + +```rust +struct Foo; +impl Foo { + abi_stable::declare_root_module_statics!{(Foo)} +} +``` + +```compile_fail +struct Foo; +impl Foo { + abi_stable::declare_root_module_statics!{Self} +} +``` + +```compile_fail +struct Foo; +impl Foo { + abi_stable::declare_root_module_statics!{(Self)} +} +``` + +```compile_fail +struct Foo; +impl Foo { + abi_stable::declare_root_module_statics!{((Self))} +} +``` + +"###)] +/// [`RootModule::root_module_statics`]: +/// ./library/trait.RootModule.html#tymethod.root_module_statics #[macro_export] macro_rules! declare_root_module_statics { ( ( $($stuff:tt)* ) ) => ( $crate::declare_root_module_statics!{$($stuff)*} ); + ( Self ) => ( + compile_error!{"Don't use `Self`, write the full type name"} + ); ( $this:ty ) => ( #[inline] fn root_module_statics()->&'static $crate::library::RootModuleStatics<$this>{ @@ -154,9 +227,6 @@ macro_rules! declare_root_module_statics { &_ROOT_MOD_STATICS } ); - ( Self ) => ( - compile_error!("Don't use `Self`, write the full type name") - ); } ////////////////////////////////////////////////////////////////////// diff --git a/abi_stable/src/library/root_mod_trait.rs b/abi_stable/src/library/root_mod_trait.rs index f38e1b9b..ad58a5b0 100644 --- a/abi_stable/src/library/root_mod_trait.rs +++ b/abi_stable/src/library/root_mod_trait.rs @@ -7,15 +7,46 @@ use crate::{ }; -/** -The root module of a dynamic library, -which may contain other modules,function pointers,and static references. - -For an example of a type implementing this trait you can look -at either the example in the readme for this crate, -or the `example/example_*_interface` crates in this crates' repository . - -*/ +/// The root module of a dynamic library, +/// which may contain other modules,function pointers,and static references. +/// +/// +/// # Examples +/// +/// For a more in-context example of a type implementing this trait you can look +/// at either the example in the readme for this crate, +/// or the `example/example_*_interface` crates in this crates' repository . +/// +/// ### Basic +/// +/// ```rust +/// use abi_stable::{ +/// library::RootModule, +/// sabi_types::VersionStrings, +/// StableAbi, +/// }; +/// +/// #[repr(C)] +/// #[derive(StableAbi)] +/// #[sabi(kind(Prefix(prefix_ref = "Module_Ref", prefix_fields = "Module_Prefix")))] +/// pub struct Module{ +/// pub first: u8, +/// // The `#[sabi(last_prefix_field)]` attribute here means that this is +/// // the last field in this module that was defined in the +/// // first compatible version of the library, +/// #[sabi(last_prefix_field)] +/// pub second: u16, +/// pub third: u32, +/// } +/// impl RootModule for Module_Ref { +/// abi_stable::declare_root_module_statics!{Module_Ref} +/// const BASE_NAME: &'static str = "example_root_module"; +/// const NAME: &'static str = "example_root_module"; +/// const VERSION_STRINGS: VersionStrings = abi_stable::package_version_strings!(); +/// } +/// +/// # fn main(){} +/// ``` pub trait RootModule: Sized + StableAbi + PrefixRefTrait + 'static { /// The name of the dynamic library,which is the same on all platforms. @@ -27,7 +58,8 @@ pub trait RootModule: Sized + StableAbi + PrefixRefTrait + 'static { /// The version number of the library that this is a root module of. /// - /// Initialize this with ` package_version_strings!() ` + /// Initialize this with + /// [`package_version_strings!()`](../macro.package_version_strings.html) const VERSION_STRINGS: VersionStrings; /// All the constants of this trait and supertraits. @@ -56,7 +88,8 @@ pub trait RootModule: Sized + StableAbi + PrefixRefTrait + 'static { /// Gets the statics for Self. /// /// To define this associated function use: - /// `abi_stable::declare_root_module_statics!{TypeOfSelf}`. + /// [`abi_stable::declare_root_module_statics!{TypeOfSelf}` + /// ](../macro.declare_root_module_statics.html). /// Passing `Self` instead of `TypeOfSelf` won't work. /// fn root_module_statics()->&'static RootModuleStatics; diff --git a/abi_stable/src/sabi_types/version.rs b/abi_stable/src/sabi_types/version.rs index 56c6707d..9ef91722 100644 --- a/abi_stable/src/sabi_types/version.rs +++ b/abi_stable/src/sabi_types/version.rs @@ -93,7 +93,7 @@ impl VersionStrings { /// "major.minor.patch" format,where each one is a valid number. /// /// This does not check whether the string is correctly formatted, - /// that check is done inside `VersionStrings::parsed`/`VersionNumber::new`. + /// that check is done inside `VersionStrings::parsed`. /// /// # Example /// From 31f32554bd6b196ae1439da22e0ea8c3956e2ba6 Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Sun, 3 Oct 2021 19:30:40 -0300 Subject: [PATCH 02/32] Formatted all crates. --- abi_stable/build.rs | 3 +- abi_stable/rustfmt.toml | 2 - abi_stable/src/abi_stability.rs | 10 +- abi_stable/src/abi_stability/abi_checking.rs | 1095 ++++++------ .../src/abi_stability/abi_checking/errors.rs | 139 +- .../src/abi_stability/const_generics.rs | 115 +- abi_stable/src/abi_stability/extra_checks.rs | 349 ++-- .../abi_stability/get_static_equivalent.rs | 31 +- .../src/abi_stability/stable_abi_trait.rs | 457 +++-- abi_stable/src/const_utils.rs | 120 +- abi_stable/src/derive_macro_reexports.rs | 132 +- abi_stable/src/docs.rs | 8 +- abi_stable/src/docs/library_evolution.rs | 18 +- abi_stable/src/docs/prefix_types.rs | 80 +- abi_stable/src/docs/sabi_nonexhaustive.rs | 66 +- abi_stable/src/docs/sabi_trait_inherent.rs | 28 +- abi_stable/src/docs/troubleshooting.rs | 6 +- abi_stable/src/docs/unsafe_code_guidelines.rs | 4 +- abi_stable/src/erased_types.rs | 26 +- abi_stable/src/erased_types/c_functions.rs | 230 ++- abi_stable/src/erased_types/dyn_trait.rs | 1524 ++++++++--------- .../src/erased_types/dyn_trait/tests.rs | 897 +++++----- .../src/erased_types/enabled_traits_macro.rs | 6 +- abi_stable/src/erased_types/interfaces.rs | 55 +- abi_stable/src/erased_types/iterator.rs | 181 +- abi_stable/src/erased_types/trait_objects.rs | 110 +- abi_stable/src/erased_types/traits.rs | 209 +-- abi_stable/src/erased_types/type_info.rs | 21 +- abi_stable/src/erased_types/vtable.rs | 152 +- abi_stable/src/external_types.rs | 15 +- .../src/external_types/crossbeam_channel.rs | 598 +++---- .../crossbeam_channel/errors.rs | 164 +- .../crossbeam_channel/extern_fns.rs | 122 +- .../crossbeam_channel/iteration.rs | 4 +- .../external_types/crossbeam_channel/tests.rs | 262 ++- abi_stable/src/external_types/parking_lot.rs | 45 +- .../src/external_types/parking_lot/mutex.rs | 404 ++--- .../src/external_types/parking_lot/once.rs | 538 +++--- .../src/external_types/parking_lot/rw_lock.rs | 619 ++++--- abi_stable/src/external_types/serde_json.rs | 327 ++-- abi_stable/src/for_examples.rs | 30 +- abi_stable/src/impls.rs | 3 +- abi_stable/src/inline_storage.rs | 104 +- abi_stable/src/internal_macros.rs | 9 +- abi_stable/src/lib.rs | 115 +- abi_stable/src/library.rs | 115 +- abi_stable/src/library/c_abi_testing.rs | 181 +- .../c_abi_testing/c_abi_testing_macros.rs | 2 +- .../src/library/c_abi_testing/functions.rs | 157 +- abi_stable/src/library/c_abi_testing/types.rs | 5 +- abi_stable/src/library/development_utils.rs | 26 +- abi_stable/src/library/errors.rs | 129 +- abi_stable/src/library/lib_header.rs | 291 ++-- abi_stable/src/library/raw_library.rs | 58 +- abi_stable/src/library/root_mod_trait.rs | 268 ++- abi_stable/src/macros.rs | 229 ++- abi_stable/src/macros/internal.rs | 29 +- abi_stable/src/marker_type.rs | 115 +- .../src/marker_type/stable_abi_impls.rs | 27 +- abi_stable/src/misc_tests.rs | 1 - .../src/misc_tests/impl_interfacetype_attr.rs | 470 +++-- .../misc_tests/impl_interfacetype_macro.rs | 218 ++- abi_stable/src/multikey_map.rs | 775 ++++----- abi_stable/src/nonexhaustive_enum.rs | 65 +- .../src/nonexhaustive_enum/alt_c_functions.rs | 51 +- .../src/nonexhaustive_enum/doc_enums.rs | 81 +- abi_stable/src/nonexhaustive_enum/examples.rs | 320 ++-- .../src/nonexhaustive_enum/nonexhaustive.rs | 764 ++++----- .../nonexhaustive_enum/nonexhaustive/tests.rs | 387 ++--- abi_stable/src/nonexhaustive_enum/traits.rs | 184 +- abi_stable/src/nonexhaustive_enum/vtable.rs | 229 ++- abi_stable/src/pointer_trait.rs | 348 ++-- abi_stable/src/prefix_type.rs | 136 +- .../src/prefix_type/accessible_fields.rs | 370 ++-- abi_stable/src/prefix_type/layout.rs | 29 +- abi_stable/src/prefix_type/prefix_ref.rs | 247 ++- abi_stable/src/prefix_type/pt_metadata.rs | 193 +-- abi_stable/src/prefix_type/tests.rs | 76 +- abi_stable/src/reflection.rs | 19 +- abi_stable/src/reflection/export_module.rs | 238 ++- abi_stable/src/sabi_trait.rs | 63 +- abi_stable/src/sabi_trait/doc_examples.rs | 34 +- abi_stable/src/sabi_trait/examples.rs | 427 +++-- abi_stable/src/sabi_trait/robject.rs | 527 +++--- abi_stable/src/sabi_trait/test_supertraits.rs | 833 ++++----- abi_stable/src/sabi_trait/tests.rs | 214 +-- abi_stable/src/sabi_trait/vtable.rs | 281 ++- abi_stable/src/sabi_types.rs | 24 +- abi_stable/src/sabi_types/constructor.rs | 66 +- abi_stable/src/sabi_types/ignored_wrapper.rs | 68 +- abi_stable/src/sabi_types/late_static_ref.rs | 189 +- abi_stable/src/sabi_types/maybe_cmp.rs | 66 +- abi_stable/src/sabi_types/move_ptr.rs | 247 ++- abi_stable/src/sabi_types/nul_str.rs | 93 +- abi_stable/src/sabi_types/rmut.rs | 400 ++--- abi_stable/src/sabi_types/rref.rs | 205 +-- abi_stable/src/sabi_types/rsmallbox.rs | 491 +++--- abi_stable/src/sabi_types/rsmallbox/tests.rs | 103 +- abi_stable/src/sabi_types/static_ref.rs | 103 +- abi_stable/src/sabi_types/version.rs | 62 +- abi_stable/src/std_types.rs | 22 +- abi_stable/src/std_types/arc.rs | 232 ++- abi_stable/src/std_types/arc/test.rs | 83 +- abi_stable/src/std_types/boxed.rs | 224 ++- abi_stable/src/std_types/boxed/test.rs | 62 +- abi_stable/src/std_types/cmp_ordering.rs | 7 +- abi_stable/src/std_types/cow.rs | 265 ++- abi_stable/src/std_types/cow/tests.rs | 178 +- abi_stable/src/std_types/map.rs | 684 ++++---- abi_stable/src/std_types/map/entry.rs | 537 +++--- abi_stable/src/std_types/map/extern_fns.rs | 192 ++- .../src/std_types/map/iterator_stuff.rs | 76 +- abi_stable/src/std_types/map/map_key.rs | 85 +- abi_stable/src/std_types/map/map_query.rs | 59 +- abi_stable/src/std_types/map/test.rs | 673 ++++---- abi_stable/src/std_types/option.rs | 150 +- abi_stable/src/std_types/range.rs | 39 +- abi_stable/src/std_types/result.rs | 125 +- abi_stable/src/std_types/slice_mut.rs | 170 +- abi_stable/src/std_types/slices.rs | 162 +- abi_stable/src/std_types/std_error.rs | 313 ++-- abi_stable/src/std_types/std_error/test.rs | 124 +- abi_stable/src/std_types/std_io.rs | 195 +-- abi_stable/src/std_types/str.rs | 25 +- abi_stable/src/std_types/string.rs | 216 ++- abi_stable/src/std_types/string/iters.rs | 2 +- abi_stable/src/std_types/string/tests.rs | 295 ++-- abi_stable/src/std_types/time.rs | 65 +- abi_stable/src/std_types/tuple.rs | 62 +- abi_stable/src/std_types/utypeid.rs | 17 +- abi_stable/src/std_types/vec.rs | 249 ++- abi_stable/src/std_types/vec/iters.rs | 41 +- abi_stable/src/std_types/vec/tests.rs | 132 +- abi_stable/src/test_utils.rs | 78 +- abi_stable/src/traits.rs | 48 +- abi_stable/src/type_layout.rs | 434 ++--- abi_stable/src/type_layout/construction.rs | 88 +- abi_stable/src/type_layout/data_structures.rs | 49 +- abi_stable/src/type_layout/iterators.rs | 43 +- abi_stable/src/type_layout/printing.rs | 308 ++-- abi_stable/src/type_layout/printing/tests.rs | 110 +- abi_stable/src/type_layout/shared_vars.rs | 71 +- abi_stable/src/type_layout/small_types.rs | 182 +- abi_stable/src/type_layout/tagging.rs | 875 +++++----- abi_stable/src/type_layout/tagging/test.rs | 202 +-- abi_stable/src/type_layout/tl_data.rs | 223 +-- abi_stable/src/type_layout/tl_enums.rs | 413 ++--- abi_stable/src/type_layout/tl_field.rs | 232 ++- abi_stable/src/type_layout/tl_fields.rs | 204 +-- abi_stable/src/type_layout/tl_functions.rs | 428 +++-- abi_stable/src/type_layout/tl_lifetimes.rs | 88 +- abi_stable/src/type_layout/tl_multi_tl.rs | 110 +- abi_stable/src/type_layout/tl_other.rs | 140 +- abi_stable/src/type_layout/tl_prefix.rs | 65 +- abi_stable/src/type_layout/tl_reflection.rs | 46 +- abi_stable/src/type_level.rs | 103 +- abi_stable/src/type_level/downcasting.rs | 65 +- abi_stable/src/utils.rs | 255 ++- abi_stable/tests/layout_tests/const_params.rs | 164 +- .../const_params/with_const_generics.rs | 21 +- abi_stable/tests/layout_tests/erased_types.rs | 85 +- .../layout_tests/extra_checks_combined.rs | 520 +++--- .../layout_tests/get_static_equivalent.rs | 170 +- .../tests/layout_tests/get_type_layout.rs | 339 ++-- .../layout_tests/lifetime_indices_tests.rs | 564 +++--- .../tests/layout_tests/nonexhaustive_enums.rs | 294 ++-- .../tests/layout_tests/pointer_types.rs | 20 +- abi_stable/tests/layout_tests/prefix_types.rs | 972 +++++------ .../tests/layout_tests/repr_and_discr.rs | 107 +- abi_stable/tests/layout_tests/sabi_trait.rs | 199 +-- abi_stable/tests/layout_tests/shared_types.rs | 29 +- .../layout_tests/stable_abi_attributes.rs | 148 +- abi_stable/tests/layout_tests/value.rs | 276 ++- abi_stable/tests/layout_tests_modules.rs | 34 +- abi_stable_derive/src/arenas.rs | 1 - abi_stable_derive/src/attribute_parsing.rs | 15 +- abi_stable_derive/src/common_tokens.rs | 31 +- .../src/composite_collections.rs | 221 ++- abi_stable_derive/src/concat_and_ranges.rs | 12 +- abi_stable_derive/src/constants.rs | 1 + .../src/export_root_module_impl.rs | 87 +- abi_stable_derive/src/fn_pointer_extractor.rs | 327 ++-- .../src/get_static_equivalent.rs | 119 +- .../attribute_parsing.rs | 63 +- abi_stable_derive/src/ignored_wrapper.rs | 66 +- abi_stable_derive/src/impl_interfacetype.rs | 136 +- .../impl_interfacetype/attribute_parsing.rs | 108 +- .../src/impl_interfacetype/macro_impl.rs | 105 +- .../src/input_code_range_tests.rs | 1 + abi_stable_derive/src/lib.rs | 76 +- abi_stable_derive/src/lifetimes.rs | 14 +- .../src/lifetimes/lifetime_counters.rs | 85 +- .../src/literals_constructors.rs | 30 +- abi_stable_derive/src/my_visibility.rs | 38 +- abi_stable_derive/src/parse_utils.rs | 68 +- abi_stable_derive/src/sabi_extern_fn_impl.rs | 107 +- abi_stable_derive/src/sabi_trait.rs | 1037 ++++++----- .../src/sabi_trait/attribute_parsing.rs | 263 ++- .../src/sabi_trait/common_tokens.rs | 11 +- .../src/sabi_trait/impl_delegations.rs | 214 +-- .../src/sabi_trait/lifetime_unelider.rs | 176 +- .../src/sabi_trait/method_where_clause.rs | 67 +- .../src/sabi_trait/methods_tokenizer.rs | 281 +-- .../src/sabi_trait/replace_self_path.rs | 87 +- abi_stable_derive/src/sabi_trait/tests.rs | 20 +- .../src/sabi_trait/trait_definition.rs | 887 +++++----- abi_stable_derive/src/set_span_visitor.rs | 32 +- abi_stable_derive/src/stable_abi.rs | 585 +++---- .../src/stable_abi/attribute_parsing.rs | 1167 ++++++------- .../src/stable_abi/common_tokens.rs | 9 +- .../src/stable_abi/generic_params.rs | 109 +- .../src/stable_abi/nonexhaustive.rs | 587 +++---- .../src/stable_abi/prefix_types.rs | 544 +++--- .../src/stable_abi/reflection.rs | 43 +- .../src/stable_abi/repr_attrs.rs | 390 ++--- .../src/stable_abi/shared_vars.rs | 325 ++-- abi_stable_derive/src/stable_abi/tests.rs | 51 +- abi_stable_derive/src/stable_abi/tl_field.rs | 76 +- .../src/stable_abi/tl_function.rs | 281 ++- .../src/stable_abi/tl_multi_tl.rs | 65 +- abi_stable_derive/src/utils.rs | 29 +- abi_stable_derive/src/workaround.rs | 77 +- abi_stable_shared/src/const_utils.rs | 7 +- abi_stable_shared/src/lib.rs | 92 +- abi_stable_shared/src/test_utils.rs | 3 +- .../src/type_layout/small_types.rs | 59 +- .../type_layout/tl_field_accessor_macro.rs | 10 +- .../src/type_layout/tl_field_macro.rs | 12 +- .../src/type_layout/tl_lifetimes_macro.rs | 18 +- .../src/type_layout/tl_multi_tl_macro.rs | 13 +- .../src/type_layout/tl_type_layout_index.rs | 14 +- as_derive_utils/src/attribute_parsing.rs | 11 +- as_derive_utils/src/datastructure.rs | 150 +- .../src/datastructure/field_map.rs | 145 +- .../src/datastructure/type_param_map.rs | 177 +- as_derive_utils/src/gen_params_in.rs | 184 +- as_derive_utils/src/lib.rs | 8 +- as_derive_utils/src/test_framework.rs | 255 ++- .../src/test_framework/regex_wrapper.rs | 13 +- .../src/test_framework/text_replacement.rs | 49 +- .../src/test_framework/vec_from_map.rs | 35 +- as_derive_utils/src/to_token_fn.rs | 4 +- as_derive_utils/src/utils.rs | 208 ++- .../impl/src/lib.rs | 286 ++-- .../interface/src/lib.rs | 191 +-- .../user/src/main.rs | 227 ++- .../user/src/tests.rs | 49 +- .../1_trait_objects/application/src/app.rs | 220 ++- .../1_trait_objects/application/src/main.rs | 287 ++-- .../application/src/vec_from_map.rs | 27 +- .../1_trait_objects/interface/src/commands.rs | 113 +- .../1_trait_objects/interface/src/error.rs | 112 +- examples/1_trait_objects/interface/src/lib.rs | 189 +- .../1_trait_objects/interface/src/utils.rs | 124 +- .../interface/src/vec_from_map.rs | 27 +- .../interface/src/which_plugin.rs | 213 +-- examples/1_trait_objects/plugin_0/src/lib.rs | 125 +- examples/1_trait_objects/plugin_1/src/lib.rs | 133 +- .../2_nonexhaustive/implementation/src/lib.rs | 294 ++-- examples/2_nonexhaustive/interface/src/lib.rs | 437 +++-- examples/2_nonexhaustive/user/src/main.rs | 46 +- playground/src/main.rs | 6 +- testing/0/impl_0/src/lib.rs | 36 +- testing/0/interface_0/src/lib.rs | 61 +- testing/0/user_0/src/main.rs | 77 +- testing/1 - loading errors/impl_1/src/lib.rs | 24 +- .../1 - loading errors/interface_1/src/lib.rs | 53 +- .../non_abi_stable_lib/src/lib.rs | 2 +- testing/1 - loading errors/user_1/src/main.rs | 50 +- .../version_compatibility/impl_0/src/lib.rs | 17 +- .../interface/src/lib.rs | 44 +- .../version_compatibility/user_0/src/main.rs | 73 +- tools/sabi_extract/src/main.rs | 103 +- 273 files changed, 22957 insertions(+), 26605 deletions(-) delete mode 100644 abi_stable/rustfmt.toml diff --git a/abi_stable/build.rs b/abi_stable/build.rs index dc843877..4aa183af 100644 --- a/abi_stable/build.rs +++ b/abi_stable/build.rs @@ -4,6 +4,5 @@ fn main() { println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=../readme.md"); - let channel=rustc_version::version_meta().unwrap().channel; - + let channel = rustc_version::version_meta().unwrap().channel; } diff --git a/abi_stable/rustfmt.toml b/abi_stable/rustfmt.toml deleted file mode 100644 index 5b6bfe5c..00000000 --- a/abi_stable/rustfmt.toml +++ /dev/null @@ -1,2 +0,0 @@ -imports_layout="Vertical" -merge_imports=true \ No newline at end of file diff --git a/abi_stable/src/abi_stability.rs b/abi_stable/src/abi_stability.rs index 340514bb..166ac54b 100644 --- a/abi_stable/src/abi_stability.rs +++ b/abi_stable/src/abi_stability.rs @@ -11,12 +11,10 @@ pub mod stable_abi_trait; pub use self::{ abi_checking::exported_check_layout_compatibility as check_layout_compatibility, - const_generics::{ConstGeneric,ConstGenericVTableFor}, - get_static_equivalent::{GetStaticEquivalent_,GetStaticEquivalent}, - stable_abi_trait::{StableAbi,PrefixStableAbi,AbiConsts,TypeLayoutCtor,GetTypeLayoutCtor}, + const_generics::{ConstGeneric, ConstGenericVTableFor}, + get_static_equivalent::{GetStaticEquivalent, GetStaticEquivalent_}, + stable_abi_trait::{AbiConsts, GetTypeLayoutCtor, PrefixStableAbi, StableAbi, TypeLayoutCtor}, }; #[doc(no_inline)] -pub use self::{ - extra_checks::{TypeChecker,ExtraChecks}, -}; +pub use self::extra_checks::{ExtraChecks, TypeChecker}; diff --git a/abi_stable/src/abi_stability/abi_checking.rs b/abi_stable/src/abi_stability/abi_checking.rs index 2a814f16..27366e33 100644 --- a/abi_stable/src/abi_stability/abi_checking.rs +++ b/abi_stable/src/abi_stability/abi_checking.rs @@ -2,105 +2,84 @@ Functions and types related to the layout checking. */ -use std::{cmp::Ordering, fmt,mem}; +use std::{cmp::Ordering, fmt, mem}; #[allow(unused_imports)] -use core_extensions::{ - matches, - SelfOps, -}; +use core_extensions::{matches, SelfOps}; use std::{ borrow::Borrow, cell::Cell, - collections::hash_map::{HashMap,Entry}, + collections::hash_map::{Entry, HashMap}, }; use crate::{ abi_stability::{ extra_checks::{ - ExtraChecksBox,ExtraChecksRef, - TypeChecker,TypeCheckerMut, - ExtraChecksError, + ExtraChecksBox, ExtraChecksError, ExtraChecksRef, TypeChecker, TypeCheckerMut, }, ConstGeneric, }, - sabi_types::{ParseVersionError, VersionStrings}, - prefix_type::{FieldAccessibility,FieldConditionality}, - sabi_types::CmpIgnored, - std_types::{ - RArc,RBox,RStr,RVec,UTypeId,RBoxError,RResult, - RSome,RNone,ROk,RErr, - }, + prefix_type::{FieldAccessibility, FieldConditionality}, + sabi_types::{CmpIgnored, ParseVersionError, VersionStrings}, + std_types::{RArc, RBox, RBoxError, RErr, RNone, ROk, RResult, RSome, RStr, RVec, UTypeId}, traits::IntoReprC, type_layout::{ - TypeLayout, TLData, TLDataDiscriminant, TLField, - FmtFullType, ReprAttr, TLDiscriminant,TLPrimitive, - TLEnum,IsExhaustive,IncompatibleWithNonExhaustive,TLNonExhaustive, - TLFieldOrFunction, TLFunction, - tagging::TagErrors, + tagging::TagErrors, FmtFullType, IncompatibleWithNonExhaustive, IsExhaustive, ReprAttr, + TLData, TLDataDiscriminant, TLDiscriminant, TLEnum, TLField, TLFieldOrFunction, TLFunction, + TLNonExhaustive, TLPrimitive, TypeLayout, }, type_level::downcasting::TD_Opaque, - utils::{max_by,min_max_by}, + utils::{max_by, min_max_by}, }; - mod errors; pub use self::errors::{ - AbiInstability, - AbiInstability as AI, + AbiInstability, AbiInstability as AI, AbiInstabilityError, AbiInstabilityErrors, ExtraCheckError, - AbiInstabilityErrors, - AbiInstabilityError, }; - //////////////////////////////////////////////////////////////////////////////// - /// What is AbiChecker::check_fields being called with. -#[derive(Debug,Copy,Clone, PartialEq,Eq,Ord,PartialOrd,Hash)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)] #[repr(C)] -enum FieldContext{ +enum FieldContext { Fields, Subfields, PhantomFields, } - ////// - -#[derive(Debug,Copy,Clone,PartialEq,Eq,Ord,PartialOrd,Hash)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)] #[repr(C)] -struct CheckingUTypeId{ - type_id:UTypeId, +struct CheckingUTypeId { + type_id: UTypeId, } -impl CheckingUTypeId{ - fn new(this: &'static TypeLayout)->Self{ - Self{ - type_id:this.get_utypeid(), +impl CheckingUTypeId { + fn new(this: &'static TypeLayout) -> Self { + Self { + type_id: this.get_utypeid(), } } } - ////// -#[derive(Debug, PartialEq,Eq,Ord,PartialOrd,Hash)] -pub enum CheckingState{ - Checking{layer:u32}, +#[derive(Debug, PartialEq, Eq, Ord, PartialOrd, Hash)] +pub enum CheckingState { + Checking { layer: u32 }, Compatible, Error, } - ////// /// Represents an error where a value was expected,but another value was found. -#[derive(Debug, PartialEq,Clone)] +#[derive(Debug, PartialEq, Clone)] #[repr(C)] pub struct ExpectedFound { pub expected: T, @@ -152,44 +131,38 @@ impl ExpectedFound { /////////////////////////////////////////////// - - #[derive(Debug)] #[repr(C)] -pub struct CheckedPrefixTypes{ - this:&'static TypeLayout, - this_prefix:__PrefixTypeMetadata, - other:&'static TypeLayout, - other_prefix:__PrefixTypeMetadata, +pub struct CheckedPrefixTypes { + this: &'static TypeLayout, + this_prefix: __PrefixTypeMetadata, + other: &'static TypeLayout, + other_prefix: __PrefixTypeMetadata, } - -#[derive(Debug,Copy,Clone)] +#[derive(Debug, Copy, Clone)] #[repr(C)] -pub struct NonExhaustiveEnumWithContext{ - layout:&'static TypeLayout, - enum_:TLEnum, - nonexhaustive:&'static TLNonExhaustive, +pub struct NonExhaustiveEnumWithContext { + layout: &'static TypeLayout, + enum_: TLEnum, + nonexhaustive: &'static TLNonExhaustive, } - -#[derive(Debug,Clone)] +#[derive(Debug, Clone)] #[repr(C)] -pub struct ExtraChecksBoxWithContext{ - t_lay:&'static TypeLayout, - o_lay:&'static TypeLayout, - extra_checks:ExtraChecksBox, +pub struct ExtraChecksBoxWithContext { + t_lay: &'static TypeLayout, + o_lay: &'static TypeLayout, + extra_checks: ExtraChecksBox, } - -#[derive(Debug,Copy,Clone)] +#[derive(Debug, Copy, Clone)] #[repr(C)] -pub struct CheckedNonExhaustiveEnums{ - this:NonExhaustiveEnumWithContext, - other:NonExhaustiveEnumWithContext, +pub struct CheckedNonExhaustiveEnums { + this: NonExhaustiveEnumWithContext, + other: NonExhaustiveEnumWithContext, } - /////////////////////////////////////////////// struct AbiChecker { @@ -198,22 +171,22 @@ struct AbiChecker { checked_nonexhaustive_enums: RVec, checked_extra_checks: RVec, - visited: HashMap<(CheckingUTypeId,CheckingUTypeId),CheckingState>, + visited: HashMap<(CheckingUTypeId, CheckingUTypeId), CheckingState>, errors: RVec, /// Layer 0 is checking a type layout, /// - /// Layer 1 is checking the type layout + /// Layer 1 is checking the type layout /// of a const parameter/ExtraCheck, /// - /// Layer 2 is checking the type layout - /// of a const parameter/ExtraCheck + /// Layer 2 is checking the type layout + /// of a const parameter/ExtraCheck /// of a const parameter/ExtraCheck, /// - /// It is an error to attempt to check the layout of types that are + /// It is an error to attempt to check the layout of types that are /// in the middle of being checked in outer layers. - current_layer:u32, + current_layer: u32, error_index: usize, } @@ -224,9 +197,9 @@ impl AbiChecker { fn new() -> Self { Self { stack_trace: RVec::new(), - checked_prefix_types:RVec::new(), - checked_nonexhaustive_enums:RVec::new(), - checked_extra_checks:RVec::new(), + checked_prefix_types: RVec::new(), + checked_nonexhaustive_enums: RVec::new(), + checked_extra_checks: RVec::new(), visited: HashMap::default(), errors: RVec::new(), @@ -236,29 +209,28 @@ impl AbiChecker { } #[inline] - fn check_fields( + fn check_fields( &mut self, errs: &mut RVec, t_lay: &'static TypeLayout, o_lay: &'static TypeLayout, - ctx:FieldContext, + ctx: FieldContext, t_fields: I, o_fields: I, - ) - where - I:ExactSizeIterator, - F:Borrow, + ) where + I: ExactSizeIterator, + F: Borrow, { - if t_fields.len()==0&&o_fields.len()==0 { + if t_fields.len() == 0 && o_fields.len() == 0 { return; } - - let t_data=t_lay.data(); - let is_prefix= match &t_data { - TLData::PrefixType{..}=>true, - TLData::Enum(enum_)=>!enum_.exhaustiveness.is_exhaustive(), - _=>false, + let t_data = t_lay.data(); + + let is_prefix = match &t_data { + TLData::PrefixType { .. } => true, + TLData::Enum(enum_) => !enum_.exhaustiveness.is_exhaustive(), + _ => false, }; match (t_fields.len().cmp(&o_fields.len()), is_prefix) { (Ordering::Greater, _) | (Ordering::Less, false) => { @@ -272,56 +244,55 @@ impl AbiChecker { } (Ordering::Equal, _) | (Ordering::Less, true) => {} } - - let acc_fields:Option<(FieldAccessibility,FieldAccessibility)>= - match (&t_data,&o_lay.data()) { - (TLData::PrefixType(t_prefix), TLData::PrefixType(o_prefix))=> - Some((t_prefix.accessible_fields, o_prefix.accessible_fields)), - _=>None, - }; + let acc_fields: Option<(FieldAccessibility, FieldAccessibility)> = + match (&t_data, &o_lay.data()) { + (TLData::PrefixType(t_prefix), TLData::PrefixType(o_prefix)) => { + Some((t_prefix.accessible_fields, o_prefix.accessible_fields)) + } + _ => None, + }; - for (field_i,(this_f,other_f)) in t_fields.zip(o_fields).enumerate() { - let this_f=this_f.borrow(); - let other_f=other_f.borrow(); + for (field_i, (this_f, other_f)) in t_fields.zip(o_fields).enumerate() { + let this_f = this_f.borrow(); + let other_f = other_f.borrow(); if this_f.name() != other_f.name() { push_err(errs, this_f, other_f, |x| *x, AI::UnexpectedField); continue; } - let t_field_abi=this_f.layout(); - let o_field_abi=other_f.layout(); + let t_field_abi = this_f.layout(); + let o_field_abi = other_f.layout(); - let is_accessible=match (ctx,acc_fields) { - (FieldContext::Fields,Some((l,r))) => { - l.is_accessible(field_i)&&r.is_accessible(field_i) - }, + let is_accessible = match (ctx, acc_fields) { + (FieldContext::Fields, Some((l, r))) => { + l.is_accessible(field_i) && r.is_accessible(field_i) + } _ => true, }; if is_accessible { - if this_f.lifetime_indices() != other_f.lifetime_indices() { push_err(errs, this_f, other_f, |x| *x, AI::FieldLifetimeMismatch); } - self.stack_trace.push(ExpectedFound{ - expected:(*this_f).into(), - found:(*other_f).into(), + self.stack_trace.push(ExpectedFound { + expected: (*this_f).into(), + found: (*other_f).into(), }); - let sf_ctx=FieldContext::Subfields; + let sf_ctx = FieldContext::Subfields; - let func_ranges=this_f.function_range().iter().zip(other_f.function_range()); - for (t_func,o_func) in func_ranges { + let func_ranges = this_f.function_range().iter().zip(other_f.function_range()); + for (t_func, o_func) in func_ranges { self.error_index += 1; let errs_index = self.error_index; let mut errs_ = RVec::::new(); - let errs=&mut errs_; + let errs = &mut errs_; - self.stack_trace.push(ExpectedFound{ - expected:t_func.into(), - found:o_func.into(), + self.stack_trace.push(ExpectedFound { + expected: t_func.into(), + found: o_func.into(), }); if t_func.paramret_lifetime_indices != o_func.paramret_lifetime_indices { @@ -342,50 +313,48 @@ impl AbiChecker { stack_trace: self.stack_trace.clone(), errs: errs_, index: errs_index, - _priv:(), + _priv: (), }); } self.stack_trace.pop(); } - - let _=self.check_inner(t_field_abi, o_field_abi); + let _ = self.check_inner(t_field_abi, o_field_abi); self.stack_trace.pop(); - }else{ - self.stack_trace.push(ExpectedFound{ - expected:(*this_f).into(), - found:(*other_f).into(), + } else { + self.stack_trace.push(ExpectedFound { + expected: (*this_f).into(), + found: (*other_f).into(), }); - - let t_field_layout=&t_field_abi; - let o_field_layout=&o_field_abi; - if t_field_layout.size()!=o_field_layout.size() { + + let t_field_layout = &t_field_abi; + let o_field_layout = &o_field_abi; + if t_field_layout.size() != o_field_layout.size() { push_err(errs, t_field_layout, o_field_layout, |x| x.size(), AI::Size); } if t_field_layout.alignment() != o_field_layout.alignment() { push_err( - errs, - t_field_layout, - o_field_layout, - |x| x.alignment(), - AI::Alignment + errs, + t_field_layout, + o_field_layout, + |x| x.alignment(), + AI::Alignment, ); } self.stack_trace.pop(); } - } } fn check_inner( - &mut self, - this: &'static TypeLayout, - other: &'static TypeLayout - ) ->Result<(),()> { - let t_cuti=CheckingUTypeId::new(this ); - let o_cuti=CheckingUTypeId::new(other); - let cuti_pair=(t_cuti,o_cuti); + &mut self, + this: &'static TypeLayout, + other: &'static TypeLayout, + ) -> Result<(), ()> { + let t_cuti = CheckingUTypeId::new(this); + let o_cuti = CheckingUTypeId::new(other); + let cuti_pair = (t_cuti, o_cuti); self.error_index += 1; let errs_index = self.error_index; @@ -394,49 +363,47 @@ impl AbiChecker { let t_lay = &this; let o_lay = &other; - let start_errors=self.errors.len(); - + let start_errors = self.errors.len(); + match self.visited.entry(cuti_pair) { - Entry::Occupied(mut entry)=>{ - match entry.get_mut() { - CheckingState::Checking{layer}if self.current_layer==*layer =>{ - return Ok(()) - } - cs@CheckingState::Checking{..}=>{ - *cs=CheckingState::Error; - self.errors.push(AbiInstabilityError { - stack_trace: self.stack_trace.clone(), - errs: rvec![AbiInstability::CyclicTypeChecking{ - interface:this, - implementation:other, - }], - index: errs_index, - _priv:(), - }); - return Err(()); - } - CheckingState::Compatible=>{ - return Ok(()); - } - CheckingState::Error=>{ - return Err(()); - } + Entry::Occupied(mut entry) => match entry.get_mut() { + CheckingState::Checking { layer } if self.current_layer == *layer => return Ok(()), + cs @ CheckingState::Checking { .. } => { + *cs = CheckingState::Error; + self.errors.push(AbiInstabilityError { + stack_trace: self.stack_trace.clone(), + errs: rvec![AbiInstability::CyclicTypeChecking { + interface: this, + implementation: other, + }], + index: errs_index, + _priv: (), + }); + return Err(()); } - } - Entry::Vacant(entry)=>{ - entry.insert(CheckingState::Checking{layer:self.current_layer}); + CheckingState::Compatible => { + return Ok(()); + } + CheckingState::Error => { + return Err(()); + } + }, + Entry::Vacant(entry) => { + entry.insert(CheckingState::Checking { + layer: self.current_layer, + }); } } (|| { let errs = &mut errs_; - let top_level_errs= &mut top_level_errs_; + let top_level_errs = &mut top_level_errs_; if t_lay.name() != o_lay.name() { push_err(errs, t_lay, o_lay, |x| x.full_type(), AI::Name); return; } - let (t_package,t_ver_str)=t_lay.package_and_version(); - let (o_package,o_ver_str)=o_lay.package_and_version(); + let (t_package, t_ver_str) = t_lay.package_and_version(); + let (o_package, o_ver_str) = o_lay.package_and_version(); if t_package != o_package { push_err(errs, t_lay, o_lay, |x| x.package(), AI::Package); return; @@ -476,22 +443,22 @@ impl AbiChecker { { let t_gens = t_lay.generics(); let o_gens = o_lay.generics(); - - let t_consts=t_gens.const_params(); - let o_consts=o_gens.const_params(); + + let t_consts = t_gens.const_params(); + let o_consts = o_gens.const_params(); if t_gens.lifetime_count() != o_gens.lifetime_count() || t_gens.const_params().len() != o_gens.const_params().len() { push_err(errs, t_lay, o_lay, |x| x.full_type(), AI::GenericParamCount); } - let mut ty_checker=TypeCheckerMut::from_ptr(&mut *self,TD_Opaque); - for (l,r) in t_consts.iter().zip(o_consts.iter()) { - match l.is_equal(r,ty_checker.sabi_reborrow_mut()) { - Ok(false)|Err(_)=>{ + let mut ty_checker = TypeCheckerMut::from_ptr(&mut *self, TD_Opaque); + for (l, r) in t_consts.iter().zip(o_consts.iter()) { + match l.is_equal(r, ty_checker.sabi_reborrow_mut()) { + Ok(false) | Err(_) => { push_err(errs, l, r, |x| *x, AI::MismatchedConstParam); } - Ok(true)=>{} + Ok(true) => {} } } } @@ -525,55 +492,49 @@ impl AbiChecker { })); } - let t_tag=t_lay.tag().to_checkable(); - let o_tag=o_lay.tag().to_checkable(); - if let Err(tag_err)=t_tag.check_compatible(&o_tag) { - errs.push(AI::TagError{ - err:tag_err, - }); + let t_tag = t_lay.tag().to_checkable(); + let o_tag = o_lay.tag().to_checkable(); + if let Err(tag_err) = t_tag.check_compatible(&o_tag) { + errs.push(AI::TagError { err: tag_err }); } - match (t_lay.extra_checks(),o_lay.extra_checks()) { - (None,_)=>{} - (Some(_),None)=>{ + match (t_lay.extra_checks(), o_lay.extra_checks()) { + (None, _) => {} + (Some(_), None) => { errs.push(AI::NoneExtraChecks); } - (Some(t_extra_checks),Some(o_extra_checks))=>{ - let mut ty_checker=TypeCheckerMut::from_ptr(&mut *self,TD_Opaque); + (Some(t_extra_checks), Some(o_extra_checks)) => { + let mut ty_checker = TypeCheckerMut::from_ptr(&mut *self, TD_Opaque); - let res=handle_extra_checks_ret( + let res = handle_extra_checks_ret( t_extra_checks.clone(), o_extra_checks.clone(), errs, top_level_errs, - move||{ - let ty_checker_=ty_checker.sabi_reborrow_mut(); - rtry!( t_extra_checks.check_compatibility(t_lay,o_lay,ty_checker_) ); - - let ty_checker_=ty_checker.sabi_reborrow_mut(); - let opt=rtry!( - t_extra_checks.combine(o_extra_checks,ty_checker_) - ); - - opt.map(|combined|{ - ExtraChecksBoxWithContext{ - t_lay, - o_lay, - extra_checks:combined - } + move || { + let ty_checker_ = ty_checker.sabi_reborrow_mut(); + rtry!(t_extra_checks.check_compatibility(t_lay, o_lay, ty_checker_)); + + let ty_checker_ = ty_checker.sabi_reborrow_mut(); + let opt = rtry!(t_extra_checks.combine(o_extra_checks, ty_checker_)); + + opt.map(|combined| ExtraChecksBoxWithContext { + t_lay, + o_lay, + extra_checks: combined, }) .piped(ROk) - } + }, ); - if let Ok(RSome(x))=res { + if let Ok(RSome(x)) = res { self.checked_extra_checks.push(x); } } } match (t_lay.data(), o_lay.data()) { - (TLData::Opaque{..}, _) => { + (TLData::Opaque { .. }, _) => { // No checks are necessary } @@ -585,195 +546,205 @@ impl AbiChecker { })); } } - (TLData::Primitive{..}, _) => {} - + (TLData::Primitive { .. }, _) => {} + (TLData::Struct { fields: t_fields }, TLData::Struct { fields: o_fields }) => { self.check_fields( - errs, + errs, this, other, - FieldContext::Fields, - t_fields.iter(), - o_fields.iter() + FieldContext::Fields, + t_fields.iter(), + o_fields.iter(), ); } (TLData::Struct { .. }, _) => {} - + (TLData::Union { fields: t_fields }, TLData::Union { fields: o_fields }) => { self.check_fields( - errs, + errs, this, other, - FieldContext::Fields, - t_fields.iter(), - o_fields.iter() + FieldContext::Fields, + t_fields.iter(), + o_fields.iter(), ); } (TLData::Union { .. }, _) => {} - - ( TLData::Enum(t_enum),TLData::Enum(o_enum) ) => { - self.check_enum(errs,this,other,t_enum,o_enum); - let t_as_ne=t_enum.exhaustiveness.as_nonexhaustive(); - let o_as_ne=o_enum.exhaustiveness.as_nonexhaustive(); - if let (Some(this_ne),Some(other_ne))=(t_as_ne,o_as_ne) { - self.checked_nonexhaustive_enums.push(CheckedNonExhaustiveEnums{ - this:NonExhaustiveEnumWithContext{ - layout:this, - enum_:t_enum, - nonexhaustive:this_ne, - }, - other:NonExhaustiveEnumWithContext{ - layout:other, - enum_:o_enum, - nonexhaustive:other_ne, - }, - }); + + (TLData::Enum(t_enum), TLData::Enum(o_enum)) => { + self.check_enum(errs, this, other, t_enum, o_enum); + let t_as_ne = t_enum.exhaustiveness.as_nonexhaustive(); + let o_as_ne = o_enum.exhaustiveness.as_nonexhaustive(); + if let (Some(this_ne), Some(other_ne)) = (t_as_ne, o_as_ne) { + self.checked_nonexhaustive_enums + .push(CheckedNonExhaustiveEnums { + this: NonExhaustiveEnumWithContext { + layout: this, + enum_: t_enum, + nonexhaustive: this_ne, + }, + other: NonExhaustiveEnumWithContext { + layout: other, + enum_: o_enum, + nonexhaustive: other_ne, + }, + }); } } (TLData::Enum { .. }, _) => {} - - ( - TLData::PrefixType (t_prefix), - TLData::PrefixType (o_prefix), - ) => { - let this_prefix =__PrefixTypeMetadata::with_prefix_layout(t_prefix,t_lay); - let other_prefix=__PrefixTypeMetadata::with_prefix_layout(o_prefix,o_lay); - - self.check_prefix_types(errs,&this_prefix,&other_prefix); - - self.checked_prefix_types.push( - CheckedPrefixTypes{this,this_prefix,other,other_prefix} - ) + + (TLData::PrefixType(t_prefix), TLData::PrefixType(o_prefix)) => { + let this_prefix = __PrefixTypeMetadata::with_prefix_layout(t_prefix, t_lay); + let other_prefix = __PrefixTypeMetadata::with_prefix_layout(o_prefix, o_lay); + + self.check_prefix_types(errs, &this_prefix, &other_prefix); + + self.checked_prefix_types.push(CheckedPrefixTypes { + this, + this_prefix, + other, + other_prefix, + }) } - ( TLData::PrefixType {..}, _ ) => {} + (TLData::PrefixType { .. }, _) => {} } })(); self.errors.extend(top_level_errs_); - let check_st=self.visited.get_mut(&cuti_pair).unwrap(); - if errs_.is_empty() && - self.errors.len()==start_errors && - *check_st!=CheckingState::Error + let check_st = self.visited.get_mut(&cuti_pair).unwrap(); + if errs_.is_empty() + && self.errors.len() == start_errors + && *check_st != CheckingState::Error { - *check_st=CheckingState::Compatible; + *check_st = CheckingState::Compatible; Ok(()) - }else{ - *check_st=CheckingState::Error; + } else { + *check_st = CheckingState::Error; self.errors.push(AbiInstabilityError { stack_trace: self.stack_trace.clone(), errs: errs_, index: errs_index, - _priv:(), + _priv: (), }); Err(()) } } - fn check_enum( &mut self, errs: &mut RVec, - this: &'static TypeLayout,other: &'static TypeLayout, - t_enum:TLEnum,o_enum:TLEnum, - ){ - let TLEnum{ fields: t_fields,.. }=t_enum; - let TLEnum{ fields: o_fields,.. }=o_enum; + this: &'static TypeLayout, + other: &'static TypeLayout, + t_enum: TLEnum, + o_enum: TLEnum, + ) { + let TLEnum { + fields: t_fields, .. + } = t_enum; + let TLEnum { + fields: o_fields, .. + } = o_enum; let t_fcount = t_enum.field_count.as_slice(); let o_fcount = o_enum.field_count.as_slice(); - let t_exhaus=t_enum.exhaustiveness; - let o_exhaus=o_enum.exhaustiveness; + let t_exhaus = t_enum.exhaustiveness; + let o_exhaus = o_enum.exhaustiveness; - match (t_exhaus.as_nonexhaustive(),o_exhaus.as_nonexhaustive()) { - (Some(this_ne),Some(other_ne))=>{ - if let Err(e)=this_ne.check_compatible(this){ + match (t_exhaus.as_nonexhaustive(), o_exhaus.as_nonexhaustive()) { + (Some(this_ne), Some(other_ne)) => { + if let Err(e) = this_ne.check_compatible(this) { errs.push(AI::IncompatibleWithNonExhaustive(e)) } - if let Err(e)=other_ne.check_compatible(other){ + if let Err(e) = other_ne.check_compatible(other) { errs.push(AI::IncompatibleWithNonExhaustive(e)) } } - (Some(_),None)|(None,Some(_))=>{ + (Some(_), None) | (None, Some(_)) => { push_err( errs, t_enum, - o_enum, - |x| x.exhaustiveness, - AI::MismatchedExhaustiveness + o_enum, + |x| x.exhaustiveness, + AI::MismatchedExhaustiveness, ); } - (None,None)=>{} + (None, None) => {} } - if t_exhaus.is_exhaustive()&&t_fcount.len()!=o_fcount.len() || - t_exhaus.is_nonexhaustive()&&t_fcount.len() >o_fcount.len() + if t_exhaus.is_exhaustive() && t_fcount.len() != o_fcount.len() + || t_exhaus.is_nonexhaustive() && t_fcount.len() > o_fcount.len() { push_err(errs, t_fcount, o_fcount, |x| x.len(), AI::TooManyVariants); } - - if let Err(d_errs)=t_enum.discriminants.compare(&o_enum.discriminants) { + if let Err(d_errs) = t_enum.discriminants.compare(&o_enum.discriminants) { errs.extend(d_errs); } - let mut t_names=t_enum.variant_names.as_str().split(';'); - let mut o_names=o_enum.variant_names.as_str().split(';'); - let mut total_field_count=0; + let mut t_names = t_enum.variant_names.as_str().split(';'); + let mut o_names = o_enum.variant_names.as_str().split(';'); + let mut total_field_count = 0; for (t_field_count, o_field_count) in t_fcount.iter().zip(o_fcount) { let t_name = t_names.next().unwrap_or(""); let o_name = o_names.next().unwrap_or(""); - - total_field_count+=usize::from(*t_field_count); - if t_field_count!=o_field_count { + total_field_count += usize::from(*t_field_count); + + if t_field_count != o_field_count { push_err( - errs, - *t_field_count, - *o_field_count, - |x| x as usize, - AI::FieldCountMismatch + errs, + *t_field_count, + *o_field_count, + |x| x as usize, + AI::FieldCountMismatch, ); } if t_name != o_name { - push_err(errs, t_name, o_name,RStr::from_str, AI::UnexpectedVariant); + push_err(errs, t_name, o_name, RStr::from_str, AI::UnexpectedVariant); continue; } } - let min_field_count=t_fields.len().min(o_fields.len()); - if total_field_count!=min_field_count { - push_err(errs, total_field_count, min_field_count,|x|x, AI::FieldCountMismatch); + let min_field_count = t_fields.len().min(o_fields.len()); + if total_field_count != min_field_count { + push_err( + errs, + total_field_count, + min_field_count, + |x| x, + AI::FieldCountMismatch, + ); } self.check_fields( - errs, - this, - other, + errs, + this, + other, FieldContext::Fields, - t_fields.iter(), - o_fields.iter() + t_fields.iter(), + o_fields.iter(), ); } - fn check_prefix_types( &mut self, errs: &mut RVec, this: &__PrefixTypeMetadata, other: &__PrefixTypeMetadata, - ){ + ) { if this.prefix_field_count != other.prefix_field_count { push_err( errs, this, other, - |x| x.prefix_field_count , - AI::MismatchedPrefixSize + |x| x.prefix_field_count, + AI::MismatchedPrefixSize, ); } @@ -783,114 +754,115 @@ impl AbiChecker { this, other, |x| x.conditional_prefix_fields, - AI::MismatchedPrefixConditionality + AI::MismatchedPrefixConditionality, ); } - self.check_fields( errs, this.layout, other.layout, FieldContext::Fields, this.fields.iter(), - other.fields.iter() + other.fields.iter(), ); } - /// Combines the prefix types into a global map of prefix types. fn final_prefix_type_checks( &mut self, - globals:&CheckingGlobals - )->Result<(),AbiInstabilityError>{ + globals: &CheckingGlobals, + ) -> Result<(), AbiInstabilityError> { self.error_index += 1; let mut errs_ = RVec::::new(); - let errs =&mut errs_; + let errs = &mut errs_; - let mut prefix_type_map=globals.prefix_type_map.lock().unwrap(); + let mut prefix_type_map = globals.prefix_type_map.lock().unwrap(); for pair in mem::take(&mut self.checked_prefix_types) { // let t_lay=pair.this_prefix; - let errors_before=self.errors.len(); - let t_utid=pair.this .get_utypeid(); - let o_utid=pair.other.get_utypeid(); + let errors_before = self.errors.len(); + let t_utid = pair.this.get_utypeid(); + let o_utid = pair.other.get_utypeid(); // let t_fields=pair.this_prefix.fields; // let o_fields=pair.other_prefix.fields; - let t_index=prefix_type_map.get_index(&t_utid); - let mut o_index=prefix_type_map.get_index(&o_utid); + let t_index = prefix_type_map.get_index(&t_utid); + let mut o_index = prefix_type_map.get_index(&o_utid); - if t_index==o_index{ - o_index=None; + if t_index == o_index { + o_index = None; } - let (min_prefix,mut max_prefix)=pair.this_prefix.min_max(pair.other_prefix); + let (min_prefix, mut max_prefix) = pair.this_prefix.min_max(pair.other_prefix); - match (t_index,o_index) { - (None,None)=>{ + match (t_index, o_index) { + (None, None) => { max_prefix.combine_fields_from(&min_prefix); - let i=prefix_type_map - .get_or_insert(t_utid,max_prefix) + let i = prefix_type_map + .get_or_insert(t_utid, max_prefix) .into_inner() .index; - prefix_type_map.associate_key(o_utid,i); + prefix_type_map.associate_key(o_utid, i); } - (Some(im_index),None)|(None,Some(im_index))=>{ + (Some(im_index), None) | (None, Some(im_index)) => { max_prefix.combine_fields_from(&min_prefix); - let im_prefix=prefix_type_map.get_mut_with_index(im_index).unwrap(); - let im_prefix_addr=im_prefix as *const _ as usize; + let im_prefix = prefix_type_map.get_mut_with_index(im_index).unwrap(); + let im_prefix_addr = im_prefix as *const _ as usize; - let (min_prefix,max_prefix)= - min_max_by(im_prefix,&mut max_prefix,|x|x.fields.len()); + let (min_prefix, max_prefix) = + min_max_by(im_prefix, &mut max_prefix, |x| x.fields.len()); - self.check_prefix_types(errs,min_prefix,max_prefix); - if !errs.is_empty() || errors_before!=self.errors.len() { break; } + self.check_prefix_types(errs, min_prefix, max_prefix); + if !errs.is_empty() || errors_before != self.errors.len() { + break; + } max_prefix.combine_fields_from(&*min_prefix); - + if im_prefix_addr != (max_prefix as *mut _ as usize) { - mem::swap(min_prefix,max_prefix); + mem::swap(min_prefix, max_prefix); } - - prefix_type_map.associate_key(t_utid,im_index); - prefix_type_map.associate_key(o_utid,im_index); + prefix_type_map.associate_key(t_utid, im_index); + prefix_type_map.associate_key(o_utid, im_index); } - (Some(l_index),Some(r_index))=>{ - let (l_prefix,r_prefix)= - prefix_type_map.get2_mut_with_index(l_index,r_index); - let l_prefix=l_prefix.unwrap(); - let r_prefix=r_prefix.unwrap(); - - let (replace,with)=if l_prefix.fields.len() < r_prefix.fields.len() { - (l_index,r_index) - }else{ - (r_index,l_index) + (Some(l_index), Some(r_index)) => { + let (l_prefix, r_prefix) = + prefix_type_map.get2_mut_with_index(l_index, r_index); + let l_prefix = l_prefix.unwrap(); + let r_prefix = r_prefix.unwrap(); + + let (replace, with) = if l_prefix.fields.len() < r_prefix.fields.len() { + (l_index, r_index) + } else { + (r_index, l_index) }; - let (min_prefix,max_prefix)=min_max_by(l_prefix,r_prefix,|x|x.fields.len()); - self.check_prefix_types(errs,min_prefix,max_prefix); - if !errs.is_empty() || errors_before!=self.errors.len() { break; } + let (min_prefix, max_prefix) = + min_max_by(l_prefix, r_prefix, |x| x.fields.len()); + self.check_prefix_types(errs, min_prefix, max_prefix); + if !errs.is_empty() || errors_before != self.errors.len() { + break; + } max_prefix.combine_fields_from(&*min_prefix); - prefix_type_map.replace_with_index(replace,with); - + prefix_type_map.replace_with_index(replace, with); } } } if errs_.is_empty() { Ok(()) - }else{ + } else { Err(AbiInstabilityError { stack_trace: self.stack_trace.clone(), errs: errs_, index: self.error_index, - _priv:(), + _priv: (), }) } } @@ -898,99 +870,106 @@ impl AbiChecker { /// Combines the nonexhaustive enums into a global map of nonexhaustive enums. fn final_non_exhaustive_enum_checks( &mut self, - globals:&CheckingGlobals - )->Result<(),AbiInstabilityError>{ + globals: &CheckingGlobals, + ) -> Result<(), AbiInstabilityError> { self.error_index += 1; let mut errs_ = RVec::::new(); - let errs =&mut errs_; - - let mut nonexhaustive_map=globals.nonexhaustive_map.lock().unwrap(); + let errs = &mut errs_; + let mut nonexhaustive_map = globals.nonexhaustive_map.lock().unwrap(); for pair in mem::take(&mut self.checked_nonexhaustive_enums) { - let CheckedNonExhaustiveEnums{this,other}=pair; - let errors_before=self.errors.len(); - - let t_utid=this .layout.get_utypeid(); - let o_utid=other.layout.get_utypeid(); + let CheckedNonExhaustiveEnums { this, other } = pair; + let errors_before = self.errors.len(); + + let t_utid = this.layout.get_utypeid(); + let o_utid = other.layout.get_utypeid(); - let t_index=nonexhaustive_map.get_index(&t_utid); - let mut o_index=nonexhaustive_map.get_index(&o_utid); + let t_index = nonexhaustive_map.get_index(&t_utid); + let mut o_index = nonexhaustive_map.get_index(&o_utid); - if t_index==o_index{ - o_index=None; + if t_index == o_index { + o_index = None; } - let mut max_=max_by(this,other,|x|x.enum_.variant_count()); - - match (t_index,o_index) { - (None,None)=>{ - let i=nonexhaustive_map - .get_or_insert(t_utid,max_) + let mut max_ = max_by(this, other, |x| x.enum_.variant_count()); + + match (t_index, o_index) { + (None, None) => { + let i = nonexhaustive_map + .get_or_insert(t_utid, max_) .into_inner() .index; - - nonexhaustive_map.associate_key(o_utid,i); + + nonexhaustive_map.associate_key(o_utid, i); } - (Some(im_index),None)|(None,Some(im_index))=>{ - let im_nonexh=nonexhaustive_map.get_mut_with_index(im_index).unwrap(); - let im_nonexh_addr=im_nonexh as *const _ as usize; + (Some(im_index), None) | (None, Some(im_index)) => { + let im_nonexh = nonexhaustive_map.get_mut_with_index(im_index).unwrap(); + let im_nonexh_addr = im_nonexh as *const _ as usize; - let (min_nonexh,max_nonexh)= - min_max_by(im_nonexh,&mut max_,|x|x.enum_.variant_count()); + let (min_nonexh, max_nonexh) = + min_max_by(im_nonexh, &mut max_, |x| x.enum_.variant_count()); self.check_enum( errs, - min_nonexh.layout,max_nonexh.layout, - min_nonexh.enum_ ,max_nonexh.enum_ , + min_nonexh.layout, + max_nonexh.layout, + min_nonexh.enum_, + max_nonexh.enum_, ); - if !errs.is_empty() || errors_before!=self.errors.len() { break; } + if !errs.is_empty() || errors_before != self.errors.len() { + break; + } if im_nonexh_addr != (max_nonexh as *mut _ as usize) { - mem::swap(min_nonexh,max_nonexh); + mem::swap(min_nonexh, max_nonexh); } - nonexhaustive_map.associate_key(t_utid,im_index); - nonexhaustive_map.associate_key(o_utid,im_index); + nonexhaustive_map.associate_key(t_utid, im_index); + nonexhaustive_map.associate_key(o_utid, im_index); } - (Some(l_index),Some(r_index))=>{ - let (l_nonexh,r_nonexh)= - nonexhaustive_map.get2_mut_with_index(l_index,r_index); - let l_nonexh=l_nonexh.unwrap(); - let r_nonexh=r_nonexh.unwrap(); + (Some(l_index), Some(r_index)) => { + let (l_nonexh, r_nonexh) = + nonexhaustive_map.get2_mut_with_index(l_index, r_index); + let l_nonexh = l_nonexh.unwrap(); + let r_nonexh = r_nonexh.unwrap(); - let (replace,with)= + let (replace, with) = if l_nonexh.enum_.variant_count() < r_nonexh.enum_.variant_count() { - (l_index,r_index) - }else{ - (r_index,l_index) + (l_index, r_index) + } else { + (r_index, l_index) }; - let (min_nonexh,max_nonexh)= - min_max_by(l_nonexh,r_nonexh,|x|x.enum_.variant_count()); - + let (min_nonexh, max_nonexh) = + min_max_by(l_nonexh, r_nonexh, |x| x.enum_.variant_count()); + self.check_enum( errs, - min_nonexh.layout,max_nonexh.layout, - min_nonexh.enum_ ,max_nonexh.enum_ , + min_nonexh.layout, + max_nonexh.layout, + min_nonexh.enum_, + max_nonexh.enum_, ); - if !errs.is_empty() || errors_before!=self.errors.len() { break; } + if !errs.is_empty() || errors_before != self.errors.len() { + break; + } - nonexhaustive_map.replace_with_index(replace,with); + nonexhaustive_map.replace_with_index(replace, with); } } } if errs_.is_empty() { Ok(()) - }else{ + } else { Err(AbiInstabilityError { stack_trace: self.stack_trace.clone(), errs: errs_, index: self.error_index, - _priv:(), + _priv: (), }) } } @@ -998,95 +977,100 @@ impl AbiChecker { /// Combines the ExtraChecksBox into a global map. fn final_extra_checks( &mut self, - globals:&CheckingGlobals - )->Result<(),RVec>{ + globals: &CheckingGlobals, + ) -> Result<(), RVec> { self.error_index += 1; let mut top_level_errs_ = RVec::::new(); let mut errs_ = RVec::::new(); - let errs =&mut errs_; - let top_level_errs =&mut top_level_errs_; + let errs = &mut errs_; + let top_level_errs = &mut top_level_errs_; - let mut extra_checker_map=globals.extra_checker_map.lock().unwrap(); + let mut extra_checker_map = globals.extra_checker_map.lock().unwrap(); for with_context in mem::take(&mut self.checked_extra_checks) { - let ExtraChecksBoxWithContext{t_lay,o_lay,extra_checks}=with_context; - - let errors_before=self.errors.len(); - let type_checker=TypeCheckerMut::from_ptr(&mut *self,TD_Opaque); - let t_utid=t_lay.get_utypeid(); - let o_utid=o_lay.get_utypeid(); - - let t_index=extra_checker_map.get_index(&t_utid); - let mut o_index=extra_checker_map.get_index(&o_utid); - - if t_index==o_index{ - o_index=None; + let ExtraChecksBoxWithContext { + t_lay, + o_lay, + extra_checks, + } = with_context; + + let errors_before = self.errors.len(); + let type_checker = TypeCheckerMut::from_ptr(&mut *self, TD_Opaque); + let t_utid = t_lay.get_utypeid(); + let o_utid = o_lay.get_utypeid(); + + let t_index = extra_checker_map.get_index(&t_utid); + let mut o_index = extra_checker_map.get_index(&o_utid); + + if t_index == o_index { + o_index = None; } - match (t_index,o_index) { - (None,None)=>{ - let i=extra_checker_map - .get_or_insert(t_utid,extra_checks) + match (t_index, o_index) { + (None, None) => { + let i = extra_checker_map + .get_or_insert(t_utid, extra_checks) .into_inner() .index; - extra_checker_map.associate_key(o_utid,i); + extra_checker_map.associate_key(o_utid, i); } - (Some(im_index),None)|(None,Some(im_index))=>{ - let other_checks=extra_checker_map.get_mut_with_index(im_index).unwrap(); + (Some(im_index), None) | (None, Some(im_index)) => { + let other_checks = extra_checker_map.get_mut_with_index(im_index).unwrap(); combine_extra_checks( errs, top_level_errs, type_checker, other_checks, - &[extra_checks.sabi_reborrow()] + &[extra_checks.sabi_reborrow()], ); - if !errs.is_empty() || errors_before!=self.errors.len() { break; } - - extra_checker_map.associate_key(t_utid,im_index); - extra_checker_map.associate_key(o_utid,im_index); + if !errs.is_empty() || errors_before != self.errors.len() { + break; + } + extra_checker_map.associate_key(t_utid, im_index); + extra_checker_map.associate_key(o_utid, im_index); } - (Some(l_index),Some(r_index))=>{ - let (l_extra_checks,r_extra_checks)= - extra_checker_map.get2_mut_with_index(l_index,r_index); - let l_extra_checks=l_extra_checks.unwrap(); - let r_extra_checks=r_extra_checks.unwrap(); + (Some(l_index), Some(r_index)) => { + let (l_extra_checks, r_extra_checks) = + extra_checker_map.get2_mut_with_index(l_index, r_index); + let l_extra_checks = l_extra_checks.unwrap(); + let r_extra_checks = r_extra_checks.unwrap(); combine_extra_checks( errs, top_level_errs, type_checker, l_extra_checks, - &[ r_extra_checks.sabi_reborrow(), extra_checks.sabi_reborrow() ] + &[r_extra_checks.sabi_reborrow(), extra_checks.sabi_reborrow()], ); - if !errs.is_empty() || errors_before!=self.errors.len() { break; } - - extra_checker_map.replace_with_index(r_index,l_index); + if !errs.is_empty() || errors_before != self.errors.len() { + break; + } + extra_checker_map.replace_with_index(r_index, l_index); } } } if errs_.is_empty() { Ok(()) - }else{ + } else { top_level_errs.push(AbiInstabilityError { stack_trace: self.stack_trace.clone(), errs: errs_, index: self.error_index, - _priv:(), + _priv: (), }); Err(top_level_errs_) } } } - /** Checks that the layout of `interface` is compatible with `implementation`. @@ -1101,56 +1085,50 @@ pub fn check_layout_compatibility( interface: &'static TypeLayout, implementation: &'static TypeLayout, ) -> Result<(), AbiInstabilityErrors> { - check_layout_compatibility_with_globals( - interface, - implementation, - get_checking_globals(), - ) + check_layout_compatibility_with_globals(interface, implementation, get_checking_globals()) } - #[inline(never)] pub fn check_layout_compatibility_with_globals( interface: &'static TypeLayout, implementation: &'static TypeLayout, - globals:&CheckingGlobals, + globals: &CheckingGlobals, ) -> Result<(), AbiInstabilityErrors> { let mut errors: RVec; if interface.is_prefix_kind() || implementation.is_prefix_kind() { - let mut errs=RVec::with_capacity(1); + let mut errs = RVec::with_capacity(1); push_err( &mut errs, interface, implementation, - |x| x.data_discriminant() , - AI::TLDataDiscriminant + |x| x.data_discriminant(), + AI::TLDataDiscriminant, ); errors = vec![AbiInstabilityError { stack_trace: vec![].into(), errs, index: 0, - _priv:(), + _priv: (), }] .into(); } else { let mut checker = AbiChecker::new(); - let _=checker.check_inner(interface, implementation); + let _ = checker.check_inner(interface, implementation); if checker.errors.is_empty() { - if let Err(e)=checker.final_prefix_type_checks(globals) { + if let Err(e) = checker.final_prefix_type_checks(globals) { checker.errors.push(e); } - if let Err(e)=checker.final_non_exhaustive_enum_checks(globals) { + if let Err(e) = checker.final_non_exhaustive_enum_checks(globals) { checker.errors.push(e); } - if let Err(e)=checker.final_extra_checks(globals) { + if let Err(e) = checker.final_extra_checks(globals) { checker.errors.extend(e); } } errors = checker.errors; } - if errors.is_empty() { Ok(()) } else { @@ -1159,7 +1137,7 @@ pub fn check_layout_compatibility_with_globals( interface, implementation, errors, - _priv:() + _priv: (), }) } } @@ -1171,7 +1149,7 @@ pub(crate) extern "C" fn check_layout_compatibility_for_ffi( interface: &'static TypeLayout, implementation: &'static TypeLayout, ) -> RResult<(), RBoxError> { - extern_fn_panic_handling!{ + extern_fn_panic_handling! { let mut is_already_inside=false; INSIDE_LAYOUT_CHECKER.with(|inside|{ is_already_inside=inside.get(); @@ -1180,7 +1158,7 @@ pub(crate) extern "C" fn check_layout_compatibility_for_ffi( let _guard=LayoutCheckerGuard; if is_already_inside { - let errors = + let errors = vec![AbiInstabilityError { stack_trace: vec![].into(), errs:vec![AbiInstability::ReentrantLayoutCheckingCall].into(), @@ -1196,7 +1174,6 @@ pub(crate) extern "C" fn check_layout_compatibility_for_ffi( } } - /** Checks that the layout of `interface` is compatible with `implementation`, @@ -1219,133 +1196,121 @@ pub extern "C" fn exported_check_layout_compatibility( interface: &'static TypeLayout, implementation: &'static TypeLayout, ) -> RResult<(), RBoxError> { - extern_fn_panic_handling!{ + extern_fn_panic_handling! { (crate::globals::initialized_globals().layout_checking) (interface,implementation) } } - - -impl AbiChecker{ +impl AbiChecker { fn check_compatibility_inner( &mut self, - interface:&'static TypeLayout, - implementation:&'static TypeLayout, - )->RResult<(),()>{ - let error_count_before=self.errors.len(); + interface: &'static TypeLayout, + implementation: &'static TypeLayout, + ) -> RResult<(), ()> { + let error_count_before = self.errors.len(); + + self.current_layer += 1; - self.current_layer+=1; - - let res=self.check_inner(interface,implementation); + let res = self.check_inner(interface, implementation); - self.current_layer-=1; + self.current_layer -= 1; - if error_count_before==self.errors.len() && res.is_ok() { + if error_count_before == self.errors.len() && res.is_ok() { ROk(()) - }else{ + } else { RErr(()) } } } -unsafe impl TypeChecker for AbiChecker{ +unsafe impl TypeChecker for AbiChecker { fn check_compatibility( &mut self, - interface:&'static TypeLayout, - implementation:&'static TypeLayout, - )->RResult<(), ExtraChecksError> { - self.check_compatibility_inner(interface,implementation) - .map_err(|_| ExtraChecksError::TypeChecker ) + interface: &'static TypeLayout, + implementation: &'static TypeLayout, + ) -> RResult<(), ExtraChecksError> { + self.check_compatibility_inner(interface, implementation) + .map_err(|_| ExtraChecksError::TypeChecker) } fn local_check_compatibility( &mut self, - interface:&'static TypeLayout, - implementation:&'static TypeLayout, - )->RResult<(), ExtraChecksError> { - let error_count_before=self.errors.len(); + interface: &'static TypeLayout, + implementation: &'static TypeLayout, + ) -> RResult<(), ExtraChecksError> { + let error_count_before = self.errors.len(); dbg!(error_count_before); println!( - "interface:{} implementation:{}", + "interface:{} implementation:{}", interface.full_type(), implementation.full_type() ); - - self.check_compatibility_inner(interface,implementation) - .map_err(|_|{ + + self.check_compatibility_inner(interface, implementation) + .map_err(|_| { AbiInstabilityErrors { interface, implementation, errors: self.errors.drain(error_count_before..).collect(), - _priv:(), + _priv: (), } .piped(RBoxError::new) .piped(ExtraChecksError::TypeCheckerErrors) }) } - } - /////////////////////////////////////////////// - -thread_local!{ +thread_local! { static INSIDE_LAYOUT_CHECKER:Cell=Cell::new(false); } - struct LayoutCheckerGuard; -impl Drop for LayoutCheckerGuard{ - fn drop(&mut self){ - INSIDE_LAYOUT_CHECKER.with(|inside|{ +impl Drop for LayoutCheckerGuard { + fn drop(&mut self) { + INSIDE_LAYOUT_CHECKER.with(|inside| { inside.set(false); }); } } - /////////////////////////////////////////////// use std::sync::Mutex; use crate::{ - sabi_types::LateStaticRef, - multikey_map::MultiKeyMap, - prefix_type::__PrefixTypeMetadata, + multikey_map::MultiKeyMap, prefix_type::__PrefixTypeMetadata, sabi_types::LateStaticRef, utils::leak_value, }; #[derive(Debug)] -pub struct CheckingGlobals{ - pub prefix_type_map:Mutex>, - pub nonexhaustive_map:Mutex>, - pub extra_checker_map:Mutex>, +pub struct CheckingGlobals { + pub prefix_type_map: Mutex>, + pub nonexhaustive_map: Mutex>, + pub extra_checker_map: Mutex>, } #[allow(clippy::new_without_default)] -impl CheckingGlobals{ - pub fn new()->Self{ - CheckingGlobals{ - prefix_type_map:MultiKeyMap::new().piped(Mutex::new), - nonexhaustive_map:MultiKeyMap::new().piped(Mutex::new), - extra_checker_map:MultiKeyMap::new().piped(Mutex::new), +impl CheckingGlobals { + pub fn new() -> Self { + CheckingGlobals { + prefix_type_map: MultiKeyMap::new().piped(Mutex::new), + nonexhaustive_map: MultiKeyMap::new().piped(Mutex::new), + extra_checker_map: MultiKeyMap::new().piped(Mutex::new), } } } -static CHECKING_GLOBALS:LateStaticRef<&CheckingGlobals>=LateStaticRef::new(); +static CHECKING_GLOBALS: LateStaticRef<&CheckingGlobals> = LateStaticRef::new(); -pub fn get_checking_globals()->&'static CheckingGlobals{ - CHECKING_GLOBALS.init(||{ - CheckingGlobals::new().piped(leak_value) - }) +pub fn get_checking_globals() -> &'static CheckingGlobals { + CHECKING_GLOBALS.init(|| CheckingGlobals::new().piped(leak_value)) } - /////////////////////////////////////////////// pub(crate) fn push_err( @@ -1363,51 +1328,47 @@ pub(crate) fn push_err( errs.push(x); } - -fn handle_extra_checks_ret( - expected_extra_checks:ExtraChecksRef<'_>, - found_extra_checks:ExtraChecksRef<'_>, +fn handle_extra_checks_ret( + expected_extra_checks: ExtraChecksRef<'_>, + found_extra_checks: ExtraChecksRef<'_>, errs: &mut RVec, top_level_errs: &mut RVec, - f:F -)->Result + f: F, +) -> Result where - F:FnOnce()->RResult + F: FnOnce() -> RResult, { - let make_extra_check_error=move|e:RBoxError|->AbiInstability{ - ExtraCheckError{ + let make_extra_check_error = move |e: RBoxError| -> AbiInstability { + ExtraCheckError { err: RArc::new(e), - expected_err: ExpectedFound{ - expected:expected_extra_checks + expected_err: ExpectedFound { + expected: expected_extra_checks .piped_ref(RBoxError::from_fmt) .piped(RArc::new), - found:found_extra_checks + found: found_extra_checks .piped_ref(RBoxError::from_fmt) .piped(RArc::new), - } - }.piped(CmpIgnored::new) - .piped(AI::ExtraCheckError) + }, + } + .piped(CmpIgnored::new) + .piped(AI::ExtraCheckError) }; match f() { - ROk(x)=>{ - Ok(x) - } - RErr(ExtraChecksError::TypeChecker)=>{ - Err(()) - } - RErr(ExtraChecksError::TypeCheckerErrors(e))=>{ + ROk(x) => Ok(x), + RErr(ExtraChecksError::TypeChecker) => Err(()), + RErr(ExtraChecksError::TypeCheckerErrors(e)) => { match e.downcast::() { - Ok(e)=>top_level_errs.extend(RBox::into_inner(e).errors), - Err(e)=>errs.push(make_extra_check_error(e)), + Ok(e) => top_level_errs.extend(RBox::into_inner(e).errors), + Err(e) => errs.push(make_extra_check_error(e)), } Err(()) } - RErr(ExtraChecksError::NoneExtraChecks)=>{ + RErr(ExtraChecksError::NoneExtraChecks) => { errs.push(AI::NoneExtraChecks); Err(()) } - RErr(ExtraChecksError::ExtraChecks(e))=>{ + RErr(ExtraChecksError::ExtraChecks(e)) => { errs.push(make_extra_check_error(e)); Err(()) } @@ -1417,25 +1378,27 @@ where fn combine_extra_checks( errs: &mut RVec, top_level_errs: &mut RVec, - mut ty_checker:TypeCheckerMut<'_>, - extra_checks:&mut ExtraChecksBox, - slic:&[ExtraChecksRef<'_>] -){ + mut ty_checker: TypeCheckerMut<'_>, + extra_checks: &mut ExtraChecksBox, + slic: &[ExtraChecksRef<'_>], +) { for other in slic { - let other_ref=other.sabi_reborrow(); - let ty_checker=ty_checker.sabi_reborrow_mut(); - let opt_ret=handle_extra_checks_ret( + let other_ref = other.sabi_reborrow(); + let ty_checker = ty_checker.sabi_reborrow_mut(); + let opt_ret = handle_extra_checks_ret( extra_checks.sabi_reborrow(), other.sabi_reborrow(), errs, top_level_errs, - || extra_checks.sabi_reborrow().combine( other_ref , ty_checker ) + || extra_checks.sabi_reborrow().combine(other_ref, ty_checker), ); match opt_ret { - Ok(RSome(new))=>{ *extra_checks=new; }, - Ok(RNone)=>{}, - Err(_)=>break, + Ok(RSome(new)) => { + *extra_checks = new; + } + Ok(RNone) => {} + Err(_) => break, } } } diff --git a/abi_stable/src/abi_stability/abi_checking/errors.rs b/abi_stable/src/abi_stability/abi_checking/errors.rs index 2a417d33..dc9445b0 100644 --- a/abi_stable/src/abi_stability/abi_checking/errors.rs +++ b/abi_stable/src/abi_stability/abi_checking/errors.rs @@ -2,14 +2,13 @@ use super::*; use core_extensions::StringExt; - /// An individual error from checking the layout of some type. -#[derive(Debug, PartialEq,Clone)] +#[derive(Debug, PartialEq, Clone)] pub enum AbiInstability { ReentrantLayoutCheckingCall, - CyclicTypeChecking{ - interface:&'static TypeLayout, - implementation:&'static TypeLayout, + CyclicTypeChecking { + interface: &'static TypeLayout, + implementation: &'static TypeLayout, }, NonZeroness(ExpectedFound), Name(ExpectedFound), @@ -36,42 +35,37 @@ pub enum AbiInstability { IncompatibleWithNonExhaustive(IncompatibleWithNonExhaustive), NoneExtraChecks, ExtraCheckError(CmpIgnored), - TagError{ - err:TagErrors, + TagError { + err: TagErrors, }, } -#[derive(Debug,Clone)] -pub struct ExtraCheckError{ - pub err:RArc, - pub expected_err:ExpectedFound>, +#[derive(Debug, Clone)] +pub struct ExtraCheckError { + pub err: RArc, + pub expected_err: ExpectedFound>, } - use self::AbiInstability as AI; #[allow(dead_code)] impl AbiInstabilityErrors { #[cfg(feature = "testing")] pub fn flatten_errors(&self) -> RVec { - self.flattened_errors() - .collect::>() + self.flattened_errors().collect::>() } #[cfg(feature = "testing")] - pub fn flattened_errors<'a>(&'a self) -> impl Iterator+'a { - self.errors - .iter() - .flat_map(|x| &x.errs ) - .cloned() + pub fn flattened_errors<'a>(&'a self) -> impl Iterator + 'a { + self.errors.iter().flat_map(|x| &x.errs).cloned() } } -impl std::error::Error for AbiInstabilityErrors{} +impl std::error::Error for AbiInstabilityErrors {} impl fmt::Debug for AbiInstabilityErrors { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt::Display::fmt(self,f) + fmt::Display::fmt(self, f) } } impl fmt::Display for AbiInstabilityErrors { @@ -91,22 +85,22 @@ impl fmt::Display for AbiInstabilityErrors { impl fmt::Display for AbiInstabilityError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let mut extra_err=None::; + let mut extra_err = None::; write!(f, "{} error(s)", self.errs.len())?; if self.stack_trace.is_empty() { - writeln!(f,".")?; - }else{ - writeln!(f,"inside:\n \n")?; + writeln!(f, ".")?; + } else { + writeln!(f, "inside:\n \n")?; } for field in &self.stack_trace { writeln!(f, "{}\n", field.found.to_string().left_padder(4))?; } - if let Some(ExpectedFound{expected,found}) = self.stack_trace.last() { + if let Some(ExpectedFound { expected, found }) = self.stack_trace.last() { writeln!( - f, + f, "Layout of expected type:\n{}\n\n\ - Layout of found type:\n{}\n", + Layout of found type:\n{}\n", expected.formatted_layout().left_padder(4), found.formatted_layout().left_padder(4), )?; @@ -116,8 +110,8 @@ impl fmt::Display for AbiInstabilityError { for err in &self.errs { let pair = match err { AI::ReentrantLayoutCheckingCall => ("reentrant layout checking call", None), - AI::CyclicTypeChecking{interface,..} => { - extra_err=Some(format!("The type:\n{}",interface)); + AI::CyclicTypeChecking { interface, .. } => { + extra_err = Some(format!("The type:\n{}", interface)); ( "Attempted to check the layout of a type while checking the layout \ @@ -139,89 +133,84 @@ impl fmt::Display for AbiInstabilityError { ) } AI::PackageVersion(v) => ("incompatible package versions", v.display_str()), - AI::MismatchedPrefixSize(v) => - ( - "prefix-types have a different prefix", - v.display_str() - ), + AI::MismatchedPrefixSize(v) => { + ("prefix-types have a different prefix", v.display_str()) + } AI::Size(v) => ("incompatible type size", v.display_str()), AI::Alignment(v) => ("incompatible type alignment", v.display_str()), - AI::GenericParamCount(v) => ( - "incompatible amount of generic parameters", - v.display_str(), - ), + AI::GenericParamCount(v) => { + ("incompatible amount of generic parameters", v.display_str()) + } AI::TLDataDiscriminant(v) => ("incompatible data ", v.debug_str()), AI::MismatchedPrimitive(v) => ("incompatible primitive", v.debug_str()), AI::FieldCountMismatch(v) => ("too many fields", v.display_str()), - AI::FnLifetimeMismatch(v) => { - ("function pointers reference different lifetimes", v.display_str()) - } + AI::FnLifetimeMismatch(v) => ( + "function pointers reference different lifetimes", + v.display_str(), + ), AI::FieldLifetimeMismatch(v) => { ("field references different lifetimes", v.display_str()) } AI::UnexpectedField(v) => ("unexpected field", v.display_str()), AI::TooManyVariants(v) => ("too many variants", v.display_str()), - AI::MismatchedPrefixConditionality(v)=>( + AI::MismatchedPrefixConditionality(v) => ( "prefix fields differ in whether they are conditional", - v.debug_str() - ), - AI::MismatchedExhaustiveness(v)=>( - "enums differ in whether they are exhaustive", - v.debug_str() - ), - AI::MismatchedConstParam(v)=>( - "The cconst parameters are different", - v.debug_str() + v.debug_str(), ), + AI::MismatchedExhaustiveness(v) => { + ("enums differ in whether they are exhaustive", v.debug_str()) + } + AI::MismatchedConstParam(v) => { + ("The cconst parameters are different", v.debug_str()) + } AI::UnexpectedVariant(v) => ("unexpected variant", v.debug_str()), - AI::ReprAttr(v)=>("incompatible repr attributes",v.debug_str()), - AI::EnumDiscriminant(v)=>("different discriminants",v.debug_str()), - AI::IncompatibleWithNonExhaustive(e)=>{ - extra_err=Some(e.to_string()); + AI::ReprAttr(v) => ("incompatible repr attributes", v.debug_str()), + AI::EnumDiscriminant(v) => ("different discriminants", v.debug_str()), + AI::IncompatibleWithNonExhaustive(e) => { + extra_err = Some(e.to_string()); - ("",None) + ("", None) } - AI::NoneExtraChecks=>{ - let msg="\ + AI::NoneExtraChecks => { + let msg = "\ Interface contains a value in `extra_checks` \ while the implementation does not.\ "; (msg, None) } AI::ExtraCheckError(ec_error) => { - let ExtraCheckError{err,expected_err}=&**ec_error; - extra_err=Some((**err).to_string()); + let ExtraCheckError { err, expected_err } = &**ec_error; + extra_err = Some((**err).to_string()); ("", expected_err.display_str()) - }, - AI::TagError{err} => { - extra_err=Some(err.to_string()); + } + AI::TagError { err } => { + extra_err = Some(err.to_string()); ("", None) - }, + } }; - let (error_msg, expected_err):(&'static str, Option>)=pair; + let (error_msg, expected_err): (&'static str, Option>) = pair; - if let Some(expected_err)=expected_err{ + if let Some(expected_err) = expected_err { writeln!( f, "\nError:{}\nExpected:\n{}\nFound:\n{}", error_msg, expected_err.expected.left_padder(4), - expected_err.found .left_padder(4), + expected_err.found.left_padder(4), )?; } - if let Some(extra_err)=&extra_err { - writeln!(f,"\nExtra:\n{}\n",extra_err.left_padder(4))?; + if let Some(extra_err) = &extra_err { + writeln!(f, "\nExtra:\n{}\n", extra_err.left_padder(4))?; } } Ok(()) } } - /// All the errors from checking the layout of every nested type in TypeLayout. #[derive(Clone, PartialEq)] #[repr(C)] @@ -229,20 +218,18 @@ pub struct AbiInstabilityErrors { pub interface: &'static TypeLayout, pub implementation: &'static TypeLayout, pub errors: RVec, - pub(super) _priv:(), + pub(super) _priv: (), } /// All the shallow errors from checking an individual type. /// /// Error that happen lower or higher on the stack are stored in separate /// `AbiInstabilityError`s. -#[derive(Debug,Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq)] #[repr(C)] pub struct AbiInstabilityError { pub stack_trace: RVec>, pub errs: RVec, pub index: usize, - pub(super) _priv:(), + pub(super) _priv: (), } - - diff --git a/abi_stable/src/abi_stability/const_generics.rs b/abi_stable/src/abi_stability/const_generics.rs index 4954519b..e9a66c29 100644 --- a/abi_stable/src/abi_stability/const_generics.rs +++ b/abi_stable/src/abi_stability/const_generics.rs @@ -2,49 +2,47 @@ use crate::{ abi_stability::{ - extra_checks::{ExtraChecksError,TypeCheckerMut}, check_layout_compatibility, + extra_checks::{ExtraChecksError, TypeCheckerMut}, }, erased_types::{ - c_functions::{adapt_std_fmt,debug_impl,partial_eq_impl}, + c_functions::{adapt_std_fmt, debug_impl, partial_eq_impl}, FormattingMode, }, marker_type::ErasedObject, - prefix_type::{PrefixTypeTrait,WithMetadata}, + prefix_type::{PrefixTypeTrait, WithMetadata}, sabi_types::RRef, - std_types::{RString,RResult,ROk,RErr}, + std_types::{RErr, ROk, RResult, RString}, type_layout::TypeLayout, StableAbi, }; use std::{ - cmp::{Eq,PartialEq}, - fmt::{self,Debug}, + cmp::{Eq, PartialEq}, + fmt::{self, Debug}, marker::PhantomData, }; - /////////////////////////////////////////////////////////////////////////////// - /// A trait object used to check equality between const generic parameters. #[repr(C)] -#[derive(Copy,Clone,StableAbi)] -pub struct ConstGeneric{ +#[derive(Copy, Clone, StableAbi)] +pub struct ConstGeneric { ptr: RRef<'static, ErasedObject>, vtable: ConstGenericVTable_Ref, } -unsafe impl Send for ConstGeneric{} -unsafe impl Sync for ConstGeneric{} +unsafe impl Send for ConstGeneric {} +unsafe impl Sync for ConstGeneric {} -impl ConstGeneric{ +impl ConstGeneric { /// Constructs a ConstGeneric from a reference and a vtable. - /// + /// /// To construct the `vtable_for` parameter use `ConstGenericVTableFor::NEW`. - pub const fn new(this:&'static T, vtable_for:ConstGenericVTableFor)->Self{ - Self{ - ptr: unsafe{ RRef::from_raw(this as *const T as *const ErasedObject) }, + pub const fn new(this: &'static T, vtable_for: ConstGenericVTableFor) -> Self { + Self { + ptr: unsafe { RRef::from_raw(this as *const T as *const ErasedObject) }, vtable: vtable_for.vtable, } } @@ -54,10 +52,10 @@ impl ConstGeneric{ /// # Safety /// /// `this` must point to an object that lives for the `'static` lifetime, - /// and `vtable` must be a `ConstGenericVTableFor::::NEW` + /// and `vtable` must be a `ConstGenericVTableFor::::NEW` /// (where `T` is the unerased type of `this`) - pub const unsafe fn from_erased(this: *const (), vtable: ConstGenericVTable_Ref)->Self{ - Self{ + pub const unsafe fn from_erased(this: *const (), vtable: ConstGenericVTable_Ref) -> Self { + Self { ptr: RRef::from_raw(this as *const ErasedObject), vtable, } @@ -67,50 +65,35 @@ impl ConstGeneric{ /// returning an error if the type layout of `self` and `other` is not compatible. pub fn is_equal( &self, - other:&Self, - mut checker:TypeCheckerMut<'_> - )->Result { - match checker.check_compatibility(self.vtable.layout(),other.vtable.layout()) { - ROk(_)=>unsafe{ - Ok(self.vtable.partial_eq()( self.ptr, other.ptr )) - }, - RErr(e)=>{ - Err(e) - } + other: &Self, + mut checker: TypeCheckerMut<'_>, + ) -> Result { + match checker.check_compatibility(self.vtable.layout(), other.vtable.layout()) { + ROk(_) => unsafe { Ok(self.vtable.partial_eq()(self.ptr, other.ptr)) }, + RErr(e) => Err(e), } } } -impl Debug for ConstGeneric{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - unsafe{ - adapt_std_fmt::( - self.ptr, - self.vtable.debug(), - f - ) - } +impl Debug for ConstGeneric { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + unsafe { adapt_std_fmt::(self.ptr, self.vtable.debug(), f) } } } - // Make sure that this isn't called within `check_layout_compatibility` itself, // since it would cause infinite recursion. -impl PartialEq for ConstGeneric{ - fn eq(&self,other:&Self)->bool{ - if check_layout_compatibility(self.vtable.layout(),other.vtable.layout()).is_err() { +impl PartialEq for ConstGeneric { + fn eq(&self, other: &Self) -> bool { + if check_layout_compatibility(self.vtable.layout(), other.vtable.layout()).is_err() { false - }else{ - unsafe{ - self.vtable.partial_eq()( self.ptr, other.ptr ) - } + } else { + unsafe { self.vtable.partial_eq()(self.ptr, other.ptr) } } } } -impl Eq for ConstGeneric{} - - +impl Eq for ConstGeneric {} /////////////////////////////////////////////////////////////////////////////// @@ -121,20 +104,23 @@ impl Eq for ConstGeneric{} #[sabi(kind(Prefix))] #[sabi(missing_field(panic))] pub struct ConstGenericVTable { - layout:&'static TypeLayout, - partial_eq:unsafe extern "C" fn(RRef<'_, ErasedObject>,RRef<'_, ErasedObject>)->bool, + layout: &'static TypeLayout, + partial_eq: unsafe extern "C" fn(RRef<'_, ErasedObject>, RRef<'_, ErasedObject>) -> bool, #[sabi(last_prefix_field)] - debug:unsafe extern "C" fn(RRef<'_, ErasedObject>,FormattingMode,&mut RString)->RResult<(),()>, + debug: unsafe extern "C" fn( + RRef<'_, ErasedObject>, + FormattingMode, + &mut RString, + ) -> RResult<(), ()>, } /// A type that contains the vtable stored in the `ConstGeneric` constructed from a `T`. /// This is used as a workaround for `const fn` not allowing trait bounds. -pub struct ConstGenericVTableFor{ - vtable:ConstGenericVTable_Ref, - _marker:PhantomData, +pub struct ConstGenericVTableFor { + vtable: ConstGenericVTable_Ref, + _marker: PhantomData, } - impl ConstGenericVTableFor { /// Allows inferring `T` by passing a reference to it. pub const fn infer_type(&self, _: &T) {} @@ -145,36 +131,34 @@ impl ConstGenericVTableFor { } } -impl ConstGenericVTableFor +impl ConstGenericVTableFor where - T: StableAbi + Eq + PartialEq + Debug + Send + Sync + 'static + T: StableAbi + Eq + PartialEq + Debug + Send + Sync + 'static, { const _VTABLE_STATIC: WithMetadata = { WithMetadata::new( PrefixTypeTrait::METADATA, - ConstGenericVTable{ + ConstGenericVTable { layout: ::LAYOUT, partial_eq: partial_eq_impl::, debug: debug_impl::, - } + }, ) }; /// Constructs a `ConstGenericVTableFor` - pub const NEW:ConstGenericVTableFor=ConstGenericVTableFor{ + pub const NEW: ConstGenericVTableFor = ConstGenericVTableFor { vtable: ConstGenericVTable_Ref(Self::_VTABLE_STATIC.static_as_prefix()), _marker: PhantomData, }; } - #[doc(hidden)] -pub struct ConstGenericErasureHack{ +pub struct ConstGenericErasureHack { pub vtable: ConstGenericVTable_Ref, pub value: T, } - #[doc(hidden)] impl ConstGenericErasureHack { pub const fn new(vtable: ConstGenericVTableFor, value: T) -> Self { @@ -184,4 +168,3 @@ impl ConstGenericErasureHack { } } } - diff --git a/abi_stable/src/abi_stability/extra_checks.rs b/abi_stable/src/abi_stability/extra_checks.rs index a2f0c50d..e30ebfa8 100644 --- a/abi_stable/src/abi_stability/extra_checks.rs +++ b/abi_stable/src/abi_stability/extra_checks.rs @@ -12,21 +12,21 @@ To add extra checks to a type follow these steps: # Combination -This is how an ExtraChecks can be combined across all +This is how an ExtraChecks can be combined across all dynamic libraries to ensure some property(which can be relied on for safety). -This is a very similar process to how abi_stable ensures that +This is a very similar process to how abi_stable ensures that vtables and modules are consistent across dynamic libraries. ### Failure -Loading many libraries that contain ExtraChecks trait objects that need -to be combined can fail if the representative version of the trait objects +Loading many libraries that contain ExtraChecks trait objects that need +to be combined can fail if the representative version of the trait objects are incompatible with those of the library, even if both the library and the binary are otherwise compatible. The graphs below uses the `LIBRARY( ExtraChecks trait object )` format, -where the trait object is compatible only if the one in the binary +where the trait object is compatible only if the one in the binary is a prefix of the string in the library, and all the libraries have a prefix of the same string. @@ -95,7 +95,7 @@ fn main(){ // - The combined trait object is attempted to be combined with the // ExtraChecks in the global map associated to both LAYOUT0 and LAYOUT2, // which are LAYOUT1B.extra_checks and LAYOUT2.extra_checks respectively. - // - Combining the trait objects with the ones in the global map fails because + // - Combining the trait objects with the ones in the global map fails because // the one from LAYOUT1B is incompatible with the one from LAYOUT2. check_layout_compatibility(LAYOUT0,LAYOUT2).unwrap_err(); } @@ -109,7 +109,7 @@ fn main(){ #[repr(C)] #[derive(StableAbi)] #[sabi( - // Replaces the C:StableAbi constraint with `C:GetStaticEquivalent` + // Replaces the C:StableAbi constraint with `C:GetStaticEquivalent` // (a supertrait of StableAbi). not_stableabi(C), bound="C:GetConstant", @@ -128,7 +128,7 @@ impl WithConstant{ } impl WithConstant -where +where C:GetConstant { const CHECKER:ConstChecker= @@ -148,7 +148,7 @@ use self::constants::*; #[allow(non_camel_case_types)] mod constants{ use super::*; - + #[derive(GetStaticEquivalent)] pub struct V1_0; @@ -278,7 +278,7 @@ impl std::error::Error for UnequalConstError{} pub(crate) fn min_max_by(l:T,r:T,mut f:F)->(T,T) -where +where F:FnMut(&T)->K, K:Ord, { @@ -321,7 +321,7 @@ fn main(){ let rect_layout=::LAYOUT; let person_layout=::LAYOUT; - + // This passes because the fields are in order check_layout_compatibility(rect_layout,rect_layout) .unwrap_or_else(|e| panic!("{}",e) ); @@ -434,7 +434,7 @@ impl std::error::Error for OutOfOrderError{} ### Associated Constant. -This defines an ExtraChecks which checks that an associated constant is +This defines an ExtraChecks which checks that an associated constant is the same for both types. ``` @@ -475,9 +475,9 @@ fn main(){ check_layout_compatibility(const0,const_second_0).unwrap(); check_layout_compatibility(const_second_0,const0).unwrap(); - + //////////// - // None of the lines below are compatible because their + // None of the lines below are compatible because their // `GetConstant::NUMBER` associated constant isn't the same value. check_layout_compatibility(const0,const1).unwrap_err(); check_layout_compatibility(const0,const2).unwrap_err(); @@ -494,7 +494,7 @@ fn main(){ #[repr(C)] #[derive(StableAbi)] #[sabi( - // Replaces the C:StableAbi constraint with `C:GetStaticEquivalent` + // Replaces the C:StableAbi constraint with `C:GetStaticEquivalent` // (a supertrait of StableAbi). not_stableabi(C), bound="C:GetConstant", @@ -513,7 +513,7 @@ impl WithConstant{ } impl WithConstant -where +where C:GetConstant { const CHECKER:ConstChecker= @@ -633,35 +633,32 @@ impl std::error::Error for UnequalConstError{} */ - use crate::{ - sabi_types::{RRef, RMut}, - std_types::{RBox,RBoxError,RCow,RResult,ROption,RNone,ROk}, - type_layout::TypeLayout, + rtry, sabi_trait, + sabi_types::{RMut, RRef}, + std_types::{RBox, RBoxError, RCow, RNone, ROk, ROption, RResult}, traits::IntoReprC, - rtry, - sabi_trait, + type_layout::TypeLayout, StableAbi, }; use std::{ error::Error as ErrorTrait, - fmt::{self,Display}, + fmt::{self, Display}, }; use core_extensions::SelfOps; - -/// This checks that the layout of types coming from dynamic libraries +/// This checks that the layout of types coming from dynamic libraries /// are compatible with those of the binary/dynlib that loads them. /// #[sabi_trait] #[sabi(no_trait_impl)] // #[sabi(debug_print_trait)] // #[sabi(debug_print)] -pub unsafe trait TypeChecker:'static+Send+Sync{ - /// Checks that `ìnterface` is compatible with `implementation.` - /// +pub unsafe trait TypeChecker: 'static + Send + Sync { + /// Checks that `ìnterface` is compatible with `implementation.` + /// /// This is equivalent to `check_layout_compatibility`, /// except that it can also be called re-entrantly /// (while `check_layout_compatibility` cannot be called re-entrantly) @@ -674,292 +671,268 @@ pub unsafe trait TypeChecker:'static+Send+Sync{ /// fn check_compatibility( &mut self, - interface:&'static TypeLayout, - implementation:&'static TypeLayout, - )->RResult<(), ExtraChecksError>; + interface: &'static TypeLayout, + implementation: &'static TypeLayout, + ) -> RResult<(), ExtraChecksError>; - /// Checks that `ìnterface` is compatible with `implementation.` - /// + /// Checks that `ìnterface` is compatible with `implementation.` + /// /// This is equivalent to the `check_compatibility` method, /// except that it does not propagate errors automatically, /// they must be returned as part of the error of the `ExtraChecks` that calls this. #[sabi(last_prefix_field)] fn local_check_compatibility( &mut self, - interface:&'static TypeLayout, - implementation:&'static TypeLayout, - )->RResult<(), ExtraChecksError>; + interface: &'static TypeLayout, + implementation: &'static TypeLayout, + ) -> RResult<(), ExtraChecksError>; } - - - - /// An ffi-safe equivalent of &'b mut dyn TypeChecker -pub type TypeCheckerMut<'b>= - TypeChecker_TO>; +pub type TypeCheckerMut<'b> = TypeChecker_TO>; /// Allows defining extra checks for a type. /// -/// Look at the +/// Look at the /// [module level documentation](./index.html) /// for more details. -/// +/// /// # Safety -/// +/// /// The `type_layout` method must be defined as `::LAYOUT`, /// or equivalent. -/// +/// /// All of the methods must be deterministic, /// always returning the same value with the same arguments. -/// +/// #[sabi_trait] #[sabi(no_trait_impl)] // #[sabi(debug_print_trait)] // #[sabi(debug_print)] -pub unsafe trait ExtraChecks:'static+Debug+Display+Clone+Send+Sync{ +pub unsafe trait ExtraChecks: 'static + Debug + Display + Clone + Send + Sync { /// Gets the type layout of `Self`(the type that implements ExtraChecks) /// - /// This is used to downcast the trait object in + /// This is used to downcast the trait object in /// `ForExtraChecksImplementor::downcast_*` methods, - /// by ensuring that its type layout is + /// by ensuring that its type layout is /// compatible with that of another ExtraChecks trait object /// - /// It can't use `UTypeId`s to check compatibility of trait objects + /// It can't use `UTypeId`s to check compatibility of trait objects /// from different dynamic libraries, /// because `UTypeId`s from different dynamic libraries are incompatible. - fn type_layout(&self)->&'static TypeLayout; + fn type_layout(&self) -> &'static TypeLayout; -/** + /** -Checks that `self` is compatible another type which implements ExtraChecks. + Checks that `self` is compatible another type which implements ExtraChecks. -Calling `check_layout_compatibility` from here will immediately return an error, -prefer doing `checker.check_compatibility(...)` instead. + Calling `check_layout_compatibility` from here will immediately return an error, + prefer doing `checker.check_compatibility(...)` instead. -# Parameters + # Parameters -`layout_containing_self`: -The TypeLayout that contains this `ExtraChecks` trait object in the extra_checks field. + `layout_containing_self`: + The TypeLayout that contains this `ExtraChecks` trait object in the extra_checks field. -`layout_containing_other`: -The TypeLayout that contains the `other` `ExtraChecks` trait object in the extra_checks field, -which `self` is compared to. + `layout_containing_other`: + The TypeLayout that contains the `other` `ExtraChecks` trait object in the extra_checks field, + which `self` is compared to. -`checker`: -The type checker,which allows this function to check type layouts. + `checker`: + The type checker,which allows this function to check type layouts. -*/ + */ fn check_compatibility( &self, - layout_containing_self:&'static TypeLayout, - layout_containing_other:&'static TypeLayout, - checker:TypeCheckerMut<'_>, - )->RResult<(), ExtraChecksError>; + layout_containing_self: &'static TypeLayout, + layout_containing_other: &'static TypeLayout, + checker: TypeCheckerMut<'_>, + ) -> RResult<(), ExtraChecksError>; /// Returns the `TypeLayout`s owned or referenced by `self`. - /// + /// /// This is necessary for the Debug implementation of `TypeLayout`. - fn nested_type_layouts(&self)->RCow<'_,[&'static TypeLayout]>; + fn nested_type_layouts(&self) -> RCow<'_, [&'static TypeLayout]>; -/** -Combines this ExtraChecks trait object with another one. + /** + Combines this ExtraChecks trait object with another one. -To guarantee that the `extra_checks` -associated with a type (inside `::LAYOUT.extra_cheks` ) -has a single representative value across all dynamic libraries, -you must override this method, -and return `ROk(RSome(_))` by combining `self` and `other` in some way. + To guarantee that the `extra_checks` + associated with a type (inside `::LAYOUT.extra_cheks` ) + has a single representative value across all dynamic libraries, + you must override this method, + and return `ROk(RSome(_))` by combining `self` and `other` in some way. -# Parameters + # Parameters -`other`: -The other ExtraChecks trait object that this is combined with.. + `other`: + The other ExtraChecks trait object that this is combined with.. -`checker`: -The trait object of the type checker,which allows this function to check type layouts. + `checker`: + The trait object of the type checker,which allows this function to check type layouts. -# Return value + # Return value -This returns: + This returns: -- `ROk(RNone)`: - If `self` doesn't need to be unified across all dynamic libraries, - or the representative version doesn't need to be updated. + - `ROk(RNone)`: + If `self` doesn't need to be unified across all dynamic libraries, + or the representative version doesn't need to be updated. -- `ROk(RSome(_))`: - If `self` needs to be unified across all dynamic libraries, - returning the combined `self` and `other`. + - `ROk(RSome(_))`: + If `self` needs to be unified across all dynamic libraries, + returning the combined `self` and `other`. -- `RErr(_)`: If there was a problem unifying `self` and `other`. + - `RErr(_)`: If there was a problem unifying `self` and `other`. -*/ + */ #[sabi(last_prefix_field)] fn combine( &self, - _other:ExtraChecksRef<'_>, - _checker:TypeCheckerMut<'_>, - )->RResult, ExtraChecksError>{ + _other: ExtraChecksRef<'_>, + _checker: TypeCheckerMut<'_>, + ) -> RResult, ExtraChecksError> { ROk(RNone) } - } - - /// The version of `ExtraChecks` that is stored in `TypeLayout`. -pub type StoredExtraChecks=ExtraChecks_CTO<'static>; +pub type StoredExtraChecks = ExtraChecks_CTO<'static>; /// An ffi-safe equivalent of `&'static dyn ExtraChecks`. -pub type ExtraChecksStaticRef=ExtraChecks_TO>; +pub type ExtraChecksStaticRef = ExtraChecks_TO>; /// An ffi-safe equivalent of `&'a dyn ExtraChecks`. -pub type ExtraChecksRef<'a>=ExtraChecks_TO>; +pub type ExtraChecksRef<'a> = ExtraChecks_TO>; /// An ffi-safe equivalent of `Box`. -pub type ExtraChecksBox=ExtraChecks_TO>; - - +pub type ExtraChecksBox = ExtraChecks_TO>; /// An extension trait for `ExtraChecks` implementors. -pub trait ForExtraChecksImplementor:StableAbi+ExtraChecks{ - -/** -Accesses the `ExtraChecks` field in `layout_containing_other`, downcasted into `Self`. +pub trait ForExtraChecksImplementor: StableAbi + ExtraChecks { + /** + Accesses the `ExtraChecks` field in `layout_containing_other`, downcasted into `Self`. -If the closure returns an `ExtraChecksError`,it'll be returned unmodified and unwrapped. + If the closure returns an `ExtraChecksError`,it'll be returned unmodified and unwrapped. -# Returns + # Returns -- ROk(_): - If `other` was downcasted to `Self`,and `f` did not return any errors. + - ROk(_): + If `other` was downcasted to `Self`,and `f` did not return any errors. -- RErr(ExtraChecksError::NoneExtraChecks): - If`layout_containing_other` does not contain an ExtraChecks trait object. + - RErr(ExtraChecksError::NoneExtraChecks): + If`layout_containing_other` does not contain an ExtraChecks trait object. -- RErr(ExtraChecksError::TypeChecker): - If there is an error while type checking. + - RErr(ExtraChecksError::TypeChecker): + If there is an error while type checking. -- RErr(ExtraChecksError::ExtraChecks(_)): - If there is an custom error within the function. + - RErr(ExtraChecksError::ExtraChecks(_)): + If there is an custom error within the function. -*/ - fn downcast_with_layout( - layout_containing_other:&'static TypeLayout, - checker:TypeCheckerMut<'_>, - f:F, - )->RResult + */ + fn downcast_with_layout( + layout_containing_other: &'static TypeLayout, + checker: TypeCheckerMut<'_>, + f: F, + ) -> RResult where - Self:'static, - F:FnOnce(&Self,TypeCheckerMut<'_>)->Result, - E:Send+Sync+ErrorTrait+'static, + Self: 'static, + F: FnOnce(&Self, TypeCheckerMut<'_>) -> Result, + E: Send + Sync + ErrorTrait + 'static, { - let other=rtry!( - layout_containing_other.extra_checks().ok_or(ExtraChecksError::NoneExtraChecks) - ); + let other = rtry!(layout_containing_other + .extra_checks() + .ok_or(ExtraChecksError::NoneExtraChecks)); - Self::downcast_with_object(other,checker,f) + Self::downcast_with_object(other, checker, f) } -/** -Allows one to access `other` downcast into `Self`. + /** + Allows one to access `other` downcast into `Self`. -If the closure returns an `ExtraChecksError`,it'll be returned unmodified and unwrapped. + If the closure returns an `ExtraChecksError`,it'll be returned unmodified and unwrapped. -# Returns + # Returns -- ROk(_): - If `other` could be downcasted to `Self`,and `f` did not return any errors. + - ROk(_): + If `other` could be downcasted to `Self`,and `f` did not return any errors. -- RErr(ExtraChecksError::TypeChecker): - If there is an error while type checking. + - RErr(ExtraChecksError::TypeChecker): + If there is an error while type checking. -- RErr(ExtraChecksError::ExtraChecks(_)): - If there is an custom error within the function. + - RErr(ExtraChecksError::ExtraChecks(_)): + If there is an custom error within the function. -*/ - fn downcast_with_object( - other:ExtraChecksRef<'_>, - mut checker:TypeCheckerMut<'_>, - f:F, - )->RResult + */ + fn downcast_with_object( + other: ExtraChecksRef<'_>, + mut checker: TypeCheckerMut<'_>, + f: F, + ) -> RResult where - F:FnOnce(&Self,TypeCheckerMut<'_>)->Result, - E:Send+Sync+ErrorTrait+'static, + F: FnOnce(&Self, TypeCheckerMut<'_>) -> Result, + E: Send + Sync + ErrorTrait + 'static, { // This checks that the layouts of `this` and `other` are compatible, // so that calling the `unchecked_downcast_into` method is sound. - rtry!( checker.check_compatibility(::LAYOUT,other.type_layout()) ); - let other_ue=unsafe{ other.obj.unchecked_downcast_into::() }; - - f(other_ue.get(),checker) - .map_err(|e|{ - match RBoxError::new(e).downcast::() { - Ok(x)=>x.piped(RBox::into_inner), - Err(e)=>ExtraChecksError::from_extra_checks(e), - } + rtry!(checker.check_compatibility(::LAYOUT, other.type_layout())); + let other_ue = unsafe { other.obj.unchecked_downcast_into::() }; + + f(other_ue.get(), checker) + .map_err(|e| match RBoxError::new(e).downcast::() { + Ok(x) => x.piped(RBox::into_inner), + Err(e) => ExtraChecksError::from_extra_checks(e), }) .into_c() } } - -impl ForExtraChecksImplementor for This -where - This:?Sized+StableAbi+ExtraChecks -{} - +impl ForExtraChecksImplementor for This where This: ?Sized + StableAbi + ExtraChecks {} /////////////////////////////////////////////////////////////////////////////// - /// The errors returned from `ExtraChecks` and `ForExtraChecksImplementor` methods. #[repr(u8)] -#[derive(Debug,StableAbi)] -pub enum ExtraChecksError{ +#[derive(Debug, StableAbi)] +pub enum ExtraChecksError { /// When a type checking error happens within `TypeChecker`. TypeChecker, /// Errors returned from `TypeChecker::local_check_compatibility` TypeCheckerErrors(RBoxError), /// When trying to get a ExtraChecks trait object from `TypeLayout.extra_checks==None` . NoneExtraChecks, - /// A custom error returned by the ExtraChecker or + /// A custom error returned by the ExtraChecker or /// the closures in `ForExtraChecksImplementor::downcast_*`. ExtraChecks(RBoxError), } - impl ExtraChecksError { /// Constructs a `ExtraChecksError::ExtraChecks` from an error. - pub fn from_extra_checks(err:E)->ExtraChecksError + pub fn from_extra_checks(err: E) -> ExtraChecksError where - E:Send+Sync+ErrorTrait+'static, + E: Send + Sync + ErrorTrait + 'static, { - let x=RBoxError::new(err); + let x = RBoxError::new(err); ExtraChecksError::ExtraChecks(x) } } - -impl Display for ExtraChecksError{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ +impl Display for ExtraChecksError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - ExtraChecksError::TypeChecker=> - Display::fmt("A type checker error happened.",f), - ExtraChecksError::TypeCheckerErrors(e)=> - writeln!(f,"Errors that happened during type checking:\n{}",e), - ExtraChecksError::NoneExtraChecks=> - Display::fmt("No `ExtraChecks` in the implementation.",f), - ExtraChecksError::ExtraChecks(e)=> - Display::fmt(e,f), + ExtraChecksError::TypeChecker => Display::fmt("A type checker error happened.", f), + ExtraChecksError::TypeCheckerErrors(e) => { + writeln!(f, "Errors that happened during type checking:\n{}", e) + } + ExtraChecksError::NoneExtraChecks => { + Display::fmt("No `ExtraChecks` in the implementation.", f) + } + ExtraChecksError::ExtraChecks(e) => Display::fmt(e, f), } } } -impl std::error::Error for ExtraChecksError{} - - - +impl std::error::Error for ExtraChecksError {} diff --git a/abi_stable/src/abi_stability/get_static_equivalent.rs b/abi_stable/src/abi_stability/get_static_equivalent.rs index 79448b41..b3eddafc 100644 --- a/abi_stable/src/abi_stability/get_static_equivalent.rs +++ b/abi_stable/src/abi_stability/get_static_equivalent.rs @@ -6,40 +6,37 @@ Containst the `GetStaticEquivalent_` trait and related items. /// A type that stands in for `Self`,used to create a `UTypeId` for doing layout checking. /// /// This may or may not have the same TypeId as Self. -pub unsafe trait GetStaticEquivalent_{ - type StaticEquivalent:'static; +pub unsafe trait GetStaticEquivalent_ { + type StaticEquivalent: 'static; } /// Gets the `'static` equivalent of a type,only for use in creating a `UTypeId`. -pub type GetStaticEquivalent= - ::StaticEquivalent; +pub type GetStaticEquivalent = ::StaticEquivalent; /// Used to avoid a `?Sized` bound on `GetStaticEquivalent_::StaticEquivalent`. -/// -/// It's fine to use this instead of `str` and `[T]` since the type is +/// +/// It's fine to use this instead of `str` and `[T]` since the type is /// only required to be unique. -pub struct Unsized(fn(&T)); - +pub struct Unsized(fn(&T)); //////////////////////////////////////////////////////////////////////////////// // Impls for non-StableAbi types //////////////////////////////////////////////////////////////////////////////// - -unsafe impl GetStaticEquivalent_ for str{ - type StaticEquivalent=Unsized; +unsafe impl GetStaticEquivalent_ for str { + type StaticEquivalent = Unsized; } unsafe impl GetStaticEquivalent_ for [T] where - T:GetStaticEquivalent_ + T: GetStaticEquivalent_, { - type StaticEquivalent=Unsized<[T::StaticEquivalent]>; + type StaticEquivalent = Unsized<[T::StaticEquivalent]>; } -unsafe impl GetStaticEquivalent_ for Unsized +unsafe impl GetStaticEquivalent_ for Unsized where - T:GetStaticEquivalent_ + T: GetStaticEquivalent_, { - type StaticEquivalent=Unsized; -} \ No newline at end of file + type StaticEquivalent = Unsized; +} diff --git a/abi_stable/src/abi_stability/stable_abi_trait.rs b/abi_stable/src/abi_stability/stable_abi_trait.rs index c3e40df6..037cd073 100644 --- a/abi_stable/src/abi_stability/stable_abi_trait.rs +++ b/abi_stable/src/abi_stability/stable_abi_trait.rs @@ -4,10 +4,10 @@ Where the StableAbi trait is declared,as well as related types/traits. use core_extensions::type_level_bool::{Boolean, False, True}; use std::{ - cell::{Cell,UnsafeCell}, - marker::{PhantomData,PhantomPinned}, + cell::{Cell, UnsafeCell}, + marker::{PhantomData, PhantomPinned}, mem::ManuallyDrop, - num::{NonZeroU8,NonZeroU16,NonZeroU32,NonZeroU64,NonZeroUsize,Wrapping}, + num::{NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize, Wrapping}, pin::Pin, ptr::NonNull, sync::atomic::{AtomicBool, AtomicIsize, AtomicPtr, AtomicUsize}, @@ -15,19 +15,16 @@ use std::{ use crate::{ abi_stability::get_static_equivalent::GetStaticEquivalent_, - sabi_types::Constructor, - std_types::utypeid::UTypeId, reflection::ModReflMode, + sabi_types::Constructor, + std_types::{utypeid::UTypeId, RSlice}, type_layout::{ - LifetimeRange, - MonoTLData, GenericTLData, TypeLayout, MonoTypeLayout, - ItemInfo,ReprAttr,TLPrimitive,TLDiscriminants, - GenericTLEnum, MonoTLEnum, CompTLField, CompTLFields, StartLen, DiscriminantRepr, + CompTLField, CompTLFields, DiscriminantRepr, GenericTLData, GenericTLEnum, ItemInfo, + LifetimeRange, MonoTLData, MonoTLEnum, MonoTypeLayout, ReprAttr, StartLen, TLDiscriminants, + TLPrimitive, TypeLayout, }, - std_types::RSlice, }; - /////////////////////// /** @@ -44,74 +41,69 @@ and passing this into a dynamic library would be equivalent to transmuting it. # Caveats This trait cannot be directly implemented for functions that take lifetime parameters, -because of that,`#[derive(StableAbi)]` detects the presence of `extern fn` types +because of that,`#[derive(StableAbi)]` detects the presence of `extern fn` types in type definitions. */ -pub unsafe trait StableAbi:GetStaticEquivalent_ { +pub unsafe trait StableAbi: GetStaticEquivalent_ { /** -Whether this type has a single invalid bit-pattern. + Whether this type has a single invalid bit-pattern. -Possible values:True/False + Possible values:True/False -Some standard library types have a single value that is invalid for them eg:0,null. -these types are the only ones which can be stored in a `Option<_>` that implements StableAbi. + Some standard library types have a single value that is invalid for them eg:0,null. + these types are the only ones which can be stored in a `Option<_>` that implements StableAbi. -An alternative for types where `IsNonZeroType=False`,you can use `ROption`. + An alternative for types where `IsNonZeroType=False`,you can use `ROption`. -Non-exhaustive list of std types that are NonZero: + Non-exhaustive list of std types that are NonZero: -- `&T` (any T). + - `&T` (any T). -- `&mut T` (any T). + - `&mut T` (any T). -- `extern "C" fn()`. + - `extern "C" fn()`. -- `std::ptr::NonNull` + - `std::ptr::NonNull` -- `std::num::NonZero*` + - `std::num::NonZero*` - */ + */ type IsNonZeroType: Boolean; /// The layout of the type provided by implementors. const LAYOUT: &'static TypeLayout; /// `const`-equivalents of the associated types. - const ABI_CONSTS: AbiConsts=AbiConsts { - type_id:Constructor( - crate::std_types::utypeid::new_utypeid:: - ), + const ABI_CONSTS: AbiConsts = AbiConsts { + type_id: Constructor(crate::std_types::utypeid::new_utypeid::), is_nonzero: ::VALUE, }; } /// A type that only has a stable layout when a `PrefixRef` to it is used. -/// +/// /// Types that implement this trait usually have a `_Prefix` suffix. -/// +/// /// # Safety -/// +/// /// This trait can only be implemented by the `StableAbi` derive /// on types that also use the `#[sabi(kind(Prefix))]` attribute, /// implementing the trait for a macro generated type. pub unsafe trait PrefixStableAbi: GetStaticEquivalent_ { /// Whether this type has a single invalid bit-pattern. type IsNonZeroType: Boolean; - + /// The layout of the type, provided by implementors. const LAYOUT: &'static TypeLayout; /// `const`-equivalents of the associated types. - const ABI_CONSTS: AbiConsts=AbiConsts { - type_id:Constructor( - crate::std_types::utypeid::new_utypeid:: - ), + const ABI_CONSTS: AbiConsts = AbiConsts { + type_id: Constructor(crate::std_types::utypeid::new_utypeid::), is_nonzero: ::VALUE, }; } - /////////////////////// /// Contains constants equivalent to the associated types in StableAbi. @@ -120,17 +112,17 @@ pub unsafe trait PrefixStableAbi: GetStaticEquivalent_ { #[derive(StableAbi)] pub struct AbiConsts { /// A function to get the unique identifier for some type - pub type_id:Constructor, - + pub type_id: Constructor, + /// Whether the type uses non-zero value optimization, /// if true then an Option implements StableAbi. pub is_nonzero: bool, } -impl AbiConsts{ +impl AbiConsts { /// Gets the `UTypeId` returned by the `type_id` field. #[inline] - pub fn get_type_id(&self)->UTypeId{ + pub fn get_type_id(&self) -> UTypeId { self.type_id.get() } } @@ -138,38 +130,32 @@ impl AbiConsts{ /////////////////////////////////////////////////////////////////////////////// /// Getter for the TypeLayout of some type,wraps an `extern "C" fn() -> &'static TypeLayout`. -pub type TypeLayoutCtor=Constructor<&'static TypeLayout>; +pub type TypeLayoutCtor = Constructor<&'static TypeLayout>; // pub unsafe trait GetTypeLayoutCtor { - #[doc(hidden)] pub struct GetTypeLayoutCtor(T); impl GetTypeLayoutCtor -where T: StableAbi, +where + T: StableAbi, { - pub const STABLE_ABI:TypeLayoutCtor=Constructor ( - get_type_layout::, - ); + pub const STABLE_ABI: TypeLayoutCtor = Constructor(get_type_layout::); - pub const SABI_OPAQUE_FIELD:TypeLayoutCtor=Constructor ( - get_type_layout::>, - ); + pub const SABI_OPAQUE_FIELD: TypeLayoutCtor = + Constructor(get_type_layout::>); } impl GetTypeLayoutCtor -where T: PrefixStableAbi, +where + T: PrefixStableAbi, { - pub const PREFIX_STABLE_ABI:TypeLayoutCtor=Constructor ( - get_prefix_field_type_layout::, - ); + pub const PREFIX_STABLE_ABI: TypeLayoutCtor = Constructor(get_prefix_field_type_layout::); } -impl GetTypeLayoutCtor{ - pub const OPAQUE_FIELD:TypeLayoutCtor=Constructor ( - get_type_layout::>, - ); +impl GetTypeLayoutCtor { + pub const OPAQUE_FIELD: TypeLayoutCtor = Constructor(get_type_layout::>); } /// Retrieves the TypeLayout of `T: StableAbi`, @@ -188,7 +174,6 @@ where ::LAYOUT } - /////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// @@ -197,21 +182,23 @@ where /////////////////////////////////////////////////////////////////////////////// -unsafe impl GetStaticEquivalent_ for PhantomData -where T:GetStaticEquivalent_ +unsafe impl GetStaticEquivalent_ for PhantomData +where + T: GetStaticEquivalent_, { - type StaticEquivalent=PhantomData; + type StaticEquivalent = PhantomData; } -unsafe impl StableAbi for PhantomData -where T:StableAbi +unsafe impl StableAbi for PhantomData +where + T: StableAbi, { type IsNonZeroType = False; const LAYOUT: &'static TypeLayout = { zst_assert!(Self); - const MONO_TYPE_LAYOUT:&MonoTypeLayout=&MonoTypeLayout::new( + const MONO_TYPE_LAYOUT: &MonoTypeLayout = &MonoTypeLayout::new( *mono_shared_vars, rstr!("PhantomData"), ItemInfo::std_type_in(nul_str!("std::marker")), @@ -220,12 +207,13 @@ where T:StableAbi ReprAttr::C, ModReflMode::Module, { - const S: &[CompTLField] = &[CompTLField::std_field(field0,LifetimeRange::EMPTY,0)]; + const S: &[CompTLField] = + &[CompTLField::std_field(field0, LifetimeRange::EMPTY, 0)]; RSlice::from_slice(S) }, ); - make_shared_vars!{ + make_shared_vars! { impl[T] PhantomData where[T: StableAbi]; @@ -244,24 +232,23 @@ where T:StableAbi }; } - macro_rules! phantomdata_tuples { (ignore; $($anything:tt)*)=>{ 1 }; - ( - $(($tuple_param:ident,$name_ident:ident=$name_str:literal))* + ( + $(($tuple_param:ident,$name_ident:ident=$name_str:literal))* )=>{ - unsafe impl<$($tuple_param,)*> - GetStaticEquivalent_ - for PhantomData<($($tuple_param,)*)> + unsafe impl<$($tuple_param,)*> + GetStaticEquivalent_ + for PhantomData<($($tuple_param,)*)> where $($tuple_param:GetStaticEquivalent_,)* { type StaticEquivalent=PhantomData<($($tuple_param::StaticEquivalent,)*)>; } - unsafe impl<$($tuple_param,)*> + unsafe impl<$($tuple_param,)*> StableAbi - for PhantomData<($($tuple_param,)*)> + for PhantomData<($($tuple_param,)*)> where $($tuple_param:StableAbi,)* { @@ -286,7 +273,7 @@ macro_rules! phantomdata_tuples { #[allow(unused_assignments)] const FIELDS:&'static [CompTLField;COUNT]={ let mut i=0; - $( + $( #[allow(non_snake_case)] let $tuple_param= CompTLField::std_field($name_ident,LifetimeRange::EMPTY,i); @@ -298,7 +285,7 @@ macro_rules! phantomdata_tuples { const COUNT:usize=$(phantomdata_tuples!(ignore;$tuple_param)+)* 0; make_shared_vars!{ - impl[$($tuple_param,)*] PhantomData<($($tuple_param,)*)> + impl[$($tuple_param,)*] PhantomData<($($tuple_param,)*)> where[ $($tuple_param:StableAbi,)* ]; @@ -332,32 +319,32 @@ fn main(){ } */ -phantomdata_tuples!{ +phantomdata_tuples! { (T0,p0="0") } -phantomdata_tuples!{ +phantomdata_tuples! { (T0,p0="0") (T1,p1="1") } -phantomdata_tuples!{ +phantomdata_tuples! { (T0,p0="0") (T1,p1="1") (T2,p2="2") } -phantomdata_tuples!{ +phantomdata_tuples! { (T0,p0="0") (T1,p1="1") (T2,p2="2") (T3,p3="3") } -phantomdata_tuples!{ +phantomdata_tuples! { (T0,p0="0") (T1,p1="1") (T2,p2="2") (T3,p3="3") (T4,p4="4") } -phantomdata_tuples!{ +phantomdata_tuples! { (T0,p0="0") (T1,p1="1") (T2,p2="2") @@ -365,7 +352,7 @@ phantomdata_tuples!{ (T4,p4="4") (T5,p5="5") } -phantomdata_tuples!{ +phantomdata_tuples! { (T0,p0="0") (T1,p1="1") (T2,p2="2") @@ -374,7 +361,7 @@ phantomdata_tuples!{ (T5,p5="5") (T6,p6="6") } -phantomdata_tuples!{ +phantomdata_tuples! { (T0,p0="0") (T1,p1="1") (T2,p2="2") @@ -384,7 +371,7 @@ phantomdata_tuples!{ (T6,p6="6") (T7,p7="7") } -phantomdata_tuples!{ +phantomdata_tuples! { (T0,p0="0") (T1,p1="1") (T2,p2="2") @@ -395,7 +382,7 @@ phantomdata_tuples!{ (T7,p7="7") (T8,p8="8") } -phantomdata_tuples!{ +phantomdata_tuples! { (T0,p0="0") (T1,p1="1") (T2,p2="2") @@ -407,7 +394,7 @@ phantomdata_tuples!{ (T8,p8="8") (T9,p9="9") } -phantomdata_tuples!{ +phantomdata_tuples! { (T0,p0="0") (T1,p1="1") (T2,p2="2") @@ -420,7 +407,7 @@ phantomdata_tuples!{ (T9,p9="9") (T10,p10="10") } -phantomdata_tuples!{ +phantomdata_tuples! { (T0,p0="0") (T1,p1="1") (T2,p2="2") @@ -434,7 +421,7 @@ phantomdata_tuples!{ (T10,p10="10") (T11,p11="11") } -phantomdata_tuples!{ +phantomdata_tuples! { (T0,p0="0") (T1,p1="1") (T2,p2="2") @@ -449,7 +436,7 @@ phantomdata_tuples!{ (T11,p11="11") (T12,p12="12") } -phantomdata_tuples!{ +phantomdata_tuples! { (T0,p0="0") (T1,p1="1") (T2,p2="2") @@ -465,7 +452,7 @@ phantomdata_tuples!{ (T12,p12="12") (T13,p13="13") } -phantomdata_tuples!{ +phantomdata_tuples! { (T0,p0="0") (T1,p1="1") (T2,p2="2") @@ -482,7 +469,7 @@ phantomdata_tuples!{ (T13,p13="13") (T14,p14="14") } -phantomdata_tuples!{ +phantomdata_tuples! { (T0,p0="0") (T1,p1="1") (T2,p2="2") @@ -501,17 +488,14 @@ phantomdata_tuples!{ (T15,p15="15") } - - - unsafe impl GetStaticEquivalent_ for () { - type StaticEquivalent=(); + type StaticEquivalent = (); } unsafe impl StableAbi for () { type IsNonZeroType = False; const LAYOUT: &'static TypeLayout = { - const MONO_TYPE_LAYOUT:&MonoTypeLayout=&MonoTypeLayout::new( + const MONO_TYPE_LAYOUT: &MonoTypeLayout = &MonoTypeLayout::new( *mono_shared_vars, rstr!("()"), ItemInfo::primitive(), @@ -522,7 +506,7 @@ unsafe impl StableAbi for () { RSlice::EMPTY, ); - make_shared_vars!{ + make_shared_vars! { impl[] (); let (mono_shared_vars,shared_vars)={}; @@ -537,17 +521,13 @@ unsafe impl StableAbi for () { }; } - - - ///////////// - unsafe impl<'a, T> GetStaticEquivalent_ for &'a T where T: 'a + GetStaticEquivalent_, { - type StaticEquivalent=&'static T::StaticEquivalent; + type StaticEquivalent = &'static T::StaticEquivalent; } // Does not allow ?Sized types because the DST fat pointer does not have a stable layout. @@ -558,21 +538,22 @@ where type IsNonZeroType = True; const LAYOUT: &'static TypeLayout = { - const MONO_TYPE_LAYOUT:&MonoTypeLayout=&MonoTypeLayout::new( + const MONO_TYPE_LAYOUT: &MonoTypeLayout = &MonoTypeLayout::new( *mono_shared_vars, rstr!("&"), ItemInfo::primitive(), MonoTLData::Primitive(TLPrimitive::SharedRef), tl_genparams!('a;0;), ReprAttr::Primitive, - ModReflMode::DelegateDeref{layout_index:0}, + ModReflMode::DelegateDeref { layout_index: 0 }, { - const S: &[CompTLField] = &[CompTLField::std_field(field0,LifetimeRange::EMPTY,0)]; + const S: &[CompTLField] = + &[CompTLField::std_field(field0, LifetimeRange::EMPTY, 0)]; RSlice::from_slice(S) }, ); - make_shared_vars!{ + make_shared_vars! { impl['a, T] &'a T where[ T: 'a + StableAbi]; @@ -591,12 +572,11 @@ where }; } - unsafe impl<'a, T> GetStaticEquivalent_ for &'a mut T where T: 'a + GetStaticEquivalent_, { - type StaticEquivalent=&'static mut T::StaticEquivalent; + type StaticEquivalent = &'static mut T::StaticEquivalent; } // Does not allow ?Sized types because the DST fat pointer does not have a stable layout. @@ -607,21 +587,22 @@ where type IsNonZeroType = True; const LAYOUT: &'static TypeLayout = { - const MONO_TYPE_LAYOUT:&MonoTypeLayout=&MonoTypeLayout::new( + const MONO_TYPE_LAYOUT: &MonoTypeLayout = &MonoTypeLayout::new( *mono_shared_vars, rstr!("&mut"), ItemInfo::primitive(), MonoTLData::Primitive(TLPrimitive::MutRef), tl_genparams!('a;0;), ReprAttr::Primitive, - ModReflMode::DelegateDeref{layout_index:0}, + ModReflMode::DelegateDeref { layout_index: 0 }, { - const S: &[CompTLField] = &[CompTLField::std_field(field0,LifetimeRange::EMPTY,0)]; + const S: &[CompTLField] = + &[CompTLField::std_field(field0, LifetimeRange::EMPTY, 0)]; RSlice::from_slice(S) }, ); - make_shared_vars!{ + make_shared_vars! { impl['a, T] &'a mut T where[ T: 'a + StableAbi]; @@ -639,14 +620,12 @@ where ) }; } - - unsafe impl GetStaticEquivalent_ for NonNull where T: GetStaticEquivalent_, { - type StaticEquivalent=NonNull; + type StaticEquivalent = NonNull; } // Does not allow ?Sized types because the DST fat pointer does not have a stable layout. @@ -657,14 +636,13 @@ where type IsNonZeroType = True; const LAYOUT: &'static TypeLayout = { - const MONO_TYPE_LAYOUT:&MonoTypeLayout=&MonoTypeLayout::new( + const MONO_TYPE_LAYOUT: &MonoTypeLayout = &MonoTypeLayout::new( *mono_shared_vars, rstr!("NonNull"), ItemInfo::std_type_in(nul_str!("std::ptr")), { - const S: &[CompTLField] = &[ - CompTLField::std_field(field0,LifetimeRange::EMPTY,1) - ]; + const S: &[CompTLField] = + &[CompTLField::std_field(field0, LifetimeRange::EMPTY, 1)]; MonoTLData::struct_(RSlice::from_slice(S)) }, tl_genparams!(;0;), @@ -673,7 +651,7 @@ where RSlice::EMPTY, ); - make_shared_vars!{ + make_shared_vars! { impl[T] NonNull where[ T: StableAbi]; @@ -692,12 +670,11 @@ where }; } - unsafe impl GetStaticEquivalent_ for AtomicPtr where T: GetStaticEquivalent_, { - type StaticEquivalent=AtomicPtr; + type StaticEquivalent = AtomicPtr; } unsafe impl StableAbi for AtomicPtr @@ -707,14 +684,13 @@ where type IsNonZeroType = False; const LAYOUT: &'static TypeLayout = { - const MONO_TYPE_LAYOUT:&MonoTypeLayout=&MonoTypeLayout::new( + const MONO_TYPE_LAYOUT: &MonoTypeLayout = &MonoTypeLayout::new( *mono_shared_vars, rstr!("AtomicPtr"), ItemInfo::std_type_in(nul_str!("std::sync::atomic")), { - const S: &[CompTLField] = &[ - CompTLField::std_field(field0,LifetimeRange::EMPTY,1) - ]; + const S: &[CompTLField] = + &[CompTLField::std_field(field0, LifetimeRange::EMPTY, 1)]; MonoTLData::struct_(RSlice::from_slice(S)) }, tl_genparams!(;0;), @@ -723,7 +699,7 @@ where RSlice::EMPTY, ); - make_shared_vars!{ + make_shared_vars! { impl[T] AtomicPtr where[T: StableAbi]; @@ -746,7 +722,7 @@ unsafe impl GetStaticEquivalent_ for *const T where T: GetStaticEquivalent_, { - type StaticEquivalent=*const T::StaticEquivalent; + type StaticEquivalent = *const T::StaticEquivalent; } // Does not allow ?Sized types because the DST fat pointer does not have a stable layout. unsafe impl StableAbi for *const T @@ -756,7 +732,7 @@ where type IsNonZeroType = False; const LAYOUT: &'static TypeLayout = { - const MONO_TYPE_LAYOUT:&MonoTypeLayout=&MonoTypeLayout::new( + const MONO_TYPE_LAYOUT: &MonoTypeLayout = &MonoTypeLayout::new( *mono_shared_vars, rstr!("*const"), ItemInfo::primitive(), @@ -765,14 +741,13 @@ where ReprAttr::Primitive, ModReflMode::Module, { - const S: &[CompTLField] = &[ - CompTLField::std_field(field0,LifetimeRange::EMPTY,0), - ]; + const S: &[CompTLField] = + &[CompTLField::std_field(field0, LifetimeRange::EMPTY, 0)]; RSlice::from_slice(S) }, ); - make_shared_vars!{ + make_shared_vars! { impl[T] *const T where[T: StableAbi]; @@ -791,12 +766,11 @@ where }; } - unsafe impl GetStaticEquivalent_ for *mut T where T: GetStaticEquivalent_, { - type StaticEquivalent=*mut T::StaticEquivalent; + type StaticEquivalent = *mut T::StaticEquivalent; } // Does not allow ?Sized types because the DST fat pointer does not have a stable layout. unsafe impl StableAbi for *mut T @@ -806,7 +780,7 @@ where type IsNonZeroType = False; const LAYOUT: &'static TypeLayout = { - const MONO_TYPE_LAYOUT:&MonoTypeLayout=&MonoTypeLayout::new( + const MONO_TYPE_LAYOUT: &MonoTypeLayout = &MonoTypeLayout::new( *mono_shared_vars, rstr!("*mut"), ItemInfo::primitive(), @@ -815,14 +789,13 @@ where ReprAttr::Primitive, ModReflMode::Module, { - const S: &[CompTLField] = &[ - CompTLField::std_field(field0,LifetimeRange::EMPTY,0), - ]; + const S: &[CompTLField] = + &[CompTLField::std_field(field0, LifetimeRange::EMPTY, 0)]; RSlice::from_slice(S) }, ); - make_shared_vars!{ + make_shared_vars! { impl[T] *mut T where[T: StableAbi]; @@ -845,23 +818,25 @@ where #[cfg(feature = "const_params")] macro_rules! impl_stable_abi_array { - ()=>{ + () => { /// When the "const_params" feature is disabled, /// this trait is implemented for arrays of up to 32 elements. #[cfg_attr(feature = "docsrs", doc(cfg(feature = "const_params")))] unsafe impl GetStaticEquivalent_ for [T; N] - where T:GetStaticEquivalent_ + where + T: GetStaticEquivalent_, { - type StaticEquivalent=[T::StaticEquivalent; N]; + type StaticEquivalent = [T::StaticEquivalent; N]; } /// When the "const_params" feature is disabled, /// this trait is implemented for arrays of up to 32 elements. #[cfg_attr(feature = "docsrs", doc(cfg(feature = "const_params")))] unsafe impl StableAbi for [T; N] - where T:StableAbi + where + T: StableAbi, { - type IsNonZeroType=False; + type IsNonZeroType = False; const LAYOUT: &'static TypeLayout = { // Used to get constants for [T; N] where T doesn't matter @@ -872,20 +847,19 @@ macro_rules! impl_stable_abi_array { *mono_shared_vars, rstr!("array"), ItemInfo::primitive(), - MonoTLData::Primitive(TLPrimitive::Array{len:N}), + MonoTLData::Primitive(TLPrimitive::Array { len: N }), tl_genparams!(;0;0), ReprAttr::Primitive, ModReflMode::Module, { - const S: &[CompTLField] = &[ - CompTLField::std_field(field0, LifetimeRange::EMPTY, 0), - ]; + const S: &[CompTLField] = + &[CompTLField::std_field(field0, LifetimeRange::EMPTY, 0)]; RSlice::from_slice(S) }, ); } - make_shared_vars!{ + make_shared_vars! { impl[T, const N: usize] [T; N] where[T: StableAbi]; @@ -904,11 +878,11 @@ macro_rules! impl_stable_abi_array { ) }; } - } + }; } #[cfg(feature = "const_params")] -impl_stable_abi_array!{} +impl_stable_abi_array! {} ///////////// @@ -981,7 +955,7 @@ unsafe impl GetStaticEquivalent_ for Option where T: GetStaticEquivalent_, { - type StaticEquivalent=Option; + type StaticEquivalent = Option; } /// Implementing abi stability for Option is fine if /// T is a NonZero primitive type. @@ -991,36 +965,30 @@ where { type IsNonZeroType = False; - const LAYOUT: &'static TypeLayout = { - const MONO_TYPE_LAYOUT:&MonoTypeLayout=&MonoTypeLayout::new( + const MONO_TYPE_LAYOUT: &MonoTypeLayout = &MonoTypeLayout::new( *mono_shared_vars, rstr!("Option"), ItemInfo::std_type_in(nul_str!("std::option")), - MonoTLData::Enum(MonoTLEnum::new( - variant_names, - rslice![1,0], - { - const S: &[CompTLField] = &[ - CompTLField::std_field(field0,LifetimeRange::EMPTY,0), - ]; - CompTLFields::from_fields(RSlice::from_slice(S)) - }, - )), + MonoTLData::Enum(MonoTLEnum::new(variant_names, rslice![1, 0], { + const S: &[CompTLField] = + &[CompTLField::std_field(field0, LifetimeRange::EMPTY, 0)]; + CompTLFields::from_fields(RSlice::from_slice(S)) + })), tl_genparams!(;0;), ReprAttr::OptionNonZero, ModReflMode::Module, RSlice::EMPTY, ); - make_shared_vars!{ + make_shared_vars! { impl[T] Option where [ T: StableAbi, ]; let (mono_shared_vars,shared_vars)={ strings={ variant_names:"Some;None;", - field0:"0", + field0:"0", }, type_layouts=[T], }; @@ -1030,16 +998,15 @@ where shared_vars, MONO_TYPE_LAYOUT, Self::ABI_CONSTS, - GenericTLData::Enum(GenericTLEnum::exhaustive( - TLDiscriminants::from_u8_slice(rslice![0,1]) - )), + GenericTLData::Enum(GenericTLEnum::exhaustive(TLDiscriminants::from_u8_slice( + rslice![0, 1], + ))), ) }; } ///////////// - macro_rules! impl_for_primitive_ints { ( $( ($type:ty,$type_name:literal,$tl_primitive:expr) ,)* @@ -1083,7 +1050,7 @@ macro_rules! impl_for_primitive_ints { ) } -impl_for_primitive_ints!{ +impl_for_primitive_ints! { (u8 ,"u8" ,TLPrimitive::U8), (i8 ,"i8" ,TLPrimitive::I8), (u16 ,"u16" ,TLPrimitive::U16), @@ -1097,7 +1064,6 @@ impl_for_primitive_ints!{ (bool ,"bool" ,TLPrimitive::Bool), } - macro_rules! impl_for_concrete { ( type IsNonZeroType=$zeroness:ty; @@ -1150,8 +1116,6 @@ macro_rules! impl_for_concrete { ) } - - impl_for_concrete! { type IsNonZeroType=False; [ @@ -1173,11 +1137,10 @@ impl_for_concrete! { } ///////////// - -mod rust_1_34_impls{ +mod rust_1_34_impls { use super::*; - use std::sync::atomic::*; use core::num::*; + use std::sync::atomic::*; impl_for_concrete! { type IsNonZeroType=False; @@ -1205,35 +1168,31 @@ mod rust_1_34_impls{ } } - -mod rust_1_36_impls{ +mod rust_1_36_impls { use super::*; use std::mem::MaybeUninit; unsafe impl GetStaticEquivalent_ for MaybeUninit where - T:GetStaticEquivalent_ + T: GetStaticEquivalent_, { - type StaticEquivalent=MaybeUninit; + type StaticEquivalent = MaybeUninit; } unsafe impl StableAbi for MaybeUninit where - T:StableAbi + T: StableAbi, { - // MaybeUninit blocks layout optimizations. type IsNonZeroType = False; - const LAYOUT: &'static TypeLayout = { - const MONO_TYPE_LAYOUT:&MonoTypeLayout=&MonoTypeLayout::new( + const MONO_TYPE_LAYOUT: &MonoTypeLayout = &MonoTypeLayout::new( *mono_shared_vars, rstr!("MaybeUninit"), ItemInfo::std_type_in(nul_str!("std::mem")), { - const S: &[CompTLField] = &[ - CompTLField::std_field(field0,LifetimeRange::EMPTY,0), - ]; + const S: &[CompTLField] = + &[CompTLField::std_field(field0, LifetimeRange::EMPTY, 0)]; MonoTLData::struct_(RSlice::from_slice(S)) }, tl_genparams!(;0;), @@ -1244,7 +1203,7 @@ mod rust_1_36_impls{ RSlice::EMPTY, ); - make_shared_vars!{ + make_shared_vars! { impl[T] MaybeUninit where [T: StableAbi]; @@ -1264,8 +1223,6 @@ mod rust_1_36_impls{ } } - - ///////////// macro_rules! impl_sabi_for_newtype { @@ -1333,13 +1290,12 @@ macro_rules! impl_sabi_for_newtype { ) } +impl_sabi_for_newtype! { Wrapping ,transparent,"Wrapping" ,"std::num" } +impl_sabi_for_newtype! { Pin ,transparent,"Pin" ,"std::pin" } +impl_sabi_for_newtype! { ManuallyDrop,transparent,"ManuallyDrop","std::mem" } -impl_sabi_for_newtype!{ Wrapping ,transparent,"Wrapping" ,"std::num" } -impl_sabi_for_newtype!{ Pin ,transparent,"Pin" ,"std::pin" } -impl_sabi_for_newtype!{ ManuallyDrop,transparent,"ManuallyDrop","std::mem" } - -impl_sabi_for_newtype!{ Cell ,C,"Cell" ,"std::cell" } -impl_sabi_for_newtype!{ UnsafeCell ,C,"UnsafeCell" ,"std::cell" } +impl_sabi_for_newtype! { Cell ,C,"Cell" ,"std::cell" } +impl_sabi_for_newtype! { UnsafeCell ,C,"UnsafeCell" ,"std::cell" } ///////////// @@ -1348,15 +1304,15 @@ macro_rules! impl_stableabi_for_unit_struct { $type_constr:ident, $type_name:literal, $item_info:expr - ) => ( - unsafe impl GetStaticEquivalent_ for $type_constr{ - type StaticEquivalent=$type_constr; + ) => { + unsafe impl GetStaticEquivalent_ for $type_constr { + type StaticEquivalent = $type_constr; } - unsafe impl StableAbi for $type_constr{ + unsafe impl StableAbi for $type_constr { type IsNonZeroType = False; const LAYOUT: &'static TypeLayout = { - const MONO_TYPE_LAYOUT:&MonoTypeLayout=&MonoTypeLayout::new( + const MONO_TYPE_LAYOUT: &MonoTypeLayout = &MonoTypeLayout::new( *mono_shared_vars, rstr!($type_name), $item_info, @@ -1367,7 +1323,7 @@ macro_rules! impl_stableabi_for_unit_struct { RSlice::EMPTY, ); - make_shared_vars!{ + make_shared_vars! { impl[] $type_constr; let (mono_shared_vars,shared_vars)={}; @@ -1381,39 +1337,38 @@ macro_rules! impl_stableabi_for_unit_struct { ) }; } - ) + }; } - -impl_stableabi_for_unit_struct!{ +impl_stableabi_for_unit_struct! { PhantomPinned,"PhantomPinned",ItemInfo::std_type_in(nul_str!("std::marker")) } ///////////// - unsafe impl GetStaticEquivalent_ for core_extensions::Void { - type StaticEquivalent=Self; + type StaticEquivalent = Self; } unsafe impl StableAbi for core_extensions::Void { type IsNonZeroType = False; const LAYOUT: &'static TypeLayout = { - const MONO_TYPE_LAYOUT:&MonoTypeLayout=&MonoTypeLayout::new( + const MONO_TYPE_LAYOUT: &MonoTypeLayout = &MonoTypeLayout::new( *mono_shared_vars, rstr!("Void"), - ItemInfo::package_and_mod( - "core_extensions;0.0.0", - nul_str!("core_extensions"), - ), - MonoTLData::Enum(MonoTLEnum::new(StartLen::EMPTY,RSlice::EMPTY,CompTLFields::EMPTY)), + ItemInfo::package_and_mod("core_extensions;0.0.0", nul_str!("core_extensions")), + MonoTLData::Enum(MonoTLEnum::new( + StartLen::EMPTY, + RSlice::EMPTY, + CompTLFields::EMPTY, + )), tl_genparams!(;;), ReprAttr::Int(DiscriminantRepr::U8), ModReflMode::Module, RSlice::EMPTY, ); - make_shared_vars!{ + make_shared_vars! { impl[] core_extensions::Void; let (mono_shared_vars,shared_vars)={}; @@ -1423,34 +1378,29 @@ unsafe impl StableAbi for core_extensions::Void { shared_vars, MONO_TYPE_LAYOUT, Self::ABI_CONSTS, - GenericTLData::Enum(GenericTLEnum::exhaustive( - TLDiscriminants::from_u8_slice(RSlice::EMPTY) - )), + GenericTLData::Enum(GenericTLEnum::exhaustive(TLDiscriminants::from_u8_slice( + RSlice::EMPTY, + ))), ) }; } - - ///////////// - - - /// The layout of `extern "C" fn()` and `unsafe extern "C" fn()` -macro_rules! empty_extern_fn_layout{ - ($this:ty) => ({ - make_shared_vars!{ +macro_rules! empty_extern_fn_layout { + ($this:ty) => {{ + make_shared_vars! { impl[] $this; let (mono_shared_vars,shared_vars)={}; } - const MONO_TL_EXTERN_FN:&'static MonoTypeLayout=&MonoTypeLayout::new( + const MONO_TL_EXTERN_FN: &'static MonoTypeLayout = &MonoTypeLayout::new( *mono_shared_vars, rstr!("AFunctionPointer"), make_item_info!(), MonoTLData::Opaque, - tl_genparams!(;;), + tl_genparams!(;;), ReprAttr::C, ModReflMode::Opaque, RSlice::EMPTY, @@ -1462,15 +1412,14 @@ macro_rules! empty_extern_fn_layout{ Self::ABI_CONSTS, GenericTLData::Opaque, ) - }) + }}; } - /// This is the only function type that implements StableAbi /// so as to make it more obvious that functions involving lifetimes /// cannot implement this trait directly (because of higher ranked trait bounds). unsafe impl GetStaticEquivalent_ for extern "C" fn() { - type StaticEquivalent=Self; + type StaticEquivalent = Self; } unsafe impl StableAbi for extern "C" fn() { type IsNonZeroType = True; @@ -1482,7 +1431,7 @@ unsafe impl StableAbi for extern "C" fn() { /// so as to make it more obvious that functions involving lifetimes /// cannot implement this trait directly (because of higher ranked trait bounds). unsafe impl GetStaticEquivalent_ for unsafe extern "C" fn() { - type StaticEquivalent=Self; + type StaticEquivalent = Self; } unsafe impl StableAbi for unsafe extern "C" fn() { type IsNonZeroType = True; @@ -1490,39 +1439,35 @@ unsafe impl StableAbi for unsafe extern "C" fn() { const LAYOUT: &'static TypeLayout = empty_extern_fn_layout!(unsafe extern "C" fn()); } - /// The TypeLayoutCtor of an `unsafe extern "C" fn()` -pub const UNSAFE_EXTERN_FN_LAYOUT:TypeLayoutCtor= +pub const UNSAFE_EXTERN_FN_LAYOUT: TypeLayoutCtor = GetTypeLayoutCtor::::STABLE_ABI; /// The TypeLayoutCtor of an `extern "C" fn()` -pub const EXTERN_FN_LAYOUT:TypeLayoutCtor= - GetTypeLayoutCtor::::STABLE_ABI; - +pub const EXTERN_FN_LAYOUT: TypeLayoutCtor = GetTypeLayoutCtor::::STABLE_ABI; ///////////// /// Allows one to create the `TypeLayout` for any type `T`, /// by pretending that it is a primitive type. -/// +/// /// Used by the StableAbi derive macro by fields marker as `#[sabi(unsafe_opaque_field)]`. -/// +/// /// # Safety -/// +/// /// You must ensure that the layout of `T` is compatible through other means. #[repr(transparent)] pub struct UnsafeOpaqueField(T); - unsafe impl GetStaticEquivalent_ for UnsafeOpaqueField { /// it is fine to use `()` because this type is treated as opaque anyway. - type StaticEquivalent=(); + type StaticEquivalent = (); } unsafe impl StableAbi for UnsafeOpaqueField { type IsNonZeroType = False; const LAYOUT: &'static TypeLayout = { - const MONO_TYPE_LAYOUT:&MonoTypeLayout=&MonoTypeLayout::new( + const MONO_TYPE_LAYOUT: &MonoTypeLayout = &MonoTypeLayout::new( *mono_shared_vars, rstr!("OpaqueField"), make_item_info!(), @@ -1533,7 +1478,7 @@ unsafe impl StableAbi for UnsafeOpaqueField { RSlice::EMPTY, ); - make_shared_vars!{ + make_shared_vars! { impl[T] UnsafeOpaqueField; let (mono_shared_vars,shared_vars)={}; @@ -1550,28 +1495,26 @@ unsafe impl StableAbi for UnsafeOpaqueField { /// Allows one to ensure that a `T` implements `StableAbi`, /// while storing an opaque layout instead of `::LAYOUT`. -/// +/// /// Used by the `StableAbi` derive macro by fields marker as `#[sabi(unsafe_sabi_opaque_field)]`. -/// +/// /// # Safety -/// +/// /// You must ensure that the layout of `T` is compatible through other means. #[repr(transparent)] pub struct SabiUnsafeOpaqueField(T); unsafe impl GetStaticEquivalent_ for SabiUnsafeOpaqueField { /// it is fine to use `()` because this type is treated as opaque anyway. - type StaticEquivalent=(); + type StaticEquivalent = (); } -unsafe impl StableAbi for SabiUnsafeOpaqueField +unsafe impl StableAbi for SabiUnsafeOpaqueField where - T:StableAbi + T: StableAbi, { type IsNonZeroType = False; - const LAYOUT: &'static TypeLayout = { - >::LAYOUT - }; + const LAYOUT: &'static TypeLayout = { >::LAYOUT }; } ///////////// diff --git a/abi_stable/src/const_utils.rs b/abi_stable/src/const_utils.rs index 0f60d7c9..704c3116 100644 --- a/abi_stable/src/const_utils.rs +++ b/abi_stable/src/const_utils.rs @@ -4,17 +4,14 @@ Utilities for const contexts. use crate::std_types::RStr; -pub use abi_stable_shared::const_utils::{ - low_bit_mask_u64, -}; - +pub use abi_stable_shared::const_utils::low_bit_mask_u64; ////////////////////////////////////////////////////////////////// // Used to test trait bounds in proc-macros. #[doc(hidden)] -pub trait AssocStr{ - const STR:RStr<'static>; +pub trait AssocStr { + const STR: RStr<'static>; } macro_rules! impl_assoc_str { @@ -27,14 +24,14 @@ macro_rules! impl_assoc_str { ) } -impl_assoc_str!{ i8,i16,i32,i64,isize,u8,u16,u32,u64,usize } +impl_assoc_str! { i8,i16,i32,i64,isize,u8,u16,u32,u64,usize } ////////////////////////////////////////////////////////////////// // Used to test trait bounds in proc-macros. #[doc(hidden)] -pub trait AssocInt{ - const NUM:usize; +pub trait AssocInt { + const NUM: usize; } macro_rules! impl_assoc_str { @@ -47,17 +44,13 @@ macro_rules! impl_assoc_str { ) } -impl_assoc_str!{ +impl_assoc_str! { i8=0,i16=1,i32=2,i64=3,isize=4, u8=5,u16=6,u32=7,u64=8,usize=9, } - - - ////////////////////////////////////// - /// Creates an empty slice. pub const fn empty_slice<'a, T>() -> &'a [T] where @@ -75,77 +68,71 @@ where const EMPTY: &'a [T] = &[]; } - ////////////////////////////////////// - /// The minimum of two `u64`s -pub const fn min_u8(l:u8,r:u8)->u8{ - [r,l][ (l < r)as usize ] +pub const fn min_u8(l: u8, r: u8) -> u8 { + [r, l][(l < r) as usize] } /// The minimum of two `u64`s -pub const fn min_u16(l:u16,r:u16)->u16{ - [r,l][ (l < r)as usize ] +pub const fn min_u16(l: u16, r: u16) -> u16 { + [r, l][(l < r) as usize] } /// The minimum of two `u64`s -pub const fn min_u64(l:u64,r:u64)->u64{ - [r,l][ (l < r)as usize ] +pub const fn min_u64(l: u64, r: u64) -> u64 { + [r, l][(l < r) as usize] } /// The minimum of two `usize`s -pub const fn min_usize(l:usize,r:usize)->usize{ - [r,l][ (l < r)as usize ] +pub const fn min_usize(l: usize, r: usize) -> usize { + [r, l][(l < r) as usize] } /// The maximum of two `u64`s -pub const fn max_u64(l:u64,r:u64)->u64{ - [l,r][ (l < r)as usize ] +pub const fn max_u64(l: u64, r: u64) -> u64 { + [l, r][(l < r) as usize] } /// The maximum of two `usize`s -pub const fn max_usize(l:usize,r:usize)->usize{ - [l,r][ (l < r)as usize ] +pub const fn max_usize(l: usize, r: usize) -> usize { + [l, r][(l < r) as usize] } /// The minimum and maximum of two `usize`s -pub const fn min_max_usize(l:usize,r:usize)->(usize,usize){ - [(r,l),(l,r)][(l < r)as usize] +pub const fn min_max_usize(l: usize, r: usize) -> (usize, usize) { + [(r, l), (l, r)][(l < r) as usize] } - - ////////////////////////////////////// /// Gets the absolute value of a usize subtraction. -pub const fn abs_sub_usize(l:usize,r:usize)->usize{ - let (min,max)=min_max_usize(l,r); - max-min +pub const fn abs_sub_usize(l: usize, r: usize) -> usize { + let (min, max) = min_max_usize(l, r); + max - min } ////////////////////////////////////// /// Saturating substraction of `usize`s. -pub const fn saturating_sub_usize(l:usize,r:usize)->usize{ +pub const fn saturating_sub_usize(l: usize, r: usize) -> usize { let mask = -((r < l) as isize); l.wrapping_sub(r) & (mask as usize) } /// Saturating substraction of `u8`s. -pub const fn saturating_sub_u8(l:u8,r:u8)->u8{ +pub const fn saturating_sub_u8(l: u8, r: u8) -> u8 { let mask = -((r < l) as i8); l.wrapping_sub(r) & (mask as u8) } /// The base 2 logarithm of a usize. -pub const fn log2_usize(n:usize)->u8{ - const USIZE_BITS:u8=(std::mem::size_of::()*8)as u8; - saturating_sub_u8(USIZE_BITS-n.leading_zeros() as u8,1)as u8 +pub const fn log2_usize(n: usize) -> u8 { + const USIZE_BITS: u8 = (std::mem::size_of::() * 8) as u8; + saturating_sub_u8(USIZE_BITS - n.leading_zeros() as u8, 1) as u8 } - - ////////////////////////////////////// /// Allows converting between `Copy` generic types that are the same concrete type. @@ -156,47 +143,46 @@ pub const fn log2_usize(n:usize)->u8{ /// since both types are required to be the same concrete type inside the macro. #[macro_export] macro_rules! type_identity { - ($from:ty=>$to:ty; $expr:expr ) => {unsafe{ - let _:$crate::pmr::AssertEq<$from,$to>; + ($from:ty=>$to:ty; $expr:expr ) => { + unsafe { + let _: $crate::pmr::AssertEq<$from, $to>; - $crate::utils::Transmuter::<$from,$to>{ from:$expr } - .to - }} + $crate::utils::Transmuter::<$from, $to> { from: $expr }.to + } + }; } ////////////////////////////////////// - #[cfg(test)] -mod tests{ +mod tests { use super::*; - const USIZE_BITS:u8=(std::mem::size_of::()*8)as u8; + const USIZE_BITS: u8 = (std::mem::size_of::() * 8) as u8; #[test] - fn abs_sub_test(){ + fn abs_sub_test() { for p in 0..USIZE_BITS { - let n=1usize<`. @@ -99,7 +99,7 @@ impl Direction{ ### Unions -It's not possible to add fields to unions,this is not currently possible +It's not possible to add fields to unions,this is not currently possible because the original author of`abi_stable` didn't see any need for it (if you need it create an issue for it). @@ -119,7 +119,7 @@ since they might not guarantee any of these properties: which could cause undefined behavior if passed between dynamic libraries, or just be unpredictable. -The potential dependence on global state is why `abi_stable` uses dynamic dispatch +The potential dependence on global state is why `abi_stable` uses dynamic dispatch for all the types it wraps in `abi_stable::external_types` # abi_stable specific @@ -129,4 +129,4 @@ If you add StableAbi types to abi_stable,make sure to add them to the list of ty (the crate is in testing/version_compatibility/interface/) -*/ \ No newline at end of file +*/ diff --git a/abi_stable/src/docs/prefix_types.rs b/abi_stable/src/docs/prefix_types.rs index 104a66b6..8c110e22 100644 --- a/abi_stable/src/docs/prefix_types.rs +++ b/abi_stable/src/docs/prefix_types.rs @@ -1,6 +1,6 @@ /*! -Prefix-types are types that derive StableAbi along with the +Prefix-types are types that derive StableAbi along with the `#[sabi(kind(Prefix(....)))]` helper attribute. This is mostly intended for **vtables** and **modules**. @@ -15,10 +15,10 @@ To convert `Foo` to `Foo_Ref` you can use any of (non-exhaustive list): - `prefix_type::WithMetadata::new`:
Use this if you need a compiletime constant.
- First create a `StaticRef>` constant using + First create a `StaticRef>` constant using the [`staticref`] macro, then construct a `Foo_Ref` constant with `Foo_Ref(THE_STATICREF_CONSTANT.as_prefix())`.
- There are two examples of this, + There are two examples of this, [for modules](#module_construction),and [for vtables](#vtable_construction) @@ -30,22 +30,22 @@ accessor methods named the same as the fields. ### Adding fields To ensure that libraries stay abi compatible, -the first minor version of the library must use the `#[sabi(last_prefix_field)]` attribute on some +the first minor version of the library must use the `#[sabi(last_prefix_field)]` attribute on some field, and every minor version after that must add fields at the end (never moving that attribute). Changing the field that `#[sabi(last_prefix_field)]` is applied to is a breaking change. Getter methods for fields after the one to which `#[sabi(last_prefix_field)]` was applied to -will return `Option` by default,because those fields might not exist +will return `Option` by default,because those fields might not exist (the struct might come from a previous version of the library). To override how to deal with nonexistent fields, use the `#[sabi(missing_field())]` attribute, applied to either the struct or the field. -### Alignment +### Alignment -To ensure that users can define empty vtables/modules that can be extended in +To ensure that users can define empty vtables/modules that can be extended in semver compatible versions, -this library forces the struct converted to ffi-safe form to have an alignment at +this library forces the struct converted to ffi-safe form to have an alignment at least that of usize. You must ensure that newer versions don't change the alignment of the struct, @@ -53,12 +53,12 @@ because that makes it ABI incompatible. # Grammar Reference -For the grammar reference,you can look at the documentation for +For the grammar reference,you can look at the documentation for [`#[derive(StableAbi)]`](../../derive.StableAbi.html). # Examples -### Example 1 +### Example 1 Declaring a Prefix-type. @@ -91,8 +91,8 @@ In this example: - `#[sabi(kind(Prefix(prefix_ref="Module_Ref")))]` declares this type as being a prefix-type with an ffi-safe pointer called `Module_Ref` to which `Module` can be converted into. -- `#[sabi(missing_field(panic))]` - makes the field accessors panic when attempting to +- `#[sabi(missing_field(panic))]` + makes the field accessors panic when attempting to access nonexistent fields instead of the default of returning an Option. - `#[sabi(last_prefix_field)]`means that it is the last field in the struct @@ -122,7 +122,7 @@ fn main(){ assert_eq!(MODULE_REF.elapsed()(1000), RDuration::from_secs(1)); assert_eq!(MODULE_REF.description().as_str(), "this is a module field"); - + } #[repr(C)] @@ -147,7 +147,7 @@ impl Module { elapsed, description: RStr::from_str("this is a module field"), }, - )); + )); } @@ -173,7 +173,7 @@ use abi_stable::{ StableAbi, }; -fn main(){ +fn main(){ unsafe { let vtable = MakeVTable::::MAKE; assert_eq!( @@ -203,7 +203,7 @@ pub struct VTable { // A dummy struct, used purely for its associated constants. struct MakeVTable(T); -impl MakeVTable +impl MakeVTable where T: Copy + Into { @@ -226,7 +226,7 @@ where -### Example 2:Declaring a type with a VTable +### Example 2:Declaring a type with a VTable Here is the implementation of a Box-like type,which uses a vtable that is a prefix type. @@ -251,7 +251,7 @@ use abi_stable::{ #[derive(StableAbi)] pub struct BoxLike { data: *mut T, - + vtable: BoxVtable_Ref, _marker: PhantomData, @@ -261,7 +261,7 @@ pub struct BoxLike { impl BoxLike{ pub fn new(value:T)->Self{ let box_=Box::new(value); - + Self{ data:Box::into_raw(box_), vtable: BoxVtable::VTABLE, @@ -320,25 +320,25 @@ impl Drop for BoxLike{ // `#[sabi(kind(Prefix))]` Declares this type as being a prefix-type, // generating both of these types: -// -// - BoxVTable_Prefix`: A struct with the fields up to (and including) the field with the +// +// - BoxVTable_Prefix`: A struct with the fields up to (and including) the field with the // `#[sabi(last_prefix_field)]` attribute. -// +// // - BoxVTable_Ref`: An ffi-safe pointer to a `BoxVtable`, with methods to get // `BoxVtable`'s fields. -// +// #[repr(C)] #[derive(StableAbi)] #[sabi(kind(Prefix))] pub(crate) struct BoxVtable { - /// The `#[sabi(last_prefix_field)]` attribute here means that this is - /// the last field in this struct that was defined in the + /// The `#[sabi(last_prefix_field)]` attribute here means that this is + /// the last field in this struct that was defined in the /// first compatible version of the library /// (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), /// requiring new fields to always be added after it. - /// - /// The `#[sabi(last_prefix_field)]` attribute would stay on this field until the library + /// + /// The `#[sabi(last_prefix_field)]` attribute would stay on this field until the library /// bumps its "major" version, /// at which point it would be moved to the last field at the time. /// @@ -382,7 +382,7 @@ unsafe extern "C" fn destroy_box(v: *mut T, call_drop: CallReferentDrop) { ``` -### Example 3:module +### Example 3:module This declares,initializes,and uses a module. @@ -397,25 +397,25 @@ use abi_stable::{ // `#[sabi(kind(Prefix))]` Declares this type as being a prefix-type, // generating both of these types: -// -// - PersonMod_Prefix`: A struct with the fields up to (and including) the field with the +// +// - PersonMod_Prefix`: A struct with the fields up to (and including) the field with the // `#[sabi(last_prefix_field)]` attribute. -// +// // - PersonMod_Ref`: // An ffi-safe pointer to a `PersonMod`,with methods to get`PersonMod`'s fields. -// +// #[repr(C)] #[derive(StableAbi)] #[sabi(kind(Prefix))] pub struct PersonMod { - /// The `#[sabi(last_prefix_field)]` attribute here means that this is - /// the last field in this struct that was defined in the + /// The `#[sabi(last_prefix_field)]` attribute here means that this is + /// the last field in this struct that was defined in the /// first compatible version of the library /// (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), /// requiring new fields to always be added below preexisting ones. - /// - /// The `#[sabi(last_prefix_field)]` attribute would stay on this field until the library + /// + /// The `#[sabi(last_prefix_field)]` attribute would stay on this field until the library /// bumps its "major" version, /// at which point it would be moved to the last field at the time. /// @@ -434,7 +434,7 @@ pub struct PersonMod { // The getter for this field returns `default_score()` if the field doesn't exist. #[sabi(missing_field(with="default_score"))] pub score: extern "C" fn(Id)->u32, - + // The getter for this field returns `Default::default()` if the field doesn't exist. #[sabi(missing_field(default))] pub visit_length: Option< extern "C" fn(Id)->RDuration >, @@ -461,7 +461,7 @@ type Id=u32; # fn customer_for(id:Id)->RDuration{ # VARS[id as usize].0 # } -# +# # #[sabi_extern_fn] # fn bike_count(id:Id)->u32{ # VARS[id as usize].1 @@ -501,10 +501,10 @@ const MODULE: PersonMod_Ref = PersonMod_Ref(_MODULE_WM_.static_as_prefix()); // Getting the value for every field of `MODULE`. -let customer_for: extern "C" fn(Id)->RDuration = +let customer_for: extern "C" fn(Id)->RDuration = MODULE.customer_for(); -let bike_count: Optionu32> = +let bike_count: Optionu32> = MODULE.bike_count(); let visits: extern "C" fn(Id)->u32= diff --git a/abi_stable/src/docs/sabi_nonexhaustive.rs b/abi_stable/src/docs/sabi_nonexhaustive.rs index 785dedce..863a2d97 100644 --- a/abi_stable/src/docs/sabi_nonexhaustive.rs +++ b/abi_stable/src/docs/sabi_nonexhaustive.rs @@ -1,18 +1,18 @@ /*! -Using the `#[sabi(kind(WithNonExhaustive(...)))]` helper attribute for +Using the `#[sabi(kind(WithNonExhaustive(...)))]` helper attribute for `#[derive(StableAbi)]` allows you to store the enum in `NonExhaustive`, using it as a non-exhaustive enum across ffi. -The enum can then be wrapped in a +The enum can then be wrapped in a [`NonExhaustive<>`](../../nonexhaustive_enum/struct.NonExhaustive.html), but can only be converted back into it if the discriminant is valid in that context. Nonexhaustive enums can safely add variants in minor versions, giving library authors some flexibility in their design. -# Items +# Items These are the items relevant to nonexhaustive enums: @@ -39,7 +39,7 @@ and usable with it afterwards # Parameters -These are the required and optional parameters for the +These are the required and optional parameters for the `#[sabi(kind(WithNonExhaustive(...)))]` helper attribute. ### Specifying alignment (optional parameter) @@ -71,7 +71,7 @@ It is a bad idea to use `Enum` since its size is allowed to change.
### Traits (optional parameter) -Specifies the traits required when constructing NonExhaustive from this enum and +Specifies the traits required when constructing NonExhaustive from this enum and usable after constructing it. If neither this parameter nor interface are specified, @@ -116,7 +116,7 @@ These are the valid traits: ### Interface (optional parameter) -This allows using a pre-existing to specify which traits are +This allows using a pre-existing to specify which traits are required when constructing `NonExhaustive<>` from this enum and are then usable with it. The type describes which traits are required using the [`InterfaceType`] trait. @@ -135,7 +135,7 @@ This means that only Debug/PartialEq are usable/required.
Example3:`interface="CloneEqInterface"`. This means that only Debug/Clone/Eq/PartialEq are usable/required.
-The `*Interface` types from the examples come from the +The `*Interface` types from the examples come from the `abi_stable::erased_types::interfaces` module. @@ -159,7 +159,7 @@ Example:`assert_nonexhaustive("Foo","Foo>")`
# `serde` support -`NonExhaustive` only implements serde::{Serialize,Deserialize} +`NonExhaustive` only implements serde::{Serialize,Deserialize} if Interface allows them in its [`InterfaceType`] implementation, and also implements the [`SerializeEnum`] and [`DeserializeEnum`] traits. @@ -167,7 +167,7 @@ and also implements the [`SerializeEnum`] and [`DeserializeEnum`] traits. This defines a nonexhaustive enum and demonstrates how it is (de)serialized. -For a more realistic example you can look at the +For a more realistic example you can look at the "examples/2_nonexhaustive/interface" crate in the repository for this crate. ``` @@ -196,7 +196,7 @@ use serde::{Deserialize,Serialize}; )))] // The `#[sabi(with_constructor)]` helper attribute here generates constructor functions // that look take the fields of the variant as parameters and return a `ValidTag_NE`. -#[sabi(with_constructor)] +#[sabi(with_constructor)] pub enum ValidTag{ #[doc(hidden)] __NonExhaustive, @@ -228,7 +228,7 @@ impl SerializeEnum for ValidTag_Interface { Module::VALUE .serialize_tag()(this) .into_result() - + } } @@ -283,26 +283,26 @@ assert_eq!( # } // In this struct: -// +// // - `#[sabi(kind(Prefix))]` // Declares this type as being a prefix-type, generating both of these types: -// -// - Module_Prefix`: A struct with the fields up to (and including) the field with the +// +// - Module_Prefix`: A struct with the fields up to (and including) the field with the // `#[sabi(last_prefix_field)]` attribute. -// +// // - Module_Ref`: An ffi-safe pointer to a `Module`,with methods to get `Module`'s fields. -// -// - `#[sabi(missing_field(panic))]` -// makes the field accessors of `ModuleRef` panic when attempting to +// +// - `#[sabi(missing_field(panic))]` +// makes the field accessors of `ModuleRef` panic when attempting to // access nonexistent fields instead of the default of returning an Option. -// +// #[repr(C)] -#[derive(StableAbi)] +#[derive(StableAbi)] #[sabi(kind(Prefix))] #[sabi(missing_field(panic))] pub struct Module{ pub serialize_tag:extern "C" fn(&ValidTag_NE)->RResult, - + /// `#[sabi(last_prefix_field)]`means that it is the last field in the struct /// that was defined in the first compatible version of the library /// (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), @@ -317,7 +317,7 @@ impl Module { // // StaticRef represents a reference to data that lives forever, // but is not necessarily `'static` according to the type system. - // + // // StaticRef not necessary in this case, it's more useful with generic types.. abi_stable::staticref!(const TMP0: WithMetadata = WithMetadata::new( PrefixTypeTrait::METADATA, @@ -337,7 +337,7 @@ impl Module { #[sabi_extern_fn] pub fn serialize_tag(enum_:&ValidTag_NE)->RResult{ let enum_=rtry!( enum_.as_enum().into_c() ); - + match serde_json::to_string(&enum_) { Ok(v)=>{ RawValueBox::try_from_string(v) @@ -396,13 +396,13 @@ pub enum Message{ #[sabi(with_boxed_constructor)] Custom(RBox), - + //////////////////////////////////////// // Available since 1.1 //////////////////////////////////////// #[sabi(with_boxed_constructor)] SaysThankYou(RBox) - + } @@ -430,8 +430,8 @@ pub struct SaysThankYou{ } # fn main(){ - -// Constructing Message::Custom wrapped in a NonExhaustive + +// Constructing Message::Custom wrapped in a NonExhaustive { let custom_message:Message_NE= Message::Custom_NE("Hello".into()); @@ -446,7 +446,7 @@ pub struct SaysThankYou{ } -// Constructing Message::SaysThankYou wrapped in a NonExhaustive +// Constructing Message::SaysThankYou wrapped in a NonExhaustive // This variant is only available since 1.1 { let says_thank_you:Message_NE= @@ -591,9 +591,9 @@ Say that we want to define a "private" enum used internally to send information between instances of the same library, of potentially different (compatible) versions. -If one of the variants from newer versions are sent into a library/binary +If one of the variants from newer versions are sent into a library/binary that has a previous version of `Event`, -`Event_NE` (an alias for NonExhaustive wrapping an Event) +`Event_NE` (an alias for NonExhaustive wrapping an Event) won't be convertible back into `Event`. ``` @@ -636,7 +636,7 @@ pub enum Event{ RemovedInstance{ object_id:ObjectId, }, - + ///////////////// // Added in 1.1 ///////////////// @@ -652,7 +652,7 @@ pub enum Event{ object_id:ObjectId, group_id:GroupId, }, - + ///////////////// // Added in 1.2 ///////////////// @@ -785,4 +785,4 @@ let groupid_1=GroupId(0); [`SerializeEnum`]: ../../nonexhaustive_enum/trait.SerializeEnum.html [`DeserializeEnum`]: ../../nonexhaustive_enum/trait.DeserializeEnum.html -*/ \ No newline at end of file +*/ diff --git a/abi_stable/src/docs/sabi_trait_inherent.rs b/abi_stable/src/docs/sabi_trait_inherent.rs index 8aac7a33..cc8901c4 100644 --- a/abi_stable/src/docs/sabi_trait_inherent.rs +++ b/abi_stable/src/docs/sabi_trait_inherent.rs @@ -11,7 +11,7 @@ annotated with the [`sabi_trait`] attribute macro". pub trait Action: Debug { /// Gets the current value of `self`. fn get(&self) -> usize; - + /// Adds `val` into `self`, returning the new value. fn add_mut(&mut self, val: usize) -> usize; @@ -50,12 +50,12 @@ impl<'lt, ErasedPtr, …> Trait_TO<'lt, ErasedPtr, …> { pub fn from_ptr( pointer: Ptr, can_it_downcast: Downcasting - ) -> Self + ) -> Self ``` Constructs `_TO` from a pointer to a type that implements `` -The `can_it_downcast` parameter describes whether the trait object can be +The `can_it_downcast` parameter describes whether the trait object can be converted back into the original type or not.
Its possible values are [`TD_CanDowncast`] and [`TD_Opaque`]. @@ -89,7 +89,7 @@ use abi_stable::{ // From a reference { // `Action_TO`s constructed from `&` are `Action_TO<'_, RRef<'_, ()>>` - // since `&T` can't soundly be transmuted back and forth into `&()` + // since `&T` can't soundly be transmuted back and forth into `&()` let object: Action_TO<'static, RRef<'static, ()>> = Action_TO::from_ptr(&20_usize, TD_CanDowncast); @@ -101,7 +101,7 @@ use abi_stable::{ let mut val = 30_usize; // `Action_TO`s constructed from `&mut` are `Action_TO<'_, RMut<'_, ()>>` - // since `&mut T` can't soundly be transmuted back and forth into `&mut ()` + // since `&mut T` can't soundly be transmuted back and forth into `&mut ()` let mut object: Action_TO<'static, RMut<'_, ()>> = Action_TO::from_ptr(&mut val, TD_CanDowncast); @@ -132,13 +132,13 @@ impl<'lt, …> Trait_TO<'lt, RBox<()>, …> { pub fn from_value<_OrigPtr, Downcasting>( pointer: _OrigPtr, can_it_downcast: Downcasting - ) -> Self + ) -> Self ``` Constructs `_TO` from a type that implements ``, wrapping that value in an [`RBox`]. -The `can_it_downcast` parameter describes whether the trait object can be +The `can_it_downcast` parameter describes whether the trait object can be converted back into the original type or not.
Its possible values are [`TD_CanDowncast`] and [`TD_Opaque`]. @@ -176,13 +176,13 @@ impl<'lt, 'sub, …> Trait_TO<'lt, RRef<'sub, ()>, …> { pointer: &'sub T, can_it_downcast: Downcasting, vtable_for: …, - ) -> Self + ) -> Self ``` Const-constructs `_TO` from a constant that implements ``, -The `can_it_downcast` parameter describes whether the trait object can be +The `can_it_downcast` parameter describes whether the trait object can be converted back into the original type or not.
Its possible values are [`TD_CanDowncast`] and [`TD_Opaque`]. @@ -199,7 +199,7 @@ use abi_stable::{ type_level::downcasting::TD_CanDowncast, }; -const TO: Action_CTO<'_, '_> = +const TO: Action_CTO<'_, '_> = Action_TO::from_const( &200, TD_CanDowncast, @@ -215,7 +215,7 @@ assert_eq!(TO.get(), 200); ```text impl<'lt, ErasedPtr, …> Trait_TO<'lt, ErasedPtr, …> { - pub fn from_sabi(obj: Trait_Backend<'lt, ErasedPtr, …>) -> Self + pub fn from_sabi(obj: Trait_Backend<'lt, ErasedPtr, …>) -> Self ``` Constructs `_TO` from the backend trait object type, @@ -241,7 +241,7 @@ use abi_stable::{ type_level::downcasting::TD_CanDowncast, }; -let mut object: Action_TO<'static, RBox<()>> = +let mut object: Action_TO<'static, RBox<()>> = Action_TO::from_value(700, TD_CanDowncast); @@ -362,7 +362,7 @@ assert_eq!(add_mut(object.sabi_reborrow_mut(), 10), 416); assert_eq!(add_mut(object, 20), 436); -fn add_mut

(mut x: Action_TO<'_, P>, how_much: usize) -> usize +fn add_mut

(mut x: Action_TO<'_, P>, how_much: usize) -> usize where // Needed for calling mutable methods on `Action_TO` P: AsMutPtr @@ -400,4 +400,4 @@ where [`TD_Opaque`]: ../../type_level/downcasting/struct.TD_Opaque.html -*/ \ No newline at end of file +*/ diff --git a/abi_stable/src/docs/troubleshooting.rs b/abi_stable/src/docs/troubleshooting.rs index 3c053f34..1a2215b2 100644 --- a/abi_stable/src/docs/troubleshooting.rs +++ b/abi_stable/src/docs/troubleshooting.rs @@ -4,7 +4,7 @@ Here are some problems and their solutions # Opaque compiletime errors -As of writing this section,having `extern fn` in a type definition causes +As of writing this section,having `extern fn` in a type definition causes compile-time errors for `#[derive(StableAbi)]` to look like this ```text @@ -12,7 +12,7 @@ error: unknown lifetime ``` ẁhere it doesn't point at what the cause of the error is. -To fix this,replace `extern fn` with `extern "C" fn` +To fix this,replace `extern fn` with `extern "C" fn` and the error message will look like this: ```text @@ -25,4 +25,4 @@ error: unknown lifetime -*/ \ No newline at end of file +*/ diff --git a/abi_stable/src/docs/unsafe_code_guidelines.rs b/abi_stable/src/docs/unsafe_code_guidelines.rs index 42f34b75..84b54e29 100644 --- a/abi_stable/src/docs/unsafe_code_guidelines.rs +++ b/abi_stable/src/docs/unsafe_code_guidelines.rs @@ -14,7 +14,7 @@ Any method that needs it calls vtable functions to do the allocation/deallocatio # Relating to global constructors in dynamic libraries -It is unsound to do load a library developed with abi_stable or +It is unsound to do load a library developed with abi_stable or checking the layout of types with `abi_stable::abi_stability::check_layout_compatibility` in global constructors, because `abi_stable` relies on initializing its global global state in the binary @@ -25,4 +25,4 @@ It is **safe** however to use anything else from `abi_stable` in global construc "Global constructor" is any code that runs before any library symbol can be loaded, including those of abi_stable modules. -*/ \ No newline at end of file +*/ diff --git a/abi_stable/src/erased_types.rs b/abi_stable/src/erased_types.rs index 363150e1..8a0da864 100644 --- a/abi_stable/src/erased_types.rs +++ b/abi_stable/src/erased_types.rs @@ -8,22 +8,19 @@ use std::{ hash::{Hash, Hasher}, }; - use serde::{Serialize, Serializer}; use crate::{ - traits::{IntoReprC, IntoReprRust}, std_types::{ - RBoxError, RCmpOrdering, RErr, ROk, ROption,RResult, RString,RStr, - RSlice, RSliceMut + RBoxError, RCmpOrdering, RErr, ROk, ROption, RResult, RSlice, RSliceMut, RStr, RString, }, + traits::{IntoReprC, IntoReprRust}, }; - #[macro_use] mod enabled_traits_macro; -pub(crate)mod c_functions; +pub(crate) mod c_functions; /// Types that implement `InterfaceType`, used in examples. pub mod interfaces; @@ -45,27 +42,20 @@ pub(crate) mod traits; pub use crate::DynTrait; pub use self::{ - dyn_trait::{ - DynTraitBound, - GetVWInterface, - UneraseError, - }, - vtable::{ InterfaceBound,VTableDT }, + dyn_trait::{DynTraitBound, GetVWInterface, UneraseError}, traits::{ - ImplType, InterfaceType, - DeserializeDyn, - SerializeImplType, SerializeProxyType, - IteratorItem,IteratorItemOrDefault, + DeserializeDyn, ImplType, InterfaceType, IteratorItem, IteratorItemOrDefault, + SerializeImplType, SerializeProxyType, }, type_info::TypeInfo, + vtable::{InterfaceBound, VTableDT}, }; #[doc(hidden)] pub use self::vtable::GetVtable; #[doc(no_inline)] -pub use crate::type_level::downcasting::{TD_CanDowncast,TD_Opaque}; - +pub use crate::type_level::downcasting::{TD_CanDowncast, TD_Opaque}; /// The formatting mode for all std::fmt formatters. /// diff --git a/abi_stable/src/erased_types/c_functions.rs b/abi_stable/src/erased_types/c_functions.rs index af8e882c..1e43ffdb 100644 --- a/abi_stable/src/erased_types/c_functions.rs +++ b/abi_stable/src/erased_types/c_functions.rs @@ -2,20 +2,17 @@ use std::{ fmt, - io::{self,Write as IoWrite,Read,BufRead}, - ptr, - mem, + io::{self, BufRead, Read, Write as IoWrite}, + mem, ptr, }; use super::*; use crate::{ marker_type::ErasedObject, - sabi_types::{RRef, RMut}, - std_types::{ - RIoError,RSeekFrom, - }, - pointer_trait::{GetPointerKind,PK_SmartPointer,PK_Reference,PK_MutReference}, + pointer_trait::{GetPointerKind, PK_MutReference, PK_Reference, PK_SmartPointer}, + sabi_types::{RMut, RRef}, + std_types::{RIoError, RSeekFrom}, }; use core_extensions::utils::transmute_ignore_size; @@ -39,18 +36,15 @@ pub(crate) unsafe fn adapt_std_fmt( fmt::Display::fmt(&*buf, formatter) } - - -pub(crate) unsafe extern "C" fn drop_pointer_impl(this: RMut<'_, ErasedPtr>){ +pub(crate) unsafe extern "C" fn drop_pointer_impl(this: RMut<'_, ErasedPtr>) { extern_fn_panic_handling! { let this=this.transmute_into_mut::(); ptr::drop_in_place(this); } } - -pub(crate) unsafe extern "C" fn clone_pointer_impl( - this: RRef<'_, ErasedPtr> +pub(crate) unsafe extern "C" fn clone_pointer_impl( + this: RRef<'_, ErasedPtr>, ) -> ErasedPtr where OrigP: Clone, @@ -62,7 +56,6 @@ where } } - //////////////////////////////////////////////////// /* @@ -71,43 +64,41 @@ only requiring `std::default::Default` for `PK_SmartPointer` because it is the only one for which `DynTrait::default` can be called. */ -pub trait DefaultImpl{ - fn default_impl()->Self; +pub trait DefaultImpl { + fn default_impl() -> Self; } impl DefaultImpl for This -where - Self:Default +where + Self: Default, { - fn default_impl()->Self{ + fn default_impl() -> Self { Default::default() } } -impl DefaultImpl for This{ - fn default_impl()->Self{ +impl DefaultImpl for This { + fn default_impl() -> Self { unreachable!("This should not be called in DynTrait::default") } } -impl DefaultImpl for This{ - fn default_impl()->Self{ +impl DefaultImpl for This { + fn default_impl() -> Self { unreachable!("This should not be called in DynTrait::default") } } - -pub(crate) unsafe extern "C" fn default_pointer_impl() -> ErasedPtr +pub(crate) unsafe extern "C" fn default_pointer_impl() -> ErasedPtr where - OrigP:GetPointerKind, - OrigP:DefaultImpl<::Kind>, + OrigP: GetPointerKind, + OrigP: DefaultImpl<::Kind>, { extern_fn_panic_handling! { transmute_ignore_size( OrigP::default_impl() ) } } - ///////////// pub(crate) unsafe extern "C" fn display_impl( @@ -157,15 +148,15 @@ where } } -pub(crate) unsafe extern "C" fn serialize_impl<'s,T,I>( - this: RRef<'s, ErasedObject> +pub(crate) unsafe extern "C" fn serialize_impl<'s, T, I>( + this: RRef<'s, ErasedObject>, ) -> RResult<>::Proxy, RBoxError> where - T: for<'borr> SerializeImplType<'borr,Interface=I>, + T: for<'borr> SerializeImplType<'borr, Interface = I>, I: for<'borr> SerializeProxyType<'borr>, { extern_fn_panic_handling! { - let ret: RResult<>::Proxy, RBoxError> = + let ret: RResult<>::Proxy, RBoxError> = this .transmute_into_ref::() .serialize_impl() @@ -177,7 +168,7 @@ where pub(crate) unsafe extern "C" fn partial_eq_impl( this: RRef<'_, ErasedObject>, - other: RRef<'_, ErasedObject> + other: RRef<'_, ErasedObject>, ) -> bool where T: PartialEq, @@ -204,7 +195,7 @@ where } pub(crate) unsafe extern "C" fn partial_cmp_ord( - this: RRef<'_, ErasedObject>, + this: RRef<'_, ErasedObject>, other: RRef<'_, ErasedObject>, ) -> ROption where @@ -240,8 +231,7 @@ pub(crate) unsafe extern "C" fn hash_Hash( pub(crate) unsafe extern "C" fn hash_slice_Hasher( this: RMut<'_, ErasedObject>, slic_: RSlice<'_, u8>, -) -where +) where T: Hasher, { extern_fn_panic_handling! { @@ -264,12 +254,12 @@ where //// fmt ////////////////////////////////////////////////////////////////////////////////////// - pub(super) unsafe extern "C" fn write_str_fmt_write( - this:RMut<'_, ErasedObject>, - data:RStr<'_> + this: RMut<'_, ErasedObject>, + data: RStr<'_>, ) -> RResult<(), ()> -where T:fmt::Write, +where + T: fmt::Write, { extern_fn_panic_handling! { let this=unsafe{ this.transmute_into_mut::() }; @@ -280,67 +270,56 @@ where T:fmt::Write, } } - ////////////////////////////////////////////////////////////////////////////////////// //// io ////////////////////////////////////////////////////////////////////////////////////// - - #[inline] -fn convert_io_result(res:io::Result)->RResult +fn convert_io_result(res: io::Result) -> RResult where - T:Into + T: Into, { match res { - Ok(v)=>ROk(v.into()), - Err(e)=>RErr(RIoError::from(e)), + Ok(v) => ROk(v.into()), + Err(e) => RErr(RIoError::from(e)), } } - /////////////////////////// - #[repr(C)] -#[derive(StableAbi)] -#[derive(Copy,Clone)] -pub struct IoWriteFns{ - pub(super) write: - unsafe extern "C" fn ( - RMut<'_, ErasedObject>, - buf: RSlice<'_,u8> - ) -> RResult, +#[derive(StableAbi, Copy, Clone)] +pub struct IoWriteFns { + pub(super) write: unsafe extern "C" fn( + RMut<'_, ErasedObject>, + buf: RSlice<'_, u8>, + ) -> RResult, pub(super) write_all: - unsafe extern "C" fn ( - RMut<'_, ErasedObject>, - buf: RSlice<'_,u8> - ) -> RResult<(),RIoError>, + unsafe extern "C" fn(RMut<'_, ErasedObject>, buf: RSlice<'_, u8>) -> RResult<(), RIoError>, - pub(super) flush:unsafe extern "C" fn (RMut<'_, ErasedObject>) -> RResult<(),RIoError>, + pub(super) flush: unsafe extern "C" fn(RMut<'_, ErasedObject>) -> RResult<(), RIoError>, } - pub(super) struct MakeIoWriteFns(W); impl MakeIoWriteFns where - W:IoWrite + W: IoWrite, { - pub(super) const NEW:IoWriteFns=IoWriteFns{ - write:io_Write_write::, - write_all:io_Write_write_all::, - flush:io_Write_flush::, + pub(super) const NEW: IoWriteFns = IoWriteFns { + write: io_Write_write::, + write_all: io_Write_write_all::, + flush: io_Write_flush::, }; } - pub(super) unsafe extern "C" fn io_Write_write( - this:RMut<'_, ErasedObject>, - buf: RSlice<'_,u8> -) -> RResult -where W:IoWrite + this: RMut<'_, ErasedObject>, + buf: RSlice<'_, u8>, +) -> RResult +where + W: IoWrite, { extern_fn_panic_handling! { let this=this.transmute_into_mut::(); @@ -350,10 +329,11 @@ where W:IoWrite } pub(super) unsafe extern "C" fn io_Write_write_all( - this:RMut<'_, ErasedObject>, - buf: RSlice<'_,u8> -) -> RResult<(),RIoError> -where W:IoWrite + this: RMut<'_, ErasedObject>, + buf: RSlice<'_, u8>, +) -> RResult<(), RIoError> +where + W: IoWrite, { extern_fn_panic_handling! { let this=this.transmute_into_mut::(); @@ -362,8 +342,11 @@ where W:IoWrite } } -pub(super) unsafe extern "C" fn io_Write_flush( this:RMut<'_, ErasedObject> ) -> RResult<(),RIoError> -where W:IoWrite +pub(super) unsafe extern "C" fn io_Write_flush( + this: RMut<'_, ErasedObject>, +) -> RResult<(), RIoError> +where + W: IoWrite, { extern_fn_panic_handling! { let this=this.transmute_into_mut::(); @@ -372,40 +355,36 @@ where W:IoWrite } } - /////////////////////////// - #[repr(C)] -#[derive(StableAbi)] -#[derive(Copy,Clone)] -pub struct IoReadFns{ +#[derive(StableAbi, Copy, Clone)] +pub struct IoReadFns { pub(super) read: - unsafe extern "C" fn(RMut<'_, ErasedObject>,RSliceMut<'_,u8>) -> RResult, + unsafe extern "C" fn(RMut<'_, ErasedObject>, RSliceMut<'_, u8>) -> RResult, pub(super) read_exact: - unsafe extern "C" fn(RMut<'_, ErasedObject>,RSliceMut<'_,u8>) -> RResult<(),RIoError>, + unsafe extern "C" fn(RMut<'_, ErasedObject>, RSliceMut<'_, u8>) -> RResult<(), RIoError>, } - pub(super) struct MakeIoReadFns(W); impl MakeIoReadFns where - W:io::Read + W: io::Read, { - pub(super) const NEW:IoReadFns=IoReadFns{ - read:io_Read_read::, - read_exact:io_Read_read_exact::, + pub(super) const NEW: IoReadFns = IoReadFns { + read: io_Read_read::, + read_exact: io_Read_read_exact::, }; } - pub(super) unsafe extern "C" fn io_Read_read( - this:RMut<'_, ErasedObject>, - buf: RSliceMut<'_,u8> -) -> RResult -where R:Read + this: RMut<'_, ErasedObject>, + buf: RSliceMut<'_, u8>, +) -> RResult +where + R: Read, { extern_fn_panic_handling! { let this=this.transmute_into_mut::(); @@ -414,12 +393,12 @@ where R:Read } } - pub(super) unsafe extern "C" fn io_Read_read_exact( - this:RMut<'_, ErasedObject>, - buf: RSliceMut<'_,u8> -) -> RResult<(),RIoError> -where R:Read + this: RMut<'_, ErasedObject>, + buf: RSliceMut<'_, u8>, +) -> RResult<(), RIoError> +where + R: Read, { extern_fn_panic_handling! { let this=this.transmute_into_mut::(); @@ -430,34 +409,32 @@ where R:Read /////////////////////////// - #[repr(C)] -#[derive(StableAbi)] -#[derive(Copy,Clone)] -pub struct IoBufReadFns{ +#[derive(StableAbi, Copy, Clone)] +pub struct IoBufReadFns { pub(super) fill_buf: - unsafe extern "C" fn(RMut<'_, ErasedObject>) -> RResult,RIoError>, + unsafe extern "C" fn(RMut<'_, ErasedObject>) -> RResult, RIoError>, - pub(super) consume:unsafe extern "C" fn(RMut<'_, ErasedObject>,usize) + pub(super) consume: unsafe extern "C" fn(RMut<'_, ErasedObject>, usize), } - pub(super) struct MakeIoBufReadFns(W); impl MakeIoBufReadFns where - W:io::BufRead + W: io::BufRead, { - pub(super) const NEW:IoBufReadFns=IoBufReadFns{ - fill_buf:io_BufRead_fill_buf::, - consume:io_BufRead_consume::, + pub(super) const NEW: IoBufReadFns = IoBufReadFns { + fill_buf: io_BufRead_fill_buf::, + consume: io_BufRead_consume::, }; } pub(super) unsafe extern "C" fn io_BufRead_fill_buf( - this:RMut<'_, ErasedObject>, -) -> RResult,RIoError> -where R:BufRead + this: RMut<'_, ErasedObject>, +) -> RResult, RIoError> +where + R: BufRead, { extern_fn_panic_handling! { let this=this.transmute_into_mut::(); @@ -469,12 +446,9 @@ where R:BufRead } } - -pub(super) unsafe extern "C" fn io_BufRead_consume( - this:RMut<'_, ErasedObject>, - amount: usize -)where - R:BufRead +pub(super) unsafe extern "C" fn io_BufRead_consume(this: RMut<'_, ErasedObject>, amount: usize) +where + R: BufRead, { extern_fn_panic_handling! { let this=this.transmute_into_mut::(); @@ -483,16 +457,14 @@ pub(super) unsafe extern "C" fn io_BufRead_consume( } } - /////////////////////////// - pub(super) unsafe extern "C" fn io_Seek_seek( - this:RMut<'_, ErasedObject>, - seek_from:RSeekFrom, -) -> RResult -where - S:io::Seek + this: RMut<'_, ErasedObject>, + seek_from: RSeekFrom, +) -> RResult +where + S: io::Seek, { extern_fn_panic_handling! { let this=unsafe{ this.transmute_into_mut::() }; diff --git a/abi_stable/src/erased_types/dyn_trait.rs b/abi_stable/src/erased_types/dyn_trait.rs index ae4f13a0..7666de5a 100644 --- a/abi_stable/src/erased_types/dyn_trait.rs +++ b/abi_stable/src/erased_types/dyn_trait.rs @@ -14,15 +14,14 @@ use serde::{de, ser, Deserialize, Deserializer}; use crate::{ abi_stability::StableAbi, + marker_type::{ErasedObject, NonOwningPhantom, UnsafeIgnoredType}, pointer_trait::{ - AsPtr, AsMutPtr, - CanTransmuteElement, TransmuteElement, OwnedPointer, - GetPointerKind, PK_SmartPointer, PK_Reference, PointerKind, + AsMutPtr, AsPtr, CanTransmuteElement, GetPointerKind, OwnedPointer, PK_Reference, + PK_SmartPointer, PointerKind, TransmuteElement, }, prefix_type::PrefixRef, - marker_type::{ErasedObject, NonOwningPhantom, UnsafeIgnoredType}, - sabi_types::{MovePtr, RRef, RMut}, - std_types::{RBox, RStr, RVec, RIoError}, + sabi_types::{MovePtr, RMut, RRef}, + std_types::{RBox, RIoError, RStr, RVec}, type_level::{ downcasting::{TD_CanDowncast, TD_Opaque}, impl_enum::{Implemented, Unimplemented}, @@ -33,44 +32,41 @@ use crate::{ #[allow(unused_imports)] use crate::std_types::Tuple2; -use super::*; use super::{ c_functions::adapt_std_fmt, trait_objects::*, + traits::{DeserializeDyn, GetSerializeProxyType, InterfaceFor}, vtable::{GetVtable, VTable_Ref}, - traits::{InterfaceFor, DeserializeDyn, GetSerializeProxyType}, - IteratorItemOrDefault, + IteratorItemOrDefault, *, }; - // #[cfg(test)] -#[cfg(all(test, not(feature ="only_new_tests")))] +#[cfg(all(test, not(feature = "only_new_tests")))] mod tests; mod priv_ { use super::*; - /// DynTrait implements ffi-safe trait objects, for a selection of traits. - /// + /// /// # Passing opaque values around with `DynTrait<_>` - /// + /// /// One can pass non-StableAbi types around by using type erasure, using this type. - /// + /// /// It generally looks like `DynTrait<'borrow, Pointer<()>, Interface>`, where: - /// + /// /// - `'borrow` is the borrow that the type that was erased had. - /// + /// /// - `Pointer` is a pointer type that implements [`AsPtr`]. - /// - /// - `Interface` is an [`InterfaceType`], which describes what traits are + /// + /// - `Interface` is an [`InterfaceType`], which describes what traits are /// required when constructing the `DynTrait<_>` and which ones it implements. - /// - /// The [`InterfaceType`] trait allows describing which traits are required + /// + /// The [`InterfaceType`] trait allows describing which traits are required /// when constructing a `DynTrait<_>`, and which ones it implements. - /// - /// ### Construction - /// + /// + /// ### Construction + /// /// To construct a `DynTrait<_>` one can use these associated functions: /// /// - [`from_value`](#method.from_value): @@ -86,114 +82,114 @@ mod priv_ { /// /// - [`from_any_ptr`](#method.from_any_ptr) /// Can be constructed from a pointer of a value.Requires a `'static` value. - /// + /// /// - [`from_borrowing_value`](#method.from_borrowing_value): /// Can be constructed from the value directly.Cannot unerase the DynTrait afterwards. /// /// - [`from_borrowing_ptr`](#method.from_borrowing_ptr) /// Can be constructed from a pointer of a value.Cannot unerase the DynTrait afterwards. - /// + /// /// DynTrait uses the impls of the value in methods, /// which means that the pointer itself does not have to implement those traits, - /// - /// ### Trait object - /// - /// `DynTrait<'borrow, Pointer<()>, Interface>` - /// can be used as a trait object for any combination of + /// + /// ### Trait object + /// + /// `DynTrait<'borrow, Pointer<()>, Interface>` + /// can be used as a trait object for any combination of /// the traits listed below. - /// + /// /// These are the traits: - /// + /// /// - Send - /// + /// /// - Sync - /// + /// /// - Iterator - /// + /// /// - DoubleEndedIterator - /// + /// /// - std::fmt::Write - /// + /// /// - std::io::Write - /// + /// /// - std::io::Seek - /// + /// /// - std::io::Read - /// + /// /// - std::io::BufRead - /// - /// - Clone - /// - /// - Display - /// - /// - Debug - /// + /// + /// - Clone + /// + /// - Display + /// + /// - Debug + /// /// - std::error::Error - /// + /// /// - Default: Can be called as an inherent method. - /// - /// - Eq - /// - /// - PartialEq - /// - /// - Ord - /// - /// - PartialOrd - /// - /// - Hash - /// + /// + /// - Eq + /// + /// - PartialEq + /// + /// - Ord + /// + /// - PartialOrd + /// + /// - Hash + /// /// - serde::Deserialize: /// first deserializes from a string, and then calls the objects' Deserialize impl. - /// + /// /// - serde::Serialize: /// first calls the objects' Deserialize impl, then serializes that as a string. - /// - /// ### Deconstruction - /// + /// + /// ### Deconstruction + /// /// `DynTrait<_>` can then be unwrapped into a concrete type, /// within the same dynamic library/executable that constructed it, /// using these (fallible) conversion methods: - /// + /// /// - [`downcast_into_impltype`](#method.downcast_into_impltype): /// Unwraps into a pointer to `T`. - /// Where `DynTrait, Interface>`'s + /// Where `DynTrait, Interface>`'s /// Interface must equal `::Interface` - /// + /// /// - [`downcast_as_impltype`](#method.downcast_as_impltype): /// Unwraps into a `&T`. - /// Where `DynTrait, Interface>`'s + /// Where `DynTrait, Interface>`'s /// Interface must equal `::Interface` - /// + /// /// - [`downcast_as_mut_impltype`](#method.downcast_as_mut_impltype): /// Unwraps into a `&mut T`. - /// Where `DynTrait, Interface>`'s + /// Where `DynTrait, Interface>`'s /// Interface must equal `::Interface` - /// + /// /// - [`downcast_into`](#method.downcast_into): /// Unwraps into a pointer to `T`.Requires `T:'static`. - /// + /// /// - [`downcast_as`](#method.downcast_as): /// Unwraps into a `&T`.Requires `T:'static`. - /// + /// /// - [`downcast_as_mut`](#method.downcast_as_mut): /// Unwraps into a `&mut T`.Requires `T:'static`. - /// - /// - /// `DynTrait` cannot be converted back if it was created + /// + /// + /// `DynTrait` cannot be converted back if it was created /// using `DynTrait::from_borrowing_*`. - /// + /// /// # Passing DynTrait between dynamic libraries - /// - /// Passing DynTrait between dynamic libraries + /// + /// Passing DynTrait between dynamic libraries /// (as in between the dynamic libraries directly loaded by the same binary/dynamic library) - /// may cause the program to panic at runtime with an error message stating that + /// may cause the program to panic at runtime with an error message stating that /// the trait is not implemented for the specific interface. - /// + /// /// This can only happen if you are passing DynTrait between dynamic libraries, /// or if DynTrait was instantiated in the parent passed to a child, /// a DynTrait instantiated in a child dynamic library passed to the parent /// should not cause a panic, it would be a bug. - /// + /// /// ```text /// binary /// _________|___________ @@ -201,28 +197,28 @@ mod priv_ { /// | | | /// lib00 lib10 lib20 /// ``` - /// - /// In this diagram passing a DynTrait constructed in lib00 to anything other than + /// + /// In this diagram passing a DynTrait constructed in lib00 to anything other than /// the binary or lib0 will cause the panic to happen if: - /// + /// /// - The [`InterfaceType`] requires extra traits in the version of the Interface /// that lib1 and lib2 know about (that the binary does not require). - /// - /// - lib1 or lib2 attempt to call methods that require the traits that were added + /// + /// - lib1 or lib2 attempt to call methods that require the traits that were added /// to the [`InterfaceType`], in versions of that interface that only they know about. - /// - /// - /// - /// - /// # serializing/deserializing DynTraits - /// + /// + /// + /// + /// + /// # serializing/deserializing DynTraits + /// /// To be able to serialize and deserialize a DynTrait, /// the interface it uses must implement [`SerializeProxyType`] and [`DeserializeDyn`], /// and the implementation type must implement `SerializeImplType`. - /// - /// For a more realistic example you can look at the + /// + /// For a more realistic example you can look at the /// "examples/0_modules_and_interface_types" crates in the repository for this crate. - /// + /// /// ``` /// use abi_stable::{ /// StableAbi, @@ -239,62 +235,62 @@ mod priv_ { /// std_types::{RBox, RStr, RBoxError, RResult, ROk, RErr}, /// traits::IntoReprC, /// }; - /// - /// + /// + /// /// ////////////////////////////////// /// //// In interface crate ///// /// ////////////////////////////////// - /// - /// + /// + /// /// use serde::{Deserialize, Serialize}; - /// + /// /// /// An `InterfaceType` describing which traits are implemented by FooInterfaceBox. /// #[repr(C)] /// #[derive(StableAbi)] /// #[sabi(impl_InterfaceType(Sync, Debug, Clone, Serialize, Deserialize, PartialEq))] /// pub struct FooInterface; - /// + /// /// /// The state passed to most functions in the TextOpsMod module. /// pub type FooInterfaceBox = DynTrait<'static, RBox<()>, FooInterface>; - /// - /// - /// /// First ::serialize_impl returns + /// + /// + /// /// First ::serialize_impl returns /// /// a RawValueBox containing the serialized data, /// /// then the returned RawValueBox is serialized. /// impl<'s> SerializeProxyType<'s> for FooInterface{ /// type Proxy = RawValueBox; /// } - /// - /// + /// + /// /// impl<'borr> DeserializeDyn<'borr, FooInterfaceBox> for FooInterface { /// type Proxy = RawValueRef<'borr>; - /// + /// /// fn deserialize_dyn(s: RawValueRef<'borr>) -> Result { /// MODULE /// .deserialize_foo()(s.get_rstr()) /// .into_result() /// } /// } - /// - /// + /// + /// /// // `#[sabi(kind(Prefix))]` declares this type as being a prefix-type, /// // generating both of these types:
- /// // + /// // /// // - Module_Prefix`: - /// // A struct with the fields up to (and including) the field with the + /// // A struct with the fields up to (and including) the field with the /// // `#[sabi(last_prefix_field)]` attribute. /// // - /// // - Module_Ref`: + /// // - Module_Ref`: /// // An ffi-safe pointer to a `Module`, with methods to get `Module`'s fields. /// #[repr(C)] - /// #[derive(StableAbi)] + /// #[derive(StableAbi)] /// #[sabi(kind(Prefix))] /// #[sabi(missing_field(panic))] /// pub struct Module{ /// #[sabi(last_prefix_field)] /// pub deserialize_foo:extern "C" fn(s:RStr<'_>)->RResult, /// } - /// + /// /// // This is how ffi-safe pointers to non-generic prefix types are constructed /// // at compile-time. /// const MODULE: Module_Ref = { @@ -304,30 +300,30 @@ mod priv_ { /// deserialize_foo, /// } /// ); - /// + /// /// Module_Ref(S.static_as_prefix()) /// }; - /// - /// + /// + /// /// ///////////////////////////////////////////////////////////////////////////////////////// /// //// In implementation crate (the one that gets compiled as a dynamic library) ///// /// ///////////////////////////////////////////////////////////////////////////////////////// - /// - /// + /// + /// /// #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] /// pub struct Foo{ /// name:String, /// } - /// + /// /// impl ImplType for Foo { /// type Interface = FooInterface; - /// + /// /// const INFO: &'static TypeInfo = impl_get_type_info! { Foo }; /// } - /// + /// /// impl<'s> SerializeImplType<'s> for Foo { /// type Interface = FooInterface; - /// + /// /// fn serialize_impl(&'s self) -> Result { /// match serde_json::to_string(self) { /// Ok(v) =>{ @@ -338,7 +334,7 @@ mod priv_ { /// } /// } /// } - /// + /// /// #[sabi_extern_fn] /// pub fn deserialize_foo(s:RStr<'_>)->RResult{ /// match serde_json::from_str::(s.into()) { @@ -346,10 +342,10 @@ mod priv_ { /// Err(e) => RErr(RBoxError::new(e)), /// } /// } - /// - /// + /// + /// /// # /* - /// #[test] + /// #[test] /// fn testing_serialization_deserialization() { /// # */ fn main() { /// let foo = Foo{name:"nope".into()}; @@ -368,40 +364,40 @@ mod priv_ { /// serde_json::to_string(&object).unwrap(), /// r##"{"name":"nope"}"## /// ); - /// + /// /// } - /// + /// /// ``` - /// - /// - /// + /// + /// + /// /// # Examples - /// - /// ### In the Readme - /// + /// + /// ### In the Readme + /// /// The primary example using `DynTrait<_>` is in the readme. - /// - /// Readme is in + /// + /// Readme is in /// [the repository for this crate](https://github.com/rodrimati1992/abi_stable_crates), /// [crates.io](https://crates.io/crates/abi_stable), /// [lib.rs](https://lib.rs/crates/abi_stable). - /// - /// - /// ### Comparing DynTraits - /// + /// + /// + /// ### Comparing DynTraits + /// /// This is only possible if the erased types don't contain borrows, /// and they are not constructed using `DynTrait::from_borrowing_*` methods. - /// + /// /// DynTraits wrapping different pointer types can be compared with each other, /// it simply uses the values' implementation of PartialEq. - /// + /// /// ``` /// use abi_stable::{ /// DynTrait, RRef, RMut, /// erased_types::interfaces::PartialEqInterface, /// std_types::{RArc, RBox}, /// }; - /// + /// /// { /// // `DynTrait`s constructed from `&` are `DynTrait<'_, RRef<'_, ()>, _>` /// // since `&T` can't soundly be transmuted back and forth into `&()` @@ -413,137 +409,137 @@ mod priv_ { /// // since `&mut T` can't soundly be transmuted back and forth into `&mut ()` /// let right: DynTrait<'static, RMut<'_, ()>, PartialEqInterface> = /// DynTrait::from_any_ptr(&mut n100, PartialEqInterface); - /// + /// /// assert_eq!(left, right); /// } /// { /// let left: DynTrait<'static, RBox<()>, _> = /// DynTrait::from_any_value(200, PartialEqInterface); - /// + /// /// let right: DynTrait<'static, RArc<()>, _> = /// DynTrait::from_any_ptr(RArc::new(200), PartialEqInterface); - /// + /// /// assert_eq!(left, right); /// } - /// + /// /// ``` - /// - /// ### Writing to a DynTrait - /// + /// + /// ### Writing to a DynTrait + /// /// This is an example of using the `write!()` macro with DynTrait. - /// + /// /// ``` /// use abi_stable::{ /// DynTrait, RMut, /// erased_types::interfaces::FmtWriteInterface, /// }; - /// + /// /// use std::fmt::Write; - /// + /// /// let mut buffer = String::new(); - /// + /// /// let mut wrapped: DynTrait<'static, RMut<'_, ()>, FmtWriteInterface> = /// DynTrait::from_any_ptr(&mut buffer, FmtWriteInterface); - /// + /// /// write!(wrapped, "Foo").unwrap(); /// write!(wrapped, "Bar").unwrap(); /// write!(wrapped, "Baz").unwrap(); - /// + /// /// drop(wrapped); - /// + /// /// assert_eq!(&buffer[..], "FooBarBaz"); - /// - /// + /// + /// /// ``` - /// - /// - /// ### Iteration - /// + /// + /// + /// ### Iteration + /// /// Using `DynTrait` as an `Iterator` and `DoubleEndedIterator`. - /// + /// /// ``` /// use abi_stable::{ /// DynTrait, /// erased_types::interfaces::DEIteratorInterface, /// }; - /// + /// /// let mut wrapped = DynTrait::from_any_value(0..=10, DEIteratorInterface::NEW); - /// + /// /// assert_eq!( /// wrapped.by_ref().take(5).collect::>(), /// vec![0, 1, 2, 3, 4] /// ); - /// + /// /// assert_eq!( /// wrapped.rev().collect::>(), /// vec![10, 9, 8, 7, 6, 5] /// ); - /// - /// + /// + /// /// ``` - /// - /// + /// + /// /// # Making pointers compatible with DynTrait - /// - /// To make pointers compatible with DynTrait, they must imlement the + /// + /// To make pointers compatible with DynTrait, they must imlement the /// `abi_stable::pointer_trait::{GetPointerKind, AsPtr, AsMutPtr, CanTransmuteElement}` /// traits as shown in the example. - /// + /// /// `GetPointerKind` should generally be implemented with `type Kind = PK_SmartPointer`. /// The exception is in the case that it is a `#[repr(transparent)]` /// wrapper around a [`RRef`]/[`RMut`]/`*const T`/`*mut T`/[`NonNull`], - /// in which case it should implement `GetPointerKind` + /// in which case it should implement `GetPointerKind` /// (when it has shared reference semantics) /// or `GetPointerKind` /// (when it has mutable reference semantics). - /// - /// ### Example - /// + /// + /// ### Example + /// /// This is an example of a newtype wrapping an `RBox`, - /// demonstrating that the pointer type doesn't have to implement + /// demonstrating that the pointer type doesn't have to implement /// the traits in the [`InterfaceType`], it's the value it points to. - /// - /// ```rust + /// + /// ```rust /// /// use abi_stable::DynTrait; - /// + /// /// fn main(){ /// let lines = "line0\nline1\nline2"; /// let mut iter = NewtypeBox::new(lines.lines()); - /// + /// /// // The type annotation here is just to show the type, it's not necessary. /// let mut wrapper: DynTrait<'_, NewtypeBox<()>, IteratorInterface> = /// DynTrait::from_borrowing_ptr(iter, IteratorInterface); - /// - /// // You can clone the DynTrait! + /// + /// // You can clone the DynTrait! /// let clone = wrapper.clone(); - /// + /// /// assert_eq!(wrapper.next(), Some("line0")); /// assert_eq!(wrapper.next(), Some("line1")); /// assert_eq!(wrapper.next(), Some("line2")); /// assert_eq!(wrapper.next(), None); - /// + /// /// assert_eq!( /// clone.rev().collect::>(), /// /// vec!["line2", "line1", "line0"], /// ) - /// + /// /// } - /// + /// /// #[repr(C)] /// #[derive(StableAbi)] /// #[sabi(impl_InterfaceType(Sync, Send, Iterator, DoubleEndedIterator, Clone, Debug))] /// pub struct IteratorInterface; - /// + /// /// impl<'a> IteratorItem<'a> for IteratorInterface{ /// type Item = &'a str; /// } - /// + /// /// ///////////////////////////////////////// - /// + /// /// use std::ops::{Deref, DerefMut}; - /// + /// /// use abi_stable::{ /// StableAbi, /// InterfaceType, @@ -556,13 +552,13 @@ mod priv_ { /// }, /// type_level::bools::True, /// }; - /// + /// /// #[repr(transparent)] /// #[derive(Default, Clone, StableAbi)] /// pub struct NewtypeBox{ /// box_:RBox, /// } - /// + /// /// impl NewtypeBox{ /// pub fn new(value:T)->Self{ /// Self{ @@ -570,47 +566,47 @@ mod priv_ { /// } /// } /// } - /// + /// /// unsafe impl GetPointerKind for NewtypeBox{ /// // This is a smart pointer because `RBox` is one. /// type Kind = PK_SmartPointer; /// type PtrTarget = T; /// } - /// + /// /// // safety: Does not create an intermediate `&T` to get a pointer to `T`. /// unsafe impl AsPtr for NewtypeBox { /// fn as_ptr(&self) -> *const T { /// self.box_.as_ptr() /// } /// } - /// + /// /// // safety: Does not create an intermediate `&mut T` to get a pointer to `T` /// unsafe impl AsMutPtr for NewtypeBox { /// fn as_mut_ptr(&mut self) -> *mut T { /// self.box_.as_mut_ptr() /// } /// } - /// + /// /// // safety: /// // NewtypeBox is safe to transmute, because RBox (the pointer type it wraps) /// // is safe to transmute /// unsafe impl CanTransmuteElement for NewtypeBox { /// type TransmutedPtr = NewtypeBox; - /// + /// /// unsafe fn transmute_element_(self) -> Self::TransmutedPtr { /// let box_: RBox = self.box_.transmute_element_(); /// NewtypeBox{box_} /// } /// } - /// + /// /// ``` - /// + /// /// [`AsPtr`]: ./pointer_trait/trait.AsPtr.html /// [`InterfaceType`]: ./trait.InterfaceType.html /// [`NonNull`]: https://doc.rust-lang.org/std/ptr/struct.NonNull.html /// [`SerializeProxyType`]: ./erased_types/trait.SerializeProxyType.html /// [`DeserializeDyn`]: ./erased_types/trait.DeserializeDyn.html - /// + /// #[repr(C)] #[derive(StableAbi)] #[sabi( @@ -619,19 +615,18 @@ mod priv_ { bound ="VTable_Ref<'borr, P, I>:StableAbi", extra_checks ="::EXTRA_CHECKS", )] - pub struct DynTrait<'borr, P, I, EV =()> + pub struct DynTrait<'borr, P, I, EV = ()> where - P:GetPointerKind + P: GetPointerKind, { pub(super) object: ManuallyDrop

, vtable: VTable_Ref<'borr, P, I>, - extra_value:EV, - _marker:NonOwningPhantom<(I, RStr<'borr>)>, - _marker2:UnsafeIgnoredType>, - + extra_value: EV, + _marker: NonOwningPhantom<(I, RStr<'borr>)>, + _marker2: UnsafeIgnoredType>, } - impl DynTrait<'static, RRef<'static, ()>,()> { + impl DynTrait<'static, RRef<'static, ()>, ()> { /// Constructs the `DynTrait<_>` from a `T:ImplType`. /// /// Use this whenever possible instead of `from_any_value`, @@ -645,11 +640,11 @@ mod priv_ { /// std_types::RBox, /// DynTrait, ImplType, StableAbi, /// }; - /// + /// /// fn main() { - /// let to: DynTrait<'static, RBox<()>, FooInterface> = + /// let to: DynTrait<'static, RBox<()>, FooInterface> = /// DynTrait::from_value(Foo(10u32)); - /// + /// /// assert_eq!(format!("{:?}", to), "Foo(10)"); /// } /// @@ -663,7 +658,7 @@ mod priv_ { /// /// const INFO: &'static TypeInfo = abi_stable::impl_get_type_info!(Foo); /// } - /// + /// /// /// An `InterfaceType` describing which traits are implemented by FooInterfaceBox. /// #[repr(C)] /// #[derive(StableAbi)] @@ -676,7 +671,7 @@ mod priv_ { where T: ImplType, T::Interface: InterfaceBound, - T: GetVtable<'static, T, RBox<()>, RBox,::Interface>, + T: GetVtable<'static, T, RBox<()>, RBox, ::Interface>, { let object = RBox::new(object); DynTrait::from_ptr(object) @@ -696,13 +691,13 @@ mod priv_ { /// DynTrait, RRef, RMut, /// ImplType, StableAbi, /// }; - /// + /// /// fn main() { /// // Constructing a DynTrait from a `&T` /// { /// // `DynTrait`s constructed from `&` are `DynTrait<'_, RRef<'_, ()>, _>` /// // since `&T` can't soundly be transmuted back and forth into `&()` - /// let rref: DynTrait<'static, RRef<'_, ()>, FooInterface> = + /// let rref: DynTrait<'static, RRef<'_, ()>, FooInterface> = /// DynTrait::from_ptr(&Foo(10u32)); /// /// assert_eq!(format!("{:?}", rref), "Foo(10)"); @@ -712,21 +707,21 @@ mod priv_ { /// let mmut = &mut Foo(20u32); /// // `DynTrait`s constructed from `&mut` are `DynTrait<'_, RMut<'_, ()>, _>` /// // since `&mut T` can't soundly be transmuted back and forth into `&mut ()` - /// let rmut: DynTrait<'static, RMut<'_, ()>, FooInterface> = + /// let rmut: DynTrait<'static, RMut<'_, ()>, FooInterface> = /// DynTrait::from_ptr(mmut); /// /// assert_eq!(format!("{:?}", rmut), "Foo(20)"); /// } /// // Constructing a DynTrait from a `RBox` /// { - /// let boxed: DynTrait<'static, RBox<()>, FooInterface> = + /// let boxed: DynTrait<'static, RBox<()>, FooInterface> = /// DynTrait::from_ptr(RBox::new(Foo(30u32))); /// /// assert_eq!(format!("{:?}", boxed), "Foo(30)"); /// } /// // Constructing a DynTrait from an `RArc` /// { - /// let arc: DynTrait<'static, RArc<()>, FooInterface> = + /// let arc: DynTrait<'static, RArc<()>, FooInterface> = /// DynTrait::from_ptr(RArc::new(Foo(30u32))); /// /// assert_eq!(format!("{:?}", arc), "Foo(30)"); @@ -743,7 +738,7 @@ mod priv_ { /// /// const INFO: &'static TypeInfo = abi_stable::impl_get_type_info!(Foo); /// } - /// + /// /// /// An `InterfaceType` describing which traits are implemented by FooInterfaceBox. /// #[repr(C)] /// #[derive(StableAbi)] @@ -760,13 +755,11 @@ mod priv_ { P: GetPointerKind + CanTransmuteElement<()>, { DynTrait { - object: unsafe{ - ManuallyDrop::new(object.transmute_element::<()>()) - }, + object: unsafe { ManuallyDrop::new(object.transmute_element::<()>()) }, vtable: T::_GET_INNER_VTABLE, - extra_value:(), - _marker:NonOwningPhantom::NEW, - _marker2:UnsafeIgnoredType::DEFAULT, + extra_value: (), + _marker: NonOwningPhantom::NEW, + _marker2: UnsafeIgnoredType::DEFAULT, } } @@ -780,27 +773,27 @@ mod priv_ { /// std_types::RBox, /// DynTrait, /// }; - /// - /// + /// + /// /// // DebugDisplayInterface is `Debug + Display + Sync + Send` - /// let to: DynTrait<'static, RBox<()>, DebugDisplayInterface> = + /// let to: DynTrait<'static, RBox<()>, DebugDisplayInterface> = /// DynTrait::from_any_value(3u8, DebugDisplayInterface); - /// + /// /// assert_eq!(format!("{}", to), "3"); /// assert_eq!(format!("{:?}", to), "3"); /// /// ``` - pub fn from_any_value(object: T, interface:I) -> DynTrait<'static, RBox<()>, I> + pub fn from_any_value(object: T, interface: I) -> DynTrait<'static, RBox<()>, I> where - T:'static, + T: 'static, I: InterfaceBound, - InterfaceFor : GetVtable<'static, T, RBox<()>, RBox, I>, + InterfaceFor: GetVtable<'static, T, RBox<()>, RBox, I>, { let object = RBox::new(object); DynTrait::from_any_ptr(object, interface) } - /// Constructs the `DynTrait<_>` from a pointer to a + /// Constructs the `DynTrait<_>` from a pointer to a /// type that doesn't borrow anything. /// /// # Example @@ -816,9 +809,9 @@ mod priv_ { /// { /// // `DynTrait`s constructed from `&` are `DynTrait<'_, RRef<'_, ()>, _>` /// // since `&T` can't soundly be transmuted back and forth into `&()` - /// let rref: DynTrait<'static, RRef<'_, ()>, DebugDisplayInterface> = + /// let rref: DynTrait<'static, RRef<'_, ()>, DebugDisplayInterface> = /// DynTrait::from_any_ptr(&21i32, DebugDisplayInterface); - /// + /// /// assert_eq!(format!("{:?}", rref), "21"); /// assert_eq!(format!("{}", rref), "21"); /// } @@ -827,50 +820,48 @@ mod priv_ { /// let mmut = &mut "hello"; /// // `DynTrait`s constructed from `&mut` are `DynTrait<'_, RMut<'_, ()>, _>` /// // since `&mut T` can't soundly be transmuted back and forth into `&mut ()` - /// let rmut: DynTrait<'static, RMut<'_, ()>, DebugDisplayInterface> = + /// let rmut: DynTrait<'static, RMut<'_, ()>, DebugDisplayInterface> = /// DynTrait::from_any_ptr(mmut, DebugDisplayInterface); - /// + /// /// assert_eq!(format!("{:?}", rmut), r#""hello""#); /// assert_eq!(format!("{}", rmut), "hello"); /// } /// // Constructing a DynTrait from a `RBox` /// { - /// let boxed: DynTrait<'static, RBox<()>, DebugDisplayInterface> = + /// let boxed: DynTrait<'static, RBox<()>, DebugDisplayInterface> = /// DynTrait::from_any_ptr(RBox::new(false), DebugDisplayInterface); - /// + /// /// assert_eq!(format!("{:?}", boxed), "false"); /// assert_eq!(format!("{}", boxed), "false"); /// } /// // Constructing a DynTrait from an `RArc` /// { - /// let arc: DynTrait<'static, RArc<()>, DebugDisplayInterface> = + /// let arc: DynTrait<'static, RArc<()>, DebugDisplayInterface> = /// DynTrait::from_any_ptr(RArc::new(30u32), DebugDisplayInterface); - /// + /// /// assert_eq!(format!("{:?}", arc), "30"); /// } /// /// ``` pub fn from_any_ptr( object: P, - _interface:I + _interface: I, ) -> DynTrait<'static, P::TransmutedPtr, I> where I: InterfaceBound, - T:'static, + T: 'static, InterfaceFor: GetVtable<'static, T, P::TransmutedPtr, P, I>, P: GetPointerKind + CanTransmuteElement<()>, { DynTrait { - object: unsafe{ - ManuallyDrop::new(object.transmute_element::<()>()) - }, + object: unsafe { ManuallyDrop::new(object.transmute_element::<()>()) }, vtable: >::_GET_INNER_VTABLE, - extra_value:(), - _marker:NonOwningPhantom::NEW, - _marker2:UnsafeIgnoredType::DEFAULT, + extra_value: (), + _marker: NonOwningPhantom::NEW, + _marker2: UnsafeIgnoredType::DEFAULT, } } - + /// Constructs the `DynTrait<_>` from a value with a `'borr` borrow. /// /// Cannot unerase the DynTrait afterwards. @@ -883,12 +874,12 @@ mod priv_ { /// std_types::RBox, /// DynTrait, /// }; - /// - /// + /// + /// /// // DebugDisplayInterface is `Debug + Display + Sync + Send` - /// let to: DynTrait<'static, RBox<()>, DebugDisplayInterface> = + /// let to: DynTrait<'static, RBox<()>, DebugDisplayInterface> = /// DynTrait::from_borrowing_value(3u8, DebugDisplayInterface); - /// + /// /// assert_eq!(format!("{}", to), "3"); /// assert_eq!(format!("{:?}", to), "3"); /// @@ -900,12 +891,12 @@ mod priv_ { /// ``` pub fn from_borrowing_value<'borr, T, I>( object: T, - interface:I, + interface: I, ) -> DynTrait<'borr, RBox<()>, I> where - T:'borr, + T: 'borr, I: InterfaceBound, - InterfaceFor : GetVtable<'borr, T, RBox<()>, RBox, I>, + InterfaceFor: GetVtable<'borr, T, RBox<()>, RBox, I>, { let object = RBox::new(object); DynTrait::from_borrowing_ptr(object, interface) @@ -929,9 +920,9 @@ mod priv_ { /// { /// // `DynTrait`s constructed from `&` are `DynTrait<'_, RRef<'_, ()>, _>` /// // since `&T` can't soundly be transmuted back and forth into `&()` - /// let rref: DynTrait<'_, RRef<'_, ()>, DebugDisplayInterface> = + /// let rref: DynTrait<'_, RRef<'_, ()>, DebugDisplayInterface> = /// DynTrait::from_borrowing_ptr(&34i32, DebugDisplayInterface); - /// + /// /// assert_eq!(format!("{:?}", rref), "34"); /// assert_eq!(format!("{}", rref), "34"); /// } @@ -940,25 +931,25 @@ mod priv_ { /// let mmut = &mut "world"; /// // `DynTrait`s constructed from `&mut` are `DynTrait<'_, RMut<'_, ()>, _>` /// // since `&mut T` can't soundly be transmuted back and forth into `&mut ()` - /// let rmut: DynTrait<'_, RMut<'_, ()>, DebugDisplayInterface> = + /// let rmut: DynTrait<'_, RMut<'_, ()>, DebugDisplayInterface> = /// DynTrait::from_borrowing_ptr(mmut, DebugDisplayInterface); - /// + /// /// assert_eq!(format!("{:?}", rmut), r#""world""#); /// assert_eq!(format!("{}", rmut), "world"); /// } /// // Constructing a DynTrait from a `RBox` /// { - /// let boxed: DynTrait<'_, RBox<()>, DebugDisplayInterface> = + /// let boxed: DynTrait<'_, RBox<()>, DebugDisplayInterface> = /// DynTrait::from_borrowing_ptr(RBox::new(true), DebugDisplayInterface); - /// + /// /// assert_eq!(format!("{:?}", boxed), "true"); /// assert_eq!(format!("{}", boxed), "true"); /// } /// // Constructing a DynTrait from an `RArc` /// { - /// let arc: DynTrait<'_, RArc<()>, DebugDisplayInterface> = + /// let arc: DynTrait<'_, RArc<()>, DebugDisplayInterface> = /// DynTrait::from_borrowing_ptr(RArc::new('a'), DebugDisplayInterface); - /// + /// /// assert_eq!(format!("{:?}", arc), "'a'"); /// assert_eq!(format!("{}", arc), "a"); /// } @@ -966,31 +957,27 @@ mod priv_ { /// ``` pub fn from_borrowing_ptr<'borr, P, T, I>( object: P, - _interface:I + _interface: I, ) -> DynTrait<'borr, P::TransmutedPtr, I> where - T:'borr, + T: 'borr, I: InterfaceBound, InterfaceFor: GetVtable<'borr, T, P::TransmutedPtr, P, I>, P: GetPointerKind + CanTransmuteElement<()>, { DynTrait { - object: unsafe{ - ManuallyDrop::new(object.transmute_element::<()>()) - }, + object: unsafe { ManuallyDrop::new(object.transmute_element::<()>()) }, vtable: >::_GET_INNER_VTABLE, - extra_value:(), - _marker:NonOwningPhantom::NEW, - _marker2:UnsafeIgnoredType::DEFAULT, + extra_value: (), + _marker: NonOwningPhantom::NEW, + _marker2: UnsafeIgnoredType::DEFAULT, } } } - - impl<'borr, P, I, EV> DynTrait<'borr, P, I, EV> where - P:AsPtr + P: AsPtr, { /// Constructs an DynTrait from an erasable pointer and an extra value. /// @@ -1004,51 +991,49 @@ mod priv_ { /// }, /// DynTrait, RRef, /// }; - /// - /// + /// + /// /// // DebugDisplayInterface is `Debug + Display + Sync + Send` - /// let to: DynTrait<'static, RRef<()>, DebugDisplayInterface, usize> = + /// let to: DynTrait<'static, RRef<()>, DebugDisplayInterface, usize> = /// DynTrait::with_extra_value::<_, TD_Opaque>(&55u8, 100usize); - /// + /// /// assert_eq!(format!("{}", to), "55"); /// assert_eq!(format!("{:?}", to), "55"); - /// + /// /// assert_eq!(to.sabi_extra_value(), &100); /// /// ``` pub fn with_extra_value( ptr: OrigPtr, extra_value: EV, - )-> DynTrait<'borr, P, I, EV> + ) -> DynTrait<'borr, P, I, EV> where OrigPtr: GetPointerKind, OrigPtr::PtrTarget: 'borr, I: InterfaceBound, - InterfaceFor: + InterfaceFor: GetVtable<'borr, OrigPtr::PtrTarget, P, OrigPtr, I>, OrigPtr: CanTransmuteElement<(), TransmutedPtr = P>, { DynTrait { - object: unsafe{ - ManuallyDrop::new(ptr.transmute_element::<()>()) - }, + object: unsafe { ManuallyDrop::new(ptr.transmute_element::<()>()) }, vtable: >::_GET_INNER_VTABLE, extra_value, - _marker:NonOwningPhantom::NEW, - _marker2:UnsafeIgnoredType::DEFAULT, + _marker: NonOwningPhantom::NEW, + _marker2: UnsafeIgnoredType::DEFAULT, } } #[doc(hidden)] pub fn with_vtable( - ptr:OrigPtr, - extra_vtable:EV, - )-> DynTrait<'borr, P, I, EV> + ptr: OrigPtr, + extra_vtable: EV, + ) -> DynTrait<'borr, P, I, EV> where OrigPtr: GetPointerKind, OrigPtr::PtrTarget: 'borr, I: InterfaceBound, - InterfaceFor: + InterfaceFor: GetVtable<'borr, OrigPtr::PtrTarget, P, OrigPtr, I>, OrigPtr: CanTransmuteElement<(), TransmutedPtr = P>, { @@ -1056,44 +1041,43 @@ mod priv_ { } } - impl<'borr,'a, I, EV> DynTrait<'borr, RRef<'a,()>, I, EV>{ - + impl<'borr, 'a, I, EV> DynTrait<'borr, RRef<'a, ()>, I, EV> { /// This function allows constructing a DynTrait in a constant/static. - /// + /// /// # Parameters - /// + /// /// `ptr`: /// This is generally constructed with `RRef::new(&value)` /// `RRef` is a reference-like type that can be erased inside a `const fn` on stable Rust /// (once it becomes possible to unsafely cast `&T` to `&()` inside a `const fn`, /// and the minimum Rust version is bumped, this type will be replaced with a reference) - /// + /// ///
- /// + /// /// `can_it_downcast` can be either: - /// + /// /// - [`TD_CanDowncast`]: /// Which allows the trait object to be unerased, requires that the value implements any. - /// + /// /// - [`TD_Opaque`]: /// Which does not allow the trait object to be unerased. - /// + /// ///
- /// + /// /// `vtable_for`: /// This is constructible with `VTableDT::GET`. /// `VTableDT` wraps the vtable for a `DynTrait`, /// while keeping the original type and pointer type that it was constructed for, /// allowing this function to be safe to call. - /// + /// ///
- /// + /// /// `extra_value`: /// This is used by `#[sabi_trait]` trait objects to store their vtable inside DynTrait. - /// - /// + /// + /// /// # Example - /// + /// /// ``` /// use abi_stable::{ /// erased_types::{ @@ -1102,9 +1086,9 @@ mod priv_ { /// }, /// sabi_types::RRef, /// }; - /// + /// /// static STRING:&str ="What the heck"; - /// + /// /// static DYN: DynTrait<'static, RRef<'static,()>, DebugDisplayInterface,()> = /// DynTrait::from_const( /// &STRING, @@ -1112,81 +1096,86 @@ mod priv_ { /// VTableDT::GET, /// (), /// ); - /// + /// /// fn main(){ /// assert_eq!( format!("{}", DYN), format!("{}", STRING) ); /// assert_eq!( format!("{:?}", DYN), format!("{:?}", STRING) ); /// } - /// + /// /// ``` - /// + /// /// [`TD_CanDowncast`]: ./type_level/downcasting/struct.TD_CanDowncast.html /// [`TD_Opaque`]: ./type_level/downcasting/struct.TD_Opaque.html pub const fn from_const( - ptr:&'a T, - can_it_downcast:Downcasting, - vtable_for:VTableDT<'borr, T, RRef<'a,()>, RRef<'a, T>, I, Downcasting>, - extra_value:EV, - )-> Self + ptr: &'a T, + can_it_downcast: Downcasting, + vtable_for: VTableDT<'borr, T, RRef<'a, ()>, RRef<'a, T>, I, Downcasting>, + extra_value: EV, + ) -> Self where - T:'borr, + T: 'borr, { - // Must wrap can_it_downcast in a ManuallyDrop because otherwise this + // Must wrap can_it_downcast in a ManuallyDrop because otherwise this // errors with `constant functions cannot evaluate destructors`. let _ = ManuallyDrop::new(can_it_downcast); DynTrait { - object: unsafe{ + object: unsafe { let x = RRef::from_raw(ptr as *const T as *const ()); ManuallyDrop::new(x) }, vtable: vtable_for.vtable, extra_value, - _marker:NonOwningPhantom::NEW, - _marker2:UnsafeIgnoredType::DEFAULT, + _marker: NonOwningPhantom::NEW, + _marker2: UnsafeIgnoredType::DEFAULT, } } } - - impl DynTrait<'static, P, I, EV> + impl DynTrait<'static, P, I, EV> where - P:GetPointerKind + P: GetPointerKind, { /// Allows checking whether 2 `DynTrait<_>`s have a value of the same type. /// /// Notes: /// - /// - Types from different dynamic libraries/executables are + /// - Types from different dynamic libraries/executables are /// never considered equal. /// /// - `DynTrait`s constructed using `DynTrait::from_borrowing_*` /// are never considered to wrap the same type. - pub fn sabi_is_same_type(&self, other:&DynTrait<'static, Other, I2, EV2>)->bool + pub fn sabi_is_same_type( + &self, + other: &DynTrait<'static, Other, I2, EV2>, + ) -> bool where - I2:InterfaceBound, - Other:GetPointerKind, + I2: InterfaceBound, + Other: GetPointerKind, { - self.sabi_vtable_address() == other.sabi_vtable_address()|| - self.sabi_vtable().type_info().is_compatible(other.sabi_vtable().type_info()) + self.sabi_vtable_address() == other.sabi_vtable_address() + || self + .sabi_vtable() + .type_info() + .is_compatible(other.sabi_vtable().type_info()) } } impl<'borr, P, I, EV> DynTrait<'borr, P, I, PrefixRef> where - P:GetPointerKind + P: GetPointerKind, { /// A vtable used by `#[sabi_trait]` derived trait objects. #[inline] - pub fn sabi_et_vtable(&self)->PrefixRef{ + pub fn sabi_et_vtable(&self) -> PrefixRef { self.extra_value } } - + impl<'borr, P, I, EV> DynTrait<'borr, P, I, EV> where - P:GetPointerKind + P: GetPointerKind, { - /// Gets access to the extra value that was stored in this DynTrait in the + /// Gets access to the extra value that was stored in this DynTrait in the /// `with_extra_value` constructor. /// /// # Example @@ -1196,16 +1185,16 @@ mod priv_ { /// erased_types::TD_Opaque, /// DynTrait, RRef, /// }; - /// - /// - /// let to: DynTrait<'static, RRef<()>, (), char> = + /// + /// + /// let to: DynTrait<'static, RRef<()>, (), char> = /// DynTrait::with_extra_value::<_, TD_Opaque>(&55u8, 'Z'); - /// + /// /// assert_eq!(to.sabi_extra_value(), &'Z'); /// /// ``` #[inline] - pub fn sabi_extra_value(&self)->&EV{ + pub fn sabi_extra_value(&self) -> &EV { &self.extra_value } @@ -1215,7 +1204,7 @@ mod priv_ { } #[inline] - pub(super)fn sabi_vtable_address(&self) -> usize { + pub(super) fn sabi_vtable_address(&self) -> usize { self.vtable.0.to_raw_ptr() as usize } @@ -1228,12 +1217,12 @@ mod priv_ { /// erased_types::TD_Opaque, /// DynTrait, RRef, /// }; - /// + /// /// let reff = &55u8; - /// - /// let to: DynTrait<'static, RRef<()>, ()> = + /// + /// let to: DynTrait<'static, RRef<()>, ()> = /// DynTrait::from_any_ptr(reff, ()); - /// + /// /// assert_eq!(to.sabi_object_address(), reff as *const _ as usize); /// /// ``` @@ -1259,7 +1248,7 @@ mod priv_ { { &mut *(self.object.as_mut_ptr() as *mut P::PtrTarget as *mut T) } - + /// Gets a reference pointing to the erased object. /// /// # Example @@ -1269,11 +1258,11 @@ mod priv_ { /// std_types::RBox, /// DynTrait, /// }; - /// - /// - /// let to: DynTrait<'static, RBox<()>, ()> = + /// + /// + /// let to: DynTrait<'static, RBox<()>, ()> = /// DynTrait::from_any_value(66u8, ()); - /// + /// /// unsafe{ /// assert_eq!(to.sabi_erased_ref().transmute_into_ref::() , &66); /// } @@ -1282,18 +1271,14 @@ mod priv_ { where P: AsPtr, { - unsafe { - RRef::from_raw(self.object.as_ptr() as *const ErasedObject) - } + unsafe { RRef::from_raw(self.object.as_ptr() as *const ErasedObject) } } - + pub(super) unsafe fn sabi_erased_ref_unbounded_lifetime<'a>(&self) -> RRef<'a, ErasedObject> where P: AsPtr, { - unsafe { - RRef::from_raw(self.object.as_ptr() as *const ErasedObject) - } + unsafe { RRef::from_raw(self.object.as_ptr() as *const ErasedObject) } } /// Gets a mutable reference pointing to the erased object. @@ -1305,11 +1290,11 @@ mod priv_ { /// std_types::RBox, /// DynTrait, /// }; - /// - /// - /// let mut to: DynTrait<'static, RBox<()>, ()> = + /// + /// + /// let mut to: DynTrait<'static, RBox<()>, ()> = /// DynTrait::from_any_value("hello", ()); - /// + /// /// unsafe{ /// assert_eq!(to.sabi_erased_mut().transmute_into_mut::<&str>() , &mut "hello"); /// } @@ -1319,9 +1304,7 @@ mod priv_ { where P: AsMutPtr, { - unsafe { - RMut::from_raw(self.object.as_mut_ptr() as *mut ErasedObject) - } + unsafe { RMut::from_raw(self.object.as_mut_ptr() as *mut ErasedObject) } } /// Gets an `RRef` pointing to the erased object. @@ -1333,11 +1316,11 @@ mod priv_ { /// std_types::RBox, /// DynTrait, /// }; - /// - /// - /// let to: DynTrait<'static, RBox<()>, ()> = + /// + /// + /// let to: DynTrait<'static, RBox<()>, ()> = /// DynTrait::from_any_value(66u8, ()); - /// + /// /// unsafe{ /// assert_eq!(to.sabi_as_rref().transmute_into_ref::() , &66); /// } @@ -1346,9 +1329,7 @@ mod priv_ { where P: AsPtr, { - unsafe { - RRef::from_raw(self.object.as_ptr() as *const ()) - } + unsafe { RRef::from_raw(self.object.as_ptr() as *const ()) } } /// Gets an `RMut` pointing to the erased object. @@ -1360,11 +1341,11 @@ mod priv_ { /// std_types::RBox, /// DynTrait, /// }; - /// - /// - /// let mut to: DynTrait<'static, RBox<()>, ()> = + /// + /// + /// let mut to: DynTrait<'static, RBox<()>, ()> = /// DynTrait::from_any_value("hello", ()); - /// + /// /// unsafe{ /// assert_eq!(to.sabi_as_rmut().transmute_into_mut::<&str>() , &mut "hello"); /// } @@ -1373,15 +1354,13 @@ mod priv_ { where P: AsMutPtr, { - unsafe { - RMut::from_raw(self.object.as_mut_ptr() as *mut ()) - } + unsafe { RMut::from_raw(self.object.as_mut_ptr() as *mut ()) } } #[inline] - fn sabi_into_erased_ptr(self)->ManuallyDrop

{ + fn sabi_into_erased_ptr(self) -> ManuallyDrop

{ let this = ManuallyDrop::new(self); - unsafe{ ptr::read(&this.object) } + unsafe { ptr::read(&this.object) } } /// Calls the `f` callback with an `MovePtr` pointing to the erased object. @@ -1394,31 +1373,30 @@ mod priv_ { /// std_types::{RBox, RString, RVec}, /// DynTrait, /// }; - /// - /// - /// let to: DynTrait<'static, RBox<()>, ()> = + /// + /// + /// let to: DynTrait<'static, RBox<()>, ()> = /// DynTrait::from_any_value(RVec::::from_slice(b"foobarbaz"), ()); - /// + /// /// let string = to.sabi_with_value(|x| unsafe{ /// MovePtr::into_inner(MovePtr::transmute::(x)) /// }); - /// + /// /// assert_eq!(string, "foobarbaz"); /// ``` #[inline] - pub fn sabi_with_value(self, f:F)->R - where - P: OwnedPointer, - F: FnOnce(MovePtr<'_,()>)->R, + pub fn sabi_with_value(self, f: F) -> R + where + P: OwnedPointer, + F: FnOnce(MovePtr<'_, ()>) -> R, { OwnedPointer::with_move_ptr(self.sabi_into_erased_ptr(), f) } } - - impl<'borr, P, I, EV> DynTrait<'borr, P, I, EV> + impl<'borr, P, I, EV> DynTrait<'borr, P, I, EV> where - P:GetPointerKind + P: GetPointerKind, { /// The uid in the vtable has to be the same as the one for T, /// otherwise it was not created from that T in the library that declared the opaque type. @@ -1432,14 +1410,14 @@ mod priv_ { Ok(()) } else { Err(UneraseError { - dyn_trait:(), - expected_type_info:t_info, - found_type_info:self.sabi_vtable().type_info(), + dyn_trait: (), + expected_type_info: t_info, + found_type_info: self.sabi_vtable().type_info(), }) } } - /// Unwraps the `DynTrait<_>` into a pointer of + /// Unwraps the `DynTrait<_>` into a pointer of /// the concrete type that it was constructed with. /// /// T is required to implement ImplType. @@ -1463,13 +1441,13 @@ mod priv_ { /// std_types::{RArc, RBox}, /// DynTrait, ImplType, StableAbi, /// }; - /// + /// /// # fn main(){ /// { /// fn to() -> DynTrait<'static, RBox<()>, FooInterface> { /// DynTrait::from_value(Foo(b'A')) /// } - /// + /// /// assert_eq!( /// to().downcast_into_impltype::>().ok(), /// Some(RBox::new(Foo(b'A'))), @@ -1483,7 +1461,7 @@ mod priv_ { /// fn to() -> DynTrait<'static, RArc<()>, FooInterface> { /// DynTrait::from_ptr(RArc::new(Foo(b'B'))) /// } - /// + /// /// assert_eq!( /// to().downcast_into_impltype::>().ok(), /// Some(RArc::new(Foo(b'B'))), @@ -1504,8 +1482,8 @@ mod priv_ { /// /// const INFO: &'static TypeInfo = abi_stable::impl_get_type_info!(Foo); /// } - /// - /// + /// + /// /// /// An `InterfaceType` describing which traits are implemented by FooInterfaceBox. /// #[repr(C)] /// #[derive(StableAbi)] @@ -1520,13 +1498,13 @@ mod priv_ { T: ImplType, { check_unerased!(self, self.sabi_check_same_destructor::()); - unsafe { + unsafe { let this = ManuallyDrop::new(self); - Ok(ptr::read(&*this.object).transmute_element::()) + Ok(ptr::read(&*this.object).transmute_element::()) } } - /// Unwraps the `DynTrait<_>` into a reference of + /// Unwraps the `DynTrait<_>` into a reference of /// the concrete type that it was constructed with. /// /// T is required to implement ImplType. @@ -1552,28 +1530,28 @@ mod priv_ { /// DynTrait, RRef, RMut, /// ImplType, StableAbi, /// }; - /// + /// /// # fn main(){ /// { - /// let to: DynTrait<'static, RRef<'_, ()>, FooInterface> = + /// let to: DynTrait<'static, RRef<'_, ()>, FooInterface> = /// DynTrait::from_ptr(&Foo(9u8)); - /// + /// /// assert_eq!(to.downcast_as_impltype::>().ok(), Some(&Foo(9u8))); /// assert_eq!(to.downcast_as_impltype::>().ok(), None); /// } /// { /// let mut val = Foo(7u8); - /// - /// let to: DynTrait<'static, RMut<'_, ()>, FooInterface> = + /// + /// let to: DynTrait<'static, RMut<'_, ()>, FooInterface> = /// DynTrait::from_ptr(&mut val); - /// + /// /// assert_eq!(to.downcast_as_impltype::>().ok(), Some(&Foo(7))); /// assert_eq!(to.downcast_as_impltype::>().ok(), None); /// } /// { - /// let to: DynTrait<'static, RArc<()>, FooInterface> = + /// let to: DynTrait<'static, RArc<()>, FooInterface> = /// DynTrait::from_ptr(RArc::new(Foo(1u8))); - /// + /// /// assert_eq!(to.downcast_as_impltype::>().ok(), Some(&Foo(1u8))); /// assert_eq!(to.downcast_as_impltype::>().ok(), None); /// } @@ -1589,8 +1567,8 @@ mod priv_ { /// /// const INFO: &'static TypeInfo = abi_stable::impl_get_type_info!(Foo); /// } - /// - /// + /// + /// /// /// An `InterfaceType` describing which traits are implemented by FooInterfaceBox. /// #[repr(C)] /// #[derive(StableAbi)] @@ -1608,7 +1586,7 @@ mod priv_ { unsafe { Ok(self.sabi_object_as()) } } - /// Unwraps the `DynTrait<_>` into a mutable reference of + /// Unwraps the `DynTrait<_>` into a mutable reference of /// the concrete type that it was constructed with. /// /// T is required to implement ImplType. @@ -1633,21 +1611,21 @@ mod priv_ { /// DynTrait, RMut, /// ImplType, StableAbi, /// }; - /// + /// /// # fn main(){ /// { /// let mut val = Foo(7u8); - /// - /// let mut to: DynTrait<'static, RMut<'_, ()>, FooInterface> = + /// + /// let mut to: DynTrait<'static, RMut<'_, ()>, FooInterface> = /// DynTrait::from_ptr(&mut val); - /// + /// /// assert_eq!(to.downcast_as_mut_impltype::>().ok(), Some(&mut Foo(7))); /// assert_eq!(to.downcast_as_mut_impltype::>().ok(), None); /// } /// { - /// let mut to: DynTrait<'static, RBox<()>, FooInterface> = + /// let mut to: DynTrait<'static, RBox<()>, FooInterface> = /// DynTrait::from_ptr(RBox::new(Foo(1u8))); - /// + /// /// assert_eq!(to.downcast_as_mut_impltype::>().ok(), Some(&mut Foo(1u8))); /// assert_eq!(to.downcast_as_mut_impltype::>().ok(), None); /// } @@ -1663,8 +1641,8 @@ mod priv_ { /// /// const INFO: &'static TypeInfo = abi_stable::impl_get_type_info!(Foo); /// } - /// - /// + /// + /// /// /// An `InterfaceType` describing which traits are implemented by FooInterfaceBox. /// #[repr(C)] /// #[derive(StableAbi)] @@ -1682,8 +1660,7 @@ mod priv_ { unsafe { Ok(self.sabi_object_as_mut()) } } - - /// Unwraps the `DynTrait<_>` into a pointer of + /// Unwraps the `DynTrait<_>` into a pointer of /// the concrete type that it was constructed with. /// /// `T` is required to not borrow anything. @@ -1707,12 +1684,12 @@ mod priv_ { /// std_types::{RArc, RBox}, /// DynTrait, /// }; - /// + /// /// { /// fn to() -> DynTrait<'static, RBox<()>, ()> { /// DynTrait::from_any_value(b'A', ()) /// } - /// + /// /// assert_eq!(to().downcast_into::().ok(), Some(RBox::new(b'A'))); /// assert_eq!(to().downcast_into::().ok(), None); /// } @@ -1720,7 +1697,7 @@ mod priv_ { /// fn to() -> DynTrait<'static, RArc<()>, ()> { /// DynTrait::from_any_ptr(RArc::new(b'B'), ()) /// } - /// + /// /// assert_eq!(to().downcast_into::().ok(), Some(RArc::new(b'B'))); /// assert_eq!(to().downcast_into::().ok(), None); /// } @@ -1728,7 +1705,7 @@ mod priv_ { /// ``` pub fn downcast_into(self) -> Result> where - T:'static, + T: 'static, P: CanTransmuteElement, Self: DynTraitBound<'borr>, InterfaceFor: ImplType, @@ -1738,14 +1715,14 @@ mod priv_ { self.sabi_check_same_destructor::, T>() ); unsafe { - unsafe { + unsafe { let this = ManuallyDrop::new(self); - Ok(ptr::read(&*this.object).transmute_element::()) + Ok(ptr::read(&*this.object).transmute_element::()) } } } - /// Unwraps the `DynTrait<_>` into a reference of + /// Unwraps the `DynTrait<_>` into a reference of /// the concrete type that it was constructed with. /// /// `T` is required to not borrow anything. @@ -1769,35 +1746,35 @@ mod priv_ { /// std_types::RArc, /// DynTrait, RRef, RMut, /// }; - /// + /// /// { - /// let to: DynTrait<'static, RRef<'_, ()>, ()> = + /// let to: DynTrait<'static, RRef<'_, ()>, ()> = /// DynTrait::from_any_ptr(&9u8, ()); - /// + /// /// assert_eq!(to.downcast_as::().ok(), Some(&9u8)); /// assert_eq!(to.downcast_as::().ok(), None); /// } /// { /// let mut val = 7u8; - /// - /// let to: DynTrait<'static, RMut<'_, ()>, ()> = + /// + /// let to: DynTrait<'static, RMut<'_, ()>, ()> = /// DynTrait::from_any_ptr(&mut val, ()); - /// + /// /// assert_eq!(to.downcast_as::().ok(), Some(&7)); /// assert_eq!(to.downcast_as::().ok(), None); /// } /// { - /// let to: DynTrait<'static, RArc<()>, ()> = + /// let to: DynTrait<'static, RArc<()>, ()> = /// DynTrait::from_any_ptr(RArc::new(1u8), ()); - /// + /// /// assert_eq!(to.downcast_as::().ok(), Some(&1u8)); /// assert_eq!(to.downcast_as::().ok(), None); /// } - /// + /// /// ``` pub fn downcast_as(&self) -> Result<&T, UneraseError<&Self>> where - T:'static, + T: 'static, P: AsPtr + CanTransmuteElement, Self: DynTraitBound<'borr>, InterfaceFor: ImplType, @@ -1809,7 +1786,7 @@ mod priv_ { unsafe { Ok(self.sabi_object_as()) } } - /// Unwraps the `DynTrait<_>` into a mutable reference of + /// Unwraps the `DynTrait<_>` into a mutable reference of /// the concrete type that it was constructed with. /// /// `T` is required to not borrow anything. @@ -1832,20 +1809,20 @@ mod priv_ { /// std_types::RBox, /// DynTrait, RMut, /// }; - /// + /// /// { /// let mut val = 7u8; - /// - /// let mut to: DynTrait<'static, RMut<'_, ()>, ()> = + /// + /// let mut to: DynTrait<'static, RMut<'_, ()>, ()> = /// DynTrait::from_any_ptr(&mut val, ()); - /// + /// /// assert_eq!(to.downcast_as_mut::().ok(), Some(&mut 7)); /// assert_eq!(to.downcast_as_mut::().ok(), None); /// } /// { - /// let mut to: DynTrait<'static, RBox<()>, ()> = + /// let mut to: DynTrait<'static, RBox<()>, ()> = /// DynTrait::from_any_ptr(RBox::new(1u8), ()); - /// + /// /// assert_eq!(to.downcast_as_mut::().ok(), Some(&mut 1u8)); /// assert_eq!(to.downcast_as_mut::().ok(), None); /// } @@ -1880,19 +1857,19 @@ mod priv_ { /// std_types::{RArc, RBox}, /// DynTrait, /// }; - /// + /// /// unsafe { /// fn to() -> DynTrait<'static, RBox<()>, ()> { /// DynTrait::from_any_value(b'A', ()) /// } - /// + /// /// assert_eq!(to().unchecked_downcast_into::(), RBox::new(b'A')); /// } /// unsafe { /// fn to() -> DynTrait<'static, RArc<()>, ()> { /// DynTrait::from_any_ptr(RArc::new(b'B'), ()) /// } - /// + /// /// assert_eq!(to().unchecked_downcast_into::(), RArc::new(b'B')); /// } /// @@ -1900,7 +1877,7 @@ mod priv_ { #[inline] pub unsafe fn unchecked_downcast_into(self) -> P::TransmutedPtr where - P: AsPtr+ CanTransmuteElement, + P: AsPtr + CanTransmuteElement, { let this = ManuallyDrop::new(self); ptr::read(&*this.object).transmute_element::() @@ -1921,33 +1898,33 @@ mod priv_ { /// std_types::RArc, /// DynTrait, RRef, RMut, /// }; - /// + /// /// unsafe { - /// let to: DynTrait<'static, RRef<'_, ()>, ()> = + /// let to: DynTrait<'static, RRef<'_, ()>, ()> = /// DynTrait::from_any_ptr(&9u8, ()); - /// + /// /// assert_eq!(to.unchecked_downcast_as::(), &9u8); /// } /// unsafe { /// let mut val = 7u8; - /// - /// let to: DynTrait<'static, RMut<'_, ()>, ()> = + /// + /// let to: DynTrait<'static, RMut<'_, ()>, ()> = /// DynTrait::from_any_ptr(&mut val, ()); - /// + /// /// assert_eq!(to.unchecked_downcast_as::(), &7); /// } /// unsafe { - /// let to: DynTrait<'static, RArc<()>, ()> = + /// let to: DynTrait<'static, RArc<()>, ()> = /// DynTrait::from_any_ptr(RArc::new(1u8), ()); - /// + /// /// assert_eq!(to.unchecked_downcast_as::(), &1u8); /// } - /// + /// /// ``` #[inline] pub unsafe fn unchecked_downcast_as(&self) -> &T where - P: AsPtr + P: AsPtr, { self.sabi_object_as() } @@ -1967,19 +1944,19 @@ mod priv_ { /// std_types::RBox, /// DynTrait, RMut, /// }; - /// + /// /// unsafe { /// let mut val = 7u8; - /// - /// let mut to: DynTrait<'static, RMut<'_, ()>, ()> = + /// + /// let mut to: DynTrait<'static, RMut<'_, ()>, ()> = /// DynTrait::from_any_ptr(&mut val, ()); - /// + /// /// assert_eq!(to.unchecked_downcast_as_mut::(), &mut 7); /// } /// unsafe { - /// let mut to: DynTrait<'static, RBox<()>, ()> = + /// let mut to: DynTrait<'static, RBox<()>, ()> = /// DynTrait::from_any_ptr(RBox::new(1u8), ()); - /// + /// /// assert_eq!(to.unchecked_downcast_as_mut::(), &mut 1u8); /// } /// @@ -1988,45 +1965,43 @@ mod priv_ { #[inline] pub unsafe fn unchecked_downcast_as_mut(&mut self) -> &mut T where - P: AsMutPtr + P: AsMutPtr, { self.sabi_object_as_mut() } - } - mod private_struct { pub struct PrivStruct; } use self::private_struct::PrivStruct; - - /// This is used to make sure that reborrowing does not change + /// This is used to make sure that reborrowing does not change /// the Send-ness or Sync-ness of the pointer. - pub trait ReborrowBounds{} + pub trait ReborrowBounds {} // If it's reborrowing, it must have either both Sync+Send or neither. - impl ReborrowBounds, Unimplemented> - for PrivStruct - {} - - impl ReborrowBounds, Implemented> - for PrivStruct - {} - - - impl<'borr, P, I, EV> DynTrait<'borr, P, I, EV> - where - P:GetPointerKind, - I:InterfaceType, + impl ReborrowBounds, Unimplemented> + for PrivStruct + { + } + + impl ReborrowBounds, Implemented> + for PrivStruct + { + } + + impl<'borr, P, I, EV> DynTrait<'borr, P, I, EV> + where + P: GetPointerKind, + I: InterfaceType, { /// Creates a shared reborrow of this DynTrait. /// /// The reborrowed DynTrait cannot use these methods: - /// + /// /// - DynTrait::default - /// + /// /// This is only callable if `DynTrait` is either `Send + Sync` or `!Send + !Sync`. /// /// # Example @@ -2041,14 +2016,14 @@ mod priv_ { /// }, /// DynTrait, InterfaceBound, RRef, /// }; - /// - /// - /// let to: DynTrait<'static, RBox<()>, DebugDisplayInterface> = + /// + /// + /// let to: DynTrait<'static, RBox<()>, DebugDisplayInterface> = /// DynTrait::from_any_value(1337_u16, DebugDisplayInterface); - /// + /// /// assert_eq!(debug_string(to.reborrow()), "1337"); - /// - /// + /// + /// /// fn debug_string(to: DynTrait<'_, RRef<'_, ()>, I>) -> String /// where /// I: InterfaceBound> @@ -2057,30 +2032,30 @@ mod priv_ { /// } /// /// ``` - pub fn reborrow<'re>(&'re self)->DynTrait<'borr, RRef<'re, ()>, I, EV> + pub fn reborrow<'re>(&'re self) -> DynTrait<'borr, RRef<'re, ()>, I, EV> where - P:AsPtr, - PrivStruct:ReborrowBounds, - EV:Copy, + P: AsPtr, + PrivStruct: ReborrowBounds, + EV: Copy, { // Reborrowing will break if I add extra functions that operate on `P`. DynTrait { object: ManuallyDrop::new(self.object.as_rref()), - vtable: unsafe{ VTable_Ref(self.vtable.0.cast()) }, - extra_value:*self.sabi_extra_value(), - _marker:NonOwningPhantom::NEW, - _marker2:UnsafeIgnoredType::DEFAULT, + vtable: unsafe { VTable_Ref(self.vtable.0.cast()) }, + extra_value: *self.sabi_extra_value(), + _marker: NonOwningPhantom::NEW, + _marker2: UnsafeIgnoredType::DEFAULT, } } /// Creates a mutable reborrow of this DynTrait. /// /// The reborrowed DynTrait cannot use these methods: - /// + /// /// - DynTrait::default - /// + /// /// - DynTrait::clone - /// + /// /// This is only callable if `DynTrait` is either `Send + Sync` or `!Send + !Sync`. /// /// # Example @@ -2091,16 +2066,16 @@ mod priv_ { /// std_types::RBox, /// DynTrait, /// }; - /// - /// + /// + /// /// let mut to = DynTrait::from_any_value(0_u8..=255, DEIteratorInterface::NEW); - /// + /// /// assert_eq!(both_ends(to.reborrow_mut()), (Some(0), Some(255))); /// assert_eq!(both_ends(to.reborrow_mut()), (Some(1), Some(254))); /// assert_eq!(both_ends(to.reborrow_mut()), (Some(2), Some(253))); /// assert_eq!(both_ends(to.reborrow_mut()), (Some(3), Some(252))); - /// - /// + /// + /// /// fn both_ends(mut to: I) -> (Option, Option) /// where /// I: DoubleEndedIterator, @@ -2109,58 +2084,56 @@ mod priv_ { /// } /// /// ``` - pub fn reborrow_mut<'re>(&'re mut self)->DynTrait<'borr, RMut<'re, ()>, I, EV> + pub fn reborrow_mut<'re>(&'re mut self) -> DynTrait<'borr, RMut<'re, ()>, I, EV> where - P:AsMutPtr, - PrivStruct:ReborrowBounds, - EV:Copy, + P: AsMutPtr, + PrivStruct: ReborrowBounds, + EV: Copy, { - let extra_value =*self.sabi_extra_value(); + let extra_value = *self.sabi_extra_value(); // Reborrowing will break if I add extra functions that operate on `P`. DynTrait { object: ManuallyDrop::new(self.object.as_rmut()), - vtable: unsafe{ VTable_Ref(self.vtable.0.cast()) }, + vtable: unsafe { VTable_Ref(self.vtable.0.cast()) }, extra_value, - _marker:NonOwningPhantom::NEW, - _marker2:UnsafeIgnoredType::DEFAULT, + _marker: NonOwningPhantom::NEW, + _marker2: UnsafeIgnoredType::DEFAULT, } } } - - impl<'borr, P, I, EV> DynTrait<'borr, P, I, EV> + impl<'borr, P, I, EV> DynTrait<'borr, P, I, EV> where - P:AsPtr + P: AsPtr, { /// Constructs a DynTrait with a `P`, using the same vtable. /// /// `P` must come from a function in the vtable, /// or come from a copy of `P:Copy+GetPointerKind`, /// to ensure that it is compatible with the functions in it. - pub(super) fn from_new_ptr(&self, object: P, extra_value:EV) -> Self { + pub(super) fn from_new_ptr(&self, object: P, extra_value: EV) -> Self { Self { - object:ManuallyDrop::new(object), + object: ManuallyDrop::new(object), vtable: self.vtable, extra_value, - _marker:NonOwningPhantom::NEW, - _marker2:UnsafeIgnoredType::DEFAULT, + _marker: NonOwningPhantom::NEW, + _marker2: UnsafeIgnoredType::DEFAULT, } } } - impl<'borr, P, I, EV> DynTrait<'borr, P, I, EV> - where - I: InterfaceBound+'borr, - EV:'borr, - P:AsPtr, + impl<'borr, P, I, EV> DynTrait<'borr, P, I, EV> + where + I: InterfaceBound + 'borr, + EV: 'borr, + P: AsPtr, { - /// Constructs a `DynTrait` with the default value for `P`. - /// + /// /// # Reborrowing - /// + /// /// This cannot be called with a reborrowed DynTrait: - /// + /// /// ```compile_fail /// # use abi_stable::{ /// # DynTrait, @@ -2169,9 +2142,9 @@ mod priv_ { /// let object = DynTrait::from_any_value((), DefaultInterface); /// let borrow = object.reborrow(); /// let _ = borrow.default(); - /// + /// /// ``` - /// + /// /// ```compile_fail /// # use abi_stable::{ /// # DynTrait, @@ -2180,17 +2153,17 @@ mod priv_ { /// let object = DynTrait::from_any_value((), DefaultInterface); /// let borrow = object.reborrow_mut(); /// let _ = borrow.default(); - /// + /// /// ``` - /// + /// /// # Example - /// + /// /// ```rust /// use abi_stable::{ /// DynTrait, /// erased_types::interfaces::DebugDefEqInterface, /// }; - /// + /// /// { /// let object = DynTrait::from_any_value(true, DebugDefEqInterface); /// @@ -2201,21 +2174,21 @@ mod priv_ { /// /// assert_eq!(object.default(), DynTrait::from_any_value(0u8, DebugDefEqInterface)); /// } - /// + /// /// ``` pub fn default(&self) -> Self where P: AsPtr + GetPointerKind, I: InterfaceType>, - EV:Copy, + EV: Copy, { - unsafe{ + unsafe { let new = self.sabi_vtable().default_ptr()(); - self.from_new_ptr(new,*self.sabi_extra_value()) + self.from_new_ptr(new, *self.sabi_extra_value()) } } - /// It serializes a `DynTrait<_>` into a string by using + /// It serializes a `DynTrait<_>` into a string by using /// `::serialize_impl`. // I'm using the lifetime in the where clause, clippy <_< #[allow(clippy::needless_lifetimes)] @@ -2223,19 +2196,16 @@ mod priv_ { where P: AsPtr, I: InterfaceType>, - I: GetSerializeProxyType<'a> + I: GetSerializeProxyType<'a>, { - unsafe{ - self.sabi_vtable().serialize()(self.sabi_erased_ref()).into_result() - } + unsafe { self.sabi_vtable().serialize()(self.sabi_erased_ref()).into_result() } } - /// Deserializes a `DynTrait<'borr, _>` from a proxy type, by using + /// Deserializes a `DynTrait<'borr, _>` from a proxy type, by using /// `>::deserialize_dyn`. - pub fn deserialize_from_proxy<'de>(proxy:I::Proxy) -> Result + pub fn deserialize_from_proxy<'de>(proxy: I::Proxy) -> Result where - P: 'borr+AsPtr, + P: 'borr + AsPtr, I: DeserializeDyn<'de, Self>, - { I::deserialize_dyn(proxy) } @@ -2243,10 +2213,10 @@ mod priv_ { impl<'borr, P, I, EV> Drop for DynTrait<'borr, P, I, EV> where - P: GetPointerKind + P: GetPointerKind, { - fn drop(&mut self){ - unsafe{ + fn drop(&mut self) { + unsafe { let vtable = self.sabi_vtable(); if

::KIND == PointerKind::SmartPointer { @@ -2255,36 +2225,31 @@ mod priv_ { } } } - } - pub use self::priv_::DynTrait; ////////////////////// - - -mod clone_impl{ - pub trait CloneImpl{ +mod clone_impl { + pub trait CloneImpl { fn clone_impl(&self) -> Self; } } use self::clone_impl::CloneImpl; - /// This impl is for smart pointers. impl<'borr, P, I, EV> CloneImpl for DynTrait<'borr, P, I, EV> where P: AsPtr, - I: InterfaceBound>+'borr, - EV:Copy+'borr, + I: InterfaceBound> + 'borr, + EV: Copy + 'borr, { fn clone_impl(&self) -> Self { - unsafe{ + unsafe { let vtable = self.sabi_vtable(); let new = vtable.clone_ptr()(RRef::

::new(&*self.object)); - self.from_new_ptr(new,*self.sabi_extra_value()) + self.from_new_ptr(new, *self.sabi_extra_value()) } } } @@ -2292,16 +2257,15 @@ where /// This impl is for references. impl<'borr, P, I, EV> CloneImpl for DynTrait<'borr, P, I, EV> where - P: AsPtr+Copy, - I: InterfaceBound>+'borr, - EV:Copy+'borr, + P: AsPtr + Copy, + I: InterfaceBound> + 'borr, + EV: Copy + 'borr, { fn clone_impl(&self) -> Self { - self.from_new_ptr(*self.object,*self.sabi_extra_value()) + self.from_new_ptr(*self.object, *self.sabi_extra_value()) } } - /** Clone is implemented for references and smart pointers, using `GetPointerKind` to decide whether `P` is a smart pointer or a reference. @@ -2325,7 +2289,7 @@ impl<'borr, P, I, EV> Clone for DynTrait<'borr, P, I, EV> where P: AsPtr, I: InterfaceBound, - Self:CloneImpl<

::Kind>, + Self: CloneImpl<

::Kind>, { fn clone(&self) -> Self { self.clone_impl() @@ -2334,19 +2298,14 @@ where ////////////////////// - impl<'borr, P, I, EV> Display for DynTrait<'borr, P, I, EV> where P: AsPtr, I: InterfaceBound>, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - unsafe{ - adapt_std_fmt::( - self.sabi_erased_ref(), - self.sabi_vtable().display(), - f - ) + unsafe { + adapt_std_fmt::(self.sabi_erased_ref(), self.sabi_vtable().display(), f) } } } @@ -2357,12 +2316,8 @@ where I: InterfaceBound>, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - unsafe{ - adapt_std_fmt::( - self.sabi_erased_ref(), - self.sabi_vtable().debug(), - f - ) + unsafe { + adapt_std_fmt::(self.sabi_erased_ref(), self.sabi_vtable().debug(), f) } } } @@ -2375,12 +2330,11 @@ where Debug = Implemented, Error = Implemented, >, -{} - - +{ +} /** -First it serializes a `DynTrait<_>` into a string by using +First it serializes a `DynTrait<_>` into a string by using ::serialize_impl, then it serializes the string. @@ -2390,13 +2344,13 @@ where P: AsPtr, I: InterfaceBound>, I: GetSerializeProxyType<'borr>, - I::ProxyType:Serialize, + I::ProxyType: Serialize, { fn serialize(&self, serializer: S) -> Result where S: Serializer, { - unsafe{ + unsafe { self.sabi_vtable().serialize()(self.sabi_erased_ref_unbounded_lifetime()) .into_result() .map_err(ser::Error::custom)? @@ -2405,15 +2359,15 @@ where } } -/// First it Deserializes a string, then it deserializes into a +/// First it Deserializes a string, then it deserializes into a /// `DynTrait<_>`, by using `::deserialize_impl`. -impl<'de,'borr:'de, P, I, EV> Deserialize<'de> for DynTrait<'borr, P, I, EV> +impl<'de, 'borr: 'de, P, I, EV> Deserialize<'de> for DynTrait<'borr, P, I, EV> where EV: 'borr, - P: AsPtr+'borr, - I: InterfaceBound+'borr, + P: AsPtr + 'borr, + I: InterfaceBound + 'borr, I: DeserializeDyn<'de, Self>, - >::Proxy:Deserialize<'de>, + >::Proxy: Deserialize<'de>, { fn deserialize(deserializer: D) -> Result where @@ -2444,9 +2398,7 @@ where return false; } - unsafe{ - self.sabi_vtable().partial_eq()(self.sabi_erased_ref(), other.sabi_erased_ref()) - } + unsafe { self.sabi_vtable().partial_eq()(self.sabi_erased_ref(), other.sabi_erased_ref()) } } } @@ -2462,9 +2414,7 @@ where return self.sabi_vtable_address().cmp(&other.sabi_vtable_address()); } - unsafe{ - self.sabi_vtable().cmp()(self.sabi_erased_ref(), other.sabi_erased_ref()).into() - } + unsafe { self.sabi_vtable().cmp()(self.sabi_erased_ref(), other.sabi_erased_ref()).into() } } } @@ -2481,7 +2431,7 @@ where return Some(self.sabi_vtable_address().cmp(&other.sabi_vtable_address())); } - unsafe{ + unsafe { self.sabi_vtable().partial_cmp()(self.sabi_erased_ref(), other.sabi_erased_ref()) .map(IntoReprRust::into_rust) .into() @@ -2498,339 +2448,314 @@ where where H: Hasher, { - unsafe{ - self.sabi_vtable().hash()(self.sabi_erased_ref(), HasherObject::new(state)) - } + unsafe { self.sabi_vtable().hash()(self.sabi_erased_ref(), HasherObject::new(state)) } } } - ////////////////////////////////////////////////////////////////// - impl<'borr, P, I, Item, EV> Iterator for DynTrait<'borr, P, I, EV> where P: AsMutPtr, I: IteratorItemOrDefault<'borr, Item = Item>, I: InterfaceBound>, - Item:'borr, + Item: 'borr, { type Item = Item; - fn next(&mut self)->Option{ - unsafe{ + fn next(&mut self) -> Option { + unsafe { let vtable = self.sabi_vtable(); (vtable.iter().next)(self.sabi_erased_mut()).into_rust() } } - fn nth(&mut self, nth:usize)->Option{ - unsafe{ + fn nth(&mut self, nth: usize) -> Option { + unsafe { let vtable = self.sabi_vtable(); (vtable.iter().nth)(self.sabi_erased_mut(), nth).into_rust() } } - fn size_hint(&self)->(usize, Option){ - unsafe{ + fn size_hint(&self) -> (usize, Option) { + unsafe { let vtable = self.sabi_vtable(); - let tuple =(vtable.iter().size_hint)(self.sabi_erased_ref()).into_rust(); + let tuple = (vtable.iter().size_hint)(self.sabi_erased_ref()).into_rust(); (tuple.0, tuple.1.into_rust()) } } - fn count(mut self)->usize{ - unsafe{ + fn count(mut self) -> usize { + unsafe { let vtable = self.sabi_vtable(); (vtable.iter().count)(self.sabi_erased_mut()) } } - fn last(mut self)->Option{ - unsafe{ + fn last(mut self) -> Option { + unsafe { let vtable = self.sabi_vtable(); (vtable.iter().last)(self.sabi_erased_mut()).into_rust() } } } - impl<'borr, P, I, Item, EV> DynTrait<'borr, P, I, EV> where P: AsMutPtr, I: IteratorItemOrDefault<'borr, Item = Item>, I: InterfaceBound>, - Item:'borr, + Item: 'borr, { -/** -Eagerly skips n elements from the iterator. + /** + Eagerly skips n elements from the iterator. -This method is faster than using `Iterator::skip`. + This method is faster than using `Iterator::skip`. -# Example + # Example -``` -# use abi_stable::{ -# DynTrait, -# erased_types::interfaces::IteratorInterface, -# std_types::RVec, -# traits::IntoReprC, -# }; + ``` + # use abi_stable::{ + # DynTrait, + # erased_types::interfaces::IteratorInterface, + # std_types::RVec, + # traits::IntoReprC, + # }; -let mut iter = 0..20; -let mut wrapped = DynTrait::from_any_ptr(&mut iter, IteratorInterface::NEW); + let mut iter = 0..20; + let mut wrapped = DynTrait::from_any_ptr(&mut iter, IteratorInterface::NEW); -assert_eq!(wrapped.next(), Some(0)); + assert_eq!(wrapped.next(), Some(0)); -wrapped.skip_eager(2); + wrapped.skip_eager(2); -assert_eq!(wrapped.next(), Some(3)); -assert_eq!(wrapped.next(), Some(4)); -assert_eq!(wrapped.next(), Some(5)); + assert_eq!(wrapped.next(), Some(3)); + assert_eq!(wrapped.next(), Some(4)); + assert_eq!(wrapped.next(), Some(5)); -wrapped.skip_eager(2); + wrapped.skip_eager(2); -assert_eq!(wrapped.next(), Some(8)); -assert_eq!(wrapped.next(), Some(9)); + assert_eq!(wrapped.next(), Some(8)); + assert_eq!(wrapped.next(), Some(9)); -wrapped.skip_eager(9); + wrapped.skip_eager(9); -assert_eq!(wrapped.next(), Some(19)); -assert_eq!(wrapped.next(), None ); + assert_eq!(wrapped.next(), Some(19)); + assert_eq!(wrapped.next(), None ); -``` + ``` -*/ - pub fn skip_eager(&mut self, n: usize){ - unsafe{ + */ + pub fn skip_eager(&mut self, n: usize) { + unsafe { let vtable = self.sabi_vtable(); (vtable.iter().skip_eager)(self.sabi_erased_mut(), n); } } + /** + Extends the `RVec` with the `self` Iterator. -/** -Extends the `RVec` with the `self` Iterator. + Extends `buffer` with as many elements of the iterator as `taking` specifies: -Extends `buffer` with as many elements of the iterator as `taking` specifies: + - RNone: Yields all elements.Use this with care, since Iterators can be infinite. -- RNone: Yields all elements.Use this with care, since Iterators can be infinite. + - RSome(n): Yields n elements. -- RSome(n): Yields n elements. + ### Example -### Example + ``` + # use abi_stable::{ + # DynTrait, + # erased_types::interfaces::IteratorInterface, + # std_types::{RVec, RSome}, + # traits::IntoReprC, + # }; -``` -# use abi_stable::{ -# DynTrait, -# erased_types::interfaces::IteratorInterface, -# std_types::{RVec, RSome}, -# traits::IntoReprC, -# }; + let mut wrapped = DynTrait::from_any_value(0.. , IteratorInterface::NEW); -let mut wrapped = DynTrait::from_any_value(0.. , IteratorInterface::NEW); + let mut buffer = vec![ 101, 102, 103 ].into_c(); + wrapped.extending_rvec(&mut buffer, RSome(5)); + assert_eq!( + &buffer[..], + &*vec![101, 102, 103, 0, 1, 2, 3, 4] + ); -let mut buffer = vec![ 101, 102, 103 ].into_c(); -wrapped.extending_rvec(&mut buffer, RSome(5)); -assert_eq!( - &buffer[..], - &*vec![101, 102, 103, 0, 1, 2, 3, 4] -); + assert_eq!( wrapped.next(), Some(5)); + assert_eq!( wrapped.next(), Some(6)); + assert_eq!( wrapped.next(), Some(7)); -assert_eq!( wrapped.next(), Some(5)); -assert_eq!( wrapped.next(), Some(6)); -assert_eq!( wrapped.next(), Some(7)); - -``` -*/ - pub fn extending_rvec(&mut self, buffer:&mut RVec, taking:ROption){ - unsafe{ + ``` + */ + pub fn extending_rvec(&mut self, buffer: &mut RVec, taking: ROption) { + unsafe { let vtable = self.sabi_vtable(); (vtable.iter().extending_rvec)(self.sabi_erased_mut(), buffer, taking); } } } - ////////////////////////////////////////////////////////////////// - impl<'borr, P, I, Item, EV> DoubleEndedIterator for DynTrait<'borr, P, I, EV> where - Self:Iterator, + Self: Iterator, P: AsMutPtr, I: IteratorItemOrDefault<'borr, Item = Item>, I: InterfaceBound>, - Item:'borr, + Item: 'borr, { - - fn next_back(&mut self)->Option{ - unsafe{ + fn next_back(&mut self) -> Option { + unsafe { let vtable = self.sabi_vtable(); (vtable.back_iter().next_back)(self.sabi_erased_mut()).into_rust() } } } - impl<'borr, P, I, Item, EV> DynTrait<'borr, P, I, EV> where - Self:Iterator, + Self: Iterator, P: AsMutPtr, I: IteratorItemOrDefault<'borr, Item = Item>, I: InterfaceBound>, - Item:'borr, + Item: 'borr, { /// Gets teh `nth` element from the back of the iterator. - /// + /// /// # Example - /// + /// /// ```rust /// use abi_stable::{ /// erased_types::interfaces::DEIteratorCloneInterface, /// DynTrait, /// }; - /// + /// /// let to = || DynTrait::from_any_value(7..=10, DEIteratorCloneInterface::NEW); - /// + /// /// assert_eq!(to().nth_back_(0), Some(10)); /// assert_eq!(to().nth_back_(1), Some(9)); /// assert_eq!(to().nth_back_(2), Some(8)); /// assert_eq!(to().nth_back_(3), Some(7)); /// assert_eq!(to().nth_back_(4), None); /// assert_eq!(to().nth_back_(5), None); - /// + /// /// ``` - /// - pub fn nth_back_(&mut self, nth:usize)->Option{ - unsafe{ + /// + pub fn nth_back_(&mut self, nth: usize) -> Option { + unsafe { let vtable = self.sabi_vtable(); (vtable.back_iter().nth_back)(self.sabi_erased_mut(), nth).into_rust() } } -/** -Extends the `RVec` with the back of the `self` DoubleEndedIterator. + /** + Extends the `RVec` with the back of the `self` DoubleEndedIterator. -Extends `buffer` with as many elements of the iterator as `taking` specifies: + Extends `buffer` with as many elements of the iterator as `taking` specifies: -- RNone: Yields all elements.Use this with care, since Iterators can be infinite. + - RNone: Yields all elements.Use this with care, since Iterators can be infinite. -- RSome(n): Yields n elements. + - RSome(n): Yields n elements. -### Example + ### Example -``` -# use abi_stable::{ -# DynTrait, -# erased_types::interfaces::DEIteratorInterface, -# std_types::{RVec, RNone}, -# traits::IntoReprC, -# }; + ``` + # use abi_stable::{ + # DynTrait, + # erased_types::interfaces::DEIteratorInterface, + # std_types::{RVec, RNone}, + # traits::IntoReprC, + # }; -let mut wrapped = DynTrait::from_any_value(0..=3 , DEIteratorInterface::NEW); + let mut wrapped = DynTrait::from_any_value(0..=3 , DEIteratorInterface::NEW); -let mut buffer = vec![ 101, 102, 103 ].into_c(); -wrapped.extending_rvec_back(&mut buffer, RNone); -assert_eq!( - &buffer[..], - &*vec![101, 102, 103, 3, 2, 1, 0] -) + let mut buffer = vec![ 101, 102, 103 ].into_c(); + wrapped.extending_rvec_back(&mut buffer, RNone); + assert_eq!( + &buffer[..], + &*vec![101, 102, 103, 3, 2, 1, 0] + ) -``` + ``` -*/ - pub fn extending_rvec_back(&mut self, buffer:&mut RVec, taking:ROption){ - unsafe{ + */ + pub fn extending_rvec_back(&mut self, buffer: &mut RVec, taking: ROption) { + unsafe { let vtable = self.sabi_vtable(); (vtable.back_iter().extending_rvec_back)(self.sabi_erased_mut(), buffer, taking); } } } - ////////////////////////////////////////////////////////////////// - impl<'borr, P, I, EV> fmtWrite for DynTrait<'borr, P, I, EV> where P: AsMutPtr, I: InterfaceBound>, { - fn write_str(&mut self, s: &str) -> Result<(), fmt::Error>{ + fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> { let vtable = self.sabi_vtable(); - unsafe{ + unsafe { match vtable.fmt_write_str()(self.sabi_erased_mut(), s.into()) { - ROk(_) =>Ok(()), - RErr(_) =>Err(fmt::Error), + ROk(_) => Ok(()), + RErr(_) => Err(fmt::Error), } } } } - - ////////////////////////////////////////////////////////////////// - #[inline] -fn to_io_result(res:RResult)->io::Result +fn to_io_result(res: RResult) -> io::Result where - T:Into + T: Into, { match res { - ROk(v) =>Ok(v.into()), - RErr(e) =>Err(e.into()), + ROk(v) => Ok(v.into()), + RErr(e) => Err(e.into()), } } - ///////////// - impl<'borr, P, I, EV> io::Write for DynTrait<'borr, P, I, EV> where P: AsMutPtr, I: InterfaceBound>, { - fn write(&mut self, buf: &[u8]) -> io::Result{ + fn write(&mut self, buf: &[u8]) -> io::Result { let vtable = self.sabi_vtable().io_write(); - unsafe{ - to_io_result((vtable.write)(self.sabi_erased_mut(), buf.into())) - } + unsafe { to_io_result((vtable.write)(self.sabi_erased_mut(), buf.into())) } } - fn flush(&mut self) -> io::Result<()>{ + fn flush(&mut self) -> io::Result<()> { let vtable = self.sabi_vtable().io_write(); - unsafe{ - to_io_result((vtable.flush)(self.sabi_erased_mut())) - } + unsafe { to_io_result((vtable.flush)(self.sabi_erased_mut())) } } fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { let vtable = self.sabi_vtable().io_write(); - unsafe{ - to_io_result((vtable.write_all)(self.sabi_erased_mut(), buf.into())) - } + unsafe { to_io_result((vtable.write_all)(self.sabi_erased_mut(), buf.into())) } } } - ///////////// - impl<'borr, P, I, EV> io::Read for DynTrait<'borr, P, I, EV> where P: AsMutPtr, I: InterfaceBound>, { - fn read(&mut self, buf: &mut [u8]) -> io::Result{ - unsafe{ + fn read(&mut self, buf: &mut [u8]) -> io::Result { + unsafe { let vtable = self.sabi_vtable().io_read(); to_io_result((vtable.read)(self.sabi_erased_mut(), buf.into())) @@ -2838,55 +2763,50 @@ where } fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> { - unsafe{ + unsafe { let vtable = self.sabi_vtable().io_read(); to_io_result((vtable.read_exact)(self.sabi_erased_mut(), buf.into())) } } - } - ///////////// - impl<'borr, P, I, EV> io::BufRead for DynTrait<'borr, P, I, EV> where P: AsMutPtr, I: InterfaceBound< IoRead = Implemented, - IoBufRead = Implemented + IoBufRead = Implemented, >, { - fn fill_buf(&mut self) -> io::Result<&[u8]>{ - unsafe{ + fn fill_buf(&mut self) -> io::Result<&[u8]> { + unsafe { let vtable = self.sabi_vtable().io_bufread(); to_io_result((vtable.fill_buf)(self.sabi_erased_mut())) } } - fn consume(&mut self, amount:usize ){ - unsafe{ + fn consume(&mut self, amount: usize) { + unsafe { let vtable = self.sabi_vtable().io_bufread(); (vtable.consume)(self.sabi_erased_mut(), amount) } } - } ///////////// - impl<'borr, P, I, EV> io::Seek for DynTrait<'borr, P, I, EV> where P: AsMutPtr, I: InterfaceBound>, { - fn seek(&mut self, pos: io::SeekFrom) -> io::Result{ - unsafe{ + fn seek(&mut self, pos: io::SeekFrom) -> io::Result { + unsafe { let vtable = self.sabi_vtable(); to_io_result(vtable.io_seek()(self.sabi_erased_mut(), pos.into())) @@ -2894,33 +2814,33 @@ where } } - ////////////////////////////////////////////////////////////////// unsafe impl<'borr, P, I, EV> Send for DynTrait<'borr, P, I, EV> where - P: Send+GetPointerKind, + P: Send + GetPointerKind, I: InterfaceBound>, -{} - +{ +} unsafe impl<'borr, P, I, EV> Sync for DynTrait<'borr, P, I, EV> where - P: Sync+GetPointerKind, + P: Sync + GetPointerKind, I: InterfaceBound>, -{} - +{ +} ////////////////////////////////////////////////////////////////// mod sealed { use super::*; pub trait Sealed {} - impl<'borr, P, I, EV> Sealed for DynTrait<'borr, P, I, EV> - where - P:GetPointerKind, + impl<'borr, P, I, EV> Sealed for DynTrait<'borr, P, I, EV> + where + P: GetPointerKind, I: InterfaceBound, - {} + { + } } use self::sealed::Sealed; @@ -2937,11 +2857,8 @@ where type Interface = I; } - /// For getting the `Interface` type parameter in `DynTrait, Interface>`. -pub type GetVWInterface<'borr, This> = - >::Interface; - +pub type GetVWInterface<'borr, This> = >::Interface; ////////////////////////////////////////////////////////////////// @@ -2949,42 +2866,41 @@ pub type GetVWInterface<'borr, This> = /// with one of the `*unerased*` methods. #[derive(Copy, Clone)] pub struct UneraseError { - dyn_trait:T, - expected_type_info:&'static TypeInfo, - found_type_info:&'static TypeInfo, + dyn_trait: T, + expected_type_info: &'static TypeInfo, + found_type_info: &'static TypeInfo, } - -impl UneraseError{ - fn map(self, f:F)->UneraseError - where F:FnOnce(T)->U +impl UneraseError { + fn map(self, f: F) -> UneraseError + where + F: FnOnce(T) -> U, { - UneraseError{ - dyn_trait :f(self.dyn_trait), - expected_type_info :self.expected_type_info, - found_type_info :self.found_type_info, + UneraseError { + dyn_trait: f(self.dyn_trait), + expected_type_info: self.expected_type_info, + found_type_info: self.found_type_info, } } /// Extracts the DynTrait, to handle the failure to unerase it. #[must_use] - pub fn into_inner(self)->T{ + pub fn into_inner(self) -> T { self.dyn_trait } } - -impl fmt::Debug for UneraseError{ +impl fmt::Debug for UneraseError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("UneraseError") - .field("dyn_trait",&"") - .field("expected_type_info",&self.expected_type_info) - .field("found_type_info",&self.found_type_info) + .field("dyn_trait", &"") + .field("expected_type_info", &self.expected_type_info) + .field("found_type_info", &self.found_type_info) .finish() } } -impl fmt::Display for UneraseError{ +impl fmt::Display for UneraseError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(self, f) } diff --git a/abi_stable/src/erased_types/dyn_trait/tests.rs b/abi_stable/src/erased_types/dyn_trait/tests.rs index be1bb7f3..32e3c94d 100644 --- a/abi_stable/src/erased_types/dyn_trait/tests.rs +++ b/abi_stable/src/erased_types/dyn_trait/tests.rs @@ -2,30 +2,23 @@ use super::*; use std::{ cmp::{Ord, Ordering, PartialEq, PartialOrd}, - collections::hash_map::DefaultHasher, fmt::{self, Display}, - hash::{Hash,Hasher}, - + hash::{Hash, Hasher}, }; -use serde::{Serialize}; +use serde::Serialize; use serde_json; #[allow(unused_imports)] use crate::{ - erased_types::{ - DynTrait,ImplType, InterfaceType,IteratorItem, - }, + erased_types::{DynTrait, ImplType, InterfaceType, IteratorItem}, impl_get_type_info, - type_level::bools::{False,True}, + std_types::{RArc, RBox, RBoxError, RCow, RNone, ROption, RSome, RStr, RString}, traits::IntoReprC, + type_level::bools::{False, True}, StableAbi, - std_types::{ - RArc, RBox, RBoxError, RCow, RStr, RString, - RNone,RSome,ROption, - }, }; #[allow(unused_imports)] @@ -40,13 +33,11 @@ struct Foo { name: T, } - #[repr(C)] #[derive(StableAbi)] -#[sabi(impl_InterfaceType(Clone,Default,Display,Debug,Serialize,Deserialize,Ord,Hash))] +#[sabi(impl_InterfaceType(Clone, Default, Display, Debug, Serialize, Deserialize, Ord, Hash))] struct FooInterface; - impl Display for Foo where S: Display, @@ -61,29 +52,29 @@ where T: 'static, { type Interface = FooInterface; - const INFO:&'static crate::erased_types::TypeInfo=impl_get_type_info! { Foo }; + const INFO: &'static crate::erased_types::TypeInfo = impl_get_type_info! { Foo }; } -impl<'s,T> SerializeImplType<'s> for Foo +impl<'s, T> SerializeImplType<'s> for Foo where T: Serialize, { - type Interface=FooInterface; + type Interface = FooInterface; fn serialize_impl(&'s self) -> Result { match serde_json::to_string(self) { - Ok(v)=>Ok(v.into_c()), - Err(e)=>Err(RBoxError::new(e)), + Ok(v) => Ok(v.into_c()), + Err(e) => Err(RBoxError::new(e)), } } } -impl<'s> SerializeProxyType<'s> for FooInterface{ - type Proxy=RString; +impl<'s> SerializeProxyType<'s> for FooInterface { + type Proxy = RString; } -impl<'a> DeserializeDyn<'a,VirtualFoo<'static>> for FooInterface { - type Proxy=RString; +impl<'a> DeserializeDyn<'a, VirtualFoo<'static>> for FooInterface { + type Proxy = RString; fn deserialize_dyn(s: RString) -> Result, RBoxError> { match ::serde_json::from_str::>(&*s) { @@ -93,73 +84,69 @@ impl<'a> DeserializeDyn<'a,VirtualFoo<'static>> for FooInterface { } } -type VirtualFoo<'a> = DynTrait<'a,RBox<()>,FooInterface>; +type VirtualFoo<'a> = DynTrait<'a, RBox<()>, FooInterface>; ///////////////////////////////// - #[repr(C)] #[derive(StableAbi)] -#[sabi(impl_InterfaceType(Send,Sync,Debug))] +#[sabi(impl_InterfaceType(Send, Sync, Debug))] struct DebugInterface; - ///////////////////////////////// - -fn new_foo()->Foo{ - Foo{ - l:1000, - r:100, - name:"hello_world".into(), +fn new_foo() -> Foo { + Foo { + l: 1000, + r: 100, + name: "hello_world".into(), } } -fn new_wrapped()->VirtualFoo<'static>{ +fn new_wrapped() -> VirtualFoo<'static> { DynTrait::from_value(new_foo()) } - #[test] -fn clone_test(){ - let wrapped_expected=Foo::::default().piped(DynTrait::from_value); - let wrapped =new_wrapped(); +fn clone_test() { + let wrapped_expected = Foo::::default().piped(DynTrait::from_value); + let wrapped = new_wrapped(); { - let cloned=wrapped.clone(); + let cloned = wrapped.clone(); - assert_eq!(wrapped,cloned); - assert_ne!(wrapped,wrapped_expected); + assert_eq!(wrapped, cloned); + assert_ne!(wrapped, wrapped_expected); } { - let reborrow=wrapped.reborrow(); - let cloned=reborrow.clone(); - assert_eq!(reborrow,cloned); - assert_ne!(wrapped,wrapped_expected); + let reborrow = wrapped.reborrow(); + let cloned = reborrow.clone(); + assert_eq!(reborrow, cloned); + assert_ne!(wrapped, wrapped_expected); } } #[test] -fn default_test(){ - let concrete=Foo::::default(); - let wrapped =new_wrapped().default(); - let wrapped_expected=Foo::::default().piped(DynTrait::from_value); - +fn default_test() { + let concrete = Foo::::default(); + let wrapped = new_wrapped().default(); + let wrapped_expected = Foo::::default().piped(DynTrait::from_value); + { - assert_eq!(wrapped,wrapped_expected); + assert_eq!(wrapped, wrapped_expected); assert_eq!( wrapped.downcast_as_impltype::>().unwrap(), &concrete ); - assert_ne!(wrapped,new_wrapped()); + assert_ne!(wrapped, new_wrapped()); } { - let reborrow=wrapped.reborrow(); + let reborrow = wrapped.reborrow(); + + assert_eq!(reborrow, wrapped_expected); - assert_eq!(reborrow,wrapped_expected); - // This should not compile!!!!! // assert_eq!(reborrow.default(),wrapped_expected.reborrow()); @@ -167,54 +154,39 @@ fn default_test(){ reborrow.downcast_as_impltype::>().unwrap(), &concrete ); - assert_ne!(reborrow,new_wrapped()); + assert_ne!(reborrow, new_wrapped()); } } - #[test] -fn fmt_test(){ - - let concrete=new_foo(); - let mut wrapped =new_wrapped(); +fn fmt_test() { + let concrete = new_foo(); + let mut wrapped = new_wrapped(); macro_rules! debug_test { - ( $wrapped:ident ) => ({ - assert_eq!( - format!("{:?}",concrete), - format!("{:?}",$wrapped), - ); + ( $wrapped:ident ) => {{ + assert_eq!(format!("{:?}", concrete), format!("{:?}", $wrapped),); - assert_eq!( - format!("{:#?}",concrete), - format!("{:#?}",$wrapped), - ); + assert_eq!(format!("{:#?}", concrete), format!("{:#?}", $wrapped),); - assert_eq!( - format!("{}",concrete), - format!("{}",$wrapped), - ); + assert_eq!(format!("{}", concrete), format!("{}", $wrapped),); - assert_eq!( - format!("{:#}",concrete), - format!("{:#}",$wrapped), - ); - }) + assert_eq!(format!("{:#}", concrete), format!("{:#}", $wrapped),); + }}; } debug_test!(wrapped); { - let reborrow=wrapped.reborrow(); + let reborrow = wrapped.reborrow(); debug_test!(reborrow); } { - let reborrow=wrapped.reborrow_mut(); + let reborrow = wrapped.reborrow_mut(); debug_test!(reborrow); } } - -pub const JSON_0:&'static str=r#" +pub const JSON_0: &'static str = r#" { "l":1000, "r":10, @@ -222,47 +194,43 @@ pub const JSON_0:&'static str=r#" } "#; - #[test] fn deserialize_test() { + let json = JSON_0; - let json=JSON_0; + let json_ss = serde_json::to_string(json).unwrap(); - let json_ss=serde_json::to_string(json).unwrap(); - let concrete = serde_json::from_str::>(json).unwrap(); let wrapped = VirtualFoo::deserialize_from_proxy(json.into()).unwrap(); - let wrapped= wrapped.reborrow(); + let wrapped = wrapped.reborrow(); let wrapped2 = serde_json::from_str::>(&json_ss).unwrap(); assert_eq!( serde_json::from_str::>(json).map_err(drop), Err(()), ); - + assert_eq!( - wrapped.downcast_as_impltype::>().unwrap(), + wrapped.downcast_as_impltype::>().unwrap(), &concrete, ); assert_eq!( - wrapped2.downcast_as_impltype::>().unwrap(), + wrapped2.downcast_as_impltype::>().unwrap(), &concrete ); } - // Unfortunately: miri doesn't like calling `extern fn(*const ErasedType)` that // were transmuted from `extern fn(*const ErasedType)` #[test] fn serialize_test() { - let concrete = new_foo(); let mut wrapped = new_wrapped(); macro_rules! serialize_test { - ( $wrapped:ident ) => ({ + ( $wrapped:ident ) => {{ assert_eq!( &*concrete.piped_ref(serde_json::to_string).unwrap(), &*$wrapped.serialize_into_proxy().unwrap() @@ -270,46 +238,47 @@ fn serialize_test() { assert_eq!( concrete - .piped_ref(serde_json::to_string).unwrap() - .piped_ref(serde_json::to_string).unwrap(), + .piped_ref(serde_json::to_string) + .unwrap() + .piped_ref(serde_json::to_string) + .unwrap(), $wrapped.piped_ref(serde_json::to_string).unwrap() ); assert_eq!( - $wrapped.serialize_into_proxy().unwrap() - .piped_ref(serde_json::to_string).unwrap(), + $wrapped + .serialize_into_proxy() + .unwrap() + .piped_ref(serde_json::to_string) + .unwrap(), $wrapped.piped_ref(serde_json::to_string).unwrap() ); - }) + }}; } - serialize_test!( wrapped ); + serialize_test!(wrapped); { - let reborrow=wrapped.reborrow(); - serialize_test!( reborrow ); + let reborrow = wrapped.reborrow(); + serialize_test!(reborrow); } { - let reborrow=wrapped.reborrow_mut(); - serialize_test!( reborrow ); + let reborrow = wrapped.reborrow_mut(); + serialize_test!(reborrow); } - } - - #[test] -fn cmp_test(){ - +fn cmp_test() { macro_rules! cmp_test { ( wrapped_0=$wrapped_0:ident, wrapped_1=$wrapped_1:ident, wrapped_2=$wrapped_2:ident, - ) => ({ + ) => {{ assert_eq!($wrapped_1 == $wrapped_0, false); assert_eq!($wrapped_1 <= $wrapped_0, false); - assert_eq!($wrapped_1 >= $wrapped_0, true ); + assert_eq!($wrapped_1 >= $wrapped_0, true); assert_eq!($wrapped_1 < $wrapped_0, false); assert_eq!($wrapped_1 > $wrapped_0, true); assert_eq!($wrapped_1 != $wrapped_0, true); @@ -329,10 +298,9 @@ fn cmp_test(){ assert_eq!($wrapped_1.eq(&$wrapped_1), true); assert_eq!($wrapped_1.ne(&$wrapped_1), false); - assert_eq!($wrapped_1 == $wrapped_2, false); assert_eq!($wrapped_1 <= $wrapped_2, true); - assert_eq!($wrapped_1 >= $wrapped_2, false ); + assert_eq!($wrapped_1 >= $wrapped_2, false); assert_eq!($wrapped_1 < $wrapped_2, true); assert_eq!($wrapped_1 > $wrapped_2, false); assert_eq!($wrapped_1 != $wrapped_2, true); @@ -340,285 +308,259 @@ fn cmp_test(){ assert_eq!($wrapped_1.cmp(&$wrapped_2), Ordering::Less); assert_eq!($wrapped_1.eq(&$wrapped_2), false); assert_eq!($wrapped_1.ne(&$wrapped_2), true); - - }) + }}; } + let mut wrapped_0 = new_foo() + .mutated(|x| x.l -= 100) + .piped(DynTrait::from_value); + let mut wrapped_1 = new_wrapped(); + let mut wrapped_2 = new_foo() + .mutated(|x| x.l += 100) + .piped(DynTrait::from_value); - - let mut wrapped_0=new_foo().mutated(|x| x.l-=100 ).piped(DynTrait::from_value); - let mut wrapped_1=new_wrapped(); - let mut wrapped_2=new_foo().mutated(|x| x.l+=100 ).piped(DynTrait::from_value); - - - cmp_test!{ + cmp_test! { wrapped_0=wrapped_0, wrapped_1=wrapped_1, wrapped_2=wrapped_2, } { - let reborrow_0=wrapped_0.reborrow(); - let reborrow_1=wrapped_1.reborrow(); - let reborrow_2=wrapped_2.reborrow(); - - cmp_test!{ + let reborrow_0 = wrapped_0.reborrow(); + let reborrow_1 = wrapped_1.reborrow(); + let reborrow_2 = wrapped_2.reborrow(); + + cmp_test! { wrapped_0=reborrow_0, wrapped_1=reborrow_1, wrapped_2=reborrow_2, } } { - let reborrow_0=wrapped_0.reborrow_mut(); - let reborrow_1=wrapped_1.reborrow_mut(); - let reborrow_2=wrapped_2.reborrow_mut(); - - cmp_test!{ + let reborrow_0 = wrapped_0.reborrow_mut(); + let reborrow_1 = wrapped_1.reborrow_mut(); + let reborrow_2 = wrapped_2.reborrow_mut(); + + cmp_test! { wrapped_0=reborrow_0, wrapped_1=reborrow_1, wrapped_2=reborrow_2, } } - - } - - #[test] -fn hash_test(){ - fn hash_value(v:&H)->u64{ - let mut hasher=DefaultHasher::new(); +fn hash_test() { + fn hash_value(v: &H) -> u64 { + let mut hasher = DefaultHasher::new(); v.hash(&mut hasher); hasher.finish() } - - + { - let mut wrapped=new_wrapped(); - assert_eq!(hash_value(&new_foo()),hash_value(&wrapped)); - + let mut wrapped = new_wrapped(); + assert_eq!(hash_value(&new_foo()), hash_value(&wrapped)); + { - let reborrow=wrapped.reborrow(); - assert_eq!(hash_value(&new_foo()),hash_value(&reborrow)); - } + let reborrow = wrapped.reborrow(); + assert_eq!(hash_value(&new_foo()), hash_value(&reborrow)); + } { - let reborrow_mut=wrapped.reborrow_mut(); - assert_eq!(hash_value(&new_foo()),hash_value(&reborrow_mut)); + let reborrow_mut = wrapped.reborrow_mut(); + assert_eq!(hash_value(&new_foo()), hash_value(&reborrow_mut)); } - } - + { - let concrete=Foo::::default(); - let hash_concrete=hash_value(&concrete); - let hash_wrapped=hash_value(&DynTrait::from_value(concrete.clone())); - - assert_eq!(hash_concrete,hash_wrapped); - } + let concrete = Foo::::default(); + let hash_concrete = hash_value(&concrete); + let hash_wrapped = hash_value(&DynTrait::from_value(concrete.clone())); + assert_eq!(hash_concrete, hash_wrapped); + } } - #[test] -fn from_any_test(){ - +fn from_any_test() { assert_eq!( DynTrait::from_value(new_foo()), - DynTrait::from_any_value(new_foo(),FooInterface), + DynTrait::from_any_value(new_foo(), FooInterface), ); assert_eq!( DynTrait::from_ptr(RArc::new(new_foo())), - DynTrait::from_any_ptr(RArc::new(new_foo()),FooInterface), + DynTrait::from_any_ptr(RArc::new(new_foo()), FooInterface), ); - } - - #[test] -fn to_any_test(){ - - let mut wrapped=DynTrait::from_any_value(new_foo(),FooInterface); - +fn to_any_test() { + let mut wrapped = DynTrait::from_any_value(new_foo(), FooInterface); macro_rules! to_unerased { - ( $wrapped:expr ; $method:ident ; $expected:expr ) => ( - assert_eq!( - $wrapped.$method ::>().map_err(drop), - Err(()) - ); + ( $wrapped:expr ; $method:ident ; $expected:expr ) => { + assert_eq!($wrapped.$method::>().map_err(drop), Err(())); - assert_eq!( - $wrapped.$method ::>().unwrap(), - $expected - ); - ) + assert_eq!($wrapped.$method::>().unwrap(), $expected); + }; } to_unerased!( wrapped.clone() ; downcast_into_impltype ; RBox::new(new_foo()) ); to_unerased!( wrapped.clone() ; downcast_into ; RBox::new(new_foo()) ); - + to_unerased!( wrapped ; downcast_as_impltype ; &new_foo() ); to_unerased!( wrapped ; downcast_as ; &new_foo() ); - + to_unerased!( wrapped ; downcast_as_mut_impltype ; &mut new_foo() ); to_unerased!( wrapped ; downcast_as_mut ; &mut new_foo() ); - + { to_unerased!(wrapped.reborrow_mut(); downcast_into_impltype; RMut::new(&mut new_foo())); to_unerased!(wrapped.reborrow_mut() ; downcast_into ; RMut::new(&mut new_foo())); - + to_unerased!( wrapped.reborrow_mut() ; downcast_as_impltype ; &new_foo() ); to_unerased!( wrapped.reborrow_mut() ; downcast_as ; &new_foo() ); - + to_unerased!( wrapped.reborrow_mut() ; downcast_as_mut_impltype ; &mut new_foo() ); to_unerased!( wrapped.reborrow_mut() ; downcast_as_mut ; &mut new_foo() ); - } + } { to_unerased!( wrapped.reborrow() ; downcast_into_impltype; RRef::new(&new_foo()) ); to_unerased!( wrapped.reborrow() ; downcast_into ; RRef::new(&new_foo()) ); - + to_unerased!( wrapped.reborrow() ; downcast_as_impltype ; &new_foo() ); to_unerased!( wrapped.reborrow() ; downcast_as ; &new_foo() ); } } - - - - ////////////////////////////////////////////////////////////////////// - - -mod borrowing{ +mod borrowing { use super::*; /// It doesn't need to be `#[repr(C)]` because DynTrait puts it behind a pointer, /// and is only interacted with through regular Rust functions. - #[derive(Default, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)] + #[derive( + Default, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize, + )] struct Foo<'a> { l: u32, r: u32, name: &'a str, } - - impl<'a> Foo<'a>{ - pub fn new(name: &'a str)->Self{ - Self{ - l:0, - r:0, - name, - } + impl<'a> Foo<'a> { + pub fn new(name: &'a str) -> Self { + Self { l: 0, r: 0, name } } } - #[repr(C)] #[derive(StableAbi)] #[sabi(impl_InterfaceType( - Send,Sync,Clone,Default,Display,Debug,Serialize,Deserialize,Hash + Send, + Sync, + Clone, + Default, + Display, + Debug, + Serialize, + Deserialize, + Hash ))] struct FooInterface; - impl<'s> SerializeProxyType<'s> for FooInterface{ - type Proxy=RString; + impl<'s> SerializeProxyType<'s> for FooInterface { + type Proxy = RString; } - - impl<'a> Display for Foo<'a>{ + impl<'a> Display for Foo<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "l:{} r:{} name:'", self.l, self.r)?; - Display::fmt(&self.name,f)?; - writeln!(f,"'")?; + Display::fmt(&self.name, f)?; + writeln!(f, "'")?; Ok(()) } } - impl ImplType for Foo<'static>{ + impl ImplType for Foo<'static> { type Interface = FooInterface; - const INFO:&'static crate::erased_types::TypeInfo=impl_get_type_info! { Foo<'static> }; + const INFO: &'static crate::erased_types::TypeInfo = impl_get_type_info! { Foo<'static> }; } - impl<'a,'s> SerializeImplType<'s> for Foo<'a>{ - type Interface=FooInterface; + impl<'a, 's> SerializeImplType<'s> for Foo<'a> { + type Interface = FooInterface; fn serialize_impl(&self) -> Result { match serde_json::to_string(self) { - Ok(v)=>Ok(v.into_c()), - Err(e)=>Err(RBoxError::new(e)), + Ok(v) => Ok(v.into_c()), + Err(e) => Err(RBoxError::new(e)), } } } - - impl<'borr> DeserializeDyn<'borr,VirtualFoo<'borr>> for FooInterface { - type Proxy=RStr<'borr>; + impl<'borr> DeserializeDyn<'borr, VirtualFoo<'borr>> for FooInterface { + type Proxy = RStr<'borr>; fn deserialize_dyn(s: RStr<'borr>) -> Result, RBoxError> { match ::serde_json::from_str::>(s.as_str()) { - Ok(x) => Ok(DynTrait::from_borrowing_value(x,FooInterface)), + Ok(x) => Ok(DynTrait::from_borrowing_value(x, FooInterface)), Err(e) => Err(RBoxError::new(e)), } } } + type VirtualFoo<'a> = DynTrait<'a, RBox<()>, FooInterface>; - type VirtualFoo<'a> = DynTrait<'a,RBox<()>,FooInterface>; - + fn check_fmt<'a>(foo: &Foo<'a>, wrapped: &VirtualFoo<'a>) { + assert_eq!(format!("{:?}", wrapped), format!("{:?}", foo)); + assert_eq!(format!("{:#?}", wrapped), format!("{:#?}", foo)); - fn check_fmt<'a>(foo:&Foo<'a>,wrapped:&VirtualFoo<'a>){ - assert_eq!(format!("{:?}",wrapped),format!("{:?}",foo)); - assert_eq!(format!("{:#?}",wrapped),format!("{:#?}",foo)); - - assert_eq!(format!("{}",wrapped),format!("{}",foo)); - assert_eq!(format!("{:#}",wrapped),format!("{:#}",foo)); + assert_eq!(format!("{}", wrapped), format!("{}", foo)); + assert_eq!(format!("{:#}", wrapped), format!("{:#}", foo)); } #[test] - fn cloning(){ - let name="hello".to_string(); - let foo:Foo<'_>=Foo::new(&name); - let wrapped=DynTrait::from_borrowing_value(foo.clone(),FooInterface); + fn cloning() { + let name = "hello".to_string(); + let foo: Foo<'_> = Foo::new(&name); + let wrapped = DynTrait::from_borrowing_value(foo.clone(), FooInterface); - let cloned=wrapped.clone(); + let cloned = wrapped.clone(); - check_fmt(&foo,&cloned); + check_fmt(&foo, &cloned); } #[test] - fn default(){ - let name="hello".to_string(); - let foo:Foo<'_>=Foo::new(&name); + fn default() { + let name = "hello".to_string(); + let foo: Foo<'_> = Foo::new(&name); + + let default_name = "".to_string(); + let default_foo = Foo::new(&default_name); + assert_eq!(default_foo, Default::default()); - let default_name="".to_string(); - let default_foo=Foo::new(&default_name); - assert_eq!(default_foo,Default::default()); - - let wrapped=DynTrait::from_borrowing_value(foo.clone(),FooInterface); + let wrapped = DynTrait::from_borrowing_value(foo.clone(), FooInterface); - let default_wrapped=wrapped.default(); + let default_wrapped = wrapped.default(); - check_fmt(&default_foo,&default_wrapped); + check_fmt(&default_foo, &default_wrapped); } #[test] - fn formatting(){ - let name="hello".to_string(); - let foo:Foo<'_>=Foo::new(&name); - let wrapped=DynTrait::from_borrowing_value(foo.clone(),FooInterface); + fn formatting() { + let name = "hello".to_string(); + let foo: Foo<'_> = Foo::new(&name); + let wrapped = DynTrait::from_borrowing_value(foo.clone(), FooInterface); - check_fmt(&foo,&wrapped); + check_fmt(&foo, &wrapped); } #[test] - fn serialize(){ - let name="hello".to_string(); - let foo:Foo<'_>=Foo::new(&name); - let wrapped=DynTrait::from_borrowing_value(foo.clone(),FooInterface); + fn serialize() { + let name = "hello".to_string(); + let foo: Foo<'_> = Foo::new(&name); + let wrapped = DynTrait::from_borrowing_value(foo.clone(), FooInterface); assert_eq!( &*serde_json::to_string(&foo).unwrap(), @@ -627,46 +569,39 @@ mod borrowing{ } #[test] - fn deserialize(){ - let list:Vec=vec![ - JSON_0.to_string(), - ]; + fn deserialize() { + let list: Vec = vec![JSON_0.to_string()]; - for str_ in list.iter().map(|s| s.as_str() ) { - let foo:Foo<'_>=serde_json::from_str(str_).unwrap(); - let wrapped=VirtualFoo::deserialize_from_proxy(str_.into()).unwrap(); + for str_ in list.iter().map(|s| s.as_str()) { + let foo: Foo<'_> = serde_json::from_str(str_).unwrap(); + let wrapped = VirtualFoo::deserialize_from_proxy(str_.into()).unwrap(); - check_fmt(&foo,&wrapped); + check_fmt(&foo, &wrapped); } } //////////////// - #[test] - fn hash(){ - let name="hello".to_string(); - let foo:Foo<'_>=Foo::new(&name); - let wrapped=DynTrait::from_borrowing_value(foo.clone(),FooInterface); + fn hash() { + let name = "hello".to_string(); + let foo: Foo<'_> = Foo::new(&name); + let wrapped = DynTrait::from_borrowing_value(foo.clone(), FooInterface); - assert_eq!( - HashedBytes::new(&foo), - HashedBytes::new(&wrapped), - ); + assert_eq!(HashedBytes::new(&foo), HashedBytes::new(&wrapped),); } - #[derive(Debug,Default,PartialEq)] + #[derive(Debug, Default, PartialEq)] pub struct HashedBytes { bytes: Vec, } impl HashedBytes { - pub fn new(value:&T) -> Self - where T:Hash + pub fn new(value: &T) -> Self + where + T: Hash, { - let mut this=Self{ - bytes:Vec::new() - }; + let mut this = Self { bytes: Vec::new() }; value.hash(&mut this); @@ -691,223 +626,202 @@ mod borrowing{ //////////////// - #[repr(C)] #[derive(StableAbi)] - #[sabi(impl_InterfaceType(Send,Sync,DoubleEndedIterator))] + #[sabi(impl_InterfaceType(Send, Sync, DoubleEndedIterator))] struct IterInterface; - - impl<'a> IteratorItem<'a> for IterInterface{ - type Item=&'a str; + impl<'a> IteratorItem<'a> for IterInterface { + type Item = &'a str; } - - fn iterator_from_lines<'borr>(s:&'borr str)->DynTrait<'borr,RBox<()>,IterInterface>{ - let list=s.lines().collect::>(); - DynTrait::from_borrowing_value(list.into_iter(),IterInterface) + fn iterator_from_lines<'borr>(s: &'borr str) -> DynTrait<'borr, RBox<()>, IterInterface> { + let list = s.lines().collect::>(); + DynTrait::from_borrowing_value(list.into_iter(), IterInterface) } - fn exact_size_hint(n:usize)->(usize,Option){ - (n,Some(n)) + fn exact_size_hint(n: usize) -> (usize, Option) { + (n, Some(n)) } #[test] - fn iterator_collect(){ - let s="line0\nline1\nline2".to_string(); - - let actual=iterator_from_lines(&s).collect::>(); + fn iterator_collect() { + let s = "line0\nline1\nline2".to_string(); - let expected=vec!["line0","line1","line2"]; + let actual = iterator_from_lines(&s).collect::>(); + + let expected = vec!["line0", "line1", "line2"]; assert_eq!(actual, expected); } #[test] - fn iterator_next(){ - let s="line0\nline1\nline2".to_string(); - let mut iter=iterator_from_lines(&s); - - assert_eq!(iter.size_hint(),exact_size_hint(3)); - assert_eq!(iter.next(),Some("line0")); - - assert_eq!(iter.size_hint(),exact_size_hint(2)); - assert_eq!(iter.next(),Some("line1")); - - - assert_eq!(iter.size_hint(),exact_size_hint(1)); - assert_eq!(iter.next(),Some("line2")); - - - assert_eq!(iter.size_hint(),exact_size_hint(0)); - assert_eq!(iter.next(),None); - assert_eq!(iter.size_hint(),exact_size_hint(0)); - - + fn iterator_next() { + let s = "line0\nline1\nline2".to_string(); + let mut iter = iterator_from_lines(&s); + + assert_eq!(iter.size_hint(), exact_size_hint(3)); + assert_eq!(iter.next(), Some("line0")); + + assert_eq!(iter.size_hint(), exact_size_hint(2)); + assert_eq!(iter.next(), Some("line1")); + + assert_eq!(iter.size_hint(), exact_size_hint(1)); + assert_eq!(iter.next(), Some("line2")); + + assert_eq!(iter.size_hint(), exact_size_hint(0)); + assert_eq!(iter.next(), None); + assert_eq!(iter.size_hint(), exact_size_hint(0)); } #[test] - fn iterator_nth(){ - let s="line0\nline1\nline2".to_string(); - - assert_eq!(iterator_from_lines(&s).nth(0),Some("line0")); - assert_eq!(iterator_from_lines(&s).nth(1),Some("line1")); - assert_eq!(iterator_from_lines(&s).nth(2),Some("line2")); - assert_eq!(iterator_from_lines(&s).nth(3),None); + fn iterator_nth() { + let s = "line0\nline1\nline2".to_string(); + + assert_eq!(iterator_from_lines(&s).nth(0), Some("line0")); + assert_eq!(iterator_from_lines(&s).nth(1), Some("line1")); + assert_eq!(iterator_from_lines(&s).nth(2), Some("line2")); + assert_eq!(iterator_from_lines(&s).nth(3), None); } #[test] - fn iterator_count(){ - let s="line0\nline1\nline2".to_string(); - - assert_eq!(iterator_from_lines(&s).count(),3); - assert_eq!(iterator_from_lines(&s).skip(0).count(),3); - assert_eq!(iterator_from_lines(&s).skip(1).count(),2); - assert_eq!(iterator_from_lines(&s).skip(2).count(),1); - assert_eq!(iterator_from_lines(&s).skip(3).count(),0); - assert_eq!(iterator_from_lines(&s).skip(4).count(),0); - } + fn iterator_count() { + let s = "line0\nline1\nline2".to_string(); + assert_eq!(iterator_from_lines(&s).count(), 3); + assert_eq!(iterator_from_lines(&s).skip(0).count(), 3); + assert_eq!(iterator_from_lines(&s).skip(1).count(), 2); + assert_eq!(iterator_from_lines(&s).skip(2).count(), 1); + assert_eq!(iterator_from_lines(&s).skip(3).count(), 0); + assert_eq!(iterator_from_lines(&s).skip(4).count(), 0); + } #[test] - fn iterator_last(){ - let s0="line0".to_string(); - let s1="line0\nline1".to_string(); - let s2="line0\nline1\nline2".to_string(); - - assert_eq!(iterator_from_lines(&s0).last(),Some("line0")); - assert_eq!(iterator_from_lines(&s1).last(),Some("line1")); - assert_eq!(iterator_from_lines(&s2).last(),Some("line2")); + fn iterator_last() { + let s0 = "line0".to_string(); + let s1 = "line0\nline1".to_string(); + let s2 = "line0\nline1\nline2".to_string(); + + assert_eq!(iterator_from_lines(&s0).last(), Some("line0")); + assert_eq!(iterator_from_lines(&s1).last(), Some("line1")); + assert_eq!(iterator_from_lines(&s2).last(), Some("line2")); } #[test] - fn iterator_skip_eager(){ - let s="line0\nline1\nline2".to_string(); + fn iterator_skip_eager() { + let s = "line0\nline1\nline2".to_string(); - let skipping=|how_many:usize|{ - let mut iter=iterator_from_lines(&s); + let skipping = |how_many: usize| { + let mut iter = iterator_from_lines(&s); iter.skip_eager(how_many); iter }; - assert_eq!(skipping(0).next(),Some("line0")); - assert_eq!(skipping(0).count(),3); - assert_eq!(skipping(1).next(),Some("line1")); - assert_eq!(skipping(1).count(),2); - assert_eq!(skipping(2).next(),Some("line2")); - assert_eq!(skipping(2).count(),1); - assert_eq!(skipping(3).next(),None); - assert_eq!(skipping(3).count(),0); + assert_eq!(skipping(0).next(), Some("line0")); + assert_eq!(skipping(0).count(), 3); + assert_eq!(skipping(1).next(), Some("line1")); + assert_eq!(skipping(1).count(), 2); + assert_eq!(skipping(2).next(), Some("line2")); + assert_eq!(skipping(2).count(), 1); + assert_eq!(skipping(3).next(), None); + assert_eq!(skipping(3).count(), 0); } - #[test] - fn iterator_extending_rvec(){ - let s="line0\nline1\nline2".to_string(); + fn iterator_extending_rvec() { + let s = "line0\nline1\nline2".to_string(); - let collected=|how_many:Option|{ - s.lines() - .take(how_many.unwrap_or(!0)) - .collect::>() - }; + let collected = + |how_many: Option| s.lines().take(how_many.unwrap_or(!0)).collect::>(); - let extending=|how_many:ROption|{ - let mut iter=iterator_from_lines(&s); - let mut buffer=RVec::new(); - iter.extending_rvec(&mut buffer,how_many); + let extending = |how_many: ROption| { + let mut iter = iterator_from_lines(&s); + let mut buffer = RVec::new(); + iter.extending_rvec(&mut buffer, how_many); buffer }; - assert_eq!(extending(RNone ),collected(None)); - assert_eq!(extending(RSome(0)),collected(Some(0))); - assert_eq!(extending(RSome(1)),collected(Some(1))); - assert_eq!(extending(RSome(2)),collected(Some(2))); - assert_eq!(extending(RSome(3)),collected(Some(3))); + assert_eq!(extending(RNone), collected(None)); + assert_eq!(extending(RSome(0)), collected(Some(0))); + assert_eq!(extending(RSome(1)), collected(Some(1))); + assert_eq!(extending(RSome(2)), collected(Some(2))); + assert_eq!(extending(RSome(3)), collected(Some(3))); } - //////////////// - #[test] - fn iterator_next_back(){ - let s="line0\nline1\nline2".to_string(); - let mut iter=iterator_from_lines(&s); - - assert_eq!(iter.size_hint(),exact_size_hint(3)); - assert_eq!(iter.next_back(),Some("line2")); - - assert_eq!(iter.size_hint(),exact_size_hint(2)); - assert_eq!(iter.next_back(),Some("line1")); - - - assert_eq!(iter.size_hint(),exact_size_hint(1)); - assert_eq!(iter.next_back(),Some("line0")); - - - assert_eq!(iter.size_hint(),exact_size_hint(0)); - assert_eq!(iter.next_back(),None); - assert_eq!(iter.size_hint(),exact_size_hint(0)); - - + fn iterator_next_back() { + let s = "line0\nline1\nline2".to_string(); + let mut iter = iterator_from_lines(&s); + + assert_eq!(iter.size_hint(), exact_size_hint(3)); + assert_eq!(iter.next_back(), Some("line2")); + + assert_eq!(iter.size_hint(), exact_size_hint(2)); + assert_eq!(iter.next_back(), Some("line1")); + + assert_eq!(iter.size_hint(), exact_size_hint(1)); + assert_eq!(iter.next_back(), Some("line0")); + + assert_eq!(iter.size_hint(), exact_size_hint(0)); + assert_eq!(iter.next_back(), None); + assert_eq!(iter.size_hint(), exact_size_hint(0)); } #[test] - fn iterator_nth_back(){ - let s="line0\nline1\nline2".to_string(); - - assert_eq!(iterator_from_lines(&s).nth_back_(0),Some("line2")); - assert_eq!(iterator_from_lines(&s).nth_back_(1),Some("line1")); - assert_eq!(iterator_from_lines(&s).nth_back_(2),Some("line0")); - assert_eq!(iterator_from_lines(&s).nth_back_(3),None); + fn iterator_nth_back() { + let s = "line0\nline1\nline2".to_string(); + + assert_eq!(iterator_from_lines(&s).nth_back_(0), Some("line2")); + assert_eq!(iterator_from_lines(&s).nth_back_(1), Some("line1")); + assert_eq!(iterator_from_lines(&s).nth_back_(2), Some("line0")); + assert_eq!(iterator_from_lines(&s).nth_back_(3), None); } #[test] - fn iterator_extending_rvec_back(){ - let s="line0\nline1\nline2".to_string(); + fn iterator_extending_rvec_back() { + let s = "line0\nline1\nline2".to_string(); - let collected=|how_many:Option|{ - s.lines().rev() + let collected = |how_many: Option| { + s.lines() + .rev() .take(how_many.unwrap_or(!0)) .collect::>() }; - let extending=|how_many:ROption|{ - let mut iter=iterator_from_lines(&s); - let mut buffer=RVec::new(); - iter.extending_rvec_back(&mut buffer,how_many); + let extending = |how_many: ROption| { + let mut iter = iterator_from_lines(&s); + let mut buffer = RVec::new(); + iter.extending_rvec_back(&mut buffer, how_many); buffer }; - assert_eq!(extending(RNone ),collected(None)); - assert_eq!(extending(RSome(0)),collected(Some(0))); - assert_eq!(extending(RSome(1)),collected(Some(1))); - assert_eq!(extending(RSome(2)),collected(Some(2))); - assert_eq!(extending(RSome(3)),collected(Some(3))); + assert_eq!(extending(RNone), collected(None)); + assert_eq!(extending(RSome(0)), collected(Some(0))); + assert_eq!(extending(RSome(1)), collected(Some(1))); + assert_eq!(extending(RSome(2)), collected(Some(2))); + assert_eq!(extending(RSome(3)), collected(Some(3))); } - - //////////////// - #[test] - fn is_same_type(){ - let value:String="hello".to_string(); + fn is_same_type() { + let value: String = "hello".to_string(); - let wrapped =DynTrait::from_borrowing_value(value.clone(),()); - let wrapped=wrapped.reborrow(); + let wrapped = DynTrait::from_borrowing_value(value.clone(), ()); + let wrapped = wrapped.reborrow(); // Creating a DynTrait with a different interface so that it // creates a different vtable. - let dbg_wrapped=DynTrait::from_borrowing_value(value.clone(),DebugInterface); + let dbg_wrapped = DynTrait::from_borrowing_value(value.clone(), DebugInterface); assert!(!wrapped.sabi_is_same_type(&dbg_wrapped)); } #[test] - fn unerase_should_not_work(){ - - let value:String="hello".to_string(); + fn unerase_should_not_work() { + let value: String = "hello".to_string(); macro_rules! to_unerased { ( $wrapped:expr ; $( $method:ident ),* $(,)* ) => ( @@ -920,165 +834,136 @@ mod borrowing{ ) } - to_unerased!( + to_unerased!( DynTrait::from_borrowing_value(value.clone(),()); downcast_into, ); - - to_unerased!( + + to_unerased!( DynTrait::from_borrowing_value(value.clone(),()); downcast_as, downcast_as_mut, ); - - } - - /////////////////////////////////////////////////////////////////////////////////// #[repr(C)] #[derive(StableAbi)] - #[sabi(impl_InterfaceType(Send,Sync,FmtWrite))] + #[sabi(impl_InterfaceType(Send, Sync, FmtWrite))] struct FmtInterface; - #[test] - fn fmt_write(){ + fn fmt_write() { use std::fmt::Write; - let mut s=String::new(); + let mut s = String::new(); { - let mut wrapped=DynTrait::from_any_ptr(&mut s,FmtInterface); - let mut wrapped=wrapped.reborrow_mut(); + let mut wrapped = DynTrait::from_any_ptr(&mut s, FmtInterface); + let mut wrapped = wrapped.reborrow_mut(); wrapped.write_char('¿').unwrap(); wrapped.write_str("Hello").unwrap(); wrapped.write_char('?').unwrap(); } - assert_eq!(&*s,"¿Hello?" ); + assert_eq!(&*s, "¿Hello?"); } - - #[repr(C)] #[derive(StableAbi)] - #[sabi(impl_InterfaceType(Send,Sync,IoWrite,IoSeek,IoRead,IoBufRead))] + #[sabi(impl_InterfaceType(Send, Sync, IoWrite, IoSeek, IoRead, IoBufRead))] struct IoInterface; - #[test] - fn io_write(){ - use std::io::{Write,Cursor}; + fn io_write() { + use std::io::{Cursor, Write}; - const FILLER:u8=255; + const FILLER: u8 = 255; - let mut buff=vec![FILLER;9]; - let mut buff=buff[..].piped_mut(Cursor::new); + let mut buff = vec![FILLER; 9]; + let mut buff = buff[..].piped_mut(Cursor::new); { - let mut wrapped=DynTrait::from_borrowing_ptr(&mut buff,IoInterface); - assert_eq!(wrapped.write(&[0,1]).map_err(drop), Ok(2)); - - wrapped.write_all(&[2,3,4,5]).unwrap(); - + let mut wrapped = DynTrait::from_borrowing_ptr(&mut buff, IoInterface); + assert_eq!(wrapped.write(&[0, 1]).map_err(drop), Ok(2)); + + wrapped.write_all(&[2, 3, 4, 5]).unwrap(); } - assert_eq!(&**buff.get_ref(),&[0,1,2,3,4,5,FILLER,FILLER,FILLER][..]); + assert_eq!( + &**buff.get_ref(), + &[0, 1, 2, 3, 4, 5, FILLER, FILLER, FILLER][..] + ); { - let mut wrapped=DynTrait::from_borrowing_ptr(&mut buff,IoInterface); + let mut wrapped = DynTrait::from_borrowing_ptr(&mut buff, IoInterface); + + wrapped + .write_all(&[2, 3, 4, 5, 6, 7, 8, 9, 10]) + .unwrap_err(); - wrapped.write_all(&[2,3,4,5,6,7,8,9,10]).unwrap_err(); - wrapped.flush().unwrap(); } } #[test] - fn io_read(){ - use std::io::{Read,Cursor}; + fn io_read() { + use std::io::{Cursor, Read}; - let mut buff=vec![1,2,3,4,5,6,7,8,9,10].piped(Cursor::new); - let mut out=vec![0;400]; + let mut buff = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10].piped(Cursor::new); + let mut out = vec![0; 400]; - let mut wrapped=DynTrait::from_any_ptr(&mut buff,IoInterface); - assert_eq!( - wrapped.read(&mut out[..3]).map_err(drop), - Ok(3) - ); - assert_eq!(&out[..3],&[1,2,3][..] ); - + let mut wrapped = DynTrait::from_any_ptr(&mut buff, IoInterface); + assert_eq!(wrapped.read(&mut out[..3]).map_err(drop), Ok(3)); + assert_eq!(&out[..3], &[1, 2, 3][..]); - assert_eq!( - wrapped.read_exact(&mut out[4..8]).map_err(drop), - Ok(()) - ); - assert_eq!(&out[4..8],&[4,5,6,7][..] ); + assert_eq!(wrapped.read_exact(&mut out[4..8]).map_err(drop), Ok(())); + assert_eq!(&out[4..8], &[4, 5, 6, 7][..]); - assert_eq!( - wrapped.read_exact(&mut out[8..]).map_err(drop), - Err(()) - ); + assert_eq!(wrapped.read_exact(&mut out[8..]).map_err(drop), Err(())); } - + #[repr(C)] #[derive(StableAbi)] - #[sabi(impl_InterfaceType(Send,Sync,IoRead,IoBufRead))] + #[sabi(impl_InterfaceType(Send, Sync, IoRead, IoBufRead))] struct IoBufReadInterface; - #[test] - fn io_bufread(){ + fn io_bufread() { + use std::io::{BufRead, Cursor}; - use std::io::{BufRead,Cursor}; + let s = "line0\nline1\nline2".as_bytes().piped(Cursor::new); - let s="line0\nline1\nline2".as_bytes().piped(Cursor::new); + let wrapped = DynTrait::from_borrowing_value(s, IoBufReadInterface); - let wrapped=DynTrait::from_borrowing_value(s,IoBufReadInterface); - assert_eq!( - wrapped.lines().collect::,_>>().unwrap(), + wrapped.lines().collect::, _>>().unwrap(), vec![ "line0".to_string(), "line1".to_string(), "line2".to_string(), ] ); - } #[test] - fn io_seek(){ - use std::io::{Read,Seek,SeekFrom,Cursor}; + fn io_seek() { + use std::io::{Cursor, Read, Seek, SeekFrom}; + + let mut buff = vec![255, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].piped(Cursor::new); + let mut out = vec![0; 400]; - let mut buff=vec![255,1,2,3,4,5,6,7,8,9,10].piped(Cursor::new); - let mut out=vec![0;400]; + let mut wrapped = DynTrait::from_any_ptr(&mut buff, IoInterface); - let mut wrapped=DynTrait::from_any_ptr(&mut buff,IoInterface); - { wrapped.seek(SeekFrom::Start(1)).unwrap(); - assert_eq!( - wrapped.read_exact(&mut out[..4]).map_err(drop), - Ok(()) - ); - assert_eq!(&out[..4],&[1,2,3,4][..] ); + assert_eq!(wrapped.read_exact(&mut out[..4]).map_err(drop), Ok(())); + assert_eq!(&out[..4], &[1, 2, 3, 4][..]); } { wrapped.seek(SeekFrom::End(-3)).unwrap(); - assert_eq!( - wrapped.read_exact(&mut out[4..7]).map_err(drop), - Ok(()) - ); - assert_eq!(&out[..7],&[1,2,3,4,8,9,10][..] ); + assert_eq!(wrapped.read_exact(&mut out[4..7]).map_err(drop), Ok(())); + assert_eq!(&out[..7], &[1, 2, 3, 4, 8, 9, 10][..]); } { wrapped.seek(SeekFrom::Current(-4)).unwrap(); - assert_eq!( - wrapped.read_exact(&mut out[7..8]).map_err(drop), - Ok(()) - ); - assert_eq!(&out[..8],&[1,2,3,4,8,9,10,7][..] ); + assert_eq!(wrapped.read_exact(&mut out[7..8]).map_err(drop), Ok(())); + assert_eq!(&out[..8], &[1, 2, 3, 4, 8, 9, 10, 7][..]); } } } - - - diff --git a/abi_stable/src/erased_types/enabled_traits_macro.rs b/abi_stable/src/erased_types/enabled_traits_macro.rs index 4f1b7632..0cc24cdc 100644 --- a/abi_stable/src/erased_types/enabled_traits_macro.rs +++ b/abi_stable/src/erased_types/enabled_traits_macro.rs @@ -2,7 +2,7 @@ macro_rules! declare_enabled_traits { (declare_index;($value:expr,$ty:ty);$which_impl0:ident,$which_impl1:ident $(,$rest:ident)* )=>{ pub const $which_impl0:$ty=$value; pub const $which_impl1:$ty=$value << 1; - + declare_enabled_traits!{declare_index;($value << 2,$ty); $($rest),* } }; (declare_index;($value:expr,$ty:ty);$which_impl:ident)=>{ @@ -69,7 +69,7 @@ macro_rules! declare_enabled_traits { impl Display for EnabledTraits{ fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ f.write_str("EnabledTraits\n")?; - + f.write_str("Auto traits:")?; if self.auto_traits==0 { f.write_str("")?; @@ -210,4 +210,4 @@ macro_rules! declare_enabled_traits { impl std::error::Error for ImpldTraitsError{} ) -} \ No newline at end of file +} diff --git a/abi_stable/src/erased_types/interfaces.rs b/abi_stable/src/erased_types/interfaces.rs index 90ab19ee..15bfa687 100644 --- a/abi_stable/src/erased_types/interfaces.rs +++ b/abi_stable/src/erased_types/interfaces.rs @@ -4,7 +4,7 @@ use std::marker::PhantomData; /// Implements `InterfaceType`, requiring `Send + Sync + Clone` #[repr(C)] #[derive(StableAbi)] -#[sabi(impl_InterfaceType(Send,Sync,Clone))] +#[sabi(impl_InterfaceType(Send, Sync, Clone))] pub struct CloneInterface; ////////////////////////////////////////////// @@ -12,7 +12,7 @@ pub struct CloneInterface; /// Implements `InterfaceType`, requiring `Send + Sync + Debug + Clone + Eq` #[repr(C)] #[derive(StableAbi)] -#[sabi(impl_InterfaceType(Send,Sync,Debug,Clone,Eq))] +#[sabi(impl_InterfaceType(Send, Sync, Debug, Clone, Eq))] pub struct CloneEqInterface; ////////////////////////////////////////////// @@ -20,26 +20,23 @@ pub struct CloneEqInterface; /// Implements `InterfaceType`, requiring `Send + Sync + Debug + Clone + DoubleEndedIterator` #[repr(C)] #[derive(StableAbi)] -#[sabi(impl_InterfaceType(Send,Sync,Debug,Clone,DoubleEndedIterator))] +#[sabi(impl_InterfaceType(Send, Sync, Debug, Clone, DoubleEndedIterator))] pub struct DEIteratorCloneInterface(PhantomData); -impl DEIteratorCloneInterface{ - pub const NEW:Self=Self(PhantomData); +impl DEIteratorCloneInterface { + pub const NEW: Self = Self(PhantomData); } -impl<'a,T:'a> IteratorItem<'a> for DEIteratorCloneInterface{ - type Item=T; +impl<'a, T: 'a> IteratorItem<'a> for DEIteratorCloneInterface { + type Item = T; } - - ////////////////////////////////////////////// - /// Implements `InterfaceType`, requiring `Send + Sync + Default` #[repr(C)] #[derive(StableAbi)] -#[sabi(impl_InterfaceType(Send,Sync,Default))] +#[sabi(impl_InterfaceType(Send, Sync, Default))] pub struct DefaultInterface; ////////////////////////////////////////////// @@ -47,28 +44,25 @@ pub struct DefaultInterface; /// Implements `InterfaceType`, requiring `Send + Sync + Debug + Eq + Default` #[repr(C)] #[derive(StableAbi)] -#[sabi(impl_InterfaceType(Send,Sync,Debug,Eq,Default))] +#[sabi(impl_InterfaceType(Send, Sync, Debug, Eq, Default))] pub struct DebugDefEqInterface; - ////////////////////////////////////////////// /// Implements `InterfaceType`, requiring `Send + Sync + Debug + PartialEq` #[repr(C)] #[derive(StableAbi)] -#[sabi(impl_InterfaceType(Send,Sync,Debug,PartialEq))] +#[sabi(impl_InterfaceType(Send, Sync, Debug, PartialEq))] pub struct PartialEqInterface; - ////////////////////////////////////////////// /// Implements `InterfaceType`, requiring `Send + Sync + Debug + std::fmt::Write` #[repr(C)] #[derive(StableAbi)] -#[sabi(impl_InterfaceType(Send,Sync,Debug,FmtWrite))] +#[sabi(impl_InterfaceType(Send, Sync, Debug, FmtWrite))] pub struct FmtWriteInterface; - ////////////////////////////////////////////// /// Implements `InterfaceType`, requiring `std::io::Write` @@ -82,42 +76,37 @@ pub struct IoWriteInterface; /// Implements `InterfaceType`, requiring `Send + Sync + Debug + Display` #[repr(C)] #[derive(StableAbi)] -#[sabi(impl_InterfaceType(Send,Sync,Debug,Display))] +#[sabi(impl_InterfaceType(Send, Sync, Debug, Display))] pub struct DebugDisplayInterface; ////////////////////////////////////////////// - /// Implements `InterfaceType`, requiring `Send + Sync + Iterator` #[repr(C)] #[derive(StableAbi)] -#[sabi(impl_InterfaceType(Send,Sync,Iterator))] +#[sabi(impl_InterfaceType(Send, Sync, Iterator))] pub struct IteratorInterface(PhantomData); -impl IteratorInterface{ - pub const NEW:Self=Self(PhantomData); +impl IteratorInterface { + pub const NEW: Self = Self(PhantomData); } -impl<'a,T:'a> IteratorItem<'a> for IteratorInterface{ - type Item=T; +impl<'a, T: 'a> IteratorItem<'a> for IteratorInterface { + type Item = T; } - ////////////////////////////////////////////// - - /// Implements `InterfaceType`, requiring `Send + Sync + DoubleEndedIterator` #[repr(C)] #[derive(StableAbi)] -#[sabi(impl_InterfaceType(Send,Sync,DoubleEndedIterator))] +#[sabi(impl_InterfaceType(Send, Sync, DoubleEndedIterator))] pub struct DEIteratorInterface(PhantomData); -impl DEIteratorInterface{ - pub const NEW:Self=Self(PhantomData); +impl DEIteratorInterface { + pub const NEW: Self = Self(PhantomData); } -impl<'a,T:'a> IteratorItem<'a> for DEIteratorInterface{ - type Item=T; +impl<'a, T: 'a> IteratorItem<'a> for DEIteratorInterface { + type Item = T; } - diff --git a/abi_stable/src/erased_types/iterator.rs b/abi_stable/src/erased_types/iterator.rs index 0c8e9d01..3f75d9a4 100644 --- a/abi_stable/src/erased_types/iterator.rs +++ b/abi_stable/src/erased_types/iterator.rs @@ -1,72 +1,60 @@ use crate::{ - sabi_types::{RRef, RMut}, - std_types::{RVec,ROption,RSome,RNone,Tuple2}, marker_type::{ErasedObject, NonOwningPhantom}, - utils::Transmuter, + sabi_types::{RMut, RRef}, + std_types::{RNone, ROption, RSome, RVec, Tuple2}, traits::IntoReprC, + utils::Transmuter, }; - /////////////////////////////////////////////////////////////////////////////////// - #[repr(C)] #[derive(StableAbi)] -pub struct IteratorFns{ - pub(super) next :unsafe extern "C" fn( RMut<'_, ErasedObject>)->ROption, +pub struct IteratorFns { + pub(super) next: unsafe extern "C" fn(RMut<'_, ErasedObject>) -> ROption, pub(super) extending_rvec: - unsafe extern "C" fn( - RMut<'_, ErasedObject>, - &mut RVec, - ROption - ), - pub(super) size_hint :unsafe extern "C" fn(RRef<'_, ErasedObject>)-> Tuple2>, - pub(super) count :unsafe extern "C" fn( RMut<'_, ErasedObject>)->usize, - pub(super) last :unsafe extern "C" fn( RMut<'_, ErasedObject>)->ROption, - pub(super) nth :unsafe extern "C" fn( RMut<'_, ErasedObject>,usize)->ROption, - pub(super) skip_eager :unsafe extern "C" fn( RMut<'_, ErasedObject>,usize), -} - - -impl Copy for IteratorFns{} -impl Clone for IteratorFns{ - fn clone(&self)->Self{ + unsafe extern "C" fn(RMut<'_, ErasedObject>, &mut RVec, ROption), + pub(super) size_hint: + unsafe extern "C" fn(RRef<'_, ErasedObject>) -> Tuple2>, + pub(super) count: unsafe extern "C" fn(RMut<'_, ErasedObject>) -> usize, + pub(super) last: unsafe extern "C" fn(RMut<'_, ErasedObject>) -> ROption, + pub(super) nth: unsafe extern "C" fn(RMut<'_, ErasedObject>, usize) -> ROption, + pub(super) skip_eager: unsafe extern "C" fn(RMut<'_, ErasedObject>, usize), +} + +impl Copy for IteratorFns {} +impl Clone for IteratorFns { + fn clone(&self) -> Self { *self } } - /////////////////////////////////////////////////////////////////////////////////// - pub struct MakeIteratorFns(NonOwningPhantom); impl MakeIteratorFns -where I:Iterator +where + I: Iterator, { - const ITER:IteratorFns=IteratorFns{ - next:next::, - extending_rvec:extending_rvec::, - size_hint:size_hint::, - count:count::, - last:last::, - nth:nth::, - skip_eager:skip_eager::, + const ITER: IteratorFns = IteratorFns { + next: next::, + extending_rvec: extending_rvec::, + size_hint: size_hint::, + count: count::, + last: last::, + nth: nth::, + skip_eager: skip_eager::, }; - pub(super) const NEW:IteratorFns<()>=unsafe{ - Transmuter{ - from:Self::ITER - }.to - }; + pub(super) const NEW: IteratorFns<()> = unsafe { Transmuter { from: Self::ITER }.to }; } - /////////////////////////////////////////////////////////////////////////////////// - -pub(super) unsafe extern "C" fn next(this: RMut<'_, ErasedObject>)->ROption -where I:Iterator +pub(super) unsafe extern "C" fn next(this: RMut<'_, ErasedObject>) -> ROption +where + I: Iterator, { extern_fn_panic_handling! { let this = this.transmute_into_mut::(); @@ -76,10 +64,10 @@ where I:Iterator pub(super) unsafe extern "C" fn extending_rvec( this: RMut<'_, ErasedObject>, - vec:&mut RVec, - taking:ROption, -)where - I:Iterator + vec: &mut RVec, + taking: ROption, +) where + I: Iterator, { extern_fn_panic_handling! { let this = this.transmute_into_mut::(); @@ -90,8 +78,11 @@ pub(super) unsafe extern "C" fn extending_rvec( } } -pub(super) unsafe extern "C" fn size_hint(this:RRef<'_, ErasedObject>)-> Tuple2> -where I:Iterator +pub(super) unsafe extern "C" fn size_hint( + this: RRef<'_, ErasedObject>, +) -> Tuple2> +where + I: Iterator, { extern_fn_panic_handling! { let this = this.transmute_into_ref::(); @@ -101,8 +92,9 @@ where I:Iterator } } -pub(super) unsafe extern "C" fn count(this: RMut<'_, ErasedObject>)->usize -where I:Iterator +pub(super) unsafe extern "C" fn count(this: RMut<'_, ErasedObject>) -> usize +where + I: Iterator, { extern_fn_panic_handling! { let this = this.transmute_into_mut::(); @@ -110,8 +102,9 @@ where I:Iterator } } -pub(super) unsafe extern "C" fn last(this: RMut<'_, ErasedObject>)->ROption -where I:Iterator +pub(super) unsafe extern "C" fn last(this: RMut<'_, ErasedObject>) -> ROption +where + I: Iterator, { extern_fn_panic_handling! { let this = this.transmute_into_mut::(); @@ -119,8 +112,9 @@ where I:Iterator } } -pub(super) unsafe extern "C" fn nth(this: RMut<'_, ErasedObject>,at:usize)->ROption -where I:Iterator +pub(super) unsafe extern "C" fn nth(this: RMut<'_, ErasedObject>, at: usize) -> ROption +where + I: Iterator, { extern_fn_panic_handling! { let this = this.transmute_into_mut::(); @@ -128,8 +122,9 @@ where I:Iterator } } -pub(super) unsafe extern "C" fn skip_eager(this: RMut<'_, ErasedObject>,skipping:usize) -where I:Iterator +pub(super) unsafe extern "C" fn skip_eager(this: RMut<'_, ErasedObject>, skipping: usize) +where + I: Iterator, { extern_fn_panic_handling! { let this = this.transmute_into_mut::(); @@ -140,64 +135,49 @@ where I:Iterator } } - - //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// - - #[repr(C)] #[derive(StableAbi)] -pub struct DoubleEndedIteratorFns{ - pub(super) next_back :unsafe extern "C" fn( RMut<'_, ErasedObject>)->ROption, +pub struct DoubleEndedIteratorFns { + pub(super) next_back: unsafe extern "C" fn(RMut<'_, ErasedObject>) -> ROption, pub(super) extending_rvec_back: - unsafe extern "C" fn( - RMut<'_, ErasedObject>, - &mut RVec, - ROption - ), - pub(super) nth_back:unsafe extern "C" fn( RMut<'_, ErasedObject>,usize)->ROption, + unsafe extern "C" fn(RMut<'_, ErasedObject>, &mut RVec, ROption), + pub(super) nth_back: unsafe extern "C" fn(RMut<'_, ErasedObject>, usize) -> ROption, } - -impl Copy for DoubleEndedIteratorFns{} -impl Clone for DoubleEndedIteratorFns{ - fn clone(&self)->Self{ +impl Copy for DoubleEndedIteratorFns {} +impl Clone for DoubleEndedIteratorFns { + fn clone(&self) -> Self { *self } } - /////////////////////////////////////////////////////////////////////////////////// - pub struct MakeDoubleEndedIteratorFns(NonOwningPhantom); impl MakeDoubleEndedIteratorFns -where I:DoubleEndedIterator +where + I: DoubleEndedIterator, { - pub(super) const ITER:DoubleEndedIteratorFns=DoubleEndedIteratorFns{ - next_back:next_back::, - extending_rvec_back:extending_rvec_back::, - nth_back:nth_back::, + pub(super) const ITER: DoubleEndedIteratorFns = DoubleEndedIteratorFns { + next_back: next_back::, + extending_rvec_back: extending_rvec_back::, + nth_back: nth_back::, }; - pub(super) const NEW:DoubleEndedIteratorFns<()>=unsafe{ - Transmuter{ - from:Self::ITER - }.to - }; + pub(super) const NEW: DoubleEndedIteratorFns<()> = + unsafe { Transmuter { from: Self::ITER }.to }; } - /////////////////////////////////////////////////////////////////////////////////// - -pub(super) unsafe extern "C" fn next_back(this: RMut<'_, ErasedObject>)->ROption -where - I:DoubleEndedIterator +pub(super) unsafe extern "C" fn next_back(this: RMut<'_, ErasedObject>) -> ROption +where + I: DoubleEndedIterator, { extern_fn_panic_handling! { let this = this.transmute_into_mut::(); @@ -207,10 +187,10 @@ where pub(super) unsafe extern "C" fn extending_rvec_back( this: RMut<'_, ErasedObject>, - vec:&mut RVec, - taking:ROption -)where - I:DoubleEndedIterator + vec: &mut RVec, + taking: ROption, +) where + I: DoubleEndedIterator, { extern_fn_panic_handling! { let this = this.transmute_into_mut::(); @@ -221,15 +201,18 @@ pub(super) unsafe extern "C" fn extending_rvec_back( } } -pub(super) unsafe extern "C" fn nth_back(this: RMut<'_, ErasedObject>,mut at:usize)->ROption -where - I:DoubleEndedIterator +pub(super) unsafe extern "C" fn nth_back( + this: RMut<'_, ErasedObject>, + mut at: usize, +) -> ROption +where + I: DoubleEndedIterator, { extern_fn_panic_handling! { let this = this.transmute_into_mut::(); for x in this.rev() { - if at == 0 { - return RSome(x) + if at == 0 { + return RSome(x) } at -= 1; } diff --git a/abi_stable/src/erased_types/trait_objects.rs b/abi_stable/src/erased_types/trait_objects.rs index 56126653..bb8733fc 100644 --- a/abi_stable/src/erased_types/trait_objects.rs +++ b/abi_stable/src/erased_types/trait_objects.rs @@ -2,9 +2,7 @@ Ffi-safe trait objects for individual traits. */ -use std::{ - fmt::{self,Display,Debug}, -}; +use std::fmt::{self, Debug, Display}; #[allow(unused_imports)] use core_extensions::SelfOps; @@ -13,135 +11,123 @@ use super::{c_functions::*, *}; use crate::{ marker_type::ErasedObject, - sabi_types::{RRef, RMut}, - std_types::RBox, pointer_trait::{AsPtr, TransmuteElement}, + sabi_types::{RMut, RRef}, + std_types::RBox, }; - - ///////////////////////////////////////////////////////////// - /// An ffi-safe equivalent of `&mut dyn std::hash::Hasher`. #[repr(C)] #[derive(StableAbi)] pub struct HasherObject<'a> { this: RMut<'a, ErasedObject>, - hash_slice: unsafe extern "C" fn(RMut<'_, ErasedObject>, RSlice<'_, u8>) , - finish: unsafe extern "C" fn(RRef<'_, ErasedObject>) -> u64 , + hash_slice: unsafe extern "C" fn(RMut<'_, ErasedObject>, RSlice<'_, u8>), + finish: unsafe extern "C" fn(RRef<'_, ErasedObject>) -> u64, } impl<'a> HasherObject<'a> { /// Constructs a `HasherObject`. - pub fn new(this: &'a mut T) -> HasherObject<'a> + pub fn new(this: &'a mut T) -> HasherObject<'a> where - T:Hasher + T: Hasher, { HasherObject { - this: unsafe{ + this: unsafe { // The lifetime is tied to the input. this.transmute_element::() }, - hash_slice:hash_slice_Hasher::, - finish:finish_Hasher::, + hash_slice: hash_slice_Hasher::, + finish: finish_Hasher::, } } /// Reborrows this `HasherObject` with a smaller lifetime. - pub fn as_mut<'b:'a>(&'b mut self)->HasherObject<'b>{ - Self{ + pub fn as_mut<'b: 'a>(&'b mut self) -> HasherObject<'b> { + Self { this: self.this.reborrow(), - hash_slice:self.hash_slice, - finish:self.finish, + hash_slice: self.hash_slice, + finish: self.finish, } } } -impl<'a> Hasher for HasherObject<'a>{ +impl<'a> Hasher for HasherObject<'a> { fn finish(&self) -> u64 { - unsafe{ - (self.finish)(self.this.as_rref()) - } + unsafe { (self.finish)(self.this.as_rref()) } } fn write(&mut self, bytes: &[u8]) { - unsafe{ - (self.hash_slice)(self.this.reborrow(), bytes.into()) - } + unsafe { (self.hash_slice)(self.this.reborrow(), bytes.into()) } } } ////////////// - /// An ffi-safe equivalent of `Box` /// (if `dyn Debug + Display` was possible). #[repr(C)] #[derive(StableAbi)] -pub struct DebugDisplayObject{ - this:RBox, - display:unsafe extern "C" fn(RRef<'_, ErasedObject>,FormattingMode,&mut RString)->RResult<(),()>, - debug :unsafe extern "C" fn(RRef<'_, ErasedObject>,FormattingMode,&mut RString)->RResult<(),()>, +pub struct DebugDisplayObject { + this: RBox, + display: unsafe extern "C" fn( + RRef<'_, ErasedObject>, + FormattingMode, + &mut RString, + ) -> RResult<(), ()>, + debug: unsafe extern "C" fn( + RRef<'_, ErasedObject>, + FormattingMode, + &mut RString, + ) -> RResult<(), ()>, } - -impl DebugDisplayObject{ +impl DebugDisplayObject { /// Constructs this `DebugDisplayObject`. - pub fn new(value: T)->DebugDisplayObject - where T:Display+Debug+'static + pub fn new(value: T) -> DebugDisplayObject + where + T: Display + Debug + 'static, { - DebugDisplayObject{ - this:unsafe{ + DebugDisplayObject { + this: unsafe { // The lifetime here is 'static,so it's fine to erase the type. RBox::new(value).transmute_element::() }, - display:display_impl::, - debug :debug_impl::, + display: display_impl::, + debug: debug_impl::, } } /// Constructs a `DebugDisplayObject`.which doesn't output anything. - pub fn no_output()->DebugDisplayObject{ + pub fn no_output() -> DebugDisplayObject { Self::new(NoFmt) } } - -impl Display for DebugDisplayObject{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - unsafe{ - adapt_std_fmt::(self.this.as_rref(), self.display , f) - } +impl Display for DebugDisplayObject { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + unsafe { adapt_std_fmt::(self.this.as_rref(), self.display, f) } } } - -impl Debug for DebugDisplayObject{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - unsafe{ - adapt_std_fmt::(self.this.as_rref(), self.debug , f) - } +impl Debug for DebugDisplayObject { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + unsafe { adapt_std_fmt::(self.this.as_rref(), self.debug, f) } } } - - struct NoFmt; -impl Display for NoFmt{ - fn fmt(&self,_:&mut fmt::Formatter<'_>)->fmt::Result{ +impl Display for NoFmt { + fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result { Ok(()) } } -impl Debug for NoFmt{ - fn fmt(&self,_:&mut fmt::Formatter<'_>)->fmt::Result{ +impl Debug for NoFmt { + fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result { Ok(()) } } - - - - ////////////// diff --git a/abi_stable/src/erased_types/traits.rs b/abi_stable/src/erased_types/traits.rs index 1d975706..31a244fd 100644 --- a/abi_stable/src/erased_types/traits.rs +++ b/abi_stable/src/erased_types/traits.rs @@ -1,11 +1,10 @@ - /*! Traits for types wrapped in `DynTrait<_>` */ use crate::{ marker_type::NonOwningPhantom, - sabi_types::{Constructor,VersionStrings}, + sabi_types::{Constructor, VersionStrings}, std_types::{RBoxError, RStr}, }; @@ -14,13 +13,13 @@ use super::TypeInfo; #[allow(unused_imports)] use crate::type_level::{ bools::{False, True}, - impl_enum::{Implemented,Unimplemented}, + impl_enum::{Implemented, Unimplemented}, trait_marker, }; /** An `implementation type`, -with an associated `interface type` which describes the traits that +with an associated `interface type` which describes the traits that must be implemented when constructing a `DynTrait` from `Self`, using the `DynTrait::from_value` and `DynTrait::from_ptr` constructors, so as to pass an opaque type across ffi. @@ -35,7 +34,7 @@ from the `DynTrait::*_unerased` functions whenever they convert back and forth between `Self` and `Self::Interface`. */ -pub trait ImplType: Sized { +pub trait ImplType: Sized { /// Describes the traits that must be implemented when constructing a /// `DynTrait` from `Self`. type Interface: InterfaceType; @@ -46,17 +45,16 @@ pub trait ImplType: Sized { const INFO: &'static TypeInfo; } - macro_rules! declare_InterfaceType { ( $(#[$attrs:meta])* - assoc_types[ - $( + assoc_types[ + $( $(#[$assoc_attrs:meta])* type $trait_:ident ; - )* + )* ] ) => ( $(#[$attrs])* @@ -74,12 +72,11 @@ macro_rules! declare_InterfaceType { ) } - -declare_InterfaceType!{ +declare_InterfaceType! { /** -Defines the usable/required traits when creating a +Defines the usable/required traits when creating a `DynTrait, ThisInterfaceType>`. This trait can only be implemented using the @@ -109,7 +106,7 @@ use abi_stable::{ pub struct FooInterface; /* -The `#[sabi(impl_InterfaceType(Clone,Debug))]` helper attribute +The `#[sabi(impl_InterfaceType(Clone,Debug))]` helper attribute (as part of #[derive(StableAbi)]) above is roughly equivalent to this impl: impl InterfaceType for FooInterface { @@ -117,7 +114,7 @@ impl InterfaceType for FooInterface { type Debug= Implemented; - ///////////////////////////////////// + ///////////////////////////////////// //// defaulted associated types ///////////////////////////////////// @@ -150,15 +147,15 @@ impl InterfaceType for FooInterface { // type Deserialize= Unimplemented; // type FmtWrite= Unimplemented; - + // type IoWrite= Unimplemented; - + // type IoSeek= Unimplemented; - + // type IoRead= Unimplemented; // type IoBufRead= Unimplemented; - + // type Error= Unimplemented; } */ @@ -202,99 +199,89 @@ impl InterfaceType for FooInterface { type Deserialize; type Iterator; - + type DoubleEndedIterator; type FmtWrite; - + type IoWrite; - + type IoSeek; - + type IoRead; type IoBufRead; - + type Error; ] } - - /////////////////////////////////////////////////////////////////////////////// - /** Describes how a type is serialized by [`DynTrait`]. [`DynTrait`]: ../struct.DynTrait.html */ pub trait SerializeImplType<'s> { - /// An [`InterfaceType`] implementor which determines the + /// An [`InterfaceType`] implementor which determines the /// intermediate type through which this is serialized. /// /// [`InterfaceType`]: ./trait.InterfaceType.html - type Interface:SerializeProxyType<'s>; + type Interface: SerializeProxyType<'s>; fn serialize_impl( - &'s self + &'s self, ) -> Result<>::Proxy, RBoxError>; } - /** Determines the intermediate type a [`SerializeImplType`] implementor is converted into, and is then serialized. [`SerializeImplType`]: ./trait.SerializeImplType.html */ -pub trait SerializeProxyType<'borr>:InterfaceType{ +pub trait SerializeProxyType<'borr>: InterfaceType { /// The intermediate type. - type Proxy:'borr; + type Proxy: 'borr; } #[doc(hidden)] -pub trait GetSerializeProxyType<'borr>:InterfaceType{ +pub trait GetSerializeProxyType<'borr>: InterfaceType { type ProxyType; } -impl<'borr,I,PT> GetSerializeProxyType<'borr> for I +impl<'borr, I, PT> GetSerializeProxyType<'borr> for I where - I:InterfaceType, - I:GetSerializeProxyTypeHelper< - 'borr, - ::Serialize, - ProxyType=PT - >, + I: InterfaceType, + I: GetSerializeProxyTypeHelper<'borr, ::Serialize, ProxyType = PT>, { - type ProxyType=PT; + type ProxyType = PT; } #[doc(hidden)] -pub trait GetSerializeProxyTypeHelper<'borr,IS>:InterfaceType{ +pub trait GetSerializeProxyTypeHelper<'borr, IS>: InterfaceType { type ProxyType; } -impl<'borr,I> GetSerializeProxyTypeHelper<'borr,Implemented> for I +impl<'borr, I> GetSerializeProxyTypeHelper<'borr, Implemented> for I where - I:SerializeProxyType<'borr>, + I: SerializeProxyType<'borr>, { - type ProxyType=>::Proxy; + type ProxyType = >::Proxy; } -impl<'borr,I> GetSerializeProxyTypeHelper<'borr,Unimplemented> for I +impl<'borr, I> GetSerializeProxyTypeHelper<'borr, Unimplemented> for I where - I:InterfaceType, + I: InterfaceType, { - type ProxyType=(); + type ProxyType = (); } - /////////////////////////////////////// - /** Describes how `D` is deserialized,using a proxy to do so. @@ -303,7 +290,7 @@ so that the implementation can be delegated to the `implementation crate`. */ -pub trait DeserializeDyn<'borr,D> { +pub trait DeserializeDyn<'borr, D> { /// The type that is deserialized and then converted into `D`, /// with `DeserializeDyn::deserialize_dyn`. type Proxy; @@ -312,149 +299,123 @@ pub trait DeserializeDyn<'borr,D> { fn deserialize_dyn(s: Self::Proxy) -> Result; } - #[doc(hidden)] -pub trait GetDeserializeDynProxy<'borr,D>:InterfaceType{ +pub trait GetDeserializeDynProxy<'borr, D>: InterfaceType { type ProxyType; } -impl<'borr,I,D,PT> GetDeserializeDynProxy<'borr,D> for I +impl<'borr, I, D, PT> GetDeserializeDynProxy<'borr, D> for I where - I:InterfaceType, - I:GetDeserializeDynProxyHelper< - 'borr, - D, - ::Deserialize, - ProxyType=PT - >, + I: InterfaceType, + I: GetDeserializeDynProxyHelper<'borr, D, ::Deserialize, ProxyType = PT>, { - type ProxyType=PT; + type ProxyType = PT; } - #[doc(hidden)] -pub trait GetDeserializeDynProxyHelper<'borr,D,IS>:InterfaceType{ +pub trait GetDeserializeDynProxyHelper<'borr, D, IS>: InterfaceType { type ProxyType; } -impl<'borr,I,D> - GetDeserializeDynProxyHelper<'borr,D,Implemented> -for I +impl<'borr, I, D> GetDeserializeDynProxyHelper<'borr, D, Implemented> + for I where - I:InterfaceType, - I:DeserializeDyn<'borr,D> + I: InterfaceType, + I: DeserializeDyn<'borr, D>, { - type ProxyType=>::Proxy; + type ProxyType = >::Proxy; } -impl<'borr,I,D> - GetDeserializeDynProxyHelper<'borr,D,Unimplemented> -for I +impl<'borr, I, D> GetDeserializeDynProxyHelper<'borr, D, Unimplemented> + for I where - I:InterfaceType, + I: InterfaceType, { - type ProxyType=(); + type ProxyType = (); } - ///////////////////////////////////////////////////////////////////// - /// The way to specify the expected `Iterator::Item` type for an `InterfaceType`. /// /// This is a separate trait to allow iterators that yield borrowed elements. -pub trait IteratorItem<'a>:InterfaceType{ +pub trait IteratorItem<'a>: InterfaceType { /// The iterator item type. type Item; } - - /// Gets the expected `Iterator::Item` type for an `InterfaceType`, /// defaulting to `()` if it doesn't require `Iterator` to be implemented. /// /// Used by `DynTrait`'s vtable to give its iterator methods a defaulted return type. -pub trait IteratorItemOrDefault<'borr>:InterfaceType{ +pub trait IteratorItemOrDefault<'borr>: InterfaceType { /// The iterator item type. type Item; } - -impl<'borr,I,Item> IteratorItemOrDefault<'borr> for I -where - I:InterfaceType, - I:IteratorItemOrDefaultHelper< - 'borr, - ::Iterator, - Item=Item, - > +impl<'borr, I, Item> IteratorItemOrDefault<'borr> for I +where + I: InterfaceType, + I: IteratorItemOrDefaultHelper<'borr, ::Iterator, Item = Item>, { - type Item=Item; + type Item = Item; } - #[doc(hidden)] -pub trait IteratorItemOrDefaultHelper<'borr,ImplIsRequired>{ +pub trait IteratorItemOrDefaultHelper<'borr, ImplIsRequired> { type Item; } -impl<'borr,I,Item> IteratorItemOrDefaultHelper<'borr,Implemented> for I +impl<'borr, I, Item> IteratorItemOrDefaultHelper<'borr, Implemented> for I where - I:IteratorItem<'borr,Item=Item>, + I: IteratorItem<'borr, Item = Item>, { - type Item=Item; + type Item = Item; } - -impl<'borr,I> IteratorItemOrDefaultHelper<'borr,Unimplemented> for I{ - type Item=(); +impl<'borr, I> IteratorItemOrDefaultHelper<'borr, Unimplemented> for I { + type Item = (); } - - ////////////////////////////////////////////////////////////////// - pub use self::interface_for::InterfaceFor; #[doc(hidden)] -pub mod interface_for{ +pub mod interface_for { use super::*; use crate::type_level::downcasting::GetUTID; /// Helper struct to get an `ImplType` implementation for any type. - pub struct InterfaceFor( - NonOwningPhantom<(T,Interface,Downcasting)> + pub struct InterfaceFor( + NonOwningPhantom<(T, Interface, Downcasting)>, ); - impl ImplType for InterfaceFor - where - Interface:InterfaceType, - Downcasting:GetUTID, + impl ImplType for InterfaceFor + where + Interface: InterfaceType, + Downcasting: GetUTID, { - type Interface=Interface; - + type Interface = Interface; + /// The `&'static TypeInfo` constant,used when unerasing `DynTrait`s into a type. - const INFO:&'static TypeInfo=&TypeInfo{ - size:std::mem::size_of::(), - alignment:std::mem::align_of::(), - _uid:>::UID, - type_name:Constructor(crate::utils::get_type_name::), - module:RStr::from_str(""), - package:RStr::from_str(""), - package_version:VersionStrings::new("99.99.99"), - _private_field:(), + const INFO: &'static TypeInfo = &TypeInfo { + size: std::mem::size_of::(), + alignment: std::mem::align_of::(), + _uid: >::UID, + type_name: Constructor(crate::utils::get_type_name::), + module: RStr::from_str(""), + package: RStr::from_str(""), + package_version: VersionStrings::new("99.99.99"), + _private_field: (), }; } } - - - ///////////////////////////////////////////////////////////////////// -crate::impl_InterfaceType!{ +crate::impl_InterfaceType! { impl crate::erased_types::InterfaceType for () { type Send=True; type Sync=True; diff --git a/abi_stable/src/erased_types/type_info.rs b/abi_stable/src/erased_types/type_info.rs index 0c9874f7..581624a8 100644 --- a/abi_stable/src/erased_types/type_info.rs +++ b/abi_stable/src/erased_types/type_info.rs @@ -5,11 +5,10 @@ Contains TypeInfo,metadata for a type. use std::fmt; use crate::{ - sabi_types::{Constructor,MaybeCmp,VersionStrings}, - std_types::{RStr,utypeid::UTypeId}, + sabi_types::{Constructor, MaybeCmp, VersionStrings}, + std_types::{utypeid::UTypeId, RStr}, }; - /// Metadata stored in the vtable of `DynTrait<_>` #[derive(Debug, Eq, PartialEq)] #[repr(C)] @@ -30,7 +29,7 @@ pub struct TypeInfo { impl TypeInfo { /// Whether the `self` is the TypeInfo for the same type as `other` pub fn is_compatible(&self, other: &Self) -> bool { - self._uid==other._uid + self._uid == other._uid } } @@ -44,16 +43,14 @@ impl fmt::Display for TypeInfo { package:'{package}'\n\ package_version:{package_version}\n\ ", - ty=self.type_name, - size=self.size, - alignment=self.alignment, - module=self.module, - package=self.package, - package_version=self.package_version + ty = self.type_name, + size = self.size, + alignment = self.alignment, + module = self.module, + package = self.package, + package_version = self.package_version ) } } - //////////////////////////////////////////// - diff --git a/abi_stable/src/erased_types/vtable.rs b/abi_stable/src/erased_types/vtable.rs index 0e46a454..4a93ad29 100644 --- a/abi_stable/src/erased_types/vtable.rs +++ b/abi_stable/src/erased_types/vtable.rs @@ -4,105 +4,93 @@ Contains `DynTrait<_>`'s vtable,and related types/traits. */ use std::{ - fmt::{self, Debug,Write as FmtWrite}, + fmt::{self, Debug, Write as FmtWrite}, io, marker::PhantomData, }; use super::{ - *, c_functions::*, - iterator::{ - IteratorFns,MakeIteratorFns, - DoubleEndedIteratorFns,MakeDoubleEndedIteratorFns, - }, - traits::{ - IteratorItemOrDefault,InterfaceFor, - SerializeImplType,GetSerializeProxyType, - }, + iterator::{DoubleEndedIteratorFns, IteratorFns, MakeDoubleEndedIteratorFns, MakeIteratorFns}, + traits::{GetSerializeProxyType, InterfaceFor, IteratorItemOrDefault, SerializeImplType}, + *, }; use crate::{ - StableAbi, - marker_type::{ErasedObject,NonOwningPhantom}, - prefix_type::{PrefixTypeTrait,WithMetadata,panic_on_missing_fieldname}, - pointer_trait::{AsPtr, GetPointerKind,CanTransmuteElement}, - sabi_types::{RRef, RMut}, - std_types::{RSome,RNone,RIoError,RSeekFrom}, + marker_type::{ErasedObject, NonOwningPhantom}, + pointer_trait::{AsPtr, CanTransmuteElement, GetPointerKind}, + prefix_type::{panic_on_missing_fieldname, PrefixTypeTrait, WithMetadata}, + sabi_types::{RMut, RRef}, + std_types::{RIoError, RNone, RSeekFrom, RSome}, type_level::{ - impl_enum::{Implemented,Unimplemented,Implementability}, + impl_enum::{Implementability, Implemented, Unimplemented}, trait_marker, }, utils::Transmuter, + StableAbi, }; - use core_extensions::TypeIdentity; - - - - /// Returns the vtable used by DynTrait to do dynamic dispatch. -pub trait GetVtable<'borr,This,ErasedPtr,OrigPtr,I:InterfaceBound> { - +pub trait GetVtable<'borr, This, ErasedPtr, OrigPtr, I: InterfaceBound> { #[doc(hidden)] - const TMP_VTABLE:VTable<'borr,ErasedPtr,I>; + const TMP_VTABLE: VTable<'borr, ErasedPtr, I>; - - staticref!{ + staticref! { #[doc(hidden)] - const _WM_VTABLE: WithMetadata> = + const _WM_VTABLE: WithMetadata> = WithMetadata::new(PrefixTypeTrait::METADATA, Self::TMP_VTABLE) } #[doc(hidden)] - const _GET_INNER_VTABLE:VTable_Ref<'borr,ErasedPtr,I>=unsafe{ - VTable_Ref(Self::_WM_VTABLE.as_prefix()) - }; - + const _GET_INNER_VTABLE: VTable_Ref<'borr, ErasedPtr, I> = + unsafe { VTable_Ref(Self::_WM_VTABLE.as_prefix()) }; } - /// A helper type for constructing a `DynTrait` at compile-time, /// by passing `VTableDT::GET` to `DynTrait::from_const`. #[repr(transparent)] -pub struct VTableDT<'borr,T,ErasedPtr,OrigPtr,I,Downcasting>{ - pub(super) vtable:VTable_Ref<'borr,ErasedPtr,I>, - _for:NonOwningPhantom<(T,OrigPtr,Downcasting)> +pub struct VTableDT<'borr, T, ErasedPtr, OrigPtr, I, Downcasting> { + pub(super) vtable: VTable_Ref<'borr, ErasedPtr, I>, + _for: NonOwningPhantom<(T, OrigPtr, Downcasting)>, } -impl<'borr,T,ErasedPtr,OrigPtr,I,Downcasting> Copy - for VTableDT<'borr,T,ErasedPtr,OrigPtr,I,Downcasting> -{} +impl<'borr, T, ErasedPtr, OrigPtr, I, Downcasting> Copy + for VTableDT<'borr, T, ErasedPtr, OrigPtr, I, Downcasting> +{ +} -impl<'borr,T,ErasedPtr,OrigPtr,I,Downcasting> Clone - for VTableDT<'borr,T,ErasedPtr,OrigPtr,I,Downcasting> +impl<'borr, T, ErasedPtr, OrigPtr, I, Downcasting> Clone + for VTableDT<'borr, T, ErasedPtr, OrigPtr, I, Downcasting> { - fn clone(&self)->Self{ + fn clone(&self) -> Self { *self } } -impl<'borr,T,ErasedPtr,OrigPtr,I,Downcasting> - VTableDT<'borr,T,ErasedPtr,OrigPtr,I,Downcasting> +impl<'borr, T, ErasedPtr, OrigPtr, I, Downcasting> + VTableDT<'borr, T, ErasedPtr, OrigPtr, I, Downcasting> where - OrigPtr: CanTransmuteElement<(), PtrTarget = T, TransmutedPtr=ErasedPtr>, - ErasedPtr: AsPtr, + OrigPtr: CanTransmuteElement<(), PtrTarget = T, TransmutedPtr = ErasedPtr>, + ErasedPtr: AsPtr, I: InterfaceBound, - InterfaceFor: GetVtable<'borr,T,ErasedPtr,OrigPtr,I>, -{ + InterfaceFor: GetVtable<'borr, T, ErasedPtr, OrigPtr, I>, +{ /// Constructs a `VTableDT`. - pub const GET:Self=Self{ - vtable:< - InterfaceFor as - GetVtable<'borr,T,ErasedPtr,OrigPtr,I> - >::_GET_INNER_VTABLE, - _for:NonOwningPhantom::NEW, - }; + pub const GET: Self = + Self { + vtable: as GetVtable< + 'borr, + T, + ErasedPtr, + OrigPtr, + I, + >>::_GET_INNER_VTABLE, + _for: NonOwningPhantom::NEW, + }; } - macro_rules! declare_meta_vtable { ( interface=$interf:ident; @@ -130,7 +118,7 @@ macro_rules! declare_meta_vtable { field_index=$field_index:ident; $(struct_bound=$struct_bound:expr;)* - + impl[$($impl_params:tt)*] VtableFieldValue<$selector:ident> where [ $($where_clause:tt)* ] { $field_value:expr } @@ -185,7 +173,7 @@ macro_rules! declare_meta_vtable { )* pub fn iter( &self - )->IteratorFns< >::Item > + )->IteratorFns< >::Item > where $interf:InterfaceBound>, $interf:IteratorItemOrDefault<'borr>, @@ -255,16 +243,16 @@ macro_rules! declare_meta_vtable { $( - impl<'borr,$value,$erased_ptr,$orig_ptr,$interf> - VTableFieldType_<'borr,$value,$erased_ptr,$orig_ptr,$interf> - for trait_selector::$selector - where + impl<'borr,$value,$erased_ptr,$orig_ptr,$interf> + VTableFieldType_<'borr,$value,$erased_ptr,$orig_ptr,$interf> + for trait_selector::$selector + where $interf:InterfaceBound, { type Field=$field_ty; } - + impl<'borr,AnyFieldTy,$value,$erased_ptr,$orig_ptr,$interf> VTableFieldValue< 'borr, @@ -291,7 +279,7 @@ macro_rules! declare_meta_vtable { $interf > for trait_selector::$selector - where + where $interf:InterfaceBound, $field_ty:TypeIdentity, FieldTy:Copy, @@ -304,22 +292,22 @@ macro_rules! declare_meta_vtable { - impl<'borr,Anything,$value,X,$erased_ptr,$orig_ptr> - MarkerTrait<'borr,Unimplemented,$value,$erased_ptr,$orig_ptr> + impl<'borr,Anything,$value,X,$erased_ptr,$orig_ptr> + MarkerTrait<'borr,Unimplemented,$value,$erased_ptr,$orig_ptr> for Anything {} $( - impl<'borr,$value,X,$erased_ptr,$orig_ptr> - MarkerTrait<'borr,Implemented,$value,$erased_ptr,$orig_ptr> + impl<'borr,$value,X,$erased_ptr,$orig_ptr> + MarkerTrait<'borr,Implemented,$value,$erased_ptr,$orig_ptr> for trait_selector::$auto_trait where $($phantom_where_clause)* {} )* $( - impl<'borr,$value,X,$erased_ptr,$orig_ptr> - MarkerTrait<'borr,Implemented,$value,$erased_ptr,$orig_ptr> + impl<'borr,$value,X,$erased_ptr,$orig_ptr> + MarkerTrait<'borr,Implemented,$value,$erased_ptr,$orig_ptr> for trait_selector::$marker_trait where $($marker_where_clause)* {} @@ -344,7 +332,7 @@ macro_rules! declare_meta_vtable { } - impl<'borr,This,$value,$erased_ptr,$orig_ptr,$interf> + impl<'borr,This,$value,$erased_ptr,$orig_ptr,$interf> GetVtable<'borr,$value,$erased_ptr,$orig_ptr,$interf> for This where @@ -412,10 +400,10 @@ macro_rules! declare_meta_vtable { #[doc(hidden)] const EXTRA_CHECKS:EnabledTraits; - $( + $( /// Whether the trait is required, /// and is usable by a `DynTrait` parameterized with this `InterfaceType`. - const $selector:bool; + const $selector:bool; )* } @@ -430,7 +418,7 @@ macro_rules! declare_meta_vtable { #[allow(non_upper_case_globals)] impl InterfaceBound for I - where + where I:InterfaceType, $( I::$auto_trait:Implementability, )* $( I::$marker_trait:Implementability, )* @@ -438,7 +426,7 @@ macro_rules! declare_meta_vtable { { #[doc(hidden)] const EXTRA_CHECKS:EnabledTraits=EnabledTraits{ - + // Auto traits have to be equivalent in every linked library, // this is why this is an array,it must match exactly. auto_traits: @@ -468,16 +456,16 @@ macro_rules! declare_meta_vtable { 0, }; - $( + $( const $selector:bool=::IS_IMPLD; )* - + const __InterfaceBound_BLANKET_IMPL:PrivStruct= PrivStruct(PhantomData); } - impl<'borr,$erased_ptr,$interf> Debug for VTable_Ref<'borr,$erased_ptr,$interf> + impl<'borr,$erased_ptr,$interf> Debug for VTable_Ref<'borr,$erased_ptr,$interf> where $interf:InterfaceBound, { @@ -534,7 +522,7 @@ declare_meta_vtable! { priv _clone_ptr; option=Option,Some,None; field_index=field_index_for__clone_ptr; - + impl[] VtableFieldValue where [OrigP:Clone] { @@ -596,7 +584,7 @@ declare_meta_vtable! { field_index=field_index_for_priv_serialize; impl[] VtableFieldValue - where [ + where [ T:for<'s>SerializeImplType<'s,Interface=I>, I:for<'s>SerializeProxyType<'s>, ]{ @@ -749,7 +737,7 @@ declare_meta_vtable! { field_index=field_index_for__io_bufread; impl[] VtableFieldValue - where [ + where [ T:io::BufRead, I:InterfaceType> ]{ @@ -774,9 +762,7 @@ declare_meta_vtable! { ////////////// - /// Used to prevent InterfaceBound being implemented outside this module, /// since it is only constructed in the impl of InterfaceBound in this module. #[doc(hidden)] pub struct PrivStruct(PhantomData); - diff --git a/abi_stable/src/external_types.rs b/abi_stable/src/external_types.rs index 2e5e5d02..3088aca1 100644 --- a/abi_stable/src/external_types.rs +++ b/abi_stable/src/external_types.rs @@ -6,22 +6,17 @@ The modules here are named after the crates whose types are being wrapped. */ -#[cfg(feature="crossbeam-channel")] +#[cfg(feature = "crossbeam-channel")] #[cfg_attr(feature = "docsrs", doc(cfg(feature = "channels")))] pub mod crossbeam_channel; pub mod parking_lot; -#[cfg(feature="serde_json")] +#[cfg(feature = "serde_json")] #[cfg_attr(feature = "docsrs", doc(cfg(feature = "serde_json")))] pub mod serde_json; +pub use self::parking_lot::{RMutex, ROnce, RRwLock}; -pub use self::{ - parking_lot::{RMutex,RRwLock,ROnce}, -}; - - -#[cfg(feature="serde_json")] -pub use self::serde_json::{RawValueRef,RawValueBox}; - +#[cfg(feature = "serde_json")] +pub use self::serde_json::{RawValueBox, RawValueRef}; diff --git a/abi_stable/src/external_types/crossbeam_channel.rs b/abi_stable/src/external_types/crossbeam_channel.rs index 4b1a2cb8..7762d3f9 100644 --- a/abi_stable/src/external_types/crossbeam_channel.rs +++ b/abi_stable/src/external_types/crossbeam_channel.rs @@ -1,61 +1,45 @@ /*! -Ffi-safe wrapper types around the -[crossbeam-channel](https://crates.io/crates/crossbeam-channel/) +Ffi-safe wrapper types around the +[crossbeam-channel](https://crates.io/crates/crossbeam-channel/) channel types. */ use std::{ - fmt::{self,Debug}, + fmt::{self, Debug}, marker::PhantomData, time::Duration, }; use crossbeam_channel::{ - Receiver, - Sender, - SendError, - RecvError, + Receiver, RecvError, RecvTimeoutError, SendError, SendTimeoutError, Sender, TryRecvError, TrySendError, - TryRecvError, - SendTimeoutError, - RecvTimeoutError, }; use core_extensions::SelfOps; use crate::{ marker_type::UnsafeIgnoredType, - traits::{IntoReprRust,ErasedType}, - std_types::{RResult,ROk,RErr,ROption,RDuration,RBox}, - prefix_type::{PrefixTypeTrait,WithMetadata}, pointer_trait::AsPtr, + prefix_type::{PrefixTypeTrait, WithMetadata}, sabi_types::RRef, + std_types::{RBox, RDuration, RErr, ROk, ROption, RResult}, + traits::{ErasedType, IntoReprRust}, }; - mod errors; mod extern_fns; mod iteration; -#[cfg(all(test,not(feature="test_miri_track_raw")))] +#[cfg(all(test, not(feature = "test_miri_track_raw")))] mod tests; -use self::{ - errors::{ - RSendError, - RRecvError, - RTrySendError, - RTryRecvError, - RSendTimeoutError, - RRecvTimeoutError, - } +use self::errors::{ + RRecvError, RRecvTimeoutError, RSendError, RSendTimeoutError, RTryRecvError, RTrySendError, }; -pub use self::{ - iteration::{RIter,RIntoIter}, -}; +pub use self::iteration::{RIntoIter, RIter}; /////////////////////////////////////////////////////////////////////////////// @@ -72,221 +56,212 @@ pub use self::{ /// assert_eq!(rx.try_recv().ok(), None); /// /// ``` -pub fn never() -> RReceiver{ +pub fn never() -> RReceiver { crossbeam_channel::never::().into() } - /// Creates a channel which can hold up to `capacity` elements in its internal queue. -/// +/// /// If `capacity==0`,the value must be sent to a receiver in the middle of a `recv` call. -/// +/// /// # Panics -/// +/// /// Panics if `capacity >= usize::max_value() / 4`. -/// +/// /// # Example -/// +/// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; -/// +/// /// let (tx,rx)=mpmc::bounded::(3); -/// +/// /// std::thread::spawn(move||{ /// tx.send(10).unwrap(); /// tx.send(11).unwrap(); /// tx.send(12).unwrap(); /// }); -/// +/// /// assert_eq!( rx.recv().unwrap(), 10 ); /// assert_eq!( rx.recv().unwrap(), 11 ); /// assert_eq!( rx.recv().unwrap(), 12 ); /// assert!( rx.try_recv().is_err() ); -/// +/// /// ``` -/// -pub fn bounded(capacity:usize) -> (RSender, RReceiver) { - let (tx,rx)=crossbeam_channel::bounded::(capacity); - ( tx.into(), rx.into() ) +/// +pub fn bounded(capacity: usize) -> (RSender, RReceiver) { + let (tx, rx) = crossbeam_channel::bounded::(capacity); + (tx.into(), rx.into()) } /// Creates a channel which can hold an unbounded amount elements in its internal queue. -/// +/// /// # Example -/// +/// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; -/// +/// /// let (tx,rx)=mpmc::unbounded::<&'static str>(); -/// +/// /// let join_guard=std::thread::spawn(move||{ /// assert_eq!( rx.recv().unwrap(), "foo" ); /// assert_eq!( rx.recv().unwrap(), "bar" ); /// assert_eq!( rx.recv().unwrap(), "baz" ); /// assert!( rx.try_recv().is_err() ); /// }); -/// +/// /// tx.send("foo").unwrap(); /// tx.send("bar").unwrap(); /// tx.send("baz").unwrap(); -/// +/// /// join_guard.join().unwrap(); -/// +/// /// ``` -/// -/// +/// +/// pub fn unbounded() -> (RSender, RReceiver) { - let (tx,rx)=crossbeam_channel::unbounded::(); - ( tx.into(), rx.into() ) + let (tx, rx) = crossbeam_channel::unbounded::(); + (tx.into(), rx.into()) } - /////////////////////////////////////////////////////////////////////////////// - /// The sender end of a channel, /// which can be either bounded or unbounded. -/// +/// /// # Example -/// +/// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; -/// +/// /// let (tx,rx)=mpmc::bounded::<&'static str>(1024); -/// +/// /// std::thread::spawn(move||{ /// for _ in 0..4{ /// tx.send("Are we there yet.").unwrap(); /// } /// }); -/// +/// /// assert_eq!(rx.recv().unwrap(),"Are we there yet."); /// assert_eq!(rx.recv().unwrap(),"Are we there yet."); /// assert_eq!(rx.recv().unwrap(),"Are we there yet."); /// assert_eq!(rx.recv().unwrap(),"Are we there yet."); /// assert!( rx.recv().is_err() ); -/// -/// +/// +/// /// ``` -/// -/// +/// +/// #[repr(C)] #[derive(StableAbi)] -pub struct RSender{ - channel:RBox>, - vtable:VTable_Ref, +pub struct RSender { + channel: RBox>, + vtable: VTable_Ref, } - -impl RSender{ - fn vtable(&self)->VTable_Ref{ +impl RSender { + fn vtable(&self) -> VTable_Ref { self.vtable } - /// Blocks until `value` is either sent,or the the other end is disconnected. - /// + /// /// If the channel queue is full,this will block to send `value`. - /// + /// /// If the channel is disconnected,this will return an error with `value`. - /// + /// /// # Example - /// + /// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; - /// + /// /// let (tx,rx)=mpmc::bounded::(3); - /// + /// /// tx.send(1057).unwrap(); - /// + /// /// drop(rx); /// assert!( tx.send(0).is_err() ); - /// + /// /// ``` - /// - pub fn send(&self,value:T) -> Result<(),SendError>{ - let vtable=self.vtable(); + /// + pub fn send(&self, value: T) -> Result<(), SendError> { + let vtable = self.vtable(); - vtable.send()(self.channel.as_rref(),value) - .piped(result_from) + vtable.send()(self.channel.as_rref(), value).piped(result_from) } - /// Immediately sends `value`,or returns with an error. - /// + /// /// An error will be returned in these 2 conditions: - /// + /// /// - the channel is full. - /// + /// /// - the channel has been disconnected. - /// - /// If the channel has a capacity of 0,it will only send `value` if + /// + /// If the channel has a capacity of 0,it will only send `value` if /// the other end is calling `recv`. - /// + /// /// # Example - /// + /// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; - /// + /// /// let (tx,rx)=mpmc::bounded::(1); - /// + /// /// tx.try_send(true).unwrap(); /// assert!( tx.try_send(true).unwrap_err().is_full() ); - /// + /// /// drop(rx); /// assert!( tx.try_send(false).unwrap_err().is_disconnected() ); - /// + /// /// ``` - /// - /// - pub fn try_send(&self,value:T) -> Result<(),TrySendError>{ - let vtable=self.vtable(); + /// + /// + pub fn try_send(&self, value: T) -> Result<(), TrySendError> { + let vtable = self.vtable(); - vtable.try_send()(self.channel.as_rref(),value) - .piped(result_from) + vtable.try_send()(self.channel.as_rref(), value).piped(result_from) } /// Blocks until a timeout to send `value`. - /// + /// /// An error will be returned in these 2 conditions: - /// + /// /// - the value could not be sent before the timeout. - /// + /// /// - the channel has been disconnected. - /// - /// If the channel has a capacity of 0,it will only send `value` if + /// + /// If the channel has a capacity of 0,it will only send `value` if /// the other end calls `recv` before the timeout. - /// + /// /// # Example - /// + /// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; - /// + /// /// use std::time::Duration; - /// + /// /// let (tx,rx)=mpmc::bounded::<()>(1); - /// + /// /// let timeout=Duration::from_millis(1); - /// + /// /// tx.send_timeout((),timeout).unwrap(); /// assert!( tx.send_timeout((),timeout).unwrap_err().is_timeout() ); - /// + /// /// drop(rx); /// assert!( tx.send_timeout((),timeout).unwrap_err().is_disconnected() ); - /// + /// /// ``` - /// - pub fn send_timeout(&self,value:T,timeout:Duration) -> Result<(),SendTimeoutError>{ - let vtable=self.vtable(); + /// + pub fn send_timeout(&self, value: T, timeout: Duration) -> Result<(), SendTimeoutError> { + let vtable = self.vtable(); - vtable.send_timeout()(self.channel.as_rref(),value,timeout.into()) - .piped(result_from) + vtable.send_timeout()(self.channel.as_rref(), value, timeout.into()).piped(result_from) } /// Returns true if there are no values in the channel queue. @@ -307,8 +282,8 @@ impl RSender{ /// rx.recv().unwrap(); /// assert!( tx.is_empty() ); /// ``` - pub fn is_empty(&self) -> bool{ - let vtable=self.vtable(); + pub fn is_empty(&self) -> bool { + let vtable = self.vtable(); vtable.sender_is_empty()(self.channel.as_rref()) } @@ -336,8 +311,8 @@ impl RSender{ /// rx.recv().unwrap(); /// assert!( !tx.is_full() ); /// ``` - pub fn is_full(&self) -> bool{ - let vtable=self.vtable(); + pub fn is_full(&self) -> bool { + let vtable = self.vtable(); vtable.sender_is_full()(self.channel.as_rref()) } @@ -364,14 +339,14 @@ impl RSender{ /// assert_eq!(tx.len(),1); /// /// ``` - pub fn len(&self) -> usize{ - let vtable=self.vtable(); - + pub fn len(&self) -> usize { + let vtable = self.vtable(); + vtable.sender_len()(self.channel.as_rref()) } /// Returns the amount of values the channel queue can hold. - /// + /// /// This returns None if the channel is unbounded. /// /// # Example @@ -390,41 +365,36 @@ impl RSender{ /// } /// /// ``` - pub fn capacity(&self) -> Option{ - let vtable=self.vtable(); - - vtable.sender_capacity()(self.channel.as_rref()) - .into_rust() - } + pub fn capacity(&self) -> Option { + let vtable = self.vtable(); + vtable.sender_capacity()(self.channel.as_rref()).into_rust() + } } - -impl Clone for RSender{ +impl Clone for RSender { /// Clones this channel end,getting another handle into the channel. /// /// Note that this allocates an RBox<_>. - fn clone(&self)->Self{ - let vtable=self.vtable(); + fn clone(&self) -> Self { + let vtable = self.vtable(); - Self{ - channel:vtable.clone_sender()(self.channel.as_rref()), - vtable:self.vtable, + Self { + channel: vtable.clone_sender()(self.channel.as_rref()), + vtable: self.vtable, } } } -impl Debug for RSender{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Debug::fmt("RSender{..}",f) +impl Debug for RSender { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Debug::fmt("RSender{..}", f) } } -unsafe impl Sync for RSender{} - -unsafe impl Send for RSender{} - +unsafe impl Sync for RSender {} +unsafe impl Send for RSender {} impl_from_rust_repr! { impl[T] From> for RSender { @@ -437,21 +407,19 @@ impl_from_rust_repr! { } } - /////////////////////////////////////////////////////////////////////////////// - /// The receiver end of a channel, /// which can be either bounded or unbounded. -/// +/// /// # Examples -/// +/// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; -/// +/// /// let (tx,rx)=mpmc::unbounded::<&'static str>(); -/// +/// /// let join_guard=std::thread::spawn(move||{ /// assert_eq!(rx.recv().unwrap(),"PING"); /// assert_eq!(rx.recv().unwrap(),"PING"); @@ -459,137 +427,132 @@ impl_from_rust_repr! { /// assert_eq!(rx.recv().unwrap(),"PING"); /// assert!( rx.try_recv().unwrap_err().is_empty() ); /// }); -/// +/// /// for _ in 0..4{ /// tx.send("PING").unwrap(); /// } -/// +/// /// join_guard.join().unwrap(); -/// +/// /// assert!( tx.send("").is_err() ); -/// -/// +/// +/// /// ``` -/// +/// #[repr(C)] #[derive(StableAbi)] -pub struct RReceiver{ - channel:RBox>, - vtable:VTable_Ref, +pub struct RReceiver { + channel: RBox>, + vtable: VTable_Ref, } - -impl RReceiver{ - fn vtable(&self)->VTable_Ref{ +impl RReceiver { + fn vtable(&self) -> VTable_Ref { self.vtable } /// Blocks until a value is either received,or the the other end is disconnected. - /// + /// /// If the channel queue is empty,this will block to receive a value. - /// + /// /// This will return an error if the channel is disconnected. - /// - /// + /// + /// /// # Example - /// + /// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; - /// + /// /// let (tx,rx)=mpmc::bounded::<&'static str>(3); - /// + /// /// tx.send("J__e H____y").unwrap(); /// assert_eq!( rx.recv().unwrap(), "J__e H____y" ); - /// + /// /// drop(tx); /// assert!( rx.recv().is_err() ); - /// + /// /// ``` - /// - pub fn recv(&self) -> Result{ - let vtable=self.vtable(); + /// + pub fn recv(&self) -> Result { + let vtable = self.vtable(); - vtable.recv()(self.channel.as_rref()) - .piped(result_from) + vtable.recv()(self.channel.as_rref()).piped(result_from) } /// Immediately receives a value,or returns with an error. - /// + /// /// An error will be returned in these 2 conditions: - /// + /// /// - the channel is empty. - /// + /// /// - the channel has been disconnected. - /// - /// If the channel has a capacity of 0,it will only receive a value if + /// + /// If the channel has a capacity of 0,it will only receive a value if /// the other end is calling `send`. - /// - /// + /// + /// /// # Example - /// + /// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; - /// + /// /// let (tx,rx)=mpmc::bounded::<&'static str>(3); - /// + /// /// assert!( rx.try_recv().is_err() ); - /// + /// /// tx.send("D__e S_____r").unwrap(); /// assert_eq!( rx.try_recv().unwrap(), "D__e S_____r" ); - /// + /// /// drop(tx); /// assert!( rx.try_recv().is_err() ); - /// + /// /// ``` - pub fn try_recv(&self) -> Result{ - let vtable=self.vtable(); + pub fn try_recv(&self) -> Result { + let vtable = self.vtable(); - vtable.try_recv()(self.channel.as_rref()) - .piped(result_from) + vtable.try_recv()(self.channel.as_rref()).piped(result_from) } - /// Blocks until a timeout to receive a value. - /// + /// /// An error will be returned in these 2 conditions: - /// + /// /// - A value could not be received before the timeout. - /// + /// /// - the channel has been disconnected. - /// - /// If the channel has a capacity of 0,it will only receive a value if + /// + /// If the channel has a capacity of 0,it will only receive a value if /// the other end calls `send` before the timeout. - /// - /// + /// + /// /// # Example - /// + /// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; - /// + /// /// use std::time::Duration; - /// + /// /// let (tx,rx)=mpmc::bounded::<&'static str>(3); - /// + /// /// let timeout=Duration::from_millis(1); - /// + /// /// assert!( rx.recv_timeout(timeout).unwrap_err().is_timeout() ); - /// + /// /// tx.send("D__e S_____r").unwrap(); /// assert_eq!( rx.recv_timeout(timeout).unwrap(), "D__e S_____r" ); - /// + /// /// drop(tx); /// assert!( rx.recv_timeout(timeout).unwrap_err().is_disconnected() ); - /// + /// /// ``` - /// - pub fn recv_timeout(&self,timeout:Duration) -> Result{ - let vtable=self.vtable(); + /// + pub fn recv_timeout(&self, timeout: Duration) -> Result { + let vtable = self.vtable(); - vtable.recv_timeout()(self.channel.as_rref(),timeout.into()) - .piped(result_from) + vtable.recv_timeout()(self.channel.as_rref(), timeout.into()).piped(result_from) } /// Returns true if there are no values in the channel queue. @@ -610,8 +573,8 @@ impl RReceiver{ /// rx.recv().unwrap(); /// assert!( rx.is_empty() ); /// ``` - pub fn is_empty(&self) -> bool{ - let vtable=self.vtable(); + pub fn is_empty(&self) -> bool { + let vtable = self.vtable(); vtable.receiver_is_empty()(self.channel.as_rref()) } @@ -639,8 +602,8 @@ impl RReceiver{ /// rx.recv().unwrap(); /// assert!( !rx.is_full() ); /// ``` - pub fn is_full(&self) -> bool{ - let vtable=self.vtable(); + pub fn is_full(&self) -> bool { + let vtable = self.vtable(); vtable.receiver_is_full()(self.channel.as_rref()) } @@ -667,14 +630,14 @@ impl RReceiver{ /// assert_eq!(rx.len(),1); /// /// ``` - pub fn len(&self) -> usize{ - let vtable=self.vtable(); - + pub fn len(&self) -> usize { + let vtable = self.vtable(); + vtable.receiver_len()(self.channel.as_rref()) } /// Returns the amount of values the channel queue can hold. - /// + /// /// This returns None if the channel is unbounded. /// /// # Example @@ -693,40 +656,37 @@ impl RReceiver{ /// } /// /// ``` - pub fn capacity(&self) -> Option{ - let vtable=self.vtable(); - - vtable.receiver_capacity()(self.channel.as_rref()) - .into_rust() + pub fn capacity(&self) -> Option { + let vtable = self.vtable(); + + vtable.receiver_capacity()(self.channel.as_rref()).into_rust() } /// Creates an Iterator that receives values from the channel. /// /// # Example - /// + /// #[cfg_attr(not(feature = "test_miri_track_raw"), doc = "```rust")] #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; - /// + /// /// use std::thread; - /// + /// /// let (tx,rx)=mpmc::bounded::(1); - /// + /// /// thread::spawn(move||{ /// for i in 0..1000 { /// tx.send(i).unwrap(); /// } /// }); - /// + /// /// for (i,n) in rx.iter().enumerate() { /// assert_eq!(i,n); /// } - /// + /// /// ``` - pub fn iter(&self)->RIter<'_,T>{ - RIter{ - channel:self, - } + pub fn iter(&self) -> RIter<'_, T> { + RIter { channel: self } } } @@ -748,36 +708,33 @@ impl IntoIterator for RReceiver { /// Creates an Iterator that receives values from the channel. #[inline] fn into_iter(self) -> RIntoIter { - RIntoIter { - channel: self - } + RIntoIter { channel: self } } } -impl Clone for RReceiver{ +impl Clone for RReceiver { /// Clones this channel end,getting another handle into the channel. /// /// Note that this allocates an RBox<_>. - fn clone(&self)->Self{ - let vtable=self.vtable(); + fn clone(&self) -> Self { + let vtable = self.vtable(); - Self{ - channel:vtable.clone_receiver()(self.channel.as_rref()), - vtable:self.vtable, + Self { + channel: vtable.clone_receiver()(self.channel.as_rref()), + vtable: self.vtable, } } } -impl Debug for RReceiver{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Debug::fmt("RReceiver{..}",f) +impl Debug for RReceiver { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Debug::fmt("RReceiver{..}", f) } } -unsafe impl Sync for RReceiver{} - -unsafe impl Send for RReceiver{} +unsafe impl Sync for RReceiver {} +unsafe impl Send for RReceiver {} impl_from_rust_repr! { impl[T] From> for RReceiver { @@ -790,112 +747,94 @@ impl_from_rust_repr! { } } - /////////////////////////////////////////////////////////////////////////////// - #[inline] -fn result_from(res:RResult)->Result +fn result_from(res: RResult) -> Result where - E0:Into + E0: Into, { match res { - ROk(x)=>Ok(x), - RErr(e)=>Err(e.into()), + ROk(x) => Ok(x), + RErr(e) => Err(e.into()), } } - - #[repr(C)] #[derive(StableAbi)] -struct ErasedSender( - PhantomData, - UnsafeIgnoredType>, -); +struct ErasedSender(PhantomData, UnsafeIgnoredType>); unsafe impl ErasedType<'_> for ErasedSender { - type Unerased=Sender; + type Unerased = Sender; } #[repr(C)] #[derive(StableAbi)] -struct ErasedReceiver( - PhantomData, - UnsafeIgnoredType>, -); +struct ErasedReceiver(PhantomData, UnsafeIgnoredType>); unsafe impl ErasedType<'_> for ErasedReceiver { - type Unerased=Receiver; + type Unerased = Receiver; } /////////////////////////////////////////////////////////////////////////////// - #[repr(C)] #[derive(StableAbi)] #[sabi(kind(Prefix))] #[sabi(missing_field(panic))] //#[sabi(debug_print)] -struct VTable{ - send:extern "C" fn(this: RRef<'_, ErasedSender>,T) -> RResult<(),RSendError>, - try_send:extern "C" fn(this: RRef<'_, ErasedSender>,T) -> RResult<(),RTrySendError>, - send_timeout: - extern "C" fn( - this: RRef<'_, ErasedSender>, - value:T, - timeout:RDuration - ) -> RResult<(),RSendTimeoutError>, - clone_sender:extern "C" fn(this: RRef<'_, ErasedSender>) -> RBox>, - sender_is_empty:extern "C" fn(this: RRef<'_, ErasedSender>) -> bool, - sender_is_full:extern "C" fn(this: RRef<'_, ErasedSender>) -> bool, - sender_len:extern "C" fn(this: RRef<'_, ErasedSender>) -> usize, - sender_capacity:extern "C" fn(this: RRef<'_, ErasedSender>) -> ROption, - - - recv: - extern "C" fn(this: RRef<'_, ErasedReceiver>) -> RResult, - try_recv: - extern "C" fn(this: RRef<'_, ErasedReceiver>) -> RResult, - recv_timeout: - extern "C" fn( - this: RRef<'_, ErasedReceiver>, - timeout: RDuration - ) -> RResult, - clone_receiver:extern "C" fn(this: RRef<'_, ErasedReceiver>) -> RBox>, - receiver_is_empty:extern "C" fn(this: RRef<'_, ErasedReceiver>) -> bool, - receiver_is_full:extern "C" fn(this: RRef<'_, ErasedReceiver>) -> bool, - receiver_len:extern "C" fn(this: RRef<'_, ErasedReceiver>) -> usize, +struct VTable { + send: extern "C" fn(this: RRef<'_, ErasedSender>, T) -> RResult<(), RSendError>, + try_send: extern "C" fn(this: RRef<'_, ErasedSender>, T) -> RResult<(), RTrySendError>, + send_timeout: extern "C" fn( + this: RRef<'_, ErasedSender>, + value: T, + timeout: RDuration, + ) -> RResult<(), RSendTimeoutError>, + clone_sender: extern "C" fn(this: RRef<'_, ErasedSender>) -> RBox>, + sender_is_empty: extern "C" fn(this: RRef<'_, ErasedSender>) -> bool, + sender_is_full: extern "C" fn(this: RRef<'_, ErasedSender>) -> bool, + sender_len: extern "C" fn(this: RRef<'_, ErasedSender>) -> usize, + sender_capacity: extern "C" fn(this: RRef<'_, ErasedSender>) -> ROption, + + recv: extern "C" fn(this: RRef<'_, ErasedReceiver>) -> RResult, + try_recv: extern "C" fn(this: RRef<'_, ErasedReceiver>) -> RResult, + recv_timeout: extern "C" fn( + this: RRef<'_, ErasedReceiver>, + timeout: RDuration, + ) -> RResult, + clone_receiver: extern "C" fn(this: RRef<'_, ErasedReceiver>) -> RBox>, + receiver_is_empty: extern "C" fn(this: RRef<'_, ErasedReceiver>) -> bool, + receiver_is_full: extern "C" fn(this: RRef<'_, ErasedReceiver>) -> bool, + receiver_len: extern "C" fn(this: RRef<'_, ErasedReceiver>) -> usize, #[sabi(last_prefix_field)] - receiver_capacity:extern "C" fn(this: RRef<'_, ErasedReceiver>) -> ROption, + receiver_capacity: extern "C" fn(this: RRef<'_, ErasedReceiver>) -> ROption, } - -struct MakeVTable<'a,T>(&'a T); - - -impl<'a,T:'a> MakeVTable<'a,T>{ - const VALUE:VTable=VTable{ - send:ErasedSender::send, - try_send:ErasedSender::try_send, - send_timeout:ErasedSender::send_timeout, - clone_sender:ErasedSender::clone, - sender_is_empty:ErasedSender::is_empty, - sender_is_full:ErasedSender::is_full, - sender_len:ErasedSender::len, - sender_capacity:ErasedSender::capacity, - - recv:ErasedReceiver::recv, - try_recv:ErasedReceiver::try_recv, - recv_timeout:ErasedReceiver::recv_timeout, - clone_receiver:ErasedReceiver::clone, - receiver_is_empty:ErasedReceiver::is_empty, - receiver_is_full:ErasedReceiver::is_full, - receiver_len:ErasedReceiver::len, - receiver_capacity:ErasedReceiver::capacity, +struct MakeVTable<'a, T>(&'a T); + +impl<'a, T: 'a> MakeVTable<'a, T> { + const VALUE: VTable = VTable { + send: ErasedSender::send, + try_send: ErasedSender::try_send, + send_timeout: ErasedSender::send_timeout, + clone_sender: ErasedSender::clone, + sender_is_empty: ErasedSender::is_empty, + sender_is_full: ErasedSender::is_full, + sender_len: ErasedSender::len, + sender_capacity: ErasedSender::capacity, + + recv: ErasedReceiver::recv, + try_recv: ErasedReceiver::try_recv, + recv_timeout: ErasedReceiver::recv_timeout, + clone_receiver: ErasedReceiver::clone, + receiver_is_empty: ErasedReceiver::is_empty, + receiver_is_full: ErasedReceiver::is_full, + receiver_len: ErasedReceiver::len, + receiver_capacity: ErasedReceiver::capacity, }; - staticref!{ + staticref! { const WM_VALUE: WithMetadata> = WithMetadata::new(PrefixTypeTrait::METADATA, Self::VALUE) } @@ -903,4 +842,3 @@ impl<'a,T:'a> MakeVTable<'a,T>{ // The VTABLE for this type in this executable/library const VTABLE: VTable_Ref = VTable_Ref(Self::WM_VALUE.as_prefix()); } - diff --git a/abi_stable/src/external_types/crossbeam_channel/errors.rs b/abi_stable/src/external_types/crossbeam_channel/errors.rs index 8aa27ecb..3f970655 100644 --- a/abi_stable/src/external_types/crossbeam_channel/errors.rs +++ b/abi_stable/src/external_types/crossbeam_channel/errors.rs @@ -6,42 +6,35 @@ use crate::StableAbi; use std::{ error::Error as ErrorTrait, - fmt::{self,Debug,Display}, + fmt::{self, Debug, Display}, }; /////////////////////////////////////////////////////////////////////////////// - #[repr(transparent)] -#[derive(PartialEq, Eq, Clone, Copy,StableAbi)] +#[derive(PartialEq, Eq, Clone, Copy, StableAbi)] pub struct RSendError(pub T); - -impl RSendError{ - pub fn into_inner(self)->T{ +impl RSendError { + pub fn into_inner(self) -> T { self.0 } } - impl Debug for RSendError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.pad("RSendError{..}") } } - impl Display for RSendError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.pad("Attempting to send on a disconnected channel") } } - - impl ErrorTrait for RSendError {} - impl_from_rust_repr! { impl[T] From> for RSendError { fn(this){ @@ -60,30 +53,24 @@ impl_into_rust_repr! { /////////////////////////////////////////////////////////////////////////////// - #[repr(C)] -#[derive(PartialEq, Eq, Clone, Copy,StableAbi)] +#[derive(PartialEq, Eq, Clone, Copy, StableAbi)] pub struct RRecvError; - impl Debug for RRecvError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.pad("RRecvError{..}") } } - impl Display for RRecvError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.pad("Attempting to recv on a disconnected channel") } } - - impl ErrorTrait for RRecvError {} - impl_from_rust_repr! { impl From for RRecvError { fn(_this){ @@ -100,39 +87,35 @@ impl_into_rust_repr! { } } - /////////////////////////////////////////////////////////////////////////////// #[repr(u8)] -#[derive(PartialEq, Eq, Clone, Copy,StableAbi)] +#[derive(PartialEq, Eq, Clone, Copy, StableAbi)] pub enum RTrySendError { Full(T), Disconnected(T), } -impl RTrySendError{ - pub fn into_inner(self) -> T{ +impl RTrySendError { + pub fn into_inner(self) -> T { match self { - RTrySendError::Full(v)=>v, - RTrySendError::Disconnected(v)=>v, + RTrySendError::Full(v) => v, + RTrySendError::Disconnected(v) => v, } } - pub fn is_full(&self) -> bool{ - matches!(self, RTrySendError::Full{..}) + pub fn is_full(&self) -> bool { + matches!(self, RTrySendError::Full { .. }) } - pub fn is_disconnected(&self) -> bool{ - matches!(self, RTrySendError::Disconnected{..}) + pub fn is_disconnected(&self) -> bool { + matches!(self, RTrySendError::Disconnected { .. }) } } - impl Debug for RTrySendError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let msg=match self { - RTrySendError::Full{..} => - "Full{..}", - RTrySendError::Disconnected{..} => - "Disconnected{..}", + let msg = match self { + RTrySendError::Full { .. } => "Full{..}", + RTrySendError::Disconnected { .. } => "Disconnected{..}", }; f.pad(msg) } @@ -140,20 +123,16 @@ impl Debug for RTrySendError { impl Display for RTrySendError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let msg=match self { - RTrySendError::Full{..} => - "Attempting to send on a full channel", - RTrySendError::Disconnected{..} => - "Attempting to send on a disconnected channel", + let msg = match self { + RTrySendError::Full { .. } => "Attempting to send on a full channel", + RTrySendError::Disconnected { .. } => "Attempting to send on a disconnected channel", }; f.pad(msg) } } - impl ErrorTrait for RTrySendError {} - impl_from_rust_repr! { impl[T] From> for RTrySendError { fn(this){ @@ -178,43 +157,36 @@ impl_into_rust_repr! { } } - /////////////////////////////////////////////////////////////////////////////// - #[repr(u8)] -#[derive(Debug,PartialEq, Eq, Clone, Copy,StableAbi)] +#[derive(Debug, PartialEq, Eq, Clone, Copy, StableAbi)] pub enum RTryRecvError { Empty, Disconnected, } - -impl RTryRecvError{ - pub fn is_empty(&self) -> bool{ - *self==RTryRecvError::Empty +impl RTryRecvError { + pub fn is_empty(&self) -> bool { + *self == RTryRecvError::Empty } - pub fn is_disconnected(&self) -> bool{ - *self==RTryRecvError::Disconnected + pub fn is_disconnected(&self) -> bool { + *self == RTryRecvError::Disconnected } } impl Display for RTryRecvError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let msg=match self { - RTryRecvError::Empty{..} => - "Attempting to recv on an empty channel", - RTryRecvError::Disconnected{..} => - "Attempting to recv on a disconnected channel", + let msg = match self { + RTryRecvError::Empty { .. } => "Attempting to recv on an empty channel", + RTryRecvError::Disconnected { .. } => "Attempting to recv on a disconnected channel", }; f.pad(msg) } } - -impl ErrorTrait for RTryRecvError{} - +impl ErrorTrait for RTryRecvError {} impl_from_rust_repr! { impl From for RTryRecvError { @@ -240,63 +212,54 @@ impl_into_rust_repr! { } } - - /////////////////////////////////////////////////////////////////////////////// #[repr(u8)] -#[derive(PartialEq, Eq, Clone, Copy,StableAbi)] +#[derive(PartialEq, Eq, Clone, Copy, StableAbi)] pub enum RSendTimeoutError { Timeout(T), Disconnected(T), } - -impl RSendTimeoutError{ - pub fn into_inner(self) -> T{ +impl RSendTimeoutError { + pub fn into_inner(self) -> T { match self { - RSendTimeoutError::Timeout(v)=>v, - RSendTimeoutError::Disconnected(v)=>v, + RSendTimeoutError::Timeout(v) => v, + RSendTimeoutError::Disconnected(v) => v, } } - pub fn is_timeout(&self) -> bool{ - matches!(self, RSendTimeoutError::Timeout{..}) + pub fn is_timeout(&self) -> bool { + matches!(self, RSendTimeoutError::Timeout { .. }) } - pub fn is_disconnected(&self) -> bool{ - matches!(self, RSendTimeoutError::Disconnected{..}) + pub fn is_disconnected(&self) -> bool { + matches!(self, RSendTimeoutError::Disconnected { .. }) } } - impl Debug for RSendTimeoutError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let msg=match self { - RSendTimeoutError::Timeout{..} => - "Timeout{..}", - RSendTimeoutError::Disconnected{..} => - "Disconnected{..}", + let msg = match self { + RSendTimeoutError::Timeout { .. } => "Timeout{..}", + RSendTimeoutError::Disconnected { .. } => "Disconnected{..}", }; f.pad(msg) } } - impl Display for RSendTimeoutError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let msg=match *self { - RSendTimeoutError::Timeout{..} => - "Timed out while attempting to send on a channel", - RSendTimeoutError::Disconnected{..} => - "Attempting to send on a disconnected channel", + let msg = match *self { + RSendTimeoutError::Timeout { .. } => "Timed out while attempting to send on a channel", + RSendTimeoutError::Disconnected { .. } => { + "Attempting to send on a disconnected channel" + } }; f.pad(msg) } } - impl ErrorTrait for RSendTimeoutError {} - impl_from_rust_repr! { impl[T] From> for RSendTimeoutError { fn(this){ @@ -323,45 +286,38 @@ impl_into_rust_repr! { } } - - /////////////////////////////////////////////////////////////////////////////// - #[repr(u8)] -#[derive(Debug,PartialEq, Eq, Clone, Copy,StableAbi)] +#[derive(Debug, PartialEq, Eq, Clone, Copy, StableAbi)] pub enum RRecvTimeoutError { Timeout, Disconnected, } - -impl RRecvTimeoutError{ - pub fn is_timeout(&self) -> bool{ - matches!(self, RRecvTimeoutError::Timeout{..}) +impl RRecvTimeoutError { + pub fn is_timeout(&self) -> bool { + matches!(self, RRecvTimeoutError::Timeout { .. }) } - pub fn is_disconnected(&self) -> bool{ - matches!(self, RRecvTimeoutError::Disconnected{..}) + pub fn is_disconnected(&self) -> bool { + matches!(self, RRecvTimeoutError::Disconnected { .. }) } } - impl Display for RRecvTimeoutError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let msg=match self { - RRecvTimeoutError::Timeout{..} => - "Timed out while attempting to recv on a channel", - RRecvTimeoutError::Disconnected{..} => - "Attempting to recv on a disconnected channel", + let msg = match self { + RRecvTimeoutError::Timeout { .. } => "Timed out while attempting to recv on a channel", + RRecvTimeoutError::Disconnected { .. } => { + "Attempting to recv on a disconnected channel" + } }; f.pad(msg) } } - impl ErrorTrait for RRecvTimeoutError {} - impl_from_rust_repr! { impl From for RRecvTimeoutError { fn(this){ @@ -388,6 +344,4 @@ impl_into_rust_repr! { } } - - -/////////////////////////////////////////////////////////////////////////////// \ No newline at end of file +/////////////////////////////////////////////////////////////////////////////// diff --git a/abi_stable/src/external_types/crossbeam_channel/extern_fns.rs b/abi_stable/src/external_types/crossbeam_channel/extern_fns.rs index a5b92e1d..fed8881d 100644 --- a/abi_stable/src/external_types/crossbeam_channel/extern_fns.rs +++ b/abi_stable/src/external_types/crossbeam_channel/extern_fns.rs @@ -3,125 +3,103 @@ use super::*; use crate::traits::IntoReprC; macro_rules! shared_fns { - ( + ( erased=$erased:ident - unerased=$unerased:ident - ) => ( - - impl $erased{ - pub(super)fn from_unerased_value(value:$unerased)->RBox{ - unsafe{ - let boxed=RBox::new(value); + unerased=$unerased:ident + ) => { + impl $erased { + pub(super) fn from_unerased_value(value: $unerased) -> RBox { + unsafe { + let boxed = RBox::new(value); ErasedType::from_unerased(boxed) } } - fn run<'a,F,R>(this: RRef<'a, Self>, f:F)->R - where F:FnOnce(&'a $unerased)->R + fn run<'a, F, R>(this: RRef<'a, Self>, f: F) -> R + where + F: FnOnce(&'a $unerased) -> R, { - extern_fn_panic_handling!{ + extern_fn_panic_handling! { unsafe{ f(Self::downcast_into(this).get()) } } } - - pub(super) extern "C" fn clone(this: RRef<'_, Self>) -> RBox{ - Self::run(this, |this|{ - Self::from_unerased_value(this.clone()) - }) + + pub(super) extern "C" fn clone(this: RRef<'_, Self>) -> RBox { + Self::run(this, |this| Self::from_unerased_value(this.clone())) } - pub(super) extern "C" fn is_empty(this: RRef<'_, Self>) -> bool{ - Self::run(this, |this|{ - this.is_empty() - }) + pub(super) extern "C" fn is_empty(this: RRef<'_, Self>) -> bool { + Self::run(this, |this| this.is_empty()) } - pub(super) extern "C" fn is_full(this: RRef<'_, Self>) -> bool{ - Self::run(this, |this|{ - this.is_full() - }) + pub(super) extern "C" fn is_full(this: RRef<'_, Self>) -> bool { + Self::run(this, |this| this.is_full()) } - pub(super) extern "C" fn len(this: RRef<'_, Self>) -> usize{ - Self::run(this, |this|{ - this.len() - }) + pub(super) extern "C" fn len(this: RRef<'_, Self>) -> usize { + Self::run(this, |this| this.len()) } - pub(super) extern "C" fn capacity(this: RRef<'_, Self>) -> ROption{ - Self::run(this, |this|{ - this.capacity().into_c() - }) + pub(super) extern "C" fn capacity(this: RRef<'_, Self>) -> ROption { + Self::run(this, |this| this.capacity().into_c()) } } - - ) + }; } - -shared_fns!{ +shared_fns! { erased=ErasedSender unerased=Sender } - -shared_fns!{ +shared_fns! { erased=ErasedReceiver unerased=Receiver } - #[inline] -fn rresult_from(res:Result)->RResult +fn rresult_from(res: Result) -> RResult where - E0:Into + E0: Into, { match res { - Ok(x)=>ROk(x), - Err(e)=>RErr(e.into()), + Ok(x) => ROk(x), + Err(e) => RErr(e.into()), } } - -impl ErasedSender{ - pub(super) extern "C" fn send(this: RRef<'_, Self>,val:T) -> RResult<(),RSendError>{ - Self::run(this, |this|{ - this.send(val).piped(rresult_from) - }) +impl ErasedSender { + pub(super) extern "C" fn send(this: RRef<'_, Self>, val: T) -> RResult<(), RSendError> { + Self::run(this, |this| this.send(val).piped(rresult_from)) } - pub(super) extern "C" fn try_send(this: RRef<'_, Self>,val:T) -> RResult<(),RTrySendError>{ - Self::run(this, |this|{ - this.try_send(val).piped(rresult_from) - }) + pub(super) extern "C" fn try_send( + this: RRef<'_, Self>, + val: T, + ) -> RResult<(), RTrySendError> { + Self::run(this, |this| this.try_send(val).piped(rresult_from)) } pub(super) extern "C" fn send_timeout( this: RRef<'_, Self>, - val:T, - timeout:RDuration, - ) -> RResult<(),RSendTimeoutError>{ - Self::run(this, |this|{ - this.send_timeout(val,timeout.into()).piped(rresult_from) + val: T, + timeout: RDuration, + ) -> RResult<(), RSendTimeoutError> { + Self::run(this, |this| { + this.send_timeout(val, timeout.into()).piped(rresult_from) }) } } - -impl ErasedReceiver{ - pub(super) extern "C" fn recv(this: RRef<'_, Self>) -> RResult{ - Self::run(this, |this|{ - this.recv().piped(rresult_from) - }) +impl ErasedReceiver { + pub(super) extern "C" fn recv(this: RRef<'_, Self>) -> RResult { + Self::run(this, |this| this.recv().piped(rresult_from)) } - pub(super) extern "C" fn try_recv(this: RRef<'_, Self>) -> RResult{ - Self::run(this, |this|{ - this.try_recv().piped(rresult_from) - }) + pub(super) extern "C" fn try_recv(this: RRef<'_, Self>) -> RResult { + Self::run(this, |this| this.try_recv().piped(rresult_from)) } pub(super) extern "C" fn recv_timeout( this: RRef<'_, Self>, - timeout:RDuration, - ) -> RResult{ - Self::run(this, |this|{ + timeout: RDuration, + ) -> RResult { + Self::run(this, |this| { this.recv_timeout(timeout.into()).piped(rresult_from) }) } } - diff --git a/abi_stable/src/external_types/crossbeam_channel/iteration.rs b/abi_stable/src/external_types/crossbeam_channel/iteration.rs index e250cdcb..4280edaa 100644 --- a/abi_stable/src/external_types/crossbeam_channel/iteration.rs +++ b/abi_stable/src/external_types/crossbeam_channel/iteration.rs @@ -26,10 +26,8 @@ impl<'a, T> Debug for RIter<'a, T> { } } - /////////////////////////////////////////////////////////////////////////////// - /// An iterator which receives the values sent through the channel, /// blocking until a value is received. /// @@ -52,4 +50,4 @@ impl Debug for RIntoIter { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.pad("RIntoIter{..}") } -} \ No newline at end of file +} diff --git a/abi_stable/src/external_types/crossbeam_channel/tests.rs b/abi_stable/src/external_types/crossbeam_channel/tests.rs index aa1f133c..baddd587 100644 --- a/abi_stable/src/external_types/crossbeam_channel/tests.rs +++ b/abi_stable/src/external_types/crossbeam_channel/tests.rs @@ -2,265 +2,257 @@ use super::*; use crossbeam_utils::thread::scope as scoped_thread; - #[test] -fn test_size_methods(){ - let cap=5; +fn test_size_methods() { + let cap = 5; { - let (tx,rx)=bounded(cap); - assert_eq!(tx.capacity(),Some(cap)); - assert_eq!(rx.capacity(),Some(cap)); + let (tx, rx) = bounded(cap); + assert_eq!(tx.capacity(), Some(cap)); + assert_eq!(rx.capacity(), Some(cap)); - assert_eq!(tx.len(),0); - assert_eq!(rx.len(),0); + assert_eq!(tx.len(), 0); + assert_eq!(rx.len(), 0); assert!(tx.is_empty()); assert!(rx.is_empty()); for i in 0..cap { tx.send(i).unwrap(); - assert_eq!(tx.len(),i+1); - assert_eq!(rx.len(),i+1); + assert_eq!(tx.len(), i + 1); + assert_eq!(rx.len(), i + 1); } - assert_eq!(tx.len(),cap); - assert_eq!(rx.len(),cap); + assert_eq!(tx.len(), cap); + assert_eq!(rx.len(), cap); assert!(tx.is_full()); assert!(rx.is_full()); for i in 0..cap { - assert_eq!(tx.len(),cap-i); - assert_eq!(rx.len(),cap-i); - assert_eq!( rx.recv().unwrap(), i); + assert_eq!(tx.len(), cap - i); + assert_eq!(rx.len(), cap - i); + assert_eq!(rx.recv().unwrap(), i); } - assert_eq!(tx.len(),0); - assert_eq!(rx.len(),0); + assert_eq!(tx.len(), 0); + assert_eq!(rx.len(), 0); assert!(tx.is_empty()); assert!(rx.is_empty()); } { - let (tx,rx)=unbounded::(); - assert_eq!(tx.capacity(),None); - assert_eq!(rx.capacity(),None); - + let (tx, rx) = unbounded::(); + assert_eq!(tx.capacity(), None); + assert_eq!(rx.capacity(), None); } } - #[test] #[cfg(not(all(miri, target_os = "windows")))] -fn send_recv(){ - scoped_thread(|scope|{ - let (tx,rx)=bounded::(0); +fn send_recv() { + scoped_thread(|scope| { + let (tx, rx) = bounded::(0); - let cap=5; - scope.spawn(move|_|{ + let cap = 5; + scope.spawn(move |_| { for i in 0..cap { tx.send(i).unwrap(); } }); for i in 0..cap { - assert_eq!( rx.recv().unwrap(), i); + assert_eq!(rx.recv().unwrap(), i); } - }).unwrap(); + }) + .unwrap(); } - // miri gets stuck in this test #[cfg(not(miri))] #[test] -fn send_try_recv(){ - let (tx,rx)=bounded::(0); - - scoped_thread(|scope|{ - let cap=5; - let tx=tx.clone(); - let rx=rx.clone(); - - assert_eq!(rx.try_recv(),Err(TryRecvError::Empty)); - - scope.spawn(move|_|{ +fn send_try_recv() { + let (tx, rx) = bounded::(0); + + scoped_thread(|scope| { + let cap = 5; + let tx = tx.clone(); + let rx = rx.clone(); + + assert_eq!(rx.try_recv(), Err(TryRecvError::Empty)); + + scope.spawn(move |_| { for i in 0..cap { tx.send(i).unwrap(); } }); - scope.spawn(move|_|{ + scope.spawn(move |_| { for i in 0..cap { loop { match rx.try_recv() { - Ok(v)=>{ - assert_eq!(v,i); - break - }, - Err(TryRecvError::Empty)=>continue, - Err(TryRecvError::Disconnected)=>panic!( - "Channel was disconnected at iteration {}", - i - ), + Ok(v) => { + assert_eq!(v, i); + break; + } + Err(TryRecvError::Empty) => continue, + Err(TryRecvError::Disconnected) => { + panic!("Channel was disconnected at iteration {}", i) + } } } } }); - }).unwrap(); - - assert_eq!(rx.try_recv(),Err(TryRecvError::Empty)); -} + }) + .unwrap(); + assert_eq!(rx.try_recv(), Err(TryRecvError::Empty)); +} // miri gets stuck here #[cfg(not(miri))] #[test] -fn try_send_recv(){ - let (tx,rx)=bounded::(0); - - scoped_thread(|scope|{ - let cap=5; - let tx=tx.clone(); - let rx=rx.clone(); +fn try_send_recv() { + let (tx, rx) = bounded::(0); + + scoped_thread(|scope| { + let cap = 5; + let tx = tx.clone(); + let rx = rx.clone(); - assert_eq!(tx.try_send(0),Err(TrySendError::Full(0))); + assert_eq!(tx.try_send(0), Err(TrySendError::Full(0))); - scope.spawn(move|_|{ + scope.spawn(move |_| { for i in 0..cap { loop { match tx.try_send(i) { - Ok(())=>break, - Err(TrySendError::Full(x))=>{ + Ok(()) => break, + Err(TrySendError::Full(x)) => { assert_eq!(x, i); - continue - }, - Err(TrySendError::Disconnected{..})=>panic!( - "Channel was disconnected at iteration {}", - i - ), + continue; + } + Err(TrySendError::Disconnected { .. }) => { + panic!("Channel was disconnected at iteration {}", i) + } } } } }); - scope.spawn(move|_|{ + scope.spawn(move |_| { for i in 0..cap { - assert_eq!( rx.recv().unwrap(), i); + assert_eq!(rx.recv().unwrap(), i); } }); - }).unwrap(); - - assert_eq!(tx.try_send(0),Err(TrySendError::Full(0))); -} - + }) + .unwrap(); -const MS:Duration=Duration::from_millis(1); + assert_eq!(tx.try_send(0), Err(TrySendError::Full(0))); +} +const MS: Duration = Duration::from_millis(1); // unsupported operation: `clock_gettime` not available when isolation is enabled #[test] #[cfg(not(all(miri, target_os = "windows")))] -fn timeout_send_recv(){ - let (tx,rx)=bounded::(0); - - scoped_thread(|scope|{ - let cap=5; +fn timeout_send_recv() { + let (tx, rx) = bounded::(0); - let tx=tx.clone(); - let rx=rx.clone(); + scoped_thread(|scope| { + let cap = 5; - assert_eq!(rx.recv_timeout(MS),Err(RecvTimeoutError::Timeout)); + let tx = tx.clone(); + let rx = rx.clone(); - scope.spawn(move|_|{ + assert_eq!(rx.recv_timeout(MS), Err(RecvTimeoutError::Timeout)); + + scope.spawn(move |_| { for i in 0..cap { - while let Err(_)=tx.send_timeout(i,MS) {} + while let Err(_) = tx.send_timeout(i, MS) {} } }); - scope.spawn(move|_|{ + scope.spawn(move |_| { for i in 0..cap { loop { match rx.recv_timeout(Duration::from_millis(1)) { - Ok(v)=>{ - assert_eq!( v , i); + Ok(v) => { + assert_eq!(v, i); break; - }, - Err(_)=>continue, + } + Err(_) => continue, } } } }); - }).unwrap(); - - assert_eq!(rx.recv_timeout(MS),Err(RecvTimeoutError::Timeout)); -} + }) + .unwrap(); + assert_eq!(rx.recv_timeout(MS), Err(RecvTimeoutError::Timeout)); +} #[test] -fn disconnected(){ +fn disconnected() { { - let (tx,rx)=unbounded::<()>(); - let clone=tx.clone(); - assert_eq!(rx.try_recv().unwrap_err(),TryRecvError::Empty); + let (tx, rx) = unbounded::<()>(); + let clone = tx.clone(); + assert_eq!(rx.try_recv().unwrap_err(), TryRecvError::Empty); drop(tx); - assert_eq!(rx.try_recv().unwrap_err(),TryRecvError::Empty); + assert_eq!(rx.try_recv().unwrap_err(), TryRecvError::Empty); drop(clone); - assert_eq!(rx.try_recv().unwrap_err(),TryRecvError::Disconnected); + assert_eq!(rx.try_recv().unwrap_err(), TryRecvError::Disconnected); } { - let (tx,rx)=bounded::<()>(0); - let clone=rx.clone(); - assert_eq!(tx.try_send(()).unwrap_err(),TrySendError::Full(())); + let (tx, rx) = bounded::<()>(0); + let clone = rx.clone(); + assert_eq!(tx.try_send(()).unwrap_err(), TrySendError::Full(())); drop(rx); - assert_eq!(tx.try_send(()).unwrap_err(),TrySendError::Full(())); + assert_eq!(tx.try_send(()).unwrap_err(), TrySendError::Full(())); drop(clone); - assert_eq!(tx.try_send(()).unwrap_err(),TrySendError::Disconnected(())); + assert_eq!(tx.try_send(()).unwrap_err(), TrySendError::Disconnected(())); } } - #[test] #[cfg(not(all(miri, target_os = "windows")))] -fn iter(){ - let (tx,rx)=unbounded::(); +fn iter() { + let (tx, rx) = unbounded::(); - scoped_thread(|scope|{ - let rx=rx.clone(); + scoped_thread(|scope| { + let rx = rx.clone(); - scope.spawn(move|_|{ + scope.spawn(move |_| { for i in 0..5 { tx.send(i).unwrap(); } }); - scope.spawn(move|_|{ - for (i,j) in rx.iter().enumerate() { - assert_eq!(i,j); + scope.spawn(move |_| { + for (i, j) in rx.iter().enumerate() { + assert_eq!(i, j); } }); - }).unwrap(); - - assert_ne!(rx.try_recv().err(),None); + }) + .unwrap(); + assert_ne!(rx.try_recv().err(), None); } - #[test] #[cfg(not(all(miri, target_os = "windows")))] -fn into_iter(){ - let (tx,rx)=unbounded::(); +fn into_iter() { + let (tx, rx) = unbounded::(); - scoped_thread(|scope|{ - let rx=rx.clone(); + scoped_thread(|scope| { + let rx = rx.clone(); - scope.spawn(move|_|{ + scope.spawn(move |_| { for i in 0..5 { tx.send(i).unwrap(); } }); - scope.spawn(move|_|{ - for (i,j) in rx.into_iter().enumerate() { - assert_eq!(i,j); + scope.spawn(move |_| { + for (i, j) in rx.into_iter().enumerate() { + assert_eq!(i, j); } }); - }).unwrap(); + }) + .unwrap(); - assert_ne!(rx.try_recv().err(),None); - -} \ No newline at end of file + assert_ne!(rx.try_recv().err(), None); +} diff --git a/abi_stable/src/external_types/parking_lot.rs b/abi_stable/src/external_types/parking_lot.rs index 04611733..3dd9648a 100644 --- a/abi_stable/src/external_types/parking_lot.rs +++ b/abi_stable/src/external_types/parking_lot.rs @@ -1,18 +1,13 @@ /*! -Ffi-safe synchronization primitives,most of which are ffi-safe wrappers of +Ffi-safe synchronization primitives,most of which are ffi-safe wrappers of [parking_lot](https://crates.io/crates/parking_lot) types */ -pub mod once; pub mod mutex; +pub mod once; pub mod rw_lock; -pub use self::{ - mutex::RMutex, - rw_lock::RRwLock, - once::ROnce, -}; - +pub use self::{mutex::RMutex, once::ROnce, rw_lock::RRwLock}; ///////////////////////////////////////////////////////////////////////////////// @@ -20,39 +15,35 @@ use std::mem; use crate::StableAbi; -#[cfg_attr(target_pointer_width="128",repr(C,align(16)))] -#[cfg_attr(target_pointer_width="64",repr(C,align(8)))] -#[cfg_attr(target_pointer_width="32",repr(C,align(4)))] -#[cfg_attr(target_pointer_width="16",repr(C,align(2)))] -#[derive(Copy,Clone,StableAbi)] +#[cfg_attr(target_pointer_width = "128", repr(C, align(16)))] +#[cfg_attr(target_pointer_width = "64", repr(C, align(8)))] +#[cfg_attr(target_pointer_width = "32", repr(C, align(4)))] +#[cfg_attr(target_pointer_width = "16", repr(C, align(2)))] +#[derive(Copy, Clone, StableAbi)] struct Overaligner; -const RAW_LOCK_SIZE:usize=mem::size_of::(); +const RAW_LOCK_SIZE: usize = mem::size_of::(); #[repr(C)] -#[derive(Copy,Clone,StableAbi)] +#[derive(Copy, Clone, StableAbi)] #[sabi(unsafe_unconstrained(T))] -struct UnsafeOveralignedField{ +struct UnsafeOveralignedField { #[sabi(unsafe_opaque_field)] - value:T, + value: T, /// Manual padding to ensure that the bytes are copied, /// even if Rust thinks there is nothing in the padding. - _padding:P, - _alignment:Overaligner, + _padding: P, + _alignment: Overaligner, } - -impl UnsafeOveralignedField{ - const fn new(value:T,_padding:P)->Self{ - Self{ +impl UnsafeOveralignedField { + const fn new(value: T, _padding: P) -> Self { + Self { value, _padding, - _alignment:Overaligner, + _alignment: Overaligner, } } } - - ///////////////////////////////////////////////////////////////////////////////// - diff --git a/abi_stable/src/external_types/parking_lot/mutex.rs b/abi_stable/src/external_types/parking_lot/mutex.rs index 316834c8..340f5388 100644 --- a/abi_stable/src/external_types/parking_lot/mutex.rs +++ b/abi_stable/src/external_types/parking_lot/mutex.rs @@ -2,48 +2,43 @@ use std::{ cell::UnsafeCell, - fmt::{self,Debug,Display}, - ops::{Deref,DerefMut}, + fmt::{self, Debug, Display}, marker::PhantomData, mem, + ops::{Deref, DerefMut}, }; -use parking_lot::{RawMutex}; -use lock_api::{ - RawMutex as RawMutexTrait, - RawMutexTimed, -}; +use lock_api::{RawMutex as RawMutexTrait, RawMutexTimed}; +use parking_lot::RawMutex; -use super::{RAW_LOCK_SIZE,UnsafeOveralignedField}; +use super::{UnsafeOveralignedField, RAW_LOCK_SIZE}; use crate::{ - StableAbi, marker_type::UnsyncUnsend, - prefix_type::{PrefixTypeTrait,WithMetadata}, + prefix_type::{PrefixTypeTrait, WithMetadata}, std_types::*, + StableAbi, }; - /////////////////////////////////////////////////////////////////////////////// -type OpaqueMutex= - UnsafeOveralignedField; +type OpaqueMutex = UnsafeOveralignedField; -const OM_PADDING:usize=RAW_LOCK_SIZE-mem::size_of::(); +const OM_PADDING: usize = RAW_LOCK_SIZE - mem::size_of::(); -const OPAQUE_MUTEX:OpaqueMutex= - OpaqueMutex::new(::INIT,[0u8;OM_PADDING]); +const OPAQUE_MUTEX: OpaqueMutex = + OpaqueMutex::new(::INIT, [0u8; OM_PADDING]); #[allow(dead_code)] -fn assert_mutex_size(){ - let _assert_size:[();RAW_LOCK_SIZE-mem::size_of::()]; - let _assert_size:[();mem::size_of::()-RAW_LOCK_SIZE]; +fn assert_mutex_size() { + let _assert_size: [(); RAW_LOCK_SIZE - mem::size_of::()]; + let _assert_size: [(); mem::size_of::() - RAW_LOCK_SIZE]; } /** A mutual exclusion lock that allows dynamic mutable borrows of shared data. -# Poisoning +# Poisoning As opposed to the standard library version of this type, this mutex type does not use poisoning, @@ -74,13 +69,12 @@ assert_eq!(*MUTEX.lock(),200); */ #[repr(C)] #[derive(StableAbi)] -pub struct RMutex{ - raw_mutex:OpaqueMutex, - data:UnsafeCell, - vtable:VTable_Ref, +pub struct RMutex { + raw_mutex: OpaqueMutex, + data: UnsafeCell, + vtable: VTable_Ref, } - /** A mutex guard,which allows mutable access to the data inside an `RMutex`. @@ -89,19 +83,16 @@ When dropped this will unlock the mutex. */ #[repr(transparent)] #[derive(StableAbi)] -#[sabi(bound="T:'a")] +#[sabi(bound = "T:'a")] #[must_use] pub struct RMutexGuard<'a, T> { rmutex: &'a RMutex, _marker: PhantomData<(&'a mut T, UnsyncUnsend)>, } - - /////////////////////////////////////////////////////////////////////////////// - -impl RMutex{ +impl RMutex { /// Constructs a mutex,wrapping `value`. /// /// # Example @@ -110,28 +101,28 @@ impl RMutex{ /// use abi_stable::external_types::RMutex; /// /// static MUTEX:RMutex>=RMutex::new(None); - /// + /// /// let mutex=RMutex::new(0); /// /// ``` - pub const fn new(value:T)->Self{ - Self{ - raw_mutex:OPAQUE_MUTEX, - data:UnsafeCell::new(value), - vtable:VTable::VTABLE, + pub const fn new(value: T) -> Self { + Self { + raw_mutex: OPAQUE_MUTEX, + data: UnsafeCell::new(value), + vtable: VTable::VTABLE, } } #[inline] - fn vtable(&self)->VTable_Ref{ + fn vtable(&self) -> VTable_Ref { self.vtable } #[inline] - fn make_guard(&self)->RMutexGuard<'_,T>{ - RMutexGuard{ - rmutex:self, - _marker:PhantomData + fn make_guard(&self) -> RMutexGuard<'_, T> { + RMutexGuard { + rmutex: self, + _marker: PhantomData, } } @@ -148,7 +139,7 @@ impl RMutex{ /// /// ``` #[inline] - pub fn into_inner(self)->T{ + pub fn into_inner(self) -> T { self.data.into_inner() } @@ -166,357 +157,340 @@ impl RMutex{ /// mutex.get_mut().push_str(", World!"); /// /// assert_eq!(mutex.lock().as_str(),"Hello, World!"); - /// + /// /// /// ``` #[inline] - pub fn get_mut(&mut self)->&mut T{ - unsafe{ &mut *self.data.get() } + pub fn get_mut(&mut self) -> &mut T { + unsafe { &mut *self.data.get() } } /** -Acquires a mutex,blocking the current thread until it can. + Acquires a mutex,blocking the current thread until it can. -This function returns a guard which releases the mutex when it is dropped. + This function returns a guard which releases the mutex when it is dropped. -Trying to lock the mutex in the same thread that holds the lock will cause a deadlock. + Trying to lock the mutex in the same thread that holds the lock will cause a deadlock. -# Example + # Example -``` -use abi_stable::external_types::RMutex; + ``` + use abi_stable::external_types::RMutex; -static MUTEX:RMutex=RMutex::new(0); + static MUTEX:RMutex=RMutex::new(0); -let guard=std::thread::spawn(|| *MUTEX.lock()+=1 ); + let guard=std::thread::spawn(|| *MUTEX.lock()+=1 ); -*MUTEX.lock()+=4; + *MUTEX.lock()+=4; -guard.join().unwrap(); + guard.join().unwrap(); -assert_eq!(*MUTEX.lock(),5); + assert_eq!(*MUTEX.lock(),5); -``` + ``` - */ + */ #[inline] - pub fn lock(&self)->RMutexGuard<'_,T>{ + pub fn lock(&self) -> RMutexGuard<'_, T> { self.vtable().lock()(&self.raw_mutex); self.make_guard() } /** -Attemps to acquire a mutex guard. + Attemps to acquire a mutex guard. -Returns the mutex guard if the mutex can be immediately acquired, -otherwise returns `RNone`. + Returns the mutex guard if the mutex can be immediately acquired, + otherwise returns `RNone`. -# Example + # Example -``` -use abi_stable::external_types::RMutex; + ``` + use abi_stable::external_types::RMutex; -static MUTEX:RMutex=RMutex::new(0); + static MUTEX:RMutex=RMutex::new(0); -let mut guard=MUTEX.try_lock().unwrap(); + let mut guard=MUTEX.try_lock().unwrap(); -assert!( MUTEX.try_lock().is_none() ); + assert!( MUTEX.try_lock().is_none() ); -assert_eq!(*guard,0); + assert_eq!(*guard,0); -``` + ``` -*/ + */ #[inline] - pub fn try_lock(&self) -> ROption>{ + pub fn try_lock(&self) -> ROption> { if self.vtable().try_lock()(&self.raw_mutex) { RSome(self.make_guard()) - }else{ + } else { RNone } } - -/** -Attempts to acquire a mutex guard for the `timeout` duration. -Once the timeout is reached,this will return `RNone`, -otherwise it will return the mutex guard. + /** + Attempts to acquire a mutex guard for the `timeout` duration. + Once the timeout is reached,this will return `RNone`, + otherwise it will return the mutex guard. -# Example -``` -use abi_stable::{ - external_types::RMutex, - std_types::RDuration, -}; + # Example -static MUTEX:RMutex=RMutex::new(0); + ``` + use abi_stable::{ + external_types::RMutex, + std_types::RDuration, + }; -static DUR:RDuration=RDuration::from_millis(4); + static MUTEX:RMutex=RMutex::new(0); -let mut guard=MUTEX.try_lock_for(DUR).unwrap(); + static DUR:RDuration=RDuration::from_millis(4); -assert!( MUTEX.try_lock_for(DUR).is_none() ); + let mut guard=MUTEX.try_lock_for(DUR).unwrap(); -assert_eq!(*guard,0); + assert!( MUTEX.try_lock_for(DUR).is_none() ); -``` + assert_eq!(*guard,0); -*/ + ``` + + */ #[inline] - pub fn try_lock_for(&self, timeout: RDuration) -> ROption>{ - if self.vtable().try_lock_for()(&self.raw_mutex,timeout) { + pub fn try_lock_for(&self, timeout: RDuration) -> ROption> { + if self.vtable().try_lock_for()(&self.raw_mutex, timeout) { RSome(self.make_guard()) - }else{ + } else { RNone } } } -unsafe impl Send for RMutex -where RawMutex:Send -{} +unsafe impl Send for RMutex where RawMutex: Send {} -unsafe impl Sync for RMutex -where RawMutex:Sync -{} +unsafe impl Sync for RMutex where RawMutex: Sync {} /////////////////////////////////////////////////////////////////////////////// - -impl<'a,T> Display for RMutexGuard<'a, T> +impl<'a, T> Display for RMutexGuard<'a, T> where - T:Display + T: Display, { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Display::fmt(&**self,f) + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Display::fmt(&**self, f) } } - -impl<'a,T> Debug for RMutexGuard<'a, T> +impl<'a, T> Debug for RMutexGuard<'a, T> where - T:Debug + T: Debug, { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Debug::fmt(&**self,f) + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Debug::fmt(&**self, f) } } +impl<'a, T> Deref for RMutexGuard<'a, T> { + type Target = T; -impl<'a,T> Deref for RMutexGuard<'a, T> { - type Target=T; - - fn deref(&self)->&T{ - unsafe{ &*self.rmutex.data.get() } + fn deref(&self) -> &T { + unsafe { &*self.rmutex.data.get() } } } - -impl<'a,T> DerefMut for RMutexGuard<'a, T> { - fn deref_mut(&mut self)->&mut T{ - unsafe{ &mut *self.rmutex.data.get() } +impl<'a, T> DerefMut for RMutexGuard<'a, T> { + fn deref_mut(&mut self) -> &mut T { + unsafe { &mut *self.rmutex.data.get() } } } -impl<'a,T> Drop for RMutexGuard<'a, T> { - fn drop(&mut self){ - let vtable=self.rmutex.vtable(); +impl<'a, T> Drop for RMutexGuard<'a, T> { + fn drop(&mut self) { + let vtable = self.rmutex.vtable(); vtable.unlock()(&self.rmutex.raw_mutex); } } - - /////////////////////////////////////////////////////////////////////////////// - #[repr(C)] #[derive(StableAbi)] #[sabi(kind(Prefix))] #[sabi(missing_field(panic))] -struct VTable{ - lock:extern "C" fn(this:&OpaqueMutex), - try_lock:extern "C" fn(this:&OpaqueMutex) -> bool, - unlock:extern "C" fn(this:&OpaqueMutex), +struct VTable { + lock: extern "C" fn(this: &OpaqueMutex), + try_lock: extern "C" fn(this: &OpaqueMutex) -> bool, + unlock: extern "C" fn(this: &OpaqueMutex), #[sabi(last_prefix_field)] - try_lock_for:extern "C" fn(this:&OpaqueMutex, timeout: RDuration) -> bool, + try_lock_for: extern "C" fn(this: &OpaqueMutex, timeout: RDuration) -> bool, } -impl VTable{ - const _TMP0: WithMetadata = - WithMetadata::new( - PrefixTypeTrait::METADATA, - VTable{ - lock, - try_lock, - unlock, - try_lock_for, - } - ); +impl VTable { + const _TMP0: WithMetadata = WithMetadata::new( + PrefixTypeTrait::METADATA, + VTable { + lock, + try_lock, + unlock, + try_lock_for, + }, + ); // The VTABLE for this type in this executable/library - const VTABLE: VTable_Ref = { - VTable_Ref(Self::_TMP0.static_as_prefix()) - }; + const VTABLE: VTable_Ref = { VTable_Ref(Self::_TMP0.static_as_prefix()) }; } - -extern "C" fn lock(this:&OpaqueMutex){ - extern_fn_panic_handling!{ +extern "C" fn lock(this: &OpaqueMutex) { + extern_fn_panic_handling! { this.value.lock(); } } -extern "C" fn try_lock(this:&OpaqueMutex) -> bool{ - extern_fn_panic_handling!{ - this.value.try_lock() +extern "C" fn try_lock(this: &OpaqueMutex) -> bool { + extern_fn_panic_handling! { + this.value.try_lock() } } -extern "C" fn unlock(this:&OpaqueMutex){ - extern_fn_panic_handling!{ +extern "C" fn unlock(this: &OpaqueMutex) { + extern_fn_panic_handling! { unsafe{ this.value.unlock(); } } } -extern "C" fn try_lock_for(this:&OpaqueMutex, timeout: RDuration) -> bool{ - extern_fn_panic_handling!{ +extern "C" fn try_lock_for(this: &OpaqueMutex, timeout: RDuration) -> bool { + extern_fn_panic_handling! { this.value.try_lock_for(timeout.into()) } } - /////////////////////////////////////////////////////////////////////////////// - - - -#[cfg(all(test,not(feature="only_new_tests")))] -mod tests{ +#[cfg(all(test, not(feature = "only_new_tests")))] +mod tests { use super::*; - use std::{ - thread, - time::Duration, - }; + use std::{thread, time::Duration}; use crossbeam_utils::thread::scope as scoped_thread; use crate::test_utils::check_formatting_equivalence; #[test] - fn get_mut(){ - let mut mutex:RMutex=RMutex::new(0); - *mutex.lock()+=100; - *mutex.get_mut()+=100; - *mutex.lock()+=100; + fn get_mut() { + let mut mutex: RMutex = RMutex::new(0); + *mutex.lock() += 100; + *mutex.get_mut() += 100; + *mutex.lock() += 100; assert_eq!(*mutex.lock(), 300); } - #[test] - fn into_inner(){ - let mutex:RMutex=RMutex::new(0); - *mutex.lock()+=100; + fn into_inner() { + let mutex: RMutex = RMutex::new(0); + *mutex.lock() += 100; assert_eq!(mutex.into_inner(), 100); } #[test] - fn debug_display(){ - let str_="\nhello\rhello\rhello\n"; - let mutex=RMutex::new(str_); - let guard=mutex.lock(); + fn debug_display() { + let str_ = "\nhello\rhello\rhello\n"; + let mutex = RMutex::new(str_); + let guard = mutex.lock(); - check_formatting_equivalence(&guard,str_); + check_formatting_equivalence(&guard, str_); } #[cfg(miri)] const ITERS: usize = 10; - + #[cfg(not(miri))] const ITERS: usize = 0x1000; #[test] #[cfg(not(all(miri, target_os = "windows")))] - fn lock(){ - static MUTEX:RMutex=RMutex::new(0); + fn lock() { + static MUTEX: RMutex = RMutex::new(0); - scoped_thread(|scope|{ + scoped_thread(|scope| { for _ in 0..8 { - scope.spawn(move|_|{ + scope.spawn(move |_| { for _ in 0..ITERS { - *MUTEX.lock()+=1; + *MUTEX.lock() += 1; } }); } - }).unwrap(); + }) + .unwrap(); - assert_eq!(*MUTEX.lock(),8 * ITERS); + assert_eq!(*MUTEX.lock(), 8 * ITERS); } #[test] #[cfg(not(all(miri, target_os = "windows")))] - fn try_lock(){ - static MUTEX:RMutex=RMutex::new(0); + fn try_lock() { + static MUTEX: RMutex = RMutex::new(0); - scoped_thread(|scope|{ + scoped_thread(|scope| { for _ in 0..8 { - scope.spawn(move|_|{ + scope.spawn(move |_| { for _ in 0..ITERS { loop { - if let RSome(mut guard)=MUTEX.try_lock() { - *guard+=1; + if let RSome(mut guard) = MUTEX.try_lock() { + *guard += 1; break; } } } }); } - }).unwrap(); + }) + .unwrap(); - scoped_thread(|scope|{ - let _guard=MUTEX.lock(); - scope.spawn(move|_|{ + scoped_thread(|scope| { + let _guard = MUTEX.lock(); + scope.spawn(move |_| { assert_eq!(MUTEX.try_lock().map(drop), RNone); }); thread::sleep(Duration::from_millis(100)); - }).unwrap(); + }) + .unwrap(); - assert_eq!(*MUTEX.lock(),8 * ITERS); + assert_eq!(*MUTEX.lock(), 8 * ITERS); } #[test] #[cfg(not(all(miri, target_os = "windows")))] - fn try_lock_for(){ - static MUTEX:RMutex=RMutex::new(0); + fn try_lock_for() { + static MUTEX: RMutex = RMutex::new(0); - scoped_thread(|scope|{ + scoped_thread(|scope| { for _ in 0..8 { - scope.spawn(move|_|{ + scope.spawn(move |_| { for i in 0..ITERS { - let wait_for=RDuration::new(0,(i as u32 + 1)*500_000); + let wait_for = RDuration::new(0, (i as u32 + 1) * 500_000); loop { - if let RSome(mut guard)=MUTEX.try_lock_for(wait_for) { - *guard+=1; + if let RSome(mut guard) = MUTEX.try_lock_for(wait_for) { + *guard += 1; break; } } } }); } - }).unwrap(); + }) + .unwrap(); #[cfg(not(miri))] - scoped_thread(|scope|{ - let _guard=MUTEX.lock(); - scope.spawn(move|_|{ - assert_eq!(MUTEX.try_lock_for(RDuration::new(0,100_000)).map(drop), RNone); + scoped_thread(|scope| { + let _guard = MUTEX.lock(); + scope.spawn(move |_| { + assert_eq!( + MUTEX.try_lock_for(RDuration::new(0, 100_000)).map(drop), + RNone + ); }); thread::sleep(Duration::from_millis(100)); - }).unwrap(); + }) + .unwrap(); - - assert_eq!(*MUTEX.lock(),8 * ITERS); + assert_eq!(*MUTEX.lock(), 8 * ITERS); } - -} \ No newline at end of file +} diff --git a/abi_stable/src/external_types/parking_lot/once.rs b/abi_stable/src/external_types/parking_lot/once.rs index 89359ca7..d39f8327 100644 --- a/abi_stable/src/external_types/parking_lot/once.rs +++ b/abi_stable/src/external_types/parking_lot/once.rs @@ -1,44 +1,39 @@ //! Contains an ffi-safe wrapper for `parking_lot::Once`. use std::{ any::Any, - fmt::{self,Debug}, + fmt::{self, Debug}, mem, - panic::{self,AssertUnwindSafe}, + panic::{self, AssertUnwindSafe}, }; -use core_extensions::{matches}; +use core_extensions::matches; -use parking_lot::{Once as PLOnce,OnceState}; +use parking_lot::{Once as PLOnce, OnceState}; -use super::{UnsafeOveralignedField,RAW_LOCK_SIZE}; +use super::{UnsafeOveralignedField, RAW_LOCK_SIZE}; use crate::{ - prefix_type::{PrefixTypeTrait,WithMetadata}, + prefix_type::{PrefixTypeTrait, WithMetadata}, sabi_types::RMut, - std_types::{RResult,ROk,RErr}, + std_types::{RErr, ROk, RResult}, }; - - /////////////////////////////////////////////////////////////////////////////// -type OpaqueOnce= - UnsafeOveralignedField; +type OpaqueOnce = UnsafeOveralignedField; -const OM_PADDING:usize=RAW_LOCK_SIZE-mem::size_of::(); +const OM_PADDING: usize = RAW_LOCK_SIZE - mem::size_of::(); -const OPAQUE_ONCE:OpaqueOnce= - OpaqueOnce::new(parking_lot::Once::new(),[0u8;OM_PADDING]); +const OPAQUE_ONCE: OpaqueOnce = OpaqueOnce::new(parking_lot::Once::new(), [0u8; OM_PADDING]); #[allow(dead_code)] -fn assert_mutex_size(){ - let _assert_size:[();RAW_LOCK_SIZE-mem::size_of::()]; - let _assert_size:[();mem::size_of::()-RAW_LOCK_SIZE]; +fn assert_mutex_size() { + let _assert_size: [(); RAW_LOCK_SIZE - mem::size_of::()]; + let _assert_size: [(); mem::size_of::() - RAW_LOCK_SIZE]; } /////////////////////////////////////////////////////////////////////////////// - /** A synchronization primitive for running global initialization once. @@ -74,12 +69,12 @@ assert_eq!(*MUTEX.lock(),1); */ #[repr(C)] #[derive(StableAbi)] -pub struct ROnce{ - opaque_once:OpaqueOnce, +pub struct ROnce { + opaque_once: OpaqueOnce, vtable: VTable_Ref, } -impl ROnce{ +impl ROnce { /// Constructs an ROnce. /// /// # Example @@ -88,11 +83,11 @@ impl ROnce{ /// use abi_stable::external_types::ROnce; /// /// static ONCE: ROnce = ROnce::new(); - /// + /// /// ``` - pub const fn new() -> ROnce{ - ROnce{ - opaque_once:OPAQUE_ONCE, + pub const fn new() -> ROnce { + ROnce { + opaque_once: OPAQUE_ONCE, vtable: VTable::VTABLE, } } @@ -107,181 +102,177 @@ impl ROnce{ /// static ONCE:ROnce=ROnce::NEW; /// /// ``` - pub const NEW:Self= - ROnce{ - opaque_once:OPAQUE_ONCE, - vtable: VTable::VTABLE, - }; + pub const NEW: Self = ROnce { + opaque_once: OPAQUE_ONCE, + vtable: VTable::VTABLE, + }; - fn vtable(&self)-> VTable_Ref{ + fn vtable(&self) -> VTable_Ref { self.vtable } -/** -Gets the running state of this ROnce. + /** + Gets the running state of this ROnce. -# Example + # Example -``` -use abi_stable::external_types::parking_lot::once::{ROnce,ROnceState}; + ``` + use abi_stable::external_types::parking_lot::once::{ROnce,ROnceState}; -use std::panic::AssertUnwindSafe; + use std::panic::AssertUnwindSafe; -let once=ROnce::new(); + let once=ROnce::new(); -assert_eq!(once.state(), ROnceState::New ); + assert_eq!(once.state(), ROnceState::New ); -let _=std::panic::catch_unwind(AssertUnwindSafe(||{ - once.call_once(|| panic!() ); -})); + let _=std::panic::catch_unwind(AssertUnwindSafe(||{ + once.call_once(|| panic!() ); + })); -assert!( once.state().poisoned() ); + assert!( once.state().poisoned() ); -once.call_once_force(|_| () ); + once.call_once_force(|_| () ); -assert!( once.state().done() ); + assert!( once.state().done() ); -``` -*/ - pub fn state(&self) -> ROnceState{ - unsafe{ self.vtable().state()(&self.opaque_once) } + ``` + */ + pub fn state(&self) -> ROnceState { + unsafe { self.vtable().state()(&self.opaque_once) } } -/** -Runs an initialization function. + /** + Runs an initialization function. -`f` will be run only if this is the first time this method has been called -on this ROnce. + `f` will be run only if this is the first time this method has been called + on this ROnce. -Once this function returns it is guaranteed that some closure passed -to this method has run to completion. + Once this function returns it is guaranteed that some closure passed + to this method has run to completion. -# Panics + # Panics -Panics in the closure will cause this ROnce to become poisoned, -and any future calls to this method will panic. + Panics in the closure will cause this ROnce to become poisoned, + and any future calls to this method will panic. -# Example + # Example -``` -use abi_stable::external_types::ROnce; + ``` + use abi_stable::external_types::ROnce; -let once=ROnce::new(); -let mut counter=0usize; + let once=ROnce::new(); + let mut counter=0usize; -once.call_once(|| counter+=1 ); -once.call_once(|| counter+=1 ); -once.call_once(|| counter+=1 ); -once.call_once(|| counter+=1 ); + once.call_once(|| counter+=1 ); + once.call_once(|| counter+=1 ); + once.call_once(|| counter+=1 ); + once.call_once(|| counter+=1 ); -assert_eq!(counter,1); + assert_eq!(counter,1); -``` -*/ - pub fn call_once(&self, f: F) + ``` + */ + pub fn call_once(&self, f: F) where - F: FnOnce() + F: FnOnce(), { - let mut closure=Closure::without_state(f); - let func=closure.func; - let res = unsafe{ + let mut closure = Closure::without_state(f); + let func = closure.func; + let res = unsafe { self.vtable().call_once()( &self.opaque_once, RMut::new(&mut closure).transmute::(), - func + func, ) }; - if let Err(e)=closure.panic { + if let Err(e) = closure.panic { panic::resume_unwind(e); } - if let RErr(())=res{ + if let RErr(()) = res { panic!("This ROnce instantce is poisoned."); } } -/** -Runs an initialization function,even if the ROnce is poisoned. + /** + Runs an initialization function,even if the ROnce is poisoned. -This will keep trying to run different closures until one of them doesn't panic. + This will keep trying to run different closures until one of them doesn't panic. -The ROnceState parameter describes whether the ROnce is New or Poisoned. + The ROnceState parameter describes whether the ROnce is New or Poisoned. -# Example + # Example -``` -use abi_stable::external_types::ROnce; + ``` + use abi_stable::external_types::ROnce; -use std::panic::{self,AssertUnwindSafe}; + use std::panic::{self,AssertUnwindSafe}; -let once=ROnce::new(); -let mut counter=0usize; + let once=ROnce::new(); + let mut counter=0usize; -for i in 0..100 { - let _=panic::catch_unwind(AssertUnwindSafe(||{ - once.call_once_force(|_|{ - if i < 6 { - panic!(); - } - counter=i; - }) - })); -} + for i in 0..100 { + let _=panic::catch_unwind(AssertUnwindSafe(||{ + once.call_once_force(|_|{ + if i < 6 { + panic!(); + } + counter=i; + }) + })); + } -assert_eq!(counter,6); + assert_eq!(counter,6); -``` + ``` -*/ - pub fn call_once_force(&self, f: F) + */ + pub fn call_once_force(&self, f: F) where F: FnOnce(ROnceState), { - let mut closure=Closure::with_state(f); - let func=closure.func; - let res= unsafe{ + let mut closure = Closure::with_state(f); + let func = closure.func; + let res = unsafe { self.vtable().call_once_force()( &self.opaque_once, RMut::new(&mut closure).transmute::(), - func + func, ) }; - if let Err(e)=closure.panic { + if let Err(e) = closure.panic { panic::resume_unwind(e); } - if let RErr(())=res{ + if let RErr(()) = res { panic!("This ROnce instantce is poisoned."); } } } -impl Debug for ROnce{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ +impl Debug for ROnce { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Once") - .field("state", &self.state()) - .finish() + .field("state", &self.state()) + .finish() } } -impl Default for ROnce{ +impl Default for ROnce { #[inline] - fn default()->Self{ + fn default() -> Self { Self::new() } } -unsafe impl Send for ROnce{} -unsafe impl Sync for ROnce{} - +unsafe impl Send for ROnce {} +unsafe impl Sync for ROnce {} /////////////////////////////////////////////////////////////////////////////// - - /// Describes the running state of an ROnce. #[repr(u8)] -#[derive(Copy, Clone, Eq, PartialEq, Debug,StableAbi)] -pub enum ROnceState{ +#[derive(Copy, Clone, Eq, PartialEq, Debug, StableAbi)] +pub enum ROnceState { /// An ROnce that hasn't started running New, /// An ROnce that panicked inside `call_once*` @@ -289,54 +280,53 @@ pub enum ROnceState{ /// An ROnce that is the middle of calling `call_once*` InProgress, /// An ROnce that has already run. - Done, + Done, } - -impl ROnceState{ +impl ROnceState { /** -Whether the ROnce is poisoned,requiring call_once_force to run. + Whether the ROnce is poisoned,requiring call_once_force to run. -# Example + # Example -``` -use abi_stable::external_types::ROnce; + ``` + use abi_stable::external_types::ROnce; -use std::panic::AssertUnwindSafe; + use std::panic::AssertUnwindSafe; -let once=ROnce::new(); + let once=ROnce::new(); -let _=std::panic::catch_unwind(AssertUnwindSafe(||{ - once.call_once(|| panic!() ); -})); + let _=std::panic::catch_unwind(AssertUnwindSafe(||{ + once.call_once(|| panic!() ); + })); -assert!(once.state().poisoned()); + assert!(once.state().poisoned()); -``` + ``` - */ - pub fn poisoned(&self) -> bool{ + */ + pub fn poisoned(&self) -> bool { matches!(self, ROnceState::Poisoned) } -/** -Whether the ROnce has already finished running. + /** + Whether the ROnce has already finished running. -# Example + # Example -``` -use abi_stable::external_types::ROnce; + ``` + use abi_stable::external_types::ROnce; -let once=ROnce::new(); + let once=ROnce::new(); -once.call_once(|| () ); + once.call_once(|| () ); -assert!(once.state().done()); + assert!(once.state().done()); -``` + ``` -*/ - pub fn done(&self) -> bool{ + */ + pub fn done(&self) -> bool { matches!(self, ROnceState::Done) } } @@ -367,272 +357,272 @@ impl_into_rust_repr! { } } - /////////////////////////////////////////////////////////////////////////////// - #[repr(C)] #[derive(StableAbi)] struct ErasedClosure; - -struct Closure{ - closure:Option, - panic:Result<(),Box>, - func:RunClosure, +struct Closure { + closure: Option, + panic: Result<(), Box>, + func: RunClosure, } -#[derive(StableAbi,Copy,Clone)] +#[derive(StableAbi, Copy, Clone)] #[repr(transparent)] -struct RunClosure{ - func: unsafe extern "C" fn(RMut<'_, ErasedClosure>,ROnceState)->RResult<(),()>, +struct RunClosure { + func: unsafe extern "C" fn(RMut<'_, ErasedClosure>, ROnceState) -> RResult<(), ()>, } - -impl Closure{ - +impl Closure { #[inline] - pub fn without_state(function:F)-> Self + pub fn without_state(function: F) -> Self where F: FnOnce(), { - Self{ - closure:Some(function), - panic:Ok(()), - func:RunClosure{func:Self::run_call_once} + Self { + closure: Some(function), + panic: Ok(()), + func: RunClosure { + func: Self::run_call_once, + }, } } #[inline] - pub fn with_state(function:F)-> Self + pub fn with_state(function: F) -> Self where F: FnOnce(ROnceState), { - Self{ - closure:Some(function), - panic:Ok(()), - func:RunClosure{func:Self::run_call_once_forced} + Self { + closure: Some(function), + panic: Ok(()), + func: RunClosure { + func: Self::run_call_once_forced, + }, } } - unsafe extern "C" fn run_call_once(this:RMut<'_, ErasedClosure>,state:ROnceState)->RResult<(),()> + unsafe extern "C" fn run_call_once( + this: RMut<'_, ErasedClosure>, + state: ROnceState, + ) -> RResult<(), ()> where F: FnOnce(), { - Self::run_call(this,state,|f,_| f() ) + Self::run_call(this, state, |f, _| f()) } - unsafe extern "C" fn run_call_once_forced(this:RMut<'_, ErasedClosure>,state:ROnceState)->RResult<(),()> + unsafe extern "C" fn run_call_once_forced( + this: RMut<'_, ErasedClosure>, + state: ROnceState, + ) -> RResult<(), ()> where F: FnOnce(ROnceState), { - Self::run_call(this,state,|f,state| f(state) ) + Self::run_call(this, state, |f, state| f(state)) } #[inline] - unsafe fn run_call(this:RMut<'_, ErasedClosure>,state:ROnceState,method:M)->RResult<(),()> + unsafe fn run_call( + this: RMut<'_, ErasedClosure>, + state: ROnceState, + method: M, + ) -> RResult<(), ()> where - M: FnOnce(F,ROnceState), + M: FnOnce(F, ROnceState), { let mut this = this.transmute_into_mut::(); - let res=panic::catch_unwind(AssertUnwindSafe(||{ - let closure=this.closure.take().unwrap(); - method(closure,state); + let res = panic::catch_unwind(AssertUnwindSafe(|| { + let closure = this.closure.take().unwrap(); + method(closure, state); })); - let ret=match res { - Ok{..}=>ROk(()), - Err{..}=>RErr(()), + let ret = match res { + Ok { .. } => ROk(()), + Err { .. } => RErr(()), }; - this.panic=res; + this.panic = res; ret } } - - - /////////////////////////////////////////////////////////////////////////////// - #[repr(C)] #[derive(StableAbi)] #[sabi(kind(Prefix))] #[sabi(missing_field(panic))] -struct VTable{ - state: unsafe extern "C" fn(&OpaqueOnce)->ROnceState, - call_once: unsafe extern "C" fn(&OpaqueOnce,RMut<'_, ErasedClosure>,RunClosure)->RResult<(),()>, - call_once_force: unsafe extern "C" fn(&OpaqueOnce,RMut<'_, ErasedClosure>,RunClosure)->RResult<(),()>, +struct VTable { + state: unsafe extern "C" fn(&OpaqueOnce) -> ROnceState, + call_once: + unsafe extern "C" fn(&OpaqueOnce, RMut<'_, ErasedClosure>, RunClosure) -> RResult<(), ()>, + call_once_force: + unsafe extern "C" fn(&OpaqueOnce, RMut<'_, ErasedClosure>, RunClosure) -> RResult<(), ()>, } -impl VTable{ +impl VTable { // The VTABLE for this type in this executable/library const VTABLE: VTable_Ref = { const S: &WithMetadata = &WithMetadata::new( PrefixTypeTrait::METADATA, - VTable{ + VTable { state, call_once, - call_once_force - } + call_once_force, + }, ); VTable_Ref(S.static_as_prefix()) }; } - - /////////////////////////////////////////////////////////////////////////////// - -unsafe extern "C" fn state(this:&OpaqueOnce)->ROnceState{ - extern_fn_panic_handling!{ +unsafe extern "C" fn state(this: &OpaqueOnce) -> ROnceState { + extern_fn_panic_handling! { this.value.state().into() } } unsafe extern "C" fn call_once( - this:&OpaqueOnce, - erased_closure:RMut<'_, ErasedClosure>, - runner:RunClosure, -)->RResult<(),()>{ - call_with_closure(||{ - this.value.call_once(||{ - (runner.func)(erased_closure,ROnceState::New).unwrap(); + this: &OpaqueOnce, + erased_closure: RMut<'_, ErasedClosure>, + runner: RunClosure, +) -> RResult<(), ()> { + call_with_closure(|| { + this.value.call_once(|| { + (runner.func)(erased_closure, ROnceState::New).unwrap(); }); }) } unsafe extern "C" fn call_once_force( - this:&OpaqueOnce, - erased_closure:RMut<'_, ErasedClosure>, - runner:RunClosure, -)->RResult<(),()>{ - call_with_closure(||{ - this.value.call_once_force(|state|{ - (runner.func)(erased_closure,state.into()).unwrap(); + this: &OpaqueOnce, + erased_closure: RMut<'_, ErasedClosure>, + runner: RunClosure, +) -> RResult<(), ()> { + call_with_closure(|| { + this.value.call_once_force(|state| { + (runner.func)(erased_closure, state.into()).unwrap(); }); }) } - #[inline] -fn call_with_closure(f:F)->RResult<(),()> +fn call_with_closure(f: F) -> RResult<(), ()> where - F:FnOnce() + F: FnOnce(), { - let res=panic::catch_unwind(AssertUnwindSafe(f)); + let res = panic::catch_unwind(AssertUnwindSafe(f)); match res { - Ok{..}=>ROk(()), - Err{..}=>RErr(()), + Ok { .. } => ROk(()), + Err { .. } => RErr(()), } } - /////////////////////////////////////////////////////////////////////////////// - - -#[cfg(all(test,not(feature="only_new_tests")))] +#[cfg(all(test, not(feature = "only_new_tests")))] //#[cfg(test)] -mod tests{ +mod tests { use super::*; - use std::{ - thread, - time::Duration, - }; + use std::{thread, time::Duration}; use crossbeam_utils::thread::scope as scoped_thread; - use abi_stable_shared::{file_span,test_utils::{must_panic}}; + use abi_stable_shared::{file_span, test_utils::must_panic}; #[test] #[cfg(not(all(miri, target_os = "windows")))] - fn state(){ + fn state() { { - let once=ROnce::new(); + let once = ROnce::new(); assert_eq!(once.state(), ROnceState::New); - once.call_once(||{}); + once.call_once(|| {}); assert_eq!(once.state(), ROnceState::Done); } { - let once=ROnce::new(); + let once = ROnce::new(); assert_eq!(once.state(), ROnceState::New); - must_panic(file_span!(),||{ - once.call_once(|| panic!() ); - }).unwrap(); + must_panic(file_span!(), || { + once.call_once(|| panic!()); + }) + .unwrap(); assert_eq!(once.state(), ROnceState::Poisoned); } { - static ONCE:ROnce=ROnce::new(); + static ONCE: ROnce = ROnce::new(); - scoped_thread(|scope|{ + scoped_thread(|scope| { let (tx_start, rx_start) = std::sync::mpsc::channel(); let (tx_end, rx_end) = std::sync::mpsc::channel(); - scope.spawn(move|_|{ + scope.spawn(move |_| { ONCE.call_once(|| { tx_start.send(()).unwrap(); rx_end.recv().unwrap(); }) }); - scope.spawn(move|_|{ + scope.spawn(move |_| { rx_start.recv().unwrap(); assert_eq!(ONCE.state(), ROnceState::InProgress); tx_end.send(()).unwrap(); }); - }).unwrap(); + }) + .unwrap(); assert_eq!(ONCE.state(), ROnceState::Done); } } #[test] - fn call_once(){ + fn call_once() { { - let once=ROnce::new(); - let mut a=0; - once.call_once(|| a+=1 ); - once.call_once(|| a+=2 ); - once.call_once(|| panic!() ); + let once = ROnce::new(); + let mut a = 0; + once.call_once(|| a += 1); + once.call_once(|| a += 2); + once.call_once(|| panic!()); assert_eq!(a, 1); } { - let once=ROnce::new(); - let mut a=0; - must_panic(file_span!(),||{ - once.call_once(|| panic!() ); - }).unwrap(); - must_panic(file_span!(),||{ - once.call_once(|| a+=2 ); - }).unwrap(); + let once = ROnce::new(); + let mut a = 0; + must_panic(file_span!(), || { + once.call_once(|| panic!()); + }) + .unwrap(); + must_panic(file_span!(), || { + once.call_once(|| a += 2); + }) + .unwrap(); assert_eq!(a, 0); } } #[test] - fn call_once_force(){ + fn call_once_force() { { - let once=ROnce::new(); - let mut a=0; - once.call_once_force(|_| a+=1 ); - once.call_once_force(|_| a+=2 ); + let once = ROnce::new(); + let mut a = 0; + once.call_once_force(|_| a += 1); + once.call_once_force(|_| a += 2); assert_eq!(a, 1); } { - let once=ROnce::new(); - let a=&mut 0; - must_panic(file_span!(),||{ - once.call_once_force(|state|{ + let once = ROnce::new(); + let a = &mut 0; + must_panic(file_span!(), || { + once.call_once_force(|state| { assert_eq!(state, ROnceState::New); panic!() }); - }).unwrap(); - once.call_once_force(|state|{ + }) + .unwrap(); + once.call_once_force(|state| { assert_eq!(state, ROnceState::Poisoned); - *a+=2; + *a += 2; }); - once.call_once_force(|_| *a+=4 ); - once.call_once_force(|_| panic!() ); + once.call_once_force(|_| *a += 4); + once.call_once_force(|_| panic!()); assert_eq!(*a, 2); } } - - -} \ No newline at end of file +} diff --git a/abi_stable/src/external_types/parking_lot/rw_lock.rs b/abi_stable/src/external_types/parking_lot/rw_lock.rs index a443097d..16e6e8d0 100644 --- a/abi_stable/src/external_types/parking_lot/rw_lock.rs +++ b/abi_stable/src/external_types/parking_lot/rw_lock.rs @@ -2,52 +2,45 @@ use std::{ cell::UnsafeCell, - fmt::{self,Debug,Display}, - ops::{Deref,DerefMut}, + fmt::{self, Debug, Display}, marker::PhantomData, mem, + ops::{Deref, DerefMut}, }; +use lock_api::{RawRwLock as RawRwLockTrait, RawRwLockTimed}; +use parking_lot::RawRwLock; -use parking_lot::{RawRwLock}; -use lock_api::{ - RawRwLock as RawRwLockTrait, - RawRwLockTimed, -}; - -use super::{RAW_LOCK_SIZE,UnsafeOveralignedField}; +use super::{UnsafeOveralignedField, RAW_LOCK_SIZE}; use crate::{ - StableAbi, marker_type::UnsyncUnsend, - prefix_type::{PrefixTypeTrait,WithMetadata}, + prefix_type::{PrefixTypeTrait, WithMetadata}, std_types::*, + StableAbi, }; - /////////////////////////////////////////////////////////////////////////////// -type OpaqueRwLock= - UnsafeOveralignedField; +type OpaqueRwLock = UnsafeOveralignedField; -const OM_PADDING:usize=RAW_LOCK_SIZE-mem::size_of::(); +const OM_PADDING: usize = RAW_LOCK_SIZE - mem::size_of::(); -const OPAQUE_LOCK:OpaqueRwLock= - OpaqueRwLock::new(::INIT,[0u8;OM_PADDING]); +const OPAQUE_LOCK: OpaqueRwLock = + OpaqueRwLock::new(::INIT, [0u8; OM_PADDING]); #[allow(dead_code)] -fn assert_lock_size(){ - let _assert_size:[();RAW_LOCK_SIZE-mem::size_of::()]; - let _assert_size:[();mem::size_of::()-RAW_LOCK_SIZE]; +fn assert_lock_size() { + let _assert_size: [(); RAW_LOCK_SIZE - mem::size_of::()]; + let _assert_size: [(); mem::size_of::() - RAW_LOCK_SIZE]; } - /** A read-write lock that allows dynamic mutable/shared borrows of shared data. RRwLock allows either multiple shared locks,or a single write lock. -# Poisoning +# Poisoning As opposed to the standard library version of this type, this rwlock type does not use poisoning, @@ -79,13 +72,12 @@ assert_eq!(*LOCK.read(),200); */ #[repr(C)] #[derive(StableAbi)] -pub struct RRwLock{ - raw_lock:OpaqueRwLock, - data:UnsafeCell, - vtable:VTable_Ref, +pub struct RRwLock { + raw_lock: OpaqueRwLock, + data: UnsafeCell, + vtable: VTable_Ref, } - /** A read guard,which allows shared access to the data inside the `RRwLock`. @@ -95,14 +87,13 @@ When dropped this will unlock the rwlock. */ #[repr(transparent)] #[derive(StableAbi)] -#[sabi(bound="T:'a")] +#[sabi(bound = "T:'a")] #[must_use] pub struct RReadGuard<'a, T> { rlock: &'a RRwLock, _marker: PhantomData<(&'a T, UnsyncUnsend)>, } - /** A write guard,which allows mutable access to the data inside the `RRwLock`. @@ -112,19 +103,16 @@ When dropped this will unlock the rwlock. */ #[repr(transparent)] #[derive(StableAbi)] -#[sabi(bound="T:'a")] +#[sabi(bound = "T:'a")] #[must_use] pub struct RWriteGuard<'a, T> { rlock: &'a RRwLock, _marker: PhantomData<(&'a mut T, UnsyncUnsend)>, } - - /////////////////////////////////////////////////////////////////////////////// - -impl RRwLock{ +impl RRwLock { /// Constructs a lock,wrapping `value`. /// /// # Example @@ -133,36 +121,36 @@ impl RRwLock{ /// use abi_stable::external_types::RRwLock; /// /// static LOCK:RRwLock>=RRwLock::new(None); - /// + /// /// let lock=RRwLock::new(0); /// /// ``` - pub const fn new(value:T)->Self{ - Self{ - raw_lock:OPAQUE_LOCK, - data:UnsafeCell::new(value), + pub const fn new(value: T) -> Self { + Self { + raw_lock: OPAQUE_LOCK, + data: UnsafeCell::new(value), vtable: VTable::VTABLE, } } #[inline] - fn vtable(&self)->VTable_Ref{ + fn vtable(&self) -> VTable_Ref { self.vtable } #[inline] - fn write_guard(&self)->RWriteGuard<'_,T>{ - RWriteGuard{ - rlock:self, - _marker:PhantomData + fn write_guard(&self) -> RWriteGuard<'_, T> { + RWriteGuard { + rlock: self, + _marker: PhantomData, } } #[inline] - fn read_guard(&self)->RReadGuard<'_,T>{ - RReadGuard{ - rlock:self, - _marker:PhantomData + fn read_guard(&self) -> RReadGuard<'_, T> { + RReadGuard { + rlock: self, + _marker: PhantomData, } } @@ -179,7 +167,7 @@ impl RRwLock{ /// /// ``` #[inline] - pub fn into_inner(self)->T{ + pub fn into_inner(self) -> T { self.data.into_inner() } @@ -200,314 +188,298 @@ impl RRwLock{ /// /// ``` #[inline] - pub fn get_mut(&mut self)->&mut T{ - unsafe{ &mut *self.data.get() } + pub fn get_mut(&mut self) -> &mut T { + unsafe { &mut *self.data.get() } } /** -Acquires a lock for reading,blocking the current thread until it can. + Acquires a lock for reading,blocking the current thread until it can. -This function returns a read guard,which releases read access when it is dropped. + This function returns a read guard,which releases read access when it is dropped. -Trying to lock the rwlock for reading in the same thread that has write -access to the same rwlock will cause a deadlock. + Trying to lock the rwlock for reading in the same thread that has write + access to the same rwlock will cause a deadlock. -# Example + # Example -``` -use abi_stable::external_types::RRwLock; + ``` + use abi_stable::external_types::RRwLock; -static LOCK:RRwLock=RRwLock::new(0); + static LOCK:RRwLock=RRwLock::new(0); -*LOCK.write()+=4; + *LOCK.write()+=4; -let read_guard_a=LOCK.read(); -let read_guard_b=LOCK.read(); + let read_guard_a=LOCK.read(); + let read_guard_b=LOCK.read(); -assert_eq!(*read_guard_a,4); -assert_eq!(*read_guard_b,4); + assert_eq!(*read_guard_a,4); + assert_eq!(*read_guard_b,4); -``` + ``` - */ + */ #[inline] - pub fn read(&self)->RReadGuard<'_,T>{ + pub fn read(&self) -> RReadGuard<'_, T> { self.vtable().lock_shared()(&self.raw_lock); self.read_guard() } /** -Attemps to acquire a lock for reading,failing if it is locked for writing. + Attemps to acquire a lock for reading,failing if it is locked for writing. -Returns the read guard if the rwlock can be immediately acquired,otherwise returns RNone. + Returns the read guard if the rwlock can be immediately acquired,otherwise returns RNone. -# Example + # Example -``` -use abi_stable::external_types::RRwLock; + ``` + use abi_stable::external_types::RRwLock; -static LOCK:RRwLock=RRwLock::new(0); + static LOCK:RRwLock=RRwLock::new(0); -let mut write_guard=LOCK.write(); + let mut write_guard=LOCK.write(); -assert!(LOCK.try_read().is_none()); + assert!(LOCK.try_read().is_none()); -*write_guard+=4; -drop(write_guard); + *write_guard+=4; + drop(write_guard); -assert_eq!(*LOCK.try_read().unwrap(),4); + assert_eq!(*LOCK.try_read().unwrap(),4); -``` + ``` -*/ + */ #[inline] - pub fn try_read(&self) -> ROption>{ + pub fn try_read(&self) -> ROption> { if self.vtable().try_lock_shared()(&self.raw_lock) { RSome(self.read_guard()) - }else{ + } else { RNone } } - -/** -Attempts to acquire a lock for reading,for the timeout duration. -Once the timeout is reached,this will return None, -otherwise it will return the read guard. + /** + Attempts to acquire a lock for reading,for the timeout duration. + Once the timeout is reached,this will return None, + otherwise it will return the read guard. -# Example -``` -use abi_stable::{ - external_types::RRwLock, - std_types::RDuration, -}; + # Example -static LOCK:RRwLock=RRwLock::new(0); + ``` + use abi_stable::{ + external_types::RRwLock, + std_types::RDuration, + }; -static DUR:RDuration=RDuration::from_millis(1); + static LOCK:RRwLock=RRwLock::new(0); -let mut write_guard=LOCK.write(); + static DUR:RDuration=RDuration::from_millis(1); -assert!(LOCK.try_read_for(DUR).is_none()); + let mut write_guard=LOCK.write(); -*write_guard+=7; -drop(write_guard); + assert!(LOCK.try_read_for(DUR).is_none()); -assert_eq!(*LOCK.try_read_for(DUR).unwrap(),7); + *write_guard+=7; + drop(write_guard); -``` + assert_eq!(*LOCK.try_read_for(DUR).unwrap(),7); -*/ + ``` + + */ #[inline] - pub fn try_read_for(&self, timeout: RDuration) -> ROption>{ - if self.vtable().try_lock_shared_for()(&self.raw_lock,timeout) { + pub fn try_read_for(&self, timeout: RDuration) -> ROption> { + if self.vtable().try_lock_shared_for()(&self.raw_lock, timeout) { RSome(self.read_guard()) - }else{ + } else { RNone } } /** -Acquires a lock for writing,blocking the current thread until it can. + Acquires a lock for writing,blocking the current thread until it can. -This function returns a write guard,which releases write access when it is dropped. + This function returns a write guard,which releases write access when it is dropped. -Trying to lock the rwlock in the same thread that has read or write -access to the same rwlock will cause a deadlock. + Trying to lock the rwlock in the same thread that has read or write + access to the same rwlock will cause a deadlock. -# Example + # Example -``` -use abi_stable::external_types::RRwLock; + ``` + use abi_stable::external_types::RRwLock; -let lock=RRwLock::new(0); + let lock=RRwLock::new(0); -let mut guard=lock.write(); + let mut guard=lock.write(); -*guard+=4; + *guard+=4; -assert_eq!(*guard,4); + assert_eq!(*guard,4); -``` - */ + ``` + */ #[inline] - pub fn write(&self)->RWriteGuard<'_,T>{ + pub fn write(&self) -> RWriteGuard<'_, T> { self.vtable().lock_exclusive()(&self.raw_lock); self.write_guard() } /** -Attemps to acquire a lock for writing. + Attemps to acquire a lock for writing. -Returns the write guard if the rwlock can be immediately acquired,otherwise returns RNone. + Returns the write guard if the rwlock can be immediately acquired,otherwise returns RNone. -# Example + # Example -``` -use abi_stable::external_types::RRwLock; + ``` + use abi_stable::external_types::RRwLock; -let lock=RRwLock::new(0); + let lock=RRwLock::new(0); -let mut guard=lock.write(); + let mut guard=lock.write(); -assert!( lock.try_write().is_none() ); + assert!( lock.try_write().is_none() ); -*guard+=4; + *guard+=4; -assert_eq!(*guard,4); + assert_eq!(*guard,4); -``` -*/ + ``` + */ #[inline] - pub fn try_write(&self) -> ROption>{ + pub fn try_write(&self) -> ROption> { if self.vtable().try_lock_exclusive()(&self.raw_lock) { RSome(self.write_guard()) - }else{ + } else { RNone } } - -/** -Attempts to acquire a lock for writing,for the timeout duration. -Once the timeout is reached,this will return None, -otherwise it will return the write guard. + /** + Attempts to acquire a lock for writing,for the timeout duration. + Once the timeout is reached,this will return None, + otherwise it will return the write guard. -# Example -``` -use abi_stable::{ - external_types::RRwLock, - std_types::RDuration, -}; + # Example -static DUR:RDuration=RDuration::from_millis(1); + ``` + use abi_stable::{ + external_types::RRwLock, + std_types::RDuration, + }; -let lock=RRwLock::new(0); + static DUR:RDuration=RDuration::from_millis(1); -let mut write_guard=lock.try_write_for(DUR).unwrap(); -*write_guard+=4; + let lock=RRwLock::new(0); -assert!( lock.try_write_for(DUR).is_none() ); + let mut write_guard=lock.try_write_for(DUR).unwrap(); + *write_guard+=4; -assert_eq!(*write_guard,4); + assert!( lock.try_write_for(DUR).is_none() ); -``` + assert_eq!(*write_guard,4); -*/ + ``` + + */ #[inline] - pub fn try_write_for(&self, timeout: RDuration) -> ROption>{ - if self.vtable().try_lock_exclusive_for()(&self.raw_lock,timeout) { + pub fn try_write_for(&self, timeout: RDuration) -> ROption> { + if self.vtable().try_lock_exclusive_for()(&self.raw_lock, timeout) { RSome(self.write_guard()) - }else{ + } else { RNone } } } -unsafe impl Send for RRwLock -where RawRwLock:Send -{} - -unsafe impl Sync for RRwLock -where RawRwLock:Sync -{} - - +unsafe impl Send for RRwLock where RawRwLock: Send {} +unsafe impl Sync for RRwLock where RawRwLock: Sync {} /////////////////////////////////////////////////////////////////////////////// - macro_rules! impl_lock_guard { - ($guard:ident) => ( - - impl<'a,T> Display for $guard<'a, T> + ($guard:ident) => { + impl<'a, T> Display for $guard<'a, T> where - T:Display + T: Display, { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Display::fmt(&**self,f) + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Display::fmt(&**self, f) } } - - impl<'a,T> Debug for $guard<'a, T> + impl<'a, T> Debug for $guard<'a, T> where - T:Debug + T: Debug, { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Debug::fmt(&**self,f) + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Debug::fmt(&**self, f) } } + impl<'a, T> Deref for $guard<'a, T> { + type Target = T; - impl<'a,T> Deref for $guard<'a, T> { - type Target=T; - - fn deref(&self)->&T{ - unsafe{ &*self.rlock.data.get() } + fn deref(&self) -> &T { + unsafe { &*self.rlock.data.get() } } } - - ) + }; } ////////////////////////////////////// -impl_lock_guard!{ RReadGuard } +impl_lock_guard! { RReadGuard } -impl<'a,T> Drop for RReadGuard<'a, T> { - fn drop(&mut self){ - let vtable=self.rlock.vtable(); +impl<'a, T> Drop for RReadGuard<'a, T> { + fn drop(&mut self) { + let vtable = self.rlock.vtable(); vtable.unlock_shared()(&self.rlock.raw_lock); } } ////////////////////////////////////// - -impl_lock_guard!{ RWriteGuard } -impl<'a,T> DerefMut for RWriteGuard<'a, T> { - fn deref_mut(&mut self)->&mut T{ - unsafe{ &mut *self.rlock.data.get() } +impl_lock_guard! { RWriteGuard } +impl<'a, T> DerefMut for RWriteGuard<'a, T> { + fn deref_mut(&mut self) -> &mut T { + unsafe { &mut *self.rlock.data.get() } } } -impl<'a,T> Drop for RWriteGuard<'a, T> { - fn drop(&mut self){ - let vtable=self.rlock.vtable(); +impl<'a, T> Drop for RWriteGuard<'a, T> { + fn drop(&mut self) { + let vtable = self.rlock.vtable(); vtable.unlock_exclusive()(&self.rlock.raw_lock); } } - - /////////////////////////////////////////////////////////////////////////////// - #[repr(C)] #[derive(StableAbi)] #[sabi(kind(Prefix))] #[sabi(missing_field(panic))] -struct VTable{ - lock_shared:extern "C" fn(this:&OpaqueRwLock), - try_lock_shared:extern "C" fn(this:&OpaqueRwLock) -> bool, - try_lock_shared_for:extern "C" fn(this:&OpaqueRwLock, timeout: RDuration) -> bool, - unlock_shared:extern "C" fn(this:&OpaqueRwLock), - - lock_exclusive:extern "C" fn(this:&OpaqueRwLock), - try_lock_exclusive:extern "C" fn(this:&OpaqueRwLock) -> bool, - try_lock_exclusive_for:extern "C" fn(this:&OpaqueRwLock, timeout: RDuration) -> bool, +struct VTable { + lock_shared: extern "C" fn(this: &OpaqueRwLock), + try_lock_shared: extern "C" fn(this: &OpaqueRwLock) -> bool, + try_lock_shared_for: extern "C" fn(this: &OpaqueRwLock, timeout: RDuration) -> bool, + unlock_shared: extern "C" fn(this: &OpaqueRwLock), + + lock_exclusive: extern "C" fn(this: &OpaqueRwLock), + try_lock_exclusive: extern "C" fn(this: &OpaqueRwLock) -> bool, + try_lock_exclusive_for: extern "C" fn(this: &OpaqueRwLock, timeout: RDuration) -> bool, #[sabi(last_prefix_field)] - unlock_exclusive:extern "C" fn(this:&OpaqueRwLock), + unlock_exclusive: extern "C" fn(this: &OpaqueRwLock), } -impl VTable{ +impl VTable { const _TMP0: WithMetadata = { - let vtable = VTable{ + let vtable = VTable { lock_shared, try_lock_shared, try_lock_shared_for, @@ -521,150 +493,138 @@ impl VTable{ }; // The VTABLE for this type in this executable/library - const VTABLE: VTable_Ref = { - VTable_Ref(Self::_TMP0.static_as_prefix()) - }; + const VTABLE: VTable_Ref = { VTable_Ref(Self::_TMP0.static_as_prefix()) }; } - - -extern "C" fn lock_shared(this:&OpaqueRwLock){ - extern_fn_panic_handling!{ +extern "C" fn lock_shared(this: &OpaqueRwLock) { + extern_fn_panic_handling! { this.value.lock_shared(); } } -extern "C" fn try_lock_shared(this:&OpaqueRwLock) -> bool{ - extern_fn_panic_handling!{ - this.value.try_lock_shared() +extern "C" fn try_lock_shared(this: &OpaqueRwLock) -> bool { + extern_fn_panic_handling! { + this.value.try_lock_shared() } } -extern "C" fn try_lock_shared_for(this:&OpaqueRwLock, timeout: RDuration) -> bool{ - extern_fn_panic_handling!{ +extern "C" fn try_lock_shared_for(this: &OpaqueRwLock, timeout: RDuration) -> bool { + extern_fn_panic_handling! { this.value.try_lock_shared_for(timeout.into()) } } -extern "C" fn unlock_shared(this:&OpaqueRwLock){ - extern_fn_panic_handling!{ +extern "C" fn unlock_shared(this: &OpaqueRwLock) { + extern_fn_panic_handling! { unsafe{ this.value.unlock_shared(); } } } - -extern "C" fn lock_exclusive(this:&OpaqueRwLock){ - extern_fn_panic_handling!{ +extern "C" fn lock_exclusive(this: &OpaqueRwLock) { + extern_fn_panic_handling! { this.value.lock_exclusive(); } } -extern "C" fn try_lock_exclusive(this:&OpaqueRwLock) -> bool{ - extern_fn_panic_handling!{ - this.value.try_lock_exclusive() +extern "C" fn try_lock_exclusive(this: &OpaqueRwLock) -> bool { + extern_fn_panic_handling! { + this.value.try_lock_exclusive() } } -extern "C" fn try_lock_exclusive_for(this:&OpaqueRwLock, timeout: RDuration) -> bool{ - extern_fn_panic_handling!{ +extern "C" fn try_lock_exclusive_for(this: &OpaqueRwLock, timeout: RDuration) -> bool { + extern_fn_panic_handling! { this.value.try_lock_exclusive_for(timeout.into()) } } -extern "C" fn unlock_exclusive(this:&OpaqueRwLock){ - extern_fn_panic_handling!{ +extern "C" fn unlock_exclusive(this: &OpaqueRwLock) { + extern_fn_panic_handling! { unsafe{ this.value.unlock_exclusive(); } } } - /////////////////////////////////////////////////////////////////////////////// - - - -#[cfg(all(test,not(feature="only_new_tests")))] -mod tests{ +#[cfg(all(test, not(feature = "only_new_tests")))] +mod tests { use super::*; - use std::{ - thread, - time::Duration, - }; + use std::{thread, time::Duration}; use crossbeam_utils::thread::scope as scoped_thread; use crate::test_utils::check_formatting_equivalence; #[test] - fn get_mut(){ - let mut lock:RRwLock=RRwLock::new(0); - assert_eq!(*lock.read(),0); - *lock.get_mut()+=100; - assert_eq!(*lock.read(),100); - *lock.get_mut()+=100; - assert_eq!(*lock.read(),200); + fn get_mut() { + let mut lock: RRwLock = RRwLock::new(0); + assert_eq!(*lock.read(), 0); + *lock.get_mut() += 100; + assert_eq!(*lock.read(), 100); + *lock.get_mut() += 100; + assert_eq!(*lock.read(), 200); } - #[test] - fn into_inner(){ - let lock:RRwLock=RRwLock::new(0); + fn into_inner() { + let lock: RRwLock = RRwLock::new(0); assert_eq!(*lock.read(), 0); - *lock.write()+=100; + *lock.write() += 100; assert_eq!(*lock.read(), 100); assert_eq!(lock.into_inner(), 100); } #[test] - fn debug_display(){ - let str_="\nhello\rhello\rhello\n"; - let lock=RRwLock::new(str_); - check_formatting_equivalence(&lock.read(),str_); - check_formatting_equivalence(&lock.write(),str_); + fn debug_display() { + let str_ = "\nhello\rhello\rhello\n"; + let lock = RRwLock::new(str_); + check_formatting_equivalence(&lock.read(), str_); + check_formatting_equivalence(&lock.write(), str_); } - const EXPECTED:usize=64; + const EXPECTED: usize = 64; #[test] #[cfg(not(all(miri, target_os = "windows")))] - fn regular_locking(){ - static LOCK:RRwLock=RRwLock::new(0); + fn regular_locking() { + static LOCK: RRwLock = RRwLock::new(0); - scoped_thread(|scope|{ + scoped_thread(|scope| { for j in 0..16 { - scope.spawn(move|_|{ + scope.spawn(move |_| { for _ in 0..8 { - if (j%2)==0 { - *LOCK.write()+=1; - }else{ - let value=*LOCK.read(); - assert!(value <= EXPECTED,"{} <= {}",value,EXPECTED); + if (j % 2) == 0 { + *LOCK.write() += 1; + } else { + let value = *LOCK.read(); + assert!(value <= EXPECTED, "{} <= {}", value, EXPECTED); } } }); } - }).unwrap(); + }) + .unwrap(); - assert_eq!(*LOCK.read(),64); + assert_eq!(*LOCK.read(), 64); } #[test] #[cfg(not(all(miri, target_os = "windows")))] - fn try_lock__(){ - static LOCK:RRwLock=RRwLock::new(0); + fn try_lock__() { + static LOCK: RRwLock = RRwLock::new(0); - scoped_thread(|scope|{ + scoped_thread(|scope| { for j in 0..16 { - scope.spawn(move|_|{ + scope.spawn(move |_| { for _ in 0..8 { loop { - if (j%2)==0 { - if let RSome(mut guard)=LOCK.try_write() { - *guard+=1; + if (j % 2) == 0 { + if let RSome(mut guard) = LOCK.try_write() { + *guard += 1; break; } - }else{ - if let RSome(guard)=LOCK.try_read() { - assert!(*guard <= EXPECTED,"{} <= {}",*guard,EXPECTED); + } else { + if let RSome(guard) = LOCK.try_read() { + assert!(*guard <= EXPECTED, "{} <= {}", *guard, EXPECTED); break; } } @@ -672,49 +632,50 @@ mod tests{ } }); } - }).unwrap(); + }) + .unwrap(); - assert_eq!(*LOCK.read(),64); + assert_eq!(*LOCK.read(), 64); - scoped_thread(|scope|{ - let _guard=LOCK.write(); - scope.spawn(move|_|{ + scoped_thread(|scope| { + let _guard = LOCK.write(); + scope.spawn(move |_| { assert_eq!(LOCK.try_read().map(drop), RNone); }); thread::sleep(Duration::from_millis(100)); - }).unwrap(); - - scoped_thread(|scope|{ - let _guard=LOCK.read(); - scope.spawn(move|_|{ + }) + .unwrap(); + + scoped_thread(|scope| { + let _guard = LOCK.read(); + scope.spawn(move |_| { assert_eq!(LOCK.try_write().map(drop), RNone); }); thread::sleep(Duration::from_millis(100)); - }).unwrap(); - - + }) + .unwrap(); } // miri detects a memory leak here, and I can't figure out why #[test] #[cfg(not(miri))] - fn try_lock_for(){ - static LOCK:RRwLock=RRwLock::new(0); + fn try_lock_for() { + static LOCK: RRwLock = RRwLock::new(0); - scoped_thread(|scope|{ + scoped_thread(|scope| { for j in 0..16 { - scope.spawn(move|_|{ + scope.spawn(move |_| { for i in 0..8 { - let wait_for=RDuration::new(0,(i+1)*500_000); + let wait_for = RDuration::new(0, (i + 1) * 500_000); loop { - if (j%2)==0 { - if let RSome(mut guard)=LOCK.try_write_for(wait_for) { - *guard+=1; + if (j % 2) == 0 { + if let RSome(mut guard) = LOCK.try_write_for(wait_for) { + *guard += 1; break; } - }else{ - if let RSome(guard)=LOCK.try_read_for(wait_for) { - assert!(*guard <= EXPECTED,"{} <= {}",*guard,EXPECTED); + } else { + if let RSome(guard) = LOCK.try_read_for(wait_for) { + assert!(*guard <= EXPECTED, "{} <= {}", *guard, EXPECTED); break; } } @@ -722,29 +683,33 @@ mod tests{ } }); } - }).unwrap(); - - assert_eq!(*LOCK.read(),64); - - - scoped_thread(|scope|{ - let _guard=LOCK.write(); - scope.spawn(move|_|{ - assert_eq!(LOCK.try_read_for(RDuration::new(0,100_000)).map(drop), RNone); + }) + .unwrap(); + + assert_eq!(*LOCK.read(), 64); + + scoped_thread(|scope| { + let _guard = LOCK.write(); + scope.spawn(move |_| { + assert_eq!( + LOCK.try_read_for(RDuration::new(0, 100_000)).map(drop), + RNone + ); }); thread::sleep(Duration::from_millis(100)); - }).unwrap(); - - - scoped_thread(|scope|{ - let _guard=LOCK.read(); - scope.spawn(move|_|{ - assert_eq!(LOCK.try_write_for(RDuration::new(0,100_000)).map(drop), RNone); + }) + .unwrap(); + + scoped_thread(|scope| { + let _guard = LOCK.read(); + scope.spawn(move |_| { + assert_eq!( + LOCK.try_write_for(RDuration::new(0, 100_000)).map(drop), + RNone + ); }); thread::sleep(Duration::from_millis(100)); - }).unwrap(); - - + }) + .unwrap(); } - -} \ No newline at end of file +} diff --git a/abi_stable/src/external_types/serde_json.rs b/abi_stable/src/external_types/serde_json.rs index 3aa952fa..5b3eb4f9 100644 --- a/abi_stable/src/external_types/serde_json.rs +++ b/abi_stable/src/external_types/serde_json.rs @@ -3,17 +3,14 @@ Ffi-safe equivalents of `serde_json` types. */ use std::{ - convert::{TryFrom,TryInto}, - fmt::{self,Debug,Display}, + convert::{TryFrom, TryInto}, + fmt::{self, Debug, Display}, }; -use serde::{Deserialize,Serialize,Deserializer,Serializer}; -use serde_json::{ - error::Error as JsonError, - value::RawValue, -}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use serde_json::{error::Error as JsonError, value::RawValue}; -use crate::std_types::{RStr,RString}; +use crate::std_types::{RStr, RString}; /** An ffi-safe equivalent of `&serde_json::value::RawValue` @@ -89,78 +86,74 @@ assert_eq!(pair.second.get(),r##"{"hello":"world"}"##); ``` */ #[repr(transparent)] -#[derive(StableAbi,Copy,Clone)] -pub struct RawValueRef<'a>{ - ref_:RStr<'a>, +#[derive(StableAbi, Copy, Clone)] +pub struct RawValueRef<'a> { + ref_: RStr<'a>, } +impl<'a> RawValueRef<'a> { + /** + Converts a `&str` to a `RawValueRef<'a>` without checking whether it is valid JSON. -impl<'a> RawValueRef<'a>{ -/** -Converts a `&str` to a `RawValueRef<'a>` without checking whether it is valid JSON. + # Safety -# Safety + `input` must be valid JSON and contain no leading or trailing whitespace. -`input` must be valid JSON and contain no leading or trailing whitespace. + # Example -# Example - -``` -use abi_stable::external_types::RawValueRef; + ``` + use abi_stable::external_types::RawValueRef; -const JSON:&'static str=r##"{"huh":"that is interesting"}"##; + const JSON:&'static str=r##"{"huh":"that is interesting"}"##; -let value=unsafe{ RawValueRef::from_str_unchecked(JSON) }; + let value=unsafe{ RawValueRef::from_str_unchecked(JSON) }; -assert_eq!( - serde_json::to_string(&value).unwrap().as_str(), - JSON -); -``` + assert_eq!( + serde_json::to_string(&value).unwrap().as_str(), + JSON + ); + ``` -*/ - pub unsafe fn from_str_unchecked(input:&'a str)->RawValueRef<'a>{ - Self{ - ref_:RStr::from(input), + */ + pub unsafe fn from_str_unchecked(input: &'a str) -> RawValueRef<'a> { + Self { + ref_: RStr::from(input), } } -/** -Converts a `RStr<'a>` to a `RawValueRef<'a>` without checking whether it is valid JSON. + /** + Converts a `RStr<'a>` to a `RawValueRef<'a>` without checking whether it is valid JSON. -# Safety + # Safety -`input` must be valid JSON and contain no leading or trailing whitespace. + `input` must be valid JSON and contain no leading or trailing whitespace. -# Example + # Example -``` -use abi_stable::{ - external_types::RawValueRef, - std_types::RStr, -}; + ``` + use abi_stable::{ + external_types::RawValueRef, + std_types::RStr, + }; -const JSON:&'static str=r##"{"huh":"that is interesting"}"##; + const JSON:&'static str=r##"{"huh":"that is interesting"}"##; -let json_rstr=RStr::from(JSON); -let value=unsafe{ RawValueRef::from_rstr_unchecked(json_rstr) }; + let json_rstr=RStr::from(JSON); + let value=unsafe{ RawValueRef::from_rstr_unchecked(json_rstr) }; -assert_eq!( - serde_json::to_string(&value).unwrap().as_str(), - JSON -); -``` + assert_eq!( + serde_json::to_string(&value).unwrap().as_str(), + JSON + ); + ``` -*/ - pub unsafe fn from_rstr_unchecked(input:RStr<'a>)->RawValueRef<'a>{ - Self{ - ref_:input, - } + */ + pub unsafe fn from_rstr_unchecked(input: RStr<'a>) -> RawValueRef<'a> { + Self { ref_: input } } - /// Attempts to convert a `&'a str` into a `RawValueRef<'a>`. /// /// Fails in the same cases as parsing a `&'a RawValue` from a string does. @@ -181,7 +174,7 @@ assert_eq!( /// /// ``` #[inline] - pub fn try_from_str(input:&'a str)->Result{ + pub fn try_from_str(input: &'a str) -> Result { input.try_into() } @@ -200,7 +193,7 @@ assert_eq!( /// /// ``` #[inline] - pub fn get(&self)->&'a str{ + pub fn get(&self) -> &'a str { self.ref_.as_str() } @@ -222,64 +215,53 @@ assert_eq!( /// /// ``` #[inline] - pub fn get_rstr(&self)->RStr<'a>{ + pub fn get_rstr(&self) -> RStr<'a> { self.get().into() } - } - -impl<'a> Debug for RawValueRef<'a>{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Debug::fmt(&self.ref_,f) +impl<'a> Debug for RawValueRef<'a> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Debug::fmt(&self.ref_, f) } } - -impl<'a> Display for RawValueRef<'a>{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Display::fmt(&self.ref_,f) +impl<'a> Display for RawValueRef<'a> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Display::fmt(&self.ref_, f) } } - -impl<'a> From<&'a RawValue> for RawValueRef<'a>{ - fn from(v:&'a RawValue)->Self{ - Self{ - ref_:v.get().into(), +impl<'a> From<&'a RawValue> for RawValueRef<'a> { + fn from(v: &'a RawValue) -> Self { + Self { + ref_: v.get().into(), } } } - -impl<'a> TryFrom<&'a str> for RawValueRef<'a>{ - type Error=JsonError; - fn try_from(v:&'a str)->Result{ - serde_json::from_str::<&'a RawValue>(v) - .map(Self::from) +impl<'a> TryFrom<&'a str> for RawValueRef<'a> { + type Error = JsonError; + fn try_from(v: &'a str) -> Result { + serde_json::from_str::<&'a RawValue>(v).map(Self::from) } } - -impl<'a> Serialize for RawValueRef<'a>{ +impl<'a> Serialize for RawValueRef<'a> { fn serialize(&self, serializer: Z) -> Result where Z: Serializer, { - unsafe{ - into_ref_rawvalue(self.ref_.as_str()).serialize(serializer) - } + unsafe { into_ref_rawvalue(self.ref_.as_str()).serialize(serializer) } } } - -impl<'de: 'a, 'a> Deserialize<'de> for RawValueRef<'a>{ +impl<'de: 'a, 'a> Deserialize<'de> for RawValueRef<'a> { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { - <&'a RawValue>::deserialize(deserializer) - .map(Self::from) + <&'a RawValue>::deserialize(deserializer).map(Self::from) } } @@ -356,78 +338,75 @@ assert_eq!(pair.second.get(),r##""How many apples?"}"##); */ #[repr(transparent)] -#[derive(StableAbi,Clone)] -pub struct RawValueBox{ - string:RString, +#[derive(StableAbi, Clone)] +pub struct RawValueBox { + string: RString, } +impl RawValueBox { + /** + Converts a `String` to an `RawValueBox` without checking whether it is valid JSON. -impl RawValueBox{ -/** -Converts a `String` to an `RawValueBox` without checking whether it is valid JSON. - -# Safety + # Safety -`input` must be valid JSON and contain no leading or trailing whitespace. + `input` must be valid JSON and contain no leading or trailing whitespace. -# Example + # Example -``` -use abi_stable::external_types::RawValueBox; + ``` + use abi_stable::external_types::RawValueBox; -const JSON:&'static str=r##"{"huh":"that is interesting"}"##; + const JSON:&'static str=r##"{"huh":"that is interesting"}"##; -let value=unsafe{ RawValueBox::from_string_unchecked(JSON.to_string()) }; + let value=unsafe{ RawValueBox::from_string_unchecked(JSON.to_string()) }; -assert_eq!( - serde_json::to_string(&value).unwrap().as_str(), - JSON -); -``` + assert_eq!( + serde_json::to_string(&value).unwrap().as_str(), + JSON + ); + ``` -*/ + */ #[inline] - pub unsafe fn from_string_unchecked(input:String)->RawValueBox{ - Self{ - string:input.into() + pub unsafe fn from_string_unchecked(input: String) -> RawValueBox { + Self { + string: input.into(), } } -/** -Converts an `RString` to an `RawValueBox` without checking whether it is valid JSON. + /** + Converts an `RString` to an `RawValueBox` without checking whether it is valid JSON. -# Safety + # Safety -`input` must be valid JSON and contain no leading or trailing whitespace. + `input` must be valid JSON and contain no leading or trailing whitespace. -# Example + # Example -``` -use abi_stable::{ - external_types::RawValueBox, - std_types::RString, -}; + ``` + use abi_stable::{ + external_types::RawValueBox, + std_types::RString, + }; -const JSON:&'static str=r##"{"huh":"that is interesting"}"##; + const JSON:&'static str=r##"{"huh":"that is interesting"}"##; -let json_rstring=RString::from(JSON); -let value=unsafe{ RawValueBox::from_rstring_unchecked(json_rstring) }; + let json_rstring=RString::from(JSON); + let value=unsafe{ RawValueBox::from_rstring_unchecked(json_rstring) }; -assert_eq!( - serde_json::to_string(&value).unwrap().as_str(), - JSON -); -``` + assert_eq!( + serde_json::to_string(&value).unwrap().as_str(), + JSON + ); + ``` -*/ + */ #[inline] - pub unsafe fn from_rstring_unchecked(input:RString)->RawValueBox{ - Self{ - string:input - } + pub unsafe fn from_rstring_unchecked(input: RString) -> RawValueBox { + Self { string: input } } /// Attempts to convert a `String` into a `RawValueBox`. @@ -450,7 +429,7 @@ assert_eq!( /// /// ``` #[inline] - pub fn try_from_string(input:String)->Result{ + pub fn try_from_string(input: String) -> Result { input.try_into() } @@ -469,10 +448,10 @@ assert_eq!( /// /// ``` #[inline] - pub fn get(&self)->&str{ + pub fn get(&self) -> &str { self.string.as_str() } - + /// Gets the json being serialized,as a `RStr<'a>`. /// /// # Example @@ -491,7 +470,7 @@ assert_eq!( /// /// ``` #[inline] - pub fn get_rstr(&self)->RStr<'_>{ + pub fn get_rstr(&self) -> RStr<'_> { self.get().into() } @@ -506,92 +485,74 @@ assert_eq!( /// /// let raw=serde_json::from_str::(JSON).unwrap(); /// - /// assert_eq!( - /// raw.get(), + /// assert_eq!( + /// raw.get(), /// RawValueRef::try_from_str(JSON).unwrap().get() /// ); /// /// ``` #[inline] - pub fn as_raw_value_ref(&self)->RawValueRef<'_>{ - unsafe{ - RawValueRef::from_str_unchecked(self.get()) - } + pub fn as_raw_value_ref(&self) -> RawValueRef<'_> { + unsafe { RawValueRef::from_str_unchecked(self.get()) } } } - -impl Debug for RawValueBox{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Debug::fmt(&self.string,f) +impl Debug for RawValueBox { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Debug::fmt(&self.string, f) } } - -impl Display for RawValueBox{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Display::fmt(&self.string,f) +impl Display for RawValueBox { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Display::fmt(&self.string, f) } } - -impl From> for RawValueBox{ - fn from(v:Box)->Self{ - let string:String=from_boxed_rawvalue(v).into(); - Self{ - string:string.into() +impl From> for RawValueBox { + fn from(v: Box) -> Self { + let string: String = from_boxed_rawvalue(v).into(); + Self { + string: string.into(), } } } - -impl TryFrom for RawValueBox{ - type Error=JsonError; - fn try_from(v:String)->Result{ - RawValue::from_string(v) - .map(Self::from) +impl TryFrom for RawValueBox { + type Error = JsonError; + fn try_from(v: String) -> Result { + RawValue::from_string(v).map(Self::from) } } - -impl Serialize for RawValueBox{ +impl Serialize for RawValueBox { fn serialize(&self, serializer: Z) -> Result where Z: Serializer, { - unsafe{ - into_ref_rawvalue(&self.string).serialize(serializer) - } + unsafe { into_ref_rawvalue(&self.string).serialize(serializer) } } } - -impl<'de> Deserialize<'de> for RawValueBox{ +impl<'de> Deserialize<'de> for RawValueBox { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { - >::deserialize(deserializer) - .map(Self::from) + >::deserialize(deserializer).map(Self::from) } } - /////////////////////////////////////////////////////////////////////////////// - -fn from_boxed_rawvalue(x:Box)->Box{ - // This would become Undefined Behavior if +fn from_boxed_rawvalue(x: Box) -> Box { + // This would become Undefined Behavior if // serde_json somehow changes RawValue to not be a transparent wrapper around `str` - unsafe{ - Box::from_raw(Box::into_raw(x) as *mut str) - } + unsafe { Box::from_raw(Box::into_raw(x) as *mut str) } } - -unsafe fn into_ref_rawvalue(x:&str)->&RawValue{ - // This would become Undefined Behavior if +unsafe fn into_ref_rawvalue(x: &str) -> &RawValue { + // This would become Undefined Behavior if // serde_json somehow changes RawValue to not be a transparent wrapper around `str` &*(x as *const str as *const RawValue) } - diff --git a/abi_stable/src/for_examples.rs b/abi_stable/src/for_examples.rs index 7cca903d..577508e6 100644 --- a/abi_stable/src/for_examples.rs +++ b/abi_stable/src/for_examples.rs @@ -7,50 +7,40 @@ use crate::{ StableAbi, }; - /// This type is used in prefix type examples. #[repr(C)] #[derive(StableAbi)] #[sabi(kind(Prefix(prefix_ref = "Module_Ref", prefix_fields = "Module_Prefix")))] -pub struct Module{ +pub struct Module { pub first: ROption, - // The `#[sabi(last_prefix_field)]` attribute here means that this is - // the last field in this struct that was defined in the + // The `#[sabi(last_prefix_field)]` attribute here means that this is + // the last field in this struct that was defined in the // first compatible version of the library, // requiring new fields to always be added after it. - // Moving this attribute is a breaking change, it can only be done in a + // Moving this attribute is a breaking change, it can only be done in a // major version bump.. #[sabi(last_prefix_field)] pub second: RStr<'static>, pub third: usize, } - impl RootModule for Module_Ref { - crate::declare_root_module_statics!{Module_Ref} + crate::declare_root_module_statics! {Module_Ref} const BASE_NAME: &'static str = "example_root_module"; const NAME: &'static str = "example_root_module"; const VERSION_STRINGS: VersionStrings = crate::package_version_strings!(); } - /// For demonstrating ffi-safe non-exhaustive enums. #[repr(u8)] // #[derive(Debug,Clone,PartialEq)] // #[sabi(debug_print)] -#[derive(StableAbi,Debug,Clone,PartialEq)] -#[sabi(kind(WithNonExhaustive( - size="[usize;10]", - traits(Debug,Clone,PartialEq), -)))] -#[sabi(with_constructor)] +#[derive(StableAbi, Debug, Clone, PartialEq)] +#[sabi(kind(WithNonExhaustive(size = "[usize;10]", traits(Debug, Clone, PartialEq),)))] +#[sabi(with_constructor)] #[non_exhaustive] -pub enum ValidTag{ +pub enum ValidTag { Foo, Bar, - Tag{ - name:RString, - tag:RString, - } + Tag { name: RString, tag: RString }, } - diff --git a/abi_stable/src/impls.rs b/abi_stable/src/impls.rs index f6fb0d7d..0aab1894 100644 --- a/abi_stable/src/impls.rs +++ b/abi_stable/src/impls.rs @@ -188,7 +188,6 @@ macro_rules! shared_impls { }; } - macro_rules! si_deref { ($self:ident) => { &**$self @@ -199,4 +198,4 @@ macro_rules! si_deref { ((method = $method:ident) $self:ident) => { $self.$method() }; -} \ No newline at end of file +} diff --git a/abi_stable/src/inline_storage.rs b/abi_stable/src/inline_storage.rs index 7127853f..50149d3a 100644 --- a/abi_stable/src/inline_storage.rs +++ b/abi_stable/src/inline_storage.rs @@ -14,8 +14,7 @@ Implementors must: - Not implement Drop,and have no drop glue. */ -pub unsafe trait InlineStorage{} - +pub unsafe trait InlineStorage {} macro_rules! impl_for_arrays { ( ty=$ty:ty , len[ $($len:expr),* $(,)* ] ) => ( @@ -25,8 +24,7 @@ macro_rules! impl_for_arrays { ) } - -impl_for_arrays!{ +impl_for_arrays! { ty=u8, len[ 0,1,2,3,4,5,6,7,8,9, @@ -39,7 +37,7 @@ impl_for_arrays!{ ] } -impl_for_arrays!{ +impl_for_arrays! { ty=u32, len[ 0,1,2,3,4,5,6,7,8,9, @@ -50,7 +48,7 @@ impl_for_arrays!{ ] } -impl_for_arrays!{ +impl_for_arrays! { ty=u64, len[ 0,1,2,3,4,5,6,7,8,9, @@ -59,7 +57,7 @@ impl_for_arrays!{ ] } -impl_for_arrays!{ +impl_for_arrays! { ty=usize, len[ 0,1,2,3,4,5,6,7,8,9, @@ -70,7 +68,6 @@ impl_for_arrays!{ ] } - macro_rules! declare_alignments { ( $(( $docs:expr, $aligner:ident, $alignment:expr ),)* @@ -80,7 +77,7 @@ macro_rules! declare_alignments { #[repr(C)] #[repr(align($alignment))] pub struct $aligner(pub Inline); - + unsafe impl InlineStorage for $aligner where Inline:InlineStorage, @@ -89,12 +86,11 @@ macro_rules! declare_alignments { ) } - /// Helper types related to the alignemnt of inline storage. -pub mod alignment{ +pub mod alignment { use super::*; - - declare_alignments!{ + + declare_alignments! { ( "Aligns its contents to an address at a multiple of 1 bytes.",AlignTo1,1 ), ( "Aligns its contents to an address at a multiple of 2 bytes.",AlignTo2,2 ), ( "Aligns its contents to an address at a multiple of 4 bytes.",AlignTo4,4 ), @@ -105,99 +101,91 @@ pub mod alignment{ ( "Aligns its contents to an address at a multiple of 128 bytes.",AlignTo128,128 ), } - /// Aligns its contents to an address to an address at + /// Aligns its contents to an address to an address at /// a multiple of the size of a pointer. #[repr(C)] #[derive(Copy, Clone)] - #[cfg_attr(target_pointer_width="128",repr(C,align(16)))] - #[cfg_attr(target_pointer_width="64",repr(C,align(8)))] - #[cfg_attr(target_pointer_width="32",repr(C,align(4)))] - #[cfg_attr(target_pointer_width="16",repr(C,align(2)))] + #[cfg_attr(target_pointer_width = "128", repr(C, align(16)))] + #[cfg_attr(target_pointer_width = "64", repr(C, align(8)))] + #[cfg_attr(target_pointer_width = "32", repr(C, align(4)))] + #[cfg_attr(target_pointer_width = "16", repr(C, align(2)))] pub struct AlignToUsize(pub Inline); - unsafe impl InlineStorage for AlignToUsize - where - Inline:InlineStorage, - {} + unsafe impl InlineStorage for AlignToUsize where Inline: InlineStorage {} } - - /////////////////////////////////////////////////////////////////////////////// /// Used internally to avoid requiring Rust 1.36.0 . #[repr(transparent)] -pub(crate) struct ScratchSpace{ +pub(crate) struct ScratchSpace { #[allow(dead_code)] - storage:std::mem::MaybeUninit, + storage: std::mem::MaybeUninit, } -impl ScratchSpace{ +impl ScratchSpace { #[inline] #[allow(dead_code)] - pub(crate) fn new(value:T)->Self + pub(crate) fn new(value: T) -> Self where - Inline:InlineStorage + Inline: InlineStorage, { Self::assert_fits_within_storage::(); - unsafe{ - Self::new_unchecked(value) - } + unsafe { Self::new_unchecked(value) } } -/** -# Safety + /** + # Safety -You must ensure that `T` has a compatible size/alignement with `Inline`, -and that `Inline` si valid for all bitpatterns. -*/ + You must ensure that `T` has a compatible size/alignement with `Inline`, + and that `Inline` si valid for all bitpatterns. + */ #[inline] #[allow(dead_code)] - pub(crate) unsafe fn new_unchecked(value:T)->Self{ - let mut this=Self::uninit_unbounded(); + pub(crate) unsafe fn new_unchecked(value: T) -> Self { + let mut this = Self::uninit_unbounded(); (&mut this as *mut Self as *mut T).write(value); this } #[inline] - pub(crate) fn uninit()->Self + pub(crate) fn uninit() -> Self where - Inline:InlineStorage + Inline: InlineStorage, { - unsafe{ - Self::uninit_unbounded() - } + unsafe { Self::uninit_unbounded() } } /// Asserts that `T` fits within `Inline`,with the correct alignment and size. - fn assert_fits_within_storage(){ - let align_val=std::mem::align_of::(); - let align_storage=std::mem::align_of::(); + fn assert_fits_within_storage() { + let align_val = std::mem::align_of::(); + let align_storage = std::mem::align_of::(); assert!( align_val <= align_storage, "The alignment of the storage is lower than the value:\n\t{} < {}", - align_storage,align_val, + align_storage, + align_val, ); - let size_val=std::mem::size_of::(); - let size_storage=std::mem::size_of::(); + let size_val = std::mem::size_of::(); + let size_storage = std::mem::size_of::(); assert!( size_val <= size_storage, "The size of the storage is smaller than the value:\n\t{} < {}", - size_storage,size_val, + size_storage, + size_val, ); } } -impl ScratchSpace{ +impl ScratchSpace { /// # Safety - /// + /// /// You must ensure that `Inline` is valid for all bitpatterns,ie:it implements `InlineStorage`. #[inline] - pub(crate) unsafe fn uninit_unbounded()->Self{ - unsafe{ - Self{ - storage:std::mem::MaybeUninit::uninit() + pub(crate) unsafe fn uninit_unbounded() -> Self { + unsafe { + Self { + storage: std::mem::MaybeUninit::uninit(), } } } } - diff --git a/abi_stable/src/internal_macros.rs b/abi_stable/src/internal_macros.rs index 688bf943..1b5891f1 100644 --- a/abi_stable/src/internal_macros.rs +++ b/abi_stable/src/internal_macros.rs @@ -10,16 +10,15 @@ macro_rules! _sabi_type_layouts { }; ( $( $ty:ty $( = $assoc_const:ident )? ,)* - ) => {{ + ) => {{ $crate::rslice![ - $( - $crate::_sabi_type_layouts!(internal; $ty $( = $assoc_const )? ), + $( + $crate::_sabi_type_layouts!(internal; $ty $( = $assoc_const )? ), )* ] }}; } - /* macro_rules! with_shared_attrs { ( @@ -77,4 +76,4 @@ macro_rules! with_shared_attrs { } }; } -*/ \ No newline at end of file +*/ diff --git a/abi_stable/src/lib.rs b/abi_stable/src/lib.rs index e59b1222..4e9d939d 100644 --- a/abi_stable/src/lib.rs +++ b/abi_stable/src/lib.rs @@ -8,13 +8,13 @@ This library allows defining Rust libraries that can be loaded at runtime, even if they were built with a different Rust version than the crate that depends on it. These are some usecases for this library: - + - Converting a Rust dependency tree from compiling statically into a single binary, into one binary (and potentially) many dynamic libraries, allowing separate re-compilation on changes. - Creating a plugin system (without support for unloading). - + # Features Currently this library has these features: @@ -66,7 +66,7 @@ These are default cargo features that enable optional crates : - "serde_json": Depends on `serde_json`, - providing ffi-safe equivalents of + providing ffi-safe equivalents of `&serde_json::value::RawValue` and `Box`, in `abi_stable::external_types::serde_json` . @@ -95,12 +95,12 @@ requires Rust Rust 1.51.0 or higher. # Glossary -`interface crate`:the crate that declares the public functions, types, and traits that +`interface crate`:the crate that declares the public functions, types, and traits that are necessary to load the library at runtime. `ìmplementation crate`:A crate that implements all the functions in the interface crate. -`user crate`:A crate that depends on an `interface crate` and +`user crate`:A crate that depends on an `interface crate` and loads 1 or more `ìmplementation crate`s for it. `module`:refers to a struct of function pointers and other static values. @@ -128,13 +128,13 @@ These are the kinds of types passed through FFI: - [Trait objects] :
Trait object-like types generated using the [`sabi_trait`] attribute macro, which erase the type of the value they wrap,implements the methods of the trait, - and can only be unwrapped back to the original type in the dynamic library/binary + and can only be unwrapped back to the original type in the dynamic library/binary that created it. - Opaque kind:
Types wrapped in [`DynTrait`], whose layout can change in any version of the library, - and can only be unwrapped back to the original type in the dynamic library/binary + and can only be unwrapped back to the original type in the dynamic library/binary that created it. - [Prefix types] :
@@ -199,7 +199,6 @@ https://github.com/rodrimati1992/abi_stable_crates/blob/master/readme.md#readme_ #![allow(non_camel_case_types)] #![deny(unused_must_use)] #![warn(rust_2018_idioms)] - #![allow(clippy::declare_interior_mutable_const)] #![allow(clippy::needless_doctest_main)] #![allow(clippy::redundant_closure_call)] @@ -211,10 +210,7 @@ https://github.com/rodrimati1992/abi_stable_crates/blob/master/readme.md#readme_ #![allow(clippy::manual_non_exhaustive)] #![allow(clippy::ptr_offset_with_cast)] #![allow(clippy::empty_loop)] - #![deny(clippy::missing_safety_doc)] - - #![cfg_attr(feature = "docsrs", feature(doc_cfg))] #[allow(unused_imports)] @@ -229,37 +225,29 @@ extern crate abi_stable_derive; extern crate self as abi_stable; - -include!{"./proc_macro_reexports/get_static_equivalent.rs"} -include!{"./proc_macro_reexports/export_root_module.rs"} -include!{"./proc_macro_reexports/sabi_extern_fn.rs"} -include!{"./proc_macro_reexports/sabi_trait_attribute.rs"} -include!{"./proc_macro_reexports/stable_abi_derive.rs"} - +include! {"./proc_macro_reexports/get_static_equivalent.rs"} +include! {"./proc_macro_reexports/export_root_module.rs"} +include! {"./proc_macro_reexports/sabi_extern_fn.rs"} +include! {"./proc_macro_reexports/sabi_trait_attribute.rs"} +include! {"./proc_macro_reexports/stable_abi_derive.rs"} #[doc(no_inline)] -pub use abi_stable::sabi_types::{RRef, RMut}; +pub use abi_stable::sabi_types::{RMut, RRef}; -use abi_stable_derive::{ - impl_InterfaceType, -}; +use abi_stable_derive::impl_InterfaceType; #[doc(hidden)] -pub use abi_stable_derive::{ - get_root_module_static, -}; +pub use abi_stable_derive::get_root_module_static; #[macro_use] mod impls; - #[macro_use] mod internal_macros; #[macro_use] mod macros; - #[cfg(test)] #[macro_use] mod test_macros; @@ -282,7 +270,6 @@ pub mod traits; pub mod for_examples; - #[macro_use] pub mod abi_stability; #[macro_use] @@ -290,15 +277,13 @@ pub mod erased_types; pub mod external_types; #[macro_use] pub mod library; +pub mod inline_storage; pub mod marker_type; mod multikey_map; pub mod nonexhaustive_enum; pub mod pointer_trait; pub mod prefix_type; pub mod type_layout; -pub mod inline_storage; - - #[doc(hidden)] pub mod derive_macro_reexports; @@ -307,9 +292,8 @@ pub mod derive_macro_reexports; #[doc(hidden)] pub use self::derive_macro_reexports as pmr; -pub mod std_types; pub mod sabi_types; - +pub mod std_types; pub mod reflection; pub mod type_level; @@ -318,30 +302,28 @@ pub mod docs; pub mod sabi_trait; - /// The header used to identify the version number of abi_stable /// that a dynamic libraries uses. -pub static LIB_HEADER:library::AbiHeader=library::AbiHeader::VALUE; - +pub static LIB_HEADER: library::AbiHeader = library::AbiHeader::VALUE; /// Miscelaneous items re-exported from core_extensions. -pub mod reexports{ - pub use core_extensions::SelfOps; - pub use core_extensions::type_level_bool::{True, False}; - pub use core_extensions::utils::transmute_ignore_size; +pub mod reexports { + pub use core_extensions::{ + type_level_bool::{False, True}, + utils::transmute_ignore_size, + SelfOps, + }; } - #[doc(hidden)] -pub const ABI_STABLE_VERSION:sabi_types::VersionStrings=package_version_strings!(); - +pub const ABI_STABLE_VERSION: sabi_types::VersionStrings = package_version_strings!(); /* I am using this static as the `identity` of this dynamic library/executable, -this assumes that private static variables don't get merged between +this assumes that private static variables don't get merged between Rust dynamic libraries that have a different global allocator. -If the address of this is the same among dynamic libraries that have *different* +If the address of this is the same among dynamic libraries that have *different* allocators,please create an issue for this. */ use std::sync::atomic::AtomicUsize; @@ -350,26 +332,18 @@ static EXECUTABLE_IDENTITY: AtomicUsize = AtomicUsize::new(1); #[doc(inline)] pub use crate::{ abi_stability::StableAbi, - erased_types::{ - dyn_trait::DynTrait, - ImplType, - InterfaceType, - }, + erased_types::{dyn_trait::DynTrait, ImplType, InterfaceType}, }; #[doc(no_inline)] pub use crate::erased_types::InterfaceBound; - - #[doc(hidden)] -pub mod globals{ +pub mod globals { use crate::{ - abi_stability::{ - abi_checking::{check_layout_compatibility_for_ffi}, - }, + abi_stability::abi_checking::check_layout_compatibility_for_ffi, sabi_types::LateStaticRef, - std_types::{RResult,RBoxError}, + std_types::{RBoxError, RResult}, type_layout::TypeLayout, utils::leak_value, }; @@ -377,39 +351,35 @@ pub mod globals{ #[repr(C)] #[derive(StableAbi)] // #[sabi(debug_print)] - pub struct Globals{ + pub struct Globals { pub layout_checking: - extern "C" fn(&'static TypeLayout,&'static TypeLayout) -> RResult<(), RBoxError> , + extern "C" fn(&'static TypeLayout, &'static TypeLayout) -> RResult<(), RBoxError>, } - impl Globals{ - pub fn new()->&'static Self{ - leak_value(Globals{ - layout_checking:check_layout_compatibility_for_ffi, + impl Globals { + pub fn new() -> &'static Self { + leak_value(Globals { + layout_checking: check_layout_compatibility_for_ffi, }) } } - pub(crate)static GLOBALS:LateStaticRef<&Globals>=LateStaticRef::new(); + pub(crate) static GLOBALS: LateStaticRef<&Globals> = LateStaticRef::new(); #[inline(never)] - pub fn initialized_globals()->&'static Globals{ - GLOBALS.init(|| Globals::new() ) + pub fn initialized_globals() -> &'static Globals { + GLOBALS.init(|| Globals::new()) } - #[inline(never)] - pub extern "C" fn initialize_globals_with(globs:&'static Globals){ - GLOBALS.init(|| globs ); + pub extern "C" fn initialize_globals_with(globs: &'static Globals) { + GLOBALS.init(|| globs); } } - #[cfg(all(test, not(feature = "testing")))] compile_error! { "tests must be run with the \"testing\" feature" } - - #[cfg(miri)] extern "Rust" { /// Miri-provided extern function to mark the block `ptr` points to as a "root" @@ -419,4 +389,3 @@ extern "Rust" { /// `ptr` has to point to the beginning of an allocated block. fn miri_static_root(ptr: *const u8); } - diff --git a/abi_stable/src/library.rs b/abi_stable/src/library.rs index 3dc0befe..cd3440ee 100644 --- a/abi_stable/src/library.rs +++ b/abi_stable/src/library.rs @@ -6,79 +6,64 @@ as well as functions/modules within. use std::{ convert::Infallible, mem, - path::{Path,PathBuf}, + path::{Path, PathBuf}, sync::atomic, }; #[allow(unused_imports)] use core_extensions::SelfOps; -use libloading::{ - Library as LibLoadingLibrary, - Symbol as LLSymbol, -}; +use libloading::{Library as LibLoadingLibrary, Symbol as LLSymbol}; pub use abi_stable_shared::mangled_root_module_loader_name; - - use crate::{ abi_stability::stable_abi_trait::StableAbi, - globals::{self,Globals}, + globals::{self, Globals}, marker_type::ErasedPrefix, prefix_type::{PrefixRef, PrefixRefTrait}, - type_layout::TypeLayout, - sabi_types::{ LateStaticRef, VersionNumber, VersionStrings }, + sabi_types::{LateStaticRef, VersionNumber, VersionStrings}, std_types::{RResult, RStr}, + type_layout::TypeLayout, }; - pub mod c_abi_testing; pub mod development_utils; -mod lib_header; mod errors; -mod root_mod_trait; +mod lib_header; mod raw_library; - +mod root_mod_trait; #[doc(no_inline)] -pub use self::c_abi_testing::{CAbiTestingFns,C_ABI_TESTING_FNS}; +pub use self::c_abi_testing::{CAbiTestingFns, C_ABI_TESTING_FNS}; pub use self::{ errors::{IntoRootModuleResult, LibraryError, RootModuleError}, lib_header::{AbiHeader, AbiHeaderRef, LibHeader}, + raw_library::RawLibrary, root_mod_trait::{ - RootModule, - lib_header_from_raw_library, - lib_header_from_path, - abi_header_from_raw_library, - abi_header_from_path, - RootModuleConsts, - ErasedRootModuleConsts, + abi_header_from_path, abi_header_from_raw_library, lib_header_from_path, + lib_header_from_raw_library, ErasedRootModuleConsts, RootModule, RootModuleConsts, }, - raw_library::RawLibrary, }; - /////////////////////////////////////////////////////////////////////////////// - /// What naming convention to expect when loading a library from a directory. -#[derive(Debug,Copy,Clone,PartialEq,Eq,Ord,PartialOrd,Hash)] -pub enum LibrarySuffix{ +#[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)] +pub enum LibrarySuffix { /// Loads a dynamic library at `/.extension` NoSuffix, - + /// Loads a dynamic library at `/-.` Suffix, } - ////////////////////////////////////////////////////////////////////// /// The path a library is loaded from. -#[derive(Debug,Copy,Clone,PartialEq,Eq,Ord,PartialOrd,Hash)] -pub enum LibraryPath<'a>{ +#[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)] +pub enum LibraryPath<'a> { /// The full path to the dynamic library. FullPath(&'a Path), /// The path to the directory that contains the dynamic library. @@ -87,26 +72,23 @@ pub enum LibraryPath<'a>{ ////////////////////////////////////////////////////////////////////// - /// Whether the ABI of a root module is checked. #[repr(u8)] -#[derive(Debug,Copy,Clone,StableAbi)] -pub enum IsLayoutChecked{ +#[derive(Debug, Copy, Clone, StableAbi)] +pub enum IsLayoutChecked { Yes(&'static TypeLayout), - No + No, } - -impl IsLayoutChecked{ - pub fn into_option(self)->Option<&'static TypeLayout>{ +impl IsLayoutChecked { + pub fn into_option(self) -> Option<&'static TypeLayout> { match self { - IsLayoutChecked::Yes(x)=>Some(x), - IsLayoutChecked::No =>None, + IsLayoutChecked::Yes(x) => Some(x), + IsLayoutChecked::No => None, } } } - ////////////////////////////////////////////////////////////////////// /// The return type of the function that the @@ -115,42 +97,40 @@ pub type RootModuleResult = RResult, RootModuleError>; ////////////////////////////////////////////////////////////////////// - /// The static variables declared for some [`RootModule`] implementor. /// [`RootModule`]: ./trait.RootModule.html #[doc(hidden)] -pub struct RootModuleStatics{ - root_mod:LateStaticRef, - raw_lib:LateStaticRef<&'static RawLibrary>, +pub struct RootModuleStatics { + root_mod: LateStaticRef, + raw_lib: LateStaticRef<&'static RawLibrary>, } -impl RootModuleStatics{ +impl RootModuleStatics { #[doc(hidden)] #[inline] - pub const fn _private_new()->Self{ - Self{ - root_mod:LateStaticRef::new(), - raw_lib:LateStaticRef::new(), + pub const fn _private_new() -> Self { + Self { + root_mod: LateStaticRef::new(), + raw_lib: LateStaticRef::new(), } } } - /// Implements the [`RootModule::root_module_statics`] associated function. /// /// To define the associated function use: /// `abi_stable::declare_root_module_statics!{TypeOfSelf}`. /// Passing `Self` instead of `TypeOfSelf` won't work. -/// +/// /// # Example -/// +/// /// ```rust /// use abi_stable::{ /// library::RootModule, /// sabi_types::VersionStrings, /// StableAbi, /// }; -/// +/// /// #[repr(C)] /// #[derive(StableAbi)] /// #[sabi(kind(Prefix(prefix_ref = "Module_Ref", prefix_fields = "Module_Prefix")))] @@ -166,11 +146,13 @@ impl RootModuleStatics{ /// const NAME: &'static str = "example_root_module"; /// const VERSION_STRINGS: VersionStrings = abi_stable::package_version_strings!(); /// } -/// +/// /// # fn main(){} /// ``` -/// -#[cfg_attr(doctest, doc = r###" +/// +#[cfg_attr( + doctest, + doc = r###" ```rust struct Foo; @@ -207,7 +189,8 @@ impl Foo { } ``` -"###)] +"### +)] /// [`RootModule::root_module_statics`]: /// ./library/trait.RootModule.html#tymethod.root_module_statics #[macro_export] @@ -231,25 +214,19 @@ macro_rules! declare_root_module_statics { ////////////////////////////////////////////////////////////////////// - #[doc(hidden)] -pub fn __call_root_module_loader(function: fn()->T ) -> RootModuleResult +pub fn __call_root_module_loader(function: fn() -> T) -> RootModuleResult where - T: IntoRootModuleResult + T: IntoRootModuleResult, { type TheResult = Result, RootModuleError>; - let res = ::std::panic::catch_unwind(||-> TheResult { + let res = ::std::panic::catch_unwind(|| -> TheResult { let ret: T::Module = function().into_root_module_result()?; - let _= ::load_module_with(|| Ok::<_,Infallible>(ret) ); - unsafe{ - ret.to_prefix_ref() - .cast::() - .piped(Ok) - } + let _ = ::load_module_with(|| Ok::<_, Infallible>(ret)); + unsafe { ret.to_prefix_ref().cast::().piped(Ok) } }); // We turn an unwinding panic into an error value let flattened: TheResult = res.unwrap_or(Err(RootModuleError::Unwound)); RootModuleResult::from(flattened) } - diff --git a/abi_stable/src/library/c_abi_testing.rs b/abi_stable/src/library/c_abi_testing.rs index cf2ab8cb..cd991b41 100644 --- a/abi_stable/src/library/c_abi_testing.rs +++ b/abi_stable/src/library/c_abi_testing.rs @@ -3,8 +3,8 @@ This module runs tests on the C abi as defined by Rust, to detect whether Rust changed how it deals with zero-sized types. */ -use crate::std_types::{RBoxError,Tuple2,Tuple3}; use super::LibraryError; +use crate::std_types::{RBoxError, Tuple2, Tuple3}; // Types used in tests from this module mod types; @@ -14,14 +14,13 @@ mod functions; #[macro_use] mod c_abi_testing_macros; -use self::types::{MyUnit}; +use self::types::MyUnit; -pub use self::functions::{C_ABI_TESTING_FNS,CAbiTestingFns}; +pub use self::functions::{CAbiTestingFns, C_ABI_TESTING_FNS}; - -/// Tests that the abi (as defined by the compiler) of the functions in +/// Tests that the abi (as defined by the compiler) of the functions in /// CAbiTestingFns is the same as the caller's. -pub fn run_tests(funcs:&CAbiTestingFns)->Result<(),LibraryError>{ +pub fn run_tests(funcs: &CAbiTestingFns) -> Result<(), LibraryError> { pair_tests(&funcs)?; triple_tests(&funcs)?; two_pair_tests(&funcs)?; @@ -29,46 +28,129 @@ pub fn run_tests(funcs:&CAbiTestingFns)->Result<(),LibraryError>{ Ok(()) } -fn make_invalid_cabi_err(expected:T,found:T)->LibraryError +fn make_invalid_cabi_err(expected: T, found: T) -> LibraryError where - T:std::fmt::Debug + T: std::fmt::Debug, { - LibraryError::InvalidCAbi{ - expected:RBoxError::from_debug(&expected), - found :RBoxError::from_debug(&found ), + LibraryError::InvalidCAbi { + expected: RBoxError::from_debug(&expected), + found: RBoxError::from_debug(&found), } } +fn pair_tests(funcs: &CAbiTestingFns) -> Result<(), LibraryError> { + check_roundtrip!(funcs, 0x1, (a = Tuple2(1, ())), ret_pair_a, take_pair_a); + check_roundtrip!(funcs, 0x5, (a = Tuple2(5, ())), ret_pair_a, take_pair_a); -fn pair_tests(funcs:&CAbiTestingFns)->Result<(),LibraryError>{ - check_roundtrip!(funcs,0x1,( a=Tuple2(1,()) ),ret_pair_a,take_pair_a); - check_roundtrip!(funcs,0x5,( a=Tuple2(5,()) ),ret_pair_a,take_pair_a); - - check_roundtrip!(funcs,0x1_0000,( a=Tuple2((),1) ),ret_pair_b,take_pair_b); - check_roundtrip!(funcs,0x5_0000,( a=Tuple2((),5) ),ret_pair_b,take_pair_b); + check_roundtrip!( + funcs, + 0x1_0000, + (a = Tuple2((), 1)), + ret_pair_b, + take_pair_b + ); + check_roundtrip!( + funcs, + 0x5_0000, + (a = Tuple2((), 5)), + ret_pair_b, + take_pair_b + ); Ok(()) } -fn triple_tests(funcs:&CAbiTestingFns)->Result<(),LibraryError>{ - check_roundtrip!(funcs,0x1_0001_0000,( a=Tuple3((),1,1) ),ret_triple_a,take_triple_a); - check_roundtrip!(funcs,0x1_0005_0000,( a=Tuple3((),5,1) ),ret_triple_a,take_triple_a); - check_roundtrip!(funcs,0x7_0001_0000,( a=Tuple3((),1,7) ),ret_triple_a,take_triple_a); - check_roundtrip!(funcs,0x7_0003_0000,( a=Tuple3((),3,7) ),ret_triple_a,take_triple_a); - - check_roundtrip!(funcs,0x1_0000_0001,( a=Tuple3(1,(),1) ),ret_triple_b,take_triple_b); - check_roundtrip!(funcs,0x1_0000_0005,( a=Tuple3(5,(),1) ),ret_triple_b,take_triple_b); - check_roundtrip!(funcs,0x7_0000_0001,( a=Tuple3(1,(),7) ),ret_triple_b,take_triple_b); - check_roundtrip!(funcs,0x7_0000_0003,( a=Tuple3(3,(),7) ),ret_triple_b,take_triple_b); - - check_roundtrip!(funcs,0x1_0001,( a=Tuple3(1,1,()) ),ret_triple_c,take_triple_c); - check_roundtrip!(funcs,0x1_0005,( a=Tuple3(5,1,()) ),ret_triple_c,take_triple_c); - check_roundtrip!(funcs,0x7_0001,( a=Tuple3(1,7,()) ),ret_triple_c,take_triple_c); - check_roundtrip!(funcs,0x7_0003,( a=Tuple3(3,7,()) ),ret_triple_c,take_triple_c); +fn triple_tests(funcs: &CAbiTestingFns) -> Result<(), LibraryError> { + check_roundtrip!( + funcs, + 0x1_0001_0000, + (a = Tuple3((), 1, 1)), + ret_triple_a, + take_triple_a + ); + check_roundtrip!( + funcs, + 0x1_0005_0000, + (a = Tuple3((), 5, 1)), + ret_triple_a, + take_triple_a + ); + check_roundtrip!( + funcs, + 0x7_0001_0000, + (a = Tuple3((), 1, 7)), + ret_triple_a, + take_triple_a + ); + check_roundtrip!( + funcs, + 0x7_0003_0000, + (a = Tuple3((), 3, 7)), + ret_triple_a, + take_triple_a + ); + + check_roundtrip!( + funcs, + 0x1_0000_0001, + (a = Tuple3(1, (), 1)), + ret_triple_b, + take_triple_b + ); + check_roundtrip!( + funcs, + 0x1_0000_0005, + (a = Tuple3(5, (), 1)), + ret_triple_b, + take_triple_b + ); + check_roundtrip!( + funcs, + 0x7_0000_0001, + (a = Tuple3(1, (), 7)), + ret_triple_b, + take_triple_b + ); + check_roundtrip!( + funcs, + 0x7_0000_0003, + (a = Tuple3(3, (), 7)), + ret_triple_b, + take_triple_b + ); + + check_roundtrip!( + funcs, + 0x1_0001, + (a = Tuple3(1, 1, ())), + ret_triple_c, + take_triple_c + ); + check_roundtrip!( + funcs, + 0x1_0005, + (a = Tuple3(5, 1, ())), + ret_triple_c, + take_triple_c + ); + check_roundtrip!( + funcs, + 0x7_0001, + (a = Tuple3(1, 7, ())), + ret_triple_c, + take_triple_c + ); + check_roundtrip!( + funcs, + 0x7_0003, + (a = Tuple3(3, 7, ())), + ret_triple_c, + take_triple_c + ); Ok(()) } -fn two_pair_tests(funcs:&CAbiTestingFns)->Result<(),LibraryError>{ - let funcs=anon_struct!{ +fn two_pair_tests(funcs: &CAbiTestingFns) -> Result<(), LibraryError> { + let funcs = anon_struct! { ret_2_pairs_a:|n|(funcs.ret_2_pairs_a)(n).into_tuple(), ret_2_pairs_b:|n|(funcs.ret_2_pairs_b)(n).into_tuple(), take_2_pairs_a:funcs.take_2_pairs_a, @@ -78,14 +160,14 @@ fn two_pair_tests(funcs:&CAbiTestingFns)->Result<(),LibraryError>{ check_roundtrip!( funcs, 0x1_0000_0005_0000, - ( a=Tuple2((),5),b=Tuple2((),1) ), + (a = Tuple2((), 5), b = Tuple2((), 1)), ret_2_pairs_a, take_2_pairs_a, ); check_roundtrip!( funcs, 0xF_0000_000A_0000, - ( a=Tuple2((),10),b=Tuple2((),15) ), + (a = Tuple2((), 10), b = Tuple2((), 15)), ret_2_pairs_a, take_2_pairs_a, ); @@ -93,32 +175,31 @@ fn two_pair_tests(funcs:&CAbiTestingFns)->Result<(),LibraryError>{ check_roundtrip!( funcs, 0x0_0007_0000_0003, - ( a=Tuple2(3,()),b=Tuple2(7,()) ), + (a = Tuple2(3, ()), b = Tuple2(7, ())), ret_2_pairs_b, take_2_pairs_b, ); check_roundtrip!( funcs, 0x0_0002_0000_000B, - ( a=Tuple2(11,()),b=Tuple2(2,()) ), + (a = Tuple2(11, ()), b = Tuple2(2, ())), ret_2_pairs_b, take_2_pairs_b, ); Ok(()) } - -fn mixed_units_test(funcs:&CAbiTestingFns)->Result<(),LibraryError>{ - let single_test=|n:u64|{ - let a=n as u16; - let b=(n>>16) as u16; - let c=(n>>32) as u16; - let d=(n>>48) as u16; - - let res=(funcs.mixed_units)(a,MyUnit,b,MyUnit,c,MyUnit,d); - if res!=n { - Err(make_invalid_cabi_err(n,res)) - }else{ +fn mixed_units_test(funcs: &CAbiTestingFns) -> Result<(), LibraryError> { + let single_test = |n: u64| { + let a = n as u16; + let b = (n >> 16) as u16; + let c = (n >> 32) as u16; + let d = (n >> 48) as u16; + + let res = (funcs.mixed_units)(a, MyUnit, b, MyUnit, c, MyUnit, d); + if res != n { + Err(make_invalid_cabi_err(n, res)) + } else { Ok(()) } }; diff --git a/abi_stable/src/library/c_abi_testing/c_abi_testing_macros.rs b/abi_stable/src/library/c_abi_testing/c_abi_testing_macros.rs index 9c768128..e7770557 100644 --- a/abi_stable/src/library/c_abi_testing/c_abi_testing_macros.rs +++ b/abi_stable/src/library/c_abi_testing/c_abi_testing_macros.rs @@ -28,7 +28,7 @@ macro_rules! check_roundtrip { } macro_rules! anon_struct { - ( + ( $($fname:ident : $fval:expr),* $(,)* ) => {{ diff --git a/abi_stable/src/library/c_abi_testing/functions.rs b/abi_stable/src/library/c_abi_testing/functions.rs index 6f9ffb05..ba04f0aa 100644 --- a/abi_stable/src/library/c_abi_testing/functions.rs +++ b/abi_stable/src/library/c_abi_testing/functions.rs @@ -5,32 +5,31 @@ use super::*; /// Functions used to test that the C abi is the same in both the library and the loader. #[repr(C)] #[derive(StableAbi)] -pub struct CAbiTestingFns{ - pub(crate) take_pair_a:extern "C" fn(Tuple2)->u32, - pub(crate) take_pair_b:extern "C" fn(Tuple2<(),u16>)->u32, - pub(crate) ret_pair_a:extern "C" fn(u32)->Tuple2, - pub(crate) ret_pair_b:extern "C" fn(u32)->Tuple2<(),u16>, - - pub(crate) take_triple_a:extern "C" fn(Tuple3<(),u16,u16>)->u64, - pub(crate) take_triple_b:extern "C" fn(Tuple3)->u64, - pub(crate) take_triple_c:extern "C" fn(Tuple3)->u64, - pub(crate) ret_triple_a:extern "C" fn(u64)->Tuple3<(),u16,u16>, - pub(crate) ret_triple_b:extern "C" fn(u64)->Tuple3, - pub(crate) ret_triple_c:extern "C" fn(u64)->Tuple3, - - pub(crate) take_2_pairs_a:extern "C" fn(Tuple2<(),u16>,Tuple2<(),u16>)->u64, - pub(crate) take_2_pairs_b:extern "C" fn(Tuple2,Tuple2)->u64, - pub(crate) ret_2_pairs_a:extern "C" fn(u64)->Tuple2,Tuple2<(),u16>>, - pub(crate) ret_2_pairs_b:extern "C" fn(u64)->Tuple2,Tuple2>, +pub struct CAbiTestingFns { + pub(crate) take_pair_a: extern "C" fn(Tuple2) -> u32, + pub(crate) take_pair_b: extern "C" fn(Tuple2<(), u16>) -> u32, + pub(crate) ret_pair_a: extern "C" fn(u32) -> Tuple2, + pub(crate) ret_pair_b: extern "C" fn(u32) -> Tuple2<(), u16>, - pub(crate) mixed_units:extern "C" fn(u16,MyUnit,u16,MyUnit,u16,MyUnit,u16)->u64, - + pub(crate) take_triple_a: extern "C" fn(Tuple3<(), u16, u16>) -> u64, + pub(crate) take_triple_b: extern "C" fn(Tuple3) -> u64, + pub(crate) take_triple_c: extern "C" fn(Tuple3) -> u64, + pub(crate) ret_triple_a: extern "C" fn(u64) -> Tuple3<(), u16, u16>, + pub(crate) ret_triple_b: extern "C" fn(u64) -> Tuple3, + pub(crate) ret_triple_c: extern "C" fn(u64) -> Tuple3, + + pub(crate) take_2_pairs_a: extern "C" fn(Tuple2<(), u16>, Tuple2<(), u16>) -> u64, + pub(crate) take_2_pairs_b: extern "C" fn(Tuple2, Tuple2) -> u64, + pub(crate) ret_2_pairs_a: extern "C" fn(u64) -> Tuple2, Tuple2<(), u16>>, + pub(crate) ret_2_pairs_b: extern "C" fn(u64) -> Tuple2, Tuple2>, + + pub(crate) mixed_units: extern "C" fn(u16, MyUnit, u16, MyUnit, u16, MyUnit, u16) -> u64, } ///////////////////////////////////// /// Functions used to test that the C abi is the same in both the library and the loader. -pub const C_ABI_TESTING_FNS:&CAbiTestingFns=&CAbiTestingFns{ +pub const C_ABI_TESTING_FNS: &CAbiTestingFns = &CAbiTestingFns { take_pair_a, take_pair_b, ret_pair_a, @@ -48,89 +47,59 @@ pub const C_ABI_TESTING_FNS:&CAbiTestingFns=&CAbiTestingFns{ mixed_units, }; - -pub(crate) extern "C" fn take_pair_a(pair:Tuple2)->u32{ +pub(crate) extern "C" fn take_pair_a(pair: Tuple2) -> u32 { pair.0 as u32 } -pub(crate) extern "C" fn take_pair_b(pair:Tuple2<(),u16>)->u32{ - (pair.1 as u32)<<16 +pub(crate) extern "C" fn take_pair_b(pair: Tuple2<(), u16>) -> u32 { + (pair.1 as u32) << 16 } -pub(crate) extern "C" fn ret_pair_a(n:u32)->Tuple2{ - Tuple2(n as u16,()) +pub(crate) extern "C" fn ret_pair_a(n: u32) -> Tuple2 { + Tuple2(n as u16, ()) } -pub(crate) extern "C" fn ret_pair_b(n:u32)->Tuple2<(),u16>{ - Tuple2((),(n>>16)as u16) +pub(crate) extern "C" fn ret_pair_b(n: u32) -> Tuple2<(), u16> { + Tuple2((), (n >> 16) as u16) } - -pub(crate) extern "C" fn take_triple_a(triple:Tuple3<(),u16,u16>)->u64{ - ((triple.1 as u64)<<16)+ - ((triple.2 as u64)<<32) -} -pub(crate) extern "C" fn take_triple_b(triple:Tuple3)->u64{ - (triple.0 as u64)+ - ((triple.2 as u64)<<32) -} -pub(crate) extern "C" fn take_triple_c(triple:Tuple3)->u64{ - (triple.0 as u64)+ - ((triple.1 as u64)<<16) -} -pub(crate) extern "C" fn ret_triple_a(n:u64)->Tuple3<(),u16,u16>{ - Tuple3( - (), - (n>>16) as u16, - (n>>32) as u16, - ) -} -pub(crate) extern "C" fn ret_triple_b(n:u64)->Tuple3{ - Tuple3( - n as u16, - (), - (n>>32) as u16, - ) -} -pub(crate) extern "C" fn ret_triple_c(n:u64)->Tuple3{ - Tuple3( - n as u16, - (n>>16) as u16, - (), - ) +pub(crate) extern "C" fn take_triple_a(triple: Tuple3<(), u16, u16>) -> u64 { + ((triple.1 as u64) << 16) + ((triple.2 as u64) << 32) } - - -pub(crate) extern "C" fn take_2_pairs_a(a:Tuple2<(),u16>,b:Tuple2<(),u16>)->u64{ - ((a.1 as u64)<<16)+ - ((b.1 as u64)<<48) -} -pub(crate) extern "C" fn take_2_pairs_b(a:Tuple2,b:Tuple2)->u64{ - (a.0 as u64)+ - ((b.0 as u64)<<32) -} -pub(crate) extern "C" fn ret_2_pairs_a(n:u64)->Tuple2,Tuple2<(),u16>>{ - Tuple2( - Tuple2((),(n>>16)as u16), - Tuple2((),(n>>48)as u16), - ) -} -pub(crate) extern "C" fn ret_2_pairs_b(n:u64)->Tuple2,Tuple2>{ - Tuple2( - Tuple2(n as u16,()), - Tuple2((n>>32)as u16,()), - ) +pub(crate) extern "C" fn take_triple_b(triple: Tuple3) -> u64 { + (triple.0 as u64) + ((triple.2 as u64) << 32) +} +pub(crate) extern "C" fn take_triple_c(triple: Tuple3) -> u64 { + (triple.0 as u64) + ((triple.1 as u64) << 16) +} +pub(crate) extern "C" fn ret_triple_a(n: u64) -> Tuple3<(), u16, u16> { + Tuple3((), (n >> 16) as u16, (n >> 32) as u16) +} +pub(crate) extern "C" fn ret_triple_b(n: u64) -> Tuple3 { + Tuple3(n as u16, (), (n >> 32) as u16) +} +pub(crate) extern "C" fn ret_triple_c(n: u64) -> Tuple3 { + Tuple3(n as u16, (n >> 16) as u16, ()) } +pub(crate) extern "C" fn take_2_pairs_a(a: Tuple2<(), u16>, b: Tuple2<(), u16>) -> u64 { + ((a.1 as u64) << 16) + ((b.1 as u64) << 48) +} +pub(crate) extern "C" fn take_2_pairs_b(a: Tuple2, b: Tuple2) -> u64 { + (a.0 as u64) + ((b.0 as u64) << 32) +} +pub(crate) extern "C" fn ret_2_pairs_a(n: u64) -> Tuple2, Tuple2<(), u16>> { + Tuple2(Tuple2((), (n >> 16) as u16), Tuple2((), (n >> 48) as u16)) +} +pub(crate) extern "C" fn ret_2_pairs_b(n: u64) -> Tuple2, Tuple2> { + Tuple2(Tuple2(n as u16, ()), Tuple2((n >> 32) as u16, ())) +} pub(crate) extern "C" fn mixed_units( - a:u16, - _:MyUnit, - b:u16, - _:MyUnit, - c:u16, - _:MyUnit, - d:u16, -)->u64{ - (a as u64)| - ((b as u64)<<16)| - ((c as u64)<<32)| - ((d as u64)<<48) + a: u16, + _: MyUnit, + b: u16, + _: MyUnit, + c: u16, + _: MyUnit, + d: u16, +) -> u64 { + (a as u64) | ((b as u64) << 16) | ((c as u64) << 32) | ((d as u64) << 48) } diff --git a/abi_stable/src/library/c_abi_testing/types.rs b/abi_stable/src/library/c_abi_testing/types.rs index f2787fd5..37720ded 100644 --- a/abi_stable/src/library/c_abi_testing/types.rs +++ b/abi_stable/src/library/c_abi_testing/types.rs @@ -1,4 +1,3 @@ - -#[derive(Debug,StableAbi,Copy,Clone)] +#[derive(Debug, StableAbi, Copy, Clone)] #[repr(C)] -pub(crate) struct MyUnit; \ No newline at end of file +pub(crate) struct MyUnit; diff --git a/abi_stable/src/library/development_utils.rs b/abi_stable/src/library/development_utils.rs index 8bf18654..c23572b0 100644 --- a/abi_stable/src/library/development_utils.rs +++ b/abi_stable/src/library/development_utils.rs @@ -1,31 +1,31 @@ //! Utilities for use while developing dynamic libraries. use std::{ - path::{Path,PathBuf}, io, + path::{Path, PathBuf}, }; use crate::library::RootModule; /// Returns the path in the target directory /// to the last version of an implementation crate's dynamic library. -/// +/// /// The path can be in either the "debug" or "release" subdirectories. -pub fn compute_library_path(target_path: &Path)->io::Result{ - let debug_dir =target_path.join("debug/" ); - let release_dir=target_path.join("release/"); +pub fn compute_library_path(target_path: &Path) -> io::Result { + let debug_dir = target_path.join("debug/"); + let release_dir = target_path.join("release/"); - let debug_path =M::get_library_path(&debug_dir); - let release_path=M::get_library_path(&release_dir); + let debug_path = M::get_library_path(&debug_dir); + let release_path = M::get_library_path(&release_dir); - Ok(match (debug_path.exists(),release_path.exists()) { - (false,false)=>debug_dir, - (true,false)=>debug_dir, - (false,true)=>release_dir, - (true,true)=>{ + Ok(match (debug_path.exists(), release_path.exists()) { + (false, false) => debug_dir, + (true, false) => debug_dir, + (false, true) => release_dir, + (true, true) => { if debug_path.metadata()?.modified()? < release_path.metadata()?.modified()? { release_dir - }else{ + } else { debug_dir } } diff --git a/abi_stable/src/library/errors.rs b/abi_stable/src/library/errors.rs index 4622f987..d3d4c274 100644 --- a/abi_stable/src/library/errors.rs +++ b/abi_stable/src/library/errors.rs @@ -1,7 +1,4 @@ -use super::{ - lib_header::AbiHeader, - root_mod_trait::RootModule, -}; +use super::{lib_header::AbiHeader, root_mod_trait::RootModule}; use crate::{ sabi_types::{ParseVersionError, VersionNumber, VersionStrings}, @@ -16,21 +13,20 @@ use std::{ #[allow(unused_imports)] use core_extensions::SelfOps; - /// All the possible errors that could happen when loading a library, /// or a module. #[derive(Debug)] pub enum LibraryError { /// When a library can't be loaded, because it doesn't exist. - OpenError{ - path:PathBuf, + OpenError { + path: PathBuf, err: Box, }, /// When a function/static does not exist. - GetSymbolError{ - library:PathBuf, + GetSymbolError { + library: PathBuf, /// The name of the function/static.Does not have to be utf-8. - symbol:Vec, + symbol: Vec, err: Box, }, /// The version string could not be parsed into a version number. @@ -41,7 +37,7 @@ pub enum LibraryError { expected_version: VersionNumber, actual_version: VersionNumber, }, - RootModule{ + RootModule { err: RootModuleError, module_name: &'static str, version: VersionStrings, @@ -54,9 +50,9 @@ pub enum LibraryError { /// is not the same. InvalidAbiHeader(AbiHeader), /// When Rust changes how it implements the C abi, - InvalidCAbi{ - expected:RBoxError, - found:RBoxError, + InvalidCAbi { + expected: RBoxError, + found: RBoxError, }, /// There could have been 0 or more errors in the function. Many(RVec), @@ -72,12 +68,17 @@ impl Display for LibraryError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("\n")?; match self { - LibraryError::OpenError{path,err} => writeln!( + LibraryError::OpenError { path, err } => writeln!( f, "Could not open library at:\n\t{}\nbecause:\n\t{}", - path.display(),err + path.display(), + err ), - LibraryError::GetSymbolError{library,symbol,err} => writeln!( + LibraryError::GetSymbolError { + library, + symbol, + err, + } => writeln!( f, "Could load symbol:\n\t{}\nin library:\n\t{}\nbecause:\n\t{}", String::from_utf8_lossy(symbol), @@ -94,21 +95,30 @@ impl Display for LibraryError { "\n'{}' library version mismatch:\nuser:{}\nlibrary:{}", library_name, expected_version, actual_version, ), - LibraryError::RootModule{err,module_name,version} => { - writeln!(f, "An error ocurred while loading this library:\t\n{}", module_name)?; + LibraryError::RootModule { + err, + module_name, + version, + } => { + writeln!( + f, + "An error ocurred while loading this library:\t\n{}", + module_name + )?; writeln!(f, "version:\n\t{}", version)?; f.write_str("the error:\n\n")?; fmt::Display::fmt(err, f) - }, + } LibraryError::AbiInstability(x) => fmt::Display::fmt(x, f), LibraryError::InvalidAbiHeader(found) => write!( f, "The abi of the library was:\n{:#?}\n\ When this library expected:\n{:#?}", - found, AbiHeader::VALUE, + found, + AbiHeader::VALUE, ), - LibraryError::InvalidCAbi{expected,found}=>{ - write!{ + LibraryError::InvalidCAbi { expected, found } => { + write! { f, "The C abi of the library is different than expected:\n\ While running tests on the library:\n\ @@ -118,10 +128,10 @@ impl Display for LibraryError { found=found, expected=expected, } - }, - LibraryError::Many(list)=>{ + } + LibraryError::Many(list) => { for e in list { - Display::fmt(e,f)?; + Display::fmt(e, f)?; } Ok(()) } @@ -133,34 +143,32 @@ impl Display for LibraryError { impl ::std::error::Error for LibraryError {} - ////////////////////////////////////////////////////////////////////// - /// The errors that a `#[export_root_module]` function can return. #[repr(u8)] #[derive(Debug, StableAbi)] -pub enum RootModuleError{ +pub enum RootModuleError { Returned(RBoxError), Unwound, } -impl RootModuleError{ +impl RootModuleError { /// Reallocates the error using the current global allocator, /// to ensure that there is no pointer into the dynamic library. - pub fn reallocate(&mut self){ + pub fn reallocate(&mut self) { match self { - Self::Returned(e)=>{ + Self::Returned(e) => { *e = e.to_formatted_error(); - }, - Self::Unwound=>{} + } + Self::Unwound => {} } } /// Converts this `RootModuleError` into a `LibraryError`, /// with metadata about the module that failed to load. pub fn into_library_error(self) -> LibraryError { - LibraryError::RootModule{ + LibraryError::RootModule { err: self, module_name: M::NAME, version: M::VERSION_STRINGS, @@ -168,12 +176,12 @@ impl RootModuleError{ } } -impl Display for RootModuleError{ +impl Display for RootModuleError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("\n")?; match self { - Self::Returned(e)=>Display::fmt(e, f)?, - Self::Unwound=>f.write_str("the root module loader panicked")?, + Self::Returned(e) => Display::fmt(e, f)?, + Self::Unwound => f.write_str("the root module loader panicked")?, } f.write_str("\n")?; Ok(()) @@ -182,23 +190,21 @@ impl Display for RootModuleError{ impl ::std::error::Error for RootModuleError {} - ////////////////////////////////////////////////////////////////////// - /// For converting the return value of a `#[export_root_module]` function /// to a `Result<(), RootModuleError>`. pub trait IntoRootModuleResult { /// The module that is loaded in the success case. type Module: RootModule; - + /// Performs the conversion fn into_root_module_result(self) -> Result; } impl IntoRootModuleResult for Result { type Module = M; - + fn into_root_module_result(self) -> Result { self.map_err(RootModuleError::Returned) } @@ -206,10 +212,9 @@ impl IntoRootModuleResult for Result { impl IntoRootModuleResult for RResult { type Module = M; - + fn into_root_module_result(self) -> Result { - self.into_result() - .map_err(RootModuleError::Returned) + self.into_result().map_err(RootModuleError::Returned) } } @@ -221,24 +226,26 @@ impl IntoRootModuleResult for M { } } - #[cfg(test)] -mod tests{ +mod tests { use super::*; use crate::{ for_examples::{Module, Module_Ref}, prefix_type::{PrefixTypeTrait, WithMetadata}, - std_types::{RBox, RSome, RErr, ROk}, + std_types::{RBox, RErr, ROk, RSome}, }; use std::fmt::Error as FmtError; - const MOD_WM: &WithMetadata = &WithMetadata::new(PrefixTypeTrait::METADATA, Module { - first: RSome(5), - second: rstr!(""), - third: 13, - }); + const MOD_WM: &WithMetadata = &WithMetadata::new( + PrefixTypeTrait::METADATA, + Module { + first: RSome(5), + second: rstr!(""), + third: 13, + }, + ); // `const PREFIX` can have different address every time it's used, // to fix that I made it a static @@ -248,7 +255,7 @@ mod tests{ fn into_root_module_result_test() { type Res = Result; type RRes = RResult; - + { assert_eq!( PREFIX.into_root_module_result().unwrap().0.to_raw_ptr() as usize, @@ -259,12 +266,15 @@ mod tests{ fn test_case( ok: Result, err: Result, - ){ - assert_eq!(ok.unwrap().0.to_raw_ptr() as usize, PREFIX.0.to_raw_ptr() as usize); + ) { + assert_eq!( + ok.unwrap().0.to_raw_ptr() as usize, + PREFIX.0.to_raw_ptr() as usize + ); let downcasted = match err.err().unwrap() { - RootModuleError::Returned(x)=>x.downcast::().unwrap(), - RootModuleError::Unwound=>unreachable!(), + RootModuleError::Returned(x) => x.downcast::().unwrap(), + RootModuleError::Unwound => unreachable!(), }; assert_eq!(downcasted, RBox::new(FmtError)); } @@ -283,7 +293,6 @@ mod tests{ let err: RRes = RErr(RBoxError::new(FmtError)); test_case(ok.into_root_module_result(), err.into_root_module_result()); - } } -} \ No newline at end of file +} diff --git a/abi_stable/src/library/lib_header.rs b/abi_stable/src/library/lib_header.rs index a035ff3f..a5fadb8b 100644 --- a/abi_stable/src/library/lib_header.rs +++ b/abi_stable/src/library/lib_header.rs @@ -7,92 +7,90 @@ use crate::{ /// Used to check the layout of modules returned by module-loading functions /// exported by dynamic libraries. -/// +/// /// Module-loading functions are declared with the [`export_root_module`] attribute. /// /// [`export_root_module`]: ../attr.export_root_module.html #[repr(C)] #[derive(StableAbi)] pub struct LibHeader { - header:AbiHeader, - root_mod_consts:ErasedRootModuleConsts, - init_globals_with:InitGlobalsWith, - module:LateStaticRef>, - constructor:Constructor, + header: AbiHeader, + root_mod_consts: ErasedRootModuleConsts, + init_globals_with: InitGlobalsWith, + module: LateStaticRef>, + constructor: Constructor, } impl LibHeader { /// Constructs a LibHeader from the root module loader. - /// + /// /// # Safety - /// - /// The `PrefixRef` returned by the function that + /// + /// The `PrefixRef` returned by the function that /// `constructor ` wraps must be have been transmuted from a `PrefixRef`. pub const unsafe fn from_constructor( - constructor:Constructor, - root_mod_consts:RootModuleConsts, + constructor: Constructor, + root_mod_consts: RootModuleConsts, ) -> Self { Self { - header:AbiHeader::VALUE, - root_mod_consts:root_mod_consts.erased(), + header: AbiHeader::VALUE, + root_mod_consts: root_mod_consts.erased(), init_globals_with: INIT_GLOBALS_WITH, - module:LateStaticRef::new(), + module: LateStaticRef::new(), constructor, } } /// Constructs a LibHeader from the module. - pub fn from_module(value:T)->Self + pub fn from_module(value: T) -> Self where T: RootModule, { Self { - header:AbiHeader::VALUE, + header: AbiHeader::VALUE, root_mod_consts: T::CONSTANTS.erased(), init_globals_with: INIT_GLOBALS_WITH, module: { - let erased = unsafe{ value.to_prefix_ref().cast::() }; + let erased = unsafe { value.to_prefix_ref().cast::() }; LateStaticRef::from_prefixref(PrefixRefTrait::PREFIX_FIELDS, erased) }, - constructor:GetAbortingConstructor::ABORTING_CONSTRUCTOR, + constructor: GetAbortingConstructor::ABORTING_CONSTRUCTOR, } } /// All the important constants of a `RootModule` for some erased type. - pub fn root_mod_consts(&self)->&ErasedRootModuleConsts{ + pub fn root_mod_consts(&self) -> &ErasedRootModuleConsts { &self.root_mod_consts } /// The version string of the library the module is being loaded from. - pub fn version_strings(&self)->VersionStrings{ + pub fn version_strings(&self) -> VersionStrings { self.root_mod_consts.version_strings() } /// Gets the layout of the root module. /// /// This returns a None if the root module layout is not included - /// because the `#[unsafe_no_layout_constant]` + /// because the `#[unsafe_no_layout_constant]` /// helper attribute was used on the function exporting the root module. - pub fn layout(&self)->Option<&'static TypeLayout>{ + pub fn layout(&self) -> Option<&'static TypeLayout> { self.root_mod_consts.layout().into_option() } - pub(super) fn initialize_library_globals(&self,globals:&'static Globals){ + pub(super) fn initialize_library_globals(&self, globals: &'static Globals) { (self.init_globals_with.0)(globals); } - - fn check_version(&self)->Result<(),LibraryError> + fn check_version(&self) -> Result<(), LibraryError> where - M:RootModule + M: RootModule, { - let expected_version = M::VERSION_STRINGS - .piped(VersionNumber::new)?; + let expected_version = M::VERSION_STRINGS.piped(VersionNumber::new)?; let actual_version = self.version_strings().piped(VersionNumber::new)?; - if expected_version.major != actual_version.major || - (expected_version.major==0) && expected_version.minor > actual_version.minor + if expected_version.major != actual_version.major + || (expected_version.major == 0) && expected_version.minor > actual_version.minor { return Err(LibraryError::IncompatibleVersionNumber { library_name: M::NAME, @@ -103,174 +101,167 @@ impl LibHeader { Ok(()) } - /** -Checks that the library is compatible,returning the root module on success. + Checks that the library is compatible,returning the root module on success. -It checks that these are compatible: + It checks that these are compatible: -- The version number of the library + - The version number of the library -- The layout of the root module. + - The layout of the root module. -# Warning + # Warning -If this function is called within a dynamic library, -it must be called at or after the function that exports its root module is called. + If this function is called within a dynamic library, + it must be called at or after the function that exports its root module is called. -**DO NOT** call this in the static initializer of a dynamic library, -since this library relies on setting up its global state before -calling the root module loader. + **DO NOT** call this in the static initializer of a dynamic library, + since this library relies on setting up its global state before + calling the root module loader. -# Errors + # Errors -This returns these errors: + This returns these errors: -- `LibraryError::ParseVersionError`: -If the version strings in the library can't be parsed as version numbers, -this can only happen if the version strings are manually constructed. + - `LibraryError::ParseVersionError`: + If the version strings in the library can't be parsed as version numbers, + this can only happen if the version strings are manually constructed. -- `LibraryError::IncompatibleVersionNumber`: -If the version number of the library is incompatible. + - `LibraryError::IncompatibleVersionNumber`: + If the version number of the library is incompatible. -- `LibraryError::AbiInstability`: -If the layout of the root module is not the expected one. + - `LibraryError::AbiInstability`: + If the layout of the root module is not the expected one. -- `LibraryError::RootModule` : -If the root module initializer returned an error or panicked. + - `LibraryError::RootModule` : + If the root module initializer returned an error or panicked. - */ - pub fn init_root_module(&self)-> Result + */ + pub fn init_root_module(&self) -> Result where - M: RootModule + M: RootModule, { self.check_version::()?; self.check_layout::() } - - /** -Checks that the version number of the library is compatible, -returning the root module on success. + Checks that the version number of the library is compatible, + returning the root module on success. -This function transmutes the root module type, -without checking that the layout is compatible first. + This function transmutes the root module type, + without checking that the layout is compatible first. -# Warning + # Warning -If this function is called within a dynamic library, -it must be called at or after the function that exports its root module is called. + If this function is called within a dynamic library, + it must be called at or after the function that exports its root module is called. -**DO NOT** call this in the static initializer of a dynamic library, -since this library relies on setting up its global state before -calling the root module loader. + **DO NOT** call this in the static initializer of a dynamic library, + since this library relies on setting up its global state before + calling the root module loader. -# Safety + # Safety -The caller must ensure that `M` has the expected layout. + The caller must ensure that `M` has the expected layout. -# Errors + # Errors -This returns these errors: + This returns these errors: -- `LibraryError::ParseVersionError`: -If the version strings in the library can't be parsed as version numbers, -this can only happen if the version strings are manually constructed. + - `LibraryError::ParseVersionError`: + If the version strings in the library can't be parsed as version numbers, + this can only happen if the version strings are manually constructed. -- `LibraryError::IncompatibleVersionNumber`: -If the version number of the library is incompatible. + - `LibraryError::IncompatibleVersionNumber`: + If the version number of the library is incompatible. -- `LibraryError::RootModule` : -If the root module initializer returned an error or panicked. + - `LibraryError::RootModule` : + If the root module initializer returned an error or panicked. - */ - pub unsafe fn init_root_module_with_unchecked_layout( - &self - )-> Result + */ + pub unsafe fn init_root_module_with_unchecked_layout(&self) -> Result where - M: RootModule + M: RootModule, { self.check_version::()?; self.unchecked_layout() .map_err(RootModuleError::into_library_error::) } - - /// Gets the root module,first - /// checking that the layout of the `M` from the dynamic library is + /// Gets the root module,first + /// checking that the layout of the `M` from the dynamic library is /// compatible with the expected layout. /// /// # Errors - /// + /// /// This returns these errors: - /// + /// /// - `LibraryError::AbiInstability`: /// If the layout of the root module is not the expected one. - /// + /// /// - `LibraryError::RootModule` : /// If the root module initializer returned an error or panicked. - /// + /// pub fn check_layout(&self) -> Result where M: RootModule, { - if let IsLayoutChecked::Yes(root_mod_layout)=self.root_mod_consts.layout(){ + if let IsLayoutChecked::Yes(root_mod_layout) = self.root_mod_consts.layout() { // Using this instead of // crate::abi_stability::abi_checking::check_layout_compatibility - // so that if this is called in a dynamic-library that loads + // so that if this is called in a dynamic-library that loads // another dynamic-library, // it uses the layout checker of the executable, // ensuring a globally unique view of the layout of types. // // This might also reduce the code in the library, // because it doesn't have to compile the layout checker for every library. - (globals::initialized_globals().layout_checking) - (::LAYOUT, root_mod_layout) + (globals::initialized_globals().layout_checking)(::LAYOUT, root_mod_layout) .into_result() - .map_err(|e|{ - // Fixes the bug where printing the error causes a segfault because it + .map_err(|e| { + // Fixes the bug where printing the error causes a segfault because it // contains static references and function pointers into the unloaded library. let formatted = e.to_formatted_error(); LibraryError::AbiInstability(formatted) })?; } - + atomic::compiler_fence(atomic::Ordering::SeqCst); - - unsafe{ + + unsafe { self.unchecked_layout() .map_err(RootModuleError::into_library_error::) } } + /** + Gets the root module without checking that the layout of `M` is the expected one. + This is effectively a transmute. -/** -Gets the root module without checking that the layout of `M` is the expected one. -This is effectively a transmute. - -This is useful if a user keeps a cache of which dynamic libraries -have been checked for layout compatibility. + This is useful if a user keeps a cache of which dynamic libraries + have been checked for layout compatibility. -# Safety + # Safety -The caller must ensure that `M` has the expected layout. + The caller must ensure that `M` has the expected layout. -# Errors + # Errors -This function can return a `RootModuleError` -because the root module failed to initialize. + This function can return a `RootModuleError` + because the root module failed to initialize. -*/ - pub unsafe fn unchecked_layout(&self)->Result + */ + pub unsafe fn unchecked_layout(&self) -> Result where M: PrefixRefTrait, { - self.module.try_init(|| (self.constructor.0)().into_result() ) - .map_err(|mut err|{ - // Making sure that the error doesn't contain references into + self.module + .try_init(|| (self.constructor.0)().into_result()) + .map_err(|mut err| { + // Making sure that the error doesn't contain references into // the unloaded library. err.reallocate(); err @@ -283,15 +274,13 @@ because the root module failed to initialize. ////////////////////////////////////////////////////////////////////// - struct GetAbortingConstructor(T); -impl GetAbortingConstructor{ - const ABORTING_CONSTRUCTOR:Constructor= - Constructor(Self::aborting_constructor); +impl GetAbortingConstructor { + const ABORTING_CONSTRUCTOR: Constructor = Constructor(Self::aborting_constructor); - extern "C" fn aborting_constructor()->T{ - extern_fn_panic_handling!{ + extern "C" fn aborting_constructor() -> T { + extern_fn_panic_handling! { panic!( "BUG:\n\ This function \ @@ -304,16 +293,13 @@ impl GetAbortingConstructor{ } } - ////////////////////////////////////////////////////////////////////// #[repr(C)] -#[derive(StableAbi,Copy,Clone)] +#[derive(StableAbi, Copy, Clone)] struct InitGlobalsWith(pub extern "C" fn(&'static Globals)); -const INIT_GLOBALS_WITH:InitGlobalsWith= - InitGlobalsWith(crate::globals::initialize_globals_with); - +const INIT_GLOBALS_WITH: InitGlobalsWith = InitGlobalsWith(crate::globals::initialize_globals_with); ////////////////////////////////////////////////////////////////////// @@ -324,83 +310,78 @@ pub struct AbiHeaderRef(pub(super) RRef<'static, AbiHeader>); impl std::ops::Deref for AbiHeaderRef { type Target = AbiHeader; - fn deref(&self) -> &AbiHeader{ + fn deref(&self) -> &AbiHeader { self.0.get() } } - - /** Represents the abi_stable version used by a compiled dynamic library, which if incompatible would produce a `LibraryError::InvalidAbiHeader` */ #[repr(C)] -#[derive(Debug,StableAbi,Copy,Clone)] +#[derive(Debug, StableAbi, Copy, Clone)] pub struct AbiHeader { /// A magic string used to check that this is actually abi_stable. - pub magic_string:[u8;32], + pub magic_string: [u8; 32], /// The major abi version of abi_stable - pub abi_major:u32, + pub abi_major: u32, /// The minor abi version of abi_stable - pub abi_minor:u32, - _priv:(), + pub abi_minor: u32, + _priv: (), } - impl AbiHeader { - /// The value of the AbiHeader stored in dynamic libraries that use this + /// The value of the AbiHeader stored in dynamic libraries that use this /// version of abi_stable - pub const VALUE:AbiHeader={ - mod value{ + pub const VALUE: AbiHeader = { + mod value { use super::*; - abi_stable_derive::construct_abi_header!{} + abi_stable_derive::construct_abi_header! {} } value::ABI_HEADER }; } - - impl AbiHeader { /// Checks whether this AbiHeader is compatible with `other`. - pub fn is_compatible(&self,other:&Self)->bool{ - self.magic_string == other.magic_string&& - self.abi_major == other.abi_major && - ( self.abi_major!=0 || self.abi_minor==other.abi_minor ) + pub fn is_compatible(&self, other: &Self) -> bool { + self.magic_string == other.magic_string + && self.abi_major == other.abi_major + && (self.abi_major != 0 || self.abi_minor == other.abi_minor) } - /// Checks whether the abi_stable version of this AbiHeader is + /// Checks whether the abi_stable version of this AbiHeader is /// compatible with the one from where this function is called. - pub fn is_valid(&self)->bool{ + pub fn is_valid(&self) -> bool { self.is_compatible(&AbiHeader::VALUE) } } impl AbiHeaderRef { /// Gets the LibHeader of a library. - /// + /// /// # Errors - /// + /// /// This returns these errors: - /// + /// /// - `LibraryError::InvalidAbiHeader`: /// If the abi_stable used by the library is not compatible. - /// + /// /// - `LibraryError::InvalidCAbi`: /// If the C abi used by the library is not compatible. - pub fn upgrade(self) -> Result<&'static LibHeader, LibraryError>{ + pub fn upgrade(self) -> Result<&'static LibHeader, LibraryError> { if !self.is_valid() { - return Err(LibraryError::InvalidAbiHeader(*self)) + return Err(LibraryError::InvalidAbiHeader(*self)); } - let lib_header: &'static LibHeader = unsafe{ self.0.transmute_into_ref() }; + let lib_header: &'static LibHeader = unsafe { self.0.transmute_into_ref() }; let c_abi_testing_fns = lib_header.root_mod_consts().c_abi_testing_fns(); crate::library::c_abi_testing::run_tests(c_abi_testing_fns)?; - let globals=globals::initialized_globals(); + let globals = globals::initialized_globals(); lib_header.initialize_library_globals(globals); diff --git a/abi_stable/src/library/raw_library.rs b/abi_stable/src/library/raw_library.rs index afa9f1b8..8f778114 100644 --- a/abi_stable/src/library/raw_library.rs +++ b/abi_stable/src/library/raw_library.rs @@ -2,48 +2,46 @@ use super::*; use std::env::consts::{DLL_PREFIX, DLL_SUFFIX}; - - /// A handle to any dynamically loaded library, /// not necessarily ones that export abi_stable compatible modules. pub struct RawLibrary { - path:PathBuf, + path: PathBuf, library: LibLoadingLibrary, } impl RawLibrary { /// Gets the full path a library would be loaded from, - pub fn path_in_directory( - directory: &Path, - base_name: &str, - suffix:LibrarySuffix, - )->PathBuf{ - let formatted:String; + pub fn path_in_directory(directory: &Path, base_name: &str, suffix: LibrarySuffix) -> PathBuf { + let formatted: String; let is_64_bits = cfg!(any(x86_64, powerpc64, aarch64)) || ::std::mem::size_of::() == 8; let bits = if is_64_bits { "64" } else { "32" }; - let maybe_suffixed_name=match suffix { - LibrarySuffix::Suffix=>{ - formatted=format!("{}-{}", base_name, bits); + let maybe_suffixed_name = match suffix { + LibrarySuffix::Suffix => { + formatted = format!("{}-{}", base_name, bits); &*formatted } - LibrarySuffix::NoSuffix=>{ - base_name - } + LibrarySuffix::NoSuffix => base_name, }; - let name=format!("{}{}{}", DLL_PREFIX, maybe_suffixed_name, DLL_SUFFIX); + let name = format!("{}{}{}", DLL_PREFIX, maybe_suffixed_name, DLL_SUFFIX); directory.join(name) } /// Loads the dynamic library at the `full_path` path. - pub fn load_at(full_path:&Path) -> Result { + pub fn load_at(full_path: &Path) -> Result { // safety: not my problem if libraries have problematic static initializers - match unsafe{ LibLoadingLibrary::new(&full_path) } { - Ok(library)=>Ok(Self { path:full_path.to_owned(), library }), - Err(err)=>Err(LibraryError::OpenError{ path:full_path.to_owned(), err: Box::new(err) }), + match unsafe { LibLoadingLibrary::new(&full_path) } { + Ok(library) => Ok(Self { + path: full_path.to_owned(), + library, + }), + Err(err) => Err(LibraryError::OpenError { + path: full_path.to_owned(), + err: Box::new(err), + }), } } @@ -56,21 +54,17 @@ impl RawLibrary { /// /// /// - pub unsafe fn get( - &self, - symbol_name: &[u8] - ) -> Result,LibraryError> - { + pub unsafe fn get(&self, symbol_name: &[u8]) -> Result, LibraryError> { match self.library.get::(symbol_name) { - Ok(symbol)=>Ok(symbol), - Err(io)=>{ - let symbol=symbol_name.to_owned(); - Err(LibraryError::GetSymbolError{ - library:self.path.clone(), - symbol, + Ok(symbol) => Ok(symbol), + Err(io) => { + let symbol = symbol_name.to_owned(); + Err(LibraryError::GetSymbolError { + library: self.path.clone(), + symbol, err: Box::new(io), }) } } } -} \ No newline at end of file +} diff --git a/abi_stable/src/library/root_mod_trait.rs b/abi_stable/src/library/root_mod_trait.rs index ad58a5b0..1e64fc35 100644 --- a/abi_stable/src/library/root_mod_trait.rs +++ b/abi_stable/src/library/root_mod_trait.rs @@ -1,38 +1,33 @@ use super::*; -use crate::{ - marker_type::NonOwningPhantom, - prefix_type::PrefixRefTrait, - utils::leak_value, -}; - +use crate::{marker_type::NonOwningPhantom, prefix_type::PrefixRefTrait, utils::leak_value}; /// The root module of a dynamic library, /// which may contain other modules,function pointers,and static references. -/// -/// +/// +/// /// # Examples -/// -/// For a more in-context example of a type implementing this trait you can look +/// +/// For a more in-context example of a type implementing this trait you can look /// at either the example in the readme for this crate, /// or the `example/example_*_interface` crates in this crates' repository . -/// +/// /// ### Basic -/// +/// /// ```rust /// use abi_stable::{ /// library::RootModule, /// sabi_types::VersionStrings, /// StableAbi, /// }; -/// +/// /// #[repr(C)] /// #[derive(StableAbi)] /// #[sabi(kind(Prefix(prefix_ref = "Module_Ref", prefix_fields = "Module_Prefix")))] /// pub struct Module{ /// pub first: u8, -/// // The `#[sabi(last_prefix_field)]` attribute here means that this is -/// // the last field in this module that was defined in the +/// // The `#[sabi(last_prefix_field)]` attribute here means that this is +/// // the last field in this module that was defined in the /// // first compatible version of the library, /// #[sabi(last_prefix_field)] /// pub second: u16, @@ -44,11 +39,10 @@ use crate::{ /// const NAME: &'static str = "example_root_module"; /// const VERSION_STRINGS: VersionStrings = abi_stable::package_version_strings!(); /// } -/// +/// /// # fn main(){} /// ``` -pub trait RootModule: Sized + StableAbi + PrefixRefTrait + 'static { - +pub trait RootModule: Sized + StableAbi + PrefixRefTrait + 'static { /// The name of the dynamic library,which is the same on all platforms. /// This is generally the name of the `implementation crate`. const BASE_NAME: &'static str; @@ -57,31 +51,31 @@ pub trait RootModule: Sized + StableAbi + PrefixRefTrait + 'static { const NAME: &'static str; /// The version number of the library that this is a root module of. - /// - /// Initialize this with + /// + /// Initialize this with /// [`package_version_strings!()`](../macro.package_version_strings.html) const VERSION_STRINGS: VersionStrings; /// All the constants of this trait and supertraits. /// /// It can safely be used as a proxy for the associated constants of this trait. - const CONSTANTS:RootModuleConsts=RootModuleConsts{ - inner:ErasedRootModuleConsts{ - base_name:RStr::from_str(Self::BASE_NAME), - name:RStr::from_str(Self::NAME), - version_strings:Self::VERSION_STRINGS, - layout:IsLayoutChecked::Yes(::LAYOUT), - c_abi_testing_fns:crate::library::c_abi_testing::C_ABI_TESTING_FNS, - _priv:(), + const CONSTANTS: RootModuleConsts = RootModuleConsts { + inner: ErasedRootModuleConsts { + base_name: RStr::from_str(Self::BASE_NAME), + name: RStr::from_str(Self::NAME), + version_strings: Self::VERSION_STRINGS, + layout: IsLayoutChecked::Yes(::LAYOUT), + c_abi_testing_fns: crate::library::c_abi_testing::C_ABI_TESTING_FNS, + _priv: (), }, - _priv:NonOwningPhantom::NEW, + _priv: NonOwningPhantom::NEW, }; /// Like `Self::CONSTANTS`, /// except without including the type layout constant for the root module. - const CONSTANTS_NO_ABI_INFO:RootModuleConsts={ - let mut consts=Self::CONSTANTS; - consts.inner.layout=IsLayoutChecked::No; + const CONSTANTS_NO_ABI_INFO: RootModuleConsts = { + let mut consts = Self::CONSTANTS; + consts.inner.layout = IsLayoutChecked::No; consts }; @@ -92,140 +86,140 @@ pub trait RootModule: Sized + StableAbi + PrefixRefTrait + 'static { /// ](../macro.declare_root_module_statics.html). /// Passing `Self` instead of `TypeOfSelf` won't work. /// - fn root_module_statics()->&'static RootModuleStatics; + fn root_module_statics() -> &'static RootModuleStatics; -/** -Gets the root module,returning None if the module is not yet loaded. -*/ + /** + Gets the root module,returning None if the module is not yet loaded. + */ #[inline] - fn get_module()->Option{ + fn get_module() -> Option { Self::root_module_statics().root_mod.get() } -/** -Gets the RawLibrary of the module, -returning None if the dynamic library failed to load -(it doesn't exist or layout checking failed). + /** + Gets the RawLibrary of the module, + returning None if the dynamic library failed to load + (it doesn't exist or layout checking failed). -Note that if the root module is initialized using `Self::load_module_with`, -this will return None even though `Self::get_module` does not. + Note that if the root module is initialized using `Self::load_module_with`, + this will return None even though `Self::get_module` does not. -*/ + */ #[inline] - fn get_raw_library()->Option<&'static RawLibrary>{ + fn get_raw_library() -> Option<&'static RawLibrary> { Self::root_module_statics().raw_lib.get() } /// Returns the path the library would be loaded from,given a directory(folder). - fn get_library_path(directory:&Path)-> PathBuf { - let base_name=Self::BASE_NAME; - RawLibrary::path_in_directory(directory, base_name,LibrarySuffix::NoSuffix) + fn get_library_path(directory: &Path) -> PathBuf { + let base_name = Self::BASE_NAME; + RawLibrary::path_in_directory(directory, base_name, LibrarySuffix::NoSuffix) } -/** + /** -Loads the root module,with a closure which either -returns the root module or an error. + Loads the root module,with a closure which either + returns the root module or an error. -If the root module was already loaded, -this will return the already loaded root module, -without calling the closure. + If the root module was already loaded, + this will return the already loaded root module, + without calling the closure. -*/ - fn load_module_with(f:F)->Result + */ + fn load_module_with(f: F) -> Result where - F:FnOnce()->Result + F: FnOnce() -> Result, { Self::root_module_statics().root_mod.try_init(f) } -/** -Loads this module from the path specified by `where_`, -first loading the dynamic library if it wasn't already loaded. + /** + Loads this module from the path specified by `where_`, + first loading the dynamic library if it wasn't already loaded. -Once the root module is loaded, -this will return the already loaded root module. + Once the root module is loaded, + this will return the already loaded root module. -# Warning + # Warning -If this function is called within a dynamic library, -it must be called at or after the function that exports its root module is called. + If this function is called within a dynamic library, + it must be called at or after the function that exports its root module is called. -**DO NOT** call this in the static initializer of a dynamic library, -since this library relies on setting up its global state before -calling the root module loader. + **DO NOT** call this in the static initializer of a dynamic library, + since this library relies on setting up its global state before + calling the root module loader. -# Errors + # Errors -This will return these errors: + This will return these errors: -- `LibraryError::OpenError`: -If the dynamic library itself could not be loaded. + - `LibraryError::OpenError`: + If the dynamic library itself could not be loaded. -- `LibraryError::GetSymbolError`: -If the root module was not exported. + - `LibraryError::GetSymbolError`: + If the root module was not exported. -- `LibraryError::InvalidAbiHeader`: -If the abi_stable version used by the library is not compatible. + - `LibraryError::InvalidAbiHeader`: + If the abi_stable version used by the library is not compatible. -- `LibraryError::ParseVersionError`: -If the version strings in the library can't be parsed as version numbers, -this can only happen if the version strings are manually constructed. + - `LibraryError::ParseVersionError`: + If the version strings in the library can't be parsed as version numbers, + this can only happen if the version strings are manually constructed. -- `LibraryError::IncompatibleVersionNumber`: -If the version number of the library is incompatible. + - `LibraryError::IncompatibleVersionNumber`: + If the version number of the library is incompatible. -- `LibraryError::AbiInstability`: -If the layout of the root module is not the expected one. + - `LibraryError::AbiInstability`: + If the layout of the root module is not the expected one. -- `LibraryError::RootModule` : -If the root module initializer returned an error or panicked. + - `LibraryError::RootModule` : + If the root module initializer returned an error or panicked. -*/ - fn load_from(where_:LibraryPath<'_>) -> Result{ - let statics=Self::root_module_statics(); - statics.root_mod.try_init(||{ - let raw_library=load_raw_library::(where_)?; - let items = unsafe{ lib_header_from_raw_library(&raw_library)? }; + */ + fn load_from(where_: LibraryPath<'_>) -> Result { + let statics = Self::root_module_statics(); + statics.root_mod.try_init(|| { + let raw_library = load_raw_library::(where_)?; + let items = unsafe { lib_header_from_raw_library(&raw_library)? }; - let root_mod=items.init_root_module::()?.initialization()?; + let root_mod = items.init_root_module::()?.initialization()?; // Important,If I don't leak the library after sucessfully loading the root module // it would cause any use of the module to be a use after free. - let raw_lib=leak_value(raw_library); - statics.raw_lib.init(|| raw_lib ); + let raw_lib = leak_value(raw_library); + statics.raw_lib.init(|| raw_lib); Ok(root_mod) }) } -/** + /** -Loads this module from the directory specified by `where_`, -first loading the dynamic library if it wasn't already loaded. + Loads this module from the directory specified by `where_`, + first loading the dynamic library if it wasn't already loaded. -Once the root module is loaded, -this will return the already loaded root module. + Once the root module is loaded, + this will return the already loaded root module. -Warnings and Errors are detailed in [`load_from`](#method.load_from), + Warnings and Errors are detailed in [`load_from`](#method.load_from), -*/ - fn load_from_directory(where_:&Path) -> Result{ + */ + fn load_from_directory(where_: &Path) -> Result { Self::load_from(LibraryPath::Directory(where_)) } -/** + /** -Loads this module from the file at `path_`, -first loading the dynamic library if it wasn't already loaded. + Loads this module from the file at `path_`, + first loading the dynamic library if it wasn't already loaded. -Once the root module is loaded, -this will return the already loaded root module. + Once the root module is loaded, + this will return the already loaded root module. -Warnings and Errors are detailed in [`load_from`](#method.load_from), + Warnings and Errors are detailed in [`load_from`](#method.load_from), -*/ - fn load_from_file(path_:&Path) -> Result{ + */ + fn load_from_file(path_: &Path) -> Result { Self::load_from(LibraryPath::FullPath(path_)) } @@ -237,18 +231,14 @@ Warnings and Errors are detailed in [`load_from`](#method.load_from), } } - /// Loads the raw library at `where_` -fn load_raw_library(where_:LibraryPath<'_>) -> Result +fn load_raw_library(where_: LibraryPath<'_>) -> Result where - M: RootModule + M: RootModule, { - let path=match where_ { - LibraryPath::Directory(directory)=>{ - M::get_library_path(&directory) - } - LibraryPath::FullPath(full_path)=> - full_path.to_owned(), + let path = match where_ { + LibraryPath::Directory(directory) => M::get_library_path(&directory), + LibraryPath::FullPath(full_path) => full_path.to_owned(), }; RawLibrary::load_at(&path) } @@ -273,15 +263,11 @@ it will contain dangling `'static` references if the library is dropped before i */ pub unsafe fn lib_header_from_raw_library( - raw_library:&RawLibrary -)->Result<&'static LibHeader, LibraryError> -{ - unsafe{ - abi_header_from_raw_library(raw_library)?.upgrade() - } + raw_library: &RawLibrary, +) -> Result<&'static LibHeader, LibraryError> { + unsafe { abi_header_from_raw_library(raw_library)?.upgrade() } } - /** Gets the AbiHeaderRef of a library. @@ -299,10 +285,9 @@ it will contain dangling `'static` references if the library is dropped before i */ pub unsafe fn abi_header_from_raw_library( - raw_library:&RawLibrary -)->Result -{ - unsafe{ + raw_library: &RawLibrary, +) -> Result { + unsafe { let mut mangled = mangled_root_module_loader_name(); mangled.push('\0'); @@ -312,7 +297,6 @@ pub unsafe fn abi_header_from_raw_library( } } - /** Gets the LibHeader of the library at the path. @@ -334,18 +318,16 @@ If the root module was not exported. If the abi_stable version used by the library is not compatible. */ -pub fn lib_header_from_path(path:&Path)->Result<&'static LibHeader, LibraryError> { - let raw_lib=RawLibrary::load_at(path)?; +pub fn lib_header_from_path(path: &Path) -> Result<&'static LibHeader, LibraryError> { + let raw_lib = RawLibrary::load_at(path)?; - let library_getter = unsafe{ lib_header_from_raw_library(&raw_lib)? }; + let library_getter = unsafe { lib_header_from_raw_library(&raw_lib)? }; mem::forget(raw_lib); Ok(library_getter) - } - /** Gets the AbiHeaderRef of the library at the path. @@ -364,20 +346,18 @@ If the dynamic library itself could not be loaded. If the root module was not exported. */ -pub fn abi_header_from_path(path:&Path)->Result { +pub fn abi_header_from_path(path: &Path) -> Result { let raw_lib = RawLibrary::load_at(path)?; - let library_getter = unsafe{ abi_header_from_raw_library(&raw_lib)? }; + let library_getter = unsafe { abi_header_from_raw_library(&raw_lib)? }; mem::forget(raw_lib); Ok(library_getter) - } ////////////////////////////////////////////////////////////////////// - macro_rules! declare_root_module_consts { ( fields=[ @@ -390,9 +370,9 @@ macro_rules! declare_root_module_consts { ) => ( /// All the constants of the [`RootModule`] trait for `M`, /// used mostly to construct a `LibHeader` with `LibHeader::from_constructor`. - /// + /// /// This is constructed with [`RootModule::CONSTANTS`]. - /// + /// /// [`RootModule`]: ./trait.RootModule.html /// [`RootModule::CONSTANTS`]: ./trait.RootModule.html#associatedconstant.CONSTANTS #[repr(C)] @@ -442,8 +422,7 @@ macro_rules! declare_root_module_consts { ) } - -declare_root_module_consts!{ +declare_root_module_consts! { fields=[ method_docs=" The name of the dynamic library,which is the same on all platforms. @@ -466,4 +445,3 @@ declare_root_module_consts!{ c_abi_testing_fns:&'static CAbiTestingFns, ] } - diff --git a/abi_stable/src/macros.rs b/abi_stable/src/macros.rs index bfdc7631..b4752501 100644 --- a/abi_stable/src/macros.rs +++ b/abi_stable/src/macros.rs @@ -1,11 +1,10 @@ #[macro_use] mod internal; - /** Use this when constructing a [`MonoTypeLayout`] when manually implementing StableAbi. -This stores indices and ranges for the type and/or const parameter taken +This stores indices and ranges for the type and/or const parameter taken from the [`SharedVars`] stored in the same [`TypeLayout`] where this is stored. # Syntax @@ -16,16 +15,16 @@ from the [`SharedVars`] stored in the same [`TypeLayout`] where this is stored. -` `: No generic parameters of that kind. --`i`: +-`i`: Takes the ith type or const parameter(indexed separately). --`i..j`: +-`i..j`: Takes from i to j (exclusive) type or const parameter(indexed separately). --`i..=j`: +-`i..=j`: Takes from i to j (inclusive) type or const parameter(indexed separately). --`x:StartLen`: +-`x:StartLen`: Takes from x.start() to x.end() (exclusive) type or const parameter(indexed separately). @@ -101,7 +100,7 @@ const PARAMS:CompGenericParams=tl_genparams!(;StartLen::new(0,2);); macro_rules! tl_genparams { (count; ) => ( 0 ); (count; $v0:lifetime) => ( 1 ); - (count; $v0:lifetime,$v1:lifetime $(,$rem:lifetime)*) => ( + (count; $v0:lifetime,$v1:lifetime $(,$rem:lifetime)*) => ( 2 + $crate::tl_genparams!(count; $($rem),* ) ); ( $($lt:lifetime),* $(,)? ; $($ty:expr)? ; $($const_p:expr)? ) => ({ @@ -112,7 +111,7 @@ macro_rules! tl_genparams { #[allow(unused_parens)] let ty_param_range=$crate::type_layout::StartLenConverter( ($($ty)?) ).to_start_len(); - + #[allow(unused_parens)] let const_param_range= $crate::type_layout::StartLenConverter( ($($const_p)?) ).to_start_len(); @@ -126,7 +125,6 @@ macro_rules! tl_genparams { }) } - /////////////////////////////////////////////////////////////////////// /** @@ -174,7 +172,7 @@ macro_rules! rtry { } /// Equivalent to `?` for [`ROption`]. -/// +/// /// [`ROption`]: ./std_types/enum.ROption.html #[macro_export] macro_rules! rtry_opt { @@ -187,24 +185,20 @@ macro_rules! rtry_opt { }}; } - - /////////////////////////////////////////////////////////////////////// macro_rules! check_unerased { ( $this:ident,$res:expr - ) => ( - if let Err(e)=$res { - return Err( e.map(move|_| $this ) ); + ) => { + if let Err(e) = $res { + return Err(e.map(move |_| $this)); } - ) + }; } - /////////////////////////////////////////////////////////////////////// - /** Use this to make sure that you handle panics inside `extern fn` correctly. @@ -214,15 +208,15 @@ It does not prevent functions inside from using `::std::panic::catch_unwind` to # Early returns -This macro by default wraps the passed code in a closure so that any +This macro by default wraps the passed code in a closure so that any early returns that happen inside don't interfere with the macro generated code. -If you don't have an early return (a `return`/`continue`/`break`) -in the code passed to this macro you can use +If you don't have an early return (a `return`/`continue`/`break`) +in the code passed to this macro you can use `extern_fn_panic_handling!{no_early_return; }`, which *might* be cheaper(this has not been tested yet). -# Example +# Example ``` use std::fmt; @@ -288,7 +282,7 @@ macro_rules! extern_fn_panic_handling { }; ::std::mem::forget(aborter_guard); - + res }); ( $($fn_contents:tt)* ) => ( @@ -303,16 +297,13 @@ macro_rules! extern_fn_panic_handling { ) } - /////////////////////////////////////////////////////////////////////// - - /** Constructs the [`TypeInfo`] for some type. -It's necessary for the type to be `'static` because +It's necessary for the type to be `'static` because [`TypeInfo`] stores a private function that returns the [`UTypeId`] of that type. # Example @@ -334,7 +325,7 @@ impl ImplType for Foo where T:'static+Send+Sync { type Interface=(); - + // You have to write the full type (eg: impl_get_type_info!{ Bar<'a,T,U> } ) , // never write Self. const INFO:&'static TypeInfo=impl_get_type_info! { Foo }; @@ -349,37 +340,33 @@ where T:'static+Send+Sync */ #[macro_export] macro_rules! impl_get_type_info { - ($type:ty) => ( - { - use std::mem; - use $crate::{ - erased_types::TypeInfo, - std_types::{RStr,utypeid::some_utypeid}, - }; + ($type:ty) => {{ + use std::mem; + use $crate::{ + erased_types::TypeInfo, + std_types::{utypeid::some_utypeid, RStr}, + }; - let type_name=$crate::sabi_types::Constructor($crate::utils::get_type_name::<$type>); - - &TypeInfo{ - size:mem::size_of::(), - alignment:mem::align_of::(), - _uid:$crate::sabi_types::Constructor( some_utypeid:: ), - type_name, - module:RStr::from_str(module_path!()), - package:RStr::from_str(env!("CARGO_PKG_NAME")), - package_version:$crate::package_version_strings!(), - _private_field:(), - } + let type_name = $crate::sabi_types::Constructor($crate::utils::get_type_name::<$type>); + + &TypeInfo { + size: mem::size_of::(), + alignment: mem::align_of::(), + _uid: $crate::sabi_types::Constructor(some_utypeid::), + type_name, + module: RStr::from_str(module_path!()), + package: RStr::from_str(env!("CARGO_PKG_NAME")), + package_version: $crate::package_version_strings!(), + _private_field: (), } - ) + }}; } /////////////////////////////////////////////////////////////////////////////////////////// - - /** Constructs a [`Tag`], -a dynamically typed value for users to check extra properties about their types +a dynamically typed value for users to check extra properties about their types when doing runtime type checking. Note that this macro is not recursive, @@ -395,7 +382,7 @@ so that if this changes it can be reported as an error. This will cause an error if the binary and dynamic library disagree about the values inside the "required traits" map entry . -In real code this should be written in a +In real code this should be written in a way that keeps the tags and the type bounds in sync. @@ -432,7 +419,7 @@ struct Value{ macro_rules! tag { ([ $( $elem:expr ),* $(,)? ])=>{{ use $crate::type_layout::tagging::{Tag,FromLiteral}; - + Tag::arr($crate::rslice![ $( FromLiteral($elem).to_tag(), )* ]) @@ -463,16 +450,14 @@ macro_rules! tag { }}; } - /////////////////////////////////////////////////////////////////////////////// - #[allow(unused_macros)] macro_rules! assert_matches { ( $(|)? $($pat:pat)|* =$expr:expr)=>{{ let ref value=$expr; assert!( - core_extensions::matches!(*value, $($pat)|* ), + core_extensions::matches!(*value, $($pat)|* ), "pattern did not match the value:\n\t\ {:?} ", @@ -481,10 +466,8 @@ macro_rules! assert_matches { }}; } - /////////////////////////////////////////////////////////////////////////////// - /** Constructs an [`ItemInfo`], with information about the place where it's called. @@ -492,24 +475,17 @@ Constructs an [`ItemInfo`], with information about the place where it's called. */ #[macro_export] macro_rules! make_item_info { - () => ( + () => { $crate::type_layout::ItemInfo::new( - concat!( - env!("CARGO_PKG_NAME"), - ";", - env!("CARGO_PKG_VERSION") - ), + concat!(env!("CARGO_PKG_NAME"), ";", env!("CARGO_PKG_VERSION")), line!(), $crate::type_layout::ModPath::inside($crate::nul_str!(module_path!())), ) - ) + }; } - /////////////////////////////////////////////////////////////////////////////// - - /** Constructs an [`RVec`] using the same syntax that the `std::vec` macro uses. @@ -519,7 +495,7 @@ Constructs an [`RVec`] using the same syntax that the `std::vec` macro uses. use abi_stable::{ rvec, - std_types::RVec, + std_types::RVec, }; assert_eq!(RVec::::new(), rvec![]); @@ -540,15 +516,13 @@ macro_rules! rvec { ) } - /////////////////////////////////////////////////////////////////////////////// - /** Use this macro to construct a `abi_stable::std_types::Tuple*` with the values passed to the macro. -# Example +# Example ``` use abi_stable::{ @@ -572,26 +546,27 @@ assert_eq!(rtuple!(3,5,8,9), Tuple4(3,5,8,9)); #[macro_export] macro_rules! rtuple { - () => (()); - ($v0:expr $(,)* ) => ( + () => { + () + }; + ($v0:expr $(,)* ) => { $crate::std_types::Tuple1($v0) - ); - ($v0:expr,$v1:expr $(,)* ) => ( - $crate::std_types::Tuple2($v0,$v1) - ); - ($v0:expr,$v1:expr,$v2:expr $(,)* ) => ( - $crate::std_types::Tuple3($v0,$v1,$v2) - ); - ($v0:expr,$v1:expr,$v2:expr,$v3:expr $(,)* ) => ( - $crate::std_types::Tuple4($v0,$v1,$v2,$v3) - ); + }; + ($v0:expr,$v1:expr $(,)* ) => { + $crate::std_types::Tuple2($v0, $v1) + }; + ($v0:expr,$v1:expr,$v2:expr $(,)* ) => { + $crate::std_types::Tuple3($v0, $v1, $v2) + }; + ($v0:expr,$v1:expr,$v2:expr,$v3:expr $(,)* ) => { + $crate::std_types::Tuple4($v0, $v1, $v2, $v3) + }; } - /** Use this macro to get the type of a `Tuple*` with the types passed to the macro. -# Example +# Example ``` use abi_stable::{ @@ -632,7 +607,6 @@ macro_rules! RTuple { ); } - /////////////////////////////////////////////////////////////////////////////// /** @@ -688,10 +662,8 @@ macro_rules! rslice { }; } - /////////////////////////////////////////////////////////////////////////////// - /** A macro to construct [`RStr`] constants. @@ -738,15 +710,14 @@ assert_eq!( RSTR_6.len(), 7 ); */ #[macro_export] -macro_rules! rstr{ - ( $str:expr ) => ({ - const __SABI_RSTR: $crate::std_types::RStr<'static> = +macro_rules! rstr { + ( $str:expr ) => {{ + const __SABI_RSTR: $crate::std_types::RStr<'static> = $crate::std_types::RStr::from_str($str); __SABI_RSTR - }) + }}; } - /** Constructs a [`NulStr`] from a string literal. @@ -773,7 +744,6 @@ macro_rules! nul_str { }} } - /** Constructs a RStr with the concatenation of the passed in strings, and variables with the range for the individual strings. @@ -828,10 +798,10 @@ macro_rules! make_shared_vars{ _inner_multi_str_mod::CONCATENATED, rslice![ $( $($lifetime_indices),* )? ], ); - + struct __ACPromoted(T); - impl<$($impl_gen)*> __ACPromoted<$type> + impl<$($impl_gen)*> __ACPromoted<$type> where $($($where_clause)*)? { $( const CONST_PARAM_UNERASED: &'static $const_ty = &$constants; )? @@ -853,9 +823,9 @@ macro_rules! make_shared_vars{ &$crate::type_layout::SharedVars::new( $mono_shared_vars, - rslice![ - $( $( GetTypeLayoutCtor::<$ty_layout>::STABLE_ABI,)* )? - $( $( GetTypeLayoutCtor::<$prefix_ty_layout>::PREFIX_STABLE_ABI,)* )? + rslice![ + $( $( GetTypeLayoutCtor::<$ty_layout>::STABLE_ABI,)* )? + $( $( GetTypeLayoutCtor::<$prefix_ty_layout>::PREFIX_STABLE_ABI,)* )? ], $crate::std_types::RSlice::from_slice(Self::CONST_PARAM), ) @@ -866,16 +836,14 @@ macro_rules! make_shared_vars{ } } - /////////////////////////////////////////////////////////////////////////////// - /// Allows declaring a [`StaticRef`] associated `const`ant. -/// +/// /// This macro is for declaring inherent associated constant of non-`'static` types. /// /// # Breaking changes -/// +/// /// This macro may be changed to produce compiler-errors when it's used to /// declare a non-associated `const`, or a constant in a trait implementation. /// @@ -892,19 +860,19 @@ macro_rules! make_shared_vars{ /// pointer_trait::CallReferentDrop, /// prefix_type::{PrefixTypeTrait, WithMetadata}, /// }; -/// +/// /// use std::{ /// mem::ManuallyDrop, /// ops::Deref, /// }; -/// +/// /// fn main(){ /// let boxed = BoxLike::new(100); /// /// assert_eq!(*boxed, 100); /// assert_eq!(boxed.into_inner(), 100); /// } -/// +/// /// /// An ffi-safe `Box` /// #[repr(C)] /// #[derive(StableAbi)] @@ -912,10 +880,10 @@ macro_rules! make_shared_vars{ /// data: *mut T, /// /// vtable: VTable_Ref, -/// +/// /// _marker: std::marker::PhantomData, /// } -/// +/// /// impl BoxLike{ /// pub fn new(value: T) -> Self { /// let box_ = Box::new(value); @@ -926,7 +894,7 @@ macro_rules! make_shared_vars{ /// _marker: std::marker::PhantomData, /// } /// } -/// +/// /// /// Extracts the value this owns. /// pub fn into_inner(self) -> T{ /// let this = ManuallyDrop::new(self); @@ -939,8 +907,8 @@ macro_rules! make_shared_vars{ /// } /// } /// } -/// -/// +/// +/// /// impl Drop for BoxLike{ /// fn drop(&mut self){ /// unsafe{ @@ -948,15 +916,15 @@ macro_rules! make_shared_vars{ /// } /// } /// } -/// +/// /// // `#[sabi(kind(Prefix))]` Declares this type as being a prefix-type, /// // generating both of these types: -/// // -/// // - VTable_Prefix`: A struct with the fields up to (and including) the field with the +/// // +/// // - VTable_Prefix`: A struct with the fields up to (and including) the field with the /// // `#[sabi(last_prefix_field)]` attribute. -/// // +/// // /// // - VTable_Ref`: An ffi-safe pointer to `VTable`,with methods to get `VTable`'s fields. -/// // +/// // /// #[repr(C)] /// #[derive(StableAbi)] /// #[sabi(kind(Prefix))] @@ -964,7 +932,7 @@ macro_rules! make_shared_vars{ /// #[sabi(last_prefix_field)] /// destructor: unsafe extern "C" fn(*mut T, CallReferentDrop), /// } -/// +/// /// impl VTable{ /// staticref!(const VTABLE_VAL: WithMetadata = WithMetadata::new( /// PrefixTypeTrait::METADATA, @@ -972,12 +940,12 @@ macro_rules! make_shared_vars{ /// destructor: destroy_box::, /// }, /// )); -/// +/// /// const VTABLE: VTable_Ref = { /// VTable_Ref( Self::VTABLE_VAL.as_prefix() ) /// }; -/// } -/// +/// } +/// /// unsafe extern "C" fn destroy_box(v: *mut T, call_drop: CallReferentDrop) { /// extern_fn_panic_handling! { /// let mut box_ = Box::from_raw(v as *mut ManuallyDrop); @@ -987,11 +955,11 @@ macro_rules! make_shared_vars{ /// drop(box_); /// } /// } -/// -/// +/// +/// /// impl Deref for BoxLike { /// type Target=T; -/// +/// /// fn deref(&self)->&T{ /// unsafe{ /// &(*self.data) @@ -1010,7 +978,7 @@ macro_rules! staticref{ $(;)? )=>{ $( - $(#[$attr])* + $(#[$attr])* $vis const $name : $crate::sabi_types::StaticRef<$ty> = { // Generating a random base36 string to avoid name collisions const fn __sabi_mtuxotq5otc3ntu5mdq4ntgwmzi( @@ -1029,15 +997,12 @@ macro_rules! staticref{ /////////////////////////////////////////////////////////////////////////////// - macro_rules! ignoring { (($($ignore:tt)*) $($passed:tt)* ) => {$($passed)*}; } - /////////////////////////////////////////////////////////////////////////////// - #[allow(unused_macros)] macro_rules! delegate_interface_serde { ( @@ -1062,11 +1027,11 @@ macro_rules! delegate_interface_serde { } } - impl<$lt,$($impl_header)* S,I> + impl<$lt,$($impl_header)* S,I> $crate::nonexhaustive_enum::DeserializeEnum< $lt, $crate::nonexhaustive_enum::NonExhaustive<$this,S,I> - > + > for $interf where $this:$crate::nonexhaustive_enum::GetEnumInfo+$lt, @@ -1091,7 +1056,7 @@ macro_rules! delegate_interface_serde { $crate::std_types::RBoxError > { - <$delegates_to as + <$delegates_to as $crate::nonexhaustive_enum::DeserializeEnum< $crate::nonexhaustive_enum::NonExhaustive<$this,S,I> > @@ -1100,5 +1065,3 @@ macro_rules! delegate_interface_serde { } ) } - - diff --git a/abi_stable/src/macros/internal.rs b/abi_stable/src/macros/internal.rs index 4f5ac6a4..bbb8a0a4 100644 --- a/abi_stable/src/macros/internal.rs +++ b/abi_stable/src/macros/internal.rs @@ -37,7 +37,6 @@ macro_rules! deref_coerced_impl_cmp_traits { }; } - macro_rules! slice_like_impl_cmp_traits { ( impl $impl_params:tt $Self:ty, @@ -61,15 +60,15 @@ macro_rules! slice_like_impl_cmp_traits { const _: () = { use std::cmp::{PartialEq, PartialOrd, Ordering}; - impl, U, $($impl_params)*> PartialEq<$Rhs> for $Self - where $($where)* + impl, U, $($impl_params)*> PartialEq<$Rhs> for $Self + where $($where)* { fn eq(&self, other: &$Rhs) -> bool { <[T] as PartialEq<[U]>>::eq(self, other) } } - impl PartialOrd<$Rhs> for $Self + impl PartialOrd<$Rhs> for $Self where T: PartialOrd, [T]: PartialOrd<[U]>, @@ -80,15 +79,15 @@ macro_rules! slice_like_impl_cmp_traits { } } - impl, T, $($impl_params)*> PartialEq<$Self> for $Rhs - where $($where)* + impl, T, $($impl_params)*> PartialEq<$Self> for $Rhs + where $($where)* { fn eq(&self, other: &$Self) -> bool { <[U] as PartialEq<[T]>>::eq(self, other) } } - impl PartialOrd<$Self> for $Rhs + impl PartialOrd<$Self> for $Rhs where U: PartialOrd, [U]: PartialOrd<[T]>, @@ -102,25 +101,21 @@ macro_rules! slice_like_impl_cmp_traits { }; } - - - macro_rules! zst_assert { - ($Self:ty) => ({ + ($Self:ty) => {{ ["Expected this to be Zero-sized"][(std::mem::size_of::<$Self>() != 0) as usize]; ["Expected this to be 1 aligned"][(std::mem::align_of::<$Self>() != 1) as usize]; ["Expected Tuple1 to be Zero-sized"] - [(std::mem::size_of::>() != 0) as usize]; + [(std::mem::size_of::>() != 0) as usize]; ["Expected Tuple1 to be 1 aligned"] - [(std::mem::align_of::>() != 1) as usize]; - + [(std::mem::align_of::>() != 1) as usize]; ["Expected Tuple1 to be Zero-sized"] - [(std::mem::size_of::>() != 0) as usize]; + [(std::mem::size_of::>() != 0) as usize]; ["Expected Tuple1 to be 1 aligned"] - [(std::mem::align_of::>() != 1) as usize]; - }); + [(std::mem::align_of::>() != 1) as usize]; + }}; } diff --git a/abi_stable/src/marker_type.rs b/abi_stable/src/marker_type.rs index cf268d71..51d9bf00 100644 --- a/abi_stable/src/marker_type.rs +++ b/abi_stable/src/marker_type.rs @@ -2,14 +2,12 @@ Zero-sized types . */ -use std::{cell::Cell,marker::PhantomData, rc::Rc}; +use std::{cell::Cell, marker::PhantomData, rc::Rc}; use crate::{ abi_stability::PrefixStableAbi, derive_macro_reexports::*, - type_layout::{ - MonoTypeLayout, MonoTLData, ReprAttr, TypeLayout, GenericTLData, - } + type_layout::{GenericTLData, MonoTLData, MonoTypeLayout, ReprAttr, TypeLayout}, }; #[macro_use] @@ -22,7 +20,7 @@ mod stable_abi_impls; #[derive(StableAbi)] pub struct SyncSend; -const _: () = zst_assert!{SyncSend}; +const _: () = zst_assert! {SyncSend}; ///////////////// @@ -31,14 +29,15 @@ pub struct UnsyncUnsend { _marker: UnsafeIgnoredType>, } -monomorphic_marker_type!{UnsyncUnsend, UnsafeIgnoredType>} +monomorphic_marker_type! {UnsyncUnsend, UnsafeIgnoredType>} impl UnsyncUnsend { /// Constructs a `UnsyncUnsend` - pub const NEW: Self = Self { _marker: UnsafeIgnoredType::NEW }; + pub const NEW: Self = Self { + _marker: UnsafeIgnoredType::NEW, + }; } - ///////////////// /// Marker type used to mark a type as being `Send + !Sync`. @@ -46,11 +45,13 @@ pub struct UnsyncSend { _marker: UnsafeIgnoredType>, } -monomorphic_marker_type!{UnsyncSend, UnsafeIgnoredType>} +monomorphic_marker_type! {UnsyncSend, UnsafeIgnoredType>} impl UnsyncSend { /// Constructs a `UnsyncSend` - pub const NEW: Self = Self { _marker: UnsafeIgnoredType::NEW }; + pub const NEW: Self = Self { + _marker: UnsafeIgnoredType::NEW, + }; } ///////////////// @@ -61,18 +62,20 @@ pub struct SyncUnsend { _marker: UnsyncUnsend, } -monomorphic_marker_type!{SyncUnsend, UnsyncUnsend} +monomorphic_marker_type! {SyncUnsend, UnsyncUnsend} impl SyncUnsend { /// Constructs a `SyncUnsend` - pub const NEW: Self = Self { _marker: UnsyncUnsend::NEW }; + pub const NEW: Self = Self { + _marker: UnsyncUnsend::NEW, + }; } -unsafe impl Sync for SyncUnsend{} +unsafe impl Sync for SyncUnsend {} ///////////////// -/// Zero-sized marker type used to signal that even though a type +/// Zero-sized marker type used to signal that even though a type /// could implement `Copy` and `Clone`, /// it is semantically an error to do so. #[repr(C)] @@ -80,14 +83,13 @@ unsafe impl Sync for SyncUnsend{} // #[sabi(debug_print)] pub struct NotCopyNotClone; -const _: () = zst_assert!{NotCopyNotClone}; +const _: () = zst_assert! {NotCopyNotClone}; ////////////////////////////////////////////////////////////// - /// Used by vtables/pointers to signal that the type has been erased. /// -pub struct ErasedObject{ +pub struct ErasedObject { _marker: NonOwningPhantom, } @@ -123,7 +125,7 @@ mod _sabi_erasedobject { None, )), generics: abi_stable ::tl_genparams !( - ; + ; __StartLen :: new(0u16, 0u16) ; __StartLen :: new(0u16, 0u16) ), @@ -156,7 +158,7 @@ mod _sabi_erasedobject { { type IsNonZeroType = __sabi_re::False; const LAYOUT: &'static __sabi_re::TypeLayout = { - zst_assert!{Self} + zst_assert! {Self} &__sabi_re::TypeLayout::from_derive::(__sabi_re::_private_TypeLayoutDerive { shared_vars: Self::__SABI_SHARED_VARS, @@ -170,14 +172,11 @@ mod _sabi_erasedobject { } } - - ////////////////////////////////////////////////////////////// - /// Used by pointers to vtables/modules to signal that the type has been erased. /// -pub struct ErasedPrefix{ +pub struct ErasedPrefix { _priv: PhantomData, } @@ -194,8 +193,6 @@ unsafe impl PrefixStableAbi for ErasedPrefix { ////////////////////////////////////////////////////////////// - - /** MarkerType which ignores its type parameter in its [`StableAbi`] implementation. @@ -210,46 +207,44 @@ since the type parameter is ignored when type checking dynamic libraries. [`StableAbi`]: ../trait.StableAbi.html */ -pub struct UnsafeIgnoredType { +pub struct UnsafeIgnoredType { _inner: PhantomData, } -impl UnsafeIgnoredType{ +impl UnsafeIgnoredType { /// Constructs an `UnsafeIgnoredType`. - pub const DEFAULT:Self=Self{ - _inner:PhantomData, + pub const DEFAULT: Self = Self { + _inner: PhantomData, }; /// Constructs an `UnsafeIgnoredType`. - pub const NEW:Self=Self{ - _inner:PhantomData, + pub const NEW: Self = Self { + _inner: PhantomData, }; } -impl Copy for UnsafeIgnoredType{} +impl Copy for UnsafeIgnoredType {} -impl Default for UnsafeIgnoredType{ - fn default()->Self{ +impl Default for UnsafeIgnoredType { + fn default() -> Self { Self::DEFAULT } } -impl Clone for UnsafeIgnoredType{ - fn clone(&self)->Self{ +impl Clone for UnsafeIgnoredType { + fn clone(&self) -> Self { *self } } - - unsafe impl GetStaticEquivalent_ for UnsafeIgnoredType { - type StaticEquivalent=(); + type StaticEquivalent = (); } unsafe impl StableAbi for UnsafeIgnoredType { type IsNonZeroType = False; const LAYOUT: &'static TypeLayout = { - const MONO_TYPE_LAYOUT:&MonoTypeLayout=&MonoTypeLayout::new( + const MONO_TYPE_LAYOUT: &MonoTypeLayout = &MonoTypeLayout::new( *mono_shared_vars, rstr!("UnsafeIgnoredType"), make_item_info!(), @@ -260,7 +255,7 @@ unsafe impl StableAbi for UnsafeIgnoredType { rslice![], ); - make_shared_vars!{ + make_shared_vars! { impl[T] UnsafeIgnoredType; let (mono_shared_vars,shared_vars)={}; @@ -277,60 +272,58 @@ unsafe impl StableAbi for UnsafeIgnoredType { }; } - ////////////////////////////////////////////////////////////// /// An ffi-safe equivalent of a `PhantomDataT>` -pub struct NonOwningPhantom{ +pub struct NonOwningPhantom { // The StableAbi layout for a `NonOwningPhantom` is the same as `PhantomData`, // the type of this field is purely for variance. - _marker: PhantomDataT> + _marker: PhantomData T>, } -impl NonOwningPhantom{ +impl NonOwningPhantom { /// Constructs a `NonOwningPhantom` - pub const DEFAULT:Self=Self{ - _marker:PhantomData, + pub const DEFAULT: Self = Self { + _marker: PhantomData, }; /// Constructs a `NonOwningPhantom` - pub const NEW:Self=Self{ - _marker:PhantomData, + pub const NEW: Self = Self { + _marker: PhantomData, }; } -impl Copy for NonOwningPhantom{} +impl Copy for NonOwningPhantom {} -impl Default for NonOwningPhantom{ +impl Default for NonOwningPhantom { #[inline(always)] - fn default()->Self{ + fn default() -> Self { Self::DEFAULT } } -impl Clone for NonOwningPhantom{ +impl Clone for NonOwningPhantom { #[inline(always)] - fn clone(&self)->Self{ + fn clone(&self) -> Self { *self } } -unsafe impl GetStaticEquivalent_ for NonOwningPhantom +unsafe impl GetStaticEquivalent_ for NonOwningPhantom where - PhantomData:GetStaticEquivalent_ + PhantomData: GetStaticEquivalent_, { - type StaticEquivalent=GetStaticEquivalent>; + type StaticEquivalent = GetStaticEquivalent>; } -unsafe impl StableAbi for NonOwningPhantom +unsafe impl StableAbi for NonOwningPhantom where - PhantomData:StableAbi + PhantomData: StableAbi, { type IsNonZeroType = False; - const LAYOUT: &'static TypeLayout = { - zst_assert!(Self); + zst_assert!(Self); as StableAbi>::LAYOUT }; } diff --git a/abi_stable/src/marker_type/stable_abi_impls.rs b/abi_stable/src/marker_type/stable_abi_impls.rs index 739110c1..33102a9a 100644 --- a/abi_stable/src/marker_type/stable_abi_impls.rs +++ b/abi_stable/src/marker_type/stable_abi_impls.rs @@ -3,11 +3,12 @@ macro_rules! monomorphic_marker_type { ($name:ident, $field:ty) => { #[allow(non_upper_case_globals)] - const _: () = {monomorphic_marker_type!{@inner $name, $field}}; + const _: () = { + monomorphic_marker_type! {@inner $name, $field} + }; }; (@inner $name:ident, $field:ty) => { - const _item_info_const_: abi_stable::type_layout::ItemInfo = - abi_stable::make_item_info!(); + const _item_info_const_: abi_stable::type_layout::ItemInfo = abi_stable::make_item_info!(); const _SHARED_VARS_STRINGS_: ::abi_stable::std_types::RStr<'static> = abi_stable::std_types::RStr::from_str("_marker;"); @@ -26,12 +27,12 @@ macro_rules! monomorphic_marker_type { None, )), generics: abi_stable :: - tl_genparams ! - (; __StartLen :: new(0u16, 0u16) ; __StartLen :: - new(0u16, 0u16)), - mod_refl_mode: __ModReflMode::Opaque, - repr_attr: __ReprAttr::C, - phantom_fields: abi_stable::std_types::RSlice::from_slice(&[]), + tl_genparams ! + (; __StartLen :: new(0u16, 0u16) ; __StartLen :: + new(0u16, 0u16)), + mod_refl_mode: __ModReflMode::Opaque, + repr_attr: __ReprAttr::C, + phantom_fields: abi_stable::std_types::RSlice::from_slice(&[]), shared_vars: abi_stable::type_layout::MonoSharedVars::new( _SHARED_VARS_STRINGS_, abi_stable::std_types::RSlice::from_slice(&[]), @@ -52,7 +53,7 @@ macro_rules! monomorphic_marker_type { unsafe impl __sabi_re::StableAbi for $name { type IsNonZeroType = __sabi_re::False; const LAYOUT: &'static __sabi_re::TypeLayout = { - zst_assert!{Self} + zst_assert! {Self} &__sabi_re::TypeLayout::from_derive::(__sabi_re::_private_TypeLayoutDerive { shared_vars: Self::__SABI_SHARED_VARS, @@ -66,9 +67,3 @@ macro_rules! monomorphic_marker_type { } }; } - - - - - - diff --git a/abi_stable/src/misc_tests.rs b/abi_stable/src/misc_tests.rs index 1d13338b..7dece3d0 100644 --- a/abi_stable/src/misc_tests.rs +++ b/abi_stable/src/misc_tests.rs @@ -1,6 +1,5 @@ // include!(concat!(env!("OUT_DIR"), "/skeptic-tests.rs")); - mod impl_interfacetype_attr; mod impl_interfacetype_macro; diff --git a/abi_stable/src/misc_tests/impl_interfacetype_attr.rs b/abi_stable/src/misc_tests/impl_interfacetype_attr.rs index 4b76c7d0..c5be47a2 100644 --- a/abi_stable/src/misc_tests/impl_interfacetype_attr.rs +++ b/abi_stable/src/misc_tests/impl_interfacetype_attr.rs @@ -1,339 +1,321 @@ use std::marker::PhantomData; use crate::{ - GetStaticEquivalent, - StableAbi, - InterfaceType, - type_level::{ - impl_enum::{Implemented,Unimplemented} - }, + type_level::impl_enum::{Implemented, Unimplemented}, + GetStaticEquivalent, InterfaceType, StableAbi, }; - //////////////////////////////////////////////////////////////////////////////// - #[repr(C)] #[derive(StableAbi)] #[sabi(impl_InterfaceType( - Send,Sync,Clone,Default, - Display,Debug,Serialize,Deserialize, - Eq,PartialEq,Ord,PartialOrd,Hash, - Iterator,DoubleEndedIterator, + Send, + Sync, + Clone, + Default, + Display, + Debug, + Serialize, + Deserialize, + Eq, + PartialEq, + Ord, + PartialOrd, + Hash, + Iterator, + DoubleEndedIterator, FmtWrite, - IoWrite,IoSeek,IoRead,IoBufRead,Error + IoWrite, + IoSeek, + IoRead, + IoBufRead, + Error ))] pub struct AllTraitsImpld; #[test] -fn assert_all_traits_impld(){ - let _:::Send =Implemented::NEW; - let _:::Sync =Implemented::NEW; - let _:::Clone =Implemented::NEW; - let _:::Default =Implemented::NEW; - let _:::Display =Implemented::NEW; - let _:::Debug =Implemented::NEW; - let _:::Serialize =Implemented::NEW; - let _:::Deserialize =Implemented::NEW; - let _:::Eq =Implemented::NEW; - let _:::PartialEq =Implemented::NEW; - let _:::Ord =Implemented::NEW; - let _:::PartialOrd =Implemented::NEW; - let _:::Hash =Implemented::NEW; - let _:::Iterator =Implemented::NEW; - let _:::DoubleEndedIterator=Implemented::NEW; - let _:::FmtWrite =Implemented::NEW; - let _:::IoWrite =Implemented::NEW; - let _:::IoSeek =Implemented::NEW; - let _:::IoRead =Implemented::NEW; - let _:::IoBufRead =Implemented::NEW; - let _:::Error =Implemented::NEW; +fn assert_all_traits_impld() { + let _: ::Send = Implemented::NEW; + let _: ::Sync = Implemented::NEW; + let _: ::Clone = Implemented::NEW; + let _: ::Default = Implemented::NEW; + let _: ::Display = Implemented::NEW; + let _: ::Debug = Implemented::NEW; + let _: ::Serialize = Implemented::NEW; + let _: ::Deserialize = Implemented::NEW; + let _: ::Eq = Implemented::NEW; + let _: ::PartialEq = Implemented::NEW; + let _: ::Ord = Implemented::NEW; + let _: ::PartialOrd = Implemented::NEW; + let _: ::Hash = Implemented::NEW; + let _: ::Iterator = Implemented::NEW; + let _: ::DoubleEndedIterator = Implemented::NEW; + let _: ::FmtWrite = Implemented::NEW; + let _: ::IoWrite = Implemented::NEW; + let _: ::IoSeek = Implemented::NEW; + let _: ::IoRead = Implemented::NEW; + let _: ::IoBufRead = Implemented::NEW; + let _: ::Error = Implemented::NEW; } - //////////////////////////////////////////////////////////////////////////////// - - #[repr(C)] #[derive(StableAbi)] // #[sabi(debug_print)] #[sabi(impl_InterfaceType())] pub struct NoTraitsImpld(PhantomData); - #[test] -fn assert_all_traits_unimpld(){ - let _: as InterfaceType>::Send =Unimplemented::NEW; - let _: as InterfaceType>::Sync =Unimplemented::NEW; - let _: as InterfaceType>::Clone =Unimplemented::NEW; - let _: as InterfaceType>::Default =Unimplemented::NEW; - let _: as InterfaceType>::Display =Unimplemented::NEW; - let _: as InterfaceType>::Debug =Unimplemented::NEW; - let _: as InterfaceType>::Serialize =Unimplemented::NEW; - let _: as InterfaceType>::Deserialize =Unimplemented::NEW; - let _: as InterfaceType>::Eq =Unimplemented::NEW; - let _: as InterfaceType>::PartialEq =Unimplemented::NEW; - let _: as InterfaceType>::Ord =Unimplemented::NEW; - let _: as InterfaceType>::PartialOrd =Unimplemented::NEW; - let _: as InterfaceType>::Hash =Unimplemented::NEW; - let _: as InterfaceType>::Iterator =Unimplemented::NEW; - let _: as InterfaceType>::DoubleEndedIterator=Unimplemented::NEW; - let _: as InterfaceType>::FmtWrite =Unimplemented::NEW; - let _: as InterfaceType>::IoWrite =Unimplemented::NEW; - let _: as InterfaceType>::IoSeek =Unimplemented::NEW; - let _: as InterfaceType>::IoRead =Unimplemented::NEW; - let _: as InterfaceType>::IoBufRead =Unimplemented::NEW; - let _: as InterfaceType>::Error =Unimplemented::NEW; +fn assert_all_traits_unimpld() { + let _: as InterfaceType>::Send = Unimplemented::NEW; + let _: as InterfaceType>::Sync = Unimplemented::NEW; + let _: as InterfaceType>::Clone = Unimplemented::NEW; + let _: as InterfaceType>::Default = Unimplemented::NEW; + let _: as InterfaceType>::Display = Unimplemented::NEW; + let _: as InterfaceType>::Debug = Unimplemented::NEW; + let _: as InterfaceType>::Serialize = Unimplemented::NEW; + let _: as InterfaceType>::Deserialize = Unimplemented::NEW; + let _: as InterfaceType>::Eq = Unimplemented::NEW; + let _: as InterfaceType>::PartialEq = Unimplemented::NEW; + let _: as InterfaceType>::Ord = Unimplemented::NEW; + let _: as InterfaceType>::PartialOrd = Unimplemented::NEW; + let _: as InterfaceType>::Hash = Unimplemented::NEW; + let _: as InterfaceType>::Iterator = Unimplemented::NEW; + let _: as InterfaceType>::DoubleEndedIterator = Unimplemented::NEW; + let _: as InterfaceType>::FmtWrite = Unimplemented::NEW; + let _: as InterfaceType>::IoWrite = Unimplemented::NEW; + let _: as InterfaceType>::IoSeek = Unimplemented::NEW; + let _: as InterfaceType>::IoRead = Unimplemented::NEW; + let _: as InterfaceType>::IoBufRead = Unimplemented::NEW; + let _: as InterfaceType>::Error = Unimplemented::NEW; } - //////////////////////////////////////////////////////////////////////////////// - #[repr(C)] #[derive(GetStaticEquivalent)] -#[sabi(impl_InterfaceType(Debug,Display))] +#[sabi(impl_InterfaceType(Debug, Display))] pub struct FmtInterface(PhantomData) -where T:std::fmt::Debug; - +where + T: std::fmt::Debug; #[test] -fn assert_fmt_traits_impld(){ - let _: as InterfaceType>::Send =Unimplemented::NEW; - let _: as InterfaceType>::Sync =Unimplemented::NEW; - let _: as InterfaceType>::Clone =Unimplemented::NEW; - let _: as InterfaceType>::Default =Unimplemented::NEW; - let _: as InterfaceType>::Display =Implemented::NEW; - let _: as InterfaceType>::Debug =Implemented::NEW; - let _: as InterfaceType>::Serialize =Unimplemented::NEW; - let _: as InterfaceType>::Deserialize =Unimplemented::NEW; - let _: as InterfaceType>::Eq =Unimplemented::NEW; - let _: as InterfaceType>::PartialEq =Unimplemented::NEW; - let _: as InterfaceType>::Ord =Unimplemented::NEW; - let _: as InterfaceType>::PartialOrd =Unimplemented::NEW; - let _: as InterfaceType>::Hash =Unimplemented::NEW; - let _: as InterfaceType>::Iterator =Unimplemented::NEW; - let _: as InterfaceType>::DoubleEndedIterator=Unimplemented::NEW; - let _: as InterfaceType>::FmtWrite =Unimplemented::NEW; - let _: as InterfaceType>::IoWrite =Unimplemented::NEW; - let _: as InterfaceType>::IoSeek =Unimplemented::NEW; - let _: as InterfaceType>::IoRead =Unimplemented::NEW; - let _: as InterfaceType>::IoBufRead =Unimplemented::NEW; - let _: as InterfaceType>::Error =Unimplemented::NEW; +fn assert_fmt_traits_impld() { + let _: as InterfaceType>::Send = Unimplemented::NEW; + let _: as InterfaceType>::Sync = Unimplemented::NEW; + let _: as InterfaceType>::Clone = Unimplemented::NEW; + let _: as InterfaceType>::Default = Unimplemented::NEW; + let _: as InterfaceType>::Display = Implemented::NEW; + let _: as InterfaceType>::Debug = Implemented::NEW; + let _: as InterfaceType>::Serialize = Unimplemented::NEW; + let _: as InterfaceType>::Deserialize = Unimplemented::NEW; + let _: as InterfaceType>::Eq = Unimplemented::NEW; + let _: as InterfaceType>::PartialEq = Unimplemented::NEW; + let _: as InterfaceType>::Ord = Unimplemented::NEW; + let _: as InterfaceType>::PartialOrd = Unimplemented::NEW; + let _: as InterfaceType>::Hash = Unimplemented::NEW; + let _: as InterfaceType>::Iterator = Unimplemented::NEW; + let _: as InterfaceType>::DoubleEndedIterator = Unimplemented::NEW; + let _: as InterfaceType>::FmtWrite = Unimplemented::NEW; + let _: as InterfaceType>::IoWrite = Unimplemented::NEW; + let _: as InterfaceType>::IoSeek = Unimplemented::NEW; + let _: as InterfaceType>::IoRead = Unimplemented::NEW; + let _: as InterfaceType>::IoBufRead = Unimplemented::NEW; + let _: as InterfaceType>::Error = Unimplemented::NEW; } - //////////////////////////////////////////////////////////////////////////////// - #[repr(C)] #[derive(GetStaticEquivalent)] -#[sabi(impl_InterfaceType(Hash,Ord))] +#[sabi(impl_InterfaceType(Hash, Ord))] pub struct HashOrdInterface(PhantomData) -where T:std::fmt::Debug; - +where + T: std::fmt::Debug; #[test] -fn assert_hash_ord_impld(){ - let _: as InterfaceType>::Send =Unimplemented::NEW; - let _: as InterfaceType>::Sync =Unimplemented::NEW; - let _: as InterfaceType>::Clone =Unimplemented::NEW; - let _: as InterfaceType>::Default =Unimplemented::NEW; - let _: as InterfaceType>::Display =Unimplemented::NEW; - let _: as InterfaceType>::Debug =Unimplemented::NEW; - let _: as InterfaceType>::Serialize =Unimplemented::NEW; - let _: as InterfaceType>::Deserialize =Unimplemented::NEW; - let _: as InterfaceType>::Eq =Implemented::NEW; - let _: as InterfaceType>::PartialEq =Implemented::NEW; - let _: as InterfaceType>::Ord =Implemented::NEW; - let _: as InterfaceType>::PartialOrd =Implemented::NEW; - let _: as InterfaceType>::Hash =Implemented::NEW; - let _: as InterfaceType>::Iterator =Unimplemented::NEW; - let _: as InterfaceType>::DoubleEndedIterator=Unimplemented::NEW; - let _: as InterfaceType>::FmtWrite =Unimplemented::NEW; - let _: as InterfaceType>::IoWrite =Unimplemented::NEW; - let _: as InterfaceType>::IoSeek =Unimplemented::NEW; - let _: as InterfaceType>::IoRead =Unimplemented::NEW; - let _: as InterfaceType>::IoBufRead =Unimplemented::NEW; - let _: as InterfaceType>::Error =Unimplemented::NEW; +fn assert_hash_ord_impld() { + let _: as InterfaceType>::Send = Unimplemented::NEW; + let _: as InterfaceType>::Sync = Unimplemented::NEW; + let _: as InterfaceType>::Clone = Unimplemented::NEW; + let _: as InterfaceType>::Default = Unimplemented::NEW; + let _: as InterfaceType>::Display = Unimplemented::NEW; + let _: as InterfaceType>::Debug = Unimplemented::NEW; + let _: as InterfaceType>::Serialize = Unimplemented::NEW; + let _: as InterfaceType>::Deserialize = Unimplemented::NEW; + let _: as InterfaceType>::Eq = Implemented::NEW; + let _: as InterfaceType>::PartialEq = Implemented::NEW; + let _: as InterfaceType>::Ord = Implemented::NEW; + let _: as InterfaceType>::PartialOrd = Implemented::NEW; + let _: as InterfaceType>::Hash = Implemented::NEW; + let _: as InterfaceType>::Iterator = Unimplemented::NEW; + let _: as InterfaceType>::DoubleEndedIterator = Unimplemented::NEW; + let _: as InterfaceType>::FmtWrite = Unimplemented::NEW; + let _: as InterfaceType>::IoWrite = Unimplemented::NEW; + let _: as InterfaceType>::IoSeek = Unimplemented::NEW; + let _: as InterfaceType>::IoRead = Unimplemented::NEW; + let _: as InterfaceType>::IoBufRead = Unimplemented::NEW; + let _: as InterfaceType>::Error = Unimplemented::NEW; } - - //////////////////////////////////////////////////////////////////////////////// - - #[repr(C)] #[derive(GetStaticEquivalent)] #[sabi(impl_InterfaceType(Eq))] pub struct OnlyEq; #[test] -fn assert_only_eq(){ - let _:::Send =Unimplemented::NEW; - let _:::Sync =Unimplemented::NEW; - let _:::Clone =Unimplemented::NEW; - let _:::Default =Unimplemented::NEW; - let _:::Display =Unimplemented::NEW; - let _:::Debug =Unimplemented::NEW; - let _:::Serialize =Unimplemented::NEW; - let _:::Deserialize =Unimplemented::NEW; - let _:::Eq =Implemented::NEW; - let _:::PartialEq =Implemented::NEW; - let _:::Ord =Unimplemented::NEW; - let _:::PartialOrd =Unimplemented::NEW; - let _:::Hash =Unimplemented::NEW; - let _:::Iterator =Unimplemented::NEW; - let _:::DoubleEndedIterator=Unimplemented::NEW; - let _:::FmtWrite =Unimplemented::NEW; - let _:::IoWrite =Unimplemented::NEW; - let _:::IoSeek =Unimplemented::NEW; - let _:::IoRead =Unimplemented::NEW; - let _:::IoBufRead =Unimplemented::NEW; - let _:::Error =Unimplemented::NEW; +fn assert_only_eq() { + let _: ::Send = Unimplemented::NEW; + let _: ::Sync = Unimplemented::NEW; + let _: ::Clone = Unimplemented::NEW; + let _: ::Default = Unimplemented::NEW; + let _: ::Display = Unimplemented::NEW; + let _: ::Debug = Unimplemented::NEW; + let _: ::Serialize = Unimplemented::NEW; + let _: ::Deserialize = Unimplemented::NEW; + let _: ::Eq = Implemented::NEW; + let _: ::PartialEq = Implemented::NEW; + let _: ::Ord = Unimplemented::NEW; + let _: ::PartialOrd = Unimplemented::NEW; + let _: ::Hash = Unimplemented::NEW; + let _: ::Iterator = Unimplemented::NEW; + let _: ::DoubleEndedIterator = Unimplemented::NEW; + let _: ::FmtWrite = Unimplemented::NEW; + let _: ::IoWrite = Unimplemented::NEW; + let _: ::IoSeek = Unimplemented::NEW; + let _: ::IoRead = Unimplemented::NEW; + let _: ::IoBufRead = Unimplemented::NEW; + let _: ::Error = Unimplemented::NEW; } - //////////////////////////////////////////////////////////////////////////////// - - #[repr(C)] #[derive(GetStaticEquivalent)] #[sabi(impl_InterfaceType(PartialOrd))] pub struct OnlyPartialOrd; #[test] -fn assert_only_partial_ord(){ - let _:::Send =Unimplemented::NEW; - let _:::Sync =Unimplemented::NEW; - let _:::Clone =Unimplemented::NEW; - let _:::Default =Unimplemented::NEW; - let _:::Display =Unimplemented::NEW; - let _:::Debug =Unimplemented::NEW; - let _:::Serialize =Unimplemented::NEW; - let _:::Deserialize =Unimplemented::NEW; - let _:::Eq =Unimplemented::NEW; - let _:::PartialEq =Implemented::NEW; - let _:::Ord =Unimplemented::NEW; - let _:::PartialOrd =Implemented::NEW; - let _:::Hash =Unimplemented::NEW; - let _:::Iterator =Unimplemented::NEW; - let _:::DoubleEndedIterator=Unimplemented::NEW; - let _:::FmtWrite =Unimplemented::NEW; - let _:::IoWrite =Unimplemented::NEW; - let _:::IoSeek =Unimplemented::NEW; - let _:::IoRead =Unimplemented::NEW; - let _:::IoBufRead =Unimplemented::NEW; - let _:::Error =Unimplemented::NEW; +fn assert_only_partial_ord() { + let _: ::Send = Unimplemented::NEW; + let _: ::Sync = Unimplemented::NEW; + let _: ::Clone = Unimplemented::NEW; + let _: ::Default = Unimplemented::NEW; + let _: ::Display = Unimplemented::NEW; + let _: ::Debug = Unimplemented::NEW; + let _: ::Serialize = Unimplemented::NEW; + let _: ::Deserialize = Unimplemented::NEW; + let _: ::Eq = Unimplemented::NEW; + let _: ::PartialEq = Implemented::NEW; + let _: ::Ord = Unimplemented::NEW; + let _: ::PartialOrd = Implemented::NEW; + let _: ::Hash = Unimplemented::NEW; + let _: ::Iterator = Unimplemented::NEW; + let _: ::DoubleEndedIterator = Unimplemented::NEW; + let _: ::FmtWrite = Unimplemented::NEW; + let _: ::IoWrite = Unimplemented::NEW; + let _: ::IoSeek = Unimplemented::NEW; + let _: ::IoRead = Unimplemented::NEW; + let _: ::IoBufRead = Unimplemented::NEW; + let _: ::Error = Unimplemented::NEW; } - //////////////////////////////////////////////////////////////////////////////// - - #[repr(C)] #[derive(GetStaticEquivalent)] #[sabi(impl_InterfaceType(Error))] pub struct OnlyError; #[test] -fn assert_only_error(){ - let _:::Send =Unimplemented::NEW; - let _:::Sync =Unimplemented::NEW; - let _:::Clone =Unimplemented::NEW; - let _:::Default =Unimplemented::NEW; - let _:::Display =Implemented::NEW; - let _:::Debug =Implemented::NEW; - let _:::Serialize =Unimplemented::NEW; - let _:::Deserialize =Unimplemented::NEW; - let _:::Eq =Unimplemented::NEW; - let _:::PartialEq =Unimplemented::NEW; - let _:::Ord =Unimplemented::NEW; - let _:::PartialOrd =Unimplemented::NEW; - let _:::Hash =Unimplemented::NEW; - let _:::Iterator =Unimplemented::NEW; - let _:::DoubleEndedIterator=Unimplemented::NEW; - let _:::FmtWrite =Unimplemented::NEW; - let _:::IoWrite =Unimplemented::NEW; - let _:::IoSeek =Unimplemented::NEW; - let _:::IoRead =Unimplemented::NEW; - let _:::IoBufRead =Unimplemented::NEW; - let _:::Error =Implemented::NEW; +fn assert_only_error() { + let _: ::Send = Unimplemented::NEW; + let _: ::Sync = Unimplemented::NEW; + let _: ::Clone = Unimplemented::NEW; + let _: ::Default = Unimplemented::NEW; + let _: ::Display = Implemented::NEW; + let _: ::Debug = Implemented::NEW; + let _: ::Serialize = Unimplemented::NEW; + let _: ::Deserialize = Unimplemented::NEW; + let _: ::Eq = Unimplemented::NEW; + let _: ::PartialEq = Unimplemented::NEW; + let _: ::Ord = Unimplemented::NEW; + let _: ::PartialOrd = Unimplemented::NEW; + let _: ::Hash = Unimplemented::NEW; + let _: ::Iterator = Unimplemented::NEW; + let _: ::DoubleEndedIterator = Unimplemented::NEW; + let _: ::FmtWrite = Unimplemented::NEW; + let _: ::IoWrite = Unimplemented::NEW; + let _: ::IoSeek = Unimplemented::NEW; + let _: ::IoRead = Unimplemented::NEW; + let _: ::IoBufRead = Unimplemented::NEW; + let _: ::Error = Implemented::NEW; } - - //////////////////////////////////////////////////////////////////////////////// - - #[repr(C)] #[derive(GetStaticEquivalent)] #[sabi(impl_InterfaceType(Iterator))] pub struct OnlyIter; #[test] -fn assert_only_iter(){ - let _:::Send =Unimplemented::NEW; - let _:::Sync =Unimplemented::NEW; - let _:::Clone =Unimplemented::NEW; - let _:::Default =Unimplemented::NEW; - let _:::Display =Unimplemented::NEW; - let _:::Debug =Unimplemented::NEW; - let _:::Serialize =Unimplemented::NEW; - let _:::Deserialize =Unimplemented::NEW; - let _:::Eq =Unimplemented::NEW; - let _:::PartialEq =Unimplemented::NEW; - let _:::Ord =Unimplemented::NEW; - let _:::PartialOrd =Unimplemented::NEW; - let _:::Hash =Unimplemented::NEW; - let _:::Iterator =Implemented::NEW; - let _:::DoubleEndedIterator=Unimplemented::NEW; - let _:::FmtWrite =Unimplemented::NEW; - let _:::IoWrite =Unimplemented::NEW; - let _:::IoSeek =Unimplemented::NEW; - let _:::IoRead =Unimplemented::NEW; - let _:::IoBufRead =Unimplemented::NEW; - let _:::Error =Unimplemented::NEW; +fn assert_only_iter() { + let _: ::Send = Unimplemented::NEW; + let _: ::Sync = Unimplemented::NEW; + let _: ::Clone = Unimplemented::NEW; + let _: ::Default = Unimplemented::NEW; + let _: ::Display = Unimplemented::NEW; + let _: ::Debug = Unimplemented::NEW; + let _: ::Serialize = Unimplemented::NEW; + let _: ::Deserialize = Unimplemented::NEW; + let _: ::Eq = Unimplemented::NEW; + let _: ::PartialEq = Unimplemented::NEW; + let _: ::Ord = Unimplemented::NEW; + let _: ::PartialOrd = Unimplemented::NEW; + let _: ::Hash = Unimplemented::NEW; + let _: ::Iterator = Implemented::NEW; + let _: ::DoubleEndedIterator = Unimplemented::NEW; + let _: ::FmtWrite = Unimplemented::NEW; + let _: ::IoWrite = Unimplemented::NEW; + let _: ::IoSeek = Unimplemented::NEW; + let _: ::IoRead = Unimplemented::NEW; + let _: ::IoBufRead = Unimplemented::NEW; + let _: ::Error = Unimplemented::NEW; } - //////////////////////////////////////////////////////////////////////////////// - - #[repr(C)] #[derive(GetStaticEquivalent)] #[sabi(impl_InterfaceType(DoubleEndedIterator))] pub struct OnlyDEIter; #[test] -fn assert_only_de_iter(){ - let _:::Send =Unimplemented::NEW; - let _:::Sync =Unimplemented::NEW; - let _:::Clone =Unimplemented::NEW; - let _:::Default =Unimplemented::NEW; - let _:::Display =Unimplemented::NEW; - let _:::Debug =Unimplemented::NEW; - let _:::Serialize =Unimplemented::NEW; - let _:::Deserialize =Unimplemented::NEW; - let _:::Eq =Unimplemented::NEW; - let _:::PartialEq =Unimplemented::NEW; - let _:::Ord =Unimplemented::NEW; - let _:::PartialOrd =Unimplemented::NEW; - let _:::Hash =Unimplemented::NEW; - let _:::Iterator =Implemented::NEW; - let _:::DoubleEndedIterator=Implemented::NEW; - let _:::FmtWrite =Unimplemented::NEW; - let _:::IoWrite =Unimplemented::NEW; - let _:::IoSeek =Unimplemented::NEW; - let _:::IoRead =Unimplemented::NEW; - let _:::IoBufRead =Unimplemented::NEW; - let _:::Error =Unimplemented::NEW; +fn assert_only_de_iter() { + let _: ::Send = Unimplemented::NEW; + let _: ::Sync = Unimplemented::NEW; + let _: ::Clone = Unimplemented::NEW; + let _: ::Default = Unimplemented::NEW; + let _: ::Display = Unimplemented::NEW; + let _: ::Debug = Unimplemented::NEW; + let _: ::Serialize = Unimplemented::NEW; + let _: ::Deserialize = Unimplemented::NEW; + let _: ::Eq = Unimplemented::NEW; + let _: ::PartialEq = Unimplemented::NEW; + let _: ::Ord = Unimplemented::NEW; + let _: ::PartialOrd = Unimplemented::NEW; + let _: ::Hash = Unimplemented::NEW; + let _: ::Iterator = Implemented::NEW; + let _: ::DoubleEndedIterator = Implemented::NEW; + let _: ::FmtWrite = Unimplemented::NEW; + let _: ::IoWrite = Unimplemented::NEW; + let _: ::IoSeek = Unimplemented::NEW; + let _: ::IoRead = Unimplemented::NEW; + let _: ::IoBufRead = Unimplemented::NEW; + let _: ::Error = Unimplemented::NEW; } - - diff --git a/abi_stable/src/misc_tests/impl_interfacetype_macro.rs b/abi_stable/src/misc_tests/impl_interfacetype_macro.rs index d826fc5c..1f25c9b7 100644 --- a/abi_stable/src/misc_tests/impl_interfacetype_macro.rs +++ b/abi_stable/src/misc_tests/impl_interfacetype_macro.rs @@ -1,26 +1,19 @@ -use std::{ - fmt::Debug, - marker::PhantomData, -}; +use std::{fmt::Debug, marker::PhantomData}; use crate::{ - GetStaticEquivalent, - StableAbi, - InterfaceType, impl_InterfaceType, type_level::{ - impl_enum::{Implemented,Unimplemented}, - bools::{False,True}, + bools::{False, True}, + impl_enum::{Implemented, Unimplemented}, }, + GetStaticEquivalent, InterfaceType, StableAbi, }; - #[repr(C)] #[derive(StableAbi)] pub struct AllTraitsImpld; - -impl_InterfaceType!{ +impl_InterfaceType! { impl InterfaceType for AllTraitsImpld{ // type Send=True; // These are True by default // type Sync=True; // These are True by default @@ -46,40 +39,36 @@ impl_InterfaceType!{ } } - #[test] -fn assert_all_traits_impld(){ - let _:::Send =Implemented::NEW; - let _:::Sync =Implemented::NEW; - let _:::Clone =Implemented::NEW; - let _:::Default =Implemented::NEW; - let _:::Display =Implemented::NEW; - let _:::Debug =Implemented::NEW; - let _:::Serialize =Implemented::NEW; - let _:::Deserialize =Implemented::NEW; - let _:::Eq =Implemented::NEW; - let _:::PartialEq =Implemented::NEW; - let _:::Ord =Implemented::NEW; - let _:::PartialOrd =Implemented::NEW; - let _:::Hash =Implemented::NEW; - let _:::Iterator =Implemented::NEW; - let _:::DoubleEndedIterator=Implemented::NEW; - let _:::FmtWrite =Implemented::NEW; - let _:::IoWrite =Implemented::NEW; - let _:::IoSeek =Implemented::NEW; - let _:::IoRead =Implemented::NEW; - let _:::IoBufRead =Implemented::NEW; - let _:::Error =Implemented::NEW; +fn assert_all_traits_impld() { + let _: ::Send = Implemented::NEW; + let _: ::Sync = Implemented::NEW; + let _: ::Clone = Implemented::NEW; + let _: ::Default = Implemented::NEW; + let _: ::Display = Implemented::NEW; + let _: ::Debug = Implemented::NEW; + let _: ::Serialize = Implemented::NEW; + let _: ::Deserialize = Implemented::NEW; + let _: ::Eq = Implemented::NEW; + let _: ::PartialEq = Implemented::NEW; + let _: ::Ord = Implemented::NEW; + let _: ::PartialOrd = Implemented::NEW; + let _: ::Hash = Implemented::NEW; + let _: ::Iterator = Implemented::NEW; + let _: ::DoubleEndedIterator = Implemented::NEW; + let _: ::FmtWrite = Implemented::NEW; + let _: ::IoWrite = Implemented::NEW; + let _: ::IoSeek = Implemented::NEW; + let _: ::IoRead = Implemented::NEW; + let _: ::IoBufRead = Implemented::NEW; + let _: ::Error = Implemented::NEW; } - - - #[repr(C)] #[derive(StableAbi)] pub struct NoTraitsImpld(PhantomData); -impl_InterfaceType!{ +impl_InterfaceType! { impl InterfaceType for NoTraitsImpld{ type Send=False; type Sync=False; @@ -87,39 +76,37 @@ impl_InterfaceType!{ } #[test] -fn assert_all_traits_unimpld(){ - let _: as InterfaceType>::Send =Unimplemented::NEW; - let _: as InterfaceType>::Sync =Unimplemented::NEW; - let _: as InterfaceType>::Clone =Unimplemented::NEW; - let _: as InterfaceType>::Default =Unimplemented::NEW; - let _: as InterfaceType>::Display =Unimplemented::NEW; - let _: as InterfaceType>::Debug =Unimplemented::NEW; - let _: as InterfaceType>::Serialize =Unimplemented::NEW; - let _: as InterfaceType>::Deserialize =Unimplemented::NEW; - let _: as InterfaceType>::Eq =Unimplemented::NEW; - let _: as InterfaceType>::PartialEq =Unimplemented::NEW; - let _: as InterfaceType>::Ord =Unimplemented::NEW; - let _: as InterfaceType>::PartialOrd =Unimplemented::NEW; - let _: as InterfaceType>::Hash =Unimplemented::NEW; - let _: as InterfaceType>::Iterator =Unimplemented::NEW; - let _: as InterfaceType>::DoubleEndedIterator=Unimplemented::NEW; - let _: as InterfaceType>::FmtWrite =Unimplemented::NEW; - let _: as InterfaceType>::IoWrite =Unimplemented::NEW; - let _: as InterfaceType>::IoSeek =Unimplemented::NEW; - let _: as InterfaceType>::IoRead =Unimplemented::NEW; - let _: as InterfaceType>::IoBufRead =Unimplemented::NEW; - let _: as InterfaceType>::Error =Unimplemented::NEW; +fn assert_all_traits_unimpld() { + let _: as InterfaceType>::Send = Unimplemented::NEW; + let _: as InterfaceType>::Sync = Unimplemented::NEW; + let _: as InterfaceType>::Clone = Unimplemented::NEW; + let _: as InterfaceType>::Default = Unimplemented::NEW; + let _: as InterfaceType>::Display = Unimplemented::NEW; + let _: as InterfaceType>::Debug = Unimplemented::NEW; + let _: as InterfaceType>::Serialize = Unimplemented::NEW; + let _: as InterfaceType>::Deserialize = Unimplemented::NEW; + let _: as InterfaceType>::Eq = Unimplemented::NEW; + let _: as InterfaceType>::PartialEq = Unimplemented::NEW; + let _: as InterfaceType>::Ord = Unimplemented::NEW; + let _: as InterfaceType>::PartialOrd = Unimplemented::NEW; + let _: as InterfaceType>::Hash = Unimplemented::NEW; + let _: as InterfaceType>::Iterator = Unimplemented::NEW; + let _: as InterfaceType>::DoubleEndedIterator = Unimplemented::NEW; + let _: as InterfaceType>::FmtWrite = Unimplemented::NEW; + let _: as InterfaceType>::IoWrite = Unimplemented::NEW; + let _: as InterfaceType>::IoSeek = Unimplemented::NEW; + let _: as InterfaceType>::IoRead = Unimplemented::NEW; + let _: as InterfaceType>::IoBufRead = Unimplemented::NEW; + let _: as InterfaceType>::Error = Unimplemented::NEW; } - - #[repr(C)] #[derive(GetStaticEquivalent)] pub struct FmtInterface(PhantomData) -where T:Debug; - +where + T: Debug; -impl_InterfaceType!{ +impl_InterfaceType! { impl InterfaceType for FmtInterface where T:Debug @@ -129,40 +116,38 @@ impl_InterfaceType!{ } } - #[test] -fn assert_fmt_traits_impld(){ - let _: as InterfaceType>::Send =Implemented::NEW; - let _: as InterfaceType>::Sync =Implemented::NEW; - let _: as InterfaceType>::Clone =Unimplemented::NEW; - let _: as InterfaceType>::Default =Unimplemented::NEW; - let _: as InterfaceType>::Display =Implemented::NEW; - let _: as InterfaceType>::Debug =Implemented::NEW; - let _: as InterfaceType>::Serialize =Unimplemented::NEW; - let _: as InterfaceType>::Deserialize =Unimplemented::NEW; - let _: as InterfaceType>::Eq =Unimplemented::NEW; - let _: as InterfaceType>::PartialEq =Unimplemented::NEW; - let _: as InterfaceType>::Ord =Unimplemented::NEW; - let _: as InterfaceType>::PartialOrd =Unimplemented::NEW; - let _: as InterfaceType>::Hash =Unimplemented::NEW; - let _: as InterfaceType>::Iterator =Unimplemented::NEW; - let _: as InterfaceType>::DoubleEndedIterator=Unimplemented::NEW; - let _: as InterfaceType>::FmtWrite =Unimplemented::NEW; - let _: as InterfaceType>::IoWrite =Unimplemented::NEW; - let _: as InterfaceType>::IoSeek =Unimplemented::NEW; - let _: as InterfaceType>::IoRead =Unimplemented::NEW; - let _: as InterfaceType>::IoBufRead =Unimplemented::NEW; - let _: as InterfaceType>::Error =Unimplemented::NEW; +fn assert_fmt_traits_impld() { + let _: as InterfaceType>::Send = Implemented::NEW; + let _: as InterfaceType>::Sync = Implemented::NEW; + let _: as InterfaceType>::Clone = Unimplemented::NEW; + let _: as InterfaceType>::Default = Unimplemented::NEW; + let _: as InterfaceType>::Display = Implemented::NEW; + let _: as InterfaceType>::Debug = Implemented::NEW; + let _: as InterfaceType>::Serialize = Unimplemented::NEW; + let _: as InterfaceType>::Deserialize = Unimplemented::NEW; + let _: as InterfaceType>::Eq = Unimplemented::NEW; + let _: as InterfaceType>::PartialEq = Unimplemented::NEW; + let _: as InterfaceType>::Ord = Unimplemented::NEW; + let _: as InterfaceType>::PartialOrd = Unimplemented::NEW; + let _: as InterfaceType>::Hash = Unimplemented::NEW; + let _: as InterfaceType>::Iterator = Unimplemented::NEW; + let _: as InterfaceType>::DoubleEndedIterator = Unimplemented::NEW; + let _: as InterfaceType>::FmtWrite = Unimplemented::NEW; + let _: as InterfaceType>::IoWrite = Unimplemented::NEW; + let _: as InterfaceType>::IoSeek = Unimplemented::NEW; + let _: as InterfaceType>::IoRead = Unimplemented::NEW; + let _: as InterfaceType>::IoBufRead = Unimplemented::NEW; + let _: as InterfaceType>::Error = Unimplemented::NEW; } - #[repr(C)] #[derive(GetStaticEquivalent)] pub struct HashEqInterface(PhantomData) -where T:Debug; +where + T: Debug; - -impl_InterfaceType!{ +impl_InterfaceType! { impl InterfaceType for HashEqInterface where T:Debug @@ -173,28 +158,27 @@ impl_InterfaceType!{ } } - #[test] -fn assert_hash_eq_impld(){ - let _: as InterfaceType>::Send =Implemented::NEW; - let _: as InterfaceType>::Sync =Implemented::NEW; - let _: as InterfaceType>::Clone =Unimplemented::NEW; - let _: as InterfaceType>::Default =Unimplemented::NEW; - let _: as InterfaceType>::Display =Unimplemented::NEW; - let _: as InterfaceType>::Debug =Unimplemented::NEW; - let _: as InterfaceType>::Serialize =Unimplemented::NEW; - let _: as InterfaceType>::Deserialize =Unimplemented::NEW; - let _: as InterfaceType>::Eq =Implemented::NEW; - let _: as InterfaceType>::PartialEq =Implemented::NEW; - let _: as InterfaceType>::Ord =Unimplemented::NEW; - let _: as InterfaceType>::PartialOrd =Unimplemented::NEW; - let _: as InterfaceType>::Hash =Implemented::NEW; - let _: as InterfaceType>::Iterator =Unimplemented::NEW; - let _: as InterfaceType>::DoubleEndedIterator=Unimplemented::NEW; - let _: as InterfaceType>::FmtWrite =Unimplemented::NEW; - let _: as InterfaceType>::IoWrite =Unimplemented::NEW; - let _: as InterfaceType>::IoSeek =Unimplemented::NEW; - let _: as InterfaceType>::IoRead =Unimplemented::NEW; - let _: as InterfaceType>::IoBufRead =Unimplemented::NEW; - let _: as InterfaceType>::Error =Unimplemented::NEW; -} \ No newline at end of file +fn assert_hash_eq_impld() { + let _: as InterfaceType>::Send = Implemented::NEW; + let _: as InterfaceType>::Sync = Implemented::NEW; + let _: as InterfaceType>::Clone = Unimplemented::NEW; + let _: as InterfaceType>::Default = Unimplemented::NEW; + let _: as InterfaceType>::Display = Unimplemented::NEW; + let _: as InterfaceType>::Debug = Unimplemented::NEW; + let _: as InterfaceType>::Serialize = Unimplemented::NEW; + let _: as InterfaceType>::Deserialize = Unimplemented::NEW; + let _: as InterfaceType>::Eq = Implemented::NEW; + let _: as InterfaceType>::PartialEq = Implemented::NEW; + let _: as InterfaceType>::Ord = Unimplemented::NEW; + let _: as InterfaceType>::PartialOrd = Unimplemented::NEW; + let _: as InterfaceType>::Hash = Implemented::NEW; + let _: as InterfaceType>::Iterator = Unimplemented::NEW; + let _: as InterfaceType>::DoubleEndedIterator = Unimplemented::NEW; + let _: as InterfaceType>::FmtWrite = Unimplemented::NEW; + let _: as InterfaceType>::IoWrite = Unimplemented::NEW; + let _: as InterfaceType>::IoSeek = Unimplemented::NEW; + let _: as InterfaceType>::IoRead = Unimplemented::NEW; + let _: as InterfaceType>::IoBufRead = Unimplemented::NEW; + let _: as InterfaceType>::Error = Unimplemented::NEW; +} diff --git a/abi_stable/src/multikey_map.rs b/abi_stable/src/multikey_map.rs index 9bea572f..8bb321e8 100644 --- a/abi_stable/src/multikey_map.rs +++ b/abi_stable/src/multikey_map.rs @@ -1,152 +1,144 @@ use std::{ borrow::Borrow, - collections::hash_map::{HashMap,Entry}, - cmp::{Eq,PartialEq}, - fmt::{self,Debug}, + cmp::{Eq, PartialEq}, + collections::hash_map::{Entry, HashMap}, + fmt::{self, Debug}, hash::Hash, mem, - ops::{Index,IndexMut}, + ops::{Index, IndexMut}, ptr, }; -use generational_arena::{ - Arena, - Index as ArenaIndex, -}; +use generational_arena::{Arena, Index as ArenaIndex}; use core_extensions::SelfOps; - /// A Map that maps multiple keys to the same value. /// /// Every key maps to a value,which is stored at an index. /// Indices can be used as a proxy for the value. #[derive(Clone)] -pub struct MultiKeyMap{ - map:HashMap, - arena:Arena>, +pub struct MultiKeyMap { + map: HashMap, + arena: Arena>, } -#[derive(Debug,Clone,PartialEq,Eq)] -struct MapValue{ - keys:Vec, - value:T +#[derive(Debug, Clone, PartialEq, Eq)] +struct MapValue { + keys: Vec, + value: T, } #[repr(transparent)] -#[derive(Debug,Copy,Clone,PartialEq,Eq)] -pub struct MapIndex{ - index:ArenaIndex, +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct MapIndex { + index: ArenaIndex, } - -#[derive(Debug,Copy,Clone,PartialEq,Eq)] -pub struct IndexValue{ - pub index:MapIndex, - pub value:T, +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct IndexValue { + pub index: MapIndex, + pub value: T, } - /// When the element was inserted,now or before the method call. -#[must_use="call `.into_inner()` to unwrap into the inner value."] -#[derive(Debug,Copy,Clone,PartialEq,Eq,PartialOrd,Ord,Hash)] -pub enum InsertionTime{ +#[must_use = "call `.into_inner()` to unwrap into the inner value."] +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum InsertionTime { Now(T), Before(T), } - -impl MultiKeyMap -where K:Hash+Eq +impl MultiKeyMap +where + K: Hash + Eq, { #[allow(clippy::new_without_default)] - pub fn new()->Self{ - Self{ - map:HashMap::default(), - arena:Arena::new(), + pub fn new() -> Self { + Self { + map: HashMap::default(), + arena: Arena::new(), } } - pub fn get(&self,key:&Q)->Option<&T> + pub fn get(&self, key: &Q) -> Option<&T> where K: Borrow, - Q: Hash + Eq+?Sized, + Q: Hash + Eq + ?Sized, { - let &i=self.map.get(key)?; + let &i = self.map.get(key)?; self.get_with_index(i) } - pub fn get_mut(&mut self,key:&Q)->Option<&mut T> + pub fn get_mut(&mut self, key: &Q) -> Option<&mut T> where K: Borrow, - Q: Hash + Eq+?Sized, + Q: Hash + Eq + ?Sized, { - let &i=self.map.get(key)?; + let &i = self.map.get(key)?; self.get_mut_with_index(i) } #[allow(dead_code)] - pub fn get2_mut(&mut self,key0:&Q,key1:&Q)->(Option<&mut T>,Option<&mut T>) + pub fn get2_mut(&mut self, key0: &Q, key1: &Q) -> (Option<&mut T>, Option<&mut T>) where K: Borrow, - Q: Hash + Eq+?Sized, + Q: Hash + Eq + ?Sized, { - let i0=self.map.get(key0).cloned(); - let i1=self.map.get(key1).cloned(); - - match (i0,i1) { - (None,None)=> - (None,None), - (Some(l),None)=> - (self.get_mut_with_index(l),None), - (None,Some(r))=> - (None,self.get_mut_with_index(r)), - (Some(l),Some(r))=> - self.get2_mut_with_index(l,r), + let i0 = self.map.get(key0).cloned(); + let i1 = self.map.get(key1).cloned(); + + match (i0, i1) { + (None, None) => (None, None), + (Some(l), None) => (self.get_mut_with_index(l), None), + (None, Some(r)) => (None, self.get_mut_with_index(r)), + (Some(l), Some(r)) => self.get2_mut_with_index(l, r), } } - pub fn get_index(&self,key:&Q)->Option + pub fn get_index(&self, key: &Q) -> Option where K: Borrow, - Q: Hash + Eq+?Sized, + Q: Hash + Eq + ?Sized, { self.map.get(key).cloned() } - pub fn get_with_index(&self,i:MapIndex)->Option<&T>{ - self.arena.get(i.index).map(|x| &x.value ) + pub fn get_with_index(&self, i: MapIndex) -> Option<&T> { + self.arena.get(i.index).map(|x| &x.value) } - pub fn get_mut_with_index(&mut self,i:MapIndex)->Option<&mut T>{ - self.arena.get_mut(i.index).map(|x| &mut x.value ) + pub fn get_mut_with_index(&mut self, i: MapIndex) -> Option<&mut T> { + self.arena.get_mut(i.index).map(|x| &mut x.value) } - + pub fn get2_mut_with_index( &mut self, - i0:MapIndex, - i1:MapIndex - )->(Option<&mut T>,Option<&mut T>) { - let (l,r)=self.arena.get2_mut(i0.index,i1.index); - fn mapper(x:&mut MapValue)->&mut T { &mut x.value } - (l.map(mapper),r.map(mapper)) + i0: MapIndex, + i1: MapIndex, + ) -> (Option<&mut T>, Option<&mut T>) { + let (l, r) = self.arena.get2_mut(i0.index, i1.index); + fn mapper(x: &mut MapValue) -> &mut T { + &mut x.value + } + (l.map(mapper), r.map(mapper)) } #[allow(dead_code)] - pub fn replace_index(&mut self,replace:MapIndex,with:T)->Option{ + pub fn replace_index(&mut self, replace: MapIndex, with: T) -> Option { self.get_mut_with_index(replace) - .map(|x| mem::replace(x,with) ) + .map(|x| mem::replace(x, with)) } #[allow(dead_code)] /// The amount of keys associated with values. - pub fn key_len(&self)->usize{ + pub fn key_len(&self) -> usize { self.map.len() } #[allow(dead_code)] /// The amount of values. - pub fn value_len(&self)->usize{ + pub fn value_len(&self) -> usize { self.arena.len() } @@ -162,49 +154,49 @@ where K:Hash+Eq - Both `replace` and `with` are valid indices - If the conditions are not satisfied this method will return None without + If the conditions are not satisfied this method will return None without modifying the collection. */ - pub fn replace_with_index(&mut self,replace:MapIndex,with:MapIndex)->Option{ - if replace==with || - !self.arena.contains(replace.index) || - !self.arena.contains(with.index) + pub fn replace_with_index(&mut self, replace: MapIndex, with: MapIndex) -> Option { + if replace == with + || !self.arena.contains(replace.index) + || !self.arena.contains(with.index) { return None; } - let with_=self.arena.remove(with.index)?; - let replaced=self.arena.get_mut(replace.index)?; + let with_ = self.arena.remove(with.index)?; + let replaced = self.arena.get_mut(replace.index)?; for key in &with_.keys { - *self.map.get_mut(key).unwrap()=replace; + *self.map.get_mut(key).unwrap() = replace; } replaced.keys.extend(with_.keys); - Some(mem::replace(&mut replaced.value,with_.value)) + Some(mem::replace(&mut replaced.value, with_.value)) } - pub fn get_or_insert(&mut self,key:K,value:T)-> InsertionTime> - where - K:Clone + pub fn get_or_insert(&mut self, key: K, value: T) -> InsertionTime> + where + K: Clone, { match self.map.entry(key.clone()) { - Entry::Occupied(entry)=>{ - let index=*entry.get(); - InsertionTime::Before(IndexValue{ + Entry::Occupied(entry) => { + let index = *entry.get(); + InsertionTime::Before(IndexValue { index, - value:&mut self.arena[index.index].value, + value: &mut self.arena[index.index].value, }) } - Entry::Vacant(entry)=>{ - let inserted=MapValue{ - keys:vec![key], + Entry::Vacant(entry) => { + let inserted = MapValue { + keys: vec![key], value, }; - let index=MapIndex::new(self.arena.insert(inserted)); + let index = MapIndex::new(self.arena.insert(inserted)); entry.insert(index); // Just inserted the value at the index - InsertionTime::Now(IndexValue{ + InsertionTime::Now(IndexValue { index, - value:&mut self.arena.get_mut(index.index).unwrap().value + value: &mut self.arena.get_mut(index.index).unwrap().value, }) } } @@ -216,21 +208,21 @@ where K:Hash+Eq /// # Panic /// /// Panics if the index is invalid. - pub fn associate_key(&mut self,key:K,index:MapIndex) - where K:Clone + pub fn associate_key(&mut self, key: K, index: MapIndex) + where + K: Clone, { - let value=match self.arena.get_mut(index.index) { - Some(x)=>x, - None=>panic!("Invalid index:{:?}", index), + let value = match self.arena.get_mut(index.index) { + Some(x) => x, + None => panic!("Invalid index:{:?}", index), }; match self.map.entry(key.clone()) { - Entry::Occupied(_)=>{} - Entry::Vacant(entry)=>{ + Entry::Occupied(_) => {} + Entry::Vacant(entry) => { entry.insert(index); value.keys.push(key); } } - } /// Associates `key` with the value at the `index`. @@ -247,210 +239,197 @@ where K:Hash+Eq /// If `key` was associated with a value,and it was the only key for that value, /// the index for the value will be invalidated. #[allow(dead_code)] - pub fn associate_key_forced(&mut self,key:K,index:MapIndex)->Option - where K:Clone+::std::fmt::Debug + pub fn associate_key_forced(&mut self, key: K, index: MapIndex) -> Option + where + K: Clone + ::std::fmt::Debug, { if !self.arena.contains(index.index) { panic!("Invalid index:{:?}", index); } - let ret=match self.map.entry(key.clone()) { - Entry::Occupied(mut entry)=>{ - let index_before=*entry.get(); + let ret = match self.map.entry(key.clone()) { + Entry::Occupied(mut entry) => { + let index_before = *entry.get(); entry.insert(index); - let slot=&mut self.arena[index_before.index]; - let key_ind=slot.keys.iter().position(|x| *x==key ).unwrap(); + let slot = &mut self.arena[index_before.index]; + let key_ind = slot.keys.iter().position(|x| *x == key).unwrap(); slot.keys.swap_remove(key_ind); if slot.keys.is_empty() { - self.arena.remove(index_before.index).unwrap() + self.arena + .remove(index_before.index) + .unwrap() .value .piped(Some) - }else{ + } else { None } } - Entry::Vacant(_)=>{ - None - } + Entry::Vacant(_) => None, }; - let value=&mut self.arena[index.index]; + let value = &mut self.arena[index.index]; self.map.entry(key.clone()).or_insert(index); value.keys.push(key); ret } } - -impl<'a,K, Q: ?Sized,T> Index<&'a Q> for MultiKeyMap where +impl<'a, K, Q: ?Sized, T> Index<&'a Q> for MultiKeyMap +where K: Eq + Hash + Borrow, Q: Eq + Hash, { - type Output=T; + type Output = T; - fn index(&self,index:&'a Q)->&T { + fn index(&self, index: &'a Q) -> &T { self.get(index).expect("no entry found for key") } } - -impl<'a,K, Q: ?Sized,T> IndexMut<&'a Q> for MultiKeyMap where +impl<'a, K, Q: ?Sized, T> IndexMut<&'a Q> for MultiKeyMap +where K: Eq + Hash + Borrow, Q: Eq + Hash, { - fn index_mut(&mut self,index:&'a Q)->&mut T { + fn index_mut(&mut self, index: &'a Q) -> &mut T { self.get_mut(index).expect("no entry found for key") } } - -impl Debug for MultiKeyMap -where - K:Eq+Hash+Debug, - T:Debug, +impl Debug for MultiKeyMap +where + K: Eq + Hash + Debug, + T: Debug, { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("MultiKeyMap") - .field("map",&self.map) - .field("arena",&self.arena) - .finish() + .field("map", &self.map) + .field("arena", &self.arena) + .finish() } } +impl Eq for MultiKeyMap +where + K: Eq + Hash, + T: Eq, +{ +} -impl Eq for MultiKeyMap -where - K:Eq+Hash, - T:Eq, -{} - - -impl PartialEq for MultiKeyMap -where - K:Eq+Hash, - T:PartialEq, +impl PartialEq for MultiKeyMap +where + K: Eq + Hash, + T: PartialEq, { - fn eq(&self,other:&Self)->bool{ - if self.arena.len()!=other.arena.len()|| - self.map.len()!=other.map.len() - { + fn eq(&self, other: &Self) -> bool { + if self.arena.len() != other.arena.len() || self.map.len() != other.map.len() { return false; } - for (_,l_val) in self.arena.iter() { - let mut keys=l_val.keys.iter(); + for (_, l_val) in self.arena.iter() { + let mut keys = l_val.keys.iter(); - let r_val_index=match other.get_index(keys.next().unwrap()) { - Some(x)=>x, - None=>return false, + let r_val_index = match other.get_index(keys.next().unwrap()) { + Some(x) => x, + None => return false, }; - let r_val=&other.arena[r_val_index.index]; + let r_val = &other.arena[r_val_index.index]; - if l_val.value!=r_val.value { + if l_val.value != r_val.value { return false; } - let all_map_to_r_val=keys.all(|key|{ - match other.get_index(key) { - Some(r_ind)=>ptr::eq(r_val,&other.arena[r_ind.index]), - None=>false, - } + let all_map_to_r_val = keys.all(|key| match other.get_index(key) { + Some(r_ind) => ptr::eq(r_val, &other.arena[r_ind.index]), + None => false, }); if !all_map_to_r_val { - return false + return false; } } true } } - -impl MapIndex{ +impl MapIndex { #[inline] - fn new(index:ArenaIndex)->Self{ - Self{index} + fn new(index: ArenaIndex) -> Self { + Self { index } } } - -impl InsertionTime{ - pub fn into_inner(self)->T{ - match self{ - InsertionTime::Before(v) - |InsertionTime::Now(v)=>v, +impl InsertionTime { + pub fn into_inner(self) -> T { + match self { + InsertionTime::Before(v) | InsertionTime::Now(v) => v, } } #[allow(dead_code)] - pub fn split(self)->(T,InsertionTime<()>){ - let discr=self.discriminant(); - (self.into_inner(),discr) + pub fn split(self) -> (T, InsertionTime<()>) { + let discr = self.discriminant(); + (self.into_inner(), discr) } #[allow(dead_code)] - pub fn map(self,f:F)->InsertionTime - where F:FnOnce(T)->U + pub fn map(self, f: F) -> InsertionTime + where + F: FnOnce(T) -> U, { - match self{ - InsertionTime::Before(v)=>InsertionTime::Before(f(v)), - InsertionTime::Now(v)=>InsertionTime::Now(f(v)), + match self { + InsertionTime::Before(v) => InsertionTime::Before(f(v)), + InsertionTime::Now(v) => InsertionTime::Now(f(v)), } } #[allow(dead_code)] - pub fn discriminant(&self)->InsertionTime<()>{ - match self{ - InsertionTime::Before{..}=>InsertionTime::Before(()), - InsertionTime::Now{..}=>InsertionTime::Now(()), + pub fn discriminant(&self) -> InsertionTime<()> { + match self { + InsertionTime::Before { .. } => InsertionTime::Before(()), + InsertionTime::Now { .. } => InsertionTime::Now(()), } } - } - - - - -#[cfg(all(test,not(feature="only_new_tests")))] -mod tests{ +#[cfg(all(test, not(feature = "only_new_tests")))] +mod tests { use super::*; use crate::test_utils::must_panic; use abi_stable_shared::file_span; - - #[test] - fn equality(){ - fn insert(map:&mut MultiKeyMap,key:u32,value:u32){ - let index=map.get_or_insert(key,value).into_inner().index; - map.associate_key(key+1,index); - map.associate_key(key+2,index); + #[test] + fn equality() { + fn insert(map: &mut MultiKeyMap, key: u32, value: u32) { + let index = map.get_or_insert(key, value).into_inner().index; + map.associate_key(key + 1, index); + map.associate_key(key + 2, index); } /////////////////////////////////////////////////// //// EQUAL /////////////////////////////////////////////////// { - let map_a=MultiKeyMap::::new(); + let map_a = MultiKeyMap::::new(); - let map_b=MultiKeyMap::::new(); + let map_b = MultiKeyMap::::new(); assert_eq!(map_a, map_b); } { - let mut map_a=MultiKeyMap::::new(); - insert(&mut map_a,1000,200); + let mut map_a = MultiKeyMap::::new(); + insert(&mut map_a, 1000, 200); - let mut map_b=MultiKeyMap::::new(); - insert(&mut map_b,1000,200); + let mut map_b = MultiKeyMap::::new(); + insert(&mut map_b, 1000, 200); assert_eq!(map_a, map_b); } { - let mut map_a=MultiKeyMap::::new(); - insert(&mut map_a,1000,200); - insert(&mut map_a,2000,400); + let mut map_a = MultiKeyMap::::new(); + insert(&mut map_a, 1000, 200); + insert(&mut map_a, 2000, 400); - let mut map_b=MultiKeyMap::::new(); - insert(&mut map_b,1000,200); - insert(&mut map_b,2000,400); + let mut map_b = MultiKeyMap::::new(); + insert(&mut map_b, 1000, 200); + insert(&mut map_b, 2000, 400); assert_eq!(map_a, map_b); } @@ -459,242 +438,230 @@ mod tests{ //// NOT EQUAL /////////////////////////////////////////////////// { - let map_a=MultiKeyMap::::new(); - - let mut map_b=MultiKeyMap::::new(); - insert(&mut map_b,1000,200); + let map_a = MultiKeyMap::::new(); + + let mut map_b = MultiKeyMap::::new(); + insert(&mut map_b, 1000, 200); assert_ne!(map_a, map_b); } { - let mut map_a=MultiKeyMap::::new(); - insert(&mut map_a,1000,200); + let mut map_a = MultiKeyMap::::new(); + insert(&mut map_a, 1000, 200); - let map_b=MultiKeyMap::::new(); + let map_b = MultiKeyMap::::new(); assert_ne!(map_a, map_b); } { - let mut map_a=MultiKeyMap::::new(); - insert(&mut map_a,1000,200); - insert(&mut map_a,2000,401); + let mut map_a = MultiKeyMap::::new(); + insert(&mut map_a, 1000, 200); + insert(&mut map_a, 2000, 401); - let mut map_b=MultiKeyMap::::new(); - insert(&mut map_b,1000,200); - insert(&mut map_b,2000,400); + let mut map_b = MultiKeyMap::::new(); + insert(&mut map_b, 1000, 200); + insert(&mut map_b, 2000, 400); assert_ne!(map_a, map_b); } - } - #[test] - fn get_or_insert(){ - let mut map=MultiKeyMap::::new(); + fn get_or_insert() { + let mut map = MultiKeyMap::::new(); + + let (ret, ret_discr) = map.get_or_insert(10, 1).split(); + *ret.value = 1234; + assert_matches!(InsertionTime::Now { .. } = ret_discr); - let (ret,ret_discr)=map.get_or_insert(10,1).split(); - *ret.value=1234; - assert_matches!(InsertionTime::Now{..}=ret_discr); - assert_matches!( - (&mut 1234,InsertionTime::Before{..})= - map.get_or_insert(10,2).map(|x| x.value ).split() + (&mut 1234, InsertionTime::Before { .. }) = + map.get_or_insert(10, 2).map(|x| x.value).split() ); assert_matches!( - (&mut 1234,InsertionTime::Before{..})= - map.get_or_insert(10,3).map(|x| x.value ).split() + (&mut 1234, InsertionTime::Before { .. }) = + map.get_or_insert(10, 3).map(|x| x.value).split() ); } #[test] - fn associate_key(){ - let mut map=MultiKeyMap::::new(); - - let (ret,ret_discr)=map.get_or_insert(100,1).split(); - let index0=ret.index; - *ret.value=1234; - assert_matches!(InsertionTime::Now{..}=ret_discr); - - let index1=map.get_or_insert(200,200).into_inner().index; - let index2=map.get_or_insert(300,300).into_inner().index; - - map.associate_key(20,index0); - map.associate_key(20,index1); - map.associate_key(20,index2); - assert_eq!(map[&20],1234); - - map.associate_key(30,index0); - map.associate_key(30,index1); - map.associate_key(30,index2); - assert_eq!(map[&30],1234); - - map.associate_key(50,index2); - map.associate_key(50,index0); - map.associate_key(50,index1); - assert_eq!(map[&50],300); - - map[&100]=456; - assert_eq!(map[&20],456 ); - assert_eq!(map[&30],456 ); + fn associate_key() { + let mut map = MultiKeyMap::::new(); + + let (ret, ret_discr) = map.get_or_insert(100, 1).split(); + let index0 = ret.index; + *ret.value = 1234; + assert_matches!(InsertionTime::Now { .. } = ret_discr); + + let index1 = map.get_or_insert(200, 200).into_inner().index; + let index2 = map.get_or_insert(300, 300).into_inner().index; + + map.associate_key(20, index0); + map.associate_key(20, index1); + map.associate_key(20, index2); + assert_eq!(map[&20], 1234); + + map.associate_key(30, index0); + map.associate_key(30, index1); + map.associate_key(30, index2); + assert_eq!(map[&30], 1234); + + map.associate_key(50, index2); + map.associate_key(50, index0); + map.associate_key(50, index1); + assert_eq!(map[&50], 300); + + map[&100] = 456; + assert_eq!(map[&20], 456); + assert_eq!(map[&30], 456); } - #[test] - fn associate_key_forced(){ - let mut map=MultiKeyMap::::new(); - - let index0=map.get_or_insert(100,1000).into_inner().index; - let index1=map.get_or_insert(200,2000).into_inner().index; - let index2=map.get_or_insert(300,3000).into_inner().index; - - assert_eq!(map.associate_key_forced(20,index2),None); - assert_eq!(map.associate_key_forced(20,index1),None); - assert_eq!(map.associate_key_forced(20,index0),None); - assert_eq!(map[&20],1000); - - assert_eq!(map.associate_key_forced(30,index2),None); - assert_eq!(map.associate_key_forced(30,index0),None); - assert_eq!(map.associate_key_forced(30,index1),None); - assert_eq!(map[&30],2000); - - assert_eq!(map.associate_key_forced(50,index1),None); - assert_eq!(map.associate_key_forced(50,index0),None); - assert_eq!(map.associate_key_forced(50,index2),None); - assert_eq!(map[&50],3000); - - assert_eq!(map.associate_key_forced(100,index2),None); - assert_eq!(map.associate_key_forced(20,index2),Some(1000)); - - assert_eq!(map.associate_key_forced(200,index2),None); - assert_eq!(map.associate_key_forced(30,index2),Some(2000)); - - must_panic(file_span!(),|| map.associate_key_forced(100,index0) ).unwrap(); - must_panic(file_span!(),|| map.associate_key_forced(200,index0) ).unwrap(); - must_panic(file_span!(),|| map.associate_key_forced(20,index0) ).unwrap(); - must_panic(file_span!(),|| map.associate_key_forced(30,index0) ).unwrap(); + fn associate_key_forced() { + let mut map = MultiKeyMap::::new(); + + let index0 = map.get_or_insert(100, 1000).into_inner().index; + let index1 = map.get_or_insert(200, 2000).into_inner().index; + let index2 = map.get_or_insert(300, 3000).into_inner().index; + + assert_eq!(map.associate_key_forced(20, index2), None); + assert_eq!(map.associate_key_forced(20, index1), None); + assert_eq!(map.associate_key_forced(20, index0), None); + assert_eq!(map[&20], 1000); + + assert_eq!(map.associate_key_forced(30, index2), None); + assert_eq!(map.associate_key_forced(30, index0), None); + assert_eq!(map.associate_key_forced(30, index1), None); + assert_eq!(map[&30], 2000); + + assert_eq!(map.associate_key_forced(50, index1), None); + assert_eq!(map.associate_key_forced(50, index0), None); + assert_eq!(map.associate_key_forced(50, index2), None); + assert_eq!(map[&50], 3000); + + assert_eq!(map.associate_key_forced(100, index2), None); + assert_eq!(map.associate_key_forced(20, index2), Some(1000)); + + assert_eq!(map.associate_key_forced(200, index2), None); + assert_eq!(map.associate_key_forced(30, index2), Some(2000)); + + must_panic(file_span!(), || map.associate_key_forced(100, index0)).unwrap(); + must_panic(file_span!(), || map.associate_key_forced(200, index0)).unwrap(); + must_panic(file_span!(), || map.associate_key_forced(20, index0)).unwrap(); + must_panic(file_span!(), || map.associate_key_forced(30, index0)).unwrap(); } - #[test] - fn replace_index(){ - let mut map=MultiKeyMap::::new(); - - let index0=map.get_or_insert(1000,200).into_inner().index; - map.associate_key(1001,index0); - map.associate_key(1002,index0); - - let index1=map.get_or_insert(2000,300).into_inner().index; - map.associate_key(2001,index1); - map.associate_key(2002,index1); - - let index2=map.get_or_insert(3000,400).into_inner().index; - map.associate_key(3001,index2); - map.associate_key(3002,index2); - - - assert_eq!(map[&1000],200); - assert_eq!(map[&1001],200); - assert_eq!(map[&1001],200); - - - map.replace_index(index0,205); - assert_eq!(map[&1000],205); - assert_eq!(map[&1001],205); - assert_eq!(map[&1001],205); - - map.replace_index(index1,305); - assert_eq!(map[&2000],305); - assert_eq!(map[&2001],305); - assert_eq!(map[&2001],305); - - map.replace_index(index2,405); - assert_eq!(map[&3000],405); - assert_eq!(map[&3001],405); - assert_eq!(map[&3001],405); + fn replace_index() { + let mut map = MultiKeyMap::::new(); + + let index0 = map.get_or_insert(1000, 200).into_inner().index; + map.associate_key(1001, index0); + map.associate_key(1002, index0); + + let index1 = map.get_or_insert(2000, 300).into_inner().index; + map.associate_key(2001, index1); + map.associate_key(2002, index1); + + let index2 = map.get_or_insert(3000, 400).into_inner().index; + map.associate_key(3001, index2); + map.associate_key(3002, index2); + + assert_eq!(map[&1000], 200); + assert_eq!(map[&1001], 200); + assert_eq!(map[&1001], 200); + + map.replace_index(index0, 205); + assert_eq!(map[&1000], 205); + assert_eq!(map[&1001], 205); + assert_eq!(map[&1001], 205); + + map.replace_index(index1, 305); + assert_eq!(map[&2000], 305); + assert_eq!(map[&2001], 305); + assert_eq!(map[&2001], 305); + + map.replace_index(index2, 405); + assert_eq!(map[&3000], 405); + assert_eq!(map[&3001], 405); + assert_eq!(map[&3001], 405); } - - #[test] - fn replace_with_index(){ - let mut map=MultiKeyMap::::new(); - - let index0=map.get_or_insert(1000,200).into_inner().index; - map.associate_key(1001,index0); - map.associate_key(1002,index0); - - let index1=map.get_or_insert(2000,300).into_inner().index; - map.associate_key(2001,index1); - map.associate_key(2002,index1); - - let index2=map.get_or_insert(3000,400).into_inner().index; - map.associate_key(3001,index2); - map.associate_key(3002,index2); - - map.replace_with_index(index0,index2); - assert_eq!(map[&1000],400); - assert_eq!(map[&1001],400); - assert_eq!(map[&1002],400); - assert_eq!(map[&2000],300); - assert_eq!(map[&2001],300); - assert_eq!(map[&2002],300); - assert_eq!(map[&3000],400); - assert_eq!(map[&3001],400); - assert_eq!(map[&3002],400); - map[&1000]=600; - assert_eq!(map[&1000],600); - assert_eq!(map[&1001],600); - assert_eq!(map[&1002],600); - assert_eq!(map[&2000],300); - assert_eq!(map[&2001],300); - assert_eq!(map[&2002],300); - assert_eq!(map[&3000],600); - assert_eq!(map[&3001],600); - assert_eq!(map[&3002],600); - - - map.replace_with_index(index1,index0); - map[&1000]=800; - assert_eq!(map[&1000],800); - assert_eq!(map[&1001],800); - assert_eq!(map[&1002],800); - assert_eq!(map[&2000],800); - assert_eq!(map[&2001],800); - assert_eq!(map[&2002],800); - assert_eq!(map[&3000],800); - assert_eq!(map[&3001],800); - assert_eq!(map[&3002],800); - + fn replace_with_index() { + let mut map = MultiKeyMap::::new(); + + let index0 = map.get_or_insert(1000, 200).into_inner().index; + map.associate_key(1001, index0); + map.associate_key(1002, index0); + + let index1 = map.get_or_insert(2000, 300).into_inner().index; + map.associate_key(2001, index1); + map.associate_key(2002, index1); + + let index2 = map.get_or_insert(3000, 400).into_inner().index; + map.associate_key(3001, index2); + map.associate_key(3002, index2); + + map.replace_with_index(index0, index2); + assert_eq!(map[&1000], 400); + assert_eq!(map[&1001], 400); + assert_eq!(map[&1002], 400); + assert_eq!(map[&2000], 300); + assert_eq!(map[&2001], 300); + assert_eq!(map[&2002], 300); + assert_eq!(map[&3000], 400); + assert_eq!(map[&3001], 400); + assert_eq!(map[&3002], 400); + map[&1000] = 600; + assert_eq!(map[&1000], 600); + assert_eq!(map[&1001], 600); + assert_eq!(map[&1002], 600); + assert_eq!(map[&2000], 300); + assert_eq!(map[&2001], 300); + assert_eq!(map[&2002], 300); + assert_eq!(map[&3000], 600); + assert_eq!(map[&3001], 600); + assert_eq!(map[&3002], 600); + + map.replace_with_index(index1, index0); + map[&1000] = 800; + assert_eq!(map[&1000], 800); + assert_eq!(map[&1001], 800); + assert_eq!(map[&1002], 800); + assert_eq!(map[&2000], 800); + assert_eq!(map[&2001], 800); + assert_eq!(map[&2002], 800); + assert_eq!(map[&3000], 800); + assert_eq!(map[&3001], 800); + assert_eq!(map[&3002], 800); } - #[test] - fn indexing(){ - let mut map=MultiKeyMap::::new(); + fn indexing() { + let mut map = MultiKeyMap::::new(); - let (index0,it0)=map.get_or_insert(1000,200).map(|x|x.index).split(); - let (index1,it1)=map.get_or_insert(2000,300).map(|x|x.index).split(); - let (index2,it2)=map.get_or_insert(3000,400).map(|x|x.index).split(); + let (index0, it0) = map.get_or_insert(1000, 200).map(|x| x.index).split(); + let (index1, it1) = map.get_or_insert(2000, 300).map(|x| x.index).split(); + let (index2, it2) = map.get_or_insert(3000, 400).map(|x| x.index).split(); - assert_eq!(it0,InsertionTime::Now(())); - assert_eq!(it1,InsertionTime::Now(())); - assert_eq!(it2,InsertionTime::Now(())); + assert_eq!(it0, InsertionTime::Now(())); + assert_eq!(it1, InsertionTime::Now(())); + assert_eq!(it2, InsertionTime::Now(())); - let expected=vec![ - (1000,index0,200), - (2000,index1,300), - (3000,index2,400), + let expected = vec![ + (1000, index0, 200), + (2000, index1, 300), + (3000, index2, 400), ]; - for (key,index,val) in expected { - assert_eq!(*map.get_with_index(index).unwrap(),val); - assert_eq!(*map.get(&key).unwrap(),val); - assert_eq!(*(&map[&key]),val); - - assert_eq!(*map.get_mut(&key).unwrap(),val); - assert_eq!(*map.get_mut_with_index(index).unwrap(),val); - assert_eq!(* (&mut map[&key]),val); + for (key, index, val) in expected { + assert_eq!(*map.get_with_index(index).unwrap(), val); + assert_eq!(*map.get(&key).unwrap(), val); + assert_eq!(*(&map[&key]), val); + + assert_eq!(*map.get_mut(&key).unwrap(), val); + assert_eq!(*map.get_mut_with_index(index).unwrap(), val); + assert_eq!(*(&mut map[&key]), val); } } - -} \ No newline at end of file +} diff --git a/abi_stable/src/nonexhaustive_enum.rs b/abi_stable/src/nonexhaustive_enum.rs index 3d3e0264..3d3e077a 100644 --- a/abi_stable/src/nonexhaustive_enum.rs +++ b/abi_stable/src/nonexhaustive_enum.rs @@ -11,73 +11,54 @@ attributes through ffi. #[doc(hidden)] pub mod doc_enums; -#[cfg(any(feature = "testing",feature="nonexhaustive_examples"))] +#[cfg(any(feature = "testing", feature = "nonexhaustive_examples"))] pub mod examples; +pub(crate) mod alt_c_functions; pub(crate) mod nonexhaustive; -pub(crate) mod vtable; pub(crate) mod traits; -pub(crate) mod alt_c_functions; - +pub(crate) mod vtable; pub(crate) use self::vtable::NonExhaustiveVtable_Ref; - pub use self::{ nonexhaustive::{ - DiscrAndEnumInfo, - NonExhaustive,NonExhaustiveFor,NonExhaustiveWI,NonExhaustiveWS, - NonExhaustiveSharedOps, - UnwrapEnumError, - }, - vtable::GetVTable, - traits::{ - GetNonExhaustive, - GetEnumInfo, - EnumInfo, - ValidDiscriminant, - SerializeEnum, - DeserializeEnum, + DiscrAndEnumInfo, NonExhaustive, NonExhaustiveFor, NonExhaustiveSharedOps, NonExhaustiveWI, + NonExhaustiveWS, UnwrapEnumError, }, -}; - - -pub(crate) use self::{ traits::{ - GetSerializeEnumProxy, + DeserializeEnum, EnumInfo, GetEnumInfo, GetNonExhaustive, SerializeEnum, ValidDiscriminant, }, + vtable::GetVTable, }; - +pub(crate) use self::traits::GetSerializeEnumProxy; ///////////////////////////////////////////////////////////// /// Asserts that the size and alignment of an enum are valid for its default storage. pub fn assert_nonexhaustive() where - T:GetEnumInfo, - T:GetVTable< - ::DefaultStorage, - ::DefaultInterface, - > + T: GetEnumInfo, + T: GetVTable<::DefaultStorage, ::DefaultInterface>, { #[derive(Debug)] - struct TypeAndStorageLayout{ - type_:&'static str, - type_size:usize, - type_alignment:usize, - storage_:&'static str, - storage_size:usize, - storage_alignment:usize, + struct TypeAndStorageLayout { + type_: &'static str, + type_size: usize, + type_alignment: usize, + storage_: &'static str, + storage_size: usize, + storage_alignment: usize, } - let lay=TypeAndStorageLayout{ + let lay = TypeAndStorageLayout { type_: std::any::type_name::(), - type_size:std::mem::size_of::(), - type_alignment:std::mem::align_of::(), + type_size: std::mem::size_of::(), + type_alignment: std::mem::align_of::(), storage_: std::any::type_name::<::DefaultStorage>(), - storage_size:std::mem::size_of::(), - storage_alignment:std::mem::align_of::(), + storage_size: std::mem::size_of::(), + storage_alignment: std::mem::align_of::(), }; assert!( @@ -91,4 +72,4 @@ where "The size of the storage is smaller than the enum:\n{:#?}", lay ); -} \ No newline at end of file +} diff --git a/abi_stable/src/nonexhaustive_enum/alt_c_functions.rs b/abi_stable/src/nonexhaustive_enum/alt_c_functions.rs index 39fa6b95..826dab8a 100644 --- a/abi_stable/src/nonexhaustive_enum/alt_c_functions.rs +++ b/abi_stable/src/nonexhaustive_enum/alt_c_functions.rs @@ -2,28 +2,23 @@ use std::ptr; use crate::{ marker_type::ErasedObject, - nonexhaustive_enum::{NonExhaustive,NonExhaustiveVtable_Ref,GetEnumInfo,SerializeEnum}, - sabi_types::{RRef, RMut}, - std_types::{ROption,RCmpOrdering,RSome,RResult,RBoxError}, + nonexhaustive_enum::{GetEnumInfo, NonExhaustive, NonExhaustiveVtable_Ref, SerializeEnum}, + sabi_types::{RMut, RRef}, + std_types::{RBoxError, RCmpOrdering, ROption, RResult, RSome}, traits::IntoReprC, }; - - - - -pub(crate) unsafe extern "C" fn drop_impl(this: RMut<'_, ErasedObject>){ +pub(crate) unsafe extern "C" fn drop_impl(this: RMut<'_, ErasedObject>) { extern_fn_panic_handling! { let this = this.transmute_into_mut::(); ptr::drop_in_place(this); } } - -pub(crate) unsafe extern "C" fn clone_impl( +pub(crate) unsafe extern "C" fn clone_impl( this: RRef<'_, ErasedObject>, - vtable:NonExhaustiveVtable_Ref, -) -> NonExhaustive + vtable: NonExhaustiveVtable_Ref, +) -> NonExhaustive where E: GetEnumInfo, E: Clone, @@ -35,13 +30,12 @@ where } } - -pub(crate) unsafe extern "C" fn partial_eq_impl( +pub(crate) unsafe extern "C" fn partial_eq_impl( this: RRef<'_, ErasedObject>, - other: RRef<'_, ErasedObject> + other: RRef<'_, ErasedObject>, ) -> bool where - E: GetEnumInfo+PartialEq, + E: GetEnumInfo + PartialEq, { extern_fn_panic_handling! { let this = this.transmute_into_ref::(); @@ -53,17 +47,17 @@ where } } -pub(crate) unsafe extern "C" fn cmp_ord( +pub(crate) unsafe extern "C" fn cmp_ord( this: RRef<'_, ErasedObject>, - other: RRef<'_, ErasedObject> + other: RRef<'_, ErasedObject>, ) -> RCmpOrdering where - E: GetEnumInfo+Ord, + E: GetEnumInfo + Ord, { extern_fn_panic_handling! { let this = this.transmute_into_ref::(); let other = other.transmute_into_ref::>(); - + match other.as_enum() { Ok(other)=>this.cmp(other).into_c(), Err(_)=>RCmpOrdering::Less, @@ -71,27 +65,26 @@ where } } -pub(crate) unsafe extern "C" fn partial_cmp_ord( - this: RRef<'_, ErasedObject>, - other: RRef<'_, ErasedObject> +pub(crate) unsafe extern "C" fn partial_cmp_ord( + this: RRef<'_, ErasedObject>, + other: RRef<'_, ErasedObject>, ) -> ROption where - E: GetEnumInfo+PartialOrd, + E: GetEnumInfo + PartialOrd, { extern_fn_panic_handling! { let this = this.transmute_into_ref::(); let other = other.transmute_into_ref::>(); - + match other.as_enum() { Ok(other)=>this.partial_cmp(other).map(IntoReprC::into_c).into_c(), Err(_)=>RSome(RCmpOrdering::Less), - } + } } } - -pub(crate) unsafe extern "C" fn serialize_impl( - this: RRef<'_, ErasedObject> +pub(crate) unsafe extern "C" fn serialize_impl( + this: RRef<'_, ErasedObject>, ) -> RResult<>::Proxy, RBoxError> where I: SerializeEnum, diff --git a/abi_stable/src/nonexhaustive_enum/doc_enums.rs b/abi_stable/src/nonexhaustive_enum/doc_enums.rs index 01cda117..424aa6f9 100644 --- a/abi_stable/src/nonexhaustive_enum/doc_enums.rs +++ b/abi_stable/src/nonexhaustive_enum/doc_enums.rs @@ -1,88 +1,59 @@ macro_rules! declare_constructors { - ($foo:ident) => ( - pub fn new_a()->NonExhaustiveFor<$foo>{ - unsafe{ - std::mem::transmute( - super::example_3::Foo::A - .piped(NonExhaustive::new) - ) - } + ($foo:ident) => { + pub fn new_a() -> NonExhaustiveFor<$foo> { + unsafe { std::mem::transmute(super::example_3::Foo::A.piped(NonExhaustive::new)) } } - pub fn new_b(n:i8)->NonExhaustiveFor<$foo>{ - unsafe{ - std::mem::transmute( - super::example_3::Foo::B(n) - .piped(NonExhaustive::new) - ) - } + pub fn new_b(n: i8) -> NonExhaustiveFor<$foo> { + unsafe { std::mem::transmute(super::example_3::Foo::B(n).piped(NonExhaustive::new)) } } - pub fn new_c()->NonExhaustiveFor<$foo>{ - unsafe{ - std::mem::transmute( - super::example_3::Foo::C - .piped(NonExhaustive::new) - ) - } + pub fn new_c() -> NonExhaustiveFor<$foo> { + unsafe { std::mem::transmute(super::example_3::Foo::C.piped(NonExhaustive::new)) } } - ) + }; } -pub mod example_1{ +pub mod example_1 { + use crate::nonexhaustive_enum::{NonExhaustive, NonExhaustiveFor}; use core_extensions::SelfOps; - use crate::nonexhaustive_enum::{NonExhaustive,NonExhaustiveFor}; #[repr(u8)] - #[derive(StableAbi,Debug,Clone,PartialEq)] - #[sabi(kind(WithNonExhaustive( - size="[usize;4]", - traits(Debug,Clone,PartialEq) - )))] - pub enum Foo{ + #[derive(StableAbi, Debug, Clone, PartialEq)] + #[sabi(kind(WithNonExhaustive(size = "[usize;4]", traits(Debug, Clone, PartialEq))))] + pub enum Foo { A, } - declare_constructors!{Foo} + declare_constructors! {Foo} } - -pub mod example_2{ +pub mod example_2 { + use crate::nonexhaustive_enum::{NonExhaustive, NonExhaustiveFor}; use core_extensions::SelfOps; - use crate::nonexhaustive_enum::{NonExhaustive,NonExhaustiveFor}; #[repr(u8)] - #[derive(StableAbi,Debug,Clone,PartialEq)] - #[sabi(kind(WithNonExhaustive( - size="[usize;4]", - traits(Debug,Clone,PartialEq) - )))] - pub enum Foo{ + #[derive(StableAbi, Debug, Clone, PartialEq)] + #[sabi(kind(WithNonExhaustive(size = "[usize;4]", traits(Debug, Clone, PartialEq))))] + pub enum Foo { A, B(i8), } - declare_constructors!{Foo} + declare_constructors! {Foo} } - -pub mod example_3{ +pub mod example_3 { + use crate::nonexhaustive_enum::{NonExhaustive, NonExhaustiveFor}; use core_extensions::SelfOps; - use crate::nonexhaustive_enum::{NonExhaustive,NonExhaustiveFor}; #[repr(u8)] - #[derive(StableAbi,Debug,Clone,PartialEq)] - #[sabi(kind(WithNonExhaustive( - size="[usize;4]", - traits(Debug,Clone,PartialEq) - )))] - pub enum Foo{ + #[derive(StableAbi, Debug, Clone, PartialEq)] + #[sabi(kind(WithNonExhaustive(size = "[usize;4]", traits(Debug, Clone, PartialEq))))] + pub enum Foo { A, B(i8), C, } - declare_constructors!{Foo} + declare_constructors! {Foo} } - - - diff --git a/abi_stable/src/nonexhaustive_enum/examples.rs b/abi_stable/src/nonexhaustive_enum/examples.rs index 7942dc7a..15c8efa0 100644 --- a/abi_stable/src/nonexhaustive_enum/examples.rs +++ b/abi_stable/src/nonexhaustive_enum/examples.rs @@ -3,397 +3,351 @@ Example non-exhaustive enums,used in tests */ #![allow(dead_code)] - -pub mod command_one{ - use std::fmt::{self,Display}; +pub mod command_one { + use std::fmt::{self, Display}; #[repr(u8)] - #[derive(StableAbi,Hash,Debug,PartialEq,Eq,Clone)] + #[derive(StableAbi, Hash, Debug, PartialEq, Eq, Clone)] #[sabi(kind(WithNonExhaustive( - size=64, - traits(Debug,PartialEq,Eq,Clone), - assert_nonexhaustive="Foo", + size = 64, + traits(Debug, PartialEq, Eq, Clone), + assert_nonexhaustive = "Foo", )))] - pub enum Foo{ + pub enum Foo { A, } - impl Display for Foo{ - fn fmt(&self,_:&mut fmt::Formatter<'_>)->fmt::Result{ + impl Display for Foo { + fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result { Ok(()) } } } -pub mod command_one_more_traits_1{ - use std::fmt::{self,Display}; +pub mod command_one_more_traits_1 { + use std::fmt::{self, Display}; #[repr(u8)] - #[derive(StableAbi,Debug,PartialEq,Eq,Clone,Hash)] + #[derive(StableAbi, Debug, PartialEq, Eq, Clone, Hash)] #[sabi(kind(WithNonExhaustive( - size=64, - traits(Debug,PartialEq,Eq,Clone,Hash), + size = 64, + traits(Debug, PartialEq, Eq, Clone, Hash), assert_nonexhaustive("Foo"), )))] - pub enum Foo{ + pub enum Foo { A, } - impl Display for Foo{ - fn fmt(&self,_:&mut fmt::Formatter<'_>)->fmt::Result{ + impl Display for Foo { + fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result { Ok(()) } } } -pub mod command_one_more_traits_2{ - use std::fmt::{self,Display}; +pub mod command_one_more_traits_2 { + use std::fmt::{self, Display}; #[repr(u8)] - #[derive(StableAbi,Debug,PartialEq,Eq,PartialOrd,Clone,Hash)] + #[derive(StableAbi, Debug, PartialEq, Eq, PartialOrd, Clone, Hash)] #[sabi(kind(WithNonExhaustive( - size=64, - traits(Debug,PartialEq,Eq,PartialOrd,Clone,Hash) + size = 64, + traits(Debug, PartialEq, Eq, PartialOrd, Clone, Hash) )))] - pub enum Foo{ + pub enum Foo { A, } - impl Display for Foo{ - fn fmt(&self,_:&mut fmt::Formatter<'_>)->fmt::Result{ + impl Display for Foo { + fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result { Ok(()) } } } -pub mod command_one_more_traits_3{ - use std::fmt::{self,Display}; +pub mod command_one_more_traits_3 { + use std::fmt::{self, Display}; #[repr(u8)] - #[derive(StableAbi,Debug,PartialEq,Eq,PartialOrd,Ord,Clone,Hash)] + #[derive(StableAbi, Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Hash)] #[sabi(kind(WithNonExhaustive( - size=64, - traits(Debug,PartialEq,Eq,PartialOrd,Ord,Clone,Hash) + size = 64, + traits(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Hash) )))] - pub enum Foo{ + pub enum Foo { A, } - impl Display for Foo{ - fn fmt(&self,_:&mut fmt::Formatter<'_>)->fmt::Result{ + impl Display for Foo { + fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result { Ok(()) } } } -pub mod command_a{ - use std::fmt::{self,Display}; +pub mod command_a { + use std::fmt::{self, Display}; #[repr(u8)] - #[derive(StableAbi,Hash,Debug,PartialEq,Eq,Clone)] - #[sabi(kind(WithNonExhaustive( - size=64, - traits(Debug,PartialEq,Eq,Clone) - )))] - pub enum Foo{ + #[derive(StableAbi, Hash, Debug, PartialEq, Eq, Clone)] + #[sabi(kind(WithNonExhaustive(size = 64, traits(Debug, PartialEq, Eq, Clone))))] + pub enum Foo { A, B(i8), } - impl Display for Foo{ - fn fmt(&self,_:&mut fmt::Formatter<'_>)->fmt::Result{ + impl Display for Foo { + fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result { Ok(()) } } } -pub mod command_a_exhaustive{ - use std::fmt::{self,Display}; +pub mod command_a_exhaustive { + use std::fmt::{self, Display}; #[repr(u8)] - #[derive(StableAbi,Hash,Debug,PartialEq,Eq,Clone)] - pub enum Foo{ + #[derive(StableAbi, Hash, Debug, PartialEq, Eq, Clone)] + pub enum Foo { A, B(i8), } - impl Display for Foo{ - fn fmt(&self,_:&mut fmt::Formatter<'_>)->fmt::Result{ + impl Display for Foo { + fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result { Ok(()) } } } -pub mod command_b{ - use std::fmt::{self,Display}; +pub mod command_b { + use std::fmt::{self, Display}; #[repr(u8)] - #[derive(StableAbi,Hash,Debug,PartialEq,Eq,Clone)] - #[sabi(kind(WithNonExhaustive( - size=64, - traits(Debug,PartialEq,Eq,Clone) - )))] - pub enum Foo{ + #[derive(StableAbi, Hash, Debug, PartialEq, Eq, Clone)] + #[sabi(kind(WithNonExhaustive(size = 64, traits(Debug, PartialEq, Eq, Clone))))] + pub enum Foo { A, B(i8), C, } - impl Display for Foo{ - fn fmt(&self,_:&mut fmt::Formatter<'_>)->fmt::Result{ + impl Display for Foo { + fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result { Ok(()) } } } -pub mod command_c{ +pub mod command_c { use crate::std_types::RString; #[repr(u8)] - #[derive(StableAbi,Hash,Debug,PartialEq,Eq,Clone)] - #[sabi(kind(WithNonExhaustive( - size=64, - traits(Debug,PartialEq,Eq,Clone) - )))] - pub enum Foo{ + #[derive(StableAbi, Hash, Debug, PartialEq, Eq, Clone)] + #[sabi(kind(WithNonExhaustive(size = 64, traits(Debug, PartialEq, Eq, Clone))))] + pub enum Foo { A, B(i8), C, - D{ - name:RString, - }, + D { name: RString }, } - } -pub mod command_c_mismatched_field{ +pub mod command_c_mismatched_field { use crate::std_types::RVec; #[repr(u8)] - #[derive(StableAbi,Hash,Debug,PartialEq,Eq,Clone)] - #[sabi(kind(WithNonExhaustive( - size=64, - traits(Debug,PartialEq,Eq,Clone) - )))] - pub enum Foo{ + #[derive(StableAbi, Hash, Debug, PartialEq, Eq, Clone)] + #[sabi(kind(WithNonExhaustive(size = 64, traits(Debug, PartialEq, Eq, Clone))))] + pub enum Foo { A, B(i8), C, - D{ - name:RVec, - }, + D { name: RVec }, } - } -pub mod command_serde{ - use std::fmt::{self,Display}; +pub mod command_serde { + use std::fmt::{self, Display}; - use serde::{Serialize,Deserialize}; + use serde::{Deserialize, Serialize}; use crate::std_types::RString; #[repr(u8)] - #[derive(StableAbi,Hash,Debug,PartialEq,Eq,Ord,PartialOrd,Clone,Deserialize,Serialize)] + #[derive( + StableAbi, Hash, Debug, PartialEq, Eq, Ord, PartialOrd, Clone, Deserialize, Serialize, + )] #[sabi(kind(WithNonExhaustive( - size=64, - traits(Debug,Display,PartialEq,Eq,Clone,Deserialize,Serialize) + size = 64, + traits(Debug, Display, PartialEq, Eq, Clone, Deserialize, Serialize) )))] // #[sabi(debug_print)] - pub enum Foo{ + pub enum Foo { A, B(i8), C, - D{ - name:RString, - }, + D { name: RString }, } - impl Display for Foo{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ + impl Display for Foo { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Foo::A=>write!(f,"Variant A"), - Foo::B(v)=>write!(f,"Variant B with value:{}",v), - Foo::C=>write!(f,"Variant C"), - Foo::D{name}=>write!(f,"Variant D named:{}",name), + Foo::A => write!(f, "Variant A"), + Foo::B(v) => write!(f, "Variant B with value:{}", v), + Foo::C => write!(f, "Variant C"), + Foo::D { name } => write!(f, "Variant D named:{}", name), } } } - - delegate_interface_serde!{ + delegate_interface_serde! { impl[T,] Traits for Foo_Interface; lifetime='borr; delegate_to=super::codecs::Json; } } -pub mod too_large{ +pub mod too_large { #[repr(u8)] - #[derive(StableAbi,Hash,Debug,PartialEq,Eq,Clone)] - #[sabi(kind(WithNonExhaustive( - size=64, - traits(Debug,PartialEq,Eq,Clone) - )))] - pub enum Foo{ + #[derive(StableAbi, Hash, Debug, PartialEq, Eq, Clone)] + #[sabi(kind(WithNonExhaustive(size = 64, traits(Debug, PartialEq, Eq, Clone))))] + pub enum Foo { A, B(i8), - C([u16;32]) + C([u16; 32]), } } - -pub mod generic_a{ - use std::fmt::{self,Display}; +pub mod generic_a { + use std::fmt::{self, Display}; #[repr(u8)] - #[derive(StableAbi,Hash,Debug,PartialOrd,Ord,PartialEq,Eq,Clone)] + #[derive(StableAbi, Hash, Debug, PartialOrd, Ord, PartialEq, Eq, Clone)] #[sabi(kind(WithNonExhaustive( - size=64, - traits(Debug,PartialEq,Eq,Ord,PartialOrd,Clone,Hash) + size = 64, + traits(Debug, PartialEq, Eq, Ord, PartialOrd, Clone, Hash) )))] //#[sabi(debug_print)] - pub enum Foo{ + pub enum Foo { A, B, C(T), } - impl Display for Foo where - T:Display + T: Display, { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Foo::A=>write!(f,"Variant A"), - Foo::B=>write!(f,"Variant B"), - Foo::C(v)=>write!(f,"Variant C:{}",v), + Foo::A => write!(f, "Variant A"), + Foo::B => write!(f, "Variant B"), + Foo::C(v) => write!(f, "Variant C:{}", v), } } } } - -pub mod many_ranges_a{ +pub mod many_ranges_a { #[repr(u8)] - #[derive(StableAbi,Debug,PartialEq,Eq,Clone)] - #[sabi(kind(WithNonExhaustive( - size=64, - traits(Debug,PartialEq,Eq,Clone) - )))] - pub enum Foo{ + #[derive(StableAbi, Debug, PartialEq, Eq, Clone)] + #[sabi(kind(WithNonExhaustive(size = 64, traits(Debug, PartialEq, Eq, Clone))))] + pub enum Foo { A, - B=40, + B = 40, C, D, - E=60, + E = 60, F, } } -pub mod many_ranges_b{ +pub mod many_ranges_b { #[repr(u8)] - #[derive(StableAbi,Debug,PartialEq,Eq,Clone)] - #[sabi(kind(WithNonExhaustive( - size=64, - traits(Debug,PartialEq,Eq,Clone) - )))] - pub enum Foo{ + #[derive(StableAbi, Debug, PartialEq, Eq, Clone)] + #[sabi(kind(WithNonExhaustive(size = 64, traits(Debug, PartialEq, Eq, Clone))))] + pub enum Foo { A, - B=40, + B = 40, C, - E=60, + E = 60, } - } - -pub mod command_h{ - use std::fmt::{self,Display}; +pub mod command_h { + use std::fmt::{self, Display}; #[repr(u8)] - #[derive(StableAbi,Hash,Debug,PartialEq,Eq,Clone)] - #[sabi(kind(WithNonExhaustive( - size=64, - traits(Debug,PartialEq,Eq,Clone) - )))] - pub enum Foo{ + #[derive(StableAbi, Hash, Debug, PartialEq, Eq, Clone)] + #[sabi(kind(WithNonExhaustive(size = 64, traits(Debug, PartialEq, Eq, Clone))))] + pub enum Foo { A, B, C, } - impl Display for Foo{ - fn fmt(&self,_:&mut fmt::Formatter<'_>)->fmt::Result{ + impl Display for Foo { + fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result { Ok(()) } } } - -pub mod command_h_mismatched_discriminant{ - use std::fmt::{self,Display}; +pub mod command_h_mismatched_discriminant { + use std::fmt::{self, Display}; #[repr(u8)] - #[derive(StableAbi,Hash,Debug,PartialEq,Eq,Clone)] - #[sabi(kind(WithNonExhaustive( - size=64, - traits(Debug,PartialEq,Eq,Clone) - )))] - pub enum Foo{ - A=40, + #[derive(StableAbi, Hash, Debug, PartialEq, Eq, Clone)] + #[sabi(kind(WithNonExhaustive(size = 64, traits(Debug, PartialEq, Eq, Clone))))] + pub enum Foo { + A = 40, B, C, } - impl Display for Foo{ - fn fmt(&self,_:&mut fmt::Formatter<'_>)->fmt::Result{ + impl Display for Foo { + fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result { Ok(()) } } } - - - - -pub mod codecs{ - use serde::{Serialize,Deserialize}; +pub mod codecs { + use serde::{Deserialize, Serialize}; use crate::{ nonexhaustive_enum::{ - SerializeEnum,DeserializeEnum,NonExhaustive, - GetEnumInfo,GetVTable, + DeserializeEnum, GetEnumInfo, GetVTable, NonExhaustive, SerializeEnum, }, - std_types::{RBoxError,RString}, - }; + std_types::{RBoxError, RString}, + }; pub struct Json; - impl SerializeEnum> for Json + impl SerializeEnum> for Json where - E:Serialize+GetEnumInfo + E: Serialize + GetEnumInfo, { - type Proxy=RString; + type Proxy = RString; - fn serialize_enum(this:&NonExhaustive) -> Result{ + fn serialize_enum(this: &NonExhaustive) -> Result { serde_json::to_string(this.as_enum()?) .map(RString::from) .map_err(RBoxError::new) } } - impl<'borr,E,S,I> DeserializeEnum<'borr,NonExhaustive> for Json + impl<'borr, E, S, I> DeserializeEnum<'borr, NonExhaustive> for Json where - E:GetVTable+for<'de>Deserialize<'de>, + E: GetVTable + for<'de> Deserialize<'de>, { - type Proxy=RString; + type Proxy = RString; - fn deserialize_enum(s: RString) -> Result, RBoxError>{ + fn deserialize_enum(s: RString) -> Result, RBoxError> { serde_json::from_str(&s) .map(NonExhaustive::with_storage_and_interface) .map_err(RBoxError::new) } } -} \ No newline at end of file +} diff --git a/abi_stable/src/nonexhaustive_enum/nonexhaustive.rs b/abi_stable/src/nonexhaustive_enum/nonexhaustive.rs index 895885e9..61656ff2 100644 --- a/abi_stable/src/nonexhaustive_enum/nonexhaustive.rs +++ b/abi_stable/src/nonexhaustive_enum/nonexhaustive.rs @@ -3,9 +3,9 @@ Contains `NonExhaustive<>` and related items. */ use std::{ - cmp::{Ordering,PartialEq,Eq,Ord,PartialOrd}, - fmt::{self,Debug,Display}, - hash::{Hash,Hasher}, + cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}, + fmt::{self, Debug, Display}, + hash::{Hash, Hasher}, marker::PhantomData, mem::ManuallyDrop, ops::Deref, @@ -13,45 +13,28 @@ use std::{ use crate::{ abi_stability::StableAbi, - erased_types::{ - c_functions, - trait_objects::{ - HasherObject, - }, - InterfaceBound, - }, + erased_types::{c_functions, trait_objects::HasherObject, InterfaceBound}, inline_storage::ScratchSpace, marker_type::ErasedObject, nonexhaustive_enum::{ - vtable::NonExhaustiveVtable_Ref, - GetVTable,GetEnumInfo,GetNonExhaustive, - ValidDiscriminant,EnumInfo, - SerializeEnum,DeserializeEnum, - }, - pointer_trait::{CanTransmuteElement,TransmuteElement}, - type_level::{ - impl_enum::Implemented, - trait_marker, + vtable::NonExhaustiveVtable_Ref, DeserializeEnum, EnumInfo, GetEnumInfo, GetNonExhaustive, + GetVTable, SerializeEnum, ValidDiscriminant, }, - sabi_types::{RRef, RMut}, + pointer_trait::{CanTransmuteElement, TransmuteElement}, + sabi_types::{RMut, RRef}, std_types::RBoxError, traits::IntoReprRust, + type_level::{impl_enum::Implemented, trait_marker}, }; -use core_extensions::{ - utils::transmute_ignore_size, -}; - -use serde::{ser,de,Serialize,Deserialize,Serializer,Deserializer}; - +use core_extensions::utils::transmute_ignore_size; +use serde::{de, ser, Deserialize, Deserializer, Serialize, Serializer}; // #[cfg(test)] -#[cfg(all(test,not(feature="only_new_tests")))] +#[cfg(all(test, not(feature = "only_new_tests")))] mod tests; - - /** A generic type for all ffi-safe non-exhaustive enums. @@ -60,12 +43,12 @@ This type allows adding variants to enums it wraps in ABI compatible versions of # Generic parameters -### `E` +### `E` This is the enum that this was constructed from, and can be unwrapped back into if it's one of the valid variants in this context. -### `S` +### `S` The storage type,used to store the enum opaquely. @@ -77,7 +60,7 @@ This is necessary because: - To give some flexibility to grow the enum in semver compatible versions of a library. -### `I` +### `I` The interface of the enum(it implements `InterfaceType`), determining which traits are required when constructing `NonExhaustive<>` @@ -166,7 +149,7 @@ fn returns_invalid_item_id()->NonExhaustiveFor{ ``` -If a library user attempted to unwrap `Error::InvalidItemId` +If a library user attempted to unwrap `Error::InvalidItemId` (using NonExhaustive::as_enum/as_enum_mut/into_enum) with the 1.0 version of `Error` they would get an `Err(..)` back. @@ -183,237 +166,214 @@ with the 1.0 version of `Error` they would get an `Err(..)` back. extra_checks="::EXTRA_CHECKS", phantom_type_param=">::NonExhaustive", )] -pub struct NonExhaustive{ +pub struct NonExhaustive { // This is an opaque field since we only care about its size and alignment #[sabi(unsafe_opaque_field)] - fill:ScratchSpace, - vtable:NonExhaustiveVtable_Ref, - _marker:PhantomData<()>, + fill: ScratchSpace, + vtable: NonExhaustiveVtable_Ref, + _marker: PhantomData<()>, } /// The type of a `NonExhaustive<>` wrapping the enum E, /// using the `E`'s default storage and interface. -pub type NonExhaustiveFor= - NonExhaustive< - E, - ::DefaultStorage, - ::DefaultInterface, - >; +pub type NonExhaustiveFor = + NonExhaustive::DefaultStorage, ::DefaultInterface>; /// The type of a `NonExhaustive<>` wrapping the enum E, /// using the `E`'s default storage and a custom interface. -pub type NonExhaustiveWI= - NonExhaustive< - E, - ::DefaultStorage, - I, - >; +pub type NonExhaustiveWI = NonExhaustive::DefaultStorage, I>; /// The type of a `NonExhaustive<>` wrapping the enum E, /// using a custom storage and the `E`'s default interface. -pub type NonExhaustiveWS= - NonExhaustive< - E, - S, - ::DefaultInterface, - >; +pub type NonExhaustiveWS = NonExhaustive::DefaultInterface>; +impl NonExhaustive { + /** + Constructs a `NonExhaustive<>` from `value` using its default interface and storage. + # Panic -impl NonExhaustive{ - -/** -Constructs a `NonExhaustive<>` from `value` using its default interface and storage. - -# Panic - -This panics if the storage has an alignment or size smaller than that of `E`. -*/ + This panics if the storage has an alignment or size smaller than that of `E`. + */ #[inline] - pub fn new(value:E)->Self + pub fn new(value: E) -> Self where - E:GetVTable, + E: GetVTable, { NonExhaustive::with_storage_and_interface(value) } -/** -Constructs a `NonExhaustive<>` from `value` using its default storage -and a custom interface. + /** + Constructs a `NonExhaustive<>` from `value` using its default storage + and a custom interface. -# Panic + # Panic -This panics if the storage has an alignment or size smaller than that of `E`. -*/ + This panics if the storage has an alignment or size smaller than that of `E`. + */ #[inline] - pub fn with_interface(value:E)->Self + pub fn with_interface(value: E) -> Self where - E:GetVTable, + E: GetVTable, { NonExhaustive::with_storage_and_interface(value) } -/** -Constructs a `NonExhaustive<>` from `value` using its default interface -and a custom storage. + /** + Constructs a `NonExhaustive<>` from `value` using its default interface + and a custom storage. -# Panic + # Panic -This panics if the storage has an alignment or size smaller than that of `E`. -*/ + This panics if the storage has an alignment or size smaller than that of `E`. + */ #[inline] - pub fn with_storage(value:E)->Self + pub fn with_storage(value: E) -> Self where - E:GetVTable, + E: GetVTable, { NonExhaustive::with_storage_and_interface(value) } -/** -Constructs a `NonExhaustive<>` from `value` using both a custom interface and storage. + /** + Constructs a `NonExhaustive<>` from `value` using both a custom interface and storage. -# Panic + # Panic -This panics if the storage has an alignment or size smaller than that of `E`. -*/ - pub fn with_storage_and_interface(value:E)->Self - where - E:GetVTable, + This panics if the storage has an alignment or size smaller than that of `E`. + */ + pub fn with_storage_and_interface(value: E) -> Self + where + E: GetVTable, { - unsafe{ - NonExhaustive::with_vtable(value,E::VTABLE_REF) - } + unsafe { NonExhaustive::with_vtable(value, E::VTABLE_REF) } } - pub(super) unsafe fn with_vtable( - value:E, - vtable:NonExhaustiveVtable_Ref - )->Self{ + pub(super) unsafe fn with_vtable(value: E, vtable: NonExhaustiveVtable_Ref) -> Self { Self::assert_fits_within_storage(); - let mut this=Self{ - fill:unsafe{ - // The fact that the vtable was constructed ensures that + let mut this = Self { + fill: unsafe { + // The fact that the vtable was constructed ensures that // `Inline` implements `InlineStorage` ScratchSpace::uninit_unbounded() }, vtable, - _marker:PhantomData + _marker: PhantomData, }; - + (&mut this.fill as *mut ScratchSpace as *mut E).write(value); this } - /// Checks that the alignment of `E` is correct,returning `true` if it is. - pub fn check_alignment()->bool{ - let align_enum=std::mem::align_of::(); - let align_storage=std::mem::align_of::(); + pub fn check_alignment() -> bool { + let align_enum = std::mem::align_of::(); + let align_storage = std::mem::align_of::(); align_enum <= align_storage } /// Checks that the size of `E` is correct,returning `true` if it is. - pub fn check_size()->bool{ - let size_enum=std::mem::size_of::(); - let size_storage=std::mem::size_of::(); + pub fn check_size() -> bool { + let size_enum = std::mem::size_of::(); + let size_storage = std::mem::size_of::(); size_enum <= size_storage } /// Asserts that `E` fits within `S`,with the correct alignment and size. - pub fn assert_fits_within_storage(){ - let align_enum=std::mem::align_of::(); - let align_storage=std::mem::align_of::(); + pub fn assert_fits_within_storage() { + let align_enum = std::mem::align_of::(); + let align_storage = std::mem::align_of::(); assert!( Self::check_alignment(), "The alignment of the storage is lower than the enum:\n\t{} < {}", - align_storage,align_enum, + align_storage, + align_enum, ); - let size_enum=std::mem::size_of::(); - let size_storage=std::mem::size_of::(); + let size_enum = std::mem::size_of::(); + let size_storage = std::mem::size_of::(); assert!( Self::check_size(), "The size of the storage is smaller than the enum:\n\t{} < {}", - size_storage,size_enum, + size_storage, + size_enum, ); } } -impl NonExhaustive +impl NonExhaustive where - E:GetEnumInfo + E: GetEnumInfo, { -/** -Unwraps a reference to this `NonExhaustive<>` into a reference to the original enum. + /** + Unwraps a reference to this `NonExhaustive<>` into a reference to the original enum. -# Errors + # Errors -This returns an error if the wrapped enum is of a variant that is -not valid in this context. + This returns an error if the wrapped enum is of a variant that is + not valid in this context. -# Example + # Example -This shows how some `NonExhaustive` can be unwrapped, and others cannot.
-That enum comes from a newer version of the library than this knows. + This shows how some `NonExhaustive` can be unwrapped, and others cannot.
+ That enum comes from a newer version of the library than this knows. -``` -use abi_stable::nonexhaustive_enum::{ - doc_enums::example_2::{Foo,new_a,new_b,new_c}, -}; + ``` + use abi_stable::nonexhaustive_enum::{ + doc_enums::example_2::{Foo,new_a,new_b,new_c}, + }; -assert_eq!(new_a() .as_enum().ok(),Some(&Foo::A) ); -assert_eq!(new_b(10).as_enum().ok(),Some(&Foo::B(10))); -assert_eq!(new_b(77).as_enum().ok(),Some(&Foo::B(77))); -assert_eq!(new_c().as_enum().ok() ,None ); + assert_eq!(new_a() .as_enum().ok(),Some(&Foo::A) ); + assert_eq!(new_b(10).as_enum().ok(),Some(&Foo::B(10))); + assert_eq!(new_b(77).as_enum().ok(),Some(&Foo::B(77))); + assert_eq!(new_c().as_enum().ok() ,None ); -``` + ``` -*/ - pub fn as_enum(&self)->Result<&E,UnwrapEnumError<&Self>>{ - let discriminant=self.get_discriminant(); + */ + pub fn as_enum(&self) -> Result<&E, UnwrapEnumError<&Self>> { + let discriminant = self.get_discriminant(); if E::is_valid_discriminant(discriminant) { - unsafe{ - Ok(&*(&self.fill as *const ScratchSpace as *const E)) - } - }else{ + unsafe { Ok(&*(&self.fill as *const ScratchSpace as *const E)) } + } else { Err(UnwrapEnumError::new(self)) } } -/** -Unwraps a mutable reference to this `NonExhaustive<>` into a -mutable reference to the original enum. + /** + Unwraps a mutable reference to this `NonExhaustive<>` into a + mutable reference to the original enum. -# Errors + # Errors -This returns an error if the wrapped enum is of a variant that is -not valid in this context. + This returns an error if the wrapped enum is of a variant that is + not valid in this context. -# Example + # Example -This shows how some `NonExhaustive` can be unwrapped, and others cannot.
-That enum comes from a newer version of the library than this knows. + This shows how some `NonExhaustive` can be unwrapped, and others cannot.
+ That enum comes from a newer version of the library than this knows. -``` -use abi_stable::nonexhaustive_enum::{ - doc_enums::example_1::{Foo,new_a,new_b,new_c}, -}; + ``` + use abi_stable::nonexhaustive_enum::{ + doc_enums::example_1::{Foo,new_a,new_b,new_c}, + }; -assert_eq!(new_a() .as_enum_mut().ok(),Some(&mut Foo::A)); -assert_eq!(new_b(10).as_enum_mut().ok(),None); -assert_eq!(new_b(77).as_enum_mut().ok(),None); -assert_eq!(new_c().as_enum_mut().ok() ,None); + assert_eq!(new_a() .as_enum_mut().ok(),Some(&mut Foo::A)); + assert_eq!(new_b(10).as_enum_mut().ok(),None); + assert_eq!(new_b(77).as_enum_mut().ok(),None); + assert_eq!(new_c().as_enum_mut().ok() ,None); -``` + ``` -*/ - pub fn as_enum_mut(&mut self)->Result<&mut E,UnwrapEnumError<&mut Self>> - where - E:GetVTable, + */ + pub fn as_enum_mut(&mut self) -> Result<&mut E, UnwrapEnumError<&mut Self>> + where + E: GetVTable, { - let discriminant=self.get_discriminant(); + let discriminant = self.get_discriminant(); if E::is_valid_discriminant(discriminant) { /* Must update the vtable every time as_enum_mut is called, @@ -421,264 +381,238 @@ assert_eq!(new_c().as_enum_mut().ok() ,None); outside the valid range for the functions in the vtable, it would be undefined behavior to call those functions. */ - self.vtable=E::VTABLE_REF; - unsafe{ - Ok(&mut *(&mut self.fill as *mut ScratchSpace as *mut E)) - } - }else{ + self.vtable = E::VTABLE_REF; + unsafe { Ok(&mut *(&mut self.fill as *mut ScratchSpace as *mut E)) } + } else { Err(UnwrapEnumError::new(self)) } } -/** -Unwraps this `NonExhaustive<>` into the original enum. + /** + Unwraps this `NonExhaustive<>` into the original enum. -# Errors + # Errors -This returns an error if the wrapped enum is of a variant that is -not valid in this context. + This returns an error if the wrapped enum is of a variant that is + not valid in this context. -# Example + # Example -This shows how some `NonExhaustive` can be unwrapped, and others cannot.
-That enum comes from a newer version of the library than this knows. + This shows how some `NonExhaustive` can be unwrapped, and others cannot.
+ That enum comes from a newer version of the library than this knows. -``` -use abi_stable::nonexhaustive_enum::{ - doc_enums::example_2::{Foo,new_a,new_b,new_c}, -}; + ``` + use abi_stable::nonexhaustive_enum::{ + doc_enums::example_2::{Foo,new_a,new_b,new_c}, + }; -assert_eq!(new_a() .into_enum().ok(),Some(Foo::A)); -assert_eq!(new_b(10).into_enum().ok(),Some(Foo::B(10))); -assert_eq!(new_b(77).into_enum().ok(),Some(Foo::B(77))); -assert_eq!(new_c().into_enum().ok() ,None); + assert_eq!(new_a() .into_enum().ok(),Some(Foo::A)); + assert_eq!(new_b(10).into_enum().ok(),Some(Foo::B(10))); + assert_eq!(new_b(77).into_enum().ok(),Some(Foo::B(77))); + assert_eq!(new_c().into_enum().ok() ,None); -*/ - pub fn into_enum(self)->Result>{ - let discriminant=self.get_discriminant(); + */ + pub fn into_enum(self) -> Result> { + let discriminant = self.get_discriminant(); if E::is_valid_discriminant(discriminant) { - let this=ManuallyDrop::new(self); - unsafe{ - Ok((&this.fill as *const ScratchSpace as *const E).read()) - } - }else{ + let this = ManuallyDrop::new(self); + unsafe { Ok((&this.fill as *const ScratchSpace as *const E).read()) } + } else { Err(UnwrapEnumError::new(self)) } } -/** -Returns whether the discriminant of this enum is valid in this context. + /** + Returns whether the discriminant of this enum is valid in this context. -The only way for it to be invalid is if the dynamic library is a -newer version than this knows. -*/ + The only way for it to be invalid is if the dynamic library is a + newer version than this knows. + */ #[inline] - pub fn is_valid_discriminant(&self)->bool{ + pub fn is_valid_discriminant(&self) -> bool { E::is_valid_discriminant(self.get_discriminant()) } -/** -Gets the value of the discriminant of the enum. -*/ + /** + Gets the value of the discriminant of the enum. + */ #[inline] - pub fn get_discriminant(&self)->E::Discriminant{ - unsafe{ - *(&self.fill as *const ScratchSpace as *const E::Discriminant) - } + pub fn get_discriminant(&self) -> E::Discriminant { + unsafe { *(&self.fill as *const ScratchSpace as *const E::Discriminant) } } - } -impl NonExhaustive{ - -/** -Transmute this `NonExhaustive` into `NonExhaustive`, -changing the type of the enum it wraps. +impl NonExhaustive { + /** + Transmute this `NonExhaustive` into `NonExhaustive`, + changing the type of the enum it wraps. -# Safety + # Safety -This has the same safety requirements that `std::mem::transmute` has. + This has the same safety requirements that `std::mem::transmute` has. -# Panics + # Panics -This panics if the storage has an alignment or size smaller than that of `F`. + This panics if the storage has an alignment or size smaller than that of `F`. -*/ - pub unsafe fn transmute_enum(self)->NonExhaustive{ - NonExhaustive::::assert_fits_within_storage(); + */ + pub unsafe fn transmute_enum(self) -> NonExhaustive { + NonExhaustive::::assert_fits_within_storage(); transmute_ignore_size(self) } -/** -Transmute this `&NonExhaustive` into `&NonExhaustive`, -changing the type of the enum it wraps. + /** + Transmute this `&NonExhaustive` into `&NonExhaustive`, + changing the type of the enum it wraps. -# Safety + # Safety -This has the same safety requirements that `std::mem::transmute` has. + This has the same safety requirements that `std::mem::transmute` has. -# Panics + # Panics -This panics if the storage has an alignment or size smaller than that of `F`. + This panics if the storage has an alignment or size smaller than that of `F`. -*/ - pub unsafe fn transmute_enum_ref(&self)->&NonExhaustive{ - NonExhaustive::::assert_fits_within_storage(); + */ + pub unsafe fn transmute_enum_ref(&self) -> &NonExhaustive { + NonExhaustive::::assert_fits_within_storage(); &*(self as *const Self as *const _) } + /** + Transmute this `&mut NonExhaustive` into `&mut NonExhaustive`, + changing the type of the enum it wraps. -/** -Transmute this `&mut NonExhaustive` into `&mut NonExhaustive`, -changing the type of the enum it wraps. - -# Safety + # Safety -This has the same safety requirements that `std::mem::transmute` has. + This has the same safety requirements that `std::mem::transmute` has. -# Panics + # Panics -This panics if the storage has an alignment or size smaller than that of `F`. + This panics if the storage has an alignment or size smaller than that of `F`. -*/ - pub unsafe fn transmute_enum_mut(&mut self)->&mut NonExhaustive{ - NonExhaustive::::assert_fits_within_storage(); + */ + pub unsafe fn transmute_enum_mut(&mut self) -> &mut NonExhaustive { + NonExhaustive::::assert_fits_within_storage(); &mut *(self as *mut Self as *mut _) } -/** -Transmute this pointer to a `NonExhaustive` into -a pointer (of the same kind) to a `NonExhaustive`, -changing the type of the enum it wraps. + /** + Transmute this pointer to a `NonExhaustive` into + a pointer (of the same kind) to a `NonExhaustive`, + changing the type of the enum it wraps. -# Safety + # Safety -This has the same safety requirements that -`abi_stable::pointer_traits::TransmuteElement::transmute_element` has. + This has the same safety requirements that + `abi_stable::pointer_traits::TransmuteElement::transmute_element` has. -# Panics + # Panics -This panics if the storage has an alignment or size smaller than that of `F`. + This panics if the storage has an alignment or size smaller than that of `F`. -*/ + */ - pub unsafe fn transmute_enum_ptr(this:P)->P::TransmutedPtr + pub unsafe fn transmute_enum_ptr(this: P) -> P::TransmutedPtr where - P:Deref, - P:CanTransmuteElement> + P: Deref, + P: CanTransmuteElement>, { - NonExhaustive::::assert_fits_within_storage(); - this.transmute_element::>() + NonExhaustive::::assert_fits_within_storage(); + this.transmute_element::>() } /// Gets a reference to the vtable of this `NonExhaustive<>`. - pub(crate) fn vtable(&self)->NonExhaustiveVtable_Ref{ + pub(crate) fn vtable(&self) -> NonExhaustiveVtable_Ref { self.vtable } - fn sabi_erased_ref(&self)->RRef<'_, ErasedObject>{ - unsafe{ - RRef::from_raw(&self.fill as *const ScratchSpace as *const ErasedObject) - } + fn sabi_erased_ref(&self) -> RRef<'_, ErasedObject> { + unsafe { RRef::from_raw(&self.fill as *const ScratchSpace as *const ErasedObject) } } - fn as_erased_ref(&self)->RRef<'_, ErasedObject>{ - unsafe{ - RRef::from_raw(self as *const Self as *const ErasedObject) - } + fn as_erased_ref(&self) -> RRef<'_, ErasedObject> { + unsafe { RRef::from_raw(self as *const Self as *const ErasedObject) } } - fn sabi_erased_mut(&mut self)->RMut<'_, ErasedObject>{ - unsafe{ - RMut::from_raw(&mut self.fill as *mut ScratchSpace as *mut ErasedObject) - } + fn sabi_erased_mut(&mut self) -> RMut<'_, ErasedObject> { + unsafe { RMut::from_raw(&mut self.fill as *mut ScratchSpace as *mut ErasedObject) } } } - -impl Clone for NonExhaustive +impl Clone for NonExhaustive where I: InterfaceBound>, { - fn clone(&self)->Self{ - unsafe{ - self.vtable().clone_()(self.sabi_erased_ref(),self.vtable) - } + fn clone(&self) -> Self { + unsafe { self.vtable().clone_()(self.sabi_erased_ref(), self.vtable) } } } -impl Display for NonExhaustive +impl Display for NonExhaustive where I: InterfaceBound>, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - unsafe{ + unsafe { c_functions::adapt_std_fmt::( self.sabi_erased_ref(), self.vtable().display(), - f + f, ) } } } -impl Debug for NonExhaustive +impl Debug for NonExhaustive where I: InterfaceBound>, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - unsafe{ + unsafe { c_functions::adapt_std_fmt::( self.sabi_erased_ref(), self.vtable().debug(), - f + f, ) } } } - -impl Eq for NonExhaustive +impl Eq for NonExhaustive where Self: PartialEq, I: InterfaceBound>, { } - -impl PartialEq> for NonExhaustive +impl PartialEq> for NonExhaustive where I1: InterfaceBound>, { - fn eq(&self, other: &NonExhaustive) -> bool { - unsafe{ - self.vtable().partial_eq()(self.sabi_erased_ref(), other.as_erased_ref()) - } + fn eq(&self, other: &NonExhaustive) -> bool { + unsafe { self.vtable().partial_eq()(self.sabi_erased_ref(), other.as_erased_ref()) } } } - -impl Ord for NonExhaustive +impl Ord for NonExhaustive where I: InterfaceBound>, Self: PartialOrd + Eq, { fn cmp(&self, other: &Self) -> Ordering { - unsafe{ - self.vtable().cmp()(self.sabi_erased_ref(), other.as_erased_ref()).into() - } + unsafe { self.vtable().cmp()(self.sabi_erased_ref(), other.as_erased_ref()).into() } } } - -impl PartialOrd> for NonExhaustive +impl PartialOrd> for NonExhaustive where I1: InterfaceBound>, - Self: PartialEq>, + Self: PartialEq>, { - fn partial_cmp(&self, other: &NonExhaustive) -> Option { - unsafe{ + fn partial_cmp(&self, other: &NonExhaustive) -> Option { + unsafe { self.vtable().partial_cmp()(self.sabi_erased_ref(), other.as_erased_ref()) .map(IntoReprRust::into_rust) .into() @@ -686,87 +620,76 @@ where } } - - ///////////////////// - -impl PartialOrd for NonExhaustive +impl PartialOrd for NonExhaustive where - E: GetEnumInfo+PartialOrd, + E: GetEnumInfo + PartialOrd, I: InterfaceBound>, Self: PartialEq, { fn partial_cmp(&self, other: &E) -> Option { - unsafe{ + unsafe { match self.as_enum() { - Ok(this)=>this.partial_cmp(other), - Err(_)=>Some(Ordering::Greater), + Ok(this) => this.partial_cmp(other), + Err(_) => Some(Ordering::Greater), } } } } -impl PartialEq for NonExhaustive +impl PartialEq for NonExhaustive where - E: GetEnumInfo+PartialEq, + E: GetEnumInfo + PartialEq, I: InterfaceBound>, { fn eq(&self, other: &E) -> bool { match self.as_enum() { - Ok(this)=>this==other, - Err(_)=>false, + Ok(this) => this == other, + Err(_) => false, } } } - ///////////////////// - -impl NonExhaustive{ +impl NonExhaustive { /// It serializes a `NonExhaustive<_>` into a proxy. pub fn serialize_into_proxy(&self) -> Result where - I: InterfaceBound>, - I: SerializeEnum>, + I: InterfaceBound>, + I: SerializeEnum>, { - unsafe{ - self.vtable().serialize()(self.as_erased_ref()).into_result() - } + unsafe { self.vtable().serialize()(self.as_erased_ref()).into_result() } } /// Deserializes a `NonExhaustive<_>` from a proxy. pub fn deserialize_from_proxy<'borr>(proxy: I::Proxy) -> Result where - I: InterfaceBound>, - I: DeserializeEnum<'borr,NonExhaustive>, - I::Proxy:'borr, - E:GetEnumInfo, + I: InterfaceBound>, + I: DeserializeEnum<'borr, NonExhaustive>, + I::Proxy: 'borr, + E: GetEnumInfo, { I::deserialize_enum(proxy) } - } - - - /** First it serializes a `NonExhaustive<_>` into a proxy,then it serializes that proxy. */ -impl Serialize for NonExhaustive +impl Serialize for NonExhaustive where I: InterfaceBound>, - I: SerializeEnum>, - I::Proxy:Serialize, + I: SerializeEnum>, + I::Proxy: Serialize, { fn serialize(&self, serializer: Z) -> Result where Z: Serializer, { - unsafe{ + unsafe { self.vtable().serialize()(self.as_erased_ref()) .into_result() .map_err(ser::Error::custom)? @@ -775,23 +698,22 @@ where } } - -/// First it Deserializes a string,then it deserializes into a +/// First it Deserializes a string,then it deserializes into a /// `NonExhaustive<_>`,by using `::deserialize_enum`. -impl<'de,E,S,I> Deserialize<'de> for NonExhaustive +impl<'de, E, S, I> Deserialize<'de> for NonExhaustive where - E: 'de+GetVTable, + E: 'de + GetVTable, S: 'de, - I: 'de+InterfaceBound>, - I: DeserializeEnum<'de,NonExhaustive>, - >>::Proxy:Deserialize<'de>, + I: 'de + InterfaceBound>, + I: DeserializeEnum<'de, NonExhaustive>, + >>::Proxy: Deserialize<'de>, { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { let s = < - >>::Proxy as + >>::Proxy as Deserialize >::deserialize(deserializer)?; @@ -799,13 +721,9 @@ where } } - - - ///////////////////// - -impl Hash for NonExhaustive +impl Hash for NonExhaustive where I: InterfaceBound>, { @@ -813,133 +731,121 @@ where where H: Hasher, { - unsafe{ - self.vtable().hash()(self.sabi_erased_ref(), HasherObject::new(state)) - } + unsafe { self.vtable().hash()(self.sabi_erased_ref(), HasherObject::new(state)) } } } - -impl std::error::Error for NonExhaustive -where +impl std::error::Error for NonExhaustive where I: InterfaceBound< Debug = Implemented, Display = Implemented, - Error = Implemented - >, -{} + Error = Implemented, + > +{ +} ///////////////////// +impl Drop for NonExhaustive { + fn drop(&mut self) { + let drop = self.vtable()._sabi_drop(); -impl Drop for NonExhaustive{ - fn drop(&mut self){ - let drop=self.vtable()._sabi_drop(); - - unsafe{ + unsafe { drop(self.sabi_erased_mut()); } } } - /////////////////////////////////////////////////////////////////////////////// /// Used to abstract over the reference-ness of `NonExhaustive<>` inside UnwrapEnumError. -pub trait NonExhaustiveSharedOps{ +pub trait NonExhaustiveSharedOps { /// The type of the discriminant of the wrapped enum. - type Discriminant:ValidDiscriminant; + type Discriminant: ValidDiscriminant; /// Gets the discriminant of the wrapped enum. - fn get_discriminant_(&self)->Self::Discriminant; - + fn get_discriminant_(&self) -> Self::Discriminant; + /// Gets miscelaneous information about the wrapped enum - fn enum_info_(&self)->&'static EnumInfo; + fn enum_info_(&self) -> &'static EnumInfo; } - /// A struct storing the discriminant and `EnumInfo` of some enum. -pub struct DiscrAndEnumInfo{ - discr:E, - enum_info:&'static EnumInfo, +pub struct DiscrAndEnumInfo { + discr: E, + enum_info: &'static EnumInfo, } - -impl DiscrAndEnumInfo{ +impl DiscrAndEnumInfo { /// Constructs this `DiscrAndEnumInfo`. - pub fn new(discr:E,enum_info:&'static EnumInfo)->Self{ - Self{discr,enum_info} + pub fn new(discr: E, enum_info: &'static EnumInfo) -> Self { + Self { discr, enum_info } } /// The value of the enum discriminant, - pub fn discr(&self)->E + pub fn discr(&self) -> E where - E:ValidDiscriminant + E: ValidDiscriminant, { self.discr } /// The `EnumInfo` of an enum. - pub fn enum_info(&self)->&'static EnumInfo{ + pub fn enum_info(&self) -> &'static EnumInfo { self.enum_info } } - impl NonExhaustiveSharedOps for DiscrAndEnumInfo where - E:ValidDiscriminant + E: ValidDiscriminant, { - type Discriminant=E; - fn get_discriminant_(&self)->E{ + type Discriminant = E; + fn get_discriminant_(&self) -> E { self.discr } - fn enum_info_(&self)->&'static EnumInfo{ + fn enum_info_(&self) -> &'static EnumInfo { self.enum_info } } - macro_rules! impl_neso { ( impl[$E:ident,$S:ident,$I:ident] - ) => ( - type Discriminant=$E::Discriminant; + ) => { + type Discriminant = $E::Discriminant; - fn get_discriminant_(&self)->$E::Discriminant { + fn get_discriminant_(&self) -> $E::Discriminant { self.get_discriminant() } - fn enum_info_(&self)->&'static EnumInfo{ + fn enum_info_(&self) -> &'static EnumInfo { self.vtable().enum_info() } - ) + }; } - -impl NonExhaustiveSharedOps for NonExhaustive +impl NonExhaustiveSharedOps for NonExhaustive where - E:GetEnumInfo, + E: GetEnumInfo, { - impl_neso!{ impl[E,S,I] } + impl_neso! { impl[E,S,I] } } -impl<'a,E,S,I> NonExhaustiveSharedOps for &'a NonExhaustive +impl<'a, E, S, I> NonExhaustiveSharedOps for &'a NonExhaustive where - E:GetEnumInfo, + E: GetEnumInfo, { - impl_neso!{ impl[E,S,I] } + impl_neso! { impl[E,S,I] } } -impl<'a,E,S,I> NonExhaustiveSharedOps for &'a mut NonExhaustive +impl<'a, E, S, I> NonExhaustiveSharedOps for &'a mut NonExhaustive where - E:GetEnumInfo, + E: GetEnumInfo, { - impl_neso!{ impl[E,S,I] } + impl_neso! { impl[E,S,I] } } - /////////////////////////////////////////////////////////////////////////////// - /** An error for a situation where a `NonExhaustive<>` could not be unwrapped into the enum because the discriminant wasn't valid in this context @@ -947,52 +853,49 @@ because the discriminant wasn't valid in this context */ #[must_use] #[repr(transparent)] -#[derive(Clone,PartialEq,Eq,PartialOrd,Ord,StableAbi)] -pub struct UnwrapEnumError{ +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, StableAbi)] +pub struct UnwrapEnumError { /// This field is either a `NonExhaustive<>` or a `DiscrAndEnumInfo<>` - pub non_exhaustive:N, - _priv:(), + pub non_exhaustive: N, + _priv: (), } - - -impl UnwrapEnumError{ +impl UnwrapEnumError { /// Gets the `non_exhaustive` field. #[must_use] - pub fn into_inner(self)->N{ + pub fn into_inner(self) -> N { self.non_exhaustive } /// Converts this into a boxed error. - pub fn into_boxed(self)->RBoxError + pub fn into_boxed(self) -> RBoxError where - N:NonExhaustiveSharedOps, + N: NonExhaustiveSharedOps, { - let x=DiscrAndEnumInfo{ - discr:self.non_exhaustive.get_discriminant_(), - enum_info:self.non_exhaustive.enum_info_(), + let x = DiscrAndEnumInfo { + discr: self.non_exhaustive.get_discriminant_(), + enum_info: self.non_exhaustive.enum_info_(), }; - let x=UnwrapEnumError::new(x); + let x = UnwrapEnumError::new(x); RBoxError::new(x) } } -impl UnwrapEnumError{ +impl UnwrapEnumError { #[inline] - const fn new(non_exhaustive:N)->Self{ - Self{ + const fn new(non_exhaustive: N) -> Self { + Self { non_exhaustive, - _priv:(), + _priv: (), } } } - impl Display for UnwrapEnumError where - N:NonExhaustiveSharedOps, + N: NonExhaustiveSharedOps, { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "Could not unwrap NonExhaustive into '{}'.\n\ @@ -1005,29 +908,24 @@ where impl Debug for UnwrapEnumError where - N:NonExhaustiveSharedOps, + N: NonExhaustiveSharedOps, { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("UnwrapEnumError") - .field("non_exhaustive",&"") - .field("discriminant",&self.non_exhaustive.get_discriminant_()) - .field("enum_info",&self.non_exhaustive.enum_info_()) - .finish() + .field("non_exhaustive", &"") + .field("discriminant", &self.non_exhaustive.get_discriminant_()) + .field("enum_info", &self.non_exhaustive.enum_info_()) + .finish() } } impl From> for RBoxError where - N:NonExhaustiveSharedOps + N: NonExhaustiveSharedOps, { - fn from(uee:UnwrapEnumError)->RBoxError{ + fn from(uee: UnwrapEnumError) -> RBoxError { uee.into_boxed() } } - -impl std::error::Error for UnwrapEnumError -where - N:NonExhaustiveSharedOps, -{} - +impl std::error::Error for UnwrapEnumError where N: NonExhaustiveSharedOps {} diff --git a/abi_stable/src/nonexhaustive_enum/nonexhaustive/tests.rs b/abi_stable/src/nonexhaustive_enum/nonexhaustive/tests.rs index eb39f9cd..3b7cfbe3 100644 --- a/abi_stable/src/nonexhaustive_enum/nonexhaustive/tests.rs +++ b/abi_stable/src/nonexhaustive_enum/nonexhaustive/tests.rs @@ -1,44 +1,31 @@ - use super::*; use crate::{ - test_utils::{ - check_formatting_equivalence, - }, nonexhaustive_enum::{ - GetEnumInfo, examples::{ - command_a, - command_b, - command_c, - command_h_mismatched_discriminant, - command_serde, - generic_a, - many_ranges_a, - many_ranges_b, + command_a, command_b, command_c, command_h_mismatched_discriminant, command_serde, + generic_a, many_ranges_a, many_ranges_b, }, + GetEnumInfo, }, + test_utils::check_formatting_equivalence, }; use core_extensions::SelfOps; - use std::{ cmp::{Ord, Ordering, PartialEq, PartialOrd}, collections::hash_map::DefaultHasher, - hash::{Hash,Hasher}, + hash::{Hash, Hasher}, sync::Arc, }; - - - #[test] -fn construct_deconstruct(){ +fn construct_deconstruct() { { - use self::command_a::{Foo as FooA}; - let mut variant_a=NonExhaustive::new(FooA::A); - let mut variant_b=NonExhaustive::new(FooA::B(11)); + use self::command_a::Foo as FooA; + let mut variant_a = NonExhaustive::new(FooA::A); + let mut variant_b = NonExhaustive::new(FooA::B(11)); assert_eq!(variant_a.as_enum(), Ok(&FooA::A)); assert_eq!(variant_b.as_enum(), Ok(&FooA::B(11))); @@ -50,11 +37,11 @@ fn construct_deconstruct(){ assert_eq!(variant_b.into_enum(), Ok(FooA::B(11))); } { - use self::command_b::{Foo as FooB}; + use self::command_b::Foo as FooB; - let mut variant_a=NonExhaustive::new(FooB::A); - let mut variant_b=NonExhaustive::new(FooB::B(11)); - let mut variant_c=NonExhaustive::new(FooB::C); + let mut variant_a = NonExhaustive::new(FooB::A); + let mut variant_b = NonExhaustive::new(FooB::B(11)); + let mut variant_c = NonExhaustive::new(FooB::C); assert_eq!(variant_a.as_enum(), Ok(&FooB::A)); assert_eq!(variant_b.as_enum(), Ok(&FooB::B(11))); @@ -70,105 +57,105 @@ fn construct_deconstruct(){ } } - #[test] -fn get_discriminant(){ +fn get_discriminant() { { use self::command_c::Foo as FooC; - let wrapped_a=NonExhaustive::new(FooC::A); - let wrapped_b=NonExhaustive::new(FooC::B(11)); - let wrapped_c=NonExhaustive::new(FooC::C); - let wrapped_d=NonExhaustive::new(FooC::D{name:"what".into()}); - - assert_eq!(wrapped_a.get_discriminant(),0); - assert_eq!(wrapped_b.get_discriminant(),1); - assert_eq!(wrapped_c.get_discriminant(),2); - assert_eq!(wrapped_d.get_discriminant(),3); + let wrapped_a = NonExhaustive::new(FooC::A); + let wrapped_b = NonExhaustive::new(FooC::B(11)); + let wrapped_c = NonExhaustive::new(FooC::C); + let wrapped_d = NonExhaustive::new(FooC::D { + name: "what".into(), + }); + + assert_eq!(wrapped_a.get_discriminant(), 0); + assert_eq!(wrapped_b.get_discriminant(), 1); + assert_eq!(wrapped_c.get_discriminant(), 2); + assert_eq!(wrapped_d.get_discriminant(), 3); } { use self::command_h_mismatched_discriminant::Foo; - let wrapped_a=NonExhaustive::new(Foo::A); - let wrapped_b=NonExhaustive::new(Foo::B); - let wrapped_c=NonExhaustive::new(Foo::C); + let wrapped_a = NonExhaustive::new(Foo::A); + let wrapped_b = NonExhaustive::new(Foo::B); + let wrapped_c = NonExhaustive::new(Foo::C); - assert_eq!(wrapped_a.get_discriminant(),40); - assert_eq!(wrapped_b.get_discriminant(),41); - assert_eq!(wrapped_c.get_discriminant(),42); + assert_eq!(wrapped_a.get_discriminant(), 40); + assert_eq!(wrapped_b.get_discriminant(), 41); + assert_eq!(wrapped_c.get_discriminant(), 42); } } - #[test] -fn is_valid_discriminant(){ +fn is_valid_discriminant() { { use self::command_c::Foo as FooC; - assert_eq!(FooC::is_valid_discriminant(0),true); - assert_eq!(FooC::is_valid_discriminant(1),true); - assert_eq!(FooC::is_valid_discriminant(2),true); - assert_eq!(FooC::is_valid_discriminant(3),true); - assert_eq!(FooC::is_valid_discriminant(4),false); - assert_eq!(FooC::is_valid_discriminant(5),false); + assert_eq!(FooC::is_valid_discriminant(0), true); + assert_eq!(FooC::is_valid_discriminant(1), true); + assert_eq!(FooC::is_valid_discriminant(2), true); + assert_eq!(FooC::is_valid_discriminant(3), true); + assert_eq!(FooC::is_valid_discriminant(4), false); + assert_eq!(FooC::is_valid_discriminant(5), false); } { use self::command_h_mismatched_discriminant::Foo; - assert_eq!(Foo::is_valid_discriminant(0),false); - assert_eq!(Foo::is_valid_discriminant(39),false); - assert_eq!(Foo::is_valid_discriminant(40),true); - assert_eq!(Foo::is_valid_discriminant(41),true); - assert_eq!(Foo::is_valid_discriminant(42),true); - assert_eq!(Foo::is_valid_discriminant(43),false); - assert_eq!(Foo::is_valid_discriminant(44),false); + assert_eq!(Foo::is_valid_discriminant(0), false); + assert_eq!(Foo::is_valid_discriminant(39), false); + assert_eq!(Foo::is_valid_discriminant(40), true); + assert_eq!(Foo::is_valid_discriminant(41), true); + assert_eq!(Foo::is_valid_discriminant(42), true); + assert_eq!(Foo::is_valid_discriminant(43), false); + assert_eq!(Foo::is_valid_discriminant(44), false); } { use self::many_ranges_a::Foo; - assert_eq!(Foo::is_valid_discriminant(0),true); - assert_eq!(Foo::is_valid_discriminant(1),false); - assert_eq!(Foo::is_valid_discriminant(2),false); - assert_eq!(Foo::is_valid_discriminant(39),false); - assert_eq!(Foo::is_valid_discriminant(40),true); - assert_eq!(Foo::is_valid_discriminant(41),true); - assert_eq!(Foo::is_valid_discriminant(42),true); - assert_eq!(Foo::is_valid_discriminant(43),false); - assert_eq!(Foo::is_valid_discriminant(44),false); - assert_eq!(Foo::is_valid_discriminant(58),false); - assert_eq!(Foo::is_valid_discriminant(59),false); - assert_eq!(Foo::is_valid_discriminant(60),true); - assert_eq!(Foo::is_valid_discriminant(61),true); - assert_eq!(Foo::is_valid_discriminant(62),false); - assert_eq!(Foo::is_valid_discriminant(63),false); + assert_eq!(Foo::is_valid_discriminant(0), true); + assert_eq!(Foo::is_valid_discriminant(1), false); + assert_eq!(Foo::is_valid_discriminant(2), false); + assert_eq!(Foo::is_valid_discriminant(39), false); + assert_eq!(Foo::is_valid_discriminant(40), true); + assert_eq!(Foo::is_valid_discriminant(41), true); + assert_eq!(Foo::is_valid_discriminant(42), true); + assert_eq!(Foo::is_valid_discriminant(43), false); + assert_eq!(Foo::is_valid_discriminant(44), false); + assert_eq!(Foo::is_valid_discriminant(58), false); + assert_eq!(Foo::is_valid_discriminant(59), false); + assert_eq!(Foo::is_valid_discriminant(60), true); + assert_eq!(Foo::is_valid_discriminant(61), true); + assert_eq!(Foo::is_valid_discriminant(62), false); + assert_eq!(Foo::is_valid_discriminant(63), false); } { use self::many_ranges_b::Foo; - assert_eq!(Foo::is_valid_discriminant(0),true); - assert_eq!(Foo::is_valid_discriminant(1),false); - assert_eq!(Foo::is_valid_discriminant(2),false); - assert_eq!(Foo::is_valid_discriminant(39),false); - assert_eq!(Foo::is_valid_discriminant(40),true); - assert_eq!(Foo::is_valid_discriminant(41),true); - assert_eq!(Foo::is_valid_discriminant(42),false); - assert_eq!(Foo::is_valid_discriminant(43),false); - assert_eq!(Foo::is_valid_discriminant(58),false); - assert_eq!(Foo::is_valid_discriminant(59),false); - assert_eq!(Foo::is_valid_discriminant(60),true); - assert_eq!(Foo::is_valid_discriminant(62),false); - assert_eq!(Foo::is_valid_discriminant(63),false); + assert_eq!(Foo::is_valid_discriminant(0), true); + assert_eq!(Foo::is_valid_discriminant(1), false); + assert_eq!(Foo::is_valid_discriminant(2), false); + assert_eq!(Foo::is_valid_discriminant(39), false); + assert_eq!(Foo::is_valid_discriminant(40), true); + assert_eq!(Foo::is_valid_discriminant(41), true); + assert_eq!(Foo::is_valid_discriminant(42), false); + assert_eq!(Foo::is_valid_discriminant(43), false); + assert_eq!(Foo::is_valid_discriminant(58), false); + assert_eq!(Foo::is_valid_discriminant(59), false); + assert_eq!(Foo::is_valid_discriminant(60), true); + assert_eq!(Foo::is_valid_discriminant(62), false); + assert_eq!(Foo::is_valid_discriminant(63), false); } } - // This also tests what happens between dynamic libraries. #[test] -fn transmuting_enums(){ - unsafe{ - use self::command_a::{Foo as FooA}; - use self::command_c::{Foo as FooC}; - - let mut variant_a=NonExhaustive::new(FooC::A).transmute_enum::(); - let mut variant_b=NonExhaustive::new(FooC::B(11)).transmute_enum::(); - let mut variant_c=NonExhaustive::new(FooC::C).transmute_enum::(); - let mut variant_d=FooC::D{name:"what".into()} - .piped(NonExhaustive::new) - .transmute_enum::(); +fn transmuting_enums() { + unsafe { + use self::{command_a::Foo as FooA, command_c::Foo as FooC}; + + let mut variant_a = NonExhaustive::new(FooC::A).transmute_enum::(); + let mut variant_b = NonExhaustive::new(FooC::B(11)).transmute_enum::(); + let mut variant_c = NonExhaustive::new(FooC::C).transmute_enum::(); + let mut variant_d = FooC::D { + name: "what".into(), + } + .piped(NonExhaustive::new) + .transmute_enum::(); assert_eq!(variant_c.is_valid_discriminant(), false); assert_eq!(variant_d.is_valid_discriminant(), false); @@ -190,83 +177,79 @@ fn transmuting_enums(){ } } - #[test] -fn clone_test(){ +fn clone_test() { use self::generic_a::Foo; - let arc=Arc::new(100); + let arc = Arc::new(100); assert_eq!(Arc::strong_count(&arc), 1); - let variant_a=NonExhaustive::new(Foo::>::A); - let variant_b=NonExhaustive::new(Foo::>::B); - let variant_c=NonExhaustive::new(Foo::>::C(arc.clone())); + let variant_a = NonExhaustive::new(Foo::>::A); + let variant_b = NonExhaustive::new(Foo::>::B); + let variant_c = NonExhaustive::new(Foo::>::C(arc.clone())); assert_eq!(Arc::strong_count(&arc), 2); - + assert_eq!(variant_a.clone(), variant_a); assert_eq!(variant_b.clone(), variant_b); { - let clone_c=variant_c.clone(); + let clone_c = variant_c.clone(); assert_eq!(Arc::strong_count(&arc), 3); assert_eq!(clone_c, variant_c); } assert_eq!(Arc::strong_count(&arc), 2); - assert_eq!(variant_a.clone(), Foo::A); assert_eq!(variant_b.clone(), Foo::B); { - let clone_c=variant_c.clone(); + let clone_c = variant_c.clone(); assert_eq!(Arc::strong_count(&arc), 3); assert_eq!(clone_c.clone(), Foo::C(arc.clone())); } assert_eq!(Arc::strong_count(&arc), 2); - drop(variant_c); assert_eq!(Arc::strong_count(&arc), 1); } - #[test] -fn fmt_test(){ - use self::command_serde::{Foo as FooC}; - - let variant_a=FooC::A; - let wrapped_a=NonExhaustive::new(variant_a.clone()); - - let variant_b=FooC::B(11); - let wrapped_b=NonExhaustive::new(variant_b.clone()); - - let variant_c=FooC::C; - let wrapped_c=NonExhaustive::new(variant_c.clone()); - - let variant_d=FooC::D{name:"what".into()}; - let wrapped_d=NonExhaustive::new(variant_d.clone()); - - check_formatting_equivalence(&variant_a,&wrapped_a); - check_formatting_equivalence(&variant_b,&wrapped_b); - check_formatting_equivalence(&variant_c,&wrapped_c); - check_formatting_equivalence(&variant_d,&wrapped_d); -} +fn fmt_test() { + use self::command_serde::Foo as FooC; + let variant_a = FooC::A; + let wrapped_a = NonExhaustive::new(variant_a.clone()); + let variant_b = FooC::B(11); + let wrapped_b = NonExhaustive::new(variant_b.clone()); + + let variant_c = FooC::C; + let wrapped_c = NonExhaustive::new(variant_c.clone()); + + let variant_d = FooC::D { + name: "what".into(), + }; + let wrapped_d = NonExhaustive::new(variant_d.clone()); + + check_formatting_equivalence(&variant_a, &wrapped_a); + check_formatting_equivalence(&variant_b, &wrapped_b); + check_formatting_equivalence(&variant_c, &wrapped_c); + check_formatting_equivalence(&variant_d, &wrapped_d); +} #[test] -fn cmp_test(){ +fn cmp_test() { use self::generic_a::Foo; - let variant_a=Foo::::A; - let wrapped_a=NonExhaustive::new(variant_a.clone()); - - let variant_b=Foo::::B; - let wrapped_b=NonExhaustive::new(variant_b.clone()); - - let variant_c=Foo::::C("what".into()); - let wrapped_c=NonExhaustive::new(variant_c.clone()); + let variant_a = Foo::::A; + let wrapped_a = NonExhaustive::new(variant_a.clone()); + + let variant_b = Foo::::B; + let wrapped_b = NonExhaustive::new(variant_b.clone()); - for wrapped in vec![&wrapped_a,&wrapped_b,&wrapped_c] { + let variant_c = Foo::::C("what".into()); + let wrapped_c = NonExhaustive::new(variant_c.clone()); + + for wrapped in vec![&wrapped_a, &wrapped_b, &wrapped_c] { assert_eq!(wrapped.cmp(&wrapped), Ordering::Equal); } assert_eq!(wrapped_a.cmp(&wrapped_b), Ordering::Less); @@ -277,14 +260,16 @@ fn cmp_test(){ loop_variables=$variant:ident,$wrapped:ident,$which_one:ident; var_b=$var_b:ident; var_c=$var_c:ident; - ) => ( + ) => { #[allow(unused_variables)] - for ($variant,$wrapped) in - vec![(&variant_a,&wrapped_a),(&variant_b,&wrapped_b),(&variant_c,&wrapped_c)] - { + for ($variant, $wrapped) in vec![ + (&variant_a, &wrapped_a), + (&variant_b, &wrapped_b), + (&variant_c, &wrapped_c), + ] { assert_eq!($wrapped == $which_one, true); assert_eq!($wrapped <= $which_one, true); - assert_eq!($wrapped >= $which_one, true ); + assert_eq!($wrapped >= $which_one, true); assert_eq!($wrapped < $which_one, false); assert_eq!($wrapped > $which_one, false); assert_eq!($wrapped != $which_one, false); @@ -312,79 +297,77 @@ fn cmp_test(){ assert_eq!(wrapped_b.partial_cmp(&$var_c), Some(Ordering::Less)); assert_eq!(wrapped_b.eq(&$var_c), false); assert_eq!(wrapped_b.ne(&$var_c), true); - - ) + }; } - cmp_tests!{ + cmp_tests! { loop_variables=variant,wrapped,variant; var_b=variant_b; var_c=variant_c; } - cmp_tests!{ + cmp_tests! { loop_variables=variant,wrapped,wrapped; var_b=wrapped_b; var_c=wrapped_c; } } - #[test] -fn hash_test(){ +fn hash_test() { use self::generic_a::Foo; - fn hash_value(v:&H)->u64{ - let mut hasher=DefaultHasher::new(); + fn hash_value(v: &H) -> u64 { + let mut hasher = DefaultHasher::new(); v.hash(&mut hasher); hasher.finish() } + let variant_a = Foo::::A; + let wrapped_a = NonExhaustive::new(variant_a.clone()); - let variant_a=Foo::::A; - let wrapped_a=NonExhaustive::new(variant_a.clone()); - - let variant_b=Foo::::B; - let wrapped_b=NonExhaustive::new(variant_b.clone()); - - let variant_c=Foo::::C("what".into()); - let wrapped_c=NonExhaustive::new(variant_c.clone()); - - for (variant,wrapped) in - vec![(&variant_a,&wrapped_a),(&variant_b,&wrapped_b),(&variant_c,&wrapped_c)] - { - assert_eq!(hash_value(variant),hash_value(wrapped)); - } -} + let variant_b = Foo::::B; + let wrapped_b = NonExhaustive::new(variant_b.clone()); + let variant_c = Foo::::C("what".into()); + let wrapped_c = NonExhaustive::new(variant_c.clone()); + for (variant, wrapped) in vec![ + (&variant_a, &wrapped_a), + (&variant_b, &wrapped_b), + (&variant_c, &wrapped_c), + ] { + assert_eq!(hash_value(variant), hash_value(wrapped)); + } +} #[test] fn serde_test() { - use self::command_serde::{Foo as FooC}; + use self::command_serde::Foo as FooC; - let variant_a=FooC::A; - let variant_b=FooC::B(10); - let variant_c=FooC::C; - let variant_d=FooC::D{name:"what".into()}; + let variant_a = FooC::A; + let variant_b = FooC::B(10); + let variant_c = FooC::C; + let variant_d = FooC::D { + name: "what".into(), + }; - let expected_a=NonExhaustive::new(variant_a.clone()); - let expected_b=NonExhaustive::new(variant_b.clone()); - let expected_c=NonExhaustive::new(variant_c.clone()); - let expected_d=NonExhaustive::new(variant_d.clone()); + let expected_a = NonExhaustive::new(variant_a.clone()); + let expected_b = NonExhaustive::new(variant_b.clone()); + let expected_c = NonExhaustive::new(variant_c.clone()); + let expected_d = NonExhaustive::new(variant_d.clone()); - let json_a=r#""A""#; - let json_dd_a=serde_json::to_string(&json_a).unwrap(); + let json_a = r#""A""#; + let json_dd_a = serde_json::to_string(&json_a).unwrap(); - let json_b=r#"{"B":10}"#; - let json_dd_b=serde_json::to_string(&json_b).unwrap(); + let json_b = r#"{"B":10}"#; + let json_dd_b = serde_json::to_string(&json_b).unwrap(); - let json_c=r#""C""#; - let json_dd_c=serde_json::to_string(&json_c).unwrap(); - - let json_d=r#"{"D":{"name":"what"}}"#; - let json_dd_d=serde_json::to_string(&json_d).unwrap(); + let json_c = r#""C""#; + let json_dd_c = serde_json::to_string(&json_c).unwrap(); + let json_d = r#"{"D":{"name":"what"}}"#; + let json_dd_d = serde_json::to_string(&json_d).unwrap(); assert_eq!( serde_json::from_str::>(r#" "oinoiasnd" "#).map_err(drop), @@ -392,30 +375,26 @@ fn serde_test() { ); assert_eq!( - NonExhaustiveFor::::deserialize_from_proxy( - r#"oinoiasnd"#.into() - ).map_err(drop), + NonExhaustiveFor::::deserialize_from_proxy(r#"oinoiasnd"#.into()).map_err(drop), Err(()), ); - for (json_dd,json,expected,variant) in - vec![ - (&*json_dd_a,json_a,&expected_a,&variant_a), - (&*json_dd_b,json_b,&expected_b,&variant_b), - (&*json_dd_c,json_c,&expected_c,&variant_c), - (&*json_dd_d,json_d,&expected_d,&variant_d), - ] - { + for (json_dd, json, expected, variant) in vec![ + (&*json_dd_a, json_a, &expected_a, &variant_a), + (&*json_dd_b, json_b, &expected_b, &variant_b), + (&*json_dd_c, json_c, &expected_c, &variant_c), + (&*json_dd_d, json_d, &expected_d, &variant_d), + ] { { - let deserialized=serde_json::from_str::>(json_dd).unwrap(); - assert_eq!(deserialized,*expected); - assert_eq!(deserialized,*variant); + let deserialized = serde_json::from_str::>(json_dd).unwrap(); + assert_eq!(deserialized, *expected); + assert_eq!(deserialized, *variant); } { - let deserialized= + let deserialized = NonExhaustiveFor::::deserialize_from_proxy(json.into()).unwrap(); - assert_eq!(deserialized,*expected); - assert_eq!(deserialized,*variant); + assert_eq!(deserialized, *expected); + assert_eq!(deserialized, *variant); } assert_eq!(&*serde_json::to_string(&expected).unwrap(), json_dd); @@ -423,5 +402,3 @@ fn serde_test() { assert_eq!(&*serde_json::to_string(&variant).unwrap(), json); } } - - diff --git a/abi_stable/src/nonexhaustive_enum/traits.rs b/abi_stable/src/nonexhaustive_enum/traits.rs index ce16f61e..c805ccc6 100644 --- a/abi_stable/src/nonexhaustive_enum/traits.rs +++ b/abi_stable/src/nonexhaustive_enum/traits.rs @@ -3,22 +3,20 @@ The traits releated to nonexhaustive enums. */ use std::{ - cmp::{Eq,Ord}, - fmt::{self,Debug}, + cmp::{Eq, Ord}, + fmt::{self, Debug}, }; - use crate::{ - std_types::{RStr,RBoxError}, + std_types::{RBoxError, RStr}, type_layout::StartLen, type_level::{ - impl_enum::{Implemented,Unimplemented}, + impl_enum::{Implemented, Unimplemented}, trait_marker, }, InterfaceType, }; - /** Gets the type whose type layout is used to represent this enum in `NonExhaustive<>`. @@ -27,13 +25,11 @@ Gets the type whose type layout is used to represent this enum in `NonExhaustive `Self::NonExhaustive` must describe the layout of this enum, with the size and alignment of `Storage`. */ -pub unsafe trait GetNonExhaustive:GetEnumInfo{ +pub unsafe trait GetNonExhaustive: GetEnumInfo { /// The type whose type layout is used to represent this enum. type NonExhaustive; } - - /** Describes the discriminant of an enum,and its valid values. @@ -42,120 +38,116 @@ Describes the discriminant of an enum,and its valid values. This must be an enum with a `#[repr(C)]` or `#[repr(SomeInteFgerType)]` attribute. */ -pub unsafe trait GetEnumInfo:Sized{ +pub unsafe trait GetEnumInfo: Sized { /// The type of the discriminant. - type Discriminant:ValidDiscriminant; + type Discriminant: ValidDiscriminant; /// The default storage type, /// used to store this enum inside `NonExhaustive<>`, /// and allow the enum to grow in size in newer ABI compatible versions. type DefaultStorage; - + /// The default InterfaceType, /// used to determine the traits that are required when constructing a `NonExhaustive<>`, /// and are then usable afterwards. type DefaultInterface; /// Information about the enum. - const ENUM_INFO:&'static EnumInfo; - + const ENUM_INFO: &'static EnumInfo; + /// The values of the discriminants of each variant. /// - fn discriminants()->&'static [Self::Discriminant]; + fn discriminants() -> &'static [Self::Discriminant]; /// Whether `discriminant` is one of the valid discriminants for this enum in this context. - fn is_valid_discriminant(discriminant:Self::Discriminant)->bool; + fn is_valid_discriminant(discriminant: Self::Discriminant) -> bool; } - pub use self::_enum_info::EnumInfo; -mod _enum_info{ +mod _enum_info { use super::*; /// Contains miscelaneous information about an enum. #[repr(C)] #[derive(StableAbi)] - pub struct EnumInfo{ + pub struct EnumInfo { /// The name of a type,eg:`Vec` for a `Vec`. - type_name:RStr<'static>, + type_name: RStr<'static>, + + strings: RStr<'static>, - strings:RStr<'static>, - /// The range inside of strings with the names of the variants of the enum,separated by ';'. - variant_names_start_len:StartLen, + variant_names_start_len: StartLen, } - impl EnumInfo{ + impl EnumInfo { #[doc(hidden)] pub const fn _for_derive( - type_name:RStr<'static>, - strings:RStr<'static>, - variant_names_start_len:StartLen, - )->Self{ - Self{ + type_name: RStr<'static>, + strings: RStr<'static>, + variant_names_start_len: StartLen, + ) -> Self { + Self { type_name, strings, variant_names_start_len, } } - + /// The name of a type,eg:`Foo` for a `Foo`. - pub fn type_name(&self)->&'static str{ + pub fn type_name(&self) -> &'static str { self.type_name.as_str() } /// The names of the variants of the enum,separated by ';'. - pub fn variant_names(&self)->&'static str{ + pub fn variant_names(&self) -> &'static str { &self.strings.as_str()[self.variant_names_start_len.to_range()] } } } -impl EnumInfo{ +impl EnumInfo { /// Gets an iterator over the names of the variants of the enum. - pub fn variant_names_iter(&self)->impl Iterator+'static+Debug+Clone { + pub fn variant_names_iter( + &self, + ) -> impl Iterator + 'static + Debug + Clone { self.variant_names().split_terminator(';') } } -impl Debug for EnumInfo{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ +impl Debug for EnumInfo { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("EnumInfo") - .field("type_name",&self.type_name()) - .field("variant_names",&IteratorAsList(self.variant_names_iter())) - .finish() + .field("type_name", &self.type_name()) + .field("variant_names", &IteratorAsList(self.variant_names_iter())) + .finish() } } - struct IteratorAsList(I); -impl Debug for IteratorAsList +impl Debug for IteratorAsList where - I:Iterator+Clone, - T:Debug, + I: Iterator + Clone, + T: Debug, { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - f.debug_list() - .entries(self.0.clone()) - .finish() + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.0.clone()).finish() } } - -///////////////////////////////////////////////////////////// +///////////////////////////////////////////////////////////// /// Marker trait for types that abi_stable supports as enum discriminants. /// /// This trait cannot be implemented outside of this module. -pub trait ValidDiscriminant:Sealed+Copy+Eq+Ord+Debug+Send+Sync+'static{} +pub trait ValidDiscriminant: Sealed + Copy + Eq + Ord + Debug + Send + Sync + 'static {} -mod sealed{ - pub trait Sealed{} +mod sealed { + pub trait Sealed {} } use self::sealed::Sealed; - macro_rules! impl_valid_discriminant { ( $($ty:ty),* $(,)* @@ -167,13 +159,10 @@ macro_rules! impl_valid_discriminant { ) } - -impl_valid_discriminant!{u8,i8,u16,i16,u32,i32,u64,i64,usize,isize} - +impl_valid_discriminant! {u8,i8,u16,i16,u32,i32,u64,i64,usize,isize} /////////////////////////////////////////////////////////////////////////////// - /** Describes how some enum is serialized. @@ -182,60 +171,49 @@ This is generally implemented by the interface of an enum [`InterfaceType`]: ../trait.InterfaceType.html */ -pub trait SerializeEnum{ +pub trait SerializeEnum { /// The intermediate type the `NE` is converted into,to serialize it. type Proxy; /// Serializes an enum into its proxy type. - fn serialize_enum(this:&NE) -> Result; + fn serialize_enum(this: &NE) -> Result; } - #[doc(hidden)] -pub trait GetSerializeEnumProxy:InterfaceType{ +pub trait GetSerializeEnumProxy: InterfaceType { type ProxyType; } -impl GetSerializeEnumProxy for I +impl GetSerializeEnumProxy for I where - I:InterfaceType, - I:GetSerializeEnumProxyHelper< - NE, - ::Serialize, - ProxyType=PT - >, + I: InterfaceType, + I: GetSerializeEnumProxyHelper::Serialize, ProxyType = PT>, { - type ProxyType=PT; + type ProxyType = PT; } #[doc(hidden)] -pub trait GetSerializeEnumProxyHelper:InterfaceType{ +pub trait GetSerializeEnumProxyHelper: InterfaceType { type ProxyType; } -impl - GetSerializeEnumProxyHelper> -for I +impl GetSerializeEnumProxyHelper> for I where - I:InterfaceType, - I:SerializeEnum, + I: InterfaceType, + I: SerializeEnum, { - type ProxyType=>::Proxy; + type ProxyType = >::Proxy; } -impl - GetSerializeEnumProxyHelper> -for I +impl GetSerializeEnumProxyHelper> for I where - I:InterfaceType, + I: InterfaceType, { - type ProxyType=(); + type ProxyType = (); } - /////////////////////////////////////// - /** Describes how a nonexhaustive enum is deserialized. @@ -248,7 +226,7 @@ This is generally implemented by the interface of an enum [`InterfaceType`]: ../trait.InterfaceType.html */ -pub trait DeserializeEnum<'borr,NE> { +pub trait DeserializeEnum<'borr, NE> { /// The intermediate type the `NE` is converted from,to deserialize it. type Proxy; @@ -257,44 +235,36 @@ pub trait DeserializeEnum<'borr,NE> { } #[doc(hidden)] -pub trait GetDeserializeEnumProxy<'borr,NE>:InterfaceType{ +pub trait GetDeserializeEnumProxy<'borr, NE>: InterfaceType { type ProxyType; } -impl<'borr,I,NE,PT> GetDeserializeEnumProxy<'borr,NE> for I +impl<'borr, I, NE, PT> GetDeserializeEnumProxy<'borr, NE> for I where - I:InterfaceType, - I:GetDeserializeEnumProxyHelper< - 'borr, - NE, - ::Deserialize, - ProxyType=PT - >, + I: InterfaceType, + I: GetDeserializeEnumProxyHelper<'borr, NE, ::Deserialize, ProxyType = PT>, { - type ProxyType=PT; + type ProxyType = PT; } - #[doc(hidden)] -pub trait GetDeserializeEnumProxyHelper<'borr,NE,IS>:InterfaceType{ +pub trait GetDeserializeEnumProxyHelper<'borr, NE, IS>: InterfaceType { type ProxyType; } -impl<'borr,I,NE> - GetDeserializeEnumProxyHelper<'borr,NE,Implemented> -for I +impl<'borr, I, NE> GetDeserializeEnumProxyHelper<'borr, NE, Implemented> + for I where - I:InterfaceType, - I:DeserializeEnum<'borr,NE> + I: InterfaceType, + I: DeserializeEnum<'borr, NE>, { - type ProxyType=>::Proxy; + type ProxyType = >::Proxy; } -impl<'borr,I,NE> - GetDeserializeEnumProxyHelper<'borr,NE,Unimplemented> -for I +impl<'borr, I, NE> + GetDeserializeEnumProxyHelper<'borr, NE, Unimplemented> for I where - I:InterfaceType, + I: InterfaceType, { - type ProxyType=(); + type ProxyType = (); } diff --git a/abi_stable/src/nonexhaustive_enum/vtable.rs b/abi_stable/src/nonexhaustive_enum/vtable.rs index 651502eb..322f7526 100644 --- a/abi_stable/src/nonexhaustive_enum/vtable.rs +++ b/abi_stable/src/nonexhaustive_enum/vtable.rs @@ -1,48 +1,43 @@ use std::{ - cmp::{PartialEq,Ord,PartialOrd}, - fmt::{Debug,Display}, + cmp::{Ord, PartialEq, PartialOrd}, + fmt::{Debug, Display}, hash::Hash, }; use crate::{ - erased_types::{c_functions,trait_objects,InterfaceType,FormattingMode,InterfaceBound}, + erased_types::{c_functions, trait_objects, FormattingMode, InterfaceBound, InterfaceType}, inline_storage::InlineStorage, - marker_type::{ErasedObject,UnsafeIgnoredType}, + marker_type::{ErasedObject, UnsafeIgnoredType}, nonexhaustive_enum::{ - alt_c_functions,NonExhaustive,EnumInfo,GetEnumInfo,SerializeEnum,GetSerializeEnumProxy, + alt_c_functions, EnumInfo, GetEnumInfo, GetSerializeEnumProxy, NonExhaustive, SerializeEnum, }, - prefix_type::{PrefixTypeTrait,WithMetadata,panic_on_missing_fieldname}, + prefix_type::{panic_on_missing_fieldname, PrefixTypeTrait, WithMetadata}, + sabi_types::{RMut, RRef}, + std_types::{RBoxError, RCmpOrdering, ROption, RResult, RString}, type_level::{ - impl_enum::{Implemented,Unimplemented}, + impl_enum::{Implemented, Unimplemented}, trait_marker, }, - sabi_types::{RRef, RMut}, - std_types::{ROption,RResult,RString,RCmpOrdering,RBoxError}, utils::Transmuter, StableAbi, }; - /// Gets the vtable of `NonExhaustive`. -pub unsafe trait GetVTable:GetEnumInfo{ +pub unsafe trait GetVTable: GetEnumInfo { #[doc(hidden)] - const VTABLE_VAL:NonExhaustiveVtable; + const VTABLE_VAL: NonExhaustiveVtable; - staticref!{ + staticref! { #[doc(hidden)] - const VTABLE_WM: WithMetadata> = + const VTABLE_WM: WithMetadata> = WithMetadata::new(PrefixTypeTrait::METADATA, Self::VTABLE_VAL) } - #[doc(hidden)] - const VTABLE_REF:NonExhaustiveVtable_Ref = unsafe{ - NonExhaustiveVtable_Ref(Self::VTABLE_WM.as_prefix()) - }; + const VTABLE_REF: NonExhaustiveVtable_Ref = + unsafe { NonExhaustiveVtable_Ref(Self::VTABLE_WM.as_prefix()) }; } - - /// The vtable for NonExhaustive<>. #[doc(hidden)] #[repr(C)] @@ -56,115 +51,117 @@ pub unsafe trait GetVTable:GetEnumInfo{ with_field_indices, //debug_print, )] -pub struct NonExhaustiveVtable{ - pub(crate) _sabi_tys:UnsafeIgnoredType<(E,S,I)>, - - pub enum_info:&'static EnumInfo, +pub struct NonExhaustiveVtable { + pub(crate) _sabi_tys: UnsafeIgnoredType<(E, S, I)>, + + pub enum_info: &'static EnumInfo, - pub(crate) _sabi_drop :unsafe extern "C" fn(this: RMut<'_, ErasedObject>), + pub(crate) _sabi_drop: unsafe extern "C" fn(this: RMut<'_, ErasedObject>), #[sabi(unsafe_opaque_field)] - pub(crate) _sabi_clone:Option< + pub(crate) _sabi_clone: Option< unsafe extern "C" fn( RRef<'_, ErasedObject>, - NonExhaustiveVtable_Ref, - )->NonExhaustive + NonExhaustiveVtable_Ref, + ) -> NonExhaustive, >, - pub(crate) _sabi_debug:Option< - unsafe extern "C" fn(RRef<'_, ErasedObject>, FormattingMode, &mut RString)->RResult<(),()> + pub(crate) _sabi_debug: Option< + unsafe extern "C" fn( + RRef<'_, ErasedObject>, + FormattingMode, + &mut RString, + ) -> RResult<(), ()>, >, - pub(crate) _sabi_display:Option< - unsafe extern "C" fn(RRef<'_, ErasedObject>, FormattingMode, &mut RString)->RResult<(),()> + pub(crate) _sabi_display: Option< + unsafe extern "C" fn( + RRef<'_, ErasedObject>, + FormattingMode, + &mut RString, + ) -> RResult<(), ()>, >, - #[sabi(unsafe_change_type=r##" + #[sabi(unsafe_change_type = r##" unsafe extern "C" fn( RRef<'_, ErasedObject> )->RResult< >>::ProxyType, RBoxError> "##)] - pub(crate) erased_sabi_serialize: Option< - unsafe extern "C" fn(RRef<'_, ErasedObject>)->RResult - >, - pub(crate) _sabi_partial_eq: Option< - unsafe extern "C" fn(RRef<'_, ErasedObject>,RRef<'_, ErasedObject>)->bool - >, + pub(crate) erased_sabi_serialize: + Option) -> RResult>, + pub(crate) _sabi_partial_eq: + Option, RRef<'_, ErasedObject>) -> bool>, pub(crate) _sabi_cmp: Option< - unsafe extern "C" fn(RRef<'_, ErasedObject>,RRef<'_, ErasedObject>)->RCmpOrdering, + unsafe extern "C" fn(RRef<'_, ErasedObject>, RRef<'_, ErasedObject>) -> RCmpOrdering, >, pub(crate) _sabi_partial_cmp: Option< - unsafe extern "C" fn(RRef<'_, ErasedObject>,RRef<'_, ErasedObject>)->ROption, + unsafe extern "C" fn( + RRef<'_, ErasedObject>, + RRef<'_, ErasedObject>, + ) -> ROption, >, #[sabi(last_prefix_field)] - pub(crate) _sabi_hash:Option< - unsafe extern "C" fn(RRef<'_, ErasedObject>,trait_objects::HasherObject<'_>) - >, + pub(crate) _sabi_hash: + Option, trait_objects::HasherObject<'_>)>, } - -unsafe impl Sync for NonExhaustiveVtable{} -unsafe impl Send for NonExhaustiveVtable{} - - -unsafe impl GetVTable for E -where - S:InlineStorage, - I:InterfaceType, - E:GetEnumInfo, - I::Sync:RequiresSync, - I::Send:RequiresSend, - I::Clone:InitCloneField, - I::Debug:InitDebugField, - I::Display:InitDisplayField, - I::Serialize:InitSerializeField, - I::PartialEq:InitPartialEqField, - I::PartialOrd:InitPartialOrdField, - I::Ord:InitOrdField, - I::Hash:InitHashField, +unsafe impl Sync for NonExhaustiveVtable {} +unsafe impl Send for NonExhaustiveVtable {} + +unsafe impl GetVTable for E +where + S: InlineStorage, + I: InterfaceType, + E: GetEnumInfo, + I::Sync: RequiresSync, + I::Send: RequiresSend, + I::Clone: InitCloneField, + I::Debug: InitDebugField, + I::Display: InitDisplayField, + I::Serialize: InitSerializeField, + I::PartialEq: InitPartialEqField, + I::PartialOrd: InitPartialOrdField, + I::Ord: InitOrdField, + I::Hash: InitHashField, { #[doc(hidden)] - const VTABLE_VAL:NonExhaustiveVtable= - NonExhaustiveVtable{ - _sabi_tys:UnsafeIgnoredType::DEFAULT, - enum_info:E::ENUM_INFO, - _sabi_drop:alt_c_functions::drop_impl::, - _sabi_clone:>::VALUE, - _sabi_debug:>::VALUE, - _sabi_display:>::VALUE, - erased_sabi_serialize:>::VALUE, - _sabi_partial_eq:>::VALUE, - _sabi_partial_cmp:>::VALUE, - _sabi_cmp:>::VALUE, - _sabi_hash:>::VALUE, - }; + const VTABLE_VAL: NonExhaustiveVtable = NonExhaustiveVtable { + _sabi_tys: UnsafeIgnoredType::DEFAULT, + enum_info: E::ENUM_INFO, + _sabi_drop: alt_c_functions::drop_impl::, + _sabi_clone: >::VALUE, + _sabi_debug: >::VALUE, + _sabi_display: >::VALUE, + erased_sabi_serialize: >::VALUE, + _sabi_partial_eq: >::VALUE, + _sabi_partial_cmp: >::VALUE, + _sabi_cmp: >::VALUE, + _sabi_hash: >::VALUE, + }; } +type UnerasedSerializeFn = unsafe extern "C" fn( + RRef<'_, ErasedObject>, +) -> RResult< + >>::ProxyType, + RBoxError, +>; - -type UnerasedSerializeFn= - unsafe extern "C" fn( - RRef<'_, ErasedObject> - )->RResult< >>::ProxyType, RBoxError>; - - -impl NonExhaustiveVtable_Ref{ - pub fn serialize(self)->UnerasedSerializeFn +impl NonExhaustiveVtable_Ref { + pub fn serialize(self) -> UnerasedSerializeFn where - I:InterfaceBound>, - I:GetSerializeEnumProxy>, + I: InterfaceBound>, + I: GetSerializeEnumProxy>, { - unsafe{ + unsafe { std::mem::transmute::< - unsafe extern "C" fn(RRef<'_, ErasedObject>)->RResult, - UnerasedSerializeFn, - >( self.priv_serialize() ) + unsafe extern "C" fn(RRef<'_, ErasedObject>) -> RResult, + UnerasedSerializeFn, + >(self.priv_serialize()) } } } - - use self::trait_bounds::*; -pub mod trait_bounds{ +pub mod trait_bounds { use super::*; macro_rules! declare_conditional_marker { @@ -175,10 +172,10 @@ pub mod trait_bounds{ ) => ( pub trait $trait_name<$self_,$Filler,$OrigPtr>{} - impl<$self_,$Filler,$OrigPtr> $trait_name<$self_,$Filler,$OrigPtr> + impl<$self_,$Filler,$OrigPtr> $trait_name<$self_,$Filler,$OrigPtr> for Unimplemented {} - + impl<$self_,$Filler,$OrigPtr> $trait_name<$self_,$Filler,$OrigPtr> for Implemented where @@ -212,7 +209,7 @@ pub mod trait_bounds{ const VALUE:Option<$field_ty>=None; } - impl<$enum_,$filler,$interf> $trait_name<$enum_,$filler,$interf> + impl<$enum_,$filler,$interf> $trait_name<$enum_,$filler,$interf> for Implemented where $($($where_preds_both)*)? @@ -240,25 +237,24 @@ pub mod trait_bounds{ ) } - - declare_conditional_marker!{ + declare_conditional_marker! { type Send; trait RequiresSend[E,S,I] where [ E:Send ] } - declare_conditional_marker!{ + declare_conditional_marker! { type Sync; trait RequiresSync[E,S,I] where [ E:Sync ] } - declare_field_initalizer!{ + declare_field_initalizer! { type Clone; trait InitCloneField[E,S,I] where_for_both[ E:GetEnumInfo, ] where [ E:Clone ] - _sabi_clone,clone_: + _sabi_clone,clone_: unsafe extern "C" fn( RRef<'_, ErasedObject>, NonExhaustiveVtable_Ref @@ -266,11 +262,11 @@ pub mod trait_bounds{ field_index=field_index_for__sabi_clone; value=alt_c_functions::clone_impl::, } - declare_field_initalizer!{ + declare_field_initalizer! { type Debug; trait InitDebugField[E,S,I] where [ E:Debug ] - _sabi_debug,debug: + _sabi_debug,debug: unsafe extern "C" fn( RRef<'_, ErasedObject>, FormattingMode, @@ -279,11 +275,11 @@ pub mod trait_bounds{ field_index=field_index_for__sabi_debug; value=c_functions::debug_impl::, } - declare_field_initalizer!{ + declare_field_initalizer! { type Display; trait InitDisplayField[E,S,I] where [ E:Display ] - _sabi_display,display: + _sabi_display,display: unsafe extern "C" fn( RRef<'_, ErasedObject>, FormattingMode, @@ -292,11 +288,11 @@ pub mod trait_bounds{ field_index=field_index_for__sabi_display; value=c_functions::display_impl::, } - declare_field_initalizer!{ + declare_field_initalizer! { type Serialize; trait InitSerializeField[E,S,I] where [ I:SerializeEnum> ] - erased_sabi_serialize,priv_serialize: + erased_sabi_serialize,priv_serialize: unsafe extern "C" fn(RRef<'_, ErasedObject>)->RResult; field_index=field_index_for_erased_sabi_serialize; value=unsafe{ @@ -310,7 +306,7 @@ pub mod trait_bounds{ }.to }, } - declare_field_initalizer!{ + declare_field_initalizer! { type PartialEq; trait InitPartialEqField[E,S,I] where_for_both[ E:GetEnumInfo, ] @@ -319,7 +315,7 @@ pub mod trait_bounds{ field_index=field_index_for__sabi_partial_eq; value=alt_c_functions::partial_eq_impl::, } - declare_field_initalizer!{ + declare_field_initalizer! { type PartialOrd; trait InitPartialOrdField[E,S,I] where_for_both[ E:GetEnumInfo, ] @@ -329,20 +325,20 @@ pub mod trait_bounds{ field_index=field_index_for__sabi_partial_cmp; value=alt_c_functions::partial_cmp_ord::, } - declare_field_initalizer!{ + declare_field_initalizer! { type Ord; trait InitOrdField[E,S,I] where_for_both[ E:GetEnumInfo, ] where [ E:Ord ] - _sabi_cmp,cmp: + _sabi_cmp,cmp: unsafe extern "C" fn( - RRef<'_, ErasedObject>, + RRef<'_, ErasedObject>, RRef<'_, ErasedObject>, )->RCmpOrdering; field_index=field_index_for__sabi_cmp; value=alt_c_functions::cmp_ord::, } - declare_field_initalizer!{ + declare_field_initalizer! { type Hash; trait InitHashField[E,S,I] where [ E:Hash ] @@ -351,4 +347,3 @@ pub mod trait_bounds{ value=c_functions::hash_Hash::, } } - diff --git a/abi_stable/src/pointer_trait.rs b/abi_stable/src/pointer_trait.rs index 0e8eb21c..ed088e9c 100644 --- a/abi_stable/src/pointer_trait.rs +++ b/abi_stable/src/pointer_trait.rs @@ -1,14 +1,11 @@ /*! Traits for pointers. */ -use std::{ - mem::ManuallyDrop, - ptr::NonNull, -}; +use std::{mem::ManuallyDrop, ptr::NonNull}; use crate::{ marker_type::NonOwningPhantom, - sabi_types::{MovePtr, RRef, RMut}, + sabi_types::{MovePtr, RMut, RRef}, utils::Transmuter, }; @@ -30,30 +27,27 @@ pub enum CallReferentDrop { No, } - /// Determines whether the pointer is deallocated. #[repr(u8)] -#[derive(Debug,Clone,Copy,PartialEq,Eq,StableAbi)] -pub enum Deallocate{ +#[derive(Debug, Clone, Copy, PartialEq, Eq, StableAbi)] +pub enum Deallocate { No, Yes, } - /////////// - /// What kind of pointer this is. -/// +/// /// The valid kinds are: -/// +/// /// - Reference:a `&T`,or a `Copy` wrapper struct containing a `&T` -/// +/// /// - MutReference:a `&mut T`,or a non-`Drop` wrapper struct containing a `&mut T` -/// +/// /// - SmartPointer: Any pointer type that's not a reference or a mutable reference. -/// -/// +/// +/// pub unsafe trait GetPointerKind: Sized { /// The kind of the pointer. type Kind: PointerKindVariant; @@ -61,7 +55,7 @@ pub unsafe trait GetPointerKind: Sized { /// What this pointer points to, /// if the type implements `std::ops::Deref` it must be the same as /// `::Target`. - /// + /// /// This is here so that pointers don't *have to* implement `Deref`. type PtrTarget; @@ -70,27 +64,26 @@ pub unsafe trait GetPointerKind: Sized { } /// A type-level equivalent of a PointerKind variant. -pub trait PointerKindVariant:Sealed{ +pub trait PointerKindVariant: Sealed { /// The value of the PointerKind variant Self is equivalent to. - const VALUE:PointerKind; + const VALUE: PointerKind; } use self::sealed::Sealed; -mod sealed{ - pub trait Sealed{} +mod sealed { + pub trait Sealed {} } - /// Describes the kind of a pointer. -#[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash,StableAbi)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash, StableAbi)] #[repr(u8)] -pub enum PointerKind{ +pub enum PointerKind { /// a `&T`,or a `Copy` wrapper struct containing a `&T` Reference, /// a `&mut T`,or a non-`Drop` wrapper struct containing a `&mut T` MutReference, /// Any pointer type that's not a reference or a mutable reference. - SmartPointer + SmartPointer, } /// The type-level equivalent of `PointerKind::Reference`. @@ -105,57 +98,54 @@ pub struct PK_MutReference; #[allow(non_camel_case_types)] pub struct PK_SmartPointer; -impl Sealed for PK_Reference{} -impl Sealed for PK_MutReference{} -impl Sealed for PK_SmartPointer{} +impl Sealed for PK_Reference {} +impl Sealed for PK_MutReference {} +impl Sealed for PK_SmartPointer {} -impl PointerKindVariant for PK_Reference{ - const VALUE:PointerKind=PointerKind::Reference; +impl PointerKindVariant for PK_Reference { + const VALUE: PointerKind = PointerKind::Reference; } -impl PointerKindVariant for PK_MutReference{ - const VALUE:PointerKind=PointerKind::MutReference; +impl PointerKindVariant for PK_MutReference { + const VALUE: PointerKind = PointerKind::MutReference; } -impl PointerKindVariant for PK_SmartPointer{ - const VALUE:PointerKind=PointerKind::SmartPointer; +impl PointerKindVariant for PK_SmartPointer { + const VALUE: PointerKind = PointerKind::SmartPointer; } -unsafe impl<'a,T> GetPointerKind for &'a T{ - type Kind=PK_Reference; +unsafe impl<'a, T> GetPointerKind for &'a T { + type Kind = PK_Reference; type PtrTarget = T; } -unsafe impl<'a,T> GetPointerKind for &'a mut T{ - type Kind=PK_MutReference; +unsafe impl<'a, T> GetPointerKind for &'a mut T { + type Kind = PK_MutReference; type PtrTarget = T; } - - /////////// - /// Whether the pointer can be transmuted to an equivalent pointer with `T` as the referent type. -/// +/// /// # Safety for implementor -/// +/// /// Implementors of this trait must ensure that: -/// -/// - The memory layout of this +/// +/// - The memory layout of this /// type is the same regardless of the type of the referent. -/// +/// /// - The pointer type is either `!Drop`(no drop glue either), /// or it uses a vtable to Drop the referent and deallocate the memory correctly. -/// +/// /// - `transmute_element_` must return a pointer to the same allocation as `self`, /// at the same offset, /// and with no reduced provenance /// (the range of addresses that are valid to dereference with pointers /// derived from the returned pointer). -/// +/// /// # Example -/// +/// /// ```rust /// use abi_stable::{ /// pointer_trait::{ @@ -165,7 +155,7 @@ unsafe impl<'a,T> GetPointerKind for &'a mut T{ /// sabi_types::StaticRef, /// std_types::{Tuple2, Tuple4}, /// }; -/// +/// /// fn main() { /// let reff = FooRef::new(&Tuple4::(3, 5, 8, 13)); /// @@ -173,12 +163,12 @@ unsafe impl<'a,T> GetPointerKind for &'a mut T{ /// let smaller = unsafe{ reff.transmute_element::>() }; /// assert_eq!(smaller.get(), &Tuple2(3u8, 5u16)); /// } -/// -/// +/// +/// /// #[derive(Debug, Copy, Clone)] /// #[repr(transparent)] /// struct FooRef(StaticRef); -/// +/// /// impl FooRef { /// pub const fn new(reff: &'static T) -> Self { /// Self(StaticRef::new(reff)) @@ -187,13 +177,13 @@ unsafe impl<'a,T> GetPointerKind for &'a mut T{ /// self.0.get() /// } /// } -/// +/// /// unsafe impl GetPointerKind for FooRef { /// type PtrTarget = T; /// type Kind = PK_Reference; /// } -/// -/// unsafe impl CanTransmuteElement for FooRef +/// +/// unsafe impl CanTransmuteElement for FooRef /// where /// T: 'static, /// U: 'static, @@ -204,16 +194,16 @@ unsafe impl<'a,T> GetPointerKind for &'a mut T{ /// FooRef(self.0.transmute_element_()) /// } /// } -/// +/// /// unsafe impl AsPtr for FooRef { /// fn as_ptr(&self) -> *const T { /// self.0.as_ptr() /// } /// } -/// -/// -/// -/// +/// +/// +/// +/// /// ``` pub unsafe trait CanTransmuteElement: GetPointerKind { /// The type of the pointer after it's element type has been changed. @@ -232,7 +222,7 @@ pub unsafe trait CanTransmuteElement: GetPointerKind { /// therefore transmuting from `&u8` to `&u16` is UB /// if the caller does not ensure that the reference is aligned to a multiple of 2 address. /// - /// + /// /// # Example /// /// ``` @@ -251,7 +241,7 @@ pub unsafe trait CanTransmuteElement: GetPointerKind { } /// Allows transmuting pointers to point to a different type. -pub trait TransmuteElement{ +pub trait TransmuteElement { /// Transmutes the element type of this pointer.. /// /// # Safety @@ -265,7 +255,7 @@ pub trait TransmuteElement{ /// therefore transmuting from `&u8` to `&u16` is UB /// if the caller does not ensure that the reference is aligned to a multiple of 2 address. /// - /// + /// /// # Example /// /// ``` @@ -281,7 +271,7 @@ pub trait TransmuteElement{ /// /// ``` #[inline(always)] - unsafe fn transmute_element(self) -> >::TransmutedPtr + unsafe fn transmute_element(self) -> >::TransmutedPtr where Self: CanTransmuteElement, { @@ -289,8 +279,7 @@ pub trait TransmuteElement{ } } -impl TransmuteElement for This{} - +impl TransmuteElement for This {} /////////// @@ -307,28 +296,25 @@ unsafe impl<'a, T: 'a, O: 'a> CanTransmuteElement for &'a T { unsafe impl<'a, T: 'a, O: 'a> CanTransmuteElement for &'a mut T { type TransmutedPtr = RMut<'a, O>; - unsafe fn transmute_element_(self) -> Self::TransmutedPtr { RMut::from_raw(self as *mut T as *mut O) } } - /////////////////////////////////////////////////////////////////////////////// - /// For getting a const raw pointer to the value that this points to. -/// +/// /// # Safety -/// +/// /// The implementor of this trait must return a pointer to the same data as /// `Deref::deref`, without constructing a `&Self::Target` in `as_ptr` /// (or any function it calls), -/// +/// /// The implementor of this trait must not override the defaulted methods. -/// +/// /// # Example -/// +/// /// ```rust /// use abi_stable::{ /// erased_types::interfaces::DebugDefEqInterface, @@ -339,31 +325,31 @@ unsafe impl<'a, T: 'a, O: 'a> CanTransmuteElement for &'a mut T { /// sabi_types::StaticRef, /// DynTrait, /// }; -/// +/// /// fn main() { /// let reff: DynTrait, DebugDefEqInterface> = /// DynTrait::from_any_ptr(BarRef::new(&1234i32), DebugDefEqInterface); /// /// assert_eq!(format!("{:?}", reff), "1234"); /// } -/// -/// +/// +/// /// #[derive(Debug, Copy, Clone)] /// #[repr(transparent)] /// struct BarRef(StaticRef); -/// +/// /// impl BarRef { /// pub const fn new(reff: &'static T) -> Self { /// Self(StaticRef::new(reff)) /// } /// } -/// +/// /// unsafe impl GetPointerKind for BarRef { /// type PtrTarget = T; /// type Kind = PK_Reference; /// } -/// -/// unsafe impl CanTransmuteElement for BarRef +/// +/// unsafe impl CanTransmuteElement for BarRef /// where /// T: 'static, /// U: 'static, @@ -374,14 +360,14 @@ unsafe impl<'a, T: 'a, O: 'a> CanTransmuteElement for &'a mut T { /// BarRef(self.0.transmute_element_()) /// } /// } -/// +/// /// unsafe impl AsPtr for BarRef { /// fn as_ptr(&self) -> *const T { /// self.0.as_ptr() /// } /// } -/// -/// +/// +/// /// ``` pub unsafe trait AsPtr: GetPointerKind { /// Gets a const raw pointer to the value that this points to. @@ -390,23 +376,23 @@ pub unsafe trait AsPtr: GetPointerKind { /// Converts this pointer to an `RRef`. #[inline(always)] fn as_rref(&self) -> RRef<'_, Self::PtrTarget> { - unsafe{ RRef::from_raw(self.as_ptr()) } + unsafe { RRef::from_raw(self.as_ptr()) } } } /// For getting a mutable raw pointer to the value that this points to. -/// +/// /// # Safety -/// +/// /// The implementor of this trait must return a pointer to the same data as /// `DerefMut::deref_mut`, /// without constructing a `&mut Self::Target` in `as_mut_ptr` /// (or any function it calls). -/// +/// /// The implementor of this trait must not override the defaulted methods. -/// +/// /// # Example -/// +/// /// ```rust /// use abi_stable::{ /// erased_types::interfaces::DEIteratorInterface, @@ -417,33 +403,33 @@ pub unsafe trait AsPtr: GetPointerKind { /// sabi_types::RMut, /// DynTrait, /// }; -/// +/// /// fn main() { /// let mut iter = 0..=5; /// let reff: DynTrait, DEIteratorInterface<_>> = /// DynTrait::from_any_ptr(QuxMut::new(&mut iter), DEIteratorInterface::NEW); /// /// assert_eq!(reff.collect::>(), [0, 1, 2, 3, 4, 5]); -/// +/// /// assert_eq!(iter.next(), None); /// } -/// -/// +/// +/// /// #[derive(Debug)] /// #[repr(transparent)] /// struct QuxMut<'a, T>(RMut<'a, T>); -/// +/// /// impl<'a, T> QuxMut<'a, T> { /// pub fn new(reff: &'a mut T) -> Self { /// Self(RMut::new(reff)) /// } /// } -/// +/// /// unsafe impl GetPointerKind for QuxMut<'_, T> { /// type PtrTarget = T; /// type Kind = PK_MutReference; /// } -/// +/// /// unsafe impl<'a, T: 'a, U: 'a> CanTransmuteElement for QuxMut<'a, T> { /// type TransmutedPtr = QuxMut<'a, U>; /// @@ -451,20 +437,20 @@ pub unsafe trait AsPtr: GetPointerKind { /// QuxMut(self.0.transmute_element_()) /// } /// } -/// +/// /// unsafe impl AsPtr for QuxMut<'_, T> { /// fn as_ptr(&self) -> *const T { /// self.0.as_ptr() /// } /// } -/// +/// /// unsafe impl AsMutPtr for QuxMut<'_, T> { /// fn as_mut_ptr(&mut self) -> *mut T { /// self.0.as_mut_ptr() /// } /// } -/// -/// +/// +/// /// ``` pub unsafe trait AsMutPtr: AsPtr { /// Gets a mutable raw pointer to the value that this points to. @@ -473,29 +459,28 @@ pub unsafe trait AsMutPtr: AsPtr { /// Converts this pointer to an `RRef`. #[inline(always)] fn as_rmut(&mut self) -> RMut<'_, Self::PtrTarget> { - unsafe{ RMut::from_raw(self.as_mut_ptr()) } + unsafe { RMut::from_raw(self.as_mut_ptr()) } } } /////////////////////////////////////////////////////////////////////////////// - /// For owned pointers, allows extracting their contents separate from deallocating them. -/// +/// /// # Safety -/// +/// /// Implementors must: -/// +/// /// - Implement this trait such that `get_move_ptr` can be called before `drop_allocation`. -/// +/// /// - Not override `with_move_ptr` -/// +/// /// - Not override `in_move_ptr` -/// +/// /// # Example -/// +/// /// Implementing this trait for a Box-like type. -/// +/// /// ```rust /// use abi_stable::{ /// pointer_trait::{ @@ -506,36 +491,36 @@ pub unsafe trait AsMutPtr: AsPtr { /// std_types::RString, /// StableAbi, /// }; -/// +/// /// use std::{ /// alloc::{self, Layout}, /// marker::PhantomData, /// mem::ManuallyDrop, /// }; -/// -/// +/// +/// /// fn main(){ /// let this = BoxLike::new(RString::from("12345")); /// /// let string: RString = this.in_move_ptr(|x: MovePtr<'_, RString>|{ /// MovePtr::into_inner(x) /// }); -/// +/// /// assert_eq!(string, "12345"); /// } -/// -/// +/// +/// /// #[repr(C)] /// #[derive(StableAbi)] /// pub struct BoxLike { /// ptr: *mut T, /// /// dropper: unsafe extern "C" fn(*mut T, CallReferentDrop), -/// +/// /// _marker: PhantomData, /// } -/// -/// +/// +/// /// impl BoxLike{ /// pub fn new(value:T)->Self{ /// let box_ = Box::new(value); @@ -547,18 +532,18 @@ pub unsafe trait AsMutPtr: AsPtr { /// } /// } /// } -/// +/// /// unsafe impl GetPointerKind for BoxLike { /// type PtrTarget = T; /// type Kind = PK_SmartPointer; /// } -/// +/// /// unsafe impl AsPtr for BoxLike { /// fn as_ptr(&self) -> *const T { /// self.ptr /// } /// } -/// +/// /// unsafe impl AsMutPtr for BoxLike { /// fn as_mut_ptr(&mut self) -> *mut T { /// self.ptr @@ -576,7 +561,7 @@ pub unsafe trait AsMutPtr: AsPtr { /// } /// } /// } -/// +/// /// impl Drop for BoxLike{ /// fn drop(&mut self){ /// unsafe{ @@ -584,7 +569,7 @@ pub unsafe trait AsMutPtr: AsPtr { /// } /// } /// } -/// +/// /// unsafe extern "C" fn destroy_box(v: *mut T, call_drop: CallReferentDrop) { /// abi_stable::extern_fn_panic_handling! { /// let mut box_ = Box::from_raw(v as *mut ManuallyDrop); @@ -594,8 +579,8 @@ pub unsafe trait AsMutPtr: AsPtr { /// drop(box_); /// } /// } -/// -/// +/// +/// /// ``` pub unsafe trait OwnedPointer: Sized + AsMutPtr + GetPointerKind { /// Gets a move pointer to the contents of this pointer. @@ -603,12 +588,12 @@ pub unsafe trait OwnedPointer: Sized + AsMutPtr + GetPointerKind { /// # Safety /// /// This function logically moves the owned contents out of this pointer, - /// the only safe thing that can be done with the pointer afterwads + /// the only safe thing that can be done with the pointer afterwads /// is to call `OwnedPointer::drop_allocation`. /// /// /// # Example - /// + /// /// ```rust /// use abi_stable::{ /// pointer_trait::OwnedPointer, @@ -625,12 +610,12 @@ pub unsafe trait OwnedPointer: Sized + AsMutPtr + GetPointerKind { /// // this is only called once, /// // and the `RVec` is never accessed again through the `RBox`. /// let moveptr: MovePtr<'_, RVec> = unsafe { OwnedPointer::get_move_ptr(&mut this) }; - /// + /// /// let vector: RVec = MovePtr::into_inner(moveptr); - /// + /// /// // safety: this is only called once, after all uses of `this` /// unsafe{ OwnedPointer::drop_allocation(&mut this); } - /// + /// /// assert_eq!(vector[..], [3, 5, 8]); /// /// ``` @@ -638,8 +623,8 @@ pub unsafe trait OwnedPointer: Sized + AsMutPtr + GetPointerKind { /// Deallocates the pointer without dropping its owned contents. /// - /// Note that if `Self::get_move_ptr` has not been called this will - /// leak the values owned by the referent of the pointer. + /// Note that if `Self::get_move_ptr` has not been called this will + /// leak the values owned by the referent of the pointer. /// /// # Safety /// @@ -647,17 +632,17 @@ pub unsafe trait OwnedPointer: Sized + AsMutPtr + GetPointerKind { /// since it'll deallocate whatever memory this pointer owns. /// /// # Example - /// + /// /// [`get_move_ptr` has an example](#get_move_ptr-example) that uses both that function /// and this one. unsafe fn drop_allocation(this: &mut ManuallyDrop); /// Runs a callback with the contents of this pointer, and then deallocates it. - /// + /// /// The pointer is deallocated even in the case that `func` panics - /// + /// /// # Example - /// + /// /// ```rust /// use abi_stable::{ /// pointer_trait::OwnedPointer, @@ -672,27 +657,27 @@ pub unsafe trait OwnedPointer: Sized + AsMutPtr + GetPointerKind { /// let cow: RCow<'static, [u8]> = OwnedPointer::with_move_ptr(this, |moveptr|{ /// MovePtr::into_inner(moveptr) /// }); - /// + /// /// assert_eq!(cow[..], [13, 21, 34]); /// /// ``` #[inline] - fn with_move_ptr(mut this: ManuallyDrop, func:F)->R - where - F: FnOnce(MovePtr<'_,Self::PtrTarget>) ->R, + fn with_move_ptr(mut this: ManuallyDrop, func: F) -> R + where + F: FnOnce(MovePtr<'_, Self::PtrTarget>) -> R, { - unsafe{ + unsafe { let guard = DropAllocationMutGuard(&mut this); func(Self::get_move_ptr(guard.0)) } } /// Runs a callback with the contents of this pointer, and then deallocates it. - /// + /// /// The pointer is deallocated even in the case that `func` panics - /// + /// /// # Example - /// + /// /// ```rust /// use abi_stable::{ /// pointer_trait::OwnedPointer, @@ -703,7 +688,7 @@ pub unsafe trait OwnedPointer: Sized + AsMutPtr + GetPointerKind { /// let this = RBox::new(Foo(41)); /// /// let cow: Foo = this.in_move_ptr(|moveptr| MovePtr::into_inner(moveptr) ); - /// + /// /// assert_eq!(cow, Foo(41)); /// /// @@ -713,11 +698,11 @@ pub unsafe trait OwnedPointer: Sized + AsMutPtr + GetPointerKind { /// /// ``` #[inline] - fn in_move_ptr(self, func:F)->R - where + fn in_move_ptr(self, func: F) -> R + where F: FnOnce(MovePtr<'_, Self::PtrTarget>) -> R, { - unsafe{ + unsafe { let mut guard = DropAllocationGuard(ManuallyDrop::new(self)); func(Self::get_move_ptr(&mut guard.0)) } @@ -729,9 +714,7 @@ struct DropAllocationGuard(ManuallyDrop); impl Drop for DropAllocationGuard { #[inline(always)] fn drop(&mut self) { - unsafe{ - T::drop_allocation(&mut self.0) - } + unsafe { T::drop_allocation(&mut self.0) } } } @@ -740,22 +723,18 @@ struct DropAllocationMutGuard<'a, T: OwnedPointer>(&'a mut ManuallyDrop); impl Drop for DropAllocationMutGuard<'_, T> { #[inline(always)] fn drop(&mut self) { - unsafe{ - T::drop_allocation(self.0) - } + unsafe { T::drop_allocation(self.0) } } } - /////////////////////////////////////////////////////////////////////////////// - /// Trait for non-owning pointers that are shared-reference-like. /// -/// # Safety +/// # Safety /// /// Implementors must only contain a non-null pointer [(*1)](#clarification1). -/// Meaning that they must be `#[repr(transparent)]` wrappers around +/// Meaning that they must be `#[repr(transparent)]` wrappers around /// `&`/`NonNull`/`impl ImmutableRef`. /// /// (*1) @@ -764,7 +743,7 @@ impl Drop for DropAllocationMutGuard<'_, T> { // # Implementation notes // // The default methods use `Transmuter` instead of: -// - `std::mem::transmute` because the compiler doesn't know that the size of +// - `std::mem::transmute` because the compiler doesn't know that the size of // `*const ()` and `Self` is the same // - `std::mem::transmute_copy`: incurrs function call overhead in unoptimized builds, // which is unnacceptable. @@ -780,67 +759,64 @@ pub unsafe trait ImmutableRef: Copy { /// Converts this pointer to a `NonNull`. #[inline(always)] - fn to_nonnull(self)->NonNull { - unsafe{ Transmuter{from: self}.to } + fn to_nonnull(self) -> NonNull { + unsafe { Transmuter { from: self }.to } } /// Constructs this pointer from a `NonNull`. - /// - /// # Safety - /// + /// + /// # Safety + /// /// `from` must be one of these: /// - /// - A pointer from a call to `ImmutableRef::to_nonnull` or + /// - A pointer from a call to `ImmutableRef::to_nonnull` or /// `ImmutableRef::to_raw_ptr` on an instance of `Self`, /// with the same lifetime. /// /// - Valid to transmute to Self. #[inline(always)] - unsafe fn from_nonnull(from: NonNull)->Self{ - unsafe{ Transmuter{from}.to } + unsafe fn from_nonnull(from: NonNull) -> Self { + unsafe { Transmuter { from }.to } } /// Converts this pointer to a raw pointer. #[inline(always)] - fn to_raw_ptr(self)->*const Self::Target { - unsafe{ Transmuter{from: self}.to } + fn to_raw_ptr(self) -> *const Self::Target { + unsafe { Transmuter { from: self }.to } } /// Constructs this pointer from a raw pointer. - /// + /// /// # Safety - /// + /// /// This has the same safety requirements as [`from_nonnull`](#method.from_nonnull) #[inline(always)] - unsafe fn from_raw_ptr(from: *const Self::Target)-> Option { - unsafe{ Transmuter{from}.to } + unsafe fn from_raw_ptr(from: *const Self::Target) -> Option { + unsafe { Transmuter { from }.to } } } /// Gets the `ImmutableRef::Target` associated type for `T`. pub type ImmutableRefOut = ::Target; - unsafe impl<'a, T> ImmutableRef for &'a T { type Target = T; #[inline(always)] #[cfg(miri)] - fn to_raw_ptr(self)->*const Self::Target { + fn to_raw_ptr(self) -> *const Self::Target { self as _ } - + #[inline(always)] #[cfg(miri)] - unsafe fn from_raw_ptr(from: *const Self::Target)-> Option { + unsafe fn from_raw_ptr(from: *const Self::Target) -> Option { std::mem::transmute(from) } } - //////////////////////////////////////////////////////////////////////////////// - /// A marker type that can be used as a proof that the `T` type parameter of /// `ImmutableRefTarget` /// implements `ImmutableRef`. @@ -848,7 +824,7 @@ pub struct ImmutableRefTarget(NonOwningPhantom<(T, U)>); impl Copy for ImmutableRefTarget {} impl Clone for ImmutableRefTarget { - fn clone(&self)->Self{ + fn clone(&self) -> Self { *self } } @@ -856,10 +832,10 @@ impl Clone for ImmutableRefTarget { impl ImmutableRefTarget { // This function is private on purpose. // - // This type is only supposed to be constructed in the default initializer for + // This type is only supposed to be constructed in the default initializer for // `ImmutableRef::TARGET`. #[inline(always)] - const fn new()->Self{ + const fn new() -> Self { Self(NonOwningPhantom::DEFAULT) } -} \ No newline at end of file +} diff --git a/abi_stable/src/prefix_type.rs b/abi_stable/src/prefix_type.rs index 3e98a8db..0d3929ea 100644 --- a/abi_stable/src/prefix_type.rs +++ b/abi_stable/src/prefix_type.rs @@ -10,8 +10,8 @@ use std::{ use crate::{ inline_storage::alignment::AlignToUsize, + marker_type::{NonOwningPhantom, NotCopyNotClone}, pointer_trait::ImmutableRef, - marker_type::{NotCopyNotClone, NonOwningPhantom}, sabi_types::StaticRef, utils::Transmuter, }; @@ -21,16 +21,16 @@ use core_extensions::SelfOps; mod accessible_fields; mod layout; -mod pt_metadata; mod prefix_ref; +mod pt_metadata; #[cfg(test)] mod tests; pub use self::{ accessible_fields::{ - BoolArray, BoolArrayIter, - FieldAccessibility, FieldConditionality, IsAccessible, IsConditional, + BoolArray, BoolArrayIter, FieldAccessibility, FieldConditionality, IsAccessible, + IsConditional, }, layout::PTStructLayout, prefix_ref::PrefixRef, @@ -58,27 +58,27 @@ pub unsafe trait PrefixTypeTrait: Sized { /// Convers `Self` to `Self::PrefixRef`,leaking it in the process. /// - /// # Warning + /// # Warning /// /// You must be careful when calling this function, /// since this leak is ignored by [miri](https://github.com/rust-lang/miri) . /// - fn leak_into_prefix(self)->Self::PrefixRef{ - let x=WithMetadata::new(Self::METADATA, self); - let x=StaticRef::leak_value(x); - let x=PrefixRef::from_staticref(x); + fn leak_into_prefix(self) -> Self::PrefixRef { + let x = WithMetadata::new(Self::METADATA, self); + let x = StaticRef::leak_value(x); + let x = PrefixRef::from_staticref(x); ::from_prefix_ref(x) } /// A struct that contains all the fields up to the field annotated with /// `#[sabi(last_prefix_field)]` inclusive. - /// + /// /// Those structs are usually named with a `_Prefix` suffix. type PrefixFields; /// A pointer to `Self::PrefixFields`, /// generally wraps a `PrefixRef`. - /// + /// /// Those pointer types are usually named with a `_Ref` suffix. type PrefixRef: PrefixRefTrait< Target = WithMetadata_, @@ -88,22 +88,21 @@ pub unsafe trait PrefixTypeTrait: Sized { //////////////////////////////////////////////////////////////////////////////// - /// Marker trait for pointers to prefix field structs. /// /// Generally prefix field structs are named with a `_Prefix` suffix, /// and have all the fields of some other struct up to the /// one with a `#[sabi(last_prefix_field)]` attribute. -/// +/// /// # Safety -/// -/// `Self` must either be `PrefixRef`, +/// +/// `Self` must either be `PrefixRef`, /// or a `#[repr(transparent)]` wrapper around one. pub unsafe trait PrefixRefTrait: Sized + ImmutableRef { /// A struct that contains all the fields of some other struct /// up to the field annotated with /// `#[sabi(last_prefix_field)]` inclusive. - /// + /// /// Those structs are usually named with a `_Prefix` suffix. // The `GetWithMetadata` bound // is a hacky way to encode this type equality bound: @@ -119,21 +118,21 @@ pub unsafe trait PrefixRefTrait: Sized + ImmutableRef { /// Converts a `PrefixRef` to `Self` #[inline] - fn from_prefix_ref(this: PrefixRef)->Self { - unsafe{ Transmuter{from: this}.to } + fn from_prefix_ref(this: PrefixRef) -> Self { + unsafe { Transmuter { from: this }.to } } - + /// Converts `Self` to a `PrefixRef` #[inline] - fn to_prefix_ref(self)->PrefixRef { - unsafe{ Transmuter{from: self}.to } + fn to_prefix_ref(self) -> PrefixRef { + unsafe { Transmuter { from: self }.to } } } //////////////////////////////////////////////////////////////////////////////// /// A helper trait for asserting that `WithMetadata_ == Self::ForSelf` -pub trait GetWithMetadata: Sized{ +pub trait GetWithMetadata: Sized { /// This is always `WithMetadata_` type ForSelf; } @@ -142,48 +141,46 @@ impl GetWithMetadata for T { type ForSelf = WithMetadata_; } - //////////////////////////////////////////////////////////////////////////////// /// A marker used to prove that `This` implements`PrefixRefTrait`. -pub struct PointsToPrefixFields{ - _phantomdata: NonOwningPhantom<(This, PF)> +pub struct PointsToPrefixFields { + _phantomdata: NonOwningPhantom<(This, PF)>, } -impl PointsToPrefixFields{ +impl PointsToPrefixFields { // This should only be callable in the default definition of PrefixRefTrait::PREFIX_FIELDS - const fn new()->Self{ - Self{_phantomdata: NonOwningPhantom::DEFAULT} + const fn new() -> Self { + Self { + _phantomdata: NonOwningPhantom::DEFAULT, + } } } //////////////////////////////////////////////////////////////////////////////// - /// Alias for [`WithMetadata_`] /// that defaults to passing `::PrefixFields` /// as the second type parameter. -/// +/// /// [`WithMetadata_`] can't have that defaulted type parameter, /// because trait bounds are incompatible with having `const fn` methods. -/// -/// +/// +/// /// [`WithMetadata_`]: ./struct.WithMetadata_.html -pub type WithMetadata::PrefixFields> = - WithMetadata_; - +pub type WithMetadata::PrefixFields> = WithMetadata_; /// Wraps a type along with its prefix-type-related metadata, /// so that it can be converted to its prefix. -/// +/// /// # Example -/// +/// /// This example demonstrates how you can construct a `WithMetadata` and /// convert it to a prefix type pointer (`Module_Ref` in this case). -/// -/// You can look at the [`PrefixRef` docs](./struct.PrefixRef.html#example) for +/// +/// You can look at the [`PrefixRef` docs](./struct.PrefixRef.html#example) for /// a more detailed example. -/// +/// /// ```rust /// use abi_stable::{ /// for_examples::{Module, Module_Ref}, @@ -191,7 +188,7 @@ pub type WithMetadata::PrefixFields> = /// std_types::{RSome, RStr}, /// staticref, /// }; -/// +/// /// const WITH_META: &WithMetadata = &WithMetadata::new( /// PrefixTypeTrait::METADATA, /// Module { @@ -200,14 +197,14 @@ pub type WithMetadata::PrefixFields> = /// third: 333, /// }, /// ); -/// +/// /// const MOD: Module_Ref = Module_Ref(WITH_META.static_as_prefix()); -/// +/// /// assert_eq!(MOD.first(), RSome(66)); /// assert_eq!(MOD.second().as_str(), "lore"); -/// +/// /// ``` -/// +/// #[repr(C)] pub struct WithMetadata_ { pub metadata: PrefixMetadata, @@ -232,9 +229,9 @@ impl WithMetadata_ { } /// Constructs a `PrefixRef` from `this`. - /// - /// # Safety - /// + /// + /// # Safety + /// /// You must enture that this `WithMetadata` lives for the entire program's lifetime. #[inline] pub const unsafe fn raw_as_prefix(this: *const Self) -> PrefixRef

{ @@ -242,9 +239,9 @@ impl WithMetadata_ { } /// Constructs a `PrefixRef` from `self`. - /// - /// # Safety - /// + /// + /// # Safety + /// /// You must ensure that `self` lives for the entire program's lifetime. /// /// # Alternative @@ -258,7 +255,7 @@ impl WithMetadata_ { } /// Constructs a `PrefixRef` from `self`. - /// + /// /// # Example /// /// ```rust @@ -267,7 +264,7 @@ impl WithMetadata_ { /// prefix_type::{PrefixRef, PrefixTypeTrait, WithMetadata}, /// std_types::{RSome, RStr}, /// }; - /// + /// /// const WITH_META: &WithMetadata = &WithMetadata::new( /// PrefixTypeTrait::METADATA, /// Module { @@ -276,20 +273,20 @@ impl WithMetadata_ { /// third: 100, /// }, /// ); - /// + /// /// const MOD: Module_Ref = Module_Ref(WITH_META.static_as_prefix()); - /// + /// /// assert_eq!(MOD.first(), RSome(13)); /// assert_eq!(MOD.second().as_str(), "foo"); - /// + /// /// ``` #[inline] pub const fn static_as_prefix(&'static self) -> PrefixRef

{ - PrefixRef::from_ref(self) + PrefixRef::from_ref(self) } } -impl StaticRef>{ +impl StaticRef> { /// Constructs a `PrefixRef

` from self. /// /// This is most useful when you have a generic type that isn't `'static` @@ -304,7 +301,7 @@ impl StaticRef>{ /// std_types::{RNone, RStr}, /// staticref, /// }; - /// + /// /// // The `staticref` invocation here declares a `StaticRef>` constant. /// const WITH_META: &WithMetadata = &WithMetadata::new( /// PrefixTypeTrait::METADATA, @@ -314,12 +311,12 @@ impl StaticRef>{ /// third: 100, /// }, /// ); - /// + /// /// const MOD: Module_Ref = Module_Ref(WITH_META.static_as_prefix()); - /// + /// /// assert_eq!(MOD.first(), RNone); /// assert_eq!(MOD.second().as_str(), "hello"); - /// + /// /// ``` pub const fn as_prefix(self) -> PrefixRef

{ PrefixRef::from_staticref(self) @@ -350,7 +347,7 @@ where impl Copy for PrefixMetadata {} impl Clone for PrefixMetadata { - fn clone(&self)->Self{ + fn clone(&self) -> Self { *self } } @@ -361,7 +358,7 @@ impl PrefixMetadata { pub const fn field_accessibility(&self) -> FieldAccessibility { self.field_accessibility } - + /// The basic layout of the prefix type, for error messages. #[inline] pub const fn type_layout(&self) -> &'static PTStructLayout { @@ -369,16 +366,15 @@ impl PrefixMetadata { } } -impl Debug for PrefixMetadata{ - fn fmt(&self, f: &mut fmt::Formatter<'_>)-> fmt::Result { +impl Debug for PrefixMetadata { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("PrefixMetadata") - .field("field_accessibility", &self.field_accessibility) - .field("type_layout", &self.type_layout) - .finish() + .field("field_accessibility", &self.field_accessibility) + .field("type_layout", &self.type_layout) + .finish() } } - //////////////////////////////////////////////////////////////////////////////// /// Used to panic with an error message informing the user that a field diff --git a/abi_stable/src/prefix_type/accessible_fields.rs b/abi_stable/src/prefix_type/accessible_fields.rs index 3e5384da..5a1f6aa5 100644 --- a/abi_stable/src/prefix_type/accessible_fields.rs +++ b/abi_stable/src/prefix_type/accessible_fields.rs @@ -1,330 +1,303 @@ -use crate::const_utils::{ - min_usize, - low_bit_mask_u64, -}; +use crate::const_utils::{low_bit_mask_u64, min_usize}; use std::{ + fmt::{self, Debug}, iter::ExactSizeIterator, - fmt::{self,Debug}, marker::PhantomData, }; - /// An array of 64 binary enums. -#[must_use="BoolArray is returned by value by every mutating method."] -#[derive(StableAbi)] -#[derive(PartialEq,Eq)] +#[must_use = "BoolArray is returned by value by every mutating method."] +#[derive(StableAbi, PartialEq, Eq)] #[repr(transparent)] -pub struct BoolArray{ - bits:u64, - _marker:PhantomData, +pub struct BoolArray { + bits: u64, + _marker: PhantomData, } -impl Copy for BoolArray{} -impl Clone for BoolArray{ - fn clone(&self)->Self{ - Self{ - bits:self.bits, - _marker:PhantomData, +impl Copy for BoolArray {} +impl Clone for BoolArray { + fn clone(&self) -> Self { + Self { + bits: self.bits, + _marker: PhantomData, } } } -/// An array with whether the ith field of a prefix-type +/// An array with whether the ith field of a prefix-type /// is accessible through its accessor method. -pub type FieldAccessibility=BoolArray; +pub type FieldAccessibility = BoolArray; -/// An array with whether the ith field in the prefix of a prefix-type +/// An array with whether the ith field in the prefix of a prefix-type /// is conditional,which means whether it has the /// `#[sabi(accessible_if=" expression ")]` attribute applied to it. -pub type FieldConditionality=BoolArray; - +pub type FieldConditionality = BoolArray; -impl BoolArray{ +impl BoolArray { /// Creates a BoolArray where the first `count` elements are truthy. #[inline] - pub const fn with_count(count:usize)->Self{ - Self{ - bits:low_bit_mask_u64(count as u32), - _marker:PhantomData, + pub const fn with_count(count: usize) -> Self { + Self { + bits: low_bit_mask_u64(count as u32), + _marker: PhantomData, } } /// Creates a BoolArray from a u64. #[inline] - pub const fn from_u64(bits:u64)->Self{ - Self{ + pub const fn from_u64(bits: u64) -> Self { + Self { bits, - _marker:PhantomData, + _marker: PhantomData, } } /// Creates a BoolArray where all elements are falsy. #[inline] - pub const fn empty()->Self{ - Self{ - bits:0, - _marker:PhantomData, + pub const fn empty() -> Self { + Self { + bits: 0, + _marker: PhantomData, } } #[inline] - const fn index_to_bits(index:usize)->u64{ - let index=index as u32; - [0,1u64.wrapping_shl(index)][(index <= 63) as usize] + const fn index_to_bits(index: usize) -> u64 { + let index = index as u32; + [0, 1u64.wrapping_shl(index)][(index <= 63) as usize] } /// Truncates self so that only the first `length` elements are truthy. - pub const fn truncated(mut self,length:usize)->Self{ - let mask=Self::with_count(length).bits(); - self.bits&=mask; + pub const fn truncated(mut self, length: usize) -> Self { + let mask = Self::with_count(length).bits(); + self.bits &= mask; self } /// Converts this array to its underlying representation #[inline] - pub const fn bits(self)->u64{ + pub const fn bits(self) -> u64 { self.bits } /// An iterator over the first `count` elements of the array. - pub const fn iter_count(self,count:usize)->BoolArrayIter{ - BoolArrayIter{ - count:min_usize(64,count), - bits:self.bits(), - _marker:PhantomData, + pub const fn iter_count(self, count: usize) -> BoolArrayIter { + BoolArrayIter { + count: min_usize(64, count), + bits: self.bits(), + _marker: PhantomData, } } /// Whether this array is equal to `other` up to the `count` element. - pub fn is_compatible(self,other:Self,count:usize)->bool{ - let all_accessible=Self::with_count(count); - let implication=(!self.bits|other.bits)&all_accessible.bits; + pub fn is_compatible(self, other: Self, count: usize) -> bool { + let all_accessible = Self::with_count(count); + let implication = (!self.bits | other.bits) & all_accessible.bits; println!( - "self:{:b}\nother:{:b}\nall_accessible:{:b}\nimplication:{:b}", - self.bits, - other.bits, - all_accessible.bits, - implication, + "self:{:b}\nother:{:b}\nall_accessible:{:b}\nimplication:{:b}", + self.bits, other.bits, all_accessible.bits, implication, ); - implication==all_accessible.bits + implication == all_accessible.bits } } - -impl FieldAccessibility{ +impl FieldAccessibility { /// Queries whether the field at the `index` position is accessible. #[inline] - pub const fn is_accessible(self,index:usize)->bool{ - let bits=Self::index_to_bits(index); - (self.bits&bits)!=0 + pub const fn is_accessible(self, index: usize) -> bool { + let bits = Self::index_to_bits(index); + (self.bits & bits) != 0 } /// Sets the accessibility of a field based on `cond`, /// on IsAccessible::Yes the field becomes accessible, /// on IsAccessible::No the field becomes inaccessible. #[inline] - pub const fn set_accessibility(mut self,index:usize,cond:IsAccessible)->Self{ - let bits=Self::index_to_bits(index); - self.bits=[self.bits&!bits,self.bits|bits][cond as usize]; + pub const fn set_accessibility(mut self, index: usize, cond: IsAccessible) -> Self { + let bits = Self::index_to_bits(index); + self.bits = [self.bits & !bits, self.bits | bits][cond as usize]; self } - } -impl FieldConditionality{ +impl FieldConditionality { /// Queries whether the field at the `index` position is conditional. #[inline] - pub const fn is_conditional(self,index:usize)->bool{ - let bits=Self::index_to_bits(index); - (self.bits&bits)!=0 + pub const fn is_conditional(self, index: usize) -> bool { + let bits = Self::index_to_bits(index); + (self.bits & bits) != 0 } /// Sets the conditionality of a field based on `cond`, /// on IsConditional::Yes the field becomes conditional, /// on IsConditional::No the field becomes unconditional. #[inline] - pub const fn set_conditionality(mut self,index:usize,cond:IsConditional)->Self{ - let bits=Self::index_to_bits(index); - self.bits=[self.bits&!bits,self.bits|bits][cond as usize]; + pub const fn set_conditionality(mut self, index: usize, cond: IsConditional) -> Self { + let bits = Self::index_to_bits(index); + self.bits = [self.bits & !bits, self.bits | bits][cond as usize]; self } - } - impl Debug for BoolArray where - T:BooleanEnum + T: BooleanEnum, { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - f.debug_list() - .entries(self.iter_count(64)) - .finish() + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.iter_count(64)).finish() } } - //////////////////////////////////////////////////////////////////////////////// /// A trait for enums with two variants where one is `truthy` and the other one is `falsy`. -pub trait BooleanEnum:Debug{ +pub trait BooleanEnum: Debug { /// The custom name of this type. - const NAME:&'static str; + const NAME: &'static str; /// Constructs this type from a boolean - fn from_bool(b:bool)->Self; + fn from_bool(b: bool) -> Self; } //////////////////////////////////////////////////////////////////////////////// /// Whether a field is accessible. -#[derive(StableAbi)] -#[derive(Debug,Copy,Clone,PartialEq,Eq)] +#[derive(StableAbi, Debug, Copy, Clone, PartialEq, Eq)] #[repr(u8)] -pub enum IsAccessible{ - No=0, - Yes=1, +pub enum IsAccessible { + No = 0, + Yes = 1, } -impl IsAccessible{ +impl IsAccessible { /// Constructs an IsAccessible with a bool saying whether this is accessible. - pub const fn new(is_accessible:bool)->Self{ - [IsAccessible::No,IsAccessible::Yes][is_accessible as usize] + pub const fn new(is_accessible: bool) -> Self { + [IsAccessible::No, IsAccessible::Yes][is_accessible as usize] } /// Describes whether this is accessible. - pub const fn is_accessible(self)->bool{ - self as usize!=0 + pub const fn is_accessible(self) -> bool { + self as usize != 0 } } -impl BooleanEnum for IsAccessible{ - const NAME:&'static str="IsAccessible"; +impl BooleanEnum for IsAccessible { + const NAME: &'static str = "IsAccessible"; - fn from_bool(b:bool)->Self{ + fn from_bool(b: bool) -> Self { Self::new(b) } } - //////////////////////////////////////////////////////////////////////////////// /// Whether a field is conditional, /// whether it has a `#[sabi(accessible_if=" expression ")]` helper attribute or not. -#[derive(StableAbi)] -#[derive(Debug,Copy,Clone,PartialEq,Eq)] +#[derive(StableAbi, Debug, Copy, Clone, PartialEq, Eq)] #[repr(u8)] -pub enum IsConditional{ - No=0, - Yes=1, +pub enum IsConditional { + No = 0, + Yes = 1, } -impl IsConditional{ +impl IsConditional { /// Constructs an IsConditional with a bool saying this is conditional. - pub const fn new(is_accessible:bool)->Self{ - [IsConditional::No,IsConditional::Yes][is_accessible as usize] + pub const fn new(is_accessible: bool) -> Self { + [IsConditional::No, IsConditional::Yes][is_accessible as usize] } /// Describes whether this is conditional. - pub const fn is_conditional(self)->bool{ - self as usize!=0 + pub const fn is_conditional(self) -> bool { + self as usize != 0 } } -impl BooleanEnum for IsConditional{ - const NAME:&'static str="IsConditional"; +impl BooleanEnum for IsConditional { + const NAME: &'static str = "IsConditional"; - fn from_bool(b:bool)->Self{ + fn from_bool(b: bool) -> Self { Self::new(b) } } - //////////////////////////////////////////////////////////////////////////////// - - -#[derive(Debug,Clone)] -pub struct BoolArrayIter{ - count:usize, - bits:u64, - _marker:PhantomData, +#[derive(Debug, Clone)] +pub struct BoolArrayIter { + count: usize, + bits: u64, + _marker: PhantomData, } - impl BoolArrayIter where - T:BooleanEnum, + T: BooleanEnum, { #[inline] - fn next_inner(&mut self,f:F)->Option - where F:FnOnce(&mut Self)->bool + fn next_inner(&mut self, f: F) -> Option + where + F: FnOnce(&mut Self) -> bool, { - if self.count==0 { + if self.count == 0 { None - }else{ + } else { Some(T::from_bool(f(self))) } } } impl Iterator for BoolArrayIter where - T:BooleanEnum, + T: BooleanEnum, { - type Item=T; + type Item = T; - fn next(&mut self)->Option{ - self.next_inner(|this|{ - this.count-=1; - let cond=(this.bits&1)!=0; - this.bits>>=1; + fn next(&mut self) -> Option { + self.next_inner(|this| { + this.count -= 1; + let cond = (this.bits & 1) != 0; + this.bits >>= 1; cond }) } #[inline] - fn size_hint(&self)->(usize,Option) { - (self.len(),Some(self.len())) + fn size_hint(&self) -> (usize, Option) { + (self.len(), Some(self.len())) } } - impl DoubleEndedIterator for BoolArrayIter where - T:BooleanEnum, + T: BooleanEnum, { - fn next_back(&mut self)->Option{ - self.next_inner(|this|{ - this.count-=1; - (this.bits&(1< Option { + self.next_inner(|this| { + this.count -= 1; + (this.bits & (1 << this.count)) != 0 }) } } impl ExactSizeIterator for BoolArrayIter where - T:BooleanEnum, + T: BooleanEnum, { #[inline] - fn len(&self)->usize{ + fn len(&self) -> usize { self.count } } - - //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// - - -#[cfg(all(test,not(feature="only_new_tests")))] -mod tests{ +#[cfg(all(test, not(feature = "only_new_tests")))] +mod tests { use super::*; - + #[test] - fn with_count(){ + fn with_count() { for count in 0..=64 { - let accessibility=BoolArray::with_count(count); + let accessibility = BoolArray::with_count(count); for i in 0..64 { assert_eq!( @@ -337,46 +310,44 @@ mod tests{ } } } - + #[test] - fn set_accessibility(){ - let mut accessibility=BoolArray::with_count(8); - assert_eq!(0b_1111_1111,accessibility.bits()); - + fn set_accessibility() { + let mut accessibility = BoolArray::with_count(8); + assert_eq!(0b_1111_1111, accessibility.bits()); + { - let mut accessibility=accessibility; - - accessibility=accessibility.set_accessibility(0,IsAccessible::No); - assert_eq!(0b_1111_1110,accessibility.bits()); + let mut accessibility = accessibility; + + accessibility = accessibility.set_accessibility(0, IsAccessible::No); + assert_eq!(0b_1111_1110, accessibility.bits()); - accessibility=accessibility.set_accessibility(2,IsAccessible::No); - assert_eq!(0b_1111_1010,accessibility.bits()); + accessibility = accessibility.set_accessibility(2, IsAccessible::No); + assert_eq!(0b_1111_1010, accessibility.bits()); - accessibility=accessibility.set_accessibility(1,IsAccessible::No); - assert_eq!(0b_1111_1000,accessibility.bits()); + accessibility = accessibility.set_accessibility(1, IsAccessible::No); + assert_eq!(0b_1111_1000, accessibility.bits()); } - - accessibility=accessibility.set_accessibility(3,IsAccessible::No); - assert_eq!(0b_1111_0111,accessibility.bits()); - - accessibility=accessibility.set_accessibility(5,IsAccessible::No); - assert_eq!(0b_1101_0111,accessibility.bits()); - - accessibility=accessibility.set_accessibility(6,IsAccessible::No); - assert_eq!(0b_1001_0111,accessibility.bits()); - - accessibility=accessibility.set_accessibility(10,IsAccessible::Yes); - assert_eq!(0b_0100_1001_0111,accessibility.bits()); - - accessibility=accessibility.set_accessibility(63,IsAccessible::Yes); - assert_eq!((1<<63)|0b_0100_1001_0111,accessibility.bits()); - + + accessibility = accessibility.set_accessibility(3, IsAccessible::No); + assert_eq!(0b_1111_0111, accessibility.bits()); + + accessibility = accessibility.set_accessibility(5, IsAccessible::No); + assert_eq!(0b_1101_0111, accessibility.bits()); + + accessibility = accessibility.set_accessibility(6, IsAccessible::No); + assert_eq!(0b_1001_0111, accessibility.bits()); + + accessibility = accessibility.set_accessibility(10, IsAccessible::Yes); + assert_eq!(0b_0100_1001_0111, accessibility.bits()); + + accessibility = accessibility.set_accessibility(63, IsAccessible::Yes); + assert_eq!((1 << 63) | 0b_0100_1001_0111, accessibility.bits()); } - - + #[test] - fn empty(){ - let accessibility=BoolArray::empty(); + fn empty() { + let accessibility = BoolArray::empty(); for i in 0..64 { assert!( @@ -387,27 +358,22 @@ mod tests{ ); } } - + #[test] - fn iter_test(){ - let iter=BoolArray::with_count(8) - .set_accessibility(1,IsAccessible::No) - .set_accessibility(3,IsAccessible::No) + fn iter_test() { + let iter = BoolArray::with_count(8) + .set_accessibility(1, IsAccessible::No) + .set_accessibility(3, IsAccessible::No) .iter_count(10) .map(IsAccessible::is_accessible); - - let expected=vec![true,false,true,false,true,true,true,true,false,false]; - let expected_rev=expected.iter().cloned().rev().collect::>(); - assert_eq!( - iter.clone().collect::>(), - expected - ); - - assert_eq!( - iter.clone().rev().collect::>(), - expected_rev - ); + let expected = vec![ + true, false, true, false, true, true, true, true, false, false, + ]; + let expected_rev = expected.iter().cloned().rev().collect::>(); + + assert_eq!(iter.clone().collect::>(), expected); + + assert_eq!(iter.clone().rev().collect::>(), expected_rev); } - -} \ No newline at end of file +} diff --git a/abi_stable/src/prefix_type/layout.rs b/abi_stable/src/prefix_type/layout.rs index 1388108f..6d58cdd5 100644 --- a/abi_stable/src/prefix_type/layout.rs +++ b/abi_stable/src/prefix_type/layout.rs @@ -1,10 +1,4 @@ -use crate::{ - std_types::RStr, - type_layout::MonoTypeLayout, -}; - - - +use crate::{std_types::RStr, type_layout::MonoTypeLayout}; /// Represents the layout of a prefix-type,for use in error messages. #[repr(C)] @@ -12,21 +6,16 @@ use crate::{ // #[derive(Debug, Copy, Clone, PartialEq, StableAbi)] pub struct PTStructLayout { /// The stringified generic parameters. - pub generics:RStr<'static>, - pub mono_layout:&'static MonoTypeLayout, + pub generics: RStr<'static>, + pub mono_layout: &'static MonoTypeLayout, } - ////////////////////////////////////////////////////////////// - -impl PTStructLayout{ +impl PTStructLayout { /// Constructs a `PTStructLayout`. - pub const fn new( - generics:RStr<'static>, - mono_layout:&'static MonoTypeLayout, - )->Self{ - Self{ + pub const fn new(generics: RStr<'static>, mono_layout: &'static MonoTypeLayout) -> Self { + Self { generics, mono_layout, } @@ -34,19 +23,19 @@ impl PTStructLayout{ /// Gets an iterator over the names of the fields. #[inline] - pub fn get_field_names(&self)->impl Iterator{ + pub fn get_field_names(&self) -> impl Iterator { self.mono_layout.field_names() } /// Gets a `Vec` with the names of the fields. #[inline] - pub fn get_field_names_vec(&self)->Vec<&'static str>{ + pub fn get_field_names_vec(&self) -> Vec<&'static str> { self.mono_layout.field_names().collect() } /// Gets the name of the `ith` field, returning `None` if there is no `ith` field. #[inline] - pub fn get_field_name(&self,ith:usize)->Option<&'static str>{ + pub fn get_field_name(&self, ith: usize) -> Option<&'static str> { self.mono_layout.get_field_name(ith) } } diff --git a/abi_stable/src/prefix_type/prefix_ref.rs b/abi_stable/src/prefix_type/prefix_ref.rs index c8c3bd21..038197df 100644 --- a/abi_stable/src/prefix_type/prefix_ref.rs +++ b/abi_stable/src/prefix_type/prefix_ref.rs @@ -1,14 +1,13 @@ use crate::{ - abi_stability::{GetStaticEquivalent_, GetStaticEquivalent, PrefixStableAbi, StableAbi}, + abi_stability::{GetStaticEquivalent, GetStaticEquivalent_, PrefixStableAbi, StableAbi}, pointer_trait::ImmutableRef, - prefix_type::{WithMetadata_, PrefixMetadata, PrefixRefTrait}, + prefix_type::{PrefixMetadata, PrefixRefTrait, WithMetadata_}, reexports::True, reflection::ModReflMode, sabi_types::StaticRef, std_types::RSlice, type_layout::{ - CompTLField, GenericTLData, LifetimeRange, MonoTLData, MonoTypeLayout, ReprAttr, - TypeLayout, + CompTLField, GenericTLData, LifetimeRange, MonoTLData, MonoTypeLayout, ReprAttr, TypeLayout, }, utils::Transmuter, }; @@ -18,26 +17,25 @@ use std::{ ptr::NonNull, }; - /// A reference to a prefix type. -/// +/// /// This is the type that all `*_Ref` pointer types generated by `StableAbi` wrap. -/// +/// /// # Example -/// +/// /// ```rust /// use abi_stable::{ /// StableAbi, /// staticref, /// prefix_type::{PrefixRef, PrefixTypeTrait, WithMetadata}, /// }; -/// +/// /// fn main(){ /// // `Module_Ref`'s constructor can also be called at compile-time /// asserts(Module_Ref(PREFIX_A)); /// asserts(Module_Ref(PREFIX_B)); /// } -/// +/// /// fn asserts(module: Module_Ref){ /// assert_eq!(module.first(), 5); /// assert_eq!(module.second(), 8); @@ -47,109 +45,105 @@ use std::{ /// assert_eq!(module.third(), Some(13)); /// } /// -/// -/// +/// +/// /// #[repr(C)] /// #[derive(StableAbi)] /// #[sabi(kind(Prefix(prefix_ref = "Module_Ref", prefix_fields = "Module_Prefix")))] /// struct Module{ /// first: usize, -/// // The `#[sabi(last_prefix_field)]` attribute here means that this is -/// // the last field in this struct that was defined in the +/// // The `#[sabi(last_prefix_field)]` attribute here means that this is +/// // the last field in this struct that was defined in the /// // first compatible version of the library, /// // requiring new fields to always be added after it. -/// // Moving this attribute is a breaking change, it can only be done in a +/// // Moving this attribute is a breaking change, it can only be done in a /// // major version bump.. /// #[sabi(last_prefix_field)] /// second: usize, /// third: usize, /// } -/// +/// /// const MOD_VAL: Module = Module{ /// first: 5, /// second: 8, /// third: 13, /// }; -/// +/// /// ///////////////////////////////////////// -/// // First way to construct a PrefixRef +/// // First way to construct a PrefixRef /// // This is a way that PrefixRef can be constructed in statics -/// +/// /// const PREFIX_A: PrefixRef = { /// const S: &WithMetadata = /// &WithMetadata::new(PrefixTypeTrait::METADATA, MOD_VAL); /// /// S.static_as_prefix() /// }; -/// +/// /// ///////////////////////////////////////// /// // Second way to construct a PrefixRef /// // This is a way that PrefixRef can be constructed in associated constants, -/// +/// /// struct WithAssoc; -/// +/// /// impl WithAssoc { /// // This macro declares a `StaticRef` pointing to the assigned `WithMetadata`. /// staticref!(const MOD_WM: WithMetadata = { /// WithMetadata::new(PrefixTypeTrait::METADATA, MOD_VAL) /// }); /// } -/// +/// /// /// const PREFIX_B: PrefixRef = WithAssoc::MOD_WM.as_prefix(); /// -/// +/// /// ///////////////////////////////////////// -/// -/// +/// +/// /// ``` #[repr(transparent)] -pub struct PrefixRef

{ +pub struct PrefixRef

{ ptr: NonNull>, } -impl

Clone for PrefixRef

{ +impl

Clone for PrefixRef

{ #[inline] - fn clone(&self)->Self{ + fn clone(&self) -> Self { *self } } -impl

Copy for PrefixRef

{} +impl

Copy for PrefixRef

{} -unsafe impl<'a, P:'a> Sync for PrefixRef

-where &'a WithMetadata_:Sync -{} +unsafe impl<'a, P: 'a> Sync for PrefixRef

where &'a WithMetadata_: Sync {} -unsafe impl<'a, P:'a> Send for PrefixRef

-where &'a WithMetadata_:Send -{} +unsafe impl<'a, P: 'a> Send for PrefixRef

where &'a WithMetadata_: Send {} impl

Debug for PrefixRef

{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let metadata = self.metadata(); f.debug_struct("PrefixRef") - .field("metadata", &metadata) - .field("value_type", &std::any::type_name::

()) - .finish() + .field("metadata", &metadata) + .field("value_type", &std::any::type_name::

()) + .finish() } } -impl

PrefixRef

{ +impl

PrefixRef

{ /// Constructs a `PrefixRef` from a raw pointer. - /// + /// /// # Safety - /// + /// /// The pointer must be a non-dangling pointer to a valid, initialized instance of `T`, /// and live for the rest of the program's lifetime /// (if called at compile-time it means live for the entire program). - /// + /// /// `T` must implement `PrefixTypeTrait`, - /// this is automatically true if this is called with + /// this is automatically true if this is called with /// `&WithMetadata::new(PrefixTypeTrait::METADATA, )`. - /// + /// /// # Example - /// + /// /// ```rust /// use abi_stable::{ /// for_examples::{Module, Module_Prefix, Module_Ref}, @@ -157,7 +151,7 @@ impl

PrefixRef

{ /// std_types::*, /// rstr, /// }; - /// + /// /// const MOD_WM: &WithMetadata = { /// &WithMetadata::new(PrefixTypeTrait::METADATA, Module{ /// first: RSome(3), @@ -167,33 +161,32 @@ impl

PrefixRef

{ /// }; /// /// const PREFIX: PrefixRef = unsafe{ PrefixRef::from_raw(MOD_WM) }; - /// + /// /// const MODULE: Module_Ref = Module_Ref(PREFIX); - /// - /// + /// + /// /// assert_eq!(MODULE.first(), RSome(3)); - /// + /// /// assert_eq!(MODULE.second().as_str(), "hello"); - /// + /// /// // The accessor returns an `Option` because the field comes after the prefix, /// // and returning an Option is the default for those. - /// assert_eq!(MODULE.third(), Some(8)); - /// + /// assert_eq!(MODULE.third(), Some(8)); + /// /// ``` #[inline(always)] pub const unsafe fn from_raw(ptr: *const WithMetadata_) -> Self { - Self{ + Self { ptr: NonNull::new_unchecked( - ptr as *const WithMetadata_ - as *mut WithMetadata_ - ) + ptr as *const WithMetadata_ as *mut WithMetadata_, + ), } } /// Constructs a `PrefixRef` from a [`StaticRef`]. - /// + /// /// # Example - /// + /// /// ```rust /// use abi_stable::{ /// for_examples::{Module, Module_Prefix, Module_Ref}, @@ -201,12 +194,12 @@ impl

PrefixRef

{ /// std_types::*, /// rstr, staticref, /// }; - /// + /// /// struct Foo {} - /// + /// /// impl Foo { /// // This macro declares a `StaticRef` pointing to the assigned `WithMetadata`. - /// staticref!{const MOD_WM: WithMetadata = + /// staticref!{const MOD_WM: WithMetadata = /// WithMetadata::new(PrefixTypeTrait::METADATA, Module{ /// first: RNone, /// second: rstr!("world"), @@ -216,32 +209,30 @@ impl

PrefixRef

{ /// } /// /// const PREFIX: PrefixRef = PrefixRef::from_staticref(Foo::MOD_WM); - /// + /// /// const MODULE: Module_Ref = Module_Ref(PREFIX); - /// - /// + /// + /// /// assert_eq!(MODULE.first(), RNone); - /// + /// /// assert_eq!(MODULE.second().as_str(), "world"); - /// + /// /// // The accessor returns an `Option` because the field comes after the prefix, /// // and returning an Option is the default for those. - /// assert_eq!(MODULE.third(), Some(13)); - /// + /// assert_eq!(MODULE.third(), Some(13)); + /// /// ``` - /// + /// /// [`StaticRef`]: ../sabi_types/struct.StaticRef.html #[inline] pub const fn from_staticref(ptr: StaticRef>) -> Self { - unsafe{ - Self::from_raw(ptr.as_ptr()) - } + unsafe { Self::from_raw(ptr.as_ptr()) } } /// Constructs a `PrefixRef` from a static reference. - /// + /// /// # Example - /// + /// /// ```rust /// use abi_stable::{ /// for_examples::{Module, Module_Prefix, Module_Ref}, @@ -249,7 +240,7 @@ impl

PrefixRef

{ /// std_types::*, /// rstr, /// }; - /// + /// /// const MOD_WM: &WithMetadata = { /// &WithMetadata::new(PrefixTypeTrait::METADATA, Module{ /// first: RNone, @@ -259,38 +250,36 @@ impl

PrefixRef

{ /// }; /// /// const PREFIX: PrefixRef = PrefixRef::from_ref(MOD_WM); - /// + /// /// const MODULE: Module_Ref = Module_Ref(PREFIX); - /// - /// + /// + /// /// assert_eq!(MODULE.first(), RNone); - /// + /// /// assert_eq!(MODULE.second().as_str(), "foo"); - /// + /// /// // The accessor returns an `Option` because the field comes after the prefix, /// // and returning an Option is the default for those. - /// assert_eq!(MODULE.third(), Some(21)); - /// + /// assert_eq!(MODULE.third(), Some(21)); + /// /// ``` - /// + /// #[inline] pub const fn from_ref(ptr: &'static WithMetadata_) -> Self { - unsafe{ - Self::from_raw(ptr) - } + unsafe { Self::from_raw(ptr) } } /// Gets the metadata about the prefix type, including available fields. - /// + /// /// # Example - /// + /// /// ```rust /// use abi_stable::{ /// for_examples::{Module, Module_Prefix}, /// prefix_type::{PrefixRef, PrefixTypeTrait, WithMetadata}, /// std_types::*, /// }; - /// + /// /// const MOD_WM: &WithMetadata = { /// &WithMetadata::new(PrefixTypeTrait::METADATA, Module{ /// first: RNone, @@ -300,27 +289,25 @@ impl

PrefixRef

{ /// }; /// /// const PREFIX: PrefixRef = PrefixRef::from_ref(MOD_WM); - /// + /// /// let accessibility = PREFIX.metadata().field_accessibility(); - /// + /// /// assert!( accessibility.is_accessible(0) ); // The `first` field /// assert!( accessibility.is_accessible(1) ); // The `second` field /// assert!( accessibility.is_accessible(2) ); // The `third` field /// assert!( !accessibility.is_accessible(3) ); // There's no field after `third` - /// + /// /// ``` - /// + /// #[inline] pub fn metadata(self) -> PrefixMetadata { - unsafe{ - (*self.ptr.as_ptr()).metadata - } + unsafe { (*self.ptr.as_ptr()).metadata } } /// Gets a reference to the pointed-to prefix. - /// + /// /// # Example - /// + /// /// ```rust /// use abi_stable::{ /// for_examples::{Module, Module_Prefix}, @@ -328,7 +315,7 @@ impl

PrefixRef

{ /// std_types::*, /// rstr, /// }; - /// + /// /// const MOD_WM: &WithMetadata = { /// &WithMetadata::new(PrefixTypeTrait::METADATA, Module{ /// first: RNone, @@ -338,61 +325,58 @@ impl

PrefixRef

{ /// }; /// /// const PREFIX_REF: PrefixRef = PrefixRef::from_ref(MOD_WM); - /// + /// /// let prefix: &Module_Prefix = PREFIX_REF.prefix(); - /// + /// /// assert_eq!(prefix.first, RNone); - /// + /// /// assert_eq!(prefix.second.as_str(), "foo"); - /// + /// /// // The `third` field is not in the prefix, so it can't be accessed here. /// // prefix.third; - /// + /// /// ``` - /// + /// #[inline] - pub fn prefix<'a>(self)-> &'a P { - unsafe{ - &(*self.ptr.as_ptr()).value.0 - } + pub fn prefix<'a>(self) -> &'a P { + unsafe { &(*self.ptr.as_ptr()).value.0 } } /// Converts this PrefixRef into a raw pointer. #[inline(always)] - pub fn to_raw_ptr(self)-> *const WithMetadata_ { - unsafe{ Transmuter{from: self}.to } + pub fn to_raw_ptr(self) -> *const WithMetadata_ { + unsafe { Transmuter { from: self }.to } } /// A const-callable version of `to_raw_ptr`, /// use `to_raw_ptr` in non-const code instead of this. - /// + /// /// `to_raw_ptr` exists for efficiency-in-debug-build reasons. #[inline] - pub const fn const_to_raw_ptr(self)-> *const WithMetadata_ { + pub const fn const_to_raw_ptr(self) -> *const WithMetadata_ { self.ptr.as_ptr() } /// Casts the pointed-to prefix to another type. - /// + /// /// # Safety - /// + /// /// This function is intended for casting the `PrefixRef

` to `PrefixRef`, /// and then cast back to `PrefixRef

` to use it again. - /// + /// /// The prefix in the returned `PrefixRef` must only be accessed /// when this `PrefixRef` was originally cosntructed with a `ẀithMetadata_<_, U>`. /// access includes calling `prefix`, and reading the `value` field in the `WithMetadata` /// that this points to. - /// - pub const unsafe fn cast(self)->PrefixRef{ - PrefixRef{ - ptr: self.ptr.cast() + /// + pub const unsafe fn cast(self) -> PrefixRef { + PrefixRef { + ptr: self.ptr.cast(), } } } - -unsafe impl

GetStaticEquivalent_ for PrefixRef

+unsafe impl

GetStaticEquivalent_ for PrefixRef

where P: GetStaticEquivalent_, { @@ -400,27 +384,28 @@ where } unsafe impl

StableAbi for PrefixRef

-where +where P: PrefixStableAbi, { type IsNonZeroType = True; const LAYOUT: &'static TypeLayout = { - const MONO_TYPE_LAYOUT:&MonoTypeLayout=&MonoTypeLayout::new( + const MONO_TYPE_LAYOUT: &MonoTypeLayout = &MonoTypeLayout::new( *mono_shared_vars, rstr!("PrefixRef"), make_item_info!(), MonoTLData::struct_(rslice![]), tl_genparams!('a;0;), ReprAttr::Transparent, - ModReflMode::DelegateDeref{layout_index:0}, + ModReflMode::DelegateDeref { layout_index: 0 }, { - const S: &[CompTLField] = &[CompTLField::std_field(field0,LifetimeRange::EMPTY,0)]; + const S: &[CompTLField] = + &[CompTLField::std_field(field0, LifetimeRange::EMPTY, 0)]; RSlice::from_slice(S) }, ); - make_shared_vars!{ + make_shared_vars! { impl[P] PrefixRef

where [P: PrefixStableAbi]; @@ -445,4 +430,4 @@ unsafe impl

ImmutableRef for PrefixRef

{ unsafe impl

PrefixRefTrait for PrefixRef

{ type PrefixFields = P; -} \ No newline at end of file +} diff --git a/abi_stable/src/prefix_type/pt_metadata.rs b/abi_stable/src/prefix_type/pt_metadata.rs index 98869ceb..f65ac4bc 100644 --- a/abi_stable/src/prefix_type/pt_metadata.rs +++ b/abi_stable/src/prefix_type/pt_metadata.rs @@ -1,227 +1,208 @@ -use std::{ - borrow::Cow, - slice, -}; +use std::{borrow::Cow, slice}; #[allow(unused_imports)] use crate::{ std_types::*, type_layout::{ - TypeLayout,TLField,TLData,TLPrefixType,TLDataDiscriminant, - TLFieldsIterator,TLFields, + TLData, TLDataDiscriminant, TLField, TLFields, TLFieldsIterator, TLPrefixType, TypeLayout, }, }; -use super::{ - accessible_fields::{FieldAccessibility,FieldConditionality,IsAccessible}, -}; - +use super::accessible_fields::{FieldAccessibility, FieldConditionality, IsAccessible}; #[allow(unused_imports)] use core_extensions::SelfOps; - #[doc(hidden)] -#[derive(Debug,Clone)] -pub struct __PrefixTypeMetadata{ +#[derive(Debug, Clone)] +pub struct __PrefixTypeMetadata { /// This is the amount of fields on the prefix of the struct, /// which is always the same for the same type,regardless of which library it comes from. - pub prefix_field_count:u8, + pub prefix_field_count: u8, - pub accessible_fields:FieldAccessibility, + pub accessible_fields: FieldAccessibility, - pub conditional_prefix_fields:FieldConditionality, + pub conditional_prefix_fields: FieldConditionality, - pub fields:__InitialFieldsOrMut, + pub fields: __InitialFieldsOrMut, /// The layout of the struct,for error messages. - pub layout:&'static TypeLayout, + pub layout: &'static TypeLayout, } - -impl __PrefixTypeMetadata{ +impl __PrefixTypeMetadata { #[allow(dead_code)] #[cfg(feature = "testing")] - pub fn new(layout:&'static TypeLayout)->Self{ + pub fn new(layout: &'static TypeLayout) -> Self { match layout.data() { - TLData::PrefixType(prefix)=> - Self::with_prefix_layout(prefix,layout), - _=>panic!( + TLData::PrefixType(prefix) => Self::with_prefix_layout(prefix, layout), + _ => panic!( "Attempting to construct a __PrefixTypeMetadata from a \ TypeLayout of a non-prefix-type.\n\ Type:{}\nDataVariant:{:?}\nPackage:{}", - layout.full_type(), - layout.data_discriminant(), - layout.package(), + layout.full_type(), + layout.data_discriminant(), + layout.package(), ), } } - pub(crate) fn with_prefix_layout(prefix:TLPrefixType,layout:&'static TypeLayout)->Self{ - Self{ - fields:__InitialFieldsOrMut::from(prefix.fields), - accessible_fields:prefix.accessible_fields, - conditional_prefix_fields:prefix.conditional_prefix_fields, - prefix_field_count:prefix.first_suffix_field, + pub(crate) fn with_prefix_layout(prefix: TLPrefixType, layout: &'static TypeLayout) -> Self { + Self { + fields: __InitialFieldsOrMut::from(prefix.fields), + accessible_fields: prefix.accessible_fields, + conditional_prefix_fields: prefix.conditional_prefix_fields, + prefix_field_count: prefix.first_suffix_field, layout, } } - // #[cfg(test)] // pub(crate) fn assert_valid(&self){ // assert_eq!(self.layout.data.as_discriminant(),TLDataDiscriminant::PrefixType ); // } /// Returns the maximum prefix.Does not check that they are compatible. - /// + /// /// # Preconditions - /// + /// /// The prefixes must already have been checked for compatibility. #[allow(dead_code)] #[cfg(feature = "testing")] - pub fn max(self,other:Self)->Self{ + pub fn max(self, other: Self) -> Self { if self.fields.len() < other.fields.len() { other - }else{ + } else { self } } /// Returns the minimum and maximum prefix.Does not check that they are compatible. - /// + /// /// # Preconditions - /// + /// /// The prefixes must already have been checked for compatibility. - pub(crate) fn min_max(self,other:Self)->(Self,Self){ + pub(crate) fn min_max(self, other: Self) -> (Self, Self) { if self.fields.len() < other.fields.len() { - (self,other) - }else{ - (other,self) + (self, other) + } else { + (other, self) } } - /// Combines the fields from `other` into `self`, /// replacing any innaccessible field with one from `other`. /// /// # Preconditions /// /// This must be called after both were checked for compatibility, - /// otherwise fields accessible in both `self` and `other` + /// otherwise fields accessible in both `self` and `other` /// won't be checked for compatibility or copied. - pub(crate) fn combine_fields_from(&mut self,other:&Self){ - let mut o_fields=other.fields.iter(); - - let min_field_count=o_fields.len().min(self.fields.len()); - - for (field_i,(t_acc,o_acc)) in - self.accessible_fields.iter_count(min_field_count) - .zip(other.accessible_fields.iter_count(min_field_count)) - .enumerate() + pub(crate) fn combine_fields_from(&mut self, other: &Self) { + let mut o_fields = other.fields.iter(); + + let min_field_count = o_fields.len().min(self.fields.len()); + + for (field_i, (t_acc, o_acc)) in self + .accessible_fields + .iter_count(min_field_count) + .zip(other.accessible_fields.iter_count(min_field_count)) + .enumerate() { - let o_field=o_fields.next().unwrap(); + let o_field = o_fields.next().unwrap(); if !t_acc.is_accessible() && o_acc.is_accessible() { - let t_fields=self.fields.to_mut(); + let t_fields = self.fields.to_mut(); - t_fields[field_i]=o_field.into_owned(); + t_fields[field_i] = o_field.into_owned(); } } - if min_field_count==self.fields.len() { - let t_fields=self.fields.to_mut(); - - for (i,o_field) in o_fields.enumerate() { - let field_i=i+min_field_count; + if min_field_count == self.fields.len() { + let t_fields = self.fields.to_mut(); + + for (i, o_field) in o_fields.enumerate() { + let field_i = i + min_field_count; t_fields.push(o_field.into_owned()); - self.accessible_fields= - self.accessible_fields.set_accessibility(field_i,IsAccessible::Yes); + self.accessible_fields = self + .accessible_fields + .set_accessibility(field_i, IsAccessible::Yes); } } } } - ///////////////////////////////////////////////////////////////////////////////// - #[doc(hidden)] -#[derive(Debug,Clone)] -pub enum __InitialFieldsOrMut{ +#[derive(Debug, Clone)] +pub enum __InitialFieldsOrMut { TLFields(TLFields), Mutable(Vec), } - -impl From for __InitialFieldsOrMut{ - fn from(this:TLFields)->Self{ +impl From for __InitialFieldsOrMut { + fn from(this: TLFields) -> Self { __InitialFieldsOrMut::TLFields(this) } } - -impl __InitialFieldsOrMut{ - pub fn to_mut(&mut self)->&mut Vec{ +impl __InitialFieldsOrMut { + pub fn to_mut(&mut self) -> &mut Vec { match self { - __InitialFieldsOrMut::Mutable(x)=>x, - this=>{ - let list=this.iter().map(Cow::into_owned).collect::>(); - *this=__InitialFieldsOrMut::Mutable(list); + __InitialFieldsOrMut::Mutable(x) => x, + this => { + let list = this.iter().map(Cow::into_owned).collect::>(); + *this = __InitialFieldsOrMut::Mutable(list); match this { - __InitialFieldsOrMut::Mutable(x)=>x, - _=>unreachable!() + __InitialFieldsOrMut::Mutable(x) => x, + _ => unreachable!(), } } } } - pub fn iter(&self)->IFOMIter<'_>{ + pub fn iter(&self) -> IFOMIter<'_> { match self { - __InitialFieldsOrMut::TLFields(x)=>IFOMIter::TLFields(x.iter()), - __InitialFieldsOrMut::Mutable(x)=>IFOMIter::Slice(x.iter()), + __InitialFieldsOrMut::TLFields(x) => IFOMIter::TLFields(x.iter()), + __InitialFieldsOrMut::Mutable(x) => IFOMIter::Slice(x.iter()), } } - pub fn len(&self)->usize{ + pub fn len(&self) -> usize { match self { - __InitialFieldsOrMut::TLFields(x)=>x.len(), - __InitialFieldsOrMut::Mutable(x)=>x.len(), + __InitialFieldsOrMut::TLFields(x) => x.len(), + __InitialFieldsOrMut::Mutable(x) => x.len(), } } } - #[repr(C)] -#[derive(Clone,Debug)] -pub enum IFOMIter<'a>{ +#[derive(Clone, Debug)] +pub enum IFOMIter<'a> { TLFields(TLFieldsIterator), - Slice(slice::Iter<'a,TLField>), + Slice(slice::Iter<'a, TLField>), } +impl<'a> Iterator for IFOMIter<'a> { + type Item = Cow<'a, TLField>; - -impl<'a> Iterator for IFOMIter<'a>{ - type Item=Cow<'a,TLField>; - - fn next(&mut self)->Option>{ + fn next(&mut self) -> Option> { match self { - IFOMIter::TLFields(iter)=>iter.next().map(Cow::Owned), - IFOMIter::Slice(iter)=>iter.next().map(Cow::Borrowed), + IFOMIter::TLFields(iter) => iter.next().map(Cow::Owned), + IFOMIter::Slice(iter) => iter.next().map(Cow::Borrowed), } } - fn size_hint(&self)->(usize,Option){ + fn size_hint(&self) -> (usize, Option) { match self { - IFOMIter::TLFields(iter)=>iter.size_hint(), - IFOMIter::Slice(iter)=>iter.size_hint(), + IFOMIter::TLFields(iter) => iter.size_hint(), + IFOMIter::Slice(iter) => iter.size_hint(), } } fn count(self) -> usize { match self { - IFOMIter::TLFields(iter)=>iter.count(), - IFOMIter::Slice(iter)=>iter.count(), + IFOMIter::TLFields(iter) => iter.count(), + IFOMIter::Slice(iter) => iter.count(), } } } - -impl<'a> std::iter::ExactSizeIterator for IFOMIter<'a>{} - +impl<'a> std::iter::ExactSizeIterator for IFOMIter<'a> {} diff --git a/abi_stable/src/prefix_type/tests.rs b/abi_stable/src/prefix_type/tests.rs index 73f42f58..34d4f274 100644 --- a/abi_stable/src/prefix_type/tests.rs +++ b/abi_stable/src/prefix_type/tests.rs @@ -1,6 +1,6 @@ use crate::{ + prefix_type::{PrefixRef, PrefixTypeTrait, WithMetadata}, StableAbi, - prefix_type::{PrefixTypeTrait, WithMetadata, PrefixRef}, }; mod cond_fields { @@ -10,24 +10,24 @@ mod cond_fields { #[repr(C)] #[derive(StableAbi)] #[sabi(kind(Prefix(prefix_ref = "Module_Ref", prefix_fields = "Module_Prefix")))] - pub struct Module{ - #[sabi(accessible_if="true")] + pub struct Module { + #[sabi(accessible_if = "true")] pub first: usize, - + #[sabi(last_prefix_field)] pub second: usize, - - #[sabi(accessible_if="true")] + + #[sabi(accessible_if = "true")] pub third: usize, - + pub fourth: usize, } impl std::ops::Deref for Module_Prefix { type Target = DerefTo; - fn deref(&self)->&DerefTo{ - &DerefTo{ + fn deref(&self) -> &DerefTo { + &DerefTo { first: "5", second: "8", third: "13", @@ -36,13 +36,15 @@ mod cond_fields { } } - pub const MOD_VAL: &WithMetadata = - &WithMetadata::new(PrefixTypeTrait::METADATA,Module{ + pub const MOD_VAL: &WithMetadata = &WithMetadata::new( + PrefixTypeTrait::METADATA, + Module { first: 5, second: 8, third: 13, fourth: 21, - }); + }, + ); pub const PREFIX: PrefixRef = MOD_VAL.static_as_prefix(); } @@ -54,35 +56,31 @@ pub struct DerefTo { pub fourth: &'static str, } - - - #[test] -fn prefix_field_vis(){ - use cond_fields::{PREFIX, Module_Ref}; +fn prefix_field_vis() { + use cond_fields::{Module_Ref, PREFIX}; let pref = PREFIX.prefix(); let modref = Module_Ref(PREFIX); - // Exploiting the fact that the compiler does a deref coercion + // Exploiting the fact that the compiler does a deref coercion // if it can't find a pub field with a given name. assert_eq!(pref.first, "5"); assert_eq!(modref.first(), Some(5)); - + assert_eq!(pref.second, 8); assert_eq!(modref.second(), 8); - + assert_eq!(pref.third, "13"); - assert_eq!(modref.third() , Some(13)); + assert_eq!(modref.third(), Some(13)); assert_eq!(pref.fourth, "21"); - assert_eq!(modref.fourth() , Some(21)); + assert_eq!(modref.fourth(), Some(21)); } //////////////////////////////////////////////////////////////////////////////// - mod different_alignments { use super::*; @@ -90,7 +88,7 @@ mod different_alignments { #[repr(C)] #[derive(StableAbi)] #[sabi(kind(Prefix(prefix_ref = "Module_Ref", prefix_fields = "Module_Prefix")))] - pub struct Module{ + pub struct Module { pub f0: u64, #[sabi(last_prefix_field)] pub f1: u8, @@ -102,8 +100,9 @@ mod different_alignments { pub f7: u8, } - pub const MOD_VAL: &WithMetadata = - &WithMetadata::new(PrefixTypeTrait::METADATA,Module{ + pub const MOD_VAL: &WithMetadata = &WithMetadata::new( + PrefixTypeTrait::METADATA, + Module { f0: 5, f1: 8, f2: 13, @@ -112,16 +111,16 @@ mod different_alignments { f5: 55, f6: 89, f7: 144, - }); + }, + ); pub const PREFIX: PrefixRef = MOD_VAL.static_as_prefix(); } - /// Making sure that suffix fields with different alignments are accessed correctly. #[test] -fn access_different_alignments(){ - use different_alignments::{PREFIX, Module_Ref}; +fn access_different_alignments() { + use different_alignments::{Module_Ref, PREFIX}; let modref = Module_Ref(PREFIX); @@ -135,10 +134,8 @@ fn access_different_alignments(){ assert_eq!(modref.f7(), Some(144)); } - //////////////////////////////////////////////////////////////////////////////// - #[repr(C, align(32))] #[derive(StableAbi, Debug, Copy, Clone, PartialEq)] pub struct AlignTo32(pub T); @@ -147,7 +144,6 @@ pub struct AlignTo32(pub T); #[derive(StableAbi, Debug, Copy, Clone, PartialEq)] pub struct AlignTo64(pub T); - mod overaligned { use super::*; @@ -155,7 +151,7 @@ mod overaligned { #[repr(C, align(32))] #[derive(StableAbi)] #[sabi(kind(Prefix))] - pub struct Module{ + pub struct Module { pub f0: u64, pub f1: u8, #[sabi(last_prefix_field)] @@ -166,8 +162,9 @@ mod overaligned { pub f6: u8, } - pub const MOD_VAL: &WithMetadata = - &WithMetadata::new(PrefixTypeTrait::METADATA,Module{ + pub const MOD_VAL: &WithMetadata = &WithMetadata::new( + PrefixTypeTrait::METADATA, + Module { f0: 5, f1: 8, f2: 13, @@ -175,15 +172,16 @@ mod overaligned { f4: AlignTo64(34), f5: 55, f6: 89, - }); + }, + ); pub const PREFIX: PrefixRef = MOD_VAL.static_as_prefix(); } /// Making sure that suffix fields with different alignments are accessed correctly. #[test] -fn access_overaligned_fields(){ - use overaligned::{PREFIX, Module_Ref}; +fn access_overaligned_fields() { + use overaligned::{Module_Ref, PREFIX}; let modref = Module_Ref(PREFIX); diff --git a/abi_stable/src/reflection.rs b/abi_stable/src/reflection.rs index 9e57d3ba..e8826ea7 100644 --- a/abi_stable/src/reflection.rs +++ b/abi_stable/src/reflection.rs @@ -2,8 +2,8 @@ Types and submodules for doing runtime reflection. */ -#[cfg(all(test,not(feature="only_new_tests")))] -pub mod tests{ +#[cfg(all(test, not(feature = "only_new_tests")))] +pub mod tests { pub mod derive_reflection; } @@ -19,26 +19,25 @@ pub mod export_module; /// /// Module reflection only allows accessing public fields. #[repr(u8)] -#[derive(Debug,Copy,Clone,PartialEq,Eq,StableAbi)] -pub enum ModReflMode{ +#[derive(Debug, Copy, Clone, PartialEq, Eq, StableAbi)] +pub enum ModReflMode { /// For modules that are reflected on at runtime. /// /// This is the default for all types. Module, /// For types whose layout can't be iterated over. /// - /// If one uses `#[sabi(module_reflection(Opaque))]` + /// If one uses `#[sabi(module_reflection(Opaque))]` Opaque, /// Delegates the layout to some other type,this is generally for references. - DelegateDeref{ + DelegateDeref { /// To which layout in `TypeLayout.shared_vars.type_layouts` this delegates to. - layout_index:u8, + layout_index: u8, }, } - -impl Default for ModReflMode{ - fn default()->Self{ +impl Default for ModReflMode { + fn default() -> Self { ModReflMode::Opaque } } diff --git a/abi_stable/src/reflection/export_module.rs b/abi_stable/src/reflection/export_module.rs index 599b1c4e..ce3a0c2d 100644 --- a/abi_stable/src/reflection/export_module.rs +++ b/abi_stable/src/reflection/export_module.rs @@ -2,174 +2,156 @@ Data structures to export a type as though it were a module. */ -use std::{ - fmt::{self,Display}, -}; +use std::fmt::{self, Display}; use core_extensions::SelfOps; -use crate::{ - reflection::{ModReflMode}, - type_layout::*, -}; +use crate::{reflection::ModReflMode, type_layout::*}; -#[derive(Debug,Serialize,Deserialize)] -pub struct MRItem{ - item_name:String, - type_:String, - field_accessor:MRFieldAccessor, +#[derive(Debug, Serialize, Deserialize)] +pub struct MRItem { + item_name: String, + type_: String, + field_accessor: MRFieldAccessor, #[serde(flatten)] - variant:MRItemVariant, + variant: MRItemVariant, } -#[derive(Debug,Serialize,Deserialize)] -pub struct MRNameType{ - name:String, - type_:String, +#[derive(Debug, Serialize, Deserialize)] +pub struct MRNameType { + name: String, + type_: String, } -#[derive(Debug,Serialize,Deserialize)] -#[serde(tag="variant")] -pub enum MRItemVariant{ +#[derive(Debug, Serialize, Deserialize)] +#[serde(tag = "variant")] +pub enum MRItemVariant { Function(MRFunction), Module(MRModule), Static, } - -#[derive(Debug,Serialize,Deserialize)] -pub struct MRFunction{ - params:Vec, - returns:MRNameType, +#[derive(Debug, Serialize, Deserialize)] +pub struct MRFunction { + params: Vec, + returns: MRNameType, } - -#[derive(Debug,Serialize,Deserialize)] -pub struct MRModule{ - mod_refl_mode:MRModReflMode, - items:Vec, +#[derive(Debug, Serialize, Deserialize)] +pub struct MRModule { + mod_refl_mode: MRModReflMode, + items: Vec, } -#[derive(Debug,Serialize,Deserialize)] -pub enum MRModReflMode{ +#[derive(Debug, Serialize, Deserialize)] +pub enum MRModReflMode { Module, Opaque, DelegateDeref, } #[repr(u8)] -#[derive(Debug,Serialize,Deserialize)] +#[derive(Debug, Serialize, Deserialize)] pub enum MRFieldAccessor { /// Accessible with `self.field_name` Direct, /// Accessible with `fn field_name(&self)->FieldType` - Method{ - name:Option, - }, + Method { name: Option }, /// Accessible with `fn field_name(&self)->Option` MethodOption, /// This field is completely inaccessible. Opaque, } +impl MRItem { + pub fn from_type_layout(layout: &'static TypeLayout) -> Self { + let type_ = layout.full_type().to_string(); -impl MRItem{ - pub fn from_type_layout( - layout:&'static TypeLayout, - )->Self{ - let type_=layout.full_type().to_string(); + let variant = Self::get_item_variant(layout); - let variant=Self::get_item_variant(layout); - - Self{ - item_name:"root".into(), + Self { + item_name: "root".into(), type_, - field_accessor:MRFieldAccessor::Direct, + field_accessor: MRFieldAccessor::Direct, variant, } } - fn get_item_variant(layout:&'static TypeLayout)->MRItemVariant { + fn get_item_variant(layout: &'static TypeLayout) -> MRItemVariant { match layout.mod_refl_mode() { - ModReflMode::Module=>{ - let fields=match layout.data() { - TLData::Struct { fields }=>fields, - TLData::PrefixType(prefix)=>prefix.fields, - TLData::Primitive{..} - |TLData::Opaque{..} - |TLData::Union{..} - |TLData::Enum {..} - =>return MRItemVariant::Static, + ModReflMode::Module => { + let fields = match layout.data() { + TLData::Struct { fields } => fields, + TLData::PrefixType(prefix) => prefix.fields, + TLData::Primitive { .. } + | TLData::Opaque { .. } + | TLData::Union { .. } + | TLData::Enum { .. } => return MRItemVariant::Static, }; - let items=fields.iter() - .filter(|f| f.field_accessor() !=FieldAccessor::Opaque ) - .map(|field|{ - let (type_,variant)=if field.is_function() { - let func=MRFunction::from(&field.function_range().index(0)); - ( - func.to_string(), - MRItemVariant::Function(func), - ) - }else{ - let layout=field.layout(); + let items = fields + .iter() + .filter(|f| f.field_accessor() != FieldAccessor::Opaque) + .map(|field| { + let (type_, variant) = if field.is_function() { + let func = MRFunction::from(&field.function_range().index(0)); + (func.to_string(), MRItemVariant::Function(func)) + } else { + let layout = field.layout(); ( layout.full_type().to_string(), Self::get_item_variant(layout), ) }; - MRItem{ - item_name:field.name().to_string(), + MRItem { + item_name: field.name().to_string(), type_, - field_accessor:field.field_accessor().into(), + field_accessor: field.field_accessor().into(), variant, } }) .collect::>(); - MRItemVariant::Module(MRModule{ - mod_refl_mode:layout.mod_refl_mode().into(), + MRItemVariant::Module(MRModule { + mod_refl_mode: layout.mod_refl_mode().into(), items, }) } - ModReflMode::Opaque=> - MRItemVariant::Static, - ModReflMode::DelegateDeref{layout_index}=>{ - let delegate_to=layout.shared_vars().type_layouts()[layout_index as usize]; - let inner_layout=delegate_to.get(); + ModReflMode::Opaque => MRItemVariant::Static, + ModReflMode::DelegateDeref { layout_index } => { + let delegate_to = layout.shared_vars().type_layouts()[layout_index as usize]; + let inner_layout = delegate_to.get(); Self::get_item_variant(inner_layout) } } } } - /////////////////////////////////////////////////////////////////////////////// - -impl<'a> From<&'a TLFunction> for MRFunction{ - fn from(this:&'a TLFunction)->Self{ - Self{ - params:this.get_params().map(MRNameType::from).collect::>(), - returns:this.get_return().into_::(), +impl<'a> From<&'a TLFunction> for MRFunction { + fn from(this: &'a TLFunction) -> Self { + Self { + params: this.get_params().map(MRNameType::from).collect::>(), + returns: this.get_return().into_::(), } } } -impl Display for MRFunction{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - write!(f,"fn(")?; - let param_count=self.params.len(); - for (param_i,param) in self.params.iter().enumerate() { - Display::fmt(param,f)?; - if param_i+1!=param_count { - Display::fmt(&", ",f)?; +impl Display for MRFunction { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "fn(")?; + let param_count = self.params.len(); + for (param_i, param) in self.params.iter().enumerate() { + Display::fmt(param, f)?; + if param_i + 1 != param_count { + Display::fmt(&", ", f)?; } } - write!(f,")")?; - - let returns=&self.returns; - Display::fmt(&"->",f)?; - Display::fmt(returns,f)?; + write!(f, ")")?; + + let returns = &self.returns; + Display::fmt(&"->", f)?; + Display::fmt(returns, f)?; Ok(()) } @@ -177,61 +159,49 @@ impl Display for MRFunction{ /////////////////////////////////////////////////////////////////////////////// - -impl From for MRNameType{ - fn from(field:TLField)->Self{ - let name=field.name().to_string(); - let type_=if field.is_function() { +impl From for MRNameType { + fn from(field: TLField) -> Self { + let name = field.name().to_string(); + let type_ = if field.is_function() { field.function_range().index(0).to_string() - }else{ + } else { field.layout().full_type().to_string() }; - Self{ - name, - type_, - } + Self { name, type_ } } } -impl Display for MRNameType{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - write!(f,"{}:{}",self.name,self.type_) +impl Display for MRNameType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}:{}", self.name, self.type_) } } /////////////////////////////////////////////////////////////////////////////// - -impl From for MRModReflMode{ - fn from(this:ModReflMode)->Self{ +impl From for MRModReflMode { + fn from(this: ModReflMode) -> Self { match this { - ModReflMode::Module{..}=> - MRModReflMode::Module, - ModReflMode::Opaque{..}=> - MRModReflMode::Opaque, - ModReflMode::DelegateDeref{..}=> - MRModReflMode::DelegateDeref, + ModReflMode::Module { .. } => MRModReflMode::Module, + ModReflMode::Opaque { .. } => MRModReflMode::Opaque, + ModReflMode::DelegateDeref { .. } => MRModReflMode::DelegateDeref, } } } /////////////////////////////////////////////////////////////////////////////// - -impl From for MRFieldAccessor{ - fn from(this:FieldAccessor)->MRFieldAccessor{ - match this{ - FieldAccessor::Direct=> - MRFieldAccessor::Direct, - FieldAccessor::Method=> - MRFieldAccessor::Method{name:None}, - FieldAccessor::MethodNamed{name}=> - MRFieldAccessor::Method{name:Some(name.to_string())}, - FieldAccessor::MethodOption=> - MRFieldAccessor::MethodOption, - FieldAccessor::Opaque=> - MRFieldAccessor::Opaque, +impl From for MRFieldAccessor { + fn from(this: FieldAccessor) -> MRFieldAccessor { + match this { + FieldAccessor::Direct => MRFieldAccessor::Direct, + FieldAccessor::Method => MRFieldAccessor::Method { name: None }, + FieldAccessor::MethodNamed { name } => MRFieldAccessor::Method { + name: Some(name.to_string()), + }, + FieldAccessor::MethodOption => MRFieldAccessor::MethodOption, + FieldAccessor::Opaque => MRFieldAccessor::Opaque, } } -} \ No newline at end of file +} diff --git a/abi_stable/src/sabi_trait.rs b/abi_stable/src/sabi_trait.rs index e3279240..fcb03d50 100644 --- a/abi_stable/src/sabi_trait.rs +++ b/abi_stable/src/sabi_trait.rs @@ -3,59 +3,42 @@ Contains items related to the `#[sabi_trait]` attribute. */ #[doc(hidden)] -pub mod reexports{ +pub mod reexports { - pub use std::{ - ops::{Deref as __DerefTrait,DerefMut as __DerefMutTrait}, - }; + pub use std::ops::{Deref as __DerefTrait, DerefMut as __DerefMutTrait}; pub use crate::{ marker_type::ErasedObject as __ErasedObject, pointer_trait::GetPointerKind as __GetPointerKind, }; - - - - pub mod __sabi_re{ + pub mod __sabi_re { pub use abi_stable::{ - erased_types::{ - DynTrait, - GetVtable, - VTableDT, - traits::InterfaceFor, - }, + erased_types::{traits::InterfaceFor, DynTrait, GetVtable, VTableDT}, + extern_fn_panic_handling, marker_type::{ - UnsafeIgnoredType, - SyncSend,UnsyncUnsend,UnsyncSend,SyncUnsend, - NonOwningPhantom, + NonOwningPhantom, SyncSend, SyncUnsend, UnsafeIgnoredType, UnsyncSend, UnsyncUnsend, }, - pointer_trait::{AsPtr, AsMutPtr, CanTransmuteElement,TransmuteElement,OwnedPointer}, + pointer_trait::{AsMutPtr, AsPtr, CanTransmuteElement, OwnedPointer, TransmuteElement}, prefix_type::{PrefixRef, PrefixTypeTrait, WithMetadata}, - traits::IntoInner, - sabi_types::{RRef,RMut,MovePtr}, sabi_trait::{ - robject::{ - RObject, - }, + robject::RObject, vtable::{ - RObjectVtable_Ref, RObjectVtable, GetRObjectVTable, - VTableTO_DT,VTableTO_RO,VTableTO, + GetRObjectVTable, RObjectVtable, RObjectVtable_Ref, VTableTO, VTableTO_DT, + VTableTO_RO, }, }, + sabi_types::{MovePtr, RMut, RRef}, std_types::RBox, + traits::IntoInner, utils::take_manuallydrop, - extern_fn_panic_handling, }; - pub use core_extensions::{ - utils::transmute_ignore_size, - TypeIdentity, - }; + pub use core_extensions::{utils::transmute_ignore_size, TypeIdentity}; pub use std::{ marker::PhantomData, - mem::{ManuallyDrop, transmute}, + mem::{transmute, ManuallyDrop}, ops::Deref, ptr, }; @@ -63,13 +46,13 @@ pub mod reexports{ } /// A prelude for modules using `#[sabi_trait]` generated traits/trait objects. -pub mod prelude{ - pub use crate::type_level::downcasting::{TD_CanDowncast,TD_Opaque}; +pub mod prelude { + pub use crate::type_level::downcasting::{TD_CanDowncast, TD_Opaque}; } -pub use crate::type_level::downcasting::{TD_CanDowncast,TD_Opaque}; +pub use crate::type_level::downcasting::{TD_CanDowncast, TD_Opaque}; -#[cfg(any(test,feature="sabi_trait_examples"))] +#[cfg(any(test, feature = "sabi_trait_examples"))] pub mod examples; pub mod doc_examples; @@ -82,23 +65,23 @@ pub mod vtable; #[cfg(test)] pub mod tests; -#[cfg(all(test,not(feature="only_new_tests")))] +#[cfg(all(test, not(feature = "only_new_tests")))] pub mod test_supertraits; use std::{ - fmt::{Debug,Display}, + fmt::{Debug, Display}, marker::PhantomData, }; use self::reexports::__sabi_re::*; pub use self::{ - vtable::{VTableTO_DT,VTableTO_RO,VTableTO}, - robject::{RObject, UneraseError, ReborrowBounds}, + robject::{RObject, ReborrowBounds, UneraseError}, + vtable::{VTableTO, VTableTO_DT, VTableTO_RO}, }; use crate::{ - erased_types::{c_functions,InterfaceType}, + erased_types::{c_functions, InterfaceType}, marker_type::ErasedObject, sabi_types::MaybeCmp, }; diff --git a/abi_stable/src/sabi_trait/doc_examples.rs b/abi_stable/src/sabi_trait/doc_examples.rs index 13bbc57d..276f34d2 100644 --- a/abi_stable/src/sabi_trait/doc_examples.rs +++ b/abi_stable/src/sabi_trait/doc_examples.rs @@ -7,34 +7,34 @@ use crate::sabi_trait; /// An example trait,used to show what `#[sabi_trait]` generates in the docs. #[sabi_trait] #[sabi(use_dyn_trait)] -pub trait ConstExample:Debug+Clone{ +pub trait ConstExample: Debug + Clone { #[sabi(last_prefix_field)] - fn next_number(&self,num:usize)->usize; + fn next_number(&self, num: usize) -> usize; } -impl ConstExample for usize{ - fn next_number(&self,num:usize)->usize{ - self+num +impl ConstExample for usize { + fn next_number(&self, num: usize) -> usize { + self + num } } /// An example trait object that uses `RObject` as a backend. #[sabi_trait] pub trait Doer: Debug { - fn value(&self)->usize; + fn value(&self) -> usize; - fn do_it(&self, num: usize)->usize; + fn do_it(&self, num: usize) -> usize; #[sabi(last_prefix_field)] fn add_into(&mut self, num: usize); } -impl Doer for usize{ - fn value(&self)->usize{ +impl Doer for usize { + fn value(&self) -> usize { *self } - fn do_it(&self,num:usize)->usize{ + fn do_it(&self, num: usize) -> usize { self + num } fn add_into(&mut self, num: usize) { @@ -42,16 +42,12 @@ impl Doer for usize{ } } - - #[sabi_trait] #[doc(hidden)] -pub trait DocHiddenTrait{} - +pub trait DocHiddenTrait {} ////////////////////////////////////////// - /// The trait used in examples of `#[sabi_trait]` trait object methods, /// in [`abi_stable::docs::sabi_trait_inherent`] #[abi_stable::sabi_trait] @@ -59,7 +55,7 @@ pub trait DocHiddenTrait{} pub trait Action: Debug { /// Gets the current value of `self`. fn get(&self) -> usize; - + /// Adds `val` into `self`, returning the new value. fn add_mut(&mut self, val: usize) -> usize; @@ -68,7 +64,6 @@ pub trait Action: Debug { fn add_into(self, val: usize) -> usize; } - impl Action for usize { fn get(&self) -> usize { *self @@ -82,8 +77,3 @@ impl Action for usize { self } } - - - - - diff --git a/abi_stable/src/sabi_trait/examples.rs b/abi_stable/src/sabi_trait/examples.rs index 99aaa4dc..3d061e9d 100644 --- a/abi_stable/src/sabi_trait/examples.rs +++ b/abi_stable/src/sabi_trait/examples.rs @@ -1,15 +1,11 @@ -use std::{ - fmt::Debug, - hash::Hash, - sync::Arc, -}; +use std::{fmt::Debug, hash::Hash, sync::Arc}; use core_extensions::SelfOps; use crate::{ - *, - std_types::{RBox,RString,RStr,RArc,ROption,Tuple1,Tuple2,Tuple3}, sabi_trait::prelude::*, + std_types::{RArc, RBox, ROption, RStr, RString, Tuple1, Tuple2, Tuple3}, + *, }; ////////////////////////////////////// @@ -76,22 +72,19 @@ let _=RSomething_TO::<_,(),PhantomData>::from_value(ptr,TD_Opaque); */ #[sabi_trait] // #[sabi(debug_print_trait)] -pub trait RSomething:Send+Sync+Clone+Debug{ - type Element:Debug; +pub trait RSomething: Send + Sync + Clone + Debug { + type Element: Debug; + + fn get(&self) -> &Self::Element; - fn get(&self)->&Self::Element; - - fn get_mut(&mut self)->&mut Self::Element; + fn get_mut(&mut self) -> &mut Self::Element; #[sabi(last_prefix_field)] - fn into_value(self)->Self::Element; + fn into_value(self) -> Self::Element; } - - - macro_rules! impls_for_something { - ( + ( $traitname:ident , extra_bounds[ $($extra_bounds:tt)* ] ) => ( @@ -165,35 +158,30 @@ macro_rules! impls_for_something { ) } - -impls_for_something!{ RSomething, extra_bounds[ Sized ] } -impls_for_something!{ DSomething, extra_bounds[ Hash ] } +impls_for_something! { RSomething, extra_bounds[ Sized ] } +impls_for_something! { DSomething, extra_bounds[ Hash ] } ////////////////////////////////////// - #[sabi_trait] //#[sabi(debug_print_trait)] #[sabi(use_dyn_trait)] -pub trait DSomething:Send+Sync+Clone+Debug+Hash{ - type Element:Debug; +pub trait DSomething: Send + Sync + Clone + Debug + Hash { + type Element: Debug; + + fn get(&self) -> &Self::Element; - fn get(&self)->&Self::Element; - - fn get_mut(&mut self)->&mut Self::Element; + fn get_mut(&mut self) -> &mut Self::Element; #[sabi(last_prefix_field)] - fn into_value(self)->Self::Element; + fn into_value(self) -> Self::Element; } - ////////////////////////////////////// - #[sabi_trait] //#[sabi(debug_print_trait)] -pub trait EmptyTrait{} - +pub trait EmptyTrait {} impl EmptyTrait for () {} @@ -203,11 +191,10 @@ impl EmptyTrait for RArc {} impl EmptyTrait for RBox {} - ////////////////////////////////////// #[sabi_trait] -pub trait StaticTrait:'static{} +pub trait StaticTrait: 'static {} ////////////////////////////////////// @@ -266,59 +253,58 @@ pub struct Dummy0; #[sabi_trait] //#[sabi(debug_print_trait)] -pub trait RSomethingElse:Send+Debug{ - fn get(&self)->&T; - +pub trait RSomethingElse: Send + Debug { + fn get(&self) -> &T; + #[sabi(last_prefix_field)] - fn into_value(self)->T; + fn into_value(self) -> T; - fn passthrough_string(&self,value:RString)->RString{ + fn passthrough_string(&self, value: RString) -> RString { value } - fn passthrough_arc(&self,value:RArc)->RArc{ + fn passthrough_arc(&self, value: RArc) -> RArc { value } } - -impl RSomethingElse for u32{ - fn get(&self)->&u32{ +impl RSomethingElse for u32 { + fn get(&self) -> &u32 { self } - fn into_value(self)->u32{ + fn into_value(self) -> u32 { self } - fn passthrough_string(&self,_:RString)->RString{ + fn passthrough_string(&self, _: RString) -> RString { RString::new() } - fn passthrough_arc(&self,_:RArc)->RArc{ + fn passthrough_arc(&self, _: RArc) -> RArc { RArc::new(77) } } impl RSomethingElse for RArc where - T:Copy+Send+Sync+Debug + T: Copy + Send + Sync + Debug, { - fn get(&self)->&T{ + fn get(&self) -> &T { &**self } - fn into_value(self)->T{ + fn into_value(self) -> T { *self } } impl RSomethingElse for RBox where - T:Copy+Send+Debug + T: Copy + Send + Debug, { - fn get(&self)->&T{ + fn get(&self) -> &T { &**self } - fn into_value(self)->T{ + fn into_value(self) -> T { *self } } @@ -327,72 +313,63 @@ where #[sabi_trait] // #[sabi(debug_print_trait)] -pub trait RFoo<'a,T:Copy+'a>{ - fn get(&'a self)->&'a T; +pub trait RFoo<'a, T: Copy + 'a> { + fn get(&'a self) -> &'a T; } - -impl<'a,A:Copy+'a> RFoo<'a,A> for Tuple1{ - fn get(&'a self)->&'a A{ +impl<'a, A: Copy + 'a> RFoo<'a, A> for Tuple1 { + fn get(&'a self) -> &'a A { &self.0 } } - -impl<'a,A:'a,B:Copy+'a> RFoo<'a,B> for Tuple2{ - fn get(&'a self)->&'a B{ +impl<'a, A: 'a, B: Copy + 'a> RFoo<'a, B> for Tuple2 { + fn get(&'a self) -> &'a B { &self.1 } } -impl<'a,A:'a,B:'a,C:Copy+'a> RFoo<'a,C> for Tuple3{ - fn get(&'a self)->&'a C{ +impl<'a, A: 'a, B: 'a, C: Copy + 'a> RFoo<'a, C> for Tuple3 { + fn get(&'a self) -> &'a C { &self.2 } } - -impl<'a,T> RFoo<'a,T> for RArc +impl<'a, T> RFoo<'a, T> for RArc where - T:'a+Copy + T: 'a + Copy, { - fn get(&'a self)->&'a T{ + fn get(&'a self) -> &'a T { &**self } } - - ////////////////////////////////////// - ////////////////////////////////////// #[sabi_trait] //#[sabi(debug_print_trait)] -pub trait Dictionary{ +pub trait Dictionary { type Value; type Unused; - fn what(&self,_:&Self::Unused); - fn get(&self,key:RStr<'_>)->Option<&Self::Value>; - fn insert(&mut self,key:RString,value:Self::Value)->ROption; + fn what(&self, _: &Self::Unused); + fn get(&self, key: RStr<'_>) -> Option<&Self::Value>; + fn insert(&mut self, key: RString, value: Self::Value) -> ROption; } - ////////////////////////////////////// - #[cfg(all(test))] -mod tests{ +mod tests { use super::*; use crate::{ - sabi_types::{RRef, RMut}, + sabi_types::{RMut, RRef}, traits::IntoReprC, }; - fn assert_sync_send_debug_clone(_:&T){} - + fn assert_sync_send_debug_clone(_: &T) {} macro_rules! _something_test { ( @@ -400,114 +377,120 @@ mod tests{ fn $something_methods:ident, $typename:ident, $traitname:ident, - ) => ( + ) => { #[test] - fn $fn_name(){ - let number=100_u32; - let object=$typename::<_,(),u32>::from_value(number,TD_CanDowncast); - let arcobj=$typename::<_,(),u32>::from_ptr(RArc::new(number),TD_CanDowncast); - let erased=$typename::<_,(),u32>::from_ptr(RBox::new(number),TD_Opaque); - + fn $fn_name() { + let number = 100_u32; + let object = $typename::<_, (), u32>::from_value(number, TD_CanDowncast); + let arcobj = $typename::<_, (), u32>::from_ptr(RArc::new(number), TD_CanDowncast); + let erased = $typename::<_, (), u32>::from_ptr(RBox::new(number), TD_Opaque); + assert_sync_send_debug_clone(&object); assert_sync_send_debug_clone(&arcobj); assert_sync_send_debug_clone(&erased); - fn assertions_unerased(mut object:$typename<'_,RBox<()>,(),u32>){ - assert_eq!(object.obj.downcast_as::().ok(),Some(&100)); - assert_eq!(object.obj.downcast_as::().ok(),None::<&i8>); - assert_eq!(object.obj.downcast_as_mut::().ok(),Some(&mut 100)); - assert_eq!(object.obj.downcast_as_mut::().ok(),None::<&mut i8>); - object=object.obj.downcast_into::() + fn assertions_unerased(mut object: $typename<'_, RBox<()>, (), u32>) { + assert_eq!(object.obj.downcast_as::().ok(), Some(&100)); + assert_eq!(object.obj.downcast_as::().ok(), None::<&i8>); + assert_eq!(object.obj.downcast_as_mut::().ok(), Some(&mut 100)); + assert_eq!(object.obj.downcast_as_mut::().ok(), None::<&mut i8>); + object = object + .obj + .downcast_into::() .unwrap_err() .into_inner() .piped($typename::from_sabi); - assert_eq!(object.obj.downcast_into::().ok(),Some(RBox::new(100))); + assert_eq!(object.obj.downcast_into::().ok(), Some(RBox::new(100))); } - fn assertions_unerased_arc(mut object:$typename<'_,RArc<()>,(),u32>){ - assert_eq!(object.obj.downcast_as::().ok(),Some(&100)); - assert_eq!(object.obj.downcast_as::().ok(),None::<&i8>); - object=object.obj.downcast_into::() + fn assertions_unerased_arc(mut object: $typename<'_, RArc<()>, (), u32>) { + assert_eq!(object.obj.downcast_as::().ok(), Some(&100)); + assert_eq!(object.obj.downcast_as::().ok(), None::<&i8>); + object = object + .obj + .downcast_into::() .unwrap_err() .into_inner() .piped($typename::from_sabi); - assert_eq!(object.obj.downcast_into::().ok(),Some(RArc::new(100))); + assert_eq!(object.obj.downcast_into::().ok(), Some(RArc::new(100))); } - fn assertions_erased(mut object:$typename<'_,RBox<()>,(),u32>){ - assert_eq!(object.obj.downcast_as::().ok(),None); - assert_eq!(object.obj.downcast_as::().ok(),None); - assert_eq!(object.obj.downcast_as_mut::().ok(),None); - assert_eq!(object.obj.downcast_as_mut::().ok(),None); - object=object.obj.downcast_into::() + fn assertions_erased(mut object: $typename<'_, RBox<()>, (), u32>) { + assert_eq!(object.obj.downcast_as::().ok(), None); + assert_eq!(object.obj.downcast_as::().ok(), None); + assert_eq!(object.obj.downcast_as_mut::().ok(), None); + assert_eq!(object.obj.downcast_as_mut::().ok(), None); + object = object + .obj + .downcast_into::() .unwrap_err() .into_inner() .piped($typename::from_sabi); - let _=object.obj.downcast_into::().unwrap_err().into_inner(); + let _ = object.obj.downcast_into::().unwrap_err().into_inner(); } - fn create_from_ref<'a,T>(value:&'a T)->$typename<'a,RRef<'a, ()>,(),T::Element> + fn create_from_ref<'a, T>( + value: &'a T, + ) -> $typename<'a, RRef<'a, ()>, (), T::Element> where - T:$traitname<()>+'a + T: $traitname<()> + 'a, { - $typename::<_,(),T::Element>::from_ptr(value,TD_Opaque) + $typename::<_, (), T::Element>::from_ptr(value, TD_Opaque) } - fn create_from_val<'a,T>(value:T)->$typename<'a,RBox<()>,(),T::Element> + fn create_from_val<'a, T>(value: T) -> $typename<'a, RBox<()>, (), T::Element> where - T:$traitname<()>+'a, + T: $traitname<()> + 'a, { - $typename::<_,(),T::Element>::from_value(value,TD_Opaque) + $typename::<_, (), T::Element>::from_value(value, TD_Opaque) } - let what=RBox::new(100); - let _=create_from_ref(&*what); - let _=create_from_val(&*what); + let what = RBox::new(100); + let _ = create_from_ref(&*what); + let _ = create_from_val(&*what); - assert_eq!(format!("{:?}",number),format!("{:?}",erased)); - assert_eq!(format!("{:?}",number),format!("{:?}",arcobj)); - assert_eq!(format!("{:?}",number),format!("{:?}",object)); + assert_eq!(format!("{:?}", number), format!("{:?}", erased)); + assert_eq!(format!("{:?}", number), format!("{:?}", arcobj)); + assert_eq!(format!("{:?}", number), format!("{:?}", object)); - assert_eq!(format!("{:#?}",number),format!("{:?}",erased)); - assert_eq!(format!("{:#?}",number),format!("{:?}",arcobj)); - assert_eq!(format!("{:#?}",number),format!("{:?}",object)); + assert_eq!(format!("{:#?}", number), format!("{:?}", erased)); + assert_eq!(format!("{:#?}", number), format!("{:?}", arcobj)); + assert_eq!(format!("{:#?}", number), format!("{:?}", object)); assertions_unerased(object.clone()); assertions_unerased(object); - + assertions_unerased_arc(arcobj.clone()); assertions_unerased_arc(arcobj); - + assertions_erased(erased.clone()); - assertions_erased(erased); + assertions_erased(erased); } #[test] - fn $something_methods(){ - let mut object=$typename::<_,(),_>::from_value(100,TD_Opaque); - let mut cloned=object.clone(); - - assert_eq!(object.get(),&100); - assert_eq!(object.get_mut(),&mut 100); - assert_eq!(object.into_value(),100); - - assert_eq!($traitname::get(&cloned),&100); - assert_eq!($traitname::get_mut(&mut cloned),&mut 100); - assert_eq!($traitname::into_value(cloned),100); - } + fn $something_methods() { + let mut object = $typename::<_, (), _>::from_value(100, TD_Opaque); + let mut cloned = object.clone(); + assert_eq!(object.get(), &100); + assert_eq!(object.get_mut(), &mut 100); + assert_eq!(object.into_value(), 100); - ) + assert_eq!($traitname::get(&cloned), &100); + assert_eq!($traitname::get_mut(&mut cloned), &mut 100); + assert_eq!($traitname::into_value(cloned), 100); + } + }; } - _something_test!{ + _something_test! { fn construct_rsomething, fn rsomething_methods, RSomething_TO, RSomething, } - _something_test!{ + _something_test! { fn construct_dsomething, fn dsomething_methods, DSomething_TO, @@ -515,64 +498,58 @@ mod tests{ } #[test] - fn construct_rempty(){ - let arc=Arc::new(107_u32); - let rarc=arc.clone().into_c(); + fn construct_rempty() { + let arc = Arc::new(107_u32); + let rarc = arc.clone().into_c(); assert_eq!(Arc::strong_count(&arc), 2); - let mut object:EmptyTrait_TO<'_,RBox<()>>= - EmptyTrait_TO::from_value(rarc.clone(),TD_CanDowncast); - + let mut object: EmptyTrait_TO<'_, RBox<()>> = + EmptyTrait_TO::from_value(rarc.clone(), TD_CanDowncast); + assert_eq!(Arc::strong_count(&arc), 3); - let erased:EmptyTrait_TO<'_,RArc<()>>= - EmptyTrait_TO::from_ptr(rarc.clone(),TD_Opaque); - + let erased: EmptyTrait_TO<'_, RArc<()>> = EmptyTrait_TO::from_ptr(rarc.clone(), TD_Opaque); + assert_eq!(Arc::strong_count(&arc), 4); - assert_eq!( - **object.obj.downcast_as::>().unwrap(), - 107 - ); - assert_eq!( - **object.obj.downcast_as_mut::>().unwrap(), - 107 - ); - + assert_eq!(**object.obj.downcast_as::>().unwrap(), 107); + assert_eq!(**object.obj.downcast_as_mut::>().unwrap(), 107); + assert_eq!(Arc::strong_count(&arc), 4); - object=object.obj.downcast_into::() + object = object + .obj + .downcast_into::() .unwrap_err() .into_inner() .piped(EmptyTrait_TO::from_sabi); assert_eq!(Arc::strong_count(&arc), 4); - + assert_eq!( object.obj.downcast_into::>().unwrap(), RBox::new(RArc::new(107)) ); - + assert_eq!(Arc::strong_count(&arc), 3); erased.obj.downcast_into::().unwrap_err(); - + assert_eq!(Arc::strong_count(&arc), 2); - } #[test] - fn test_reborrowing(){ - let arc=Arc::new(107_u32); - let rarc=arc.clone().into_c(); + fn test_reborrowing() { + let arc = Arc::new(107_u32); + let rarc = arc.clone().into_c(); assert_eq!(Arc::strong_count(&arc), 2); - let mut object:RSomething_TO<'_,RBox<()>,(),u32>= - RSomething_TO::<_,(),u32>::from_value(rarc.clone(),TD_CanDowncast); - + let mut object: RSomething_TO<'_, RBox<()>, (), u32> = + RSomething_TO::<_, (), u32>::from_value(rarc.clone(), TD_CanDowncast); + assert_eq!(Arc::strong_count(&arc), 3); - - for _ in 0..10{ + + for _ in 0..10 { assert_eq!( object.obj.reborrow().downcast_into::>().unwrap(), RRef::new(&RArc::new(107)) @@ -580,21 +557,23 @@ mod tests{ } assert_eq!(Arc::strong_count(&arc), 3); - - for _ in 0..10{ + for _ in 0..10 { assert_eq!( - object.obj.reborrow_mut().downcast_into::>().unwrap(), + object + .obj + .reborrow_mut() + .downcast_into::>() + .unwrap(), RMut::new(&mut RArc::new(107)) ); } - assert_eq!(Arc::strong_count(&arc), 3); { - let cloned=object.obj.reborrow().clone(); + let cloned = object.obj.reborrow().clone(); - assert_eq!(format!("{:?}",cloned),"107"); + assert_eq!(format!("{:?}", cloned), "107"); } assert_eq!(Arc::strong_count(&arc), 3); @@ -602,98 +581,82 @@ mod tests{ drop(object); assert_eq!(Arc::strong_count(&arc), 2); - } #[test] - fn rsomething_else(){ + fn rsomething_else() { { - let object=RSomethingElse_TO::from_value(RArc::new(100_u32),TD_Opaque); - let _:&dyn RSomethingElse=&object; - - assert_eq!(object.get(),&100); - assert_eq!(object.passthrough_arc(RArc::new(90)), RArc::new(90)); - assert_eq!(object.passthrough_string(RString::from("what")), RString::from("what")); - assert_eq!(object.into_value(),100); + let object = RSomethingElse_TO::from_value(RArc::new(100_u32), TD_Opaque); + let _: &dyn RSomethingElse = &object; - } - { - let object=RSomethingElse_TO::from_value(RArc::new(100_u32),TD_Opaque); + assert_eq!(object.get(), &100); + assert_eq!(object.passthrough_arc(RArc::new(90)), RArc::new(90)); assert_eq!( - RSomethingElse::get(&object,), - &100 + object.passthrough_string(RString::from("what")), + RString::from("what") ); + assert_eq!(object.into_value(), 100); + } + { + let object = RSomethingElse_TO::from_value(RArc::new(100_u32), TD_Opaque); + assert_eq!(RSomethingElse::get(&object,), &100); assert_eq!( - RSomethingElse::passthrough_arc(&object,RArc::new(90)), + RSomethingElse::passthrough_arc(&object, RArc::new(90)), RArc::new(90) ); assert_eq!( - RSomethingElse::passthrough_string(&object,RString::from("what")), + RSomethingElse::passthrough_string(&object, RString::from("what")), RString::from("what") ); - assert_eq!( - RSomethingElse::into_value(object), - 100 - ); + assert_eq!(RSomethingElse::into_value(object), 100); } { - let object=RSomethingElse_TO::<_,u32>::from_value(100u32,TD_CanDowncast); + let object = RSomethingElse_TO::<_, u32>::from_value(100u32, TD_CanDowncast); assert_eq!( - RSomethingElse::passthrough_arc(&object,RArc::new(90)), + RSomethingElse::passthrough_arc(&object, RArc::new(90)), RArc::new(77) ); assert_eq!( - RSomethingElse::passthrough_string(&object,RString::from("what")), + RSomethingElse::passthrough_string(&object, RString::from("what")), RString::from("") ); } } #[test] - fn rfoo(){ - let object = &RFoo_TO::from_ptr(RBox::new(RArc::new(76)),TD_Opaque); - let tuple1_object = &RFoo_TO::from_ptr(RArc::new(Tuple1(100)),TD_Opaque); - let tuple2_object = &RFoo_TO::from_value(Tuple2(101u32,202_u32),TD_Opaque); - let tuple3_object = &RFoo_TO::from_value(Tuple3(11,22,300_u32),TD_Opaque); - - assert_eq!(object.get(),&76); - assert_eq!(tuple1_object.get(),&100); - assert_eq!(tuple2_object.get(),&202); - assert_eq!(tuple3_object.get(),&300); - - assert_eq!(RFoo::get(object),&76); - assert_eq!(RFoo::get(tuple1_object),&100); - assert_eq!(RFoo::get(tuple2_object),&202); - assert_eq!(RFoo::get(tuple3_object),&300); + fn rfoo() { + let object = &RFoo_TO::from_ptr(RBox::new(RArc::new(76)), TD_Opaque); + let tuple1_object = &RFoo_TO::from_ptr(RArc::new(Tuple1(100)), TD_Opaque); + let tuple2_object = &RFoo_TO::from_value(Tuple2(101u32, 202_u32), TD_Opaque); + let tuple3_object = &RFoo_TO::from_value(Tuple3(11, 22, 300_u32), TD_Opaque); + + assert_eq!(object.get(), &76); + assert_eq!(tuple1_object.get(), &100); + assert_eq!(tuple2_object.get(), &202); + assert_eq!(tuple3_object.get(), &300); + + assert_eq!(RFoo::get(object), &76); + assert_eq!(RFoo::get(tuple1_object), &100); + assert_eq!(RFoo::get(tuple2_object), &202); + assert_eq!(RFoo::get(tuple3_object), &300); } #[test] - fn test_from_const(){ - const RS_U32:RSomething_CTO<'static,'static,(),u32>= - RSomething_CTO::from_const( - &0, - TD_Opaque, - RSomething_MV::VTABLE, - ); + fn test_from_const() { + const RS_U32: RSomething_CTO<'static, 'static, (), u32> = + RSomething_CTO::from_const(&0, TD_Opaque, RSomething_MV::VTABLE); assert_eq!(RS_U32.get(), &0); - fn make_const_rsomething<'borr,'a,T,U>(ref_:&'a T)->RSomething_CTO<'borr,'a,(),U> + fn make_const_rsomething<'borr, 'a, T, U>(ref_: &'a T) -> RSomething_CTO<'borr, 'a, (), U> where - T:'borr+RSomething<(),Element=U>, - U:Debug, + T: 'borr + RSomething<(), Element = U>, + U: Debug, { - RSomething_CTO::from_const( - ref_, - TD_Opaque, - RSomething_MV::VTABLE, - ) + RSomething_CTO::from_const(ref_, TD_Opaque, RSomething_MV::VTABLE) } - let hi=make_const_rsomething(&77); + let hi = make_const_rsomething(&77); assert_eq!(hi.get(), &77); - - } - -} \ No newline at end of file +} diff --git a/abi_stable/src/sabi_trait/robject.rs b/abi_stable/src/sabi_trait/robject.rs index 720c2a91..aae4533f 100644 --- a/abi_stable/src/sabi_trait/robject.rs +++ b/abi_stable/src/sabi_trait/robject.rs @@ -1,108 +1,100 @@ use super::*; - -use std::{ - fmt, -}; + +use std::fmt; #[allow(unused_imports)] use core_extensions::SelfOps; use crate::{ abi_stability::PrefixStableAbi, - erased_types::{ - c_functions::adapt_std_fmt, - InterfaceBound, - }, - sabi_types::{MaybeCmp, RRef, RMut}, - std_types::UTypeId, + erased_types::{c_functions::adapt_std_fmt, InterfaceBound}, pointer_trait::{ - AsPtr, AsMutPtr, - CanTransmuteElement, TransmuteElement, - GetPointerKind, PK_SmartPointer, PK_Reference, PointerKind, + AsMutPtr, AsPtr, CanTransmuteElement, GetPointerKind, PK_Reference, PK_SmartPointer, + PointerKind, TransmuteElement, }, + sabi_trait::vtable::{BaseVtable_Prefix, BaseVtable_Ref}, + sabi_types::{MaybeCmp, RMut, RRef}, + std_types::UTypeId, type_level::{ impl_enum::{Implemented, Unimplemented}, trait_marker, }, - sabi_trait::vtable::{BaseVtable_Ref, BaseVtable_Prefix}, StableAbi, }; - /// `RObject` implements ffi-safe trait objects, for a minimal selection of traits. -/// -/// The main use of `RObject<_>` is as the default backend for `#[sabi_trait]` +/// +/// The main use of `RObject<_>` is as the default backend for `#[sabi_trait]` /// generated trait objects. -/// +/// /// # Construction -/// +/// /// `RObject<_>` is how `#[sabi_trait]`-based ffi-safe trait objects are implemented, /// and there's no way to construct it separate from those. -/// +/// /// # Trait object -/// -/// `RObject<'borrow, Pointer<()>, Interface, VTable>` -/// can be used as a trait object for any combination of +/// +/// `RObject<'borrow, Pointer<()>, Interface, VTable>` +/// can be used as a trait object for any combination of /// the traits listed below: -/// +/// /// - `Send` -/// +/// /// - `Sync` -/// +/// /// - `Debug` -/// +/// /// - `Display` -/// +/// /// - `Error` -/// +/// /// - `Clone` -/// +/// /// # Deconstruction -/// +/// /// `RObject<_>` can be unwrapped into a concrete type, /// within the same dynamic library/executable that constructed it, /// using these (fallible) conversion methods: -/// +/// /// - [`downcast_into`](#method.downcast_into): /// Unwraps into a pointer to `T`.Requires `T: 'static`. -/// +/// /// - [`downcast_as`](#method.downcast_as): /// Unwraps into a `&T`.Requires `T: 'static`. -/// +/// /// - [`downcast_as_mut`](#method.downcast_as_mut): /// Unwraps into a `&mut T`.Requires `T: 'static`. -/// +/// /// `RObject` can only be converted back if the trait object was constructed to allow it. -/// -/// -/// -/// -/// +/// +/// +/// +/// +/// #[repr(C)] #[derive(StableAbi)] #[sabi( not_stableabi(V), - bound="V:PrefixStableAbi", - bound="I:InterfaceBound", - extra_checks="::EXTRA_CHECKS", + bound = "V:PrefixStableAbi", + bound = "I:InterfaceBound", + extra_checks = "::EXTRA_CHECKS" )] pub struct RObject<'lt, P, I, V> where - P: GetPointerKind + P: GetPointerKind, { - vtable:PrefixRef, + vtable: PrefixRef, ptr: ManuallyDrop

, - _marker:PhantomData<(&'lt (), I)>, + _marker: PhantomData<(&'lt (), I)>, } -mod clone_impl{ - pub trait CloneImpl{ +mod clone_impl { + pub trait CloneImpl { fn clone_impl(&self) -> Self; } } use self::clone_impl::CloneImpl; - /// This impl is for smart pointers. impl<'lt, P, I, V> CloneImpl for RObject<'lt, P, I, V> where @@ -110,13 +102,12 @@ where I: InterfaceType>, { fn clone_impl(&self) -> Self { - let ptr=unsafe{ - self.sabi_robject_vtable()._sabi_clone().unwrap()(RRef::new(&self.ptr)) - }; - Self{ - vtable:self.vtable, - ptr:ManuallyDrop::new(ptr), - _marker:PhantomData, + let ptr = + unsafe { self.sabi_robject_vtable()._sabi_clone().unwrap()(RRef::new(&self.ptr)) }; + Self { + vtable: self.vtable, + ptr: ManuallyDrop::new(ptr), + _marker: PhantomData, } } } @@ -124,14 +115,14 @@ where /// This impl is for references. impl<'lt, P, I, V> CloneImpl for RObject<'lt, P, I, V> where - P: AsPtr+Copy, + P: AsPtr + Copy, I: InterfaceType, { fn clone_impl(&self) -> Self { - Self{ - vtable:self.vtable, - ptr:ManuallyDrop::new(*self.ptr), - _marker:PhantomData, + Self { + vtable: self.vtable, + ptr: ManuallyDrop::new(*self.ptr), + _marker: PhantomData, } } } @@ -179,42 +170,40 @@ impl<'lt, P, I, V> Clone for RObject<'lt, P, I, V> where P: AsPtr, I: InterfaceType, - Self:CloneImpl<

::Kind>, + Self: CloneImpl<

::Kind>, { fn clone(&self) -> Self { self.clone_impl() } } - -impl<'lt, P, I, V> Debug for RObject<'lt, P, I, V> +impl<'lt, P, I, V> Debug for RObject<'lt, P, I, V> where - P: AsPtr+AsPtr, + P: AsPtr + AsPtr, I: InterfaceType>, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - unsafe{ + unsafe { adapt_std_fmt::( - self.sabi_erased_ref(), - self.sabi_robject_vtable()._sabi_debug().unwrap(), - f + self.sabi_erased_ref(), + self.sabi_robject_vtable()._sabi_debug().unwrap(), + f, ) } } } - -impl<'lt, P, I, V> Display for RObject<'lt, P, I, V> +impl<'lt, P, I, V> Display for RObject<'lt, P, I, V> where P: AsPtr, I: InterfaceType>, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - unsafe{ + unsafe { adapt_std_fmt::( - self.sabi_erased_ref(), - self.sabi_robject_vtable()._sabi_display().unwrap(), - f + self.sabi_erased_ref(), + self.sabi_robject_vtable()._sabi_display().unwrap(), + f, ) } } @@ -222,144 +211,138 @@ where impl<'lt, P, I, V> std::error::Error for RObject<'lt, P, I, V> where - P: AsPtr, + P: AsPtr, I: InterfaceBound< - Display=Implemented, - Debug=Implemented, - Error=Implemented, + Display = Implemented, + Debug = Implemented, + Error = Implemented, >, -{} - - - -unsafe impl<'lt, P, I, V> Send for RObject<'lt, P, I, V> -where - P:GetPointerKind, - I:InterfaceType>, -{} +{ +} -unsafe impl<'lt, P, I, V> Sync for RObject<'lt, P, I, V> +unsafe impl<'lt, P, I, V> Send for RObject<'lt, P, I, V> where - P:GetPointerKind, - I:InterfaceType>, -{} + P: GetPointerKind, + I: InterfaceType>, +{ +} +unsafe impl<'lt, P, I, V> Sync for RObject<'lt, P, I, V> +where + P: GetPointerKind, + I: InterfaceType>, +{ +} impl<'lt, P, I, V> RObject<'lt, P, I, V> where - P:AsPtr, + P: AsPtr, { -/** + /** -Constructs an RObject from a pointer and an extra vtable. + Constructs an RObject from a pointer and an extra vtable. -This is mostly intended to be called by `#[sabi_trait]` generated trait objects. + This is mostly intended to be called by `#[sabi_trait]` generated trait objects. -# Safety + # Safety -These are the requirements for the caller: + These are the requirements for the caller: -- `P` must be a pointer to the type that the vtable functions - take as the first parameter. + - `P` must be a pointer to the type that the vtable functions + take as the first parameter. -- The vtable must not come from a reborrowed `RObject` - (created using `RObject::reborrow` or `RObject::reborrow_mut`). + - The vtable must not come from a reborrowed `RObject` + (created using `RObject::reborrow` or `RObject::reborrow_mut`). -- The vtable must be the `SomeVTableName` of a struct declared with - `#[derive(StableAbi)] #[sabi(kind(Prefix(prefix_ref="SomeVTableName")))]`. + - The vtable must be the `SomeVTableName` of a struct declared with + `#[derive(StableAbi)] #[sabi(kind(Prefix(prefix_ref="SomeVTableName")))]`. -- The vtable must have `RObjectVtable_Ref` as its first declared field + - The vtable must have `RObjectVtable_Ref` as its first declared field -*/ - pub unsafe fn with_vtable( - ptr:OrigPtr, - vtable:PrefixRef, - )-> RObject<'lt, P, I, V> - where - OrigPtr: CanTransmuteElement<(), TransmutedPtr=P>, - OrigPtr::PtrTarget: Sized+'lt, - P:AsPtr, + */ + pub unsafe fn with_vtable(ptr: OrigPtr, vtable: PrefixRef) -> RObject<'lt, P, I, V> + where + OrigPtr: CanTransmuteElement<(), TransmutedPtr = P>, + OrigPtr::PtrTarget: Sized + 'lt, + P: AsPtr, { - RObject{ + RObject { vtable, - ptr:ManuallyDrop::new( ptr.transmute_element::<()>() ), - _marker:PhantomData, + ptr: ManuallyDrop::new(ptr.transmute_element::<()>()), + _marker: PhantomData, } } } +impl<'borr, 'a, I, V> RObject<'borr, RRef<'a, ()>, I, V> { + /** + This function allows constructing an RObject in a constant/static. -impl<'borr,'a, I, V> RObject<'borr, RRef<'a,()>, I, V>{ - -/** -This function allows constructing an RObject in a constant/static. - -This is mostly intended for `#[sabi_trait] generated trait objects` + This is mostly intended for `#[sabi_trait] generated trait objects` -# Safety + # Safety -This has the same safety requirements as `RObject::with_vtable` + This has the same safety requirements as `RObject::with_vtable` -# Example + # Example -Because this is intended for `#[sabi_trait]` generated trait objects, -this demonstrates how to construct one in a constant. + Because this is intended for `#[sabi_trait]` generated trait objects, + this demonstrates how to construct one in a constant. -``` -use abi_stable::sabi_trait::{ - doc_examples::{ConstExample_CTO, ConstExample_MV}, - prelude::TD_Opaque, -}; + ``` + use abi_stable::sabi_trait::{ + doc_examples::{ConstExample_CTO, ConstExample_MV}, + prelude::TD_Opaque, + }; -const EXAMPLE0:ConstExample_CTO<'static,'static>= - ConstExample_CTO::from_const( - &0usize, - TD_Opaque, - ConstExample_MV::VTABLE, - ); + const EXAMPLE0:ConstExample_CTO<'static,'static>= + ConstExample_CTO::from_const( + &0usize, + TD_Opaque, + ConstExample_MV::VTABLE, + ); -``` + ``` -*/ + */ pub const unsafe fn with_vtable_const( ptr: &'a T, - vtable:VTableTO_RO, Downcasting, V>, - )-> Self + vtable: VTableTO_RO, Downcasting, V>, + ) -> Self where - T:'borr, + T: 'borr, { - RObject{ + RObject { vtable: vtable.robject_vtable(), - ptr:{ - let x=RRef::new(ptr).transmute::<()>(); + ptr: { + let x = RRef::new(ptr).transmute::<()>(); ManuallyDrop::new(x) }, - _marker:PhantomData, + _marker: PhantomData, } } } - impl<'lt, P, I, V> RObject<'lt, P, I, V> where - P:GetPointerKind, + P: GetPointerKind, { /// The uid in the vtable has to be the same as the one for T, - /// otherwise it was not created from that T in the library that + /// otherwise it was not created from that T in the library that /// declared the trait object. fn sabi_check_same_utypeid(&self) -> Result<(), UneraseError<()>> where - T:'static, + T: 'static, { - let expected_typeid=self.sabi_robject_vtable()._sabi_type_id().get(); - let actual_typeid=UTypeId::new::(); + let expected_typeid = self.sabi_robject_vtable()._sabi_type_id().get(); + let actual_typeid = UTypeId::new::(); if expected_typeid == MaybeCmp::Just(actual_typeid) { Ok(()) } else { Err(UneraseError { - robject:(), + robject: (), expected_typeid, actual_typeid, }) @@ -375,14 +358,14 @@ where /// - It is called in a dynamic library/binary outside /// the one from which this RObject was constructed. /// - /// - The trait object wrapping this `RObject` was constructed with a + /// - The trait object wrapping this `RObject` was constructed with a /// `TD_CanDowncast` argument. /// /// - `T` is not the concrete type this `RObject<_>` was constructed with. /// /// # Example /// - /// ```rust + /// ```rust /// use abi_stable::{ /// sabi_trait::doc_examples::Doer_TO, /// std_types::RBox, @@ -398,17 +381,17 @@ where /// ``` pub fn downcast_into(self) -> Result> where - T:'static, - P: AsPtr + CanTransmuteElement, + T: 'static, + P: AsPtr + CanTransmuteElement, { check_unerased!(self, self.sabi_check_same_utypeid::()); unsafe { - let this=ManuallyDrop::new(self); - Ok(ptr::read(&*this.ptr).transmute_element::()) + let this = ManuallyDrop::new(self); + Ok(ptr::read(&*this.ptr).transmute_element::()) } } - /// Attempts to unerase this trait object into a reference of + /// Attempts to unerase this trait object into a reference of /// the value was constructed with. /// /// # Errors @@ -418,14 +401,14 @@ where /// - It is called in a dynamic library/binary outside /// the one from which this RObject was constructed. /// - /// - The trait object wrapping this `RObject` was constructed with a + /// - The trait object wrapping this `RObject` was constructed with a /// `TD_CanDowncast` argument. /// /// - `T` is not the concrete type this `RObject<_>` was constructed with. /// /// # Example /// - /// ```rust + /// ```rust /// use abi_stable::{ /// sabi_trait::doc_examples::Doer_TO, /// std_types::RArc, @@ -443,7 +426,7 @@ where /// } /// { /// // `#[sabi_trait]` trait objects constructed from `&` - /// // use `RRef<'_, ()>` instead of `&'_ ()` + /// // use `RRef<'_, ()>` instead of `&'_ ()` /// // since `&T` can't soundly be transmuted back and forth into `&()` /// let to: Doer_TO<'_, RRef<'_, ()>> = /// Doer_TO::from_ptr(&13usize, TD_CanDowncast); @@ -453,8 +436,8 @@ where /// } /// { /// let mmut = &mut 21usize; - /// // `#[sabi_trait]` trait objects constructed from `&mut` - /// // use `RMut<'_, ()>` instead of `&'_ mut ()` + /// // `#[sabi_trait]` trait objects constructed from `&mut` + /// // use `RMut<'_, ()>` instead of `&'_ mut ()` /// // since `&mut T` can't soundly be transmuted back and forth into `&mut ()` /// let to: Doer_TO<'_, RMut<'_, ()>> = /// Doer_TO::from_ptr(mmut, TD_CanDowncast); @@ -466,16 +449,14 @@ where /// ``` pub fn downcast_as(&self) -> Result<&T, UneraseError<&Self>> where - T:'static, - P:AsPtr+CanTransmuteElement, + T: 'static, + P: AsPtr + CanTransmuteElement, { check_unerased!(self, self.sabi_check_same_utypeid::()); - unsafe { - Ok(&*(self.ptr.as_ptr() as *const T)) - } + unsafe { Ok(&*(self.ptr.as_ptr() as *const T)) } } - /// Attempts to unerase this trait object into a mutable reference of + /// Attempts to unerase this trait object into a mutable reference of /// the value was constructed with. /// /// # Errors @@ -485,7 +466,7 @@ where /// - It is called in a dynamic library/binary outside /// the one from which this RObject was constructed. /// - /// - The trait object wrapping this `RObject` was constructed with a + /// - The trait object wrapping this `RObject` was constructed with a /// `TD_CanDowncast` argument. /// /// - `T` is not the concrete type this `RObject<_>` was constructed with. @@ -493,7 +474,7 @@ where /// /// # Example /// - /// ```rust + /// ```rust /// use abi_stable::{ /// sabi_trait::doc_examples::Doer_TO, /// std_types::RBox, @@ -511,8 +492,8 @@ where /// } /// { /// let mmut = &mut 55usize; - /// // `#[sabi_trait]` trait objects constructed from `&mut` - /// // use `RMut<'_, ()>` instead of `&'_ mut ()` + /// // `#[sabi_trait]` trait objects constructed from `&mut` + /// // use `RMut<'_, ()>` instead of `&'_ mut ()` /// // since `&mut T` can't soundly be transmuted back and forth into `&mut ()` /// let mut to: Doer_TO<'_, RMut<'_, ()>> = /// Doer_TO::from_ptr(mmut, TD_CanDowncast); @@ -524,13 +505,11 @@ where /// ``` pub fn downcast_as_mut(&mut self) -> Result<&mut T, UneraseError<&mut Self>> where - T:'static, - P:AsMutPtr+CanTransmuteElement, + T: 'static, + P: AsMutPtr + CanTransmuteElement, { check_unerased!(self, self.sabi_check_same_utypeid::()); - unsafe { - Ok(&mut *(self.ptr.as_mut_ptr() as *mut T)) - } + unsafe { Ok(&mut *(self.ptr.as_mut_ptr() as *mut T)) } } /// Unwraps the `RObject<_>` into a pointer to T, @@ -543,7 +522,7 @@ where /// /// # Example /// - /// ```rust + /// ```rust /// use abi_stable::{ /// sabi_trait::doc_examples::Doer_TO, /// std_types::RBox, @@ -551,7 +530,7 @@ where /// }; /// /// let to = ||Doer_TO::from_value(5usize, TD_Opaque); - /// + /// /// unsafe{ /// // `to.obj` is an RObject /// assert_eq!(to().obj.unchecked_downcast_into::(), RBox::new(5usize)); @@ -560,9 +539,9 @@ where #[inline] pub unsafe fn unchecked_downcast_into(self) -> P::TransmutedPtr where - P: AsPtr + CanTransmuteElement, + P: AsPtr + CanTransmuteElement, { - let this=ManuallyDrop::new(self); + let this = ManuallyDrop::new(self); ptr::read(&*this.ptr).transmute_element::() } @@ -576,7 +555,7 @@ where /// /// # Example /// - /// ```rust + /// ```rust /// use abi_stable::{ /// sabi_trait::doc_examples::Doer_TO, /// std_types::RArc, @@ -595,7 +574,7 @@ where /// } /// { /// // `#[sabi_trait]` trait objects constructed from `&` - /// // use `RRef<'_, ()>` instead of `&'_ ()` + /// // use `RRef<'_, ()>` instead of `&'_ ()` /// // since `&T` can't soundly be transmuted back and forth into `&()` /// let to: Doer_TO<'_, RRef<'_, ()>> = /// Doer_TO::from_ptr(&13usize, TD_Opaque); @@ -606,8 +585,8 @@ where /// } /// { /// let mmut = &mut 21usize; - /// // `#[sabi_trait]` trait objects constructed from `&mut` - /// // use `RMut<'_, ()>` instead of `&'_ mut ()` + /// // `#[sabi_trait]` trait objects constructed from `&mut` + /// // use `RMut<'_, ()>` instead of `&'_ mut ()` /// // since `&mut T` can't soundly be transmuted back and forth into `&mut ()` /// let to: Doer_TO<'_, RMut<'_, ()>> = /// Doer_TO::from_ptr(mmut, TD_Opaque); @@ -621,7 +600,7 @@ where #[inline] pub unsafe fn unchecked_downcast_as(&self) -> &T where - P:AsPtr, + P: AsPtr, { &*(self.ptr.as_ptr() as *const T) } @@ -636,7 +615,7 @@ where /// /// # Example /// - /// ```rust + /// ```rust /// use abi_stable::{ /// sabi_trait::doc_examples::Doer_TO, /// std_types::RBox, @@ -655,8 +634,8 @@ where /// } /// { /// let mmut = &mut 55usize; - /// // `#[sabi_trait]` trait objects constructed from `&mut` - /// // use `RMut<'_, ()>` instead of `&'_ mut ()` + /// // `#[sabi_trait]` trait objects constructed from `&mut` + /// // use `RMut<'_, ()>` instead of `&'_ mut ()` /// // since `&mut T` can't soundly be transmuted back and forth into `&mut ()` /// let mut to: Doer_TO<'_, RMut<'_, ()>> = /// Doer_TO::from_ptr(mmut, TD_Opaque); @@ -670,38 +649,36 @@ where #[inline] pub unsafe fn unchecked_downcast_as_mut(&mut self) -> &mut T where - P:AsMutPtr, + P: AsMutPtr, { &mut *(self.ptr.as_mut_ptr() as *mut T) } - } - mod private_struct { pub struct PrivStruct; } use self::private_struct::PrivStruct; - -/// This is used to make sure that reborrowing does not change +/// This is used to make sure that reborrowing does not change /// the Send-ness or Sync-ness of the pointer. -pub trait ReborrowBounds{} +pub trait ReborrowBounds {} // If it's reborrowing, it must have either both Sync+Send or neither. -impl ReborrowBounds, Unimplemented> -for PrivStruct -{} - -impl ReborrowBounds, Implemented> -for PrivStruct -{} +impl ReborrowBounds, Unimplemented> + for PrivStruct +{ +} +impl ReborrowBounds, Implemented> + for PrivStruct +{ +} impl<'lt, P, I, V> RObject<'lt, P, I, V> where - P:GetPointerKind, - I:InterfaceType, + P: GetPointerKind, + I: InterfaceType, { /// Creates a shared reborrow of this RObject. /// @@ -716,20 +693,20 @@ where /// type_level::downcasting::TD_Opaque, /// RRef, RMut, /// }; - /// + /// /// let mut to: Doer_TO<'_, RBox<()>> = /// Doer_TO::from_value(13usize, TD_Opaque); - /// + /// /// // `to.obj` is an RObject /// assert_eq!(debug_string(to.obj.reborrow()), "13"); /// assert_eq!(debug_string(to.obj.reborrow()), "13"); - /// + /// /// // `#[sabi_trait]` trait objects have an equivalent `sabi_reborrow` method. /// assert_eq!(debug_string(to.sabi_reborrow()), "13"); /// assert_eq!(debug_string(to.sabi_reborrow()), "13"); - /// - /// - /// fn debug_string(to: T) -> String + /// + /// + /// fn debug_string(to: T) -> String /// where /// T: std::fmt::Debug /// { @@ -737,16 +714,16 @@ where /// } /// /// ``` - pub fn reborrow<'re>(&'re self)->RObject<'lt, RRef<'re, ()>, I, V> + pub fn reborrow<'re>(&'re self) -> RObject<'lt, RRef<'re, ()>, I, V> where - P:AsPtr, - PrivStruct:ReborrowBounds, + P: AsPtr, + PrivStruct: ReborrowBounds, { // Reborrowing will break if I add extra functions that operate on `P`. - RObject{ - vtable:self.vtable, - ptr:ManuallyDrop::new(self.ptr.as_rref()), - _marker:PhantomData, + RObject { + vtable: self.vtable, + ptr: ManuallyDrop::new(self.ptr.as_rref()), + _marker: PhantomData, } } @@ -767,16 +744,16 @@ where /// type_level::downcasting::TD_Opaque, /// RRef, RMut, /// }; - /// + /// /// let mut to: Doer_TO<'_, RBox<()>> = /// Doer_TO::from_value(2usize, TD_Opaque); - /// + /// /// // `#[sabi_trait]` trait objects have an equivalent `sabi_reborrow_mut` method, /// // which delegate to this method. /// assert_eq!(increment(to.sabi_reborrow_mut()).value(), 3); /// assert_eq!(increment(to.sabi_reborrow_mut()).value(), 4); - /// - /// + /// + /// /// fn increment(mut to: T) -> T /// where /// T: Doer @@ -786,69 +763,62 @@ where /// } /// /// ``` - pub fn reborrow_mut<'re>(&'re mut self)->RObject<'lt, RMut<'re, ()>, I, V> + pub fn reborrow_mut<'re>(&'re mut self) -> RObject<'lt, RMut<'re, ()>, I, V> where - P:AsMutPtr, - PrivStruct:ReborrowBounds, + P: AsMutPtr, + PrivStruct: ReborrowBounds, { // Reborrowing will break if I add extra functions that operate on `P`. RObject { vtable: self.vtable, ptr: ManuallyDrop::new(self.ptr.as_rmut()), - _marker:PhantomData, + _marker: PhantomData, } } } - - - impl<'lt, P, I, V> RObject<'lt, P, I, V> where - P:GetPointerKind, + P: GetPointerKind, { /// Gets the vtable. #[inline] - pub fn sabi_et_vtable(&self)->PrefixRef{ + pub fn sabi_et_vtable(&self) -> PrefixRef { self.vtable } /// The vtable common to all `#[sabi_trait]` generated trait objects. #[inline] - pub fn sabi_robject_vtable(&self)->RObjectVtable_Ref<(), P, I>{ - unsafe{ - BaseVtable_Ref(self.vtable.cast::>()) - ._sabi_vtable() - } + pub fn sabi_robject_vtable(&self) -> RObjectVtable_Ref<(), P, I> { + unsafe { BaseVtable_Ref(self.vtable.cast::>())._sabi_vtable() } } #[inline] - fn sabi_into_erased_ptr(self)->ManuallyDrop

{ - let __this= ManuallyDrop::new(self); - unsafe{ ptr::read(&__this.ptr) } + fn sabi_into_erased_ptr(self) -> ManuallyDrop

{ + let __this = ManuallyDrop::new(self); + unsafe { ptr::read(&__this.ptr) } } /// Gets an `RRef` pointing to the erased object. pub fn sabi_erased_ref(&self) -> RRef<'_, ErasedObject<()>> where - P: AsPtr + P: AsPtr, { - unsafe{ RRef::from_raw(self.ptr.as_ptr() as *const _) } + unsafe { RRef::from_raw(self.ptr.as_ptr() as *const _) } } /// Gets an `RMut` pointing to the erased object. pub fn sabi_erased_mut(&mut self) -> RMut<'_, ErasedObject<()>> where - P: AsMutPtr + P: AsMutPtr, { - unsafe{ RMut::from_raw(self.ptr.as_mut_ptr() as *mut _) } + unsafe { RMut::from_raw(self.ptr.as_mut_ptr() as *mut _) } } - /// Gets an `RRef` pointing to the erased object. pub fn sabi_as_rref(&self) -> RRef<'_, ()> where - P: AsPtr + P: AsPtr, { self.ptr.as_rref() } @@ -856,17 +826,17 @@ where /// Gets an `RMut` pointing to the erased object. pub fn sabi_as_rmut(&mut self) -> RMut<'_, ()> where - P: AsMutPtr + P: AsMutPtr, { self.ptr.as_rmut() } /// Calls the `f` callback with an `MovePtr` pointing to the erased object. #[inline] - pub fn sabi_with_value(self, f:F)->R - where - P: OwnedPointer, - F: FnOnce(MovePtr<'_,()>)->R, + pub fn sabi_with_value(self, f: F) -> R + where + P: OwnedPointer, + F: FnOnce(MovePtr<'_, ()>) -> R, { OwnedPointer::with_move_ptr(self.sabi_into_erased_ptr(), f) } @@ -874,66 +844,61 @@ where impl Drop for RObject<'_, P, I, V> where - P:GetPointerKind, + P: GetPointerKind, { - fn drop(&mut self){ + fn drop(&mut self) { // This condition is necessary because if the RObject was reborrowed, // the destructor function would take a different pointer type. - if

::KIND==PointerKind::SmartPointer { - let destructor=self.sabi_robject_vtable()._sabi_drop(); - unsafe{ + if

::KIND == PointerKind::SmartPointer { + let destructor = self.sabi_robject_vtable()._sabi_drop(); + unsafe { destructor(RMut::

::new(&mut self.ptr)); } } } } - - - - ////////////////////////////////////////////////////////////////// /// Error for `RObject<_>` being downcasted into the wrong type /// with one of the `*downcast*` methods. #[derive(Copy, Clone)] pub struct UneraseError { - robject:T, - expected_typeid:MaybeCmp, - actual_typeid:UTypeId, + robject: T, + expected_typeid: MaybeCmp, + actual_typeid: UTypeId, } - -impl UneraseError{ - fn map(self, f:F)->UneraseError - where F:FnOnce(T)->U +impl UneraseError { + fn map(self, f: F) -> UneraseError + where + F: FnOnce(T) -> U, { - UneraseError{ - robject :f(self.robject), - expected_typeid:self.expected_typeid, - actual_typeid :self.actual_typeid, + UneraseError { + robject: f(self.robject), + expected_typeid: self.expected_typeid, + actual_typeid: self.actual_typeid, } } /// Extracts the RObject, to handle the failure to unerase it. #[must_use] - pub fn into_inner(self)->T{ + pub fn into_inner(self) -> T { self.robject } } - -impl fmt::Debug for UneraseError{ +impl fmt::Debug for UneraseError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("UneraseError") - .field("dyn_trait",&"") - .field("expected_typeid",&self.expected_typeid) - .field("actual_typeid",&self.actual_typeid) + .field("dyn_trait", &"") + .field("expected_typeid", &self.expected_typeid) + .field("actual_typeid", &self.actual_typeid) .finish() } } -impl fmt::Display for UneraseError{ +impl fmt::Display for UneraseError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(self, f) } diff --git a/abi_stable/src/sabi_trait/test_supertraits.rs b/abi_stable/src/sabi_trait/test_supertraits.rs index 8a614b2e..88b501ab 100644 --- a/abi_stable/src/sabi_trait/test_supertraits.rs +++ b/abi_stable/src/sabi_trait/test_supertraits.rs @@ -1,221 +1,218 @@ // This pub module only tests that the code inside compiles -#![allow(dead_code)] +#![allow(dead_code)] use std::{ - cmp::{Eq,PartialEq,Ord,PartialOrd}, + cmp::{Eq, Ord, PartialEq, PartialOrd}, error::Error as ErrorTrait, - fmt::{self,Display,Debug,Write as FmtWriteTrait}, + fmt::{self, Debug, Display, Write as FmtWriteTrait}, io::{ - self, + self, BufRead as IoBufReadTrait, Read as IoReadTrait, Seek as IoSeekTrait, Write as IoWriteTrait, - Read as IoReadTrait, - BufRead as IoBufReadTrait, - Seek as IoSeekTrait, }, }; - - use crate::{ sabi_trait, - type_level::downcasting::{TD_Opaque,TD_CanDowncast}, + type_level::downcasting::{TD_CanDowncast, TD_Opaque}, }; - -pub mod no_supertraits{ +pub mod no_supertraits { use super::*; #[sabi_trait] - pub trait Trait{ - fn method(&self){} + pub trait Trait { + fn method(&self) {} } pub struct Struct; - impl Trait for Struct{} + impl Trait for Struct {} - fn test_constructible(){ - let object=Trait_TO::from_value(Struct,TD_CanDowncast); + fn test_constructible() { + let object = Trait_TO::from_value(Struct, TD_CanDowncast); object.method(); } } -pub mod static_supertrait{ +pub mod static_supertrait { use super::*; #[sabi_trait] - pub trait Trait:'static { - fn method(&self){} + pub trait Trait: 'static { + fn method(&self) {} } use self::Trait_trait::Trait_Bounds; pub struct Struct<'a>(&'a str); - impl Trait for Struct<'_>{} + impl Trait for Struct<'_> {} - fn test_constructible(){ - let object=Trait_TO::from_value(Struct(""),TD_CanDowncast); + fn test_constructible() { + let object = Trait_TO::from_value(Struct(""), TD_CanDowncast); object.method(); } // Testing that Trait_Bounds has 'static as a supertrait, - trait Dummy{ + trait Dummy { fn dummy() - where T:Trait_Bounds; + where + T: Trait_Bounds; } - impl Dummy for (){ + impl Dummy for () { fn dummy() - where T:Trait_Bounds+'static - {} + where + T: Trait_Bounds + 'static, + { + } } - // Testing that Trait does not have 'static as a supertrait. - fn assert_trait_inner(_:T) - where T:Trait - {} - fn assert_trait(){ - let mut a=String::new(); + fn assert_trait_inner(_: T) + where + T: Trait, + { + } + fn assert_trait() { + let mut a = String::new(); a.push_str("w"); assert_trait_inner(Struct(&a)); } } -pub mod nonstatic_supertrait{ +pub mod nonstatic_supertrait { use super::*; #[sabi_trait] - pub trait Trait<'a>:'a { - fn method(&self){} + pub trait Trait<'a>: 'a { + fn method(&self) {} } use self::Trait_trait::Trait_Bounds; pub struct Struct<'a>(&'a str); - impl<'a,'b> Trait<'a> for Struct<'b>{} - impl<'a,T> Trait<'a> for Option{} + impl<'a, 'b> Trait<'a> for Struct<'b> {} + impl<'a, T> Trait<'a> for Option {} - fn test_constructible(){ - let object=Trait_TO::from_value(Struct(""),TD_CanDowncast); + fn test_constructible() { + let object = Trait_TO::from_value(Struct(""), TD_CanDowncast); object.method(); } // Testing that Trait_Bounds has 'a as a supertrait, - trait Dummy{ - fn dummy<'a,T>() - where T:Trait_Bounds<'a>; - } - impl Dummy for (){ - fn dummy<'a,T>() - where T:Trait_Bounds<'a>+'a - {} + trait Dummy { + fn dummy<'a, T>() + where + T: Trait_Bounds<'a>; + } + impl Dummy for () { + fn dummy<'a, T>() + where + T: Trait_Bounds<'a> + 'a, + { + } } - - struct MakeBorrowedCTO<'a,'b,T>(&'b (),&'a (),T); + struct MakeBorrowedCTO<'a, 'b, T>(&'b (), &'a (), T); - impl<'a,'b,T> MakeBorrowedCTO<'a,'b,T> + impl<'a, 'b, T> MakeBorrowedCTO<'a, 'b, T> where - T:'a, - 'a:'b, + T: 'a, + 'a: 'b, { - pub const NONE:Option<&'a T>=None; - - pub const CONST:Trait_CTO<'a,'a,'b>= - Trait_CTO::from_const( - &Self::NONE, - TD_Opaque, - Trait_MV::VTABLE, - ); - pub fn get_const(_:&'a T)->Trait_CTO<'a,'a,'b>{ + pub const NONE: Option<&'a T> = None; + + pub const CONST: Trait_CTO<'a, 'a, 'b> = + Trait_CTO::from_const(&Self::NONE, TD_Opaque, Trait_MV::VTABLE); + pub fn get_const(_: &'a T) -> Trait_CTO<'a, 'a, 'b> { Self::CONST } } - // Testing that Trait does not have 'a as a supertrait. - fn assert_trait_inner<'a,T>(_:T) - where T:Trait<'a> - {} - fn assert_trait(){ - let mut a=String::new(); + fn assert_trait_inner<'a, T>(_: T) + where + T: Trait<'a>, + { + } + fn assert_trait() { + let mut a = String::new(); a.push_str("w"); assert_trait_inner(Struct(&a)); { - let a=0usize; + let a = 0usize; MakeBorrowedCTO::get_const(&a).method(); } { - let a=String::new(); + let a = String::new(); MakeBorrowedCTO::get_const(&a).method(); } } } -pub mod only_clone{ +pub mod only_clone { use super::*; #[sabi_trait] - pub trait Trait:Clone{ - fn method(&self){} + pub trait Trait: Clone { + fn method(&self) {} } #[derive(Clone)] pub struct Struct; - impl Trait for Struct{} + impl Trait for Struct {} - fn test_constructible(){ - let object=Trait_TO::from_value(Struct,TD_CanDowncast); + fn test_constructible() { + let object = Trait_TO::from_value(Struct, TD_CanDowncast); object.method(); - let _=object.clone(); + let _ = object.clone(); } } -pub mod only_display{ +pub mod only_display { use super::*; #[sabi_trait] #[sabi(use_dyntrait)] - pub trait Trait:Display{ - fn method(&self){} + pub trait Trait: Display { + fn method(&self) {} } pub struct Struct; - impl Display for Struct{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Display::fmt("What!?",f) + impl Display for Struct { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Display::fmt("What!?", f) } } - impl Trait for Struct{} + impl Trait for Struct {} - fn test_constructible(){ - let object=Trait_TO::from_value(Struct,TD_CanDowncast); + fn test_constructible() { + let object = Trait_TO::from_value(Struct, TD_CanDowncast); object.method(); - format!("{}",object); + format!("{}", object); } } -pub mod only_debug{ +pub mod only_debug { use super::*; #[sabi_trait] - pub trait Trait:Debug{ - fn method(&self){} + pub trait Trait: Debug { + fn method(&self) {} } #[derive(Debug)] pub struct Struct; - impl Trait for Struct{} + impl Trait for Struct {} - fn test_constructible(){ - let object=Trait_TO::from_value(Struct,TD_CanDowncast); + fn test_constructible() { + let object = Trait_TO::from_value(Struct, TD_CanDowncast); object.method(); - format!("{:?}",object); + format!("{:?}", object); } } @@ -287,650 +284,691 @@ pub mod only_debug{ // } // } -pub mod only_partial_eq{ +pub mod only_partial_eq { use super::*; #[sabi_trait] #[sabi(use_dyntrait)] // #[sabi(debug_print_trait)] - pub trait Trait:PartialEq{ - fn method(&self){} + pub trait Trait: PartialEq { + fn method(&self) {} } #[derive(PartialEq)] pub struct Struct; - impl Trait for Struct{} + impl Trait for Struct {} - fn assert_bound(_:&T) + fn assert_bound(_: &T) where - T:Trait+PartialEq - {} + T: Trait + PartialEq, + { + } - fn test_constructible(){ - let object=Trait_TO::from_value(Struct,TD_CanDowncast); + fn test_constructible() { + let object = Trait_TO::from_value(Struct, TD_CanDowncast); object.method(); assert_bound(&object); } } -pub mod only_eq{ +pub mod only_eq { use super::*; #[sabi_trait] #[sabi(use_dyntrait)] - pub trait Trait:Eq{ - fn method(&self){} + pub trait Trait: Eq { + fn method(&self) {} } - #[derive(Eq,PartialEq)] + #[derive(Eq, PartialEq)] pub struct Struct; - impl Trait for Struct{} + impl Trait for Struct {} - fn assert_bound(_:&T) + fn assert_bound(_: &T) where - T:Trait+Eq - {} + T: Trait + Eq, + { + } - fn test_constructible(){ - let object=Trait_TO::from_value(Struct,TD_CanDowncast); + fn test_constructible() { + let object = Trait_TO::from_value(Struct, TD_CanDowncast); object.method(); assert_bound(&object); } } -pub mod only_partial_ord{ +pub mod only_partial_ord { use super::*; #[sabi_trait] #[sabi(use_dyntrait)] - pub trait Trait:PartialOrd{ - fn method(&self){} + pub trait Trait: PartialOrd { + fn method(&self) {} } - #[derive(PartialEq,PartialOrd)] + #[derive(PartialEq, PartialOrd)] pub struct Struct; - impl Trait for Struct{} + impl Trait for Struct {} - fn assert_bound(_:&T) + fn assert_bound(_: &T) where - T:Trait+PartialOrd - {} + T: Trait + PartialOrd, + { + } - fn test_constructible(){ - let object=Trait_TO::from_value(Struct,TD_CanDowncast); + fn test_constructible() { + let object = Trait_TO::from_value(Struct, TD_CanDowncast); object.method(); assert_bound(&object); } } -pub mod only_ord{ +pub mod only_ord { use super::*; #[sabi_trait] #[sabi(use_dyntrait)] - pub trait Trait:Ord{ - fn method(&self){} + pub trait Trait: Ord { + fn method(&self) {} } - #[derive(PartialEq,PartialOrd,Eq,Ord)] + #[derive(PartialEq, PartialOrd, Eq, Ord)] pub struct Struct; - impl Trait for Struct{} + impl Trait for Struct {} - fn assert_bound(_:&T) + fn assert_bound(_: &T) where - T:Trait+Ord - {} + T: Trait + Ord, + { + } - fn test_constructible(){ - let object=Trait_TO::from_value(Struct,TD_CanDowncast); + fn test_constructible() { + let object = Trait_TO::from_value(Struct, TD_CanDowncast); object.method(); assert_bound(&object); } } -pub mod only_hash{ +pub mod only_hash { use super::*; #[sabi_trait] #[sabi(use_dyntrait)] - pub trait Trait:Hash{ - fn method(&self){} + pub trait Trait: Hash { + fn method(&self) {} } #[derive(Hash)] pub struct Struct; - impl Trait for Struct{} + impl Trait for Struct {} - fn assert_bound(_:&T) + fn assert_bound(_: &T) where - T:Trait+std::hash::Hash - {} + T: Trait + std::hash::Hash, + { + } - fn test_constructible(){ - let object=Trait_TO::from_value(Struct,TD_CanDowncast); + fn test_constructible() { + let object = Trait_TO::from_value(Struct, TD_CanDowncast); object.method(); assert_bound(&object); } } -pub mod only_iterator_a{ +pub mod only_iterator_a { use super::*; #[sabi_trait] #[sabi(use_dyntrait)] - pub trait Trait<'a,T:'a>:Iterator{ - fn method(&self){} + pub trait Trait<'a, T: 'a>: Iterator { + fn method(&self) {} } - pub struct Struct<'a,T>(&'a T); + pub struct Struct<'a, T>(&'a T); - impl<'a,T> Trait<'a,T> for Struct<'a,T>{} + impl<'a, T> Trait<'a, T> for Struct<'a, T> {} - impl<'a,T> Iterator for Struct<'a,T>{ - type Item=&'a T; - fn next(&mut self)->Option<&'a T>{ + impl<'a, T> Iterator for Struct<'a, T> { + type Item = &'a T; + fn next(&mut self) -> Option<&'a T> { None } } - fn assert_bound<'a,T:'a>(_:&T) + fn assert_bound<'a, T: 'a>(_: &T) where - T:Trait<'a,i32>+Iterator - {} + T: Trait<'a, i32> + Iterator, + { + } - fn test_constructible(){ - let object=Trait_TO::from_value(Struct(&0),TD_CanDowncast); + fn test_constructible() { + let object = Trait_TO::from_value(Struct(&0), TD_CanDowncast); object.method(); assert_bound(&object); } } -pub mod only_iterator_b{ +pub mod only_iterator_b { use super::*; #[sabi_trait] #[sabi(use_dyntrait)] - pub trait Trait:Iterator{ - fn method(&self){} + pub trait Trait: Iterator { + fn method(&self) {} } pub struct Struct; - impl Trait for Struct{} + impl Trait for Struct {} - impl Iterator for Struct{ - type Item=&'static i32; - fn next(&mut self)->Option<&'static i32>{ + impl Iterator for Struct { + type Item = &'static i32; + fn next(&mut self) -> Option<&'static i32> { None } } - fn assert_bound(_:&T) + fn assert_bound(_: &T) where - T:Trait+Iterator - {} + T: Trait + Iterator, + { + } - fn test_constructible(){ - let object=Trait_TO::from_value(Struct,TD_CanDowncast); + fn test_constructible() { + let object = Trait_TO::from_value(Struct, TD_CanDowncast); object.method(); assert_bound(&object); } } -pub mod only_de_iterator{ +pub mod only_de_iterator { use super::*; #[sabi_trait] #[sabi(use_dyntrait)] - pub trait Trait:DoubleEndedIterator{ - fn method(&self){} + pub trait Trait: DoubleEndedIterator { + fn method(&self) {} } pub struct Struct; - impl Trait for Struct{} + impl Trait for Struct {} - impl Iterator for Struct{ - type Item=&'static i32; - fn next(&mut self)->Option<&'static i32>{ + impl Iterator for Struct { + type Item = &'static i32; + fn next(&mut self) -> Option<&'static i32> { None } } - impl DoubleEndedIterator for Struct{ - fn next_back(&mut self)->Option<&'static i32>{ + impl DoubleEndedIterator for Struct { + fn next_back(&mut self) -> Option<&'static i32> { None } } - fn assert_bound(_:&T) + fn assert_bound(_: &T) where - T:Trait+DoubleEndedIterator - {} + T: Trait + DoubleEndedIterator, + { + } - fn test_constructible(){ - let object=Trait_TO::from_value(Struct,TD_CanDowncast); + fn test_constructible() { + let object = Trait_TO::from_value(Struct, TD_CanDowncast); object.method(); assert_bound(&object); } } - -pub mod only_error{ +pub mod only_error { use super::*; #[sabi_trait] #[sabi(use_dyntrait)] - pub trait Trait:Error{ - fn method(&self){} + pub trait Trait: Error { + fn method(&self) {} } #[derive(Debug)] pub struct Struct; - impl Display for Struct{ - fn fmt(&self,_:&mut fmt::Formatter<'_>)->fmt::Result{ + impl Display for Struct { + fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result { Ok(()) } } - impl ErrorTrait for Struct{} + impl ErrorTrait for Struct {} - impl Trait for Struct{} + impl Trait for Struct {} - fn assert_bound(_:&T) + fn assert_bound(_: &T) where - T:Trait+ErrorTrait - {} + T: Trait + ErrorTrait, + { + } - fn test_constructible(){ - let object=Trait_TO::from_value(Struct,TD_CanDowncast); + fn test_constructible() { + let object = Trait_TO::from_value(Struct, TD_CanDowncast); object.method(); assert_bound(&object); } } -pub mod only_fmt_write{ +pub mod only_fmt_write { use super::*; #[sabi_trait] #[sabi(use_dyntrait)] - pub trait Trait:FmtWrite{ - fn method(&self){} + pub trait Trait: FmtWrite { + fn method(&self) {} } pub struct Struct; - impl FmtWriteTrait for Struct{ - fn write_str(&mut self, _: &str) -> Result<(), fmt::Error>{ + impl FmtWriteTrait for Struct { + fn write_str(&mut self, _: &str) -> Result<(), fmt::Error> { Ok(()) } } - impl Trait for Struct{} + impl Trait for Struct {} - fn assert_bound(_:&T) + fn assert_bound(_: &T) where - T:Trait+FmtWriteTrait - {} + T: Trait + FmtWriteTrait, + { + } - fn test_constructible(){ - let object=Trait_TO::from_value(Struct,TD_CanDowncast); + fn test_constructible() { + let object = Trait_TO::from_value(Struct, TD_CanDowncast); object.method(); assert_bound(&object); } } -pub mod only_io_write{ +pub mod only_io_write { use super::*; #[sabi_trait] #[sabi(use_dyntrait)] - pub trait Trait:IoWrite{ - fn method(&self){} + pub trait Trait: IoWrite { + fn method(&self) {} } pub struct Struct; - impl IoWriteTrait for Struct{ - fn write(&mut self, _buf: &[u8]) -> io::Result{ + impl IoWriteTrait for Struct { + fn write(&mut self, _buf: &[u8]) -> io::Result { Ok(0) } - fn flush(&mut self) -> io::Result<()>{ + fn flush(&mut self) -> io::Result<()> { Ok(()) } } - impl Trait for Struct{} + impl Trait for Struct {} - fn assert_bound(_:&T) + fn assert_bound(_: &T) where - T:Trait+IoWriteTrait - {} + T: Trait + IoWriteTrait, + { + } - fn test_constructible(){ - let object=Trait_TO::from_value(Struct,TD_CanDowncast); + fn test_constructible() { + let object = Trait_TO::from_value(Struct, TD_CanDowncast); object.method(); assert_bound(&object); } } -pub mod only_io_read{ +pub mod only_io_read { use super::*; #[sabi_trait] #[sabi(use_dyntrait)] - pub trait Trait:IoRead{ - fn method(&self){} + pub trait Trait: IoRead { + fn method(&self) {} } pub struct Struct; - impl IoReadTrait for Struct{ - fn read(&mut self, _buf: &mut [u8]) -> io::Result{ + impl IoReadTrait for Struct { + fn read(&mut self, _buf: &mut [u8]) -> io::Result { Ok(0) } } - impl Trait for Struct{} + impl Trait for Struct {} - fn assert_bound(_:&T) + fn assert_bound(_: &T) where - T:Trait+IoReadTrait - {} + T: Trait + IoReadTrait, + { + } - fn test_constructible(){ - let object=Trait_TO::from_value(Struct,TD_CanDowncast); + fn test_constructible() { + let object = Trait_TO::from_value(Struct, TD_CanDowncast); object.method(); assert_bound(&object); } } -pub mod only_io_bufread{ +pub mod only_io_bufread { use super::*; #[sabi_trait] #[sabi(use_dyntrait)] - pub trait Trait:IoBufRead{ - fn method(&self){} + pub trait Trait: IoBufRead { + fn method(&self) {} } pub struct Struct; - impl IoReadTrait for Struct{ - fn read(&mut self, _buf: &mut [u8]) -> io::Result{ + impl IoReadTrait for Struct { + fn read(&mut self, _buf: &mut [u8]) -> io::Result { Ok(0) } } - impl IoBufReadTrait for Struct{ - fn fill_buf(&mut self) -> io::Result<&[u8]>{ + impl IoBufReadTrait for Struct { + fn fill_buf(&mut self) -> io::Result<&[u8]> { Ok(&[]) } - fn consume(&mut self, _amt: usize){} - + fn consume(&mut self, _amt: usize) {} } - impl Trait for Struct{} + impl Trait for Struct {} - fn assert_bound(_:&T) + fn assert_bound(_: &T) where - T:Trait+IoBufReadTrait - {} + T: Trait + IoBufReadTrait, + { + } - fn test_constructible(){ - let object=Trait_TO::from_value(Struct,TD_CanDowncast); + fn test_constructible() { + let object = Trait_TO::from_value(Struct, TD_CanDowncast); object.method(); assert_bound(&object); } } -pub mod only_io_seek{ +pub mod only_io_seek { use super::*; #[sabi_trait] #[sabi(use_dyntrait)] - pub trait Trait:IoSeek{ - fn method(&self){} + pub trait Trait: IoSeek { + fn method(&self) {} } pub struct Struct; - impl IoSeekTrait for Struct{ - fn seek(&mut self, _: io::SeekFrom) -> io::Result{ + impl IoSeekTrait for Struct { + fn seek(&mut self, _: io::SeekFrom) -> io::Result { Ok(0) } } - impl Trait for Struct{} + impl Trait for Struct {} - fn assert_bound(_:&T) + fn assert_bound(_: &T) where - T:Trait+IoSeekTrait - {} + T: Trait + IoSeekTrait, + { + } - fn test_constructible(){ - let object=Trait_TO::from_value(Struct,TD_CanDowncast); + fn test_constructible() { + let object = Trait_TO::from_value(Struct, TD_CanDowncast); object.method(); assert_bound(&object); } } - //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// - -pub mod every_trait{ +pub mod every_trait { use super::*; #[sabi_trait] #[sabi(use_dyntrait)] pub trait Trait: - Clone+ - Iterator+DoubleEndedIterator+ - Display+Debug+Error+ - PartialEq+Eq+PartialOrd+Ord+ - Hash+ - FmtWrite+IoWrite+IoRead+IoBufRead+IoSeek + Clone + + Iterator + + DoubleEndedIterator + + Display + + Debug + + Error + + PartialEq + + Eq + + PartialOrd + + Ord + + Hash + + FmtWrite + + IoWrite + + IoRead + + IoBufRead + + IoSeek { - fn method(&self){} + fn method(&self) {} } - #[derive(Debug,Clone,PartialEq,PartialOrd,Eq,Ord,Hash)] + #[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)] pub struct Struct; - impl Display for Struct{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Display::fmt("What!?",f) + impl Display for Struct { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Display::fmt("What!?", f) } } - impl Iterator for Struct{ - type Item=&'static (); - fn next(&mut self)->Option<&'static ()>{ + impl Iterator for Struct { + type Item = &'static (); + fn next(&mut self) -> Option<&'static ()> { None } } - impl DoubleEndedIterator for Struct{ - fn next_back(&mut self)->Option<&'static ()>{ + impl DoubleEndedIterator for Struct { + fn next_back(&mut self) -> Option<&'static ()> { None } } - impl ErrorTrait for Struct{} + impl ErrorTrait for Struct {} - impl FmtWriteTrait for Struct{ - fn write_str(&mut self, _: &str) -> Result<(), fmt::Error>{ + impl FmtWriteTrait for Struct { + fn write_str(&mut self, _: &str) -> Result<(), fmt::Error> { Ok(()) } } - impl IoWriteTrait for Struct{ - fn write(&mut self, _buf: &[u8]) -> io::Result{ + impl IoWriteTrait for Struct { + fn write(&mut self, _buf: &[u8]) -> io::Result { Ok(0) } - fn flush(&mut self) -> io::Result<()>{ + fn flush(&mut self) -> io::Result<()> { Ok(()) } } - impl IoReadTrait for Struct{ - fn read(&mut self, _buf: &mut [u8]) -> io::Result{ + impl IoReadTrait for Struct { + fn read(&mut self, _buf: &mut [u8]) -> io::Result { Ok(0) } } - impl IoBufReadTrait for Struct{ - fn fill_buf(&mut self) -> io::Result<&[u8]>{ + impl IoBufReadTrait for Struct { + fn fill_buf(&mut self) -> io::Result<&[u8]> { Ok(&[]) } - fn consume(&mut self, _amt: usize){} + fn consume(&mut self, _amt: usize) {} } - impl IoSeekTrait for Struct{ - fn seek(&mut self, _: io::SeekFrom) -> io::Result{ + impl IoSeekTrait for Struct { + fn seek(&mut self, _: io::SeekFrom) -> io::Result { Ok(0) } } - impl Trait for Struct{} + impl Trait for Struct {} - fn assert_bound(_:&T) + fn assert_bound(_: &T) where - T:Trait+ - Clone+ - Iterator+DoubleEndedIterator+ - Display+Debug+ErrorTrait+ - PartialEq+Eq+PartialOrd+Ord+ - std::hash::Hash+ - FmtWriteTrait+IoWriteTrait+IoReadTrait+IoBufReadTrait+IoSeekTrait - {} - - fn test_constructible(){ - let object=Trait_TO::from_value(Struct,TD_CanDowncast); + T: Trait + + Clone + + Iterator + + DoubleEndedIterator + + Display + + Debug + + ErrorTrait + + PartialEq + + Eq + + PartialOrd + + Ord + + std::hash::Hash + + FmtWriteTrait + + IoWriteTrait + + IoReadTrait + + IoBufReadTrait + + IoSeekTrait, + { + } + + fn test_constructible() { + let object = Trait_TO::from_value(Struct, TD_CanDowncast); object.method(); assert_bound(&object); } - } - - //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// - - -pub mod every_trait_static{ +pub mod every_trait_static { use super::*; #[sabi_trait] #[sabi(use_dyntrait)] pub trait Trait: - 'static+ - Clone+ - Iterator+DoubleEndedIterator+ - Display+Debug+Error+ - PartialEq+Eq+PartialOrd+Ord+ - Hash+ - FmtWrite+IoWrite+IoRead+IoBufRead+IoSeek + 'static + + Clone + + Iterator + + DoubleEndedIterator + + Display + + Debug + + Error + + PartialEq + + Eq + + PartialOrd + + Ord + + Hash + + FmtWrite + + IoWrite + + IoRead + + IoBufRead + + IoSeek { - fn method(&self){} + fn method(&self) {} } - #[derive(Debug,Clone,PartialEq,PartialOrd,Eq,Ord,Hash)] + #[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)] pub struct Struct; - impl Display for Struct{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Display::fmt("What!?",f) + impl Display for Struct { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Display::fmt("What!?", f) } } - impl Iterator for Struct{ - type Item=&'static (); - fn next(&mut self)->Option<&'static ()>{ + impl Iterator for Struct { + type Item = &'static (); + fn next(&mut self) -> Option<&'static ()> { None } } - impl DoubleEndedIterator for Struct{ - fn next_back(&mut self)->Option<&'static ()>{ + impl DoubleEndedIterator for Struct { + fn next_back(&mut self) -> Option<&'static ()> { None } } - impl ErrorTrait for Struct{} + impl ErrorTrait for Struct {} - impl FmtWriteTrait for Struct{ - fn write_str(&mut self, _: &str) -> Result<(), fmt::Error>{ + impl FmtWriteTrait for Struct { + fn write_str(&mut self, _: &str) -> Result<(), fmt::Error> { Ok(()) } } - impl IoWriteTrait for Struct{ - fn write(&mut self, _buf: &[u8]) -> io::Result{ + impl IoWriteTrait for Struct { + fn write(&mut self, _buf: &[u8]) -> io::Result { Ok(0) } - fn flush(&mut self) -> io::Result<()>{ + fn flush(&mut self) -> io::Result<()> { Ok(()) } } - impl IoReadTrait for Struct{ - fn read(&mut self, _buf: &mut [u8]) -> io::Result{ + impl IoReadTrait for Struct { + fn read(&mut self, _buf: &mut [u8]) -> io::Result { Ok(0) } } - impl IoBufReadTrait for Struct{ - fn fill_buf(&mut self) -> io::Result<&[u8]>{ + impl IoBufReadTrait for Struct { + fn fill_buf(&mut self) -> io::Result<&[u8]> { Ok(&[]) } - fn consume(&mut self, _amt: usize){} + fn consume(&mut self, _amt: usize) {} } - impl IoSeekTrait for Struct{ - fn seek(&mut self, _: io::SeekFrom) -> io::Result{ + impl IoSeekTrait for Struct { + fn seek(&mut self, _: io::SeekFrom) -> io::Result { Ok(0) } } - impl Trait for Struct{} + impl Trait for Struct {} - fn assert_bound(_:&T) + fn assert_bound(_: &T) where - T:Trait+ - Clone+ - Iterator+DoubleEndedIterator+ - Display+Debug+ErrorTrait+ - PartialEq+Eq+PartialOrd+Ord+ - std::hash::Hash+ - FmtWriteTrait+IoWriteTrait+IoReadTrait+IoBufReadTrait+IoSeekTrait - {} - - fn test_constructible(){ - let object=Trait_TO::from_value(Struct,TD_CanDowncast); + T: Trait + + Clone + + Iterator + + DoubleEndedIterator + + Display + + Debug + + ErrorTrait + + PartialEq + + Eq + + PartialOrd + + Ord + + std::hash::Hash + + FmtWriteTrait + + IoWriteTrait + + IoReadTrait + + IoBufReadTrait + + IoSeekTrait, + { + } + + fn test_constructible() { + let object = Trait_TO::from_value(Struct, TD_CanDowncast); object.method(); assert_bound(&object); } - } - - //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// - - - -pub mod every_trait_nonstatic{ +pub mod every_trait_nonstatic { use super::*; #[sabi_trait] @@ -946,102 +984,97 @@ pub mod every_trait_nonstatic{ { fn method(&self){} } - #[derive(Debug,Clone,PartialEq,PartialOrd,Eq,Ord,Hash)] + #[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)] pub struct Struct<'a>(&'a str); - impl Display for Struct<'_>{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Display::fmt("What!?",f) + impl Display for Struct<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Display::fmt("What!?", f) } } - impl Iterator for Struct<'_>{ - type Item=&'static (); - fn next(&mut self)->Option<&'static ()>{ + impl Iterator for Struct<'_> { + type Item = &'static (); + fn next(&mut self) -> Option<&'static ()> { None } } - impl DoubleEndedIterator for Struct<'_>{ - fn next_back(&mut self)->Option<&'static ()>{ + impl DoubleEndedIterator for Struct<'_> { + fn next_back(&mut self) -> Option<&'static ()> { None } } - impl ErrorTrait for Struct<'_>{} + impl ErrorTrait for Struct<'_> {} - impl FmtWriteTrait for Struct<'_>{ - fn write_str(&mut self, _: &str) -> Result<(), fmt::Error>{ + impl FmtWriteTrait for Struct<'_> { + fn write_str(&mut self, _: &str) -> Result<(), fmt::Error> { Ok(()) } } - impl IoWriteTrait for Struct<'_>{ - fn write(&mut self, _buf: &[u8]) -> io::Result{ + impl IoWriteTrait for Struct<'_> { + fn write(&mut self, _buf: &[u8]) -> io::Result { Ok(0) } - fn flush(&mut self) -> io::Result<()>{ + fn flush(&mut self) -> io::Result<()> { Ok(()) } } - impl IoReadTrait for Struct<'_>{ - fn read(&mut self, _buf: &mut [u8]) -> io::Result{ + impl IoReadTrait for Struct<'_> { + fn read(&mut self, _buf: &mut [u8]) -> io::Result { Ok(0) } } - impl IoBufReadTrait for Struct<'_>{ - fn fill_buf(&mut self) -> io::Result<&[u8]>{ + impl IoBufReadTrait for Struct<'_> { + fn fill_buf(&mut self) -> io::Result<&[u8]> { Ok(&[]) } - fn consume(&mut self, _amt: usize){} + fn consume(&mut self, _amt: usize) {} } - impl IoSeekTrait for Struct<'_>{ - fn seek(&mut self, _: io::SeekFrom) -> io::Result{ + impl IoSeekTrait for Struct<'_> { + fn seek(&mut self, _: io::SeekFrom) -> io::Result { Ok(0) } } - impl<'a> Trait<'a> for Struct<'a>{} + impl<'a> Trait<'a> for Struct<'a> {} - fn assert_bound<'a,T>(_:&T) + fn assert_bound<'a, T>(_: &T) where - T:Trait<'a> - {} + T: Trait<'a>, + { + } - fn test_constructible(){ + fn test_constructible() { use crate::std_types::RBox; - let string=String::new(); - let value=Struct(&string); - let object=Trait_TO::from_ptr(RBox::new(value),TD_Opaque); + let string = String::new(); + let value = Struct(&string); + let object = Trait_TO::from_ptr(RBox::new(value), TD_Opaque); object.method(); assert_bound(&object); { - let value=Struct(&string); + let value = Struct(&string); constructs_const_a(&value); - let value=Struct(""); + let value = Struct(""); constructs_const_a(&value); } - } - const CONST_A:Trait_CTO<'static,'static,'static>= - Trait_CTO::from_const( - &Struct(""), - TD_Opaque, - Trait_MV::VTABLE, - ); + const CONST_A: Trait_CTO<'static, 'static, 'static> = + Trait_CTO::from_const(&Struct(""), TD_Opaque, Trait_MV::VTABLE); - fn constructs_const_a<'a,'b,'borr,T>(ref_:&'b T)->Trait_CTO<'a,'borr,'b> + fn constructs_const_a<'a, 'b, 'borr, T>(ref_: &'b T) -> Trait_CTO<'a, 'borr, 'b> where - T:'borr+'a+Trait<'a> + T: 'borr + 'a + Trait<'a>, { - Trait_CTO::from_const(ref_,TD_Opaque,Trait_MV::VTABLE) + Trait_CTO::from_const(ref_, TD_Opaque, Trait_MV::VTABLE) } - -} \ No newline at end of file +} diff --git a/abi_stable/src/sabi_trait/tests.rs b/abi_stable/src/sabi_trait/tests.rs index 182eb496..e385b8b7 100644 --- a/abi_stable/src/sabi_trait/tests.rs +++ b/abi_stable/src/sabi_trait/tests.rs @@ -1,171 +1,161 @@ -use std::{ - mem, -}; +use std::mem; use crate::{ - *, - std_types::{RBox, RStr}, sabi_trait::prelude::*, + std_types::{RBox, RStr}, type_level::bools::*, + *, }; -use abi_stable_shared::{file_span,test_utils::{must_panic}}; - +use abi_stable_shared::{file_span, test_utils::must_panic}; -mod empty{ +mod empty { use super::*; #[sabi_trait] - pub trait Trait{} + pub trait Trait {} impl Trait for () {} impl Trait for True {} } -mod method_no_default{ +mod method_no_default { use super::*; #[sabi_trait] - pub trait Trait{ - fn apply(&self,l:u32,r:u32)->u32; + pub trait Trait { + fn apply(&self, l: u32, r: u32) -> u32; } - + impl Trait for () { - fn apply(&self,l:u32,r:u32)->u32{ - (l+r)*2 + fn apply(&self, l: u32, r: u32) -> u32 { + (l + r) * 2 } } } -mod method_disabled_one_default{ +mod method_disabled_one_default { use super::*; - + #[sabi_trait] - pub trait Trait{ - fn first_method(&self)->u32{ + pub trait Trait { + fn first_method(&self) -> u32 { 0xf000 } #[sabi(no_default_fallback)] - fn apply(&self,l:u32,r:u32)->u32{ - (l+r)*3 + fn apply(&self, l: u32, r: u32) -> u32 { + (l + r) * 3 } - fn last_method(&self)->u32{ + fn last_method(&self) -> u32 { 0xfAAA } } - + impl Trait for () { - fn apply(&self,l:u32,r:u32)->u32{ - (l+r)*4 + fn apply(&self, l: u32, r: u32) -> u32 { + (l + r) * 4 } } } -mod method_disabled_all_default{ +mod method_disabled_all_default { use super::*; - + #[sabi_trait] #[sabi(no_default_fallback)] - pub trait Trait{ - fn first_method(&self)->u32{ + pub trait Trait { + fn first_method(&self) -> u32 { 0xf000 } - fn last_method(&self)->u32{ + fn last_method(&self) -> u32 { 0xfAAA } } - + impl Trait for () {} } -mod method_default{ +mod method_default { use super::*; #[sabi_trait] - pub trait Trait{ - fn apply(&self,l:u32,r:u32)->u32{ - (l+r)*3 + pub trait Trait { + fn apply(&self, l: u32, r: u32) -> u32 { + (l + r) * 3 } } impl Trait for () {} impl Trait for True { - fn apply(&self,l:u32,r:u32)->u32{ - (l+r)*4 + fn apply(&self, l: u32, r: u32) -> u32 { + (l + r) * 4 } } } - #[test] -fn downcasting_tests(){ - - - unsafe{ +fn downcasting_tests() { + unsafe { use self::method_disabled_one_default::*; - let empty=empty::Trait_TO::from_value((),TD_Opaque); - let object=mem::transmute::<_,Trait_TO<'_,RBox<()>>>(empty); + let empty = empty::Trait_TO::from_value((), TD_Opaque); + let object = mem::transmute::<_, Trait_TO<'_, RBox<()>>>(empty); assert_eq!(object.first_method(), 0xf000); assert_eq!(object.last_method(), 0xfAAA); - must_panic(file_span!(),|| object.apply(2,5) ).unwrap(); + must_panic(file_span!(), || object.apply(2, 5)).unwrap(); } - unsafe{ + unsafe { use self::method_disabled_all_default::*; - let empty=empty::Trait_TO::from_value((),TD_Opaque); - let object=mem::transmute::<_,Trait_TO<'_,RBox<()>>>(empty); - must_panic(file_span!(),|| object.first_method() ).unwrap(); - must_panic(file_span!(),|| object.last_method() ).unwrap(); + let empty = empty::Trait_TO::from_value((), TD_Opaque); + let object = mem::transmute::<_, Trait_TO<'_, RBox<()>>>(empty); + must_panic(file_span!(), || object.first_method()).unwrap(); + must_panic(file_span!(), || object.last_method()).unwrap(); } - unsafe{ + unsafe { use self::method_no_default::*; - let empty=empty::Trait_TO::from_value((),TD_Opaque); - let object=mem::transmute::<_,Trait_TO<'_,RBox<()>>>(empty); - must_panic(file_span!(),|| object.apply(2,5) ).unwrap(); + let empty = empty::Trait_TO::from_value((), TD_Opaque); + let object = mem::transmute::<_, Trait_TO<'_, RBox<()>>>(empty); + must_panic(file_span!(), || object.apply(2, 5)).unwrap(); } - unsafe{ + unsafe { use self::method_default::*; - let empty=empty::Trait_TO::from_value((),TD_Opaque); - let object=mem::transmute::<_,Trait_TO<'_,RBox<()>>>(empty); - assert_eq!(object.apply(2,5),21); + let empty = empty::Trait_TO::from_value((), TD_Opaque); + let object = mem::transmute::<_, Trait_TO<'_, RBox<()>>>(empty); + assert_eq!(object.apply(2, 5), 21); } - { - let no_default=method_no_default::Trait_TO::from_value((),TD_Opaque); + let no_default = method_no_default::Trait_TO::from_value((), TD_Opaque); { - assert_eq!(no_default.apply(2,5), 14); + assert_eq!(no_default.apply(2, 5), 14); } - unsafe{ + unsafe { use self::method_default::*; - let object=mem::transmute::<_,Trait_TO<'_,RBox<()>>>(no_default); - assert_eq!(object.apply(2,5), 14); + let object = mem::transmute::<_, Trait_TO<'_, RBox<()>>>(no_default); + assert_eq!(object.apply(2, 5), 14); } } { - let with_default=method_default::Trait_TO::from_value(True,TD_Opaque); + let with_default = method_default::Trait_TO::from_value(True, TD_Opaque); { - assert_eq!(with_default.apply(2,5), 28); + assert_eq!(with_default.apply(2, 5), 28); } - unsafe{ + unsafe { use self::method_no_default::*; - let object=mem::transmute::<_,Trait_TO<'_,RBox<()>>>(with_default); - assert_eq!(object.apply(2,5), 28); + let object = mem::transmute::<_, Trait_TO<'_, RBox<()>>>(with_default); + assert_eq!(object.apply(2, 5), 28); } } } - - - #[sabi_trait] -trait DefaultMethodPair{ - fn foo(&self,x:u32)->u32{ - self.bar(x+10) +trait DefaultMethodPair { + fn foo(&self, x: u32) -> u32 { + self.bar(x + 10) } - fn bar(&self,y:u32)->u32{ - self.baz(y+20) + fn bar(&self, y: u32) -> u32 { + self.baz(y + 20) } - fn baz(&self,z:u32)->u32{ - z+40 + fn baz(&self, z: u32) -> u32 { + z + 40 } } @@ -173,87 +163,75 @@ struct A; struct B; struct C; - -impl DefaultMethodPair for A{ - fn foo(&self,x:u32)->u32{ - x+100 +impl DefaultMethodPair for A { + fn foo(&self, x: u32) -> u32 { + x + 100 } } -impl DefaultMethodPair for B{ - fn bar(&self,y:u32)->u32{ - y+200 +impl DefaultMethodPair for B { + fn bar(&self, y: u32) -> u32 { + y + 200 } } -impl DefaultMethodPair for C{ - fn baz(&self,z:u32)->u32{ - z+300 +impl DefaultMethodPair for C { + fn baz(&self, z: u32) -> u32 { + z + 300 } } - #[test] -fn default_methods(){ - let a=DefaultMethodPair_TO::from_value(A,TD_Opaque); - let b=DefaultMethodPair_TO::from_value(B,TD_Opaque); - let c=DefaultMethodPair_TO::from_value(C,TD_Opaque); +fn default_methods() { + let a = DefaultMethodPair_TO::from_value(A, TD_Opaque); + let b = DefaultMethodPair_TO::from_value(B, TD_Opaque); + let c = DefaultMethodPair_TO::from_value(C, TD_Opaque); assert_eq!(a.foo(1), 101); assert_eq!(b.foo(1), 211); assert_eq!(c.foo(1), 331); } - - /*//////////////////////////////////////////////////////////////////////////////// Test that #[sabi(no_trait_impl)] disables the trait impl for the trait object. *///////////////////////////////////////////////////////////////////////////////// #[sabi_trait] #[sabi(no_trait_impl)] -trait NoTraitImplA{} - -impl

NoTraitImplA for NoTraitImplA_TO<'_,P> -where P:crate::pointer_trait::GetPointerKind, -{} - +trait NoTraitImplA {} +impl

NoTraitImplA for NoTraitImplA_TO<'_, P> where P: crate::pointer_trait::GetPointerKind {} #[sabi_trait] #[sabi(no_trait_impl)] -trait NoTraitImplB{} - -impl NoTraitImplB for This{} - +trait NoTraitImplB {} +impl NoTraitImplB for This {} /*//////////////////////////////////////////////////////////////////////////////// Test that prefix methods can have a default impl. *///////////////////////////////////////////////////////////////////////////////// - -mod defaulted_prefix_method{ +mod defaulted_prefix_method { use super::*; #[sabi_trait] - pub trait Trait{ + pub trait Trait { #[sabi(last_prefix_field)] - fn apply(&self)->u32 { + fn apply(&self) -> u32 { 3 } } - + impl Trait for () {} impl Trait for u32 { - fn apply(&self)->u32 { + fn apply(&self) -> u32 { *self + 5 } } - } #[test] -fn defaulted_prefix_method_works(){ +fn defaulted_prefix_method_works() { use defaulted_prefix_method::Trait_TO; { let obj = Trait_TO::from_value((), TD_Opaque); @@ -269,12 +247,10 @@ fn defaulted_prefix_method_works(){ } } - /*//////////////////////////////////////////////////////////////////////////////// Test all the kinds of borrows in return types. *///////////////////////////////////////////////////////////////////////////////// - #[sabi_trait] trait BorrowKinds { fn ref_borrow_a(&self) -> &bool { @@ -299,15 +275,14 @@ trait BorrowKinds { } } -impl BorrowKinds for u32{ +impl BorrowKinds for u32 { fn mut_borrow(&mut self) -> &mut u32 { self } } - #[test] -fn borrow_kinds(){ +fn borrow_kinds() { let mut obj = BorrowKinds_TO::from_value(3u32, TD_Opaque); assert_eq!(obj.ref_borrow_a(), &true); @@ -316,5 +291,4 @@ fn borrow_kinds(){ assert_eq!(obj.non_self_borrow().as_str(), "baz"); assert_eq!(*obj.mut_borrow(), 3); assert_eq!(obj.not_borrow(), 89); - } diff --git a/abi_stable/src/sabi_trait/vtable.rs b/abi_stable/src/sabi_trait/vtable.rs index 2185b85e..d4fda9ed 100644 --- a/abi_stable/src/sabi_trait/vtable.rs +++ b/abi_stable/src/sabi_trait/vtable.rs @@ -1,251 +1,238 @@ use super::*; use crate::{ - erased_types::{FormattingMode,InterfaceBound,VTableDT}, + erased_types::{FormattingMode, InterfaceBound, VTableDT}, marker_type::NonOwningPhantom, prefix_type::PrefixRef, + sabi_types::Constructor, + std_types::{RResult, RString, Tuple3, UTypeId}, type_level::{ - downcasting::{GetUTID}, - impl_enum::{Implemented,Unimplemented}, + downcasting::GetUTID, + impl_enum::{Implemented, Unimplemented}, trait_marker, }, - sabi_types::Constructor, - std_types::{UTypeId,RResult,RString,Tuple3}, }; ////////////////////////////////////////////////////////////////////////////// /// Gets an `RObjectVtable_Ref<_Self,ErasedPtr,TO>`(the vtable for RObject itself), /// which is stored as the first field of all generated trait object vtables. -pub unsafe trait GetRObjectVTable:Sized+InterfaceType{ - const ROBJECT_VTABLE:RObjectVtable_Ref<_Self,ErasedPtr,Self>; +pub unsafe trait GetRObjectVTable: + Sized + InterfaceType +{ + const ROBJECT_VTABLE: RObjectVtable_Ref<_Self, ErasedPtr, Self>; } - -unsafe impl - GetRObjectVTable for I +unsafe impl GetRObjectVTable for I where - I:AreTraitsImpld+InterfaceType, + I: AreTraitsImpld + InterfaceType, { - const ROBJECT_VTABLE:RObjectVtable_Ref<_Self,ErasedPtr,Self>={ - GetRObjectVTableHelper::::TMP_VTABLE - }; + const ROBJECT_VTABLE: RObjectVtable_Ref<_Self, ErasedPtr, Self> = + { GetRObjectVTableHelper::::TMP_VTABLE }; } - ////////////////////////////////////////////////////////////////////////////// /// The `VTableTO` passed to `#[sabi_trait]` /// generated trait objects that have `RObject` as their backend. #[allow(non_camel_case_types)] -pub type VTableTO_RO=VTableTO; +pub type VTableTO_RO = VTableTO; /// The `VTableTO` passed to `#[sabi_trait]` /// generated trait objects that have `DynTrait` as their backend. #[allow(non_camel_case_types)] -pub type VTableTO_DT<'borr,_Self,ErasedPtr,OrigPtr,I,Downcasting,V>= - VTableTO< - _Self, - OrigPtr, - Downcasting, - V, - VTableDT<'borr,_Self,ErasedPtr,OrigPtr,I,Downcasting> - >; - - +pub type VTableTO_DT<'borr, _Self, ErasedPtr, OrigPtr, I, Downcasting, V> = VTableTO< + _Self, + OrigPtr, + Downcasting, + V, + VTableDT<'borr, _Self, ErasedPtr, OrigPtr, I, Downcasting>, +>; /// This is used to safely pass the vtable to `#[sabi_trait]` generated trait objects, /// using `_CTO::from_const( &value, _MV::VTABLE )`. /// /// `` is whatever the name of the trait that one is constructing the trait object for. -pub struct VTableTO<_Self,OrigPtr,Downcasting,V,DT>{ - vtable:PrefixRef, - for_dyn_trait:DT, - _for:PhantomData>>, +pub struct VTableTO<_Self, OrigPtr, Downcasting, V, DT> { + vtable: PrefixRef, + for_dyn_trait: DT, + _for: PhantomData>>, } -impl<_Self,OrigPtr,Downcasting,V,DT> Copy for VTableTO<_Self,OrigPtr,Downcasting,V,DT> -where DT:Copy -{} +impl<_Self, OrigPtr, Downcasting, V, DT> Copy for VTableTO<_Self, OrigPtr, Downcasting, V, DT> where + DT: Copy +{ +} -impl<_Self,OrigPtr,Downcasting,V,DT> Clone for VTableTO<_Self,OrigPtr,Downcasting,V,DT> -where DT:Copy +impl<_Self, OrigPtr, Downcasting, V, DT> Clone for VTableTO<_Self, OrigPtr, Downcasting, V, DT> +where + DT: Copy, { - fn clone(&self)->Self{ + fn clone(&self) -> Self { *self } } +impl<_Self, OrigPtr, Downcasting, V> VTableTO<_Self, OrigPtr, Downcasting, V, ()> { + /** + Wraps an erased vtable. -impl<_Self,OrigPtr,Downcasting,V> VTableTO<_Self,OrigPtr,Downcasting,V,()>{ - -/** -Wraps an erased vtable. + # Safety -# Safety + These are the requirements for the caller: -These are the requirements for the caller: + - `OrigPtr` must be a pointer to the type that the vtable functions + take as the first parameter. -- `OrigPtr` must be a pointer to the type that the vtable functions - take as the first parameter. + - The vtable must not come from a reborrowed RObject + (created using RObject::reborrow or RObject::reborrow_mut). -- The vtable must not come from a reborrowed RObject - (created using RObject::reborrow or RObject::reborrow_mut). + - The vtable must be the `` of a struct declared with + `#[derive(StableAbi)]``#[sabi(kind(Prefix(prefix_ref="")))]`. -- The vtable must be the `` of a struct declared with - `#[derive(StableAbi)]``#[sabi(kind(Prefix(prefix_ref="")))]`. - -- The vtable must have `PrefixRef>` - as its first declared field -*/ - pub const unsafe fn for_robject(vtable:PrefixRef)->Self{ - Self{ + - The vtable must have `PrefixRef>` + as its first declared field + */ + pub const unsafe fn for_robject(vtable: PrefixRef) -> Self { + Self { vtable, - for_dyn_trait:(), - _for:PhantomData + for_dyn_trait: (), + _for: PhantomData, } } - - } - -impl<_Self,OrigPtr,Downcasting,V,DT> VTableTO<_Self,OrigPtr,Downcasting,V,DT>{ +impl<_Self, OrigPtr, Downcasting, V, DT> VTableTO<_Self, OrigPtr, Downcasting, V, DT> { /// Gets the vtable that RObject is constructed with. - pub const fn robject_vtable(&self)->PrefixRef{ + pub const fn robject_vtable(&self) -> PrefixRef { self.vtable } } -impl<'borr,_Self,ErasedPtr,OrigPtr,I,Downcasting,V> - VTableTO_DT<'borr,_Self,ErasedPtr,OrigPtr,I,Downcasting,V> +impl<'borr, _Self, ErasedPtr, OrigPtr, I, Downcasting, V> + VTableTO_DT<'borr, _Self, ErasedPtr, OrigPtr, I, Downcasting, V> { /// Gets the vtable for DynTrait. pub const fn dyntrait_vtable( - &self - )->VTableDT<'borr,_Self,ErasedPtr,OrigPtr,I,Downcasting>{ + &self, + ) -> VTableDT<'borr, _Self, ErasedPtr, OrigPtr, I, Downcasting> { self.for_dyn_trait } } -impl<'borr,_Self,ErasedPtr,OrigPtr,I,Downcasting,V> - VTableTO_DT<'borr,_Self,ErasedPtr,OrigPtr,I,Downcasting,V> +impl<'borr, _Self, ErasedPtr, OrigPtr, I, Downcasting, V> + VTableTO_DT<'borr, _Self, ErasedPtr, OrigPtr, I, Downcasting, V> { + /** + Wraps an erased vtable,alongside the vtable for DynTrait. -/** -Wraps an erased vtable,alongside the vtable for DynTrait. + # Safety -# Safety - -This has the same safety requirements as the 'for_robject' constructor -*/ + This has the same safety requirements as the 'for_robject' constructor + */ pub const unsafe fn for_dyntrait( - vtable:PrefixRef, - for_dyn_trait:VTableDT<'borr,_Self,ErasedPtr,OrigPtr,I,Downcasting>, - )->Self{ - Self{ + vtable: PrefixRef, + for_dyn_trait: VTableDT<'borr, _Self, ErasedPtr, OrigPtr, I, Downcasting>, + ) -> Self { + Self { vtable, for_dyn_trait, - _for:PhantomData + _for: PhantomData, } } - } - ////////////////////////////////////////////////////////////////////////////// - - #[doc(hidden)] -pub trait AreTraitsImpld:Sized { - const VTABLE_VAL:RObjectVtable<_Self,ErasedPtr,Self>; +pub trait AreTraitsImpld: Sized { + const VTABLE_VAL: RObjectVtable<_Self, ErasedPtr, Self>; } -impl AreTraitsImpld for I -where - I:InterfaceType, - I::Sync:RequiresSync<_Self,ErasedPtr,OrigPtr>, - I::Send:RequiresSend<_Self,ErasedPtr,OrigPtr>, - I::Clone:InitCloneField<_Self,ErasedPtr,OrigPtr>, - I::Debug:InitDebugField<_Self,ErasedPtr,OrigPtr>, - I::Display:InitDisplayField<_Self,ErasedPtr,OrigPtr>, - IA:GetUTID<_Self>, +impl AreTraitsImpld for I +where + I: InterfaceType, + I::Sync: RequiresSync<_Self, ErasedPtr, OrigPtr>, + I::Send: RequiresSend<_Self, ErasedPtr, OrigPtr>, + I::Clone: InitCloneField<_Self, ErasedPtr, OrigPtr>, + I::Debug: InitDebugField<_Self, ErasedPtr, OrigPtr>, + I::Display: InitDisplayField<_Self, ErasedPtr, OrigPtr>, + IA: GetUTID<_Self>, { - const VTABLE_VAL:RObjectVtable<_Self,ErasedPtr,I>= - RObjectVtable{ - _sabi_tys:NonOwningPhantom::NEW, - _sabi_type_id:>::UID, - _sabi_drop:c_functions::drop_pointer_impl::, - _sabi_clone:>::VALUE, - _sabi_debug:>::VALUE, - _sabi_display:>::VALUE, - }; + const VTABLE_VAL: RObjectVtable<_Self, ErasedPtr, I> = RObjectVtable { + _sabi_tys: NonOwningPhantom::NEW, + _sabi_type_id: >::UID, + _sabi_drop: c_functions::drop_pointer_impl::, + _sabi_clone: >::VALUE, + _sabi_debug: >::VALUE, + _sabi_display: >::VALUE, + }; } // A dummy type used to get around a compiler limitation WRT associated constants in traits. #[doc(hidden)] -struct GetRObjectVTableHelper(IA,_Self,ErasedPtr,OrigPtr,I); +struct GetRObjectVTableHelper(IA, _Self, ErasedPtr, OrigPtr, I); -impl - GetRObjectVTableHelper -where - I:AreTraitsImpld, +impl GetRObjectVTableHelper +where + I: AreTraitsImpld, { - staticref!{ + staticref! { const TMP_WM: WithMetadata> = WithMetadata::new(PrefixTypeTrait::METADATA, I::VTABLE_VAL); } - const TMP_VTABLE: RObjectVtable_Ref<_Self,ErasedPtr,I> = unsafe{ - RObjectVtable_Ref(Self::TMP_WM.as_prefix()) - }; - - + const TMP_VTABLE: RObjectVtable_Ref<_Self, ErasedPtr, I> = + unsafe { RObjectVtable_Ref(Self::TMP_WM.as_prefix()) }; } - /// The vtable for RObject,which all `#[trait_object]` derived trait objects contain. #[repr(C)] #[derive(StableAbi)] #[sabi(kind(Prefix))] #[sabi(missing_field(default))] -pub struct RObjectVtable<_Self,ErasedPtr,I>{ - pub _sabi_tys:NonOwningPhantom<(_Self,ErasedPtr,I)>, - - pub _sabi_type_id:Constructor>, - - pub _sabi_drop :unsafe extern "C" fn(this:RMut<'_, ErasedPtr>), - pub _sabi_clone:Option)->ErasedPtr>, - pub _sabi_debug:Option< - unsafe extern "C" fn(RRef<'_, ErasedObject>,FormattingMode,&mut RString)->RResult<(),()> +pub struct RObjectVtable<_Self, ErasedPtr, I> { + pub _sabi_tys: NonOwningPhantom<(_Self, ErasedPtr, I)>, + + pub _sabi_type_id: Constructor>, + + pub _sabi_drop: unsafe extern "C" fn(this: RMut<'_, ErasedPtr>), + pub _sabi_clone: Option) -> ErasedPtr>, + pub _sabi_debug: Option< + unsafe extern "C" fn( + RRef<'_, ErasedObject>, + FormattingMode, + &mut RString, + ) -> RResult<(), ()>, >, #[sabi(last_prefix_field)] - pub _sabi_display:Option< - unsafe extern "C" fn(RRef<'_, ErasedObject>,FormattingMode,&mut RString)->RResult<(),()> + pub _sabi_display: Option< + unsafe extern "C" fn( + RRef<'_, ErasedObject>, + FormattingMode, + &mut RString, + ) -> RResult<(), ()>, >, } - - /// The common prefix of all `#[trait_object]` derived vtables, /// with `RObjectVtable_Ref` as its first field. #[repr(C)] #[derive(StableAbi)] #[sabi( - bound="I:InterfaceBound", - extra_checks="::EXTRA_CHECKS", - kind(Prefix), + bound = "I:InterfaceBound", + extra_checks = "::EXTRA_CHECKS", + kind(Prefix) )] -pub(super)struct BaseVtable<_Self,ErasedPtr,I>{ - pub _sabi_tys:NonOwningPhantom<(_Self,ErasedPtr,I)>, +pub(super) struct BaseVtable<_Self, ErasedPtr, I> { + pub _sabi_tys: NonOwningPhantom<(_Self, ErasedPtr, I)>, #[sabi(last_prefix_field)] - pub _sabi_vtable: RObjectVtable_Ref<_Self,ErasedPtr,I>, + pub _sabi_vtable: RObjectVtable_Ref<_Self, ErasedPtr, I>, } use self::trait_bounds::*; -pub mod trait_bounds{ +pub mod trait_bounds { use super::*; macro_rules! declare_conditional_marker { @@ -256,11 +243,11 @@ pub mod trait_bounds{ ) => ( pub trait $trait_name<$self_,$ErasedPtr,$OrigPtr>{} - impl<$self_,$ErasedPtr,$OrigPtr> $trait_name<$self_,$ErasedPtr,$OrigPtr> + impl<$self_,$ErasedPtr,$OrigPtr> $trait_name<$self_,$ErasedPtr,$OrigPtr> for Unimplemented {} - - impl<$self_,$ErasedPtr,$OrigPtr> $trait_name<$self_,ErasedPtr,$OrigPtr> + + impl<$self_,$ErasedPtr,$OrigPtr> $trait_name<$self_,ErasedPtr,$OrigPtr> for Implemented where $($where_preds)* @@ -280,13 +267,13 @@ pub mod trait_bounds{ const VALUE:Option<$field_ty>; } - impl<$self_,$ErasedPtr,$OrigPtr> $trait_name<$self_,$ErasedPtr,$OrigPtr> + impl<$self_,$ErasedPtr,$OrigPtr> $trait_name<$self_,$ErasedPtr,$OrigPtr> for Unimplemented { const VALUE:Option<$field_ty>=None; } - impl<$self_,$ErasedPtr,$OrigPtr> $trait_name<$self_,ErasedPtr,$OrigPtr> + impl<$self_,$ErasedPtr,$OrigPtr> $trait_name<$self_,ErasedPtr,$OrigPtr> for Implemented where $($where_preds)* @@ -296,43 +283,37 @@ pub mod trait_bounds{ ) } - - declare_conditional_marker!{ + declare_conditional_marker! { type Send; trait RequiresSend[_Self,ErasedPtr,OrigPtr] where [ _Self:Send,OrigPtr:Send ] } - declare_conditional_marker!{ + declare_conditional_marker! { type Sync; trait RequiresSync[_Self,ErasedPtr,OrigPtr] where [ _Self:Sync,OrigPtr:Sync ] } - declare_field_initalizer!{ + declare_field_initalizer! { type Clone; trait InitCloneField[_Self,ErasedPtr,OrigPtr] where [ OrigPtr:Clone ] type=unsafe extern "C" fn(this:RRef<'_, ErasedPtr>)->ErasedPtr, value=c_functions::clone_pointer_impl::, } - declare_field_initalizer!{ + declare_field_initalizer! { type Debug; trait InitDebugField[_Self,ErasedPtr,OrigPtr] where [ _Self:Debug ] type=unsafe extern "C" fn(RRef<'_, ErasedObject>,FormattingMode,&mut RString)->RResult<(),()>, value=c_functions::debug_impl::<_Self>, } - declare_field_initalizer!{ + declare_field_initalizer! { type Display; trait InitDisplayField[_Self,ErasedPtr,OrigPtr] where [ _Self:Display ] type=unsafe extern "C" fn(RRef<'_, ErasedObject>,FormattingMode,&mut RString)->RResult<(),()>, value=c_functions::display_impl::<_Self>, } - - - - } - diff --git a/abi_stable/src/sabi_types.rs b/abi_stable/src/sabi_types.rs index bb9c81f1..1fec9d4b 100644 --- a/abi_stable/src/sabi_types.rs +++ b/abi_stable/src/sabi_types.rs @@ -2,30 +2,28 @@ ffi-safe types that aren't wrappers for other types. */ - mod constructor; mod ignored_wrapper; mod late_static_ref; -mod nul_str; mod maybe_cmp; mod move_ptr; -mod static_ref; -mod rref; +mod nul_str; mod rmut; -pub mod version; +mod rref; pub mod rsmallbox; - +mod static_ref; +pub mod version; pub use self::{ - constructor::{Constructor,ConstructorOrValue}, + constructor::{Constructor, ConstructorOrValue}, ignored_wrapper::CmpIgnored, - static_ref::StaticRef, - nul_str::NulStr, + late_static_ref::LateStaticRef, maybe_cmp::MaybeCmp, move_ptr::MovePtr, - rref::RRef, + nul_str::NulStr, rmut::RMut, + rref::RRef, rsmallbox::RSmallBox, - late_static_ref::LateStaticRef, - version::{VersionNumber,VersionStrings,ParseVersionError}, -}; \ No newline at end of file + static_ref::StaticRef, + version::{ParseVersionError, VersionNumber, VersionStrings}, +}; diff --git a/abi_stable/src/sabi_types/constructor.rs b/abi_stable/src/sabi_types/constructor.rs index c14ebb43..5acecf95 100644 --- a/abi_stable/src/sabi_types/constructor.rs +++ b/abi_stable/src/sabi_types/constructor.rs @@ -1,9 +1,8 @@ use std::{ - cmp::{Eq,Ord,PartialEq,PartialOrd,Ordering}, - fmt::{self,Debug,Display}, + cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}, + fmt::{self, Debug, Display}, }; - /** Newtype wrapper to pass function pointers to `const fn`. @@ -62,19 +61,19 @@ assert_ne!(C,D); #[repr(transparent)] #[derive(StableAbi)] // #[sabi(debug_print)] -pub struct Constructor(pub extern "C" fn()->T); +pub struct Constructor(pub extern "C" fn() -> T); -impl Copy for Constructor{} +impl Copy for Constructor {} -impl Clone for Constructor{ - fn clone(&self)->Self{ +impl Clone for Constructor { + fn clone(&self) -> Self { *self } } impl Debug for Constructor where - T:Debug + T: Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Debug::fmt(&self.get(), f) @@ -83,7 +82,7 @@ where impl Display for Constructor where - T:Display + T: Display, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Display::fmt(&self.get(), f) @@ -97,69 +96,62 @@ impl Constructor { } } -impl Eq for Constructor -where - T:Eq -{} +impl Eq for Constructor where T: Eq {} impl PartialEq for Constructor where - T:PartialEq + T: PartialEq, { - fn eq(&self,other:&Self)->bool{ - self.get()==other.get() + fn eq(&self, other: &Self) -> bool { + self.get() == other.get() } } impl Ord for Constructor where - T:Ord + T: Ord, { - fn cmp(&self,other:&Self)->Ordering{ + fn cmp(&self, other: &Self) -> Ordering { self.get().cmp(&other.get()) } } impl PartialOrd for Constructor where - T:PartialOrd + T: PartialOrd, { - fn partial_cmp(&self,other:&Self)->Option{ + fn partial_cmp(&self, other: &Self) -> Option { self.get().partial_cmp(&other.get()) } } - //////////////////////////////////////////////////////////////////////////////// - - /// Either the constructor for a value or the value itself #[repr(u8)] -#[derive(StableAbi,Copy,Clone)] +#[derive(StableAbi, Copy, Clone)] //#[sabi(debug_print)] -pub enum ConstructorOrValue{ +pub enum ConstructorOrValue { /// This is an `extern "C" fn()->T` which is used to construct a value of type `T` Constructor(Constructor), /// A value of type `T` - Value(T) + Value(T), } -impl ConstructorOrValue{ - /// Gets the wrapped value,computing it from its constructor if this +impl ConstructorOrValue { + /// Gets the wrapped value,computing it from its constructor if this /// is the `Constructor` variant - pub fn get(&mut self)->&T{ + pub fn get(&mut self) -> &T { match self { - ConstructorOrValue::Value(v)=>v, - &mut ConstructorOrValue::Constructor(func)=>{ - let v=(func.0)(); - *self=ConstructorOrValue::Value(v); + ConstructorOrValue::Value(v) => v, + &mut ConstructorOrValue::Constructor(func) => { + let v = (func.0)(); + *self = ConstructorOrValue::Value(v); match self { - ConstructorOrValue::Value(v)=>v, - _=>unreachable!() + ConstructorOrValue::Value(v) => v, + _ => unreachable!(), } - }, + } } } } - diff --git a/abi_stable/src/sabi_types/ignored_wrapper.rs b/abi_stable/src/sabi_types/ignored_wrapper.rs index 7b297282..9a729aaf 100644 --- a/abi_stable/src/sabi_types/ignored_wrapper.rs +++ b/abi_stable/src/sabi_types/ignored_wrapper.rs @@ -3,16 +3,16 @@ Wrapper type(s) where their value is ignored in some trait impls . */ use std::{ - ops::{Deref,DerefMut}, - fmt::{self,Debug,Display}, - cmp::{Ordering,Eq,PartialEq,Ord,PartialOrd}, - hash::{Hash,Hasher}, + cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}, + fmt::{self, Debug, Display}, + hash::{Hash, Hasher}, + ops::{Deref, DerefMut}, }; /** Wrapper type used to ignore its contents in comparisons. -Use this if you want to derive trait while ignoring the contents of fields in the +Use this if you want to derive trait while ignoring the contents of fields in the `PartialEq`/`Eq`/`PartialOrd`/`Ord`/`Hash` traits. It also replaces the hash of T with the hash of `()`. @@ -60,13 +60,12 @@ assert_eq!( map.get(&a).unwrap().alt_name.as_str(), "H___ of B_____" ); */ #[repr(transparent)] -#[derive(Default,Copy,Clone,StableAbi)] -pub struct CmpIgnored{ - pub value:T, +#[derive(Default, Copy, Clone, StableAbi)] +pub struct CmpIgnored { + pub value: T, } - -impl CmpIgnored{ +impl CmpIgnored { /// Constructs a CmpIgnored. /// /// # Example @@ -77,80 +76,73 @@ impl CmpIgnored{ /// let val=CmpIgnored::new(100); /// /// ``` - pub const fn new(value:T)->Self{ - Self{value} + pub const fn new(value: T) -> Self { + Self { value } } } - -impl From for CmpIgnored{ - fn from(value:T)->Self{ - Self{value} +impl From for CmpIgnored { + fn from(value: T) -> Self { + Self { value } } } - impl Deref for CmpIgnored { - type Target=T; + type Target = T; - fn deref(&self)->&Self::Target{ + fn deref(&self) -> &Self::Target { &self.value } } impl DerefMut for CmpIgnored { - fn deref_mut(&mut self)->&mut Self::Target{ + fn deref_mut(&mut self) -> &mut Self::Target { &mut self.value } } impl Display for CmpIgnored where - T:Display, + T: Display, { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Display::fmt(&**self,f) + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Display::fmt(&**self, f) } } - impl Debug for CmpIgnored where - T:Debug, + T: Debug, { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Debug::fmt(&**self,f) + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Debug::fmt(&**self, f) } } impl Eq for CmpIgnored {} - impl PartialEq for CmpIgnored { - fn eq(&self, _other: &Self) -> bool{ + fn eq(&self, _other: &Self) -> bool { true } } - -impl Ord for CmpIgnored{ - fn cmp(&self, _other: &Self) -> Ordering{ +impl Ord for CmpIgnored { + fn cmp(&self, _other: &Self) -> Ordering { Ordering::Equal } } - -impl PartialOrd for CmpIgnored{ - fn partial_cmp(&self, _other: &Self) -> Option{ +impl PartialOrd for CmpIgnored { + fn partial_cmp(&self, _other: &Self) -> Option { Some(Ordering::Equal) } } - -impl Hash for CmpIgnored{ +impl Hash for CmpIgnored { fn hash(&self, state: &mut H) where - H: Hasher + H: Hasher, { ().hash(state) } diff --git a/abi_stable/src/sabi_types/late_static_ref.rs b/abi_stable/src/sabi_types/late_static_ref.rs index aeb47f8c..62f6fa6e 100644 --- a/abi_stable/src/sabi_types/late_static_ref.rs +++ b/abi_stable/src/sabi_types/late_static_ref.rs @@ -5,13 +5,13 @@ A late-initialized static reference. use std::{ marker::PhantomData, ptr::{self, NonNull}, - sync::atomic::{AtomicPtr,Ordering}, + sync::atomic::{AtomicPtr, Ordering}, }; use crate::{ external_types::RMutex, - prefix_type::{PointsToPrefixFields, PrefixRef}, pointer_trait::{ImmutableRef, ImmutableRefTarget}, + prefix_type::{PointsToPrefixFields, PrefixRef}, }; /** @@ -60,7 +60,7 @@ pub enum UserAction{ fn load_config(file_path:&Path)->Result<&'static Config,RBoxError>{ static CONFIG:LateStaticRef<&Config>=LateStaticRef::new(); - + CONFIG.try_init(||{ let file=load_file(file_path).map_err(RBoxError::new)?; let config=serde_json::from_str::(&file).map_err(RBoxError::new)?; @@ -86,18 +86,18 @@ fn load_config(file_path:&Path)->Result<&'static Config,RBoxError>{ */ #[repr(C)] #[derive(StableAbi)] -pub struct LateStaticRef{ - pointer:AtomicPtr<()>, - lock:RMutex<()>, +pub struct LateStaticRef { + pointer: AtomicPtr<()>, + lock: RMutex<()>, _marker: PhantomData, } -const LOCK:RMutex<()>=RMutex::new(()); +const LOCK: RMutex<()> = RMutex::new(()); unsafe impl Sync for LateStaticRef {} unsafe impl Send for LateStaticRef {} -impl LateStaticRef{ +impl LateStaticRef { /// Constructs the `LateStaticRef` in an uninitialized state. /// /// # Example @@ -108,8 +108,8 @@ impl LateStaticRef{ /// static LATE_REF:LateStaticRef<&String>=LateStaticRef::new(); /// /// ``` - pub const fn new()->Self{ - Self{ + pub const fn new() -> Self { + Self { lock: LOCK, pointer: AtomicPtr::new(ptr::null_mut()), _marker: PhantomData, @@ -117,7 +117,7 @@ impl LateStaticRef{ } } -impl LateStaticRef<&'static T>{ +impl LateStaticRef<&'static T> { /// Constructs `LateStaticRef`, initialized with `value`. /// /// # Example @@ -129,8 +129,8 @@ impl LateStaticRef<&'static T>{ /// LateStaticRef::from_ref(&"Hello!"); /// /// ``` - pub const fn from_ref(value:&'static T)->Self{ - Self{ + pub const fn from_ref(value: &'static T) -> Self { + Self { lock: LOCK, pointer: AtomicPtr::new(value as *const T as *mut ()), _marker: PhantomData, @@ -158,7 +158,7 @@ impl LateStaticRef { /// pub static LATE_REF: LateStaticRef = { /// // This is how you can construct a `LateStaticRef`, /// // from a `Foo_Ref` at compile-time. - /// // + /// // /// // If you don't need a `LateStaticRef` you can construct a `PersonMod_Ref` constant, /// // and use that. /// LateStaticRef::from_prefixref(PrefixRefTrait::PREFIX_FIELDS, MODULE.0) @@ -168,15 +168,15 @@ impl LateStaticRef { /// #[derive(StableAbi)] /// #[sabi(kind(Prefix))] /// pub struct PersonMod { - /// /// The `#[sabi(last_prefix_field)]` attribute here means that this is - /// /// the last field in this struct that was defined in the + /// /// The `#[sabi(last_prefix_field)]` attribute here means that this is + /// /// the last field in this struct that was defined in the /// /// first compatible version of the library. /// /// Moving this attribute is a braeking change. /// #[sabi(last_prefix_field)] /// pub get_number: extern "C" fn()->u32, - /// + /// /// } - /// + /// /// const MODULE: PersonMod_Ref = { /// /// const S: &WithMetadata = &WithMetadata::new( @@ -188,18 +188,18 @@ impl LateStaticRef { /// /// PersonMod_Ref(S.static_as_prefix()) /// }; - /// + /// /// extern fn get_number()->u32{ /// 100 /// } /// ``` - /// + /// /// [`PrefixRef`]: ../prefix_type/struct.PrefixRef.html - pub const fn from_prefixref

(_: PointsToPrefixFields, ptr: PrefixRef

) -> Self + pub const fn from_prefixref

(_: PointsToPrefixFields, ptr: PrefixRef

) -> Self where - P: 'static + P: 'static, { - Self{ + Self { lock: LOCK, pointer: AtomicPtr::new(ptr.const_to_raw_ptr() as *mut ()), _marker: PhantomData, @@ -212,7 +212,7 @@ impl LateStaticRef { /// /// # Safety /// - /// The passed in pointer must be valid for passing to + /// The passed in pointer must be valid for passing to /// [`::from_nonnull`], /// it must be a valid pointer to `U`, /// and be valid to dereference for the rest of the program's lifetime. @@ -229,36 +229,36 @@ impl LateStaticRef { /// sabi_types::LateStaticRef, /// utils::ref_as_nonnull, /// }; - /// - /// use std::ptr::NonNull; - /// + /// + /// use std::ptr::NonNull; + /// /// #[derive(Copy, Clone)] /// struct Foo<'a>(&'a u64); - /// + /// /// impl<'a> Foo<'a> { /// const fn as_nonnull(self) -> NonNull { /// ref_as_nonnull(self.0) /// } /// } - /// + /// /// unsafe impl<'a> ImmutableRef for Foo<'a> { /// type Target = u64; /// } - /// + /// /// const MODULE: LateStaticRef> = { /// unsafe{ /// LateStaticRef::from_custom( /// ImmutableRef::TARGET, /// Foo(&100).as_nonnull(), - /// ) + /// ) /// } /// }; /// ``` pub const unsafe fn from_custom( _target: ImmutableRefTarget, ptr: NonNull, - )->Self{ - Self{ + ) -> Self { + Self { lock: LOCK, pointer: AtomicPtr::new(ptr.as_ptr() as *mut ()), _marker: PhantomData, @@ -266,15 +266,15 @@ impl LateStaticRef { } } -impl LateStaticRef +impl LateStaticRef where - T: ImmutableRef + 'static + T: ImmutableRef + 'static, { /// Lazily initializes the `LateStaticRef` with `initializer`, /// returning the `T` if either it was already initialized,or /// if `initalizer` returned Ok(..). /// - /// If `initializer` returns an `Err(...)` this returns the error and + /// If `initializer` returns an `Err(...)` this returns the error and /// allows the `LateStaticRef` to be initializer later. /// /// If `initializer` panics,the panic is propagated, @@ -294,7 +294,7 @@ where /// LateStaticRef::from_ref(&"Hello!"); /// /// assert_eq!( LATE.try_init(|| Err("oh no!") ), Err("oh no!") ); - /// assert_eq!( + /// assert_eq!( /// LATE /// .try_init(||->Result<&'static String,()>{ /// Ok( leak_value("Yay".to_string()) ) @@ -302,35 +302,37 @@ where /// .map(|s| s.as_str() ), /// Ok("Yay"), /// ); - /// + /// /// assert_eq!( EARLY.try_init(|| Err("oh no!") ), Ok(&"Hello!") ); /// /// /// ``` - pub fn try_init(&self,initializer:F)->Result - where F:FnOnce()->Result + pub fn try_init(&self, initializer: F) -> Result + where + F: FnOnce() -> Result, { - if let Some(pointer)=self.get() { + if let Some(pointer) = self.get() { return Ok(pointer); } - - let guard_=self.lock.lock(); - - if let Some(pointer)=self.get() { + + let guard_ = self.lock.lock(); + + if let Some(pointer) = self.get() { return Ok(pointer); } - let pointer=initializer()?; + let pointer = initializer()?; - self.pointer.store(pointer.to_raw_ptr() as *mut T::Target as *mut (), Ordering::Release); + self.pointer.store( + pointer.to_raw_ptr() as *mut T::Target as *mut (), + Ordering::Release, + ); drop(guard_); Ok(pointer) - } - /// Lazily initializes the `LateStaticRef` with `initializer`, /// returning the `T` if either it was already initialized, /// or `initalizer` returns it without panicking. @@ -361,13 +363,11 @@ where /// /// ``` #[inline] - pub fn init(&self,initializer:F)->T - where F:FnOnce()->T + pub fn init(&self, initializer: F) -> T + where + F: FnOnce() -> T, { - self - .try_init(||->Result{ - Ok(initializer()) - }) + self.try_init(|| -> Result { Ok(initializer()) }) .expect("bug:LateStaticRef::try_init should only return an Err if `initializer` does") } @@ -397,86 +397,71 @@ where /// assert_eq!( EARLY.get(), Some(&"Hello!") ); /// /// ``` - pub fn get(&self)->Option{ - unsafe{ - T::from_raw_ptr(self.pointer.load(Ordering::Acquire) as *const T::Target) - } + pub fn get(&self) -> Option { + unsafe { T::from_raw_ptr(self.pointer.load(Ordering::Acquire) as *const T::Target) } } } -use ::std::panic::{ - UnwindSafe, - RefUnwindSafe, -}; - -impl UnwindSafe for LateStaticRef{} -impl RefUnwindSafe for LateStaticRef{} +use ::std::panic::{RefUnwindSafe, UnwindSafe}; +impl UnwindSafe for LateStaticRef {} +impl RefUnwindSafe for LateStaticRef {} ////////////////////////////////////////////////////// - //#[cfg(test)] -#[cfg(all(test,not(feature="only_new_tests")))] -mod tests{ +#[cfg(all(test, not(feature = "only_new_tests")))] +mod tests { use super::*; use std::panic::catch_unwind; - static N_100:u32=100; - static N_277:u32=277; + static N_100: u32 = 100; + static N_277: u32 = 277; #[test] - fn test_init(){ - let ptr=LateStaticRef::<&u32>::new(); + fn test_init() { + let ptr = LateStaticRef::<&u32>::new(); - assert_eq!(None,ptr.get() ); - - let caught=catch_unwind(||{ - ptr.init(|| panic!() ); + assert_eq!(None, ptr.get()); + + let caught = catch_unwind(|| { + ptr.init(|| panic!()); }); assert!(caught.is_err()); - assert_eq!(None,ptr.get() ); + assert_eq!(None, ptr.get()); - assert_eq!(100,*ptr.init(|| &N_100 )); - assert_eq!(100,*ptr.init(|| panic!("this should not run") )); - - assert_eq!( - (&N_100)as *const u32, - ptr.get().unwrap() as *const u32 - ); + assert_eq!(100, *ptr.init(|| &N_100)); + assert_eq!(100, *ptr.init(|| panic!("this should not run"))); + assert_eq!((&N_100) as *const u32, ptr.get().unwrap() as *const u32); } #[test] - fn test_try_init(){ - let ptr=LateStaticRef::<&u32>::new(); + fn test_try_init() { + let ptr = LateStaticRef::<&u32>::new(); + + assert_eq!(None, ptr.get()); - assert_eq!(None,ptr.get() ); - - let caught=catch_unwind(||{ - let _=ptr.try_init(||->Result<_,i32>{ panic!() }); + let caught = catch_unwind(|| { + let _ = ptr.try_init(|| -> Result<_, i32> { panic!() }); }); assert!(caught.is_err()); - assert_eq!(None,ptr.get() ); + assert_eq!(None, ptr.get()); - assert_eq!(Err(10),ptr.try_init(||->Result<_,i32>{ Err(10) })); - assert_eq!(Err(17),ptr.try_init(||->Result<_,i32>{ Err(17) })); + assert_eq!(Err(10), ptr.try_init(|| -> Result<_, i32> { Err(10) })); + assert_eq!(Err(17), ptr.try_init(|| -> Result<_, i32> { Err(17) })); + + assert_eq!(Ok(&277), ptr.try_init(|| -> Result<_, i32> { Ok(&N_277) })); - assert_eq!(Ok(&277),ptr.try_init(||->Result<_,i32>{ Ok(&N_277) })); - assert_eq!( Ok(&277), - ptr.try_init(||->Result<_,i32>{ panic!("this should not run") }) - ); - - assert_eq!( - (&N_277)as *const u32, - ptr.get().unwrap() as *const u32 + ptr.try_init(|| -> Result<_, i32> { panic!("this should not run") }) ); + assert_eq!((&N_277) as *const u32, ptr.get().unwrap() as *const u32); } } diff --git a/abi_stable/src/sabi_types/maybe_cmp.rs b/abi_stable/src/sabi_types/maybe_cmp.rs index c3750b71..d3fe313f 100644 --- a/abi_stable/src/sabi_types/maybe_cmp.rs +++ b/abi_stable/src/sabi_types/maybe_cmp.rs @@ -1,6 +1,4 @@ -use std::{ - cmp::{PartialEq, Eq, PartialOrd,Ordering}, -}; +use std::cmp::{Eq, Ordering, PartialEq, PartialOrd}; /** An Option-like type which only compares equal if it contains a value(the `Just` variant). @@ -29,22 +27,16 @@ pub enum MaybeCmp { Nothing, } - - - -impl Eq for MaybeCmp -where - T: Eq, -{} +impl Eq for MaybeCmp where T: Eq {} impl PartialEq for MaybeCmp where T: PartialEq, { fn eq(&self, other: &Self) -> bool { - match (self,other) { - (MaybeCmp::Just(l),MaybeCmp::Just(r))=> l == r, - _=>false, + match (self, other) { + (MaybeCmp::Just(l), MaybeCmp::Just(r)) => l == r, + _ => false, } } } @@ -54,31 +46,39 @@ where T: PartialOrd, { fn partial_cmp(&self, other: &Self) -> Option { - match (self,other) { - (MaybeCmp::Just(l),MaybeCmp::Just(r))=>l.partial_cmp(r), - _=>None, + match (self, other) { + (MaybeCmp::Just(l), MaybeCmp::Just(r)) => l.partial_cmp(r), + _ => None, } } } - //#[cfg(test)] -#[cfg(all(test,not(feature="only_new_tests")))] -mod tets{ +#[cfg(all(test, not(feature = "only_new_tests")))] +mod tets { use super::*; #[test] - fn comparisons(){ - assert_eq!(MaybeCmp::Just(0),MaybeCmp::Just(0)); - - assert_ne!(MaybeCmp::Just(0),MaybeCmp::Just(1)); - assert_ne!(MaybeCmp::Nothing,MaybeCmp::Just(0)); - assert_ne!(MaybeCmp::Just(0),MaybeCmp::Nothing); - assert_ne!(MaybeCmp::<()>::Nothing,MaybeCmp::Nothing); - - assert_eq!(MaybeCmp::Just(0).partial_cmp(&MaybeCmp::Just(0)),Some(Ordering::Equal)); - assert_eq!(MaybeCmp::Just(0).partial_cmp(&MaybeCmp::Just(1)),Some(Ordering::Less)); - assert_eq!(MaybeCmp::Nothing.partial_cmp(&MaybeCmp::Just(0)),None); - assert_eq!(MaybeCmp::Just(0).partial_cmp(&MaybeCmp::Nothing),None); - assert_eq!(MaybeCmp::<()>::Nothing.partial_cmp(&MaybeCmp::Nothing),None); + fn comparisons() { + assert_eq!(MaybeCmp::Just(0), MaybeCmp::Just(0)); + + assert_ne!(MaybeCmp::Just(0), MaybeCmp::Just(1)); + assert_ne!(MaybeCmp::Nothing, MaybeCmp::Just(0)); + assert_ne!(MaybeCmp::Just(0), MaybeCmp::Nothing); + assert_ne!(MaybeCmp::<()>::Nothing, MaybeCmp::Nothing); + + assert_eq!( + MaybeCmp::Just(0).partial_cmp(&MaybeCmp::Just(0)), + Some(Ordering::Equal) + ); + assert_eq!( + MaybeCmp::Just(0).partial_cmp(&MaybeCmp::Just(1)), + Some(Ordering::Less) + ); + assert_eq!(MaybeCmp::Nothing.partial_cmp(&MaybeCmp::Just(0)), None); + assert_eq!(MaybeCmp::Just(0).partial_cmp(&MaybeCmp::Nothing), None); + assert_eq!( + MaybeCmp::<()>::Nothing.partial_cmp(&MaybeCmp::Nothing), + None + ); } -} \ No newline at end of file +} diff --git a/abi_stable/src/sabi_types/move_ptr.rs b/abi_stable/src/sabi_types/move_ptr.rs index 53702b9f..fa41d89f 100644 --- a/abi_stable/src/sabi_types/move_ptr.rs +++ b/abi_stable/src/sabi_types/move_ptr.rs @@ -3,19 +3,15 @@ Contains the `MovePtr<_>` type. */ use std::{ - alloc::{self,Layout}, - ops::{Deref,DerefMut}, - fmt::{self,Display}, + alloc::{self, Layout}, + fmt::{self, Display}, marker::PhantomData, mem::ManuallyDrop, + ops::{Deref, DerefMut}, ptr::{self, NonNull}, }; -use crate::{ - traits::IntoInner, - sabi_types::RMut, - std_types::RBox, -}; +use crate::{sabi_types::RMut, std_types::RBox, traits::IntoInner}; /** A move pointer, which allows moving the value from the reference, @@ -25,7 +21,7 @@ If `MovePtr::into_inner` isn't called, this drops the referenced value when it's # Safety -This is unsafe to construct since the user must ensure that the +This is unsafe to construct since the user must ensure that the original owner of the value never accesses it again. # Motivation @@ -60,8 +56,8 @@ assert_eq!( move_rbox_to_box(RBox::new(99)), Box::new(99) ); assert_eq!( move_rbox_to_box(RBox::new(())), Box::new(()) ); assert_eq!( - move_rbox_to_box(RBox::new(String::from("SHIT"))), - Box::new(String::from("SHIT")) + move_rbox_to_box(RBox::new(String::from("SHIT"))), + Box::new(String::from("SHIT")) ); @@ -86,13 +82,13 @@ let rbox = RBox::new(0x100); let second_rbox; -unsafe{ +unsafe{ let mut rbox = ManuallyDrop::new(rbox); - + let move_ptr = unsafe{ MovePtr::from_rmut(rbox.as_rmut()) }; second_rbox = RBox::from_move_ptr(move_ptr); - - OwnedPointer::drop_allocation(&mut rbox); + + OwnedPointer::drop_allocation(&mut rbox); } assert_eq!(second_rbox, RBox::new(0x100)); @@ -104,49 +100,48 @@ assert_eq!(second_rbox, RBox::new(0x100)); */ #[repr(transparent)] #[derive(StableAbi)] -#[sabi(bound="T:'a")] -pub struct MovePtr<'a,T>{ +#[sabi(bound = "T:'a")] +pub struct MovePtr<'a, T> { ptr: NonNull, _marker: PhantomData<&'a mut T>, } - -impl<'a,T> MovePtr<'a,T>{ +impl<'a, T> MovePtr<'a, T> { /// Constructs this move pointer from a mutable reference, /// moving the value out of the reference. /// - /// # Safety + /// # Safety /// - /// Callers must ensure that the original owner of the value won't + /// Callers must ensure that the original owner of the value won't /// access the moved-out value anymore. /// /// # Example /// /// ``` /// use abi_stable::sabi_types::MovePtr; - /// + /// /// use std::mem::ManuallyDrop; - /// + /// /// let mut manual = ManuallyDrop::new(String::from("hello")); - /// + /// /// let moveptr = unsafe{ MovePtr::new(&mut *manual) }; /// /// drop(moveptr); // moveptr drops the String here. /// ``` #[inline] - pub unsafe fn new(ptr: &'a mut T)->Self{ + pub unsafe fn new(ptr: &'a mut T) -> Self { Self { ptr: NonNull::new_unchecked(ptr), - _marker:PhantomData, + _marker: PhantomData, } } /// Constructs this move pointer from an `RMut`, /// moving the value out of the reference. /// - /// # Safety + /// # Safety /// - /// Callers must ensure that the original owner of the value won't + /// Callers must ensure that the original owner of the value won't /// access the moved-out value anymore. /// /// # Example @@ -158,38 +153,38 @@ impl<'a,T> MovePtr<'a,T>{ /// pointer_trait::AsMutPtr, /// utils::manuallydrop_as_rmut, /// }; - /// + /// /// use std::mem::ManuallyDrop; - /// - /// + /// + /// /// let mut mdrop = ManuallyDrop::new(RString::from("hello")); - /// + /// /// // safety: `mdrop` is never accessed again /// let moveptr = unsafe{ MovePtr::from_rmut(manuallydrop_as_rmut(&mut mdrop)) }; /// assert_eq!(*moveptr, "hello"); /// /// let string: RString = MovePtr::into_inner(moveptr); /// assert_eq!(string, "hello"); - /// + /// /// ``` #[inline] - pub unsafe fn from_rmut(ptr: RMut<'a, T>)->Self{ + pub unsafe fn from_rmut(ptr: RMut<'a, T>) -> Self { Self { ptr: NonNull::new_unchecked(ptr.into_raw()), - _marker:PhantomData, + _marker: PhantomData, } } /// Constructs this move pointer from a raw pointer, /// moving the value out of it. /// - /// # Safety + /// # Safety /// - /// Callers must ensure that the original owner of the value won't + /// Callers must ensure that the original owner of the value won't /// access the moved-out value anymore. /// /// Because this takes a mutable pointer, the lifetime of this `MovePtr` is unbounded. - /// You must ensure that it's not used for longer than the lifetime of the + /// You must ensure that it's not used for longer than the lifetime of the /// pointed-to value. /// /// # Example @@ -202,24 +197,24 @@ impl<'a,T> MovePtr<'a,T>{ /// utils::manuallydrop_as_raw_mut, /// rvec, /// }; - /// + /// /// use std::mem::ManuallyDrop; - /// - /// + /// + /// /// let mut mdrop = ManuallyDrop::new(rvec![3, 5, 8]); - /// + /// /// // safety: `mdrop` is never accessed again /// let moveptr = unsafe{ MovePtr::from_raw(manuallydrop_as_raw_mut(&mut mdrop)) }; /// assert_eq!(moveptr[..], [3, 5, 8]); /// /// let vector: RVec = MovePtr::into_inner(moveptr); /// assert_eq!(vector[..], [3, 5, 8]); - /// + /// /// ``` - pub unsafe fn from_raw(ptr: *mut T)->Self{ - Self{ + pub unsafe fn from_raw(ptr: *mut T) -> Self { + Self { ptr: NonNull::new_unchecked(ptr), - _marker:PhantomData, + _marker: PhantomData, } } @@ -233,17 +228,17 @@ impl<'a,T> MovePtr<'a,T>{ /// sabi_types::MovePtr, /// std_types::RBox, /// }; - /// + /// /// let rbox=RBox::new(String::from("NOPE")); /// let address_rbox=&*rbox as *const String as usize; /// /// rbox.in_move_ptr(|move_ptr|{ /// assert_eq!( address_rbox, MovePtr::as_ptr(&move_ptr) as usize ); /// }); - /// + /// /// ``` #[inline(always)] - pub const fn as_ptr(this:&Self)->*const T{ + pub const fn as_ptr(this: &Self) -> *const T { this.ptr.as_ptr() } @@ -259,17 +254,17 @@ impl<'a,T> MovePtr<'a,T>{ /// sabi_types::MovePtr, /// std_types::RBox, /// }; - /// + /// /// let rbox=RBox::new(String::from("NOPE")); /// let address_rbox=&*rbox as *const String as usize; /// /// rbox.in_move_ptr(|mut move_ptr|{ /// assert_eq!( address_rbox, MovePtr::as_mut_ptr(&mut move_ptr) as usize ); /// }); - /// + /// /// ``` #[inline(always)] - pub fn as_mut_ptr(this:&mut Self)->*mut T{ + pub fn as_mut_ptr(this: &mut Self) -> *mut T { this.ptr.as_ptr() } @@ -285,18 +280,18 @@ impl<'a,T> MovePtr<'a,T>{ /// sabi_types::MovePtr, /// std_types::RBox, /// }; - /// + /// /// let rbox=RBox::new(String::from("NOPE")); /// /// let string=rbox.in_move_ptr(|move_ptr|unsafe{ /// MovePtr::into_raw(move_ptr).read() /// }); - /// + /// /// assert_eq!(string,String::from("NOPE")); - /// + /// /// ``` #[inline] - pub fn into_raw(this:Self)->*mut T{ + pub fn into_raw(this: Self) -> *mut T { let this = ManuallyDrop::new(this); let ptr = this.ptr.as_ptr(); ptr @@ -312,27 +307,27 @@ impl<'a,T> MovePtr<'a,T>{ /// sabi_types::MovePtr, /// std_types::RBox, /// }; - /// + /// /// let rbox=RBox::new(String::from("WHAT!!!")); /// /// let boxed=rbox.in_move_ptr(|move_ptr|unsafe{ /// MovePtr::into_box(move_ptr) /// }); - /// + /// /// assert_eq!(boxed,Box::new(String::from("WHAT!!!"))); - /// + /// /// ``` #[inline] - pub fn into_box(this:Self)->Box{ - unsafe{ + pub fn into_box(this: Self) -> Box { + unsafe { let raw = Self::into_raw(this); if std::mem::size_of::() == 0 { Box::from_raw(raw) } else { - let allocated=alloc::alloc(Layout::new::()) as *mut T; + let allocated = alloc::alloc(Layout::new::()) as *mut T; - raw.copy_to_nonoverlapping(allocated,1); + raw.copy_to_nonoverlapping(allocated, 1); Box::from_raw(allocated) } @@ -349,18 +344,18 @@ impl<'a,T> MovePtr<'a,T>{ /// sabi_types::MovePtr, /// std_types::RBox, /// }; - /// + /// /// let rbox=RBox::new(String::from("WHAT!!!")); /// /// let boxed=rbox.in_move_ptr(|move_ptr|unsafe{ /// MovePtr::into_rbox(move_ptr) /// }); - /// + /// /// assert_eq!( boxed, RBox::new(String::from("WHAT!!!")) ); - /// + /// /// ``` #[inline] - pub fn into_rbox(this:Self)->RBox{ + pub fn into_rbox(this: Self) -> RBox { Self::into_box(this).into() } @@ -374,30 +369,28 @@ impl<'a,T> MovePtr<'a,T>{ /// sabi_types::MovePtr, /// std_types::RBox, /// }; - /// + /// /// let rbox=RBox::new(String::from("(The Wi)zard(of)oz")); /// /// let string=rbox.in_move_ptr(|ptr| MovePtr::into_inner(ptr) ); - /// + /// /// assert_eq!( string, String::from("(The Wi)zard(of)oz") ); - /// + /// /// ``` #[inline] - pub fn into_inner(this:Self)->T{ - let this=ManuallyDrop::new(this); - unsafe{ - this.ptr.as_ptr().read() - } + pub fn into_inner(this: Self) -> T { + let this = ManuallyDrop::new(this); + unsafe { this.ptr.as_ptr().read() } } /// Transmute this `RMove<'a, T>` into a `RMove<'a, U>`. - /// + /// /// # Safety - /// - /// This has the safety requirements as + /// + /// This has the safety requirements as /// [`std::mem::transmute`](https://doc.rust-lang.org/std/mem/fn.transmute.html), /// as well as requiring that this `MovePtr` is aligned for `U`. - /// + /// /// /// # Example /// @@ -407,111 +400,109 @@ impl<'a,T> MovePtr<'a,T>{ /// sabi_types::MovePtr, /// std_types::{RBox, RString, RVec}, /// }; - /// + /// /// let rbox = RBox::new(RString::from("hello")); /// /// let bytes = rbox.in_move_ptr(|ptr| unsafe{ /// MovePtr::into_inner(MovePtr::transmute::>(ptr)) /// }); - /// + /// /// assert_eq!(bytes.as_slice(), b"hello"); - /// + /// /// ``` #[inline] pub unsafe fn transmute(this: Self) -> MovePtr<'a, U> where - U: 'a + U: 'a, { std::mem::transmute::, MovePtr<'a, U>>(this) } } - shared_impls! { mod=move_ptr_impls new_type=MovePtr['a][T], original_type=AAAA, } - -impl<'a,T> Display for MovePtr<'a,T> +impl<'a, T> Display for MovePtr<'a, T> where - T:Display, + T: Display, { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Display::fmt(&**self,f) + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Display::fmt(&**self, f) } } -impl<'a,T> Deref for MovePtr<'a,T>{ - type Target=T; +impl<'a, T> Deref for MovePtr<'a, T> { + type Target = T; - fn deref(&self)->&T{ - unsafe{ &*(self.ptr.as_ptr() as *const _) } + fn deref(&self) -> &T { + unsafe { &*(self.ptr.as_ptr() as *const _) } } } -impl<'a,T> DerefMut for MovePtr<'a,T>{ - fn deref_mut(&mut self)->&mut T{ - unsafe{ &mut *self.ptr.as_ptr() } +impl<'a, T> DerefMut for MovePtr<'a, T> { + fn deref_mut(&mut self) -> &mut T { + unsafe { &mut *self.ptr.as_ptr() } } } -impl<'a,T> IntoInner for MovePtr<'a,T>{ - type Element=T; - - fn into_inner_(self)->T{ +impl<'a, T> IntoInner for MovePtr<'a, T> { + type Element = T; + + fn into_inner_(self) -> T { Self::into_inner(self) } } -impl<'a,T> Drop for MovePtr<'a,T>{ - fn drop(&mut self){ - unsafe{ +impl<'a, T> Drop for MovePtr<'a, T> { + fn drop(&mut self) { + unsafe { ptr::drop_in_place(self.ptr.as_ptr()); } } } -unsafe impl<'a, T: Send> Send for MovePtr<'a,T> {} +unsafe impl<'a, T: Send> Send for MovePtr<'a, T> {} -unsafe impl<'a, T: Sync> Sync for MovePtr<'a,T> {} +unsafe impl<'a, T: Sync> Sync for MovePtr<'a, T> {} //#[cfg(test)] -#[cfg(all(test,not(feature="only_new_tests")))] -mod test{ +#[cfg(all(test, not(feature = "only_new_tests")))] +mod test { use super::*; use std::sync::Arc; #[test] - fn with_manuallydrop(){ - let arc=Arc::new(10); - unsafe{ - let mut cloned_arc=ManuallyDrop::new(arc.clone()); - - let move_ptr=MovePtr::new(&mut *cloned_arc); - assert_eq!(Arc::strong_count(&*move_ptr),2); - - let moved_arc=MovePtr::into_inner(move_ptr); - assert_eq!(Arc::strong_count(&moved_arc),2); + fn with_manuallydrop() { + let arc = Arc::new(10); + unsafe { + let mut cloned_arc = ManuallyDrop::new(arc.clone()); + + let move_ptr = MovePtr::new(&mut *cloned_arc); + assert_eq!(Arc::strong_count(&*move_ptr), 2); + + let moved_arc = MovePtr::into_inner(move_ptr); + assert_eq!(Arc::strong_count(&moved_arc), 2); } - assert_eq!(Arc::strong_count(&arc),1); - unsafe{ - let mut cloned_arc=ManuallyDrop::new(arc.clone()); - - let move_ptr=MovePtr::new(&mut *cloned_arc); - assert_eq!(Arc::strong_count(&*move_ptr),2); + assert_eq!(Arc::strong_count(&arc), 1); + unsafe { + let mut cloned_arc = ManuallyDrop::new(arc.clone()); + + let move_ptr = MovePtr::new(&mut *cloned_arc); + assert_eq!(Arc::strong_count(&*move_ptr), 2); } - assert_eq!(Arc::strong_count(&arc),1); + assert_eq!(Arc::strong_count(&arc), 1); } #[test] - fn take_mutable_reference(){ - unsafe{ + fn take_mutable_reference() { + unsafe { let mut val = 3u32; let mut mutref = ManuallyDrop::new(&mut val); - + let mut move_ptr = MovePtr::<&mut u32>::new(&mut *mutref); assert_eq!(**move_ptr, 3); @@ -522,4 +513,4 @@ mod test{ assert_eq!(*moved_mut, 5); } } -} \ No newline at end of file +} diff --git a/abi_stable/src/sabi_types/nul_str.rs b/abi_stable/src/sabi_types/nul_str.rs index 0ea4c51f..49214d7e 100644 --- a/abi_stable/src/sabi_types/nul_str.rs +++ b/abi_stable/src/sabi_types/nul_str.rs @@ -1,59 +1,56 @@ //! A nul-terminated string,which is just a pointer to the string data, //! it doesn't know the length of the string. -use crate::{ - std_types::RStr, - utils::ref_as_nonnull, -}; +use crate::{std_types::RStr, utils::ref_as_nonnull}; use std::{ - cmp::{PartialEq,Eq}, + cmp::{Eq, PartialEq}, fmt::{self, Debug, Display}, marker::PhantomData, ptr::NonNull, }; - - /// A utf8 null-terminated string slice. #[repr(transparent)] -#[derive(Copy,Clone,StableAbi)] -pub struct NulStr<'a>{ - ptr:NonNull, - _marker:PhantomData<&'a u8>, +#[derive(Copy, Clone, StableAbi)] +pub struct NulStr<'a> { + ptr: NonNull, + _marker: PhantomData<&'a u8>, } -unsafe impl Sync for NulStr<'_>{} -unsafe impl Send for NulStr<'_>{} +unsafe impl Sync for NulStr<'_> {} +unsafe impl Send for NulStr<'_> {} - -impl NulStr<'static>{ +impl NulStr<'static> { /// An empty string. - pub const EMPTY: Self = NulStr{ptr: ref_as_nonnull(&0), _marker: PhantomData}; + pub const EMPTY: Self = NulStr { + ptr: ref_as_nonnull(&0), + _marker: PhantomData, + }; } -impl<'a> NulStr<'a>{ +impl<'a> NulStr<'a> { /// Constructs an NulStr from a slice. - /// + /// /// # Safety - /// + /// /// `str` must be nul terminated(a 0 byte). - pub const unsafe fn from_str(str: &'a str) -> Self{ - Self{ + pub const unsafe fn from_str(str: &'a str) -> Self { + Self { ptr: NonNull::new_unchecked(str.as_ptr() as *mut u8), - _marker:PhantomData, + _marker: PhantomData, } } /// Constructs an NulStr from a pointer. - /// + /// /// # Safety - /// + /// /// The pointer must point to a utf8 and nul terminated (a 0 byte) sequence of bytes. - pub const unsafe fn from_ptr(ptr: *const u8) -> Self{ - Self{ + pub const unsafe fn from_ptr(ptr: *const u8) -> Self { + Self { ptr: NonNull::new_unchecked(ptr as *mut u8), - _marker:PhantomData, + _marker: PhantomData, } } @@ -61,11 +58,11 @@ impl<'a> NulStr<'a>{ /// /// # Performance /// - /// This conversion requires traversing through the entire string to + /// This conversion requires traversing through the entire string to /// find the nul byte. - pub fn to_str_with_nul(&self)->&'a str{ - unsafe{ - let bytes=std::ffi::CStr::from_ptr(self.ptr.as_ptr() as *const _).to_bytes_with_nul(); + pub fn to_str_with_nul(&self) -> &'a str { + unsafe { + let bytes = std::ffi::CStr::from_ptr(self.ptr.as_ptr() as *const _).to_bytes_with_nul(); std::str::from_utf8_unchecked(bytes) } } @@ -74,9 +71,9 @@ impl<'a> NulStr<'a>{ /// /// # Performance /// - /// This conversion requires traversing through the entire string to + /// This conversion requires traversing through the entire string to /// find the nul byte. - pub fn to_rstr_with_nul(&self)->RStr<'a>{ + pub fn to_rstr_with_nul(&self) -> RStr<'a> { self.to_str_with_nul().into() } @@ -84,10 +81,10 @@ impl<'a> NulStr<'a>{ /// /// # Performance /// - /// This conversion requires traversing through the entire string to + /// This conversion requires traversing through the entire string to /// find the nul byte. - pub fn to_str(self)->&'a str{ - unsafe{ + pub fn to_str(self) -> &'a str { + unsafe { let bytes = std::ffi::CStr::from_ptr(self.ptr.as_ptr() as *const _).to_bytes(); std::str::from_utf8_unchecked(bytes) } @@ -97,33 +94,29 @@ impl<'a> NulStr<'a>{ /// /// # Performance /// - /// This conversion requires traversing through the entire string to + /// This conversion requires traversing through the entire string to /// find the nul byte. - pub fn to_rstr(self)->RStr<'a>{ + pub fn to_rstr(self) -> RStr<'a> { self.to_str().into() } } - -impl<'a> PartialEq for NulStr<'a>{ - fn eq(&self,other:&Self)->bool{ - self.ptr==other.ptr || - self.to_str()==other.to_str() +impl<'a> PartialEq for NulStr<'a> { + fn eq(&self, other: &Self) -> bool { + self.ptr == other.ptr || self.to_str() == other.to_str() } } -impl<'a> Eq for NulStr<'a>{} - - +impl<'a> Eq for NulStr<'a> {} impl Display for NulStr<'_> { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Display::fmt(self.to_str(),f) + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Display::fmt(self.to_str(), f) } } impl Debug for NulStr<'_> { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Debug::fmt(self.to_str(),f) + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Debug::fmt(self.to_str(), f) } } diff --git a/abi_stable/src/sabi_types/rmut.rs b/abi_stable/src/sabi_types/rmut.rs index 1f39eca1..cbf34311 100644 --- a/abi_stable/src/sabi_types/rmut.rs +++ b/abi_stable/src/sabi_types/rmut.rs @@ -1,51 +1,51 @@ use std::{ - fmt::{self,Display}, + fmt::{self, Display}, marker::PhantomData, ptr::NonNull, }; use crate::{ + pointer_trait::{AsMutPtr, AsPtr, CanTransmuteElement, GetPointerKind, PK_MutReference}, sabi_types::RRef, - pointer_trait::{AsPtr, AsMutPtr, CanTransmuteElement,GetPointerKind,PK_MutReference}, }; /// Equivalent to `&'a mut T`, /// which allows a few more operations without causing Undefined Behavior. -/// +/// /// # Purpose -/// +/// /// This type is used as the `&mut self` parameter in abi_stable trait objects -/// because it can be soundly transmuted +/// because it can be soundly transmuted /// to point to other smaller but compatible types, then back to the original type. -/// +/// /// This crate is tested with [miri] to detect bugs in unsafe code, /// which implements the [Stacked Borrows model]. /// Because that model forbids `&mut T` to `&mut ()` to `&mut T` transmutes /// (when `T` isn't zero-sized), /// it required defining `RMut` to allow a mutable-reference-like type that can be transmuted. -/// +/// /// # Example -/// +/// /// This example demonstrates how a simple `&mut dyn Any`-like type can be implemented. -/// +/// /// ```rust /// use abi_stable::{ /// marker_type::ErasedObject, /// std_types::UTypeId, /// RMut, /// }; -/// -/// fn main(){ +/// +/// fn main(){ /// let mut value = WithTypeId::new(5u32); /// let mut clone = value.clone(); /// let mut erased = value.erase(); -/// +/// /// assert_eq!(WithTypeId::downcast::(erased.reborrow()), None); /// assert_eq!(WithTypeId::downcast::(erased.reborrow()), None); /// assert_eq!(WithTypeId::downcast::(erased.reborrow()), Some(&mut clone)); /// } -/// -/// // `#[repr(C))]` with a trailing `T` field is required for soundly transmuting from +/// +/// // `#[repr(C))]` with a trailing `T` field is required for soundly transmuting from /// // `RMut<'a, WithTypeId>` to `RMut<'a, WithTypeId>`. /// #[repr(C)] /// #[derive(Debug, PartialEq, Clone)] @@ -53,7 +53,7 @@ use crate::{ /// type_id: UTypeId, /// value: T, /// } -/// +/// /// impl WithTypeId { /// pub fn new(value: T) -> Self /// where @@ -64,14 +64,14 @@ use crate::{ /// value, /// } /// } -/// +/// /// pub fn erase(&mut self) -> RMut<'_, WithTypeId> { /// unsafe{ RMut::new(self).transmute::>() } /// } /// } -/// +/// /// impl WithTypeId { -/// pub fn downcast(this: RMut<'_, Self>) -> Option<&mut WithTypeId> +/// pub fn downcast(this: RMut<'_, Self>) -> Option<&mut WithTypeId> /// where /// T: 'static /// { @@ -83,59 +83,52 @@ use crate::{ /// } /// } /// } -/// -/// +/// +/// /// ``` -/// +/// /// /// # Type Prefix -/// +/// /// A type parameter `U` is considered a prefix of `T` in all of these cases: -/// +/// /// - `U` is a zero-sized type with an alignment equal or lower than `T` -/// +/// /// - `U` is a `#[repr(transparent)]` wrapper over `T` -/// +/// /// - `U` and `T` are both `#[repr(C)]` structs, /// in which `T` starts with the fields of `U` in the same order, /// and `U` has an alignment equal to or lower than `T`. -/// +/// /// Please note that it can be unsound to transmute a non-local /// type if it has private fields, /// since it may assume it was constructed in a particular way. -/// +/// /// [Stacked Borrows model]: /// https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md -/// +/// /// [miri]: https://github.com/rust-lang/miri -/// +/// #[repr(transparent)] #[derive(StableAbi)] -#[sabi( - bound="T:'a", -)] -pub struct RMut<'a, T>{ +#[sabi(bound = "T:'a")] +pub struct RMut<'a, T> { ref_: NonNull, - _marker:PhantomData<&'a mut T>, + _marker: PhantomData<&'a mut T>, } impl<'a, T> Display for RMut<'a, T> where - T:Display + T: Display, { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Display::fmt(self.get(),f) + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Display::fmt(self.get(), f) } } -unsafe impl<'a, T> Sync for RMut<'a, T> -where &'a T:Sync -{} - -unsafe impl<'a, T> Send for RMut<'a, T> -where &'a T:Send -{} +unsafe impl<'a, T> Sync for RMut<'a, T> where &'a T: Sync {} +unsafe impl<'a, T> Send for RMut<'a, T> where &'a T: Send {} shared_impls! { mod=static_ref_impls @@ -144,9 +137,7 @@ shared_impls! { deref_approach=(method = get), } - -impl<'a, T> RMut<'a, T>{ - +impl<'a, T> RMut<'a, T> { /// Constructs this RMut from a mutable reference /// /// # Example @@ -160,14 +151,14 @@ impl<'a, T> RMut<'a, T>{ /// /// assert_eq!(*rmut.get(), 13); /// assert_eq!(foo, 13); - /// + /// /// ``` #[inline(always)] - pub fn new(ref_:&'a mut T)->Self{ - unsafe{ - Self{ + pub fn new(ref_: &'a mut T) -> Self { + unsafe { + Self { ref_: NonNull::new_unchecked(ref_), - _marker:PhantomData, + _marker: PhantomData, } } } @@ -186,7 +177,7 @@ impl<'a, T> RMut<'a, T>{ /// use abi_stable::RMut; /// /// let mut foo = 3u32; - /// // safety: + /// // safety: /// // `&mut foo` is casted to a pointer to a compatible type (`u32` to `i32`), /// // `rmut` is only used for the lifetime of foo, /// // and is the only active pointer to `foo` while it's used. @@ -195,84 +186,84 @@ impl<'a, T> RMut<'a, T>{ /// /// assert_eq!(*rmut.get(), -1); /// assert_eq!(foo, !0); - /// + /// /// ``` #[inline(always)] - pub unsafe fn from_raw(ref_:*mut T)->Self + pub unsafe fn from_raw(ref_: *mut T) -> Self where - T:'a, + T: 'a, { - Self{ + Self { ref_: NonNull::new_unchecked(ref_), - _marker:PhantomData, + _marker: PhantomData, } } /// Reborrows this `RMut`, with a shorter lifetime. - /// + /// /// This allows passing an `RMut` to functions multiple times, /// but with a shorter lifetime argument. - /// - /// # Example + /// + /// # Example /// /// ```rust /// use abi_stable::RMut; /// /// let mut foo = 3; /// let mut rmut = RMut::new(&mut foo); - /// + /// /// assert_eq!(mutate(rmut.reborrow()), 6); /// assert_eq!(mutate(rmut.reborrow()), 12); /// assert_eq!(mutate(rmut.reborrow()), 24); - /// + /// /// // last use of rmut, so it can be moved instead of being reborrowed. /// assert_eq!(mutate(rmut), 48); - /// + /// /// fn mutate(mut rmut: RMut<'_, u32>) -> u32 { /// *rmut.get_mut() *= 2; /// rmut.get_copy() /// } - /// + /// /// ``` #[inline(always)] pub fn reborrow(&mut self) -> RMut<'_, T> { - RMut{ + RMut { ref_: self.ref_, _marker: PhantomData, } } /// Reborrows this `RMut` into a shared reference. - /// + /// /// Note that because the reference reborrows this `RMut<'a, T>` - /// its lifetime argument is strictly smaller. + /// its lifetime argument is strictly smaller. /// To turn an `RMut<'a, T>` into a `&'a T` (with the same lifetime argument) /// you can use [`into_ref`](#method.into_ref). - /// - /// + /// + /// /// # Example - /// + /// /// ```rust /// use abi_stable::RMut; - /// + /// /// let mut val = 89; /// let rmut = RMut::new(&mut val); - /// + /// /// assert_eq!(rmut.get(), &89); - /// + /// /// ``` - /// + /// /// ### Lifetimes - /// + /// /// This demonstrates when `into_ref` works, but `get` doesn't. - /// + /// /// ```rust /// # use abi_stable::RMut; /// fn stuff<'a>(x: RMut<'a, i32>) -> &'a i32 { /// x.into_ref() /// } /// ``` - /// + /// /// This doesn't compile, because `get` reborrows `foo`. /// ```compile_fail /// # use abi_stable::RMut; @@ -281,90 +272,90 @@ impl<'a, T> RMut<'a, T>{ /// } /// ``` #[inline(always)] - pub fn get(&self)->&T{ - unsafe{ &*(self.ref_.as_ptr() as *const T) } + pub fn get(&self) -> &T { + unsafe { &*(self.ref_.as_ptr() as *const T) } } /// Copies the value that this `RMut` points to. - /// + /// /// # Example - /// + /// /// ```rust /// use abi_stable::RMut; - /// + /// /// let mut val = "hello"; /// let mut rmut = RMut::new(&mut val); - /// + /// /// *rmut.get_mut() = "world"; - /// + /// /// assert_eq!(rmut.get_copy(), "world"); - /// + /// /// ``` #[inline(always)] pub fn get_copy(&self) -> T where - T: Copy + T: Copy, { - unsafe{ *(self.ref_.as_ptr() as *const T) } + unsafe { *(self.ref_.as_ptr() as *const T) } } /// Converts this `RMut<'a, T>` into a `&'a T` - /// + /// /// # Example - /// + /// /// ```rust /// use abi_stable::RMut; - /// + /// /// let mut val = 89; - /// + /// /// assert_eq!(mutate(RMut::new(&mut val)), &44); - /// + /// /// fn mutate(mut rmut: RMut<'_, u32>) -> &u32 { /// *rmut.get_mut() /= 2; /// rmut.into_ref() /// } - /// + /// /// ``` /// #[inline(always)] - pub fn into_ref(self) -> &'a T{ - unsafe{ &*(self.ref_.as_ptr() as *const T) } + pub fn into_ref(self) -> &'a T { + unsafe { &*(self.ref_.as_ptr() as *const T) } } /// Reborrows this `RMut` into a mutable reference. - /// + /// /// Note that because the mutable reference reborrows this `RMut<'a, T>` - /// its lifetime argument is strictly smaller. + /// its lifetime argument is strictly smaller. /// To turn an `RMut<'a, T>` into a `&'a mut T` (with the same lifetime argument) /// you can use [`into_mut`](#method.into_mut). - /// + /// /// # Example - /// + /// /// ```rust /// use abi_stable::RMut; - /// + /// /// let mut val = 89; /// let mut rmut = RMut::new(&mut val); - /// + /// /// assert_eq!(rmut.get_mut(), &mut 89); - /// + /// /// *rmut.get_mut() += 10; - /// + /// /// assert_eq!(rmut.get_mut(), &mut 99); - /// + /// /// ``` - /// + /// /// ### Lifetimes - /// + /// /// This demonstrates when `into_mut` works, but `get_mut` doesn't. - /// + /// /// ```rust /// # use abi_stable::RMut; /// fn stuff<'a>(x: RMut<'a, i32>) -> &'a mut i32 { /// x.into_mut() /// } /// ``` - /// + /// /// This doesn't compile, because `get_mut` reborrows `foo`. /// ```compile_fail /// # use abi_stable::RMut; @@ -373,62 +364,62 @@ impl<'a, T> RMut<'a, T>{ /// } /// ``` #[inline(always)] - pub fn get_mut(&mut self)->&mut T{ - unsafe{ &mut *self.ref_.as_ptr() } + pub fn get_mut(&mut self) -> &mut T { + unsafe { &mut *self.ref_.as_ptr() } } /// Converts this `RMut<'a, T>` into a `&'a mut T` - /// + /// /// # Example - /// + /// /// ```rust /// use abi_stable::RMut; - /// + /// /// let mut val = 13; - /// + /// /// let rmut = RMut::new(&mut val); - /// + /// /// assert_eq!(rmut.get(), &13); - /// + /// /// *rmut.into_mut() += 8; - /// + /// /// assert_eq!(val, 21); - /// + /// /// ``` #[inline(always)] - pub fn into_mut(self)->&'a mut T{ - unsafe{ &mut *self.ref_.as_ptr() } + pub fn into_mut(self) -> &'a mut T { + unsafe { &mut *self.ref_.as_ptr() } } /// Reborrows this `RMut` as a const raw pointer. - /// + /// /// # Example - /// + /// /// ```rust /// use abi_stable::RMut; - /// + /// /// let mut val = 34; /// let rmut = RMut::new(&mut val); - /// + /// /// unsafe{ /// assert_eq!(*rmut.as_ptr(), 34); /// } /// ``` #[inline] - pub fn as_ptr(&self)->*const T{ + pub fn as_ptr(&self) -> *const T { self.ref_.as_ptr() } /// Reborrows this `RMut` as a mutable raw pointer. /// /// # Example - /// + /// /// ```rust /// use abi_stable::RMut; - /// + /// /// let mut val = 34; /// let mut rmut = RMut::new(&mut val); - /// + /// /// unsafe{ /// rmut.as_mut_ptr().write(7); /// @@ -438,20 +429,20 @@ impl<'a, T> RMut<'a, T>{ /// } /// ``` #[inline] - pub fn as_mut_ptr(&mut self)->*mut T{ + pub fn as_mut_ptr(&mut self) -> *mut T { self.ref_.as_ptr() } /// Converts this `RMut<'a, T>` into a `*mut T` /// /// # Example - /// + /// /// ```rust /// use abi_stable::RMut; - /// + /// /// let mut val = 89; /// let rmut = RMut::new(&mut val); - /// + /// /// unsafe{ /// let ptr = rmut.into_raw(); /// @@ -463,32 +454,32 @@ impl<'a, T> RMut<'a, T>{ /// } /// ``` #[inline] - pub fn into_raw(self)->*mut T{ + pub fn into_raw(self) -> *mut T { self.ref_.as_ptr() } /// Transmutes this `RMut<'a, T>` to a `*mut U`. /// /// # Example - /// + /// /// ```rust /// use abi_stable::RMut; - /// + /// /// let mut val = Direction::Up; /// let rmut = RMut::new(&mut val); - /// + /// /// assert_eq!(rmut.get(), &Direction::Up); - /// - /// let ptr = rmut.transmute_into_raw::(); - /// + /// + /// let ptr = rmut.transmute_into_raw::(); + /// /// unsafe { /// assert_eq!(*ptr, 2); /// *ptr = 3; /// } - /// + /// /// assert_eq!(val, Direction::Down); - /// - /// + /// + /// /// #[repr(u8)] /// #[derive(Debug, PartialEq)] /// enum Direction { @@ -497,10 +488,10 @@ impl<'a, T> RMut<'a, T>{ /// Up = 2, /// Down = 3, /// } - /// + /// /// ``` #[inline(always)] - pub fn transmute_into_raw(self)->*mut U{ + pub fn transmute_into_raw(self) -> *mut U { self.ref_.as_ptr() as *mut U } @@ -509,32 +500,32 @@ impl<'a, T> RMut<'a, T>{ /// # Safety /// /// Either of these must be the case: - /// + /// /// - [`U` is a prefix of `T`](#type-prefix-exp) - /// + /// /// - `RMut<'a, U>` was the original type of this `RMut<'a, T>`. /// /// # Example - /// + /// /// ```rust /// use abi_stable::RMut; - /// + /// /// let mut val = 13u8; /// let rmut = RMut::new(&mut val); - /// + /// /// assert_eq!(rmut.get(), &13); - /// + /// /// unsafe{ /// *rmut.transmute_into_mut::() = -1; /// } - /// + /// /// assert_eq!(val, 255); - /// + /// /// ``` #[inline(always)] - pub unsafe fn transmute_into_mut(self)->&'a mut U + pub unsafe fn transmute_into_mut(self) -> &'a mut U where - U:'a, + U: 'a, { &mut *(self.ref_.as_ptr() as *mut U) } @@ -544,36 +535,36 @@ impl<'a, T> RMut<'a, T>{ /// # Safety /// /// Either of these must be the case: - /// + /// /// - [`U` is a prefix of `T`](#type-prefix-exp) - /// + /// /// - `RMut<'a, U>` was the original type of this `RMut<'a, T>`. /// /// # Example - /// + /// /// ```rust /// use abi_stable::RMut; - /// + /// /// let mut val: [u32; 3] = [2, 3, 0]; /// let mut rmut = RMut::new(&mut val); - /// + /// /// unsafe{ /// // safety: /// // it's sound to transmute mutable references of arrays into shorter arrays. - /// // + /// // /// // The `.reborrow()` prevents the `rmut` from being consumed. /// compute_next(rmut.reborrow().transmute::<[u32; 2]>()); /// assert_eq!(rmut.get_copy(), [3, 5, 0]); - /// + /// /// compute_next(rmut.reborrow().transmute::<[u32; 2]>()); /// assert_eq!(rmut.get_copy(), [5, 8, 0]); - /// + /// /// // last use of `rmut`, so no need to reborrow /// compute_next(rmut.transmute::<[u32; 2]>()); /// } /// /// assert_eq!(val, [8, 13, 0]); - /// + /// /// fn compute_next(rmut: RMut<'_, [u32; 2]>) { /// let [v0, v1] = rmut.into_mut(); /// let next = *v0 + *v1; @@ -581,61 +572,55 @@ impl<'a, T> RMut<'a, T>{ /// } /// ``` #[inline(always)] - pub unsafe fn transmute(self)->RMut<'a,U> + pub unsafe fn transmute(self) -> RMut<'a, U> where - U:'a, + U: 'a, { - RMut::from_raw( - self.ref_.as_ptr() as *mut U - ) + RMut::from_raw(self.ref_.as_ptr() as *mut U) } - + /// Reborrows this `RMut<'a, T>` into an `RRef<'_, T>` - /// + /// /// # Example - /// + /// /// ```rust /// use abi_stable::{RRef, RMut}; - /// + /// /// let mut val = 77; /// let rmut = RMut::new(&mut val); - /// + /// /// for _ in 0..10 { /// assertion(rmut.as_rref()); /// } - /// + /// /// fn assertion(rref: RRef<'_, u32>) { /// assert_eq!(rref.get_copy(), 77); /// } /// ``` #[inline(always)] pub fn as_rref<'r>(&'r self) -> RRef<'r, T> { - unsafe{ - RRef::from_raw(self.ref_.as_ptr()) - } + unsafe { RRef::from_raw(self.ref_.as_ptr()) } } /// Converts this `RMut<'a, T>` to an `RRef<'_, T>` - /// + /// /// # Example - /// + /// /// ```rust /// use abi_stable::{RRef, RMut}; - /// + /// /// let mut val = 0; /// let rmut = RMut::new(&mut val); - /// + /// /// assertion(rmut.into_rref()); - /// + /// /// fn assertion(rref: RRef<'_, u32>) { /// assert_eq!(rref.get_copy(), 0); /// } /// ``` #[inline(always)] pub fn into_rref(self) -> RRef<'a, T> { - unsafe{ - RRef::from_raw(self.ref_.as_ptr()) - } + unsafe { RRef::from_raw(self.ref_.as_ptr()) } } } @@ -646,7 +631,7 @@ unsafe impl<'a, T> AsPtr for RMut<'a, T> { } #[inline(always)] fn as_rref(&self) -> RRef<'_, T> { - unsafe{ RRef::from_raw(self.ref_.as_ptr() as *const T) } + unsafe { RRef::from_raw(self.ref_.as_ptr() as *const T) } } } @@ -662,18 +647,17 @@ unsafe impl<'a, T> AsMutPtr for RMut<'a, T> { } } - -unsafe impl<'a, T> GetPointerKind for RMut<'a, T>{ - type Kind=PK_MutReference; +unsafe impl<'a, T> GetPointerKind for RMut<'a, T> { + type Kind = PK_MutReference; type PtrTarget = T; } -unsafe impl<'a,T,U> CanTransmuteElement for RMut<'a, T> +unsafe impl<'a, T, U> CanTransmuteElement for RMut<'a, T> where - U:'a, + U: 'a, { - type TransmutedPtr= RMut<'a,U>; + type TransmutedPtr = RMut<'a, U>; #[inline(always)] unsafe fn transmute_element_(self) -> Self::TransmutedPtr { @@ -681,15 +665,13 @@ where } } - - #[cfg(test)] mod tests { use super::*; #[test] - fn construction_test(){ - unsafe{ + fn construction_test() { + unsafe { let val: *mut i32 = &mut 3; let mut rmut = RMut::from_raw(val); *rmut.get_mut() += 5; @@ -704,20 +686,20 @@ mod tests { } #[test] - fn access(){ + fn access() { let mut num = 5; - let mut mutref= RMut::new(&mut num); - + let mut mutref = RMut::new(&mut num); + assert_eq!(*mutref.get_mut(), 5); *mutref.get_mut() = 21; - + assert_eq!(*mutref.get(), 21); assert_eq!(mutref.get_copy(), 21); assert_eq!(*mutref.reborrow().into_ref(), 21); *mutref.reborrow().into_mut() = 34; - unsafe{ + unsafe { assert_eq!(*mutref.as_ptr(), 34); *mutref.as_mut_ptr() = 55; @@ -729,10 +711,10 @@ mod tests { } #[test] - fn transmutes(){ + fn transmutes() { let mut num = 0u8; - unsafe{ + unsafe { let ptr = RMut::new(&mut num).transmute_into_raw::(); assert_eq!(*ptr, Enum::Foo); @@ -740,7 +722,7 @@ mod tests { assert_eq!(*ptr, Enum::Bar); assert_eq!(num, 1); } - unsafe{ + unsafe { let mref = RMut::new(&mut num).transmute_into_mut::(); assert_eq!(*mref, Enum::Bar); @@ -748,7 +730,7 @@ mod tests { assert_eq!(*mref, Enum::Qux); assert_eq!(num, 2); } - unsafe{ + unsafe { let mut rmut = RMut::new(&mut num).transmute::(); assert_eq!(rmut, RMut::new(&mut Enum::Qux)); @@ -756,7 +738,7 @@ mod tests { assert_eq!(*rmut.get(), Enum::Foo); assert_eq!(num, 0); } - unsafe{ + unsafe { let mut rmut: RMut<'_, Enum> = RMut::new(&mut num).transmute_element_(); assert_eq!(rmut, RMut::new(&mut Enum::Foo)); @@ -772,7 +754,7 @@ mod tests { assert_eq!(rmut.as_rref(), RRef::new(&0)); assert_eq!(rmut.reborrow().into_rref(), RRef::new(&0)); - + assert_eq!(rmut.as_rmut(), RMut::new(&mut 0)); } @@ -784,5 +766,3 @@ mod tests { Qux = 2, } } - - diff --git a/abi_stable/src/sabi_types/rref.rs b/abi_stable/src/sabi_types/rref.rs index 45e411df..895428d3 100644 --- a/abi_stable/src/sabi_types/rref.rs +++ b/abi_stable/src/sabi_types/rref.rs @@ -1,49 +1,49 @@ use std::{ - fmt::{self,Display}, + fmt::{self, Display}, marker::PhantomData, ptr::NonNull, }; use crate::{ - pointer_trait::{AsPtr, CanTransmuteElement,GetPointerKind,PK_Reference}, + pointer_trait::{AsPtr, CanTransmuteElement, GetPointerKind, PK_Reference}, utils::ref_as_nonnull, }; /// Equivalent to `&'a T`, /// which allows a few more operations without causing Undefined Behavior. -/// +/// /// # Purpose -/// +/// /// This type is used as the `&self` parameter in abi_stable trait objects -/// because it can be soundly transmuted +/// because it can be soundly transmuted /// to point to other smaller but compatible types, then back to the original type. -/// +/// /// This crate is tested with [miri] to detect bugs in unsafe code, /// which implements the [Stacked Borrows model]. /// Because that model forbids `&T` to `&()` to `&T` transmutes (when `T` isn't zero-sized), /// it required defining `RRef` to allow a reference-like type that can be transmuted. -/// +/// /// # Example -/// +/// /// This example demonstrates how a simple `&dyn Any`-like type can be implemented. -/// +/// /// ```rust /// use abi_stable::{ /// marker_type::ErasedObject, /// std_types::UTypeId, /// RRef, /// }; -/// -/// fn main(){ +/// +/// fn main(){ /// let value = WithTypeId::new(5u32); /// let erased = value.erase(); -/// +/// /// assert_eq!(WithTypeId::downcast::(erased), None); /// assert_eq!(WithTypeId::downcast::(erased), None); /// assert_eq!(WithTypeId::downcast::(erased), Some(&value)); /// } -/// -/// // `#[repr(C))]` with a trailing `T` field is required for soundly transmuting from +/// +/// // `#[repr(C))]` with a trailing `T` field is required for soundly transmuting from /// // `RRef<'a, WithTypeId>` to `RRef<'a, WithTypeId>`. /// #[repr(C)] /// #[derive(Debug, PartialEq)] @@ -51,7 +51,7 @@ use crate::{ /// type_id: UTypeId, /// value: T, /// } -/// +/// /// impl WithTypeId { /// pub fn new(value: T) -> Self /// where @@ -62,14 +62,14 @@ use crate::{ /// value, /// } /// } -/// +/// /// pub fn erase(&self) -> RRef<'_, WithTypeId> { /// unsafe{ RRef::new(self).transmute::>() } /// } /// } -/// +/// /// impl WithTypeId { -/// pub fn downcast(this: RRef<'_, Self>) -> Option<&WithTypeId> +/// pub fn downcast(this: RRef<'_, Self>) -> Option<&WithTypeId> /// where /// T: 'static /// { @@ -81,68 +81,60 @@ use crate::{ /// } /// } /// } -/// -/// +/// +/// /// ``` -/// +/// /// /// # Type Prefix -/// +/// /// A type parameter `U` is considered a prefix of `T` in all of these cases: -/// +/// /// - `U` is a zero-sized type with an alignment equal or lower than `T` -/// +/// /// - `U` is a `#[repr(transparent)]` wrapper over `T` -/// +/// /// - `U` and `T` are both `#[repr(C)]` structs, /// in which `T` starts with the fields of `U` in the same order, /// and `U` has an alignment equal to or lower than `T`. -/// +/// /// Please note that it can be unsound to transmute a non-local /// type if it has private fields, /// since it may assume it was constructed in a particular way. -/// +/// /// [Stacked Borrows model]: /// https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md -/// +/// /// [miri]: https://github.com/rust-lang/miri -/// +/// #[repr(transparent)] #[derive(StableAbi)] -#[sabi( - bound="T:'a", -)] -pub struct RRef<'a,T>{ +#[sabi(bound = "T:'a")] +pub struct RRef<'a, T> { ref_: NonNull, - _marker:PhantomData<&'a T>, + _marker: PhantomData<&'a T>, } -impl<'a,T> Display for RRef<'a,T> +impl<'a, T> Display for RRef<'a, T> where - T:Display + T: Display, { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Display::fmt(self.get(), f) } } - -impl<'a,T> Clone for RRef<'a,T>{ - fn clone(&self)->Self{ +impl<'a, T> Clone for RRef<'a, T> { + fn clone(&self) -> Self { *self } } -impl<'a,T> Copy for RRef<'a,T>{} - -unsafe impl<'a,T> Sync for RRef<'a,T> -where &'a T:Sync -{} +impl<'a, T> Copy for RRef<'a, T> {} -unsafe impl<'a,T> Send for RRef<'a,T> -where &'a T:Send -{} +unsafe impl<'a, T> Sync for RRef<'a, T> where &'a T: Sync {} +unsafe impl<'a, T> Send for RRef<'a, T> where &'a T: Send {} shared_impls! { mod=static_ref_impls @@ -151,8 +143,7 @@ shared_impls! { deref_approach=(method = get), } - -impl<'a,T> RRef<'a,T>{ +impl<'a, T> RRef<'a, T> { /// Constructs this RRef from a reference. /// /// # Example @@ -171,10 +162,10 @@ impl<'a,T> RRef<'a,T>{ /// /// ``` #[inline(always)] - pub const fn new(ref_:&'a T)->Self{ - Self{ + pub const fn new(ref_: &'a T) -> Self { + Self { ref_: ref_as_nonnull(ref_), - _marker:PhantomData, + _marker: PhantomData, } } @@ -202,68 +193,68 @@ impl<'a,T> RRef<'a,T>{ /// /// ``` #[inline(always)] - pub const unsafe fn from_raw(ref_:*const T)->Self + pub const unsafe fn from_raw(ref_: *const T) -> Self where - T:'a, + T: 'a, { - Self{ + Self { ref_: NonNull::new_unchecked(ref_ as *mut T), - _marker:PhantomData, + _marker: PhantomData, } } /// Casts this to an equivalent reference. /// /// # Example - /// + /// /// ```rust /// use abi_stable::RRef; - /// + /// /// let rref = RRef::new(&89); - /// + /// /// assert_eq!(rref.get(), &89); - /// + /// /// ``` #[inline(always)] - pub fn get(self) -> &'a T{ - unsafe{ &*(self.ref_.as_ptr() as *const T) } + pub fn get(self) -> &'a T { + unsafe { &*(self.ref_.as_ptr() as *const T) } } /// Copies the value that this points to. - /// + /// /// # Example - /// + /// /// ```rust /// use abi_stable::RRef; - /// + /// /// let rref = RRef::new(&55); - /// + /// /// assert_eq!(rref.get_copy(), 55); - /// + /// /// ``` #[inline(always)] - pub fn get_copy(self) -> T - where - T: Copy + pub fn get_copy(self) -> T + where + T: Copy, { - unsafe{ *(self.ref_.as_ptr() as *const T) } + unsafe { *(self.ref_.as_ptr() as *const T) } } /// Casts this to an equivalent raw pointer. /// /// # Example - /// + /// /// ```rust /// use abi_stable::RRef; - /// + /// /// let rref = RRef::new(&89); - /// + /// /// unsafe{ /// assert_eq!(*rref.as_ptr(), 89); /// } /// ``` #[inline(always)] - pub const fn as_ptr(self) -> *const T{ + pub const fn as_ptr(self) -> *const T { self.ref_.as_ptr() as *const T } @@ -272,11 +263,11 @@ impl<'a,T> RRef<'a,T>{ /// # Safety /// /// Either of these must be the case: - /// + /// /// - [`U` is a prefix of `T`](#type-prefix-exp) - /// + /// /// - `RRef<'a, U>` was the original type of this `RRef<'a, T>`. - /// + /// /// # Example /// /// ``` @@ -288,24 +279,22 @@ impl<'a,T> RRef<'a,T>{ /// /// // safety: Wrapping is a `#[repr(transparent)]` wrapper with one `pub` field. /// let trans = unsafe{ rref.transmute::>() }; - /// + /// /// assert_eq!(trans, RRef::new(&Wrapping(13u32))); - /// + /// /// /// ``` #[inline(always)] - pub const unsafe fn transmute(self)->RRef<'a,U> + pub const unsafe fn transmute(self) -> RRef<'a, U> where - U:'a, + U: 'a, { - RRef::from_raw( - self.ref_.as_ptr() as *const U - ) + RRef::from_raw(self.ref_.as_ptr() as *const U) } /// Transmutes this to a raw pointer pointing to a different type. #[inline(always)] - pub const fn transmute_into_raw(self)->*const U{ + pub const fn transmute_into_raw(self) -> *const U { self.ref_.as_ptr() as *const T as *const U } @@ -314,11 +303,11 @@ impl<'a,T> RRef<'a,T>{ /// # Safety /// /// Either of these must be the case: - /// + /// /// - [`U` is a prefix of `T`](#type-prefix-exp) - /// + /// /// - `RRef<'a, U>` was the original type of this `RRef<'a, T>`. - /// + /// /// # Example /// /// ```rust @@ -334,26 +323,25 @@ impl<'a,T> RRef<'a,T>{ /// /// ``` #[inline(always)] - pub unsafe fn transmute_into_ref(self) -> &'a U + pub unsafe fn transmute_into_ref(self) -> &'a U where - U: 'a + U: 'a, { &*(self.ref_.as_ptr() as *const T as *const U) } - } -unsafe impl<'a,T> GetPointerKind for RRef<'a,T>{ - type Kind=PK_Reference; +unsafe impl<'a, T> GetPointerKind for RRef<'a, T> { + type Kind = PK_Reference; type PtrTarget = T; } -unsafe impl<'a,T,U> CanTransmuteElement for RRef<'a,T> +unsafe impl<'a, T, U> CanTransmuteElement for RRef<'a, T> where - U:'a, + U: 'a, { - type TransmutedPtr = RRef<'a,U>; + type TransmutedPtr = RRef<'a, U>; #[inline(always)] unsafe fn transmute_element_(self) -> Self::TransmutedPtr { @@ -373,14 +361,13 @@ unsafe impl AsPtr for RRef<'_, T> { } } - #[cfg(test)] mod tests { use super::*; #[test] - fn construction_test(){ - unsafe{ + fn construction_test() { + unsafe { let three: *const i32 = &3; assert_eq!(RRef::from_raw(three).get_copy(), 3); } @@ -389,21 +376,21 @@ mod tests { } #[test] - fn access(){ + fn access() { let reference = RRef::new(&8); - + assert_eq!(*reference.get(), 8); assert_eq!(reference.get_copy(), 8); - unsafe{ + unsafe { assert_eq!(*reference.as_ptr(), 8); } } #[test] - fn transmutes(){ + fn transmutes() { let reference = RRef::new(&(!0u32)); - unsafe{ + unsafe { assert_eq!(reference.transmute::().get_copy(), -1); assert_eq!(*reference.transmute_into_raw::(), -1); assert_eq!(reference.transmute_into_ref::(), &-1); @@ -411,14 +398,12 @@ mod tests { } #[test] - fn as_ptr_impl(){ + fn as_ptr_impl() { let reference = RRef::new(&89u32); - unsafe{ + unsafe { assert_eq!(*AsPtr::as_ptr(&reference), 89); assert_eq!(AsPtr::as_rref(&reference), reference); } } } - - diff --git a/abi_stable/src/sabi_types/rsmallbox.rs b/abi_stable/src/sabi_types/rsmallbox.rs index 7a45c0af..898119c1 100644 --- a/abi_stable/src/sabi_types/rsmallbox.rs +++ b/abi_stable/src/sabi_types/rsmallbox.rs @@ -4,184 +4,181 @@ Contains the `RSmallBox<_>` type. use crate::{ pointer_trait::{ - AsPtr, AsMutPtr, CallReferentDrop,Deallocate,CanTransmuteElement, - GetPointerKind,PK_SmartPointer,OwnedPointer, + AsMutPtr, AsPtr, CallReferentDrop, CanTransmuteElement, Deallocate, GetPointerKind, + OwnedPointer, PK_SmartPointer, }, sabi_types::MovePtr, std_types::RBox, }; use std::{ - alloc::{self,Layout}, - fmt::{self,Display}, + alloc::{self, Layout}, + fmt::{self, Display}, marker::PhantomData, - mem::{self,ManuallyDrop}, - ops::{Deref,DerefMut}, + mem::{self, ManuallyDrop}, + ops::{Deref, DerefMut}, ptr, }; #[allow(unused_imports)] use core_extensions::SelfOps; -use serde::{Serialize,Deserialize,Serializer,Deserializer}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; - -pub use crate::inline_storage::{alignment,InlineStorage}; use crate::inline_storage::ScratchSpace; - +pub use crate::inline_storage::{alignment, InlineStorage}; pub use self::private::RSmallBox; -mod private{ +mod private { use super::*; + /** + + A box type which stores small values inline as an optimization. + + # Inline storage + + The `Inline` type parameter + is the storage space on the stack (as in inline with the `RSmallBox` struct) + where small values get stored,instead of storing them on the heap. + + It has to have an alignment greater than or equal to the value being stored, + otherwise storing the value on the heap. + + To ensure that the inline storage has enough alignemnt you can use one of the + `AlignTo*` types from the (reexported) alignment submodule, + or from `abi_stable::inline_storage::alignment`. + + # Examples + + ### In a nonexhaustive enum + + Using an RSmallBox to store a generic type in a nonexhaustive enum. + + ``` + use abi_stable::{ + sabi_types::RSmallBox, + std_types::RString, + reexports::SelfOps, + StableAbi, + }; + + #[repr(u8)] + #[derive(StableAbi,Debug,Clone,PartialEq)] + #[sabi(kind(WithNonExhaustive( + // Determines the maximum size of this enum in semver compatible versions. + // This is 7 usize large because: + // - The enum discriminant occupies 1 usize(because the enum is usize aligned). + // - RSmallBox: is 6 usize large + size="[usize;7]", + // Determines the traits that are required when wrapping this enum in NonExhaustive, + // and are then available with it. + traits(Debug,Clone,PartialEq), + )))] + pub enum SomeEnum{ + #[doc(hidden)] + __NonExhaustive, + Foo, + Bar, + // This variant was added in a newer (compatible) version of the library. + Baz(RSmallBox) + } -/** - -A box type which stores small values inline as an optimization. - -# Inline storage - -The `Inline` type parameter -is the storage space on the stack (as in inline with the `RSmallBox` struct) -where small values get stored,instead of storing them on the heap. - -It has to have an alignment greater than or equal to the value being stored, -otherwise storing the value on the heap. - -To ensure that the inline storage has enough alignemnt you can use one of the -`AlignTo*` types from the (reexported) alignment submodule, -or from `abi_stable::inline_storage::alignment`. - -# Examples - -### In a nonexhaustive enum - -Using an RSmallBox to store a generic type in a nonexhaustive enum. - -``` -use abi_stable::{ - sabi_types::RSmallBox, - std_types::RString, - reexports::SelfOps, - StableAbi, -}; - -#[repr(u8)] -#[derive(StableAbi,Debug,Clone,PartialEq)] -#[sabi(kind(WithNonExhaustive( - // Determines the maximum size of this enum in semver compatible versions. - // This is 7 usize large because: - // - The enum discriminant occupies 1 usize(because the enum is usize aligned). - // - RSmallBox: is 6 usize large - size="[usize;7]", - // Determines the traits that are required when wrapping this enum in NonExhaustive, - // and are then available with it. - traits(Debug,Clone,PartialEq), -)))] -pub enum SomeEnum{ - #[doc(hidden)] - __NonExhaustive, - Foo, - Bar, - // This variant was added in a newer (compatible) version of the library. - Baz(RSmallBox) -} + impl SomeEnum{ + pub fn is_inline(&self)->bool{ + match self { + SomeEnum::__NonExhaustive=>true, + SomeEnum::Foo=>true, + SomeEnum::Bar=>true, + SomeEnum::Baz(rsbox)=>RSmallBox::is_inline(rsbox), + } + } -impl SomeEnum{ - pub fn is_inline(&self)->bool{ - match self { - SomeEnum::__NonExhaustive=>true, - SomeEnum::Foo=>true, - SomeEnum::Bar=>true, - SomeEnum::Baz(rsbox)=>RSmallBox::is_inline(rsbox), + pub fn is_heap_allocated(&self)->bool{ + !self.is_inline() } - } - pub fn is_heap_allocated(&self)->bool{ - !self.is_inline() } -} - - -#[repr(C)] -#[derive(StableAbi,Debug,Clone,PartialEq)] -pub struct FullName{ - pub name:RString, - pub surname:RString, -} -# fn main(){ + #[repr(C)] + #[derive(StableAbi,Debug,Clone,PartialEq)] + pub struct FullName{ + pub name:RString, + pub surname:RString, + } -let rstring="Oh boy!" - .piped(RString::from) - .piped(RSmallBox::new) - .piped(SomeEnum::Baz); + # fn main(){ -let full_name= - FullName{ name:"R__e".into(), surname:"L_____e".into() } + let rstring="Oh boy!" + .piped(RString::from) .piped(RSmallBox::new) .piped(SomeEnum::Baz); + let full_name= + FullName{ name:"R__e".into(), surname:"L_____e".into() } + .piped(RSmallBox::new) + .piped(SomeEnum::Baz); -assert!( rstring.is_inline() ); -assert!( full_name.is_heap_allocated() ); + assert!( rstring.is_inline() ); + assert!( full_name.is_heap_allocated() ); -# } -``` + # } -### Trying out different `Inline` type parameters + ``` -This example demonstrates how changing the `Inline` type parameter can -change whether an RString is stored inline or on the heap. + ### Trying out different `Inline` type parameters -``` -use abi_stable::{ - inline_storage::alignment::AlignToUsize, - sabi_types::RSmallBox, - std_types::RString, - StableAbi, -}; + This example demonstrates how changing the `Inline` type parameter can + change whether an RString is stored inline or on the heap. -use std::mem; + ``` + use abi_stable::{ + inline_storage::alignment::AlignToUsize, + sabi_types::RSmallBox, + std_types::RString, + StableAbi, + }; -type JustRightInlineBox= - RSmallBox()*4 ]>>; + use std::mem; -let string=RString::from("What is that supposed to mean?"); + type JustRightInlineBox= + RSmallBox()*4 ]>>; -let small=RSmallBox::<_,[usize;3]>::new(string.clone()); -let medium=RSmallBox::<_,[usize;4]>::new(string.clone()); -let large=RSmallBox::<_,[usize;16]>::new(string.clone()); -let not_enough_alignment=RSmallBox::<_,[u8;64]>::new(string.clone()); -let just_right=JustRightInlineBox::new(string.clone()); + let string=RString::from("What is that supposed to mean?"); + let small=RSmallBox::<_,[usize;3]>::new(string.clone()); + let medium=RSmallBox::<_,[usize;4]>::new(string.clone()); + let large=RSmallBox::<_,[usize;16]>::new(string.clone()); + let not_enough_alignment=RSmallBox::<_,[u8;64]>::new(string.clone()); + let just_right=JustRightInlineBox::new(string.clone()); -assert!( RSmallBox::is_heap_allocated(&small) ); -assert!( RSmallBox::is_inline(&medium) ); -assert!( RSmallBox::is_inline(&large) ); -assert!( RSmallBox::is_heap_allocated(¬_enough_alignment) ); -assert!( RSmallBox::is_inline(&just_right) ); -``` + assert!( RSmallBox::is_heap_allocated(&small) ); + assert!( RSmallBox::is_inline(&medium) ); + assert!( RSmallBox::is_inline(&large) ); + assert!( RSmallBox::is_heap_allocated(¬_enough_alignment) ); + assert!( RSmallBox::is_inline(&just_right) ); -*/ + ``` + + */ #[repr(C)] #[derive(StableAbi)] #[sabi(not_stableabi(Inline))] - pub struct RSmallBox{ + pub struct RSmallBox { // This is an opaque field since we only care about its size and alignment #[sabi(unsafe_opaque_field)] - inline:ScratchSpace, - ptr:*mut T, - destroy: unsafe extern "C" fn(*mut T, CallReferentDrop,Deallocate), - _marker:PhantomData + inline: ScratchSpace, + ptr: *mut T, + destroy: unsafe extern "C" fn(*mut T, CallReferentDrop, Deallocate), + _marker: PhantomData, } - impl RSmallBox{ + impl RSmallBox { /// Constructs this RSmallBox from a value. /// /// # Example @@ -191,21 +188,19 @@ assert!( RSmallBox::is_inline(&just_right) ); /// sabi_types::RSmallBox, /// std_types::RString, /// }; - /// + /// /// let xbox=RSmallBox::<_,[usize;4]>::new(RString::from("one")); - /// + /// /// /// ``` #[inline] - pub fn new(value:T)->RSmallBox + pub fn new(value: T) -> RSmallBox where - Inline:InlineStorage + Inline: InlineStorage, { - let mut value=ManuallyDrop::new(value); + let mut value = ManuallyDrop::new(value); - unsafe{ - RSmallBox::from_move_ptr(MovePtr::new(&mut *value)) - } + unsafe { RSmallBox::from_move_ptr(MovePtr::new(&mut *value)) } } /// Gets a raw pointer into the underlying data. @@ -217,20 +212,20 @@ assert!( RSmallBox::is_inline(&just_right) ); /// sabi_types::RSmallBox, /// std_types::RString, /// }; - /// + /// /// let mut play=RSmallBox::<_,[usize;4]>::new(RString::from("station")); - /// + /// /// let play_addr=&mut play as *mut RSmallBox<_,_> as usize; /// let heap_addr=RSmallBox::as_mut_ptr(&mut play) as usize; - /// + /// /// assert_eq!(play_addr,heap_addr); /// /// ``` #[inline] - pub fn as_mut_ptr(this:&mut Self)->*mut T{ + pub fn as_mut_ptr(this: &mut Self) -> *mut T { if this.ptr.is_null() { &mut this.inline as *mut ScratchSpace as *mut T - }else{ + } else { this.ptr } } @@ -245,22 +240,22 @@ assert!( RSmallBox::is_inline(&just_right) ); /// reexports::SelfOps, /// std_types::RVec, /// }; - /// + /// /// let mut generations=vec![1,2,3,4,5,6,7,8] /// .piped(RVec::from) /// .piped(RSmallBox::<_,[usize;2]>::new); - /// + /// /// let generations_addr=&generations as *const RSmallBox<_,_> as usize; /// let heap_addr=RSmallBox::as_ptr(&generations) as usize; - /// + /// /// assert_ne!(generations_addr,heap_addr); /// /// ``` #[inline] - pub fn as_ptr(this:&Self)->*const T{ + pub fn as_ptr(this: &Self) -> *const T { if this.ptr.is_null() { &this.inline as *const ScratchSpace as *const T - }else{ + } else { this.ptr } } @@ -275,42 +270,45 @@ assert!( RSmallBox::is_inline(&just_right) ); /// sabi_types::RSmallBox, /// std_types::RBox, /// }; - /// + /// /// let rbox=RBox::new(1000_u64); /// let rsbox:RSmallBox= /// rbox.in_move_ptr(|x| RSmallBox::::from_move_ptr(x) ); - /// + /// /// assert_eq!( *rsbox, 1000_u64 ); /// /// ``` - pub fn from_move_ptr(from_ptr:MovePtr<'_,T>)->Self + pub fn from_move_ptr(from_ptr: MovePtr<'_, T>) -> Self where - Inline:InlineStorage + Inline: InlineStorage, { - let destroy=destroy::; - let inline_size =mem::size_of::(); - let value_size =mem::size_of::(); - - let inline_align =mem::align_of::(); - let value_align =mem::align_of::(); - - unsafe{ - let mut inline:ScratchSpace=ScratchSpace::uninit(); - let (storage_ptr,ptr)=if inline_size < value_size || inline_align < value_align { - let x=alloc::alloc(Layout::new::()); - (x,x as *mut T) - }else{ - ( (&mut inline as *mut ScratchSpace as *mut u8), ptr::null_mut() ) + let destroy = destroy::; + let inline_size = mem::size_of::(); + let value_size = mem::size_of::(); + + let inline_align = mem::align_of::(); + let value_align = mem::align_of::(); + + unsafe { + let mut inline: ScratchSpace = ScratchSpace::uninit(); + let (storage_ptr, ptr) = if inline_size < value_size || inline_align < value_align { + let x = alloc::alloc(Layout::new::()); + (x, x as *mut T) + } else { + ( + (&mut inline as *mut ScratchSpace as *mut u8), + ptr::null_mut(), + ) }; (MovePtr::into_raw(from_ptr) as *const T as *const u8) - .copy_to_nonoverlapping(storage_ptr,value_size); + .copy_to_nonoverlapping(storage_ptr, value_size); - Self{ + Self { inline, ptr, destroy, - _marker:PhantomData, + _marker: PhantomData, } } } @@ -321,7 +319,7 @@ assert!( RSmallBox::is_inline(&just_right) ); /// /// ``` /// use abi_stable::sabi_types::RSmallBox; - /// + /// /// let old=RSmallBox::::new(599_u64); /// assert!( ! RSmallBox::is_inline(&old) ); /// @@ -331,14 +329,11 @@ assert!( RSmallBox::is_inline(&just_right) ); /// /// ``` #[inline] - pub fn move_(this:Self)->RSmallBox + pub fn move_(this: Self) -> RSmallBox where - Inline2:InlineStorage + Inline2: InlineStorage, { - Self::with_move_ptr( - ManuallyDrop::new(this), - RSmallBox::from_move_ptr - ) + Self::with_move_ptr(ManuallyDrop::new(this), RSmallBox::from_move_ptr) } /// Queries whether the value is stored inline. @@ -350,7 +345,7 @@ assert!( RSmallBox::is_inline(&just_right) ); /// sabi_types::RSmallBox, /// std_types::RString, /// }; - /// + /// /// let heap=RSmallBox::::new(599_u64); /// assert!( ! RSmallBox::is_inline(&heap) ); /// @@ -358,11 +353,10 @@ assert!( RSmallBox::is_inline(&just_right) ); /// assert!( RSmallBox::is_inline(&inline) ); /// /// ``` - pub fn is_inline(this:&Self)->bool{ + pub fn is_inline(this: &Self) -> bool { this.ptr.is_null() } - /// Queries whether the value is stored on the heap. /// /// # Example @@ -372,7 +366,7 @@ assert!( RSmallBox::is_inline(&just_right) ); /// sabi_types::RSmallBox, /// std_types::RHashMap, /// }; - /// + /// /// let heap=RSmallBox::<_,[u8;4]>::new(String::new()); /// assert!( RSmallBox::is_heap_allocated(&heap) ); /// @@ -380,7 +374,7 @@ assert!( RSmallBox::is_inline(&just_right) ); /// assert!( ! RSmallBox::is_heap_allocated(&inline) ); /// /// ``` - pub fn is_heap_allocated(this:&Self)->bool{ + pub fn is_heap_allocated(this: &Self) -> bool { !this.ptr.is_null() } @@ -390,84 +384,70 @@ assert!( RSmallBox::is_inline(&just_right) ); /// /// ``` /// use abi_stable::sabi_types::RSmallBox; - /// + /// /// let rbox=RSmallBox::<_,[usize;3]>::new(vec![0,1,2]); /// assert_eq!( RSmallBox::into_inner(rbox), vec![0,1,2] ); /// /// ``` #[allow(clippy::redundant_closure)] - pub fn into_inner(this:Self)->T{ - Self::with_move_ptr( - ManuallyDrop::new(this), - |x|MovePtr::into_inner(x) - ) + pub fn into_inner(this: Self) -> T { + Self::with_move_ptr(ManuallyDrop::new(this), |x| MovePtr::into_inner(x)) } - pub(super) unsafe fn drop_in_place(this:&mut Self,drop_referent:CallReferentDrop){ - let (ptr,dealloc)=if this.ptr.is_null() { - (&mut this.inline as *mut ScratchSpace as *mut T,Deallocate::No) - }else{ - (this.ptr,Deallocate::Yes) + pub(super) unsafe fn drop_in_place(this: &mut Self, drop_referent: CallReferentDrop) { + let (ptr, dealloc) = if this.ptr.is_null() { + ( + &mut this.inline as *mut ScratchSpace as *mut T, + Deallocate::No, + ) + } else { + (this.ptr, Deallocate::Yes) }; - (this.destroy)(ptr,drop_referent,dealloc); + (this.destroy)(ptr, drop_referent, dealloc); } } /// Converts an RBox into an RSmallBox,currently this allocates. - impl From> for RSmallBox + impl From> for RSmallBox where - Inline:InlineStorage + Inline: InlineStorage, { - fn from(this:RBox)->Self{ - RBox::with_move_ptr( - ManuallyDrop::new(this), - Self::from_move_ptr - ) + fn from(this: RBox) -> Self { + RBox::with_move_ptr(ManuallyDrop::new(this), Self::from_move_ptr) } } - /// Converts a RSmallBox into an RBox,currently this allocates. #[allow(clippy::redundant_closure)] - impl Into> for RSmallBox + impl Into> for RSmallBox where - Inline:InlineStorage + Inline: InlineStorage, { - fn into(self)->RBox{ - Self::with_move_ptr( - ManuallyDrop::new(self), - |x|MovePtr::into_rbox(x) - ) + fn into(self) -> RBox { + Self::with_move_ptr(ManuallyDrop::new(self), |x| MovePtr::into_rbox(x)) } } - } - /////////////////////////////////////////////////////////////////////////////// - -unsafe impl GetPointerKind for RSmallBox{ - type Kind=PK_SmartPointer; +unsafe impl GetPointerKind for RSmallBox { + type Kind = PK_SmartPointer; type PtrTarget = T; } -impl Deref for RSmallBox{ - type Target=T; +impl Deref for RSmallBox { + type Target = T; - fn deref(&self)->&T{ - unsafe{ - &*Self::as_ptr(self) - } + fn deref(&self) -> &T { + unsafe { &*Self::as_ptr(self) } } } -impl DerefMut for RSmallBox{ - fn deref_mut(&mut self)->&mut T{ - unsafe{ - &mut *Self::as_mut_ptr(self) - } +impl DerefMut for RSmallBox { + fn deref_mut(&mut self) -> &mut T { + unsafe { &mut *Self::as_mut_ptr(self) } } } @@ -483,64 +463,57 @@ unsafe impl AsMutPtr for RSmallBox { } } - -impl Default for RSmallBox +impl Default for RSmallBox where T: Default, - Inline:InlineStorage, + Inline: InlineStorage, { fn default() -> Self { Self::new(T::default()) } } - -impl Clone for RSmallBox +impl Clone for RSmallBox where T: Clone, - Inline:InlineStorage, + Inline: InlineStorage, { fn clone(&self) -> Self { RSmallBox::new((**self).clone()) } } - -impl Display for RSmallBox -where - T:Display +impl Display for RSmallBox +where + T: Display, { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Display::fmt(&**self,f) + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Display::fmt(&**self, f) } } - - shared_impls! { mod=box_impls new_type=RSmallBox[][T,Inline], original_type=Box, } - -unsafe impl CanTransmuteElement for RSmallBox { - type TransmutedPtr = RSmallBox; +unsafe impl CanTransmuteElement for RSmallBox { + type TransmutedPtr = RSmallBox; unsafe fn transmute_element_(self) -> Self::TransmutedPtr { core_extensions::utils::transmute_ignore_size(self) } } -unsafe impl Send for RSmallBox {} -unsafe impl Sync for RSmallBox {} +unsafe impl Send for RSmallBox {} +unsafe impl Sync for RSmallBox {} /////////////////////////////////////////////////////////////////////////////// - -impl Serialize for RSmallBox +impl Serialize for RSmallBox where - T:Serialize + T: Serialize, { fn serialize(&self, serializer: S) -> Result where @@ -550,11 +523,10 @@ where } } - -impl<'de,T,Inline> Deserialize<'de> for RSmallBox +impl<'de, T, Inline> Deserialize<'de> for RSmallBox where - Inline:InlineStorage, - T:Deserialize<'de> + Inline: InlineStorage, + T: Deserialize<'de>, { fn deserialize(deserializer: D) -> Result where @@ -564,35 +536,29 @@ where } } - ////////////////////////////////////////////////////////////////////////////// - -unsafe impl OwnedPointer for RSmallBox{ +unsafe impl OwnedPointer for RSmallBox { #[inline] - unsafe fn get_move_ptr(this:&mut ManuallyDrop)->MovePtr<'_, T>{ + unsafe fn get_move_ptr(this: &mut ManuallyDrop) -> MovePtr<'_, T> { MovePtr::new(&mut **this) } #[inline] - unsafe fn drop_allocation(this:&mut ManuallyDrop){ - Self::drop_in_place(&mut **this,CallReferentDrop::No); + unsafe fn drop_allocation(this: &mut ManuallyDrop) { + Self::drop_in_place(&mut **this, CallReferentDrop::No); } } - - -impl Drop for RSmallBox{ - fn drop(&mut self){ - unsafe{ - Self::drop_in_place(self,CallReferentDrop::Yes); +impl Drop for RSmallBox { + fn drop(&mut self) { + unsafe { + Self::drop_in_place(self, CallReferentDrop::Yes); } } } - - -unsafe extern "C" fn destroy(ptr:*mut T,drop_referent:CallReferentDrop,dealloc:Deallocate){ +unsafe extern "C" fn destroy(ptr: *mut T, drop_referent: CallReferentDrop, dealloc: Deallocate) { extern_fn_panic_handling! {no_early_return; if let CallReferentDrop::Yes=drop_referent{ ptr::drop_in_place(ptr); @@ -605,8 +571,5 @@ unsafe extern "C" fn destroy(ptr:*mut T,drop_referent:CallReferentDrop,deallo ////////////////////////////////////////////////////////////////////////////// - - - -#[cfg(all(test,not(feature="only_new_tests")))] -mod tests; \ No newline at end of file +#[cfg(all(test, not(feature = "only_new_tests")))] +mod tests; diff --git a/abi_stable/src/sabi_types/rsmallbox/tests.rs b/abi_stable/src/sabi_types/rsmallbox/tests.rs index c9faa415..2657c101 100644 --- a/abi_stable/src/sabi_types/rsmallbox/tests.rs +++ b/abi_stable/src/sabi_types/rsmallbox/tests.rs @@ -3,99 +3,96 @@ use super::*; use std::sync::Arc; #[test] -fn construct(){ - let arc=Arc::new(100); +fn construct() { + let arc = Arc::new(100); { - let box_=RSmallBox::<_,[usize;4]>::new(arc.clone()); + let box_ = RSmallBox::<_, [usize; 4]>::new(arc.clone()); assert_eq!(&*box_, &arc); - assert_eq!(box_.piped_ref(RSmallBox::is_inline),true); - assert_eq!(box_.piped_ref(RSmallBox::is_heap_allocated),false); + assert_eq!(box_.piped_ref(RSmallBox::is_inline), true); + assert_eq!(box_.piped_ref(RSmallBox::is_heap_allocated), false); assert_eq!(Arc::strong_count(&arc), 2); } assert_eq!(Arc::strong_count(&arc), 1); { - let box_=RSmallBox::<_,[u8;2]>::new(arc.clone()); + let box_ = RSmallBox::<_, [u8; 2]>::new(arc.clone()); assert_eq!(&*box_, &arc); - assert_eq!(box_.piped_ref(RSmallBox::is_inline),false); - assert_eq!(box_.piped_ref(RSmallBox::is_heap_allocated),true); + assert_eq!(box_.piped_ref(RSmallBox::is_inline), false); + assert_eq!(box_.piped_ref(RSmallBox::is_heap_allocated), true); assert_eq!(Arc::strong_count(&arc), 2); } assert_eq!(Arc::strong_count(&arc), 1); } - #[test] -fn from_move_ptr(){ - let arc=Arc::new(100); +fn from_move_ptr() { + let arc = Arc::new(100); { - let box_= RBox::with_move_ptr( + let box_ = RBox::with_move_ptr( ManuallyDrop::new(RBox::new(arc.clone())), - RSmallBox::<_,[u8;2]>::from_move_ptr, + RSmallBox::<_, [u8; 2]>::from_move_ptr, ); assert_eq!(&*box_, &arc); - assert_eq!(box_.piped_ref(RSmallBox::is_inline),false); - assert_eq!(box_.piped_ref(RSmallBox::is_heap_allocated),true); + assert_eq!(box_.piped_ref(RSmallBox::is_inline), false); + assert_eq!(box_.piped_ref(RSmallBox::is_heap_allocated), true); assert_eq!(Arc::strong_count(&*box_), 2); assert_eq!(Arc::strong_count(&arc), 2); } assert_eq!(Arc::strong_count(&arc), 1); { - let box_=RBox::with_move_ptr( + let box_ = RBox::with_move_ptr( ManuallyDrop::new(RBox::new(arc.clone())), - RSmallBox::<_,[usize;1]>::from_move_ptr, + RSmallBox::<_, [usize; 1]>::from_move_ptr, ); assert_eq!(&*box_, &arc); - assert_eq!(box_.piped_ref(RSmallBox::is_inline),true); - assert_eq!(box_.piped_ref(RSmallBox::is_heap_allocated),false); + assert_eq!(box_.piped_ref(RSmallBox::is_inline), true); + assert_eq!(box_.piped_ref(RSmallBox::is_heap_allocated), false); assert_eq!(Arc::strong_count(&*box_), 2); assert_eq!(Arc::strong_count(&arc), 2); } - + assert_eq!(Arc::strong_count(&arc), 1); } - #[test] -fn from_rbox(){ - let arc=Arc::new(100); +fn from_rbox() { + let arc = Arc::new(100); { - let box_:RSmallBox<_,[u8;2]>= RBox::new(arc.clone()).into(); + let box_: RSmallBox<_, [u8; 2]> = RBox::new(arc.clone()).into(); assert_eq!(&*box_, &arc); - assert_eq!(box_.piped_ref(RSmallBox::is_inline),false); - assert_eq!(box_.piped_ref(RSmallBox::is_heap_allocated),true); + assert_eq!(box_.piped_ref(RSmallBox::is_inline), false); + assert_eq!(box_.piped_ref(RSmallBox::is_heap_allocated), true); assert_eq!(Arc::strong_count(&*box_), 2); assert_eq!(Arc::strong_count(&arc), 2); } assert_eq!(Arc::strong_count(&arc), 1); { - let box_:RSmallBox<_,[usize;1]>= RBox::new(arc.clone()).into(); + let box_: RSmallBox<_, [usize; 1]> = RBox::new(arc.clone()).into(); assert_eq!(&*box_, &arc); - assert_eq!(box_.piped_ref(RSmallBox::is_inline),true); - assert_eq!(box_.piped_ref(RSmallBox::is_heap_allocated),false); + assert_eq!(box_.piped_ref(RSmallBox::is_inline), true); + assert_eq!(box_.piped_ref(RSmallBox::is_heap_allocated), false); assert_eq!(Arc::strong_count(&*box_), 2); assert_eq!(Arc::strong_count(&arc), 2); } - + assert_eq!(Arc::strong_count(&arc), 1); } - #[test] -fn into_rbox(){ - let arc=Arc::new(100); +fn into_rbox() { + let arc = Arc::new(100); { - let box_:RBox<_>= RSmallBox::<_,[u8;2]>::new(arc.clone()).into(); + let box_: RBox<_> = RSmallBox::<_, [u8; 2]>::new(arc.clone()).into(); assert_eq!(&*box_, &arc); assert_eq!(Arc::strong_count(&*box_), 2); @@ -103,44 +100,42 @@ fn into_rbox(){ } assert_eq!(Arc::strong_count(&arc), 1); { - let box_:RBox<_>= RSmallBox::<_,[usize;1]>::new(arc.clone()).into(); + let box_: RBox<_> = RSmallBox::<_, [usize; 1]>::new(arc.clone()).into(); assert_eq!(&*box_, &arc); assert_eq!(Arc::strong_count(&*box_), 2); assert_eq!(Arc::strong_count(&arc), 2); } - + assert_eq!(Arc::strong_count(&arc), 1); } - #[test] -fn into_inner(){ - let arc=Arc::new(100); +fn into_inner() { + let arc = Arc::new(100); { - let box_=RSmallBox::<_,[usize;4]>::new(arc.clone()); + let box_ = RSmallBox::<_, [usize; 4]>::new(arc.clone()); assert_eq!(Arc::strong_count(&arc), 2); - assert_eq!(box_.piped(RSmallBox::into_inner),arc); + assert_eq!(box_.piped(RSmallBox::into_inner), arc); } assert_eq!(Arc::strong_count(&arc), 1); { - let box_=RSmallBox::<_,[u8;2]>::new(arc.clone()); + let box_ = RSmallBox::<_, [u8; 2]>::new(arc.clone()); assert_eq!(Arc::strong_count(&arc), 2); - assert_eq!(box_.piped(RSmallBox::into_inner),arc); + assert_eq!(box_.piped(RSmallBox::into_inner), arc); } assert_eq!(Arc::strong_count(&arc), 1); } - #[test] -fn alignments(){ +fn alignments() { use super::alignment::*; - assert_eq!(mem::align_of::>(),1); - assert_eq!(mem::align_of::>(),2); - assert_eq!(mem::align_of::>(),4); - assert_eq!(mem::align_of::>(),8); - assert_eq!(mem::align_of::>(),16); - assert_eq!(mem::align_of::>(),32); - assert_eq!(mem::align_of::>(),64); - assert_eq!(mem::align_of::>(),128); -} \ No newline at end of file + assert_eq!(mem::align_of::>(), 1); + assert_eq!(mem::align_of::>(), 2); + assert_eq!(mem::align_of::>(), 4); + assert_eq!(mem::align_of::>(), 8); + assert_eq!(mem::align_of::>(), 16); + assert_eq!(mem::align_of::>(), 32); + assert_eq!(mem::align_of::>(), 64); + assert_eq!(mem::align_of::>(), 128); +} diff --git a/abi_stable/src/sabi_types/static_ref.rs b/abi_stable/src/sabi_types/static_ref.rs index b61c3c9a..c06026c3 100644 --- a/abi_stable/src/sabi_types/static_ref.rs +++ b/abi_stable/src/sabi_types/static_ref.rs @@ -1,18 +1,14 @@ - -use crate::{ - pointer_trait::{AsPtr, CanTransmuteElement,GetPointerKind,PK_Reference}, -}; +use crate::pointer_trait::{AsPtr, CanTransmuteElement, GetPointerKind, PK_Reference}; use std::{ - ops::{Deref}, - fmt::{self,Display}, + fmt::{self, Display}, + ops::Deref, ptr::NonNull, }; - /** A wrapper type for vtable static references, -and other constants that have `non-'static` generic parameters +and other constants that have `non-'static` generic parameters but are safe to reference for the lifetime of `T`. # Purpose @@ -49,7 +45,7 @@ fn main(){ #[derive(StableAbi)] pub struct BoxLike { data: *mut T, - + vtable: StaticRef>, _marker: PhantomData, @@ -107,36 +103,30 @@ unsafe fn drop_box(object: *mut T){ */ #[repr(transparent)] #[derive(StableAbi)] -pub struct StaticRef{ +pub struct StaticRef { ref_: NonNull, } impl Display for StaticRef where - T:Display + T: Display, { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Display::fmt(&**self,f) + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Display::fmt(&**self, f) } } - -impl Clone for StaticRef{ - fn clone(&self)->Self{ +impl Clone for StaticRef { + fn clone(&self) -> Self { *self } } -impl Copy for StaticRef{} +impl Copy for StaticRef {} -unsafe impl<'a,T:'a> Sync for StaticRef -where &'a T:Sync -{} - -unsafe impl<'a,T:'a> Send for StaticRef -where &'a T:Send -{} +unsafe impl<'a, T: 'a> Sync for StaticRef where &'a T: Sync {} +unsafe impl<'a, T: 'a> Send for StaticRef where &'a T: Send {} shared_impls! { mod=static_ref_impls @@ -144,8 +134,7 @@ shared_impls! { original_type=AAAA, } - -impl StaticRef{ +impl StaticRef { /// Constructs this StaticRef from a raw pointer. /// /// # Safety @@ -168,9 +157,9 @@ impl StaticRef{ /// } /// /// ``` - pub const unsafe fn from_raw(ref_:*const T)->Self{ - Self{ - ref_: unsafe{ NonNull::new_unchecked(ref_ as *mut T) }, + pub const unsafe fn from_raw(ref_: *const T) -> Self { + Self { + ref_: unsafe { NonNull::new_unchecked(ref_ as *mut T) }, } } @@ -196,18 +185,16 @@ impl StaticRef{ /// } /// /// ``` - pub const fn new(ref_:&'static T)->Self{ - Self{ - ref_: unsafe{ NonNull::new_unchecked(ref_ as *const T as *mut T) }, + pub const fn new(ref_: &'static T) -> Self { + Self { + ref_: unsafe { NonNull::new_unchecked(ref_ as *const T as *mut T) }, } } /// Creates a StaticRef by heap allocating and leaking `val`. pub fn leak_value(val: T) -> Self { // Safety: This is safe, because the value is a leaked heap allocation. - unsafe{ - Self::from_raw(crate::utils::leak_value(val)) - } + unsafe { Self::from_raw(crate::utils::leak_value(val)) } } /// Gets access to the reference. @@ -233,8 +220,8 @@ impl StaticRef{ /// GetPtr::::STATIC.get(); /// /// ``` - pub fn get<'a>(self)->&'a T{ - unsafe{ &*(self.ref_.as_ptr() as *const T) } + pub fn get<'a>(self) -> &'a T { + unsafe { &*(self.ref_.as_ptr() as *const T) } } /// Gets access to the referenced value,as a raw pointer. @@ -259,7 +246,7 @@ impl StaticRef{ /// GetPtr::::STATIC.as_ptr(); /// /// ``` - pub const fn as_ptr(self)->*const T{ + pub const fn as_ptr(self) -> *const T { self.ref_.as_ptr() as *const T } @@ -291,17 +278,15 @@ impl StaticRef{ /// }; /// /// ``` - pub const unsafe fn transmute(self)->StaticRef{ - StaticRef::from_raw( - self.ref_.as_ptr() as *const T as *const U - ) + pub const unsafe fn transmute(self) -> StaticRef { + StaticRef::from_raw(self.ref_.as_ptr() as *const T as *const U) } } -impl Deref for StaticRef{ - type Target=T; +impl Deref for StaticRef { + type Target = T; - fn deref(&self)->&T{ + fn deref(&self) -> &T { self.get() } } @@ -312,14 +297,14 @@ unsafe impl AsPtr for StaticRef { } } -unsafe impl GetPointerKind for StaticRef{ - type Kind=PK_Reference; +unsafe impl GetPointerKind for StaticRef { + type Kind = PK_Reference; type PtrTarget = T; } -unsafe impl CanTransmuteElement for StaticRef{ - type TransmutedPtr= StaticRef; +unsafe impl CanTransmuteElement for StaticRef { + type TransmutedPtr = StaticRef; #[inline(always)] unsafe fn transmute_element_(self) -> StaticRef { @@ -327,42 +312,38 @@ unsafe impl CanTransmuteElement for StaticRef{ } } - - #[cfg(test)] mod tests { use super::*; #[test] - fn construction_test(){ - unsafe{ + fn construction_test() { + unsafe { let three: *const i32 = &3; assert_eq!(*StaticRef::from_raw(three), 3); } assert_eq!(*StaticRef::new(&5), 5); - + assert_eq!(*StaticRef::leak_value(8), 8); } #[test] - fn access(){ + fn access() { let reference = StaticRef::new(&8); - + assert_eq!(*reference.get(), 8); - unsafe{ + unsafe { assert_eq!(*reference.as_ptr(), 8); } } #[test] - fn transmutes(){ + fn transmutes() { let reference = StaticRef::new(&(!0u32)); - unsafe{ + unsafe { assert_eq!(*reference.transmute::(), -1); } } } - - diff --git a/abi_stable/src/sabi_types/version.rs b/abi_stable/src/sabi_types/version.rs index 9ef91722..d6e8376d 100644 --- a/abi_stable/src/sabi_types/version.rs +++ b/abi_stable/src/sabi_types/version.rs @@ -89,42 +89,44 @@ pub struct VersionNumber { } impl VersionStrings { - /// Constructs a VersionStrings from a string with the + /// Constructs a VersionStrings from a string with the /// "major.minor.patch" format,where each one is a valid number. - /// + /// /// This does not check whether the string is correctly formatted, /// that check is done inside `VersionStrings::parsed`. - /// + /// /// # Example - /// + /// /// ``` /// use abi_stable::sabi_types::VersionStrings; - /// + /// /// static VERSION:VersionStrings=VersionStrings::new("0.1.2"); - /// + /// /// ``` - pub const fn new(version:&'static str)->Self{ - Self{version:RStr::from_str(version)} + pub const fn new(version: &'static str) -> Self { + Self { + version: RStr::from_str(version), + } } /// Attempts to convert a `VersionStrings` into a `VersionNumber` - /// + /// /// # Errors - /// + /// /// This returns a `ParseVersionError` if the string is not correctly formatted. - /// + /// /// # Example - /// + /// /// ``` /// use abi_stable::sabi_types::{VersionNumber,VersionStrings}; - /// + /// /// static VERSION:VersionStrings=VersionStrings::new("0.1.2"); - /// + /// /// assert_eq!( VERSION.parsed(), Ok(VersionNumber{major:0,minor:1,patch:2}) ); /// /// let err_version=VersionStrings::new("0.a.2.b"); /// assert!( err_version.parsed().is_err() ); - /// + /// /// ``` pub fn parsed(self) -> Result { VersionNumber::new(self) @@ -133,37 +135,40 @@ impl VersionStrings { impl VersionNumber { /// Attempts to convert a `VersionStrings` into a `VersionNumber` - /// + /// /// # Errors - /// + /// /// This returns a `ParseVersionError` if the string is not correctly formatted. - /// + /// /// # Example - /// + /// /// ``` /// use abi_stable::sabi_types::{VersionNumber,VersionStrings}; - /// + /// /// static VERSION:VersionStrings=VersionStrings::new("10.5.20"); - /// + /// /// assert_eq!( VersionNumber::new(VERSION), Ok(VersionNumber{major:10,minor:5,patch:20}) ); /// /// let err_version=VersionStrings::new("not a version number"); /// assert!( VersionNumber::new(err_version).is_err() ); - /// + /// /// ``` pub fn new(vn: VersionStrings) -> Result { - let mut iter=vn.version.splitn(3,'.'); + let mut iter = vn.version.splitn(3, '.'); VersionNumber { - major: iter.next() + major: iter + .next() .unwrap_or("") .parse() .map_err(|x| ParseVersionError::new(vn, "major", x))?, - minor: iter.next() + minor: iter + .next() .unwrap_or("") .parse() .map_err(|x| ParseVersionError::new(vn, "minor", x))?, - patch: iter.next() + patch: iter + .next() .unwrap_or("") .split_while(|x| ('0'..='9').contains(&x)) .find(|x| x.key) @@ -267,15 +272,14 @@ impl fmt::Display for VersionNumber { impl fmt::Display for VersionStrings { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt::Display::fmt(&self.version,f) + fmt::Display::fmt(&self.version, f) } } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// - -/// Instantiates a [`VersionStrings`] with the +/// Instantiates a [`VersionStrings`] with the /// major.minor.patch version of the library where it is invoked. /// /// [`VersionStrings`]: ./sabi_types/version/struct.VersionStrings.html diff --git a/abi_stable/src/std_types.rs b/abi_stable/src/std_types.rs index 7c4e5081..e26def87 100644 --- a/abi_stable/src/std_types.rs +++ b/abi_stable/src/std_types.rs @@ -2,7 +2,7 @@ Contains many ffi-safe equivalents of standard library types. The vast majority of them can be converted to and from std equivalents. -For ffi-safe equivalents/wrappers of types outside the standard library go to +For ffi-safe equivalents/wrappers of types outside the standard library go to the [external_types module](../external_types/index.html) */ @@ -11,8 +11,8 @@ pub(crate) mod arc; pub(crate) mod boxed; pub(crate) mod cmp_ordering; pub mod cow; -pub(crate) mod option; pub mod map; +pub(crate) mod option; pub(crate) mod range; pub(crate) mod result; pub(crate) mod slice_mut; @@ -26,20 +26,18 @@ pub(crate) mod tuple; pub mod utypeid; pub mod vec; - /** Some types from the `std::sync` module have ffi-safe equivalents in abi_stable::external_types. -The `sync::{Mutex,RwLock,Once}` equivalents are declared in +The `sync::{Mutex,RwLock,Once}` equivalents are declared in `abi_stable::external_types::parking_lot` -The `mpsc` equivalents are declared in +The `mpsc` equivalents are declared in `abi_stable::external_types::crossbeam_channel`, this is enabled by default with the `channels`/`crossbeam-channel` cargo feature. */ -pub mod sync{} - +pub mod sync {} #[doc(inline)] pub use self::{ @@ -52,12 +50,12 @@ pub use self::{ result::{RErr, ROk, RResult}, slice_mut::RSliceMut, slices::RSlice, - std_error::{RBoxError, RBoxError_,SendRBoxError, UnsyncRBoxError}, - std_io::{RIoError,RSeekFrom, RIoErrorKind}, + std_error::{RBoxError, RBoxError_, SendRBoxError, UnsyncRBoxError}, + std_io::{RIoError, RIoErrorKind, RSeekFrom}, str::RStr, string::RString, time::RDuration, - tuple::{Tuple1,Tuple2, Tuple3, Tuple4}, - vec::RVec, + tuple::{Tuple1, Tuple2, Tuple3, Tuple4}, utypeid::UTypeId, -}; \ No newline at end of file + vec::RVec, +}; diff --git a/abi_stable/src/std_types/arc.rs b/abi_stable/src/std_types/arc.rs index 6acc7845..43f0017a 100644 --- a/abi_stable/src/std_types/arc.rs +++ b/abi_stable/src/std_types/arc.rs @@ -2,83 +2,79 @@ Contains the ffi-safe equivalent of `std::sync::Arc`. */ -use std::{ - borrow::{Borrow}, - marker::PhantomData, - mem::ManuallyDrop, - sync::Arc, -}; +use std::{borrow::Borrow, marker::PhantomData, mem::ManuallyDrop, sync::Arc}; use core_extensions::SelfOps; use crate::{ abi_stability::StableAbi, pointer_trait::{ - AsPtr, CallReferentDrop, CanTransmuteElement, - GetPointerKind,PK_SmartPointer, + AsPtr, CallReferentDrop, CanTransmuteElement, GetPointerKind, PK_SmartPointer, }, - prefix_type::{PrefixTypeTrait,WithMetadata}, + prefix_type::{PrefixTypeTrait, WithMetadata}, sabi_types::Constructor, - std_types::{RResult,utypeid::{UTypeId,new_utypeid}}, + std_types::{ + utypeid::{new_utypeid, UTypeId}, + RResult, + }, }; - -#[cfg(all(test,not(feature="only_new_tests")))] +#[cfg(all(test, not(feature = "only_new_tests")))] mod test; mod private { use super::*; -/** -Ffi-safe version of `std::sync::Arc` + /** + Ffi-safe version of `std::sync::Arc` -# Example + # Example -Using an `RArc>>` to get a list populated from multiple threads. + Using an `RArc>>` to get a list populated from multiple threads. -``` -use abi_stable::{ - external_types::RMutex, - std_types::{RArc,RVec}, -}; + ``` + use abi_stable::{ + external_types::RMutex, + std_types::{RArc,RVec}, + }; -use std::thread; + use std::thread; -let arc=RArc::new(RMutex::new(RVec::new())); + let arc=RArc::new(RMutex::new(RVec::new())); -{ - let arc2=RArc::clone(&arc); - assert!( std::ptr::eq(&*arc,&*arc2) ); -} + { + let arc2=RArc::clone(&arc); + assert!( std::ptr::eq(&*arc,&*arc2) ); + } -let mut guards=Vec::new(); + let mut guards=Vec::new(); -for i in 0..10_u64 { - let arc=RArc::clone(&arc); - guards.push(thread::spawn(move||{ - for j in 0..100_u64{ - arc.lock().push(i*100+j); - } - })); -} + for i in 0..10_u64 { + let arc=RArc::clone(&arc); + guards.push(thread::spawn(move||{ + for j in 0..100_u64{ + arc.lock().push(i*100+j); + } + })); + } -for guard in guards{ - guard.join().unwrap(); -} + for guard in guards{ + guard.join().unwrap(); + } -let mut vec=RArc::try_unwrap(arc) - .ok() - .expect("All the threads were joined,so this must be the only RArc") - .into_inner(); + let mut vec=RArc::try_unwrap(arc) + .ok() + .expect("All the threads were joined,so this must be the only RArc") + .into_inner(); -vec.sort(); + vec.sort(); -assert_eq!( vec, (0..1000).collect::>() ); + assert_eq!( vec, (0..1000).collect::>() ); -``` + ``` -*/ + */ #[derive(StableAbi)] #[repr(C)] pub struct RArc { @@ -99,8 +95,8 @@ assert_eq!( vec, (0..1000).collect::>() ); } } - unsafe impl GetPointerKind for RArc{ - type Kind=PK_SmartPointer; + unsafe impl GetPointerKind for RArc { + type Kind = PK_SmartPointer; type PtrTarget = T; } @@ -124,7 +120,7 @@ assert_eq!( vec, (0..1000).collect::>() ); pub(super) fn data(&self) -> *const T { self.data } - + #[inline(always)] pub(super) unsafe fn data_mut(&mut self) -> *mut T { self.data as *mut T @@ -175,7 +171,7 @@ impl RArc { /// /// # When is T cloned /// - /// `T` is cloned if the current dynamic_library/executable is + /// `T` is cloned if the current dynamic_library/executable is /// not the one that created the `RArc`, /// and the strong count is greater than 1. /// @@ -194,10 +190,10 @@ impl RArc { where T: Clone, { - let this_vtable =this.vtable(); - let other_vtable=VTableGetter::LIB_VTABLE; - if ::std::ptr::eq(this_vtable.0.to_raw_ptr(), other_vtable.0.to_raw_ptr())|| - this_vtable.type_id()==other_vtable.type_id() + let this_vtable = this.vtable(); + let other_vtable = VTableGetter::LIB_VTABLE; + if ::std::ptr::eq(this_vtable.0.to_raw_ptr(), other_vtable.0.to_raw_ptr()) + || this_vtable.type_id() == other_vtable.type_id() { unsafe { Arc::from_raw(this.into_raw()) } } else { @@ -214,7 +210,7 @@ impl RArc { /// /// ``` /// use abi_stable::std_types::RArc; - /// + /// /// let arc0=RArc::new(100); /// assert_eq!( RArc::try_unwrap(arc0), Ok(100) ); /// @@ -224,11 +220,9 @@ impl RArc { /// /// ``` #[inline] - pub fn try_unwrap(this: Self) -> Result{ + pub fn try_unwrap(this: Self) -> Result { let vtable = this.vtable(); - unsafe{ - (vtable.try_unwrap())(this).into_result() - } + unsafe { (vtable.try_unwrap())(this).into_result() } } /// Attempts to create a mutable reference to `T`, @@ -238,7 +232,7 @@ impl RArc { /// /// ``` /// use abi_stable::std_types::RArc; - /// + /// /// let mut arc0=RArc::new(100); /// *RArc::get_mut(&mut arc0).unwrap()+=400; /// assert_eq!( *arc0, 500 ); @@ -249,18 +243,16 @@ impl RArc { /// /// ``` #[inline] - pub fn get_mut(this: &mut Self) -> Option<&mut T>{ + pub fn get_mut(this: &mut Self) -> Option<&mut T> { let vtable = this.vtable(); - unsafe{ - (vtable.get_mut())(this) - } + unsafe { (vtable.get_mut())(this) } } /// Makes a mutable reference to `T`. /// /// If there are other `RArc`s pointing to the same value, /// then `T` is cloned into a new `RArc` to ensure unique ownership of the value. - /// + /// /// /// # Postconditions /// @@ -272,7 +264,7 @@ impl RArc { /// /// ``` /// use abi_stable::std_types::RArc; - /// + /// /// let mut arc0=RArc::new(100); /// *RArc::make_mut(&mut arc0)+=400; /// assert_eq!( *arc0, 500 ); @@ -285,21 +277,20 @@ impl RArc { /// /// ``` #[inline] - pub fn make_mut(this: &mut Self) -> &mut T - where T:Clone + pub fn make_mut(this: &mut Self) -> &mut T + where + T: Clone, { - // Workaround for non-lexical lifetimes not being smart enough + // Workaround for non-lexical lifetimes not being smart enough // to figure out that this borrow doesn't continue in the None branch. - let unbounded_this=unsafe{ &mut *(this as *mut Self) }; + let unbounded_this = unsafe { &mut *(this as *mut Self) }; match Self::get_mut(unbounded_this) { - Some(x)=>x, - None=>{ - let new_arc=RArc::new((**this).clone()); - *this=new_arc; + Some(x) => x, + None => { + let new_arc = RArc::new((**this).clone()); + *this = new_arc; // This is fine,since this is a freshly created arc with a clone of the data. - unsafe{ - &mut *this.data_mut() - } + unsafe { &mut *this.data_mut() } } } } @@ -310,7 +301,7 @@ impl RArc { /// /// ``` /// use abi_stable::std_types::RArc; - /// + /// /// let arc=RArc::new(0); /// assert_eq!( RArc::strong_count(&arc), 1 ); /// @@ -318,11 +309,9 @@ impl RArc { /// assert_eq!( RArc::strong_count(&arc), 2 ); /// /// ``` - pub fn strong_count(this:&Self)->usize{ + pub fn strong_count(this: &Self) -> usize { let vtable = this.vtable(); - unsafe{ - vtable.strong_count()(this) - } + unsafe { vtable.strong_count()(this) } } /// Gets the number of `std::sync::Weak` that point to the value. @@ -331,46 +320,39 @@ impl RArc { /// /// ``` /// use abi_stable::std_types::RArc; - /// + /// /// use std::sync::Arc; - /// + /// /// let rustarc=Arc::new(0); /// let arc=RArc::from(rustarc.clone()); /// assert_eq!( RArc::weak_count(&arc), 0 ); - /// + /// /// let weak_0=Arc::downgrade(&rustarc); /// assert_eq!( RArc::weak_count(&arc), 1 ); /// /// let weak_1=Arc::downgrade(&rustarc); /// assert_eq!( RArc::weak_count(&arc), 2 ); /// ``` - pub fn weak_count(this:&Self)->usize{ + pub fn weak_count(this: &Self) -> usize { let vtable = this.vtable(); - unsafe{ - vtable.weak_count()(this) - } + unsafe { vtable.weak_count()(this) } } - } - //////////////////////////////////////////////////////////////////// - -impl Borrow for RArc{ - fn borrow(&self)->&T{ +impl Borrow for RArc { + fn borrow(&self) -> &T { self } } - -impl AsRef for RArc{ - fn as_ref(&self)->&T{ +impl AsRef for RArc { + fn as_ref(&self) -> &T { self } } - //////////////////////////////////////////////////////////////////// impl Default for RArc @@ -384,9 +366,7 @@ where impl Clone for RArc { fn clone(&self) -> Self { - unsafe{ - (self.vtable().clone_())(self) - } + unsafe { (self.vtable().clone_())(self) } } } @@ -430,8 +410,8 @@ mod vtable_mod { pub(super) struct VTableGetter<'a, T>(&'a T); impl<'a, T: 'a> VTableGetter<'a, T> { - const DEFAULT_VTABLE:ArcVtable=ArcVtable { - type_id:Constructor( new_utypeid::> ), + const DEFAULT_VTABLE: ArcVtable = ArcVtable { + type_id: Constructor(new_utypeid::>), destructor: destructor_arc::, clone_: clone_arc::, get_mut: get_mut_arc::, @@ -440,18 +420,17 @@ mod vtable_mod { weak_count: weak_count_arc::, }; - staticref!{ + staticref! { const WM_DEFAULT: WithMetadata>= WithMetadata::new(PrefixTypeTrait::METADATA,Self::DEFAULT_VTABLE) } // The VTABLE for this type in this executable/library - pub(super) const LIB_VTABLE: ArcVtable_Ref = { - ArcVtable_Ref(Self::WM_DEFAULT.as_prefix()) - }; + pub(super) const LIB_VTABLE: ArcVtable_Ref = + { ArcVtable_Ref(Self::WM_DEFAULT.as_prefix()) }; #[cfg(test)] - staticref!{const WM_FOR_TESTING: WithMetadata>= + staticref! {const WM_FOR_TESTING: WithMetadata>= WithMetadata::new( PrefixTypeTrait::METADATA, ArcVtable{ @@ -462,9 +441,8 @@ mod vtable_mod { } #[cfg(test)] - pub(super) const LIB_VTABLE_FOR_TESTING: ArcVtable_Ref = { - ArcVtable_Ref(Self::WM_FOR_TESTING.as_prefix()) - }; + pub(super) const LIB_VTABLE_FOR_TESTING: ArcVtable_Ref = + { ArcVtable_Ref(Self::WM_FOR_TESTING.as_prefix()) }; } #[derive(StableAbi)] @@ -472,14 +450,14 @@ mod vtable_mod { #[sabi(kind(Prefix))] #[sabi(missing_field(panic))] pub struct ArcVtable { - pub(super) type_id:Constructor, + pub(super) type_id: Constructor, pub(super) destructor: unsafe extern "C" fn(*const T, CallReferentDrop), pub(super) clone_: unsafe extern "C" fn(&RArc) -> RArc, pub(super) get_mut: unsafe extern "C" fn(&mut RArc) -> Option<&mut T>, pub(super) try_unwrap: unsafe extern "C" fn(RArc) -> RResult>, pub(super) strong_count: unsafe extern "C" fn(&RArc) -> usize, #[sabi(last_prefix_field)] - pub(super) weak_count:unsafe extern "C" fn(&RArc) -> usize, + pub(super) weak_count: unsafe extern "C" fn(&RArc) -> usize, } unsafe extern "C" fn destructor_arc(this: *const T, call_drop: CallReferentDrop) { @@ -492,26 +470,26 @@ mod vtable_mod { } } - unsafe fn with_arc_ref(this:&RArc,f:F)->R + unsafe fn with_arc_ref(this: &RArc, f: F) -> R where - F:FnOnce(&Arc)->R + F: FnOnce(&Arc) -> R, { - let x=this.data(); - let x=Arc::from_raw(x); - let x=ManuallyDrop::new(x); + let x = this.data(); + let x = Arc::from_raw(x); + let x = ManuallyDrop::new(x); f(&x) } unsafe extern "C" fn clone_arc(this: &RArc) -> RArc { - with_arc_ref(this,|x| Arc::clone(&x).into() ) + with_arc_ref(this, |x| Arc::clone(&x).into()) } - unsafe extern "C" fn get_mut_arc<'a,T>(this: &'a mut RArc) -> Option<&'a mut T> { - let arc=Arc::from_raw(this.data()); - let mut arc=ManuallyDrop::new(arc); + unsafe extern "C" fn get_mut_arc<'a, T>(this: &'a mut RArc) -> Option<&'a mut T> { + let arc = Arc::from_raw(this.data()); + let mut arc = ManuallyDrop::new(arc); // This is fine,since we are only touching the data afterwards, // which is guaranteed to have the 'a lifetime. - let arc:&'a mut Arc=&mut *(&mut *arc as *mut Arc); + let arc: &'a mut Arc = &mut *(&mut *arc as *mut Arc); Arc::get_mut(arc) } @@ -524,13 +502,11 @@ mod vtable_mod { } unsafe extern "C" fn strong_count_arc(this: &RArc) -> usize { - with_arc_ref(this,|x| Arc::strong_count(&x) ) + with_arc_ref(this, |x| Arc::strong_count(&x)) } unsafe extern "C" fn weak_count_arc(this: &RArc) -> usize { - with_arc_ref(this,|x| Arc::weak_count(&x) ) + with_arc_ref(this, |x| Arc::weak_count(&x)) } - - } use self::vtable_mod::{ArcVtable_Ref, VTableGetter}; diff --git a/abi_stable/src/std_types/arc/test.rs b/abi_stable/src/std_types/arc/test.rs index 9a0d4630..97c2486b 100644 --- a/abi_stable/src/std_types/arc/test.rs +++ b/abi_stable/src/std_types/arc/test.rs @@ -2,20 +2,26 @@ use super::*; use std::cell::Cell; -fn refaddr<'a,T>(ref_:&'a T)->usize{ +fn refaddr<'a, T>(ref_: &'a T) -> usize { ref_ as *const T as usize } #[test] fn to_from_arc() { let orig_a = Arc::new(1000); - let a_addr = (&*orig_a) as *const _ as usize ; + let a_addr = (&*orig_a) as *const _ as usize; let mut reprc_a = orig_a.clone().piped(RArc::from); assert_eq!(a_addr, refaddr(&*reprc_a)); - assert_eq!(a_addr, reprc_a.clone().piped(|a| refaddr(&*a) )); - assert_eq!(a_addr, reprc_a.clone().piped(RArc::into_arc).piped(|a| refaddr(&*a) ) ); + assert_eq!(a_addr, reprc_a.clone().piped(|a| refaddr(&*a))); + assert_eq!( + a_addr, + reprc_a + .clone() + .piped(RArc::into_arc) + .piped(|a| refaddr(&*a)) + ); reprc_a.set_vtable_for_testing(); @@ -57,72 +63,69 @@ fn into_raw() { assert_eq!(Arc::strong_count(&orig_a), 1); } - #[test] -fn get_mut(){ - let mut conv=Arc::new(200).piped(RArc::from); +fn get_mut() { + let mut conv = Arc::new(200).piped(RArc::from); { - let _conv_clone=conv.clone(); - assert_eq!(RArc::get_mut(&mut conv),None); + let _conv_clone = conv.clone(); + assert_eq!(RArc::get_mut(&mut conv), None); } - assert_eq!(RArc::get_mut(&mut conv),Some(&mut 200)); + assert_eq!(RArc::get_mut(&mut conv), Some(&mut 200)); } - #[test] -fn make_mut(){ - let count=Cell::new(1); - let dod=DecrementOnDrop(&count); +fn make_mut() { + let count = Cell::new(1); + let dod = DecrementOnDrop(&count); - let mut arc = Arc::new(ValueAndDod{ - value:'a', - dod:dod.clone(), - }).piped(RArc::from); + let mut arc = Arc::new(ValueAndDod { + value: 'a', + dod: dod.clone(), + }) + .piped(RArc::from); { - assert_eq!(dod.count(),2); - let arc_clone=arc.clone(); + assert_eq!(dod.count(), 2); + let arc_clone = arc.clone(); - let mutref=RArc::make_mut(&mut arc); - assert_eq!(dod.count(),3); - mutref.value='c'; + let mutref = RArc::make_mut(&mut arc); + assert_eq!(dod.count(), 3); + mutref.value = 'c'; - assert_eq!(arc_clone.value,'a'); + assert_eq!(arc_clone.value, 'a'); } - assert_eq!(dod.count(),2); - assert_eq!(arc.value,'c'); + assert_eq!(dod.count(), 2); + assert_eq!(arc.value, 'c'); } - - ///////////////////////////////////////// #[derive(Clone)] -struct ValueAndDod<'a,T>{ - value:T, - dod:DecrementOnDrop<'a>, +struct ValueAndDod<'a, T> { + value: T, + dod: DecrementOnDrop<'a>, } ///////////////////////////////////////// struct DecrementOnDrop<'a>(&'a Cell); -impl<'a> DecrementOnDrop<'a>{ - fn count(&self)->u32{ +impl<'a> DecrementOnDrop<'a> { + fn count(&self) -> u32 { self.0.get() } } -impl<'a> Clone for DecrementOnDrop<'a>{ - fn clone(&self)->Self{ - self.0.set(self.0.get()+1); +impl<'a> Clone for DecrementOnDrop<'a> { + fn clone(&self) -> Self { + self.0.set(self.0.get() + 1); DecrementOnDrop(self.0) } } -impl<'a> Drop for DecrementOnDrop<'a>{ - fn drop(&mut self){ - self.0.set(self.0.get()-1); +impl<'a> Drop for DecrementOnDrop<'a> { + fn drop(&mut self) { + self.0.set(self.0.get() - 1); } -} \ No newline at end of file +} diff --git a/abi_stable/src/std_types/boxed.rs b/abi_stable/src/std_types/boxed.rs index 301ea4de..55881e60 100644 --- a/abi_stable/src/std_types/boxed.rs +++ b/abi_stable/src/std_types/boxed.rs @@ -2,16 +2,15 @@ Contains the ffi-safe equivalent of `std::boxed::Box`. */ - use std::{ - borrow::{Borrow,BorrowMut}, + borrow::{Borrow, BorrowMut}, error::Error as StdError, future::Future, hash::Hasher, - iter::FusedIterator, io::{self, BufRead, IoSlice, IoSliceMut, Read, Seek, Write}, - marker::{PhantomData, Unpin}, - mem::ManuallyDrop, + iter::FusedIterator, + marker::{PhantomData, Unpin}, + mem::ManuallyDrop, ops::DerefMut, pin::Pin, ptr, @@ -24,60 +23,59 @@ use core_extensions::SelfOps; use crate::{ marker_type::NonOwningPhantom, pointer_trait::{ - AsPtr, AsMutPtr, - CallReferentDrop,Deallocate, CanTransmuteElement, - GetPointerKind,PK_SmartPointer,OwnedPointer, + AsMutPtr, AsPtr, CallReferentDrop, CanTransmuteElement, Deallocate, GetPointerKind, + OwnedPointer, PK_SmartPointer, }, - traits::{IntoReprRust}, - sabi_types::{Constructor,MovePtr}, - std_types::utypeid::{UTypeId,new_utypeid}, - prefix_type::{PrefixTypeTrait,WithMetadata}, + prefix_type::{PrefixTypeTrait, WithMetadata}, + sabi_types::{Constructor, MovePtr}, + std_types::utypeid::{new_utypeid, UTypeId}, + traits::IntoReprRust, }; // #[cfg(test)] -#[cfg(all(test,not(feature="only_new_tests")))] +#[cfg(all(test, not(feature = "only_new_tests")))] mod test; mod private { use super::*; /** -Ffi-safe equivalent of `std::box::Box`. - -# Example - -Declaring a recursive datatype. + Ffi-safe equivalent of `std::box::Box`. -``` -use abi_stable::{ - std_types::{RBox,RString}, - StableAbi, -}; - -#[repr(u8)] -#[derive(StableAbi)] -enum Command{ - SendProduct{ - id:u64, - }, - GoProtest{ - cause:RString, - place:RString, - }, - SendComplaint{ - cause:RString, - website:RString, - }, - WithMetadata{ - command:RBox, - metadata:RString, - }, -} + # Example + Declaring a recursive datatype. -``` + ``` + use abi_stable::{ + std_types::{RBox,RString}, + StableAbi, + }; - */ + #[repr(u8)] + #[derive(StableAbi)] + enum Command{ + SendProduct{ + id:u64, + }, + GoProtest{ + cause:RString, + place:RString, + }, + SendComplaint{ + cause:RString, + website:RString, + }, + WithMetadata{ + command:RBox, + metadata:RString, + }, + } + + + ``` + + */ #[repr(C)] #[derive(StableAbi)] pub struct RBox { @@ -89,7 +87,7 @@ enum Command{ impl RBox { /// Constucts an `RBox` from a value. /// - /// # Example + /// # Example /// /// ``` /// use abi_stable::std_types::RBox; @@ -110,7 +108,7 @@ enum Command{ /// Converts a `Box` to an `RBox`,reusing its heap allocation. /// - /// # Example + /// # Example /// /// ``` /// use abi_stable::std_types::RBox; @@ -134,7 +132,7 @@ enum Command{ /// /// ``` /// use std::mem::ManuallyDrop; - /// + /// /// use abi_stable::{ /// pointer_trait::OwnedPointer, /// sabi_types::RSmallBox, @@ -143,11 +141,11 @@ enum Command{ /// /// let b=RSmallBox::<_,[u8;1]>::new(77u8); /// let rbox:RBox<_>=b.in_move_ptr(|x| RBox::from_move_ptr(x) ); - /// + /// /// assert_eq!(*rbox,77); /// /// ``` - pub fn from_move_ptr(p: MovePtr<'_,T>) -> RBox { + pub fn from_move_ptr(p: MovePtr<'_, T>) -> RBox { MovePtr::into_rbox(p) } @@ -188,8 +186,8 @@ enum Command{ pub use self::private::RBox; -unsafe impl GetPointerKind for RBox{ - type Kind=PK_SmartPointer; +unsafe impl GetPointerKind for RBox { + type Kind = PK_SmartPointer; type PtrTarget = T; } @@ -224,10 +222,10 @@ impl RBox { let this = ManuallyDrop::new(this); unsafe { - let this_vtable =this.vtable(); - let other_vtable= VTableGetter::LIB_VTABLE; - if ::std::ptr::eq(this_vtable.0.to_raw_ptr(), other_vtable.0.to_raw_ptr())|| - this_vtable.type_id()==other_vtable.type_id() + let this_vtable = this.vtable(); + let other_vtable = VTableGetter::LIB_VTABLE; + if ::std::ptr::eq(this_vtable.0.to_raw_ptr(), other_vtable.0.to_raw_ptr()) + || this_vtable.type_id() == other_vtable.type_id() { Box::from_raw(this.data()) } else { @@ -235,7 +233,8 @@ impl RBox { // Just deallocating the Box<_>. without dropping the inner value (this.vtable().destructor())( this.data() as *mut (), - CallReferentDrop::No,Deallocate::Yes + CallReferentDrop::No, + Deallocate::Yes, ); ret } @@ -266,9 +265,7 @@ impl RBox { /// pub fn into_pin(self) -> Pin> { // safety: this is the same as what Box does. - unsafe { - Pin::new_unchecked(self) - } + unsafe { Pin::new_unchecked(self) } } } @@ -280,55 +277,47 @@ impl DerefMut for RBox { ///////////////////////////////////////////////////////////////// - - -unsafe impl OwnedPointer for RBox{ +unsafe impl OwnedPointer for RBox { #[inline] - unsafe fn get_move_ptr(this: &mut ManuallyDrop) -> MovePtr<'_, T>{ + unsafe fn get_move_ptr(this: &mut ManuallyDrop) -> MovePtr<'_, T> { MovePtr::from_raw(this.data_mut()) } #[inline] - unsafe fn drop_allocation(this: &mut ManuallyDrop){ + unsafe fn drop_allocation(this: &mut ManuallyDrop) { unsafe { let data: *mut T = this.data(); - (this.vtable().destructor())(data as *mut (), CallReferentDrop::No,Deallocate::Yes); + (this.vtable().destructor())(data as *mut (), CallReferentDrop::No, Deallocate::Yes); } } } - ///////////////////////////////////////////////////////////////// - -impl Borrow for RBox{ - fn borrow(&self)->&T{ +impl Borrow for RBox { + fn borrow(&self) -> &T { self } } - -impl BorrowMut for RBox{ - fn borrow_mut(&mut self)->&mut T{ +impl BorrowMut for RBox { + fn borrow_mut(&mut self) -> &mut T { self } } - -impl AsRef for RBox{ - fn as_ref(&self)->&T{ +impl AsRef for RBox { + fn as_ref(&self) -> &T { self } } - -impl AsMut for RBox{ - fn as_mut(&mut self)->&mut T{ +impl AsMut for RBox { + fn as_mut(&mut self) -> &mut T { self } } - ///////////////////////////////////////////////////////////////// impl_from_rust_repr! { @@ -387,9 +376,9 @@ impl Unpin for RBox {} /////////////////////////////////////////////////////////////// -impl Iterator for RBox +impl Iterator for RBox where - I: Iterator + I: Iterator, { type Item = I::Item; fn next(&mut self) -> Option { @@ -406,9 +395,9 @@ where } } -impl DoubleEndedIterator for RBox +impl DoubleEndedIterator for RBox where - I: DoubleEndedIterator + I: DoubleEndedIterator, { fn next_back(&mut self) -> Option { (**self).next_back() @@ -418,26 +407,22 @@ where } } -impl ExactSizeIterator for RBox +impl ExactSizeIterator for RBox where - I: ExactSizeIterator + I: ExactSizeIterator, { fn len(&self) -> usize { (**self).len() } } -impl FusedIterator for RBox -where - I: FusedIterator -{} - +impl FusedIterator for RBox where I: FusedIterator {} /////////////////////////////////////////////////////////////// -impl Future for RBox +impl Future for RBox where - F: Future + Unpin + F: Future + Unpin, { type Output = F::Output; @@ -448,9 +433,9 @@ where /////////////////////////////////////////////////////////////// -impl StdError for RBox +impl StdError for RBox where - T: StdError + T: StdError, { #[allow(deprecated, deprecated_in_future)] fn description(&self) -> &str { @@ -469,11 +454,9 @@ where /////////////////////////////////////////////////////////////// - - -impl Read for RBox +impl Read for RBox where - T: Read + T: Read, { #[inline] fn read(&mut self, buf: &mut [u8]) -> io::Result { @@ -501,9 +484,9 @@ where } } -impl Write for RBox +impl Write for RBox where - T: Write + T: Write, { #[inline] fn write(&mut self, buf: &[u8]) -> io::Result { @@ -531,9 +514,9 @@ where } } -impl Seek for RBox +impl Seek for RBox where - T: Seek + T: Seek, { #[inline] fn seek(&mut self, pos: io::SeekFrom) -> io::Result { @@ -541,9 +524,9 @@ where } } -impl BufRead for RBox +impl BufRead for RBox where - T: BufRead + T: BufRead, { #[inline] fn fill_buf(&mut self) -> io::Result<&[u8]> { @@ -568,8 +551,7 @@ where /////////////////////////////////////////////////////////////// - -impl Hasher for RBox +impl Hasher for RBox where T: Hasher, { @@ -624,7 +606,7 @@ impl Drop for RBox { unsafe { let data = self.data(); let dstr = RBox::vtable(self).destructor(); - dstr(data as *mut (), CallReferentDrop::Yes,Deallocate::Yes); + dstr(data as *mut (), CallReferentDrop::Yes, Deallocate::Yes); } } } @@ -636,34 +618,32 @@ impl Drop for RBox { #[sabi(kind(Prefix))] #[sabi(missing_field(panic))] pub(crate) struct BoxVtable { - type_id:Constructor, + type_id: Constructor, #[sabi(last_prefix_field)] - destructor: unsafe extern "C" fn(*mut (), CallReferentDrop,Deallocate), + destructor: unsafe extern "C" fn(*mut (), CallReferentDrop, Deallocate), _marker: NonOwningPhantom, } struct VTableGetter<'a, T>(&'a T); impl<'a, T: 'a> VTableGetter<'a, T> { - const DEFAULT_VTABLE:BoxVtable=BoxVtable{ - type_id:Constructor( new_utypeid::> ), + const DEFAULT_VTABLE: BoxVtable = BoxVtable { + type_id: Constructor(new_utypeid::>), destructor: destroy_box::, _marker: NonOwningPhantom::NEW, }; - staticref!{ - const WM_DEFAULT: WithMetadata> = + staticref! { + const WM_DEFAULT: WithMetadata> = WithMetadata::new(PrefixTypeTrait::METADATA, Self::DEFAULT_VTABLE); } // The VTABLE for this type in this executable/library - const LIB_VTABLE: BoxVtable_Ref = unsafe{ - BoxVtable_Ref(Self::WM_DEFAULT.as_prefix()) - }; + const LIB_VTABLE: BoxVtable_Ref = unsafe { BoxVtable_Ref(Self::WM_DEFAULT.as_prefix()) }; #[cfg(test)] - staticref!{ - const WM_FOR_TESTING: WithMetadata> = + staticref! { + const WM_FOR_TESTING: WithMetadata> = WithMetadata::new( PrefixTypeTrait::METADATA, BoxVtable { @@ -679,7 +659,11 @@ impl<'a, T: 'a> VTableGetter<'a, T> { BoxVtable_Ref(Self::WM_FOR_TESTING.as_prefix()); } -unsafe extern "C" fn destroy_box(ptr: *mut (), call_drop: CallReferentDrop,dealloc:Deallocate) { +unsafe extern "C" fn destroy_box( + ptr: *mut (), + call_drop: CallReferentDrop, + dealloc: Deallocate, +) { extern_fn_panic_handling! {no_early_return; let ptr = ptr as *mut T; if let CallReferentDrop::Yes=call_drop { diff --git a/abi_stable/src/std_types/boxed/test.rs b/abi_stable/src/std_types/boxed/test.rs index f640d034..f61f1ded 100644 --- a/abi_stable/src/std_types/boxed/test.rs +++ b/abi_stable/src/std_types/boxed/test.rs @@ -2,14 +2,10 @@ use super::*; use std::sync::Arc; -use crate::{ - sabi_types::MovePtr, - test_utils::{must_panic}, -}; +use crate::{sabi_types::MovePtr, test_utils::must_panic}; use abi_stable_shared::file_span; - #[test] fn new_and_drop() { let arc_a = Arc::new(100); @@ -74,54 +70,42 @@ fn mutated() { assert_eq!(*a, 1337); } - #[test] -fn with_move_ptr_runs(){ +fn with_move_ptr_runs() { let rbox = ManuallyDrop::new(RBox::new(rvec![3])); - - must_panic(file_span!(),||{ - OwnedPointer::with_move_ptr(rbox,|_|{ + + must_panic(file_span!(), || { + OwnedPointer::with_move_ptr(rbox, |_| { panic!(); }); - }).unwrap(); - + }) + .unwrap(); let rbox = ManuallyDrop::new(RBox::new(rvec![5])); - assert_eq!( - OwnedPointer::with_move_ptr(rbox,|_|10), - 10 - ); + assert_eq!(OwnedPointer::with_move_ptr(rbox, |_| 10), 10); } #[test] -fn owned_pointer_trait(){ - let arc=Arc::new(10); +fn owned_pointer_trait() { + let arc = Arc::new(10); + unsafe { + let cloned_arc = ManuallyDrop::new(RBox::new(arc.clone())); + OwnedPointer::with_move_ptr(cloned_arc, |move_ptr| { + assert_eq!(Arc::strong_count(&move_ptr), 2); - unsafe{ - let cloned_arc=ManuallyDrop::new(RBox::new(arc.clone())); - - OwnedPointer::with_move_ptr(cloned_arc,|move_ptr|{ - assert_eq!(Arc::strong_count(&move_ptr),2); - - let moved_arc=MovePtr::into_inner(move_ptr); - assert_eq!(Arc::strong_count(&moved_arc),2); + let moved_arc = MovePtr::into_inner(move_ptr); + assert_eq!(Arc::strong_count(&moved_arc), 2); }); } - assert_eq!(Arc::strong_count(&arc),1); - unsafe{ - let cloned_arc=ManuallyDrop::new(RBox::new(arc.clone())); - - OwnedPointer::with_move_ptr(cloned_arc,|move_ptr|{ - assert_eq!(Arc::strong_count(&move_ptr),2); + assert_eq!(Arc::strong_count(&arc), 1); + unsafe { + let cloned_arc = ManuallyDrop::new(RBox::new(arc.clone())); + + OwnedPointer::with_move_ptr(cloned_arc, |move_ptr| { + assert_eq!(Arc::strong_count(&move_ptr), 2); }); } - assert_eq!(Arc::strong_count(&arc),1); + assert_eq!(Arc::strong_count(&arc), 1); } - - - - - - diff --git a/abi_stable/src/std_types/cmp_ordering.rs b/abi_stable/src/std_types/cmp_ordering.rs index 20ec83c5..c5fd9a94 100644 --- a/abi_stable/src/std_types/cmp_ordering.rs +++ b/abi_stable/src/std_types/cmp_ordering.rs @@ -2,7 +2,6 @@ Contains the ffi-safe equivalent of `std::cmp::Ordering`. */ - use std::cmp::Ordering; /** @@ -41,7 +40,7 @@ pub enum RCmpOrdering { Greater, } -impl RCmpOrdering{ +impl RCmpOrdering { /// Converts this `RCmpOrdering` into a `std::cmp::Ordering`; /// /// # Example @@ -49,7 +48,7 @@ impl RCmpOrdering{ /// ``` /// use abi_stable::std_types::RCmpOrdering; /// use std::cmp::Ordering; - /// + /// /// /// assert_eq!( RCmpOrdering::Less.into_ordering(), Ordering::Less ); /// assert_eq!( RCmpOrdering::Equal.into_ordering(), Ordering::Equal ); @@ -57,7 +56,7 @@ impl RCmpOrdering{ /// /// ``` #[inline] - pub fn into_ordering(self)->Ordering{ + pub fn into_ordering(self) -> Ordering { self.into() } } diff --git a/abi_stable/src/std_types/cow.rs b/abi_stable/src/std_types/cow.rs index 279023a7..d9bff46e 100644 --- a/abi_stable/src/std_types/cow.rs +++ b/abi_stable/src/std_types/cow.rs @@ -2,39 +2,38 @@ Contains the ffi-safe equivalent of `std::borrow::Cow`,and related items. */ -use std::{borrow::{Borrow,Cow}, fmt, ops::Deref}; +use std::{ + borrow::{Borrow, Cow}, + fmt, + ops::Deref, +}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; #[allow(unused_imports)] -use core_extensions::{ - SelfOps, - matches, -}; +use core_extensions::{matches, SelfOps}; use crate::{ - StableAbi, std_types::{RSlice, RStr, RString, RVec}, traits::IntoReprC, + StableAbi, }; // #[cfg(test)] -#[cfg(all(test,not(feature="only_new_tests")))] +#[cfg(all(test, not(feature = "only_new_tests")))] mod tests; - //////////////////////////////////////////////////////////////////// - /// The main bound of `RCow<_>`. /// /// All the methods in this trait convert the parameter to the return type. pub trait BorrowOwned<'a>: 'a + ToOwned { /// The owned type, stored in `RCow::Owned` type ROwned; - + /// The borrowed type, stored in `RCow::Borrowed` - type RBorrowed: 'a + Copy ; + type RBorrowed: 'a + Copy; fn r_borrow(this: &'a Self::ROwned) -> Self::RBorrowed; fn r_to_owned(this: Self::RBorrowed) -> Self::ROwned; @@ -209,8 +208,8 @@ Note:this example allocates when the number is neither a multiple of 5 or 3. #[derive(StableAbi)] #[sabi( not_stableabi(B), - bound=">::RBorrowed: StableAbi", - bound=">::ROwned : StableAbi", + bound = ">::RBorrowed: StableAbi", + bound = ">::ROwned : StableAbi" )] pub enum RCow<'a, B> where @@ -222,12 +221,11 @@ where use self::RCow::{Borrowed, Owned}; - // /////////////////////////////////////////////////////////////////////////// impl<'a, B> RCow<'a, B> where - B: BorrowOwned<'a>+?Sized, + B: BorrowOwned<'a> + ?Sized, { /// Get a mutable reference to the owned form of RCow, /// converting to the owned form if it is currently the borrowed form. @@ -236,17 +234,17 @@ where /// /// ``` /// use abi_stable::std_types::RCow; - /// + /// /// let mut cow:RCow<'_,str>=RCow::from("Hello"); - /// + /// /// assert_eq!(&*cow,"Hello"); /// assert!(cow.is_borrowed()); - /// + /// /// cow.to_mut().push_str(", world!"); - /// + /// /// assert!(cow.is_owned()); /// assert_eq!(cow,RCow::from("Hello, world!")); - /// + /// /// ``` pub fn to_mut(&mut self) -> &mut B::ROwned { if let Borrowed(v) = *self { @@ -265,16 +263,16 @@ where /// /// ``` /// use abi_stable::std_types::RCow; - /// + /// /// let mut cow:RCow<'_,str>=RCow::from("Hello"); /// /// assert_eq!(&*cow,"Hello"); - /// + /// /// let mut buff=cow.into_owned(); /// buff.push_str(", world!"); - /// + /// /// assert_eq!(&*buff,"Hello, world!"); - /// + /// /// ``` pub fn into_owned(self) -> B::ROwned { match self { @@ -298,7 +296,7 @@ where /// assert_eq!( cow.borrowed(), RSlice::from_slice(&[0,1,2,3]) ); /// } /// ``` - pub fn borrowed<'b:'a>(&'b self)->>::RBorrowed{ + pub fn borrowed<'b: 'a>(&'b self) -> >::RBorrowed { match self { Borrowed(x) => *x, Owned(x) => B::r_borrow(x), @@ -311,7 +309,7 @@ where /// /// ``` /// use abi_stable::std_types::RCow; - /// + /// /// { /// let cow:RCow<'_,[u8]>=RCow::from(&[0,1,2,3][..]); /// assert!( cow.is_borrowed() ); @@ -320,10 +318,10 @@ where /// let cow:RCow<'_,[u8]>=RCow::from(vec![0,1,2,3]); /// assert!( !cow.is_borrowed() ); /// } - /// + /// /// ``` - pub fn is_borrowed(&self)->bool{ - matches!(self, Borrowed{..}) + pub fn is_borrowed(&self) -> bool { + matches!(self, Borrowed { .. }) } /// Whether this is an owning RCow. @@ -332,28 +330,27 @@ where /// /// ``` /// use abi_stable::std_types::RCow; - /// + /// /// let cow:RCow<'_,[u8]>=RCow::from(&[0,1,2,3][..]); /// assert!( !cow.is_owned() ); - /// + /// /// let cow:RCow<'_,[u8]>=RCow::from(vec![0,1,2,3]); /// assert!( cow.is_owned() ); - /// + /// /// ``` - pub fn is_owned(&self)->bool{ - matches!(self, Owned{..}) + pub fn is_owned(&self) -> bool { + matches!(self, Owned { .. }) } } - #[allow(dead_code)] #[cfg(test)] impl<'a, B> RCow<'a, B> where - B: BorrowOwned<'a>+?Sized, + B: BorrowOwned<'a> + ?Sized, { /// Access this as a borrowing RCow.Returns None if it's not a borrowing one. - fn as_borrowed(&self)->Option{ + fn as_borrowed(&self) -> Option { match *self { Borrowed(x) => Some(x), Owned(_) => None, @@ -361,7 +358,7 @@ where } /// Access this as an owned RCow.Returns None if it's not an owned one. - fn as_owned(&self)->Option<&B::ROwned>{ + fn as_owned(&self) -> Option<&B::ROwned> { match self { Borrowed(_) => None, Owned(x) => Some(x), @@ -369,17 +366,16 @@ where } } - impl<'a, B> Copy for RCow<'a, B> where - B: BorrowOwned<'a>+?Sized, + B: BorrowOwned<'a> + ?Sized, B::ROwned: Copy, { } impl<'a, B> Clone for RCow<'a, B> where - B: BorrowOwned<'a>+?Sized, + B: BorrowOwned<'a> + ?Sized, B::ROwned: Clone, { fn clone(&self) -> Self { @@ -392,10 +388,10 @@ where impl<'a, B> Deref for RCow<'a, B> where - B: BorrowOwned<'a>+?Sized, + B: BorrowOwned<'a> + ?Sized, { type Target = B; - + #[inline] fn deref(&self) -> &Self::Target { match self { @@ -407,30 +403,27 @@ where //////////////////// - -impl<'a,B> Borrow for RCow<'a, B> +impl<'a, B> Borrow for RCow<'a, B> where - B: BorrowOwned<'a>+?Sized, + B: BorrowOwned<'a> + ?Sized, { - fn borrow(&self)->&B{ + fn borrow(&self) -> &B { self } } - -impl<'a,B> AsRef for RCow<'a, B> +impl<'a, B> AsRef for RCow<'a, B> where - B: BorrowOwned<'a>+?Sized, + B: BorrowOwned<'a> + ?Sized, { - fn as_ref(&self)->&B{ + fn as_ref(&self) -> &B { self } } //////////////////////////// - -slice_like_impl_cmp_traits!{ +slice_like_impl_cmp_traits! { impl[] RCow<'_, [T]>, where[T: Clone]; Vec, @@ -439,19 +432,19 @@ slice_like_impl_cmp_traits!{ } #[cfg(feature = "const_params")] -slice_like_impl_cmp_traits!{ +slice_like_impl_cmp_traits! { impl[const N: usize] RCow<'_, [T]>, where[T: Clone]; [U; N], } -slice_like_impl_cmp_traits!{ +slice_like_impl_cmp_traits! { impl[] RCow<'_, [T]>, where[T: Clone, U: Clone]; Cow<'_, [U]>, } -deref_coerced_impl_cmp_traits!{ +deref_coerced_impl_cmp_traits! { RCow<'_, str>; coerce_to = str, [ @@ -462,10 +455,9 @@ deref_coerced_impl_cmp_traits!{ ] } - shared_impls! { mod=slice_impls - new_type=RCow['a][] + new_type=RCow['a][] extra[B] constrained[B] where [ B:BorrowOwned<'a>+?Sized ], @@ -486,14 +478,12 @@ impl_into_rust_repr! { } } - //////////////////////////////////////////////////////////// - impl_from_rust_repr! { impl['a,B] From> for RCow<'a,B> - where [ - B: BorrowOwned<'a>+?Sized , + where [ + B: BorrowOwned<'a>+?Sized , ]{ fn(this){ match this{ @@ -504,111 +494,105 @@ impl_from_rust_repr! { } } - - -impl<'a> From<&'a str> for RCow<'a,str>{ +impl<'a> From<&'a str> for RCow<'a, str> { #[inline] - fn from(this:&'a str)->Self{ + fn from(this: &'a str) -> Self { RCow::Borrowed(this.into_c()) } } -impl<'a> From> for RCow<'a,str>{ +impl<'a> From> for RCow<'a, str> { #[inline] - fn from(this:RStr<'a>)->Self{ + fn from(this: RStr<'a>) -> Self { RCow::Borrowed(this) } } -impl<'a> From for RCow<'a,str>{ +impl<'a> From for RCow<'a, str> { #[inline] - fn from(this:String)->Self{ + fn from(this: String) -> Self { RCow::Owned(this.into()) } } -impl<'a> From<&'a String> for RCow<'a,str>{ +impl<'a> From<&'a String> for RCow<'a, str> { #[inline] - fn from(this:&'a String)->Self{ + fn from(this: &'a String) -> Self { RCow::Borrowed(this.as_str().into()) } } -impl<'a> From for RCow<'a,str>{ +impl<'a> From for RCow<'a, str> { #[inline] - fn from(this:RString)->Self{ + fn from(this: RString) -> Self { RCow::Owned(this) } } -impl<'a> From<&'a RString> for RCow<'a,str>{ +impl<'a> From<&'a RString> for RCow<'a, str> { #[inline] - fn from(this:&'a RString)->Self{ + fn from(this: &'a RString) -> Self { RCow::Borrowed(this.as_rstr()) } } - - -impl<'a,T> From<&'a [T]> for RCow<'a,[T]> -where - T:Clone +impl<'a, T> From<&'a [T]> for RCow<'a, [T]> +where + T: Clone, { #[inline] - fn from(this:&'a [T])->Self{ + fn from(this: &'a [T]) -> Self { RCow::Borrowed(RSlice::from(this)) } } -impl<'a,T> RCow<'a,[T]> -where - T:Clone +impl<'a, T> RCow<'a, [T]> +where + T: Clone, { /// For converting a `&'a [T]` to an `RCow<'a,[T]>`, /// most useful when converting from `&'a [T;N]` because it coerces the array to a slice. #[inline] - pub fn from_slice(this:&'a [T])->Self{ + pub fn from_slice(this: &'a [T]) -> Self { RCow::Borrowed(RSlice::from(this)) } } -impl<'a,T> From> for RCow<'a,[T]> -where - T:Clone +impl<'a, T> From> for RCow<'a, [T]> +where + T: Clone, { #[inline] - fn from(this:RSlice<'a,T>)->Self{ + fn from(this: RSlice<'a, T>) -> Self { RCow::Borrowed(this) } } -impl<'a,T> From> for RCow<'a,[T]> -where - T:Clone +impl<'a, T> From> for RCow<'a, [T]> +where + T: Clone, { #[inline] - fn from(this:Vec)->Self{ + fn from(this: Vec) -> Self { RCow::Owned(RVec::from(this)) } } -impl<'a,T> From> for RCow<'a,[T]> -where - T:Clone +impl<'a, T> From> for RCow<'a, [T]> +where + T: Clone, { #[inline] - fn from(this:RVec)->Self{ + fn from(this: RVec) -> Self { RCow::Owned(this) } } - //////////////////////////////////////////////////////////// - impl<'a, B> fmt::Display for RCow<'a, B> where - B: BorrowOwned<'a> +?Sized, + B: BorrowOwned<'a> + ?Sized, B: fmt::Display, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -616,12 +600,10 @@ where } } - //////////////////////////////////////////////////////////// - /** -Deserializes an `RCow<'a,[u8]>` that borrows the slice from the deserializer +Deserializes an `RCow<'a,[u8]>` that borrows the slice from the deserializer whenever possible. # Example @@ -657,29 +639,25 @@ assert!( deserialized_slice.slice.is_borrowed() ); ``` */ -pub fn deserialize_borrowed_bytes<'de,'a,D>(deserializer: D) -> Result, D::Error> +pub fn deserialize_borrowed_bytes<'de, 'a, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, - 'de:'a + 'de: 'a, { #[derive(Deserialize)] - struct BorrowingCowSlice<'a>{ + struct BorrowingCowSlice<'a> { #[serde(borrow)] - cow:Cow<'a,[u8]> + cow: Cow<'a, [u8]>, } - as Deserialize<'de>>::deserialize(deserializer) - .map(|x|{ - match x.cow { - Cow::Borrowed(y)=>RCow::Borrowed(y.into()), - Cow::Owned(y) =>RCow::Owned(y.into()), - } - }) + as Deserialize<'de>>::deserialize(deserializer).map(|x| match x.cow { + Cow::Borrowed(y) => RCow::Borrowed(y.into()), + Cow::Owned(y) => RCow::Owned(y.into()), + }) } - /** -Deserializes an `RCow<'a,str>` that borrows the string from the deserializer +Deserializes an `RCow<'a,str>` that borrows the string from the deserializer whenever possible. @@ -719,63 +697,53 @@ assert!( deserialized_slice.slice.is_borrowed() ); */ -pub fn deserialize_borrowed_str<'de,'a,D>(deserializer: D) -> Result, D::Error> +pub fn deserialize_borrowed_str<'de, 'a, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, - 'de:'a + 'de: 'a, { #[derive(Deserialize)] - struct BorrowingCowStr<'a>( - #[serde(borrow)] - Cow<'a,str> - ); + struct BorrowingCowStr<'a>(#[serde(borrow)] Cow<'a, str>); - as Deserialize<'de>>::deserialize(deserializer) - .map(|x| RCow::from(x.0) ) + as Deserialize<'de>>::deserialize(deserializer).map(|x| RCow::from(x.0)) } -impl<'de, 'a,T> Deserialize<'de> for RCow<'a, [T]> -where - T:Clone+Deserialize<'de>, +impl<'de, 'a, T> Deserialize<'de> for RCow<'a, [T]> +where + T: Clone + Deserialize<'de>, { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { - >::deserialize(deserializer) - .map(RCow::<'a,[T]>::Owned) + >::deserialize(deserializer).map(RCow::<'a, [T]>::Owned) } } - - -impl<'de,'a> Deserialize<'de> for RCow<'a, str>{ +impl<'de, 'a> Deserialize<'de> for RCow<'a, str> { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { - as Deserialize<'de>>::deserialize(deserializer) - .map(RCow::from) + as Deserialize<'de>>::deserialize(deserializer).map(RCow::from) } } impl<'de, 'a, T> Deserialize<'de> for RCow<'a, T> where - T: Clone+Deserialize<'de>, + T: Clone + Deserialize<'de>, { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { - - >::deserialize(deserializer) - .map(RCow::Owned) + >::deserialize(deserializer).map(RCow::Owned) } } impl<'a, B> Serialize for RCow<'a, B> where - B: BorrowOwned<'a>+?Sized, + B: BorrowOwned<'a> + ?Sized, B: Serialize, { fn serialize(&self, serializer: S) -> Result @@ -815,13 +783,12 @@ assert!( deserialized_slice.cow.is_borrowed() ); */ #[derive(Deserialize)] #[serde(transparent)] -pub struct BorrowingRCowU8Slice<'a>{ +pub struct BorrowingRCowU8Slice<'a> { /// The deserialized `Cow`. - #[serde(borrow,deserialize_with="deserialize_borrowed_bytes")] - pub cow:RCow<'a,[u8]> + #[serde(borrow, deserialize_with = "deserialize_borrowed_bytes")] + pub cow: RCow<'a, [u8]>, } - /** A helper type,to deserialize a `RCow<'a,str>` which borrows from the deserializer. @@ -851,14 +818,10 @@ assert!( deserialized_slice.cow.is_borrowed() ); */ #[derive(Deserialize)] #[serde(transparent)] -pub struct BorrowingRCowStr<'a>{ +pub struct BorrowingRCowStr<'a> { /// The deserialized `Cow`. - #[serde(borrow,deserialize_with="deserialize_borrowed_str")] - pub cow:RCow<'a,str> + #[serde(borrow, deserialize_with = "deserialize_borrowed_str")] + pub cow: RCow<'a, str>, } - - - ////////////////////////////////////////////////////////////////////////////////////// - diff --git a/abi_stable/src/std_types/cow/tests.rs b/abi_stable/src/std_types/cow/tests.rs index da1dd21a..50f72167 100644 --- a/abi_stable/src/std_types/cow/tests.rs +++ b/abi_stable/src/std_types/cow/tests.rs @@ -1,51 +1,62 @@ use super::*; #[test] -fn from_into_cow(){ +fn from_into_cow() { macro_rules! from_tests { ( $from:ident, Cow<$cow_param:ty> - ) => ({ + ) => {{ { - let borrowed_rcow=$from.into_c().piped(RCow::<$cow_param>::Borrowed); + let borrowed_rcow = $from.into_c().piped(RCow::<$cow_param>::Borrowed); assert_eq!( - $from.piped(Cow::<$cow_param>::Borrowed).piped(RCow::from).as_borrowed(), + $from + .piped(Cow::<$cow_param>::Borrowed) + .piped(RCow::from) + .as_borrowed(), borrowed_rcow.as_borrowed(), ); } { - let owned_rcow=$from.to_owned().into_c().piped(RCow::<$cow_param>::Owned); + let owned_rcow = $from.to_owned().into_c().piped(RCow::<$cow_param>::Owned); assert_eq!( - $from.to_owned().piped(Cow::<$cow_param>::Owned).piped(RCow::from).as_owned(), + $from + .to_owned() + .piped(Cow::<$cow_param>::Owned) + .piped(RCow::from) + .as_owned(), owned_rcow.as_owned(), ); } - }) + }}; } - + { - let line="what the heck"; - from_tests!{ line, Cow< str > } + let line = "what the heck"; + from_tests! { line, Cow< str > } } { - let list=[0,1,2,3]; - let list=&list[..]; - from_tests!{ list, Cow< [u8] > } + let list = [0, 1, 2, 3]; + let list = &list[..]; + from_tests! { list, Cow< [u8] > } } { - let value=&1000u32; + let value = &1000u32; { - let borrowed_rcow=value.piped(RCow::::Borrowed); + let borrowed_rcow = value.piped(RCow::::Borrowed); assert_eq!( value.piped(Cow::Borrowed).piped(RCow::from).as_borrowed(), borrowed_rcow.as_borrowed(), ); } { - let owned_rcow=value.to_owned().piped(RCow::::Owned); + let owned_rcow = value.to_owned().piped(RCow::::Owned); assert_eq!( - value.to_owned().piped(Cow::::Owned).piped(RCow::from).as_owned(), + value + .to_owned() + .piped(Cow::::Owned) + .piped(RCow::from) + .as_owned(), owned_rcow.as_owned(), ); } @@ -53,116 +64,93 @@ fn from_into_cow(){ } #[test] -fn to_mut(){ - +fn to_mut() { { - let mut value=RCow::::Borrowed(&100); + let mut value = RCow::::Borrowed(&100); assert_eq!(*value, 100); - *value.to_mut()=137; + *value.to_mut() = 137; assert_eq!(*value, 137); } { - let mut value=RCow::::Borrowed("what".into_c()); + let mut value = RCow::::Borrowed("what".into_c()); assert_eq!(&*value, "what"); - - *value.to_mut()="the".piped(RString::from); + + *value.to_mut() = "the".piped(RString::from); assert_eq!(&*value, "the"); } { - let arr=[0,1,2,3]; + let arr = [0, 1, 2, 3]; - let mut value=RCow::<[u32]>::Borrowed( (&arr[..]).into() ); - assert_eq!(&*value, &arr[..] ); - *value.to_mut()=vec![99,100,101].into_c(); - assert_eq!(&*value, &[99,100,101][..]); + let mut value = RCow::<[u32]>::Borrowed((&arr[..]).into()); + assert_eq!(&*value, &arr[..]); + *value.to_mut() = vec![99, 100, 101].into_c(); + assert_eq!(&*value, &[99, 100, 101][..]); } - - } - #[test] -fn into_owned(){ - +fn into_owned() { { - let value=RCow::::Borrowed(&100); - let value:u32=value.into_owned(); - assert_eq!(value,100); + let value = RCow::::Borrowed(&100); + let value: u32 = value.into_owned(); + assert_eq!(value, 100); } { - let value=RCow::::Borrowed("what".into_c()); - let value:RString=value.into_owned(); - assert_eq!(&*value,"what"); + let value = RCow::::Borrowed("what".into_c()); + let value: RString = value.into_owned(); + assert_eq!(&*value, "what"); } { - let arr=[0,1,2,3]; - let value=RCow::<[u32]>::Borrowed( (&arr[..]).into() ); - let value:RVec=value.into_owned(); - assert_eq!(&*value,&arr[..]); + let arr = [0, 1, 2, 3]; + let value = RCow::<[u32]>::Borrowed((&arr[..]).into()); + let value: RVec = value.into_owned(); + assert_eq!(&*value, &arr[..]); } - - } - - #[test] -fn deserialize(){ - - {// Borrowed string - let json=r##" "what the hell" "##; - let str_borr="what the hell".piped(RStr::from); +fn deserialize() { + { + // Borrowed string + let json = r##" "what the hell" "##; + let str_borr = "what the hell".piped(RStr::from); - let what:BorrowingRCowStr<'_>=serde_json::from_str(json).unwrap(); + let what: BorrowingRCowStr<'_> = serde_json::from_str(json).unwrap(); - assert_eq!( - what.cow.as_borrowed(), - Some(str_borr), - ); + assert_eq!(what.cow.as_borrowed(), Some(str_borr),); } - {// Owned string - let json=r##" "what \nthe hell" "##; - let str_owned="what \nthe hell".piped(RString::from); + { + // Owned string + let json = r##" "what \nthe hell" "##; + let str_owned = "what \nthe hell".piped(RString::from); - let what:RCow<'_,str>=serde_json::from_str(json).unwrap(); + let what: RCow<'_, str> = serde_json::from_str(json).unwrap(); - assert_eq!( - what.as_owned(), - Some(&str_owned), - ); + assert_eq!(what.as_owned(), Some(&str_owned),); } - {// Owned list - let json=r##" [0,1,2,3] "##; - - let what:RCow<'_,[u8]>=serde_json::from_str(json).unwrap(); - - assert_eq!( - what.as_owned(), - Some(&vec![0,1,2,3].into_c()), - ); - } - {// Borrowed list,using bincode. - let list=[0u8,1,2,3]; - let serialized=bincode::serialize(&list[..]).unwrap(); - - let what:BorrowingRCowU8Slice<'_>=bincode::deserialize(&serialized[..]).unwrap(); - - assert_eq!( - what.cow.as_borrowed(), - Some((&list[..]).into_c()), - ); - } - {// Owned value - let json=r##" 1000 "##; + { + // Owned list + let json = r##" [0,1,2,3] "##; - let what:RCow<'_,u16>=serde_json::from_str(json).unwrap(); + let what: RCow<'_, [u8]> = serde_json::from_str(json).unwrap(); - assert_eq!( - what.as_owned(), - Some(&1000), - ); + assert_eq!(what.as_owned(), Some(&vec![0, 1, 2, 3].into_c()),); + } + { + // Borrowed list,using bincode. + let list = [0u8, 1, 2, 3]; + let serialized = bincode::serialize(&list[..]).unwrap(); + + let what: BorrowingRCowU8Slice<'_> = bincode::deserialize(&serialized[..]).unwrap(); + assert_eq!(what.cow.as_borrowed(), Some((&list[..]).into_c()),); } + { + // Owned value + let json = r##" 1000 "##; + let what: RCow<'_, u16> = serde_json::from_str(json).unwrap(); -} \ No newline at end of file + assert_eq!(what.as_owned(), Some(&1000),); + } +} diff --git a/abi_stable/src/std_types/map.rs b/abi_stable/src/std_types/map.rs index e8fc3433..022f92f9 100644 --- a/abi_stable/src/std_types/map.rs +++ b/abi_stable/src/std_types/map.rs @@ -4,57 +4,47 @@ Contains the ffi-safe equivalent of `std::collections::HashMap`,and related item use std::{ borrow::Borrow, - collections::{HashMap,hash_map::RandomState}, - cmp::{Eq,PartialEq}, - fmt::{self,Debug}, - hash::{Hash,Hasher,BuildHasher}, - ops::{Index,IndexMut}, + cmp::{Eq, PartialEq}, + collections::{hash_map::RandomState, HashMap}, + fmt::{self, Debug}, + hash::{BuildHasher, Hash, Hasher}, iter::FromIterator, - ptr::NonNull, marker::PhantomData, mem, + ops::{Index, IndexMut}, + ptr::NonNull, }; #[allow(unused_imports)] use core_extensions::SelfOps; use crate::{ - DynTrait, - StableAbi, - marker_type::{ErasedObject,NonOwningPhantom,NotCopyNotClone,UnsafeIgnoredType}, erased_types::trait_objects::HasherObject, - pointer_trait::{AsPtr, AsMutPtr}, - prefix_type::{PrefixTypeTrait,WithMetadata}, - sabi_types::{RRef, RMut}, + marker_type::{ErasedObject, NonOwningPhantom, NotCopyNotClone, UnsafeIgnoredType}, + pointer_trait::{AsMutPtr, AsPtr}, + prefix_type::{PrefixTypeTrait, WithMetadata}, + sabi_types::{RMut, RRef}, std_types::*, - traits::{IntoReprRust,ErasedType}, + traits::{ErasedType, IntoReprRust}, + DynTrait, StableAbi, }; - mod entry; mod extern_fns; mod iterator_stuff; -mod map_query; mod map_key; +mod map_query; -#[cfg(all(test,not(feature="only_new_tests")))] +#[cfg(all(test, not(feature = "only_new_tests")))] mod test; -use self::{ - map_query::MapQuery, - map_key::MapKey, - entry::{BoxedREntry}, -}; +use self::{entry::BoxedREntry, map_key::MapKey, map_query::MapQuery}; pub use self::{ - iterator_stuff::{ - RefIterInterface,MutIterInterface,ValIterInterface, - IntoIter, - }, - entry::{REntry,ROccupiedEntry,RVacantEntry}, + entry::{REntry, ROccupiedEntry, RVacantEntry}, + iterator_stuff::{IntoIter, MutIterInterface, RefIterInterface, ValIterInterface}, }; - /** An ffi-safe hashmap,which wraps `std::collections::HashMap`, @@ -113,35 +103,29 @@ for Tuple2(k,v) in map { // The hasher doesn't matter unsafe_unconstrained(S), )] -pub struct RHashMap{ - map:RBox>, - vtable:VTable_Ref, +pub struct RHashMap { + map: RBox>, + vtable: VTable_Ref, } - /////////////////////////////////////////////////////////////////////////////// - -struct BoxedHashMap<'a,K,V,S>{ - map:HashMap,V,S>, - entry:Option>, +struct BoxedHashMap<'a, K, V, S> { + map: HashMap, V, S>, + entry: Option>, } /// An RHashMap iterator, /// implementing `Iterator > + !Send + !Sync + Clone` -pub type Iter<'a,K,V>= - DynTrait<'a,RBox<()>,RefIterInterface>; +pub type Iter<'a, K, V> = DynTrait<'a, RBox<()>, RefIterInterface>; /// An RHashMap iterator, /// implementing `Iterator > + !Send + !Sync` -pub type IterMut<'a,K,V>= - DynTrait<'a,RBox<()>,MutIterInterface>; +pub type IterMut<'a, K, V> = DynTrait<'a, RBox<()>, MutIterInterface>; /// An RHashMap iterator, /// implementing `Iterator > + !Send + !Sync` -pub type Drain<'a,K,V>= - DynTrait<'a,RBox<()>,ValIterInterface>; - +pub type Drain<'a, K, V> = DynTrait<'a, RBox<()>, ValIterInterface>; /// Used as the erased type of the RHashMap type. #[repr(C)] @@ -150,24 +134,19 @@ pub type Drain<'a,K,V>= // The hasher doesn't matter unsafe_unconstrained(S), )] -struct ErasedMap( - PhantomData<(K,V)>, - UnsafeIgnoredType -); +struct ErasedMap(PhantomData<(K, V)>, UnsafeIgnoredType); -unsafe impl<'a,K:'a,V:'a,S:'a> ErasedType<'a> for ErasedMap { - type Unerased=BoxedHashMap<'a,K,V,S>; +unsafe impl<'a, K: 'a, V: 'a, S: 'a> ErasedType<'a> for ErasedMap { + type Unerased = BoxedHashMap<'a, K, V, S>; } - /////////////////////////////////////////////////////////////////////////////// - -impl RHashMap{ +impl RHashMap { /// Constructs an empty RHashMap. - /// + /// /// # Example - /// + /// /// ``` /// use abi_stable::std_types::{RHashMap,RString}; /// @@ -175,44 +154,43 @@ impl RHashMap{ /// assert!(map.is_empty()); /// map.insert("Hello".into(),10); /// assert_eq!(map.is_empty(),false); - /// + /// /// ``` #[inline] - pub fn new()->RHashMap - where - Self:Default + pub fn new() -> RHashMap + where + Self: Default, { Self::default() } /// Constructs an empty RHashMap with at least the passed capacity. - /// + /// /// # Example - /// + /// /// ``` /// use abi_stable::std_types::{RHashMap,RString}; /// /// let mut map=RHashMap::::with_capacity(10); /// assert!(map.capacity()>=10); - /// + /// /// ``` #[inline] - pub fn with_capacity(capacity:usize)->RHashMap - where - Self:Default + pub fn with_capacity(capacity: usize) -> RHashMap + where + Self: Default, { - let mut this=Self::default(); + let mut this = Self::default(); this.reserve(capacity); this } } - -impl RHashMap{ +impl RHashMap { /// Constructs an empty RHashMap with the passed `hash_builder` to hash the keys. - /// + /// /// # Example - /// + /// /// ``` /// use abi_stable::std_types::{RHashMap,RString}; /// use std::collections::hash_map::RandomState; @@ -222,21 +200,21 @@ impl RHashMap{ /// assert!(map.is_empty()); /// map.insert("Hello".into(),10); /// assert_eq!(map.is_empty(),false); - /// + /// /// ``` #[inline] - pub fn with_hasher(hash_builder: S) -> RHashMap + pub fn with_hasher(hash_builder: S) -> RHashMap where - K:Eq+Hash, - S:BuildHasher+Default, + K: Eq + Hash, + S: BuildHasher + Default, { - Self::with_capacity_and_hasher(0,hash_builder) + Self::with_capacity_and_hasher(0, hash_builder) } /// Constructs an empty RHashMap with at least the passed capacity, /// and the passed `hash_builder` to hash the keys. - /// + /// /// # Example - /// + /// /// ``` /// use abi_stable::std_types::{RHashMap,RString}; /// use std::collections::hash_map::RandomState; @@ -244,36 +222,29 @@ impl RHashMap{ /// let s = RandomState::new(); /// let mut map=RHashMap::::with_capacity_and_hasher(10,s); /// assert!(map.capacity()>=10); - /// + /// /// ``` - pub fn with_capacity_and_hasher( - capacity: usize, - hash_builder: S - ) -> RHashMap + pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> RHashMap where - K:Eq+Hash, - S:BuildHasher+Default, + K: Eq + Hash, + S: BuildHasher + Default, { - let mut map=VTable::::erased_map(hash_builder); + let mut map = VTable::::erased_map(hash_builder); ErasedMap::reserve(map.as_rmut(), capacity); - RHashMap{ + RHashMap { map, - vtable:VTable::VTABLE_REF, + vtable: VTable::VTABLE_REF, } } } - -impl RHashMap{ - - fn vtable(&self)->VTable_Ref{ +impl RHashMap { + fn vtable(&self) -> VTable_Ref { self.vtable } - } - -impl RHashMap{ +impl RHashMap { /// Returns whether the map associates a value with the key. /// /// # Example @@ -287,10 +258,10 @@ impl RHashMap{ /// assert_eq!(map.contains_key("boo"),true); /// /// ``` - pub fn contains_key(&self,query:&Q)->bool + pub fn contains_key(&self, query: &Q) -> bool where - K:Borrow, - Q:Hash+Eq+?Sized + K: Borrow, + Q: Hash + Eq + ?Sized, { self.get(query).is_some() } @@ -310,15 +281,13 @@ impl RHashMap{ /// assert_eq!(map.get("boo"), Some(&0)); /// /// ``` - pub fn get(&self,query:&Q)->Option<&V> + pub fn get(&self, query: &Q) -> Option<&V> where - K:Borrow, - Q:Hash+Eq+?Sized + K: Borrow, + Q: Hash + Eq + ?Sized, { - let vtable=self.vtable(); - unsafe{ - vtable.get_elem()(self.map.as_rref(),MapQuery::new(&query)) - } + let vtable = self.vtable(); + unsafe { vtable.get_elem()(self.map.as_rref(), MapQuery::new(&query)) } } /// Returns a mutable reference to the value associated with the key. @@ -336,15 +305,13 @@ impl RHashMap{ /// assert_eq!(map.get_mut("boo"), Some(&mut 0)); /// /// ``` - pub fn get_mut(&mut self,query:&Q)->Option<&mut V> + pub fn get_mut(&mut self, query: &Q) -> Option<&mut V> where - K:Borrow, - Q:Hash+Eq+?Sized + K: Borrow, + Q: Hash + Eq + ?Sized, { - let vtable=self.vtable(); - unsafe{ - vtable.get_mut_elem()(self.map.as_rmut(),MapQuery::new(&query)) - } + let vtable = self.vtable(); + unsafe { vtable.get_mut_elem()(self.map.as_rmut(), MapQuery::new(&query)) } } /// Removes the value associated with the key. @@ -363,12 +330,12 @@ impl RHashMap{ /// assert_eq!(map.remove(&3), RNone); /// /// ``` - pub fn remove(&mut self,query:&Q)->ROption + pub fn remove(&mut self, query: &Q) -> ROption where - K:Borrow, - Q:Hash+Eq+?Sized + K: Borrow, + Q: Hash + Eq + ?Sized, { - self.remove_entry(query).map(|x| x.1 ) + self.remove_entry(query).map(|x| x.1) } /// Removes the entry for the key. @@ -387,18 +354,17 @@ impl RHashMap{ /// assert_eq!(map.remove_entry(&3), RNone); /// /// ``` - pub fn remove_entry(&mut self,query:&Q)->ROption> + pub fn remove_entry(&mut self, query: &Q) -> ROption> where - K:Borrow, - Q:Hash+Eq+?Sized + K: Borrow, + Q: Hash + Eq + ?Sized, { - let vtable=self.vtable(); - vtable.remove_entry()(self.map.as_rmut(),MapQuery::new(&query)) + let vtable = self.vtable(); + vtable.remove_entry()(self.map.as_rmut(), MapQuery::new(&query)) } } - -impl RHashMap{ +impl RHashMap { /// Returns whether the map associates a value with the key. /// /// # Example @@ -412,7 +378,7 @@ impl RHashMap{ /// assert_eq!(map.contains_key(&11),true); /// /// ``` - pub fn contains_key_p(&self,key:&K)->bool{ + pub fn contains_key_p(&self, key: &K) -> bool { self.get_p(key).is_some() } @@ -431,11 +397,9 @@ impl RHashMap{ /// assert_eq!(map.get(&12), Some(&0)); /// /// ``` - pub fn get_p(&self,key:&K)->Option<&V>{ - let vtable=self.vtable(); - unsafe{ - vtable.get_elem_p()(self.map.as_rref(),&key) - } + pub fn get_p(&self, key: &K) -> Option<&V> { + let vtable = self.vtable(); + unsafe { vtable.get_elem_p()(self.map.as_rref(), &key) } } /// Returns a mutable reference to the value associated with the key. @@ -453,11 +417,9 @@ impl RHashMap{ /// assert_eq!(map.get_mut(&12), Some(&mut 0)); /// /// ``` - pub fn get_mut_p(&mut self,key:&K)->Option<&mut V>{ - let vtable=self.vtable(); - unsafe{ - vtable.get_mut_elem_p()(self.map.as_rmut(),&key) - } + pub fn get_mut_p(&mut self, key: &K) -> Option<&mut V> { + let vtable = self.vtable(); + unsafe { vtable.get_mut_elem_p()(self.map.as_rmut(), &key) } } /// Removes the value associated with the key. @@ -476,8 +438,8 @@ impl RHashMap{ /// assert_eq!(map.remove_p(&3), RNone); /// /// ``` - pub fn remove_p(&mut self,key:&K)->ROption{ - self.remove_entry_p(key).map(|x| x.1 ) + pub fn remove_p(&mut self, key: &K) -> ROption { + self.remove_entry_p(key).map(|x| x.1) } /// Removes the entry for the key. @@ -496,9 +458,9 @@ impl RHashMap{ /// assert_eq!(map.remove_entry_p(&3), RNone); /// /// ``` - pub fn remove_entry_p(&mut self,key:&K)->ROption>{ - let vtable=self.vtable(); - vtable.remove_entry_p()(self.map.as_rmut(),&key) + pub fn remove_entry_p(&mut self, key: &K) -> ROption> { + let vtable = self.vtable(); + vtable.remove_entry_p()(self.map.as_rmut(), &key) } /// Returns a reference to the value associated with the key. @@ -527,8 +489,9 @@ impl RHashMap{ /// assert_eq!(map.index_p(&0),&1); /// /// ``` - pub fn index_p(&self,key:&K)->&V{ - self.get_p(key).expect("no entry in RHashMap<_,_> found for key") + pub fn index_p(&self, key: &K) -> &V { + self.get_p(key) + .expect("no entry in RHashMap<_,_> found for key") } /// Returns a mutable reference to the value associated with the key. @@ -557,8 +520,9 @@ impl RHashMap{ /// assert_eq!(map.index_mut_p(&0),&mut 1); /// /// ``` - pub fn index_mut_p(&mut self,key:&K)->&mut V{ - self.get_mut_p(key).expect("no entry in RHashMap<_,_> found for key") + pub fn index_mut_p(&mut self, key: &K) -> &mut V { + self.get_mut_p(key) + .expect("no entry in RHashMap<_,_> found for key") } ////////////////////////////////// @@ -579,11 +543,9 @@ impl RHashMap{ /// assert_eq!(map[&2],3); /// /// ``` - pub fn insert(&mut self,key:K,value:V)->ROption{ - let vtable=self.vtable(); - unsafe{ - vtable.insert_elem()(self.map.as_rmut(),key,value) - } + pub fn insert(&mut self, key: K, value: V) -> ROption { + let vtable = self.vtable(); + unsafe { vtable.insert_elem()(self.map.as_rmut(), key, value) } } /// Reserves enough space to insert `reserved` extra elements without reallocating. @@ -597,10 +559,10 @@ impl RHashMap{ /// map.reserve(10); /// /// ``` - pub fn reserve(&mut self,reserved:usize){ - let vtable=self.vtable(); + pub fn reserve(&mut self, reserved: usize) { + let vtable = self.vtable(); - vtable.reserve()(self.map.as_rmut(),reserved); + vtable.reserve()(self.map.as_rmut(), reserved); } /// Removes all the entries in the map. @@ -621,8 +583,8 @@ impl RHashMap{ /// assert_eq!(map.contains_key(&3),false); /// /// ``` - pub fn clear(&mut self){ - let vtable=self.vtable(); + pub fn clear(&mut self) { + let vtable = self.vtable(); vtable.clear_map()(self.map.as_rmut()); } @@ -642,8 +604,8 @@ impl RHashMap{ /// assert_eq!(map.len(),2); /// /// ``` - pub fn len(&self)->usize{ - let vtable=self.vtable(); + pub fn len(&self) -> usize { + let vtable = self.vtable(); vtable.len()(self.map.as_rref()) } @@ -661,8 +623,8 @@ impl RHashMap{ /// assert!(map.capacity()>=4); /// /// ``` - pub fn capacity(&self)->usize{ - let vtable=self.vtable(); + pub fn capacity(&self) -> usize { + let vtable = self.vtable(); vtable.capacity()(self.map.as_rref()) } @@ -680,8 +642,8 @@ impl RHashMap{ /// assert_eq!(map.is_empty(),false); /// /// ``` - pub fn is_empty(&self)->bool{ - self.len()==0 + pub fn is_empty(&self) -> bool { + self.len() == 0 } /// Iterates over the entries in the map,with references to the values in the map. @@ -704,12 +666,12 @@ impl RHashMap{ /// assert_eq!( list, vec![Tuple2(&0,&1),Tuple2(&3,&4)] ); /// /// ``` - pub fn iter (&self)->Iter<'_,K,V>{ - let vtable=self.vtable(); + pub fn iter(&self) -> Iter<'_, K, V> { + let vtable = self.vtable(); vtable.iter()(self.map.as_rref()) } - + /// Iterates over the entries in the map,with mutable references to the values in the map. /// /// This returns a type that implements @@ -730,14 +692,14 @@ impl RHashMap{ /// assert_eq!( list, vec![Tuple2(&0,&mut 1),Tuple2(&3,&mut 4)] ); /// /// ``` - pub fn iter_mut(&mut self)->IterMut<'_,K,V>{ - let vtable=self.vtable(); + pub fn iter_mut(&mut self) -> IterMut<'_, K, V> { + let vtable = self.vtable(); vtable.iter_mut()(self.map.as_rmut()) } /// Clears the map,returning an iterator over all the entries that were removed. - /// + /// /// This returns a type that implements `Iterator > + !Send + !Sync` /// /// # Example @@ -757,277 +719,257 @@ impl RHashMap{ /// assert!(map.is_empty()); /// /// ``` - pub fn drain (&mut self)->Drain<'_,K,V>{ - let vtable=self.vtable(); + pub fn drain(&mut self) -> Drain<'_, K, V> { + let vtable = self.vtable(); vtable.drain()(self.map.as_rmut()) } -/** -Gets a handle into the entry in the map for the key, -that allows operating directly on the entry. + /** + Gets a handle into the entry in the map for the key, + that allows operating directly on the entry. -# Example + # Example -``` -use abi_stable::std_types::RHashMap; + ``` + use abi_stable::std_types::RHashMap; -let mut map=RHashMap::::new(); + let mut map=RHashMap::::new(); -// Inserting an entry that wasn't there before. -{ - let mut entry=map.entry(0); - assert_eq!(entry.get(),None); - assert_eq!(entry.or_insert(3),&mut 3); - assert_eq!(map.get(&0),Some(&3)); -} + // Inserting an entry that wasn't there before. + { + let mut entry=map.entry(0); + assert_eq!(entry.get(),None); + assert_eq!(entry.or_insert(3),&mut 3); + assert_eq!(map.get(&0),Some(&3)); + } -``` -*/ - pub fn entry(&mut self,key:K)->REntry<'_,K,V>{ - let vtable=self.vtable(); + ``` + */ + pub fn entry(&mut self, key: K) -> REntry<'_, K, V> { + let vtable = self.vtable(); - vtable.entry()(self.map.as_rmut(),key) + vtable.entry()(self.map.as_rmut(), key) } } - /// This returns an `Iterator >+!Send+!Sync` -impl IntoIterator for RHashMap{ - type Item=Tuple2; - type IntoIter=IntoIter; - - fn into_iter(self)->IntoIter{ - let vtable=self.vtable(); +impl IntoIterator for RHashMap { + type Item = Tuple2; + type IntoIter = IntoIter; + + fn into_iter(self) -> IntoIter { + let vtable = self.vtable(); vtable.iter_val()(self.map) } } - /// This returns an `Iterator > + !Send + !Sync + Clone` -impl<'a,K,V,S> IntoIterator for &'a RHashMap{ - type Item=Tuple2<&'a K,&'a V>; - type IntoIter=Iter<'a,K,V>; - - fn into_iter(self)->Self::IntoIter{ +impl<'a, K, V, S> IntoIterator for &'a RHashMap { + type Item = Tuple2<&'a K, &'a V>; + type IntoIter = Iter<'a, K, V>; + + fn into_iter(self) -> Self::IntoIter { self.iter() } } - /// This returns a type that implements /// `Iterator > + !Send + !Sync` -impl<'a,K,V,S> IntoIterator for &'a mut RHashMap{ - type Item=Tuple2<&'a K,&'a mut V>; - type IntoIter=IterMut<'a,K,V>; - - fn into_iter(self)->Self::IntoIter{ +impl<'a, K, V, S> IntoIterator for &'a mut RHashMap { + type Item = Tuple2<&'a K, &'a mut V>; + type IntoIter = IterMut<'a, K, V>; + + fn into_iter(self) -> Self::IntoIter { self.iter_mut() } } - -impl From> for RHashMap +impl From> for RHashMap where - Self:Default + Self: Default, { - fn from(map:HashMap)->Self{ + fn from(map: HashMap) -> Self { map.into_iter().collect() } } -impl Into> for RHashMap +impl Into> for RHashMap where - K:Eq+Hash, - S:BuildHasher+Default, + K: Eq + Hash, + S: BuildHasher + Default, { - fn into(self)->HashMap{ + fn into(self) -> HashMap { self.into_iter().map(IntoReprRust::into_rust).collect() } } - -impl FromIterator<(K,V)> for RHashMap +impl FromIterator<(K, V)> for RHashMap where - Self:Default, + Self: Default, { fn from_iter(iter: I) -> Self where - I: IntoIterator + I: IntoIterator, { - let mut map=Self::default(); + let mut map = Self::default(); map.extend(iter); map } } - -impl FromIterator> for RHashMap +impl FromIterator> for RHashMap where - Self:Default + Self: Default, { fn from_iter(iter: I) -> Self where - I: IntoIterator> + I: IntoIterator>, { - let mut map=Self::default(); + let mut map = Self::default(); map.extend(iter); map } } - -impl Extend<(K,V)> for RHashMap{ - fn extend(&mut self,iter: I) +impl Extend<(K, V)> for RHashMap { + fn extend(&mut self, iter: I) where - I: IntoIterator + I: IntoIterator, { - let iter=iter.into_iter(); + let iter = iter.into_iter(); self.reserve(iter.size_hint().0); - for (k,v) in iter { - self.insert(k,v); + for (k, v) in iter { + self.insert(k, v); } } } - -impl Extend> for RHashMap{ +impl Extend> for RHashMap { #[inline] - fn extend(&mut self,iter: I) + fn extend(&mut self, iter: I) where - I: IntoIterator> + I: IntoIterator>, { - self.extend( iter.into_iter().map(Tuple2::into_rust) ); + self.extend(iter.into_iter().map(Tuple2::into_rust)); } } -impl Default for RHashMap +impl Default for RHashMap where - K:Eq+Hash, - S:BuildHasher+Default, + K: Eq + Hash, + S: BuildHasher + Default, { - fn default()->Self{ + fn default() -> Self { Self::with_hasher(S::default()) } } - -impl Clone for RHashMap -where - K:Clone, - V:Clone, - Self:Default +impl Clone for RHashMap +where + K: Clone, + V: Clone, + Self: Default, { - fn clone(&self)->Self{ - self.iter().map(|Tuple2(k,v)| (k.clone(),v.clone()) ).collect() + fn clone(&self) -> Self { + self.iter() + .map(|Tuple2(k, v)| (k.clone(), v.clone())) + .collect() } } - -impl Debug for RHashMap -where - K:Debug, - V:Debug, +impl Debug for RHashMap +where + K: Debug, + V: Debug, { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_map() - .entries(self.iter().map(Tuple2::into_rust)) - .finish() + .entries(self.iter().map(Tuple2::into_rust)) + .finish() } } +impl Eq for RHashMap +where + K: Eq, + V: Eq, +{ +} -impl Eq for RHashMap -where - K:Eq, - V:Eq, -{} - - -impl PartialEq for RHashMap -where - K:PartialEq, - V:PartialEq, +impl PartialEq for RHashMap +where + K: PartialEq, + V: PartialEq, { - fn eq(&self,other:&Self)->bool{ + fn eq(&self, other: &Self) -> bool { if self.len() != other.len() { return false; } self.iter() - .all(|Tuple2(k, vl)|{ - other.get_p(k) - .map_or(false, |vr| *vr == *vl) - }) + .all(|Tuple2(k, vl)| other.get_p(k).map_or(false, |vr| *vr == *vl)) } } +unsafe impl Send for RHashMap where HashMap: Send {} -unsafe impl Send for RHashMap -where - HashMap: Send, -{} - -unsafe impl Sync for RHashMap -where - HashMap: Sync, -{} - +unsafe impl Sync for RHashMap where HashMap: Sync {} -impl Index<&Q> for RHashMap +impl Index<&Q> for RHashMap where - K:Borrow, - Q:Eq+Hash+?Sized + K: Borrow, + Q: Eq + Hash + ?Sized, { - type Output=V; + type Output = V; - fn index(&self,query:&Q)->&V{ - self.get(query).expect("no entry in RHashMap<_,_> found for key") + fn index(&self, query: &Q) -> &V { + self.get(query) + .expect("no entry in RHashMap<_,_> found for key") } } -impl IndexMut<&Q> for RHashMap +impl IndexMut<&Q> for RHashMap where - K:Borrow, - Q:Eq+Hash+?Sized + K: Borrow, + Q: Eq + Hash + ?Sized, { - fn index_mut(&mut self,query:&Q)->&mut V{ - self.get_mut(query).expect("no entry in RHashMap<_,_> found for key") + fn index_mut(&mut self, query: &Q) -> &mut V { + self.get_mut(query) + .expect("no entry in RHashMap<_,_> found for key") } } - -mod serde{ +mod serde { use super::*; use ::serde::{ - de::{Visitor, MapAccess}, + de::{MapAccess, Visitor}, ser::SerializeMap, - Deserialize,Serialize,Deserializer,Serializer, + Deserialize, Deserializer, Serialize, Serializer, }; - - struct RHashMapVisitor { - _marker: NonOwningPhantom> + struct RHashMapVisitor { + _marker: NonOwningPhantom>, } - impl RHashMapVisitor { + impl RHashMapVisitor { fn new() -> Self { RHashMapVisitor { - _marker: NonOwningPhantom::NEW + _marker: NonOwningPhantom::NEW, } } } - impl<'de,K,V,S> Visitor<'de> for RHashMapVisitor + impl<'de, K, V, S> Visitor<'de> for RHashMapVisitor where K: Deserialize<'de>, V: Deserialize<'de>, - RHashMap:Default, + RHashMap: Default, { - type Value = RHashMap; + type Value = RHashMap; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("an RHashMap") @@ -1037,7 +979,7 @@ mod serde{ where M: MapAccess<'de>, { - let capacity=map_access.size_hint().unwrap_or(0); + let capacity = map_access.size_hint().unwrap_or(0); let mut map = RHashMap::default(); map.reserve(capacity); @@ -1049,11 +991,11 @@ mod serde{ } } - impl<'de,K,V,S> Deserialize<'de> for RHashMap + impl<'de, K, V, S> Deserialize<'de> for RHashMap where K: Deserialize<'de>, V: Deserialize<'de>, - Self:Default, + Self: Default, { fn deserialize(deserializer: D) -> Result where @@ -1063,16 +1005,14 @@ mod serde{ } } - - - impl Serialize for RHashMap + impl Serialize for RHashMap where - K:Serialize, - V:Serialize, + K: Serialize, + V: Serialize, { fn serialize(&self, serializer: Z) -> Result where - Z: Serializer + Z: Serializer, { let mut map = serializer.serialize_map(Some(self.len()))?; for Tuple2(k, v) in self.iter() { @@ -1081,14 +1021,10 @@ mod serde{ map.end() } } - - } - /////////////////////////////////////////////////////////////////////////////// - #[derive(StableAbi)] #[repr(C)] #[sabi( @@ -1098,82 +1034,72 @@ mod serde{ unsafe_unconstrained(S), //debug_print, )] -struct VTable{ - /// - insert_elem:extern "C" fn(RMut<'_, ErasedMap>,K,V)->ROption, - - get_elem:for<'a> extern "C" fn(RRef<'a, ErasedMap>,MapQuery<'_,K>)->Option<&'a V>, - get_mut_elem:for<'a> extern "C" fn(RMut<'a, ErasedMap>,MapQuery<'_,K>)->Option<&'a mut V>, - remove_entry:extern "C" fn(RMut<'_, ErasedMap>,MapQuery<'_,K>)->ROption>, - - get_elem_p:for<'a> extern "C" fn(RRef<'a, ErasedMap>,&K)->Option<&'a V>, - get_mut_elem_p:for<'a> extern "C" fn(RMut<'a, ErasedMap>,&K)->Option<&'a mut V>, - remove_entry_p:extern "C" fn(RMut<'_, ErasedMap>,&K)->ROption>, - - reserve:extern "C" fn(RMut<'_, ErasedMap>,usize), - clear_map:extern "C" fn(RMut<'_, ErasedMap>), - len:extern "C" fn(RRef<'_, ErasedMap>)->usize, - capacity:extern "C" fn(RRef<'_, ErasedMap>)->usize, - iter :extern "C" fn(RRef<'_, ErasedMap> )->Iter<'_,K,V>, - iter_mut:extern "C" fn(RMut<'_, ErasedMap> )->IterMut<'_,K,V>, - drain :extern "C" fn(RMut<'_, ErasedMap> )->Drain<'_,K,V>, - iter_val:extern "C" fn(RBox>)->IntoIter, +struct VTable { + /// + insert_elem: extern "C" fn(RMut<'_, ErasedMap>, K, V) -> ROption, + + get_elem: for<'a> extern "C" fn(RRef<'a, ErasedMap>, MapQuery<'_, K>) -> Option<&'a V>, + get_mut_elem: + for<'a> extern "C" fn(RMut<'a, ErasedMap>, MapQuery<'_, K>) -> Option<&'a mut V>, + remove_entry: + extern "C" fn(RMut<'_, ErasedMap>, MapQuery<'_, K>) -> ROption>, + + get_elem_p: for<'a> extern "C" fn(RRef<'a, ErasedMap>, &K) -> Option<&'a V>, + get_mut_elem_p: for<'a> extern "C" fn(RMut<'a, ErasedMap>, &K) -> Option<&'a mut V>, + remove_entry_p: extern "C" fn(RMut<'_, ErasedMap>, &K) -> ROption>, + + reserve: extern "C" fn(RMut<'_, ErasedMap>, usize), + clear_map: extern "C" fn(RMut<'_, ErasedMap>), + len: extern "C" fn(RRef<'_, ErasedMap>) -> usize, + capacity: extern "C" fn(RRef<'_, ErasedMap>) -> usize, + iter: extern "C" fn(RRef<'_, ErasedMap>) -> Iter<'_, K, V>, + iter_mut: extern "C" fn(RMut<'_, ErasedMap>) -> IterMut<'_, K, V>, + drain: extern "C" fn(RMut<'_, ErasedMap>) -> Drain<'_, K, V>, + iter_val: extern "C" fn(RBox>) -> IntoIter, #[sabi(last_prefix_field)] - entry:extern "C" fn(RMut<'_, ErasedMap>,K)->REntry<'_,K,V>, + entry: extern "C" fn(RMut<'_, ErasedMap>, K) -> REntry<'_, K, V>, } - - -impl VTable +impl VTable where - K:Eq+Hash, - S:BuildHasher, + K: Eq + Hash, + S: BuildHasher, { - const VTABLE_VAL: WithMetadata> = { - WithMetadata::new(PrefixTypeTrait::METADATA, Self::VTABLE) - }; + const VTABLE_VAL: WithMetadata> = + { WithMetadata::new(PrefixTypeTrait::METADATA, Self::VTABLE) }; - const VTABLE_REF: VTable_Ref = unsafe{ - VTable_Ref(Self::VTABLE_VAL.as_prefix()) - }; + const VTABLE_REF: VTable_Ref = unsafe { VTable_Ref(Self::VTABLE_VAL.as_prefix()) }; - fn erased_map(hash_builder:S)->RBox>{ - unsafe{ - let map=HashMap::,V,S>::with_hasher(hash_builder); - let boxed=BoxedHashMap{ - map, - entry:None, - }; - let boxed=RBox::new(boxed); - mem::transmute::,RBox>>(boxed) + fn erased_map(hash_builder: S) -> RBox> { + unsafe { + let map = HashMap::, V, S>::with_hasher(hash_builder); + let boxed = BoxedHashMap { map, entry: None }; + let boxed = RBox::new(boxed); + mem::transmute::, RBox>>(boxed) } } - - const VTABLE:VTable=VTable{ - insert_elem :ErasedMap::insert_elem, - - get_elem :ErasedMap::get_elem, - get_mut_elem:ErasedMap::get_mut_elem, - remove_entry:ErasedMap::remove_entry, - - get_elem_p :ErasedMap::get_elem_p, - get_mut_elem_p:ErasedMap::get_mut_elem_p, - remove_entry_p:ErasedMap::remove_entry_p, - - reserve :ErasedMap::reserve, - clear_map :ErasedMap::clear_map, - len :ErasedMap::len, - capacity :ErasedMap::capacity, - iter :ErasedMap::iter, - iter_mut :ErasedMap::iter_mut, - drain :ErasedMap::drain, - iter_val :ErasedMap::iter_val, - entry :ErasedMap::entry, + const VTABLE: VTable = VTable { + insert_elem: ErasedMap::insert_elem, + + get_elem: ErasedMap::get_elem, + get_mut_elem: ErasedMap::get_mut_elem, + remove_entry: ErasedMap::remove_entry, + + get_elem_p: ErasedMap::get_elem_p, + get_mut_elem_p: ErasedMap::get_mut_elem_p, + remove_entry_p: ErasedMap::remove_entry_p, + + reserve: ErasedMap::reserve, + clear_map: ErasedMap::clear_map, + len: ErasedMap::len, + capacity: ErasedMap::capacity, + iter: ErasedMap::iter, + iter_mut: ErasedMap::iter_mut, + drain: ErasedMap::drain, + iter_val: ErasedMap::iter_val, + entry: ErasedMap::entry, }; - } - - /////////////////////////////////////////////////////////////////////////////// diff --git a/abi_stable/src/std_types/map/entry.rs b/abi_stable/src/std_types/map/entry.rs index bfe31e4a..055bca46 100644 --- a/abi_stable/src/std_types/map/entry.rs +++ b/abi_stable/src/std_types/map/entry.rs @@ -1,97 +1,84 @@ use super::*; use std::{ - collections::hash_map::{OccupiedEntry,VacantEntry,Entry}, + collections::hash_map::{Entry, OccupiedEntry, VacantEntry}, mem::ManuallyDrop, ptr, }; use crate::{ marker_type::UnsafeIgnoredType, - prefix_type::{WithMetadata,PrefixTypeTrait}, - sabi_types::{RRef, RMut}, + prefix_type::{PrefixTypeTrait, WithMetadata}, + sabi_types::{RMut, RRef}, }; - /// The enum stored alongside the unerased HashMap. -pub(super) enum BoxedREntry<'a,K,V>{ - Occupied(UnerasedOccupiedEntry<'a,K,V>), - Vacant(UnerasedVacantEntry<'a,K,V>), +pub(super) enum BoxedREntry<'a, K, V> { + Occupied(UnerasedOccupiedEntry<'a, K, V>), + Vacant(UnerasedVacantEntry<'a, K, V>), } /// A handle into an entry in a map, which is either vacant or occupied. #[derive(StableAbi)] #[repr(C)] -#[sabi( - bound="K:'a", - bound="V:'a", -)] -pub enum REntry<'a,K,V>{ - Occupied(ROccupiedEntry<'a,K,V>), - Vacant(RVacantEntry<'a,K,V>), +#[sabi(bound = "K:'a", bound = "V:'a")] +pub enum REntry<'a, K, V> { + Occupied(ROccupiedEntry<'a, K, V>), + Vacant(RVacantEntry<'a, K, V>), } - ///////////////////////////////////////////////////////////////////////////////////////////// - #[derive(StableAbi)] #[repr(C)] -struct ErasedOccupiedEntry(PhantomData<(K,V)>); +struct ErasedOccupiedEntry(PhantomData<(K, V)>); #[derive(StableAbi)] #[repr(C)] -struct ErasedVacantEntry (PhantomData<(K,V)>); +struct ErasedVacantEntry(PhantomData<(K, V)>); -type UnerasedOccupiedEntry<'a,K,V>= - ManuallyDrop,V>>; +type UnerasedOccupiedEntry<'a, K, V> = ManuallyDrop, V>>; -type UnerasedVacantEntry<'a,K,V>= - ManuallyDrop,V>>; +type UnerasedVacantEntry<'a, K, V> = ManuallyDrop, V>>; - -unsafe impl<'a,K:'a,V:'a> ErasedType<'a> for ErasedOccupiedEntry { - type Unerased=UnerasedOccupiedEntry<'a,K,V>; +unsafe impl<'a, K: 'a, V: 'a> ErasedType<'a> for ErasedOccupiedEntry { + type Unerased = UnerasedOccupiedEntry<'a, K, V>; } -unsafe impl<'a,K:'a,V:'a> ErasedType<'a> for ErasedVacantEntry { - type Unerased=UnerasedVacantEntry<'a,K,V>; +unsafe impl<'a, K: 'a, V: 'a> ErasedType<'a> for ErasedVacantEntry { + type Unerased = UnerasedVacantEntry<'a, K, V>; } ///////////////////////////////////////////////////////////////////////////////////////////// -impl<'a,K,V> From,V>> for BoxedREntry<'a,K,V> +impl<'a, K, V> From, V>> for BoxedREntry<'a, K, V> where - K:Eq+Hash + K: Eq + Hash, { - fn from(entry:Entry<'a,MapKey,V>)->Self{ + fn from(entry: Entry<'a, MapKey, V>) -> Self { match entry { - Entry::Occupied(entry)=> - entry.piped(ManuallyDrop::new).piped(BoxedREntry::Occupied), - Entry::Vacant(entry) => - entry.piped(ManuallyDrop::new).piped(BoxedREntry::Vacant), + Entry::Occupied(entry) => entry.piped(ManuallyDrop::new).piped(BoxedREntry::Occupied), + Entry::Vacant(entry) => entry.piped(ManuallyDrop::new).piped(BoxedREntry::Vacant), } } } -impl<'a,K,V> REntry<'a,K,V> +impl<'a, K, V> REntry<'a, K, V> where - K:Eq+Hash + K: Eq + Hash, { - pub(super)unsafe fn new(entry:&'a mut BoxedREntry<'a,K,V>)->Self{ + pub(super) unsafe fn new(entry: &'a mut BoxedREntry<'a, K, V>) -> Self { match entry { - BoxedREntry::Occupied(entry)=> - entry.piped(ROccupiedEntry::new).piped(REntry::Occupied), - BoxedREntry::Vacant(entry) => - entry.piped(RVacantEntry::new).piped(REntry::Vacant), + BoxedREntry::Occupied(entry) => { + entry.piped(ROccupiedEntry::new).piped(REntry::Occupied) + } + BoxedREntry::Vacant(entry) => entry.piped(RVacantEntry::new).piped(REntry::Vacant), } } } ///////////////////////////////////////////////////////////////////////////////////////////// - - impl<'a, K, V> REntry<'a, K, V> { /// Returns a reference to the value in the entry. /// @@ -176,9 +163,9 @@ impl<'a, K, V> REntry<'a, K, V> { /// ); /// /// ``` - pub fn or_insert_with(self, default: F) -> &'a mut V - where - F: FnOnce() -> V + pub fn or_insert_with(self, default: F) -> &'a mut V + where + F: FnOnce() -> V, { match self { REntry::Occupied(entry) => entry.into_mut(), @@ -209,7 +196,7 @@ impl<'a, K, V> REntry<'a, K, V> { } /// Allows mutating an occupied entry before doing other operations. - /// + /// /// This is a no-op on a vacant entry. /// /// # Example @@ -228,14 +215,14 @@ impl<'a, K, V> REntry<'a, K, V> { /// ); /// ``` pub fn and_modify(self, f: F) -> Self - where - F: FnOnce(&mut V) + where + F: FnOnce(&mut V), { match self { REntry::Occupied(mut entry) => { f(entry.get_mut()); REntry::Occupied(entry) - }, + } REntry::Vacant(entry) => REntry::Vacant(entry), } } @@ -256,9 +243,9 @@ impl<'a, K, V> REntry<'a, K, V> { /// assert_eq!(map.entry(1).or_default(),&mut 0); /// /// ``` - pub fn or_default(self) -> &'a mut V + pub fn or_default(self) -> &'a mut V where - V: Default + V: Default, { match self { REntry::Occupied(entry) => entry.into_mut(), @@ -267,69 +254,61 @@ impl<'a, K, V> REntry<'a, K, V> { } } - -impl Debug for REntry<'_,K,V> +impl Debug for REntry<'_, K, V> where - K:Debug, - V:Debug, + K: Debug, + V: Debug, { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - REntry::Occupied(entry)=>Debug::fmt(entry,f), - REntry::Vacant(entry)=>Debug::fmt(entry,f), + REntry::Occupied(entry) => Debug::fmt(entry, f), + REntry::Vacant(entry) => Debug::fmt(entry, f), } } } - ///////////////////////////////////////////////////////////////////////////////////////////// /// A handle into an occupied entry in a map. #[derive(StableAbi)] #[repr(C)] -#[sabi( - bound="K:'a", - bound="V:'a", -)] -pub struct ROccupiedEntry<'a,K,V>{ - entry: RMut<'a, ErasedOccupiedEntry>, - vtable:OccupiedVTable_Ref, - _marker:UnsafeIgnoredType> +#[sabi(bound = "K:'a", bound = "V:'a")] +pub struct ROccupiedEntry<'a, K, V> { + entry: RMut<'a, ErasedOccupiedEntry>, + vtable: OccupiedVTable_Ref, + _marker: UnsafeIgnoredType>, } /// A handle into a vacant entry in a map. #[derive(StableAbi)] #[repr(C)] -#[sabi( - bound="K:'a", - bound="V:'a", -)] -pub struct RVacantEntry<'a,K,V>{ - entry: RMut<'a, ErasedVacantEntry>, - vtable:VacantVTable_Ref, - _marker:UnsafeIgnoredType> +#[sabi(bound = "K:'a", bound = "V:'a")] +pub struct RVacantEntry<'a, K, V> { + entry: RMut<'a, ErasedVacantEntry>, + vtable: VacantVTable_Ref, + _marker: UnsafeIgnoredType>, } ///////////////////////////////////////////////////////////////////////////////////////////// -impl<'a,K,V> ROccupiedEntry<'a,K,V>{ - fn vtable(&self)->OccupiedVTable_Ref{ +impl<'a, K, V> ROccupiedEntry<'a, K, V> { + fn vtable(&self) -> OccupiedVTable_Ref { self.vtable } } -impl<'a,K,V> ROccupiedEntry<'a,K,V>{ - fn into_inner(self)-> RMut<'a, ErasedOccupiedEntry>{ - let mut this=ManuallyDrop::new(self); - unsafe{ ((&mut this.entry) as *mut RMut<'a, ErasedOccupiedEntry>).read() } +impl<'a, K, V> ROccupiedEntry<'a, K, V> { + fn into_inner(self) -> RMut<'a, ErasedOccupiedEntry> { + let mut this = ManuallyDrop::new(self); + unsafe { ((&mut this.entry) as *mut RMut<'a, ErasedOccupiedEntry>).read() } } - pub(super) fn new(entry:&'a mut UnerasedOccupiedEntry<'a,K,V>)->Self{ - unsafe{ - Self{ - entry:ErasedOccupiedEntry::from_unerased(entry), - vtable:OccupiedVTable::VTABLE_REF, - _marker:UnsafeIgnoredType::DEFAULT, + pub(super) fn new(entry: &'a mut UnerasedOccupiedEntry<'a, K, V>) -> Self { + unsafe { + Self { + entry: ErasedOccupiedEntry::from_unerased(entry), + vtable: OccupiedVTable::VTABLE_REF, + _marker: UnsafeIgnoredType::DEFAULT, } } } @@ -354,8 +333,8 @@ impl<'a,K,V> ROccupiedEntry<'a,K,V>{ /// /// /// ``` - pub fn key(&self)->&K{ - let vtable=self.vtable(); + pub fn key(&self) -> &K { + let vtable = self.vtable(); vtable.key()(self.entry.as_rref()) } @@ -380,8 +359,8 @@ impl<'a,K,V> ROccupiedEntry<'a,K,V>{ /// /// /// ``` - pub fn get(&self)->&V{ - let vtable=self.vtable(); + pub fn get(&self) -> &V { + let vtable = self.vtable(); vtable.get_elem()(self.entry.as_rref()) } @@ -407,14 +386,14 @@ impl<'a,K,V> ROccupiedEntry<'a,K,V>{ /// /// /// ``` - pub fn get_mut(&mut self)->&mut V{ - let vtable=self.vtable(); + pub fn get_mut(&mut self) -> &mut V { + let vtable = self.vtable(); vtable.get_mut_elem()(self.entry.reborrow()) } /// Gets a mutable reference to the value in the entry, - /// that borrows with the lifetime of the map instead of + /// that borrows with the lifetime of the map instead of /// borrowing from this `ROccupiedEntry`. /// /// # Example @@ -435,8 +414,8 @@ impl<'a,K,V> ROccupiedEntry<'a,K,V>{ /// /// /// ``` - pub fn into_mut(self)->&'a mut V{ - let vtable=self.vtable(); + pub fn into_mut(self) -> &'a mut V { + let vtable = self.vtable(); vtable.fn_into_mut_elem()(self) } @@ -464,10 +443,10 @@ impl<'a,K,V> ROccupiedEntry<'a,K,V>{ /// assert_eq!( map.get("baz"), Some(&0xDEAD)); /// /// ``` - pub fn insert(&mut self,value:V)->V{ - let vtable=self.vtable(); + pub fn insert(&mut self, value: V) -> V { + let vtable = self.vtable(); - vtable.insert_elem()(self.entry.reborrow(),value) + vtable.insert_elem()(self.entry.reborrow(), value) } /// Removes the entry from the map,returns the value. @@ -493,33 +472,31 @@ impl<'a,K,V> ROccupiedEntry<'a,K,V>{ /// assert!( ! map.contains_key("baz") ); /// /// ``` - pub fn remove(self)->V{ - let vtable=self.vtable(); + pub fn remove(self) -> V { + let vtable = self.vtable(); vtable.remove()(self) } } - -impl Debug for ROccupiedEntry<'_,K,V> +impl Debug for ROccupiedEntry<'_, K, V> where - K:Debug, - V:Debug, + K: Debug, + V: Debug, { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("ROccupiedEntry") - .field("key",self.key()) - .field("value",self.get()) - .finish() + .field("key", self.key()) + .field("value", self.get()) + .finish() } } +impl<'a, K, V> Drop for ROccupiedEntry<'a, K, V> { + fn drop(&mut self) { + let vtable = self.vtable(); -impl<'a,K,V> Drop for ROccupiedEntry<'a,K,V>{ - fn drop(&mut self){ - let vtable=self.vtable(); - - unsafe{ + unsafe { vtable.drop_entry()(self.entry.reborrow()); } } @@ -527,27 +504,27 @@ impl<'a,K,V> Drop for ROccupiedEntry<'a,K,V>{ ///////////////////////////////////////////////////////////////////////////////////////////// -impl<'a,K,V> RVacantEntry<'a,K,V>{ - fn vtable(&self)->VacantVTable_Ref{ +impl<'a, K, V> RVacantEntry<'a, K, V> { + fn vtable(&self) -> VacantVTable_Ref { self.vtable } } -impl<'a,K,V> RVacantEntry<'a,K,V>{ - fn into_inner(self)-> RMut<'a, ErasedVacantEntry> { - let mut this=ManuallyDrop::new(self); - unsafe{ ((&mut this.entry) as *mut RMut<'a, ErasedVacantEntry>).read() } +impl<'a, K, V> RVacantEntry<'a, K, V> { + fn into_inner(self) -> RMut<'a, ErasedVacantEntry> { + let mut this = ManuallyDrop::new(self); + unsafe { ((&mut this.entry) as *mut RMut<'a, ErasedVacantEntry>).read() } } - pub(super) fn new(entry:&'a mut UnerasedVacantEntry<'a,K,V>)->Self + pub(super) fn new(entry: &'a mut UnerasedVacantEntry<'a, K, V>) -> Self where - K:Eq+Hash + K: Eq + Hash, { - unsafe{ - Self{ - entry:ErasedVacantEntry::from_unerased(entry), + unsafe { + Self { + entry: ErasedVacantEntry::from_unerased(entry), vtable: VacantVTable::VTABLE_REF, - _marker:UnsafeIgnoredType::DEFAULT, + _marker: UnsafeIgnoredType::DEFAULT, } } } @@ -574,7 +551,7 @@ impl<'a,K,V> RVacantEntry<'a,K,V>{ /// /// ``` pub fn key(&self) -> &K { - let vtable=self.vtable(); + let vtable = self.vtable(); vtable.key()(self.entry.as_rref()) } @@ -601,7 +578,7 @@ impl<'a,K,V> RVacantEntry<'a,K,V>{ /// /// ``` pub fn into_key(self) -> K { - let vtable=self.vtable(); + let vtable = self.vtable(); vtable.fn_into_key()(self) } @@ -628,217 +605,205 @@ impl<'a,K,V> RVacantEntry<'a,K,V>{ /// /// ``` pub fn insert(self, value: V) -> &'a mut V { - let vtable=self.vtable(); + let vtable = self.vtable(); - vtable.insert_elem()(self,value) + vtable.insert_elem()(self, value) } } - - -impl Debug for RVacantEntry<'_,K,V> +impl Debug for RVacantEntry<'_, K, V> where - K:Debug, + K: Debug, { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("RVacantEntry") - .field("key",self.key()) - .finish() + .field("key", self.key()) + .finish() } } +impl<'a, K, V> Drop for RVacantEntry<'a, K, V> { + fn drop(&mut self) { + let vtable = self.vtable(); -impl<'a,K,V> Drop for RVacantEntry<'a,K,V>{ - fn drop(&mut self){ - let vtable=self.vtable(); - - unsafe{ - vtable.drop_entry()(self.entry.reborrow()) - } + unsafe { vtable.drop_entry()(self.entry.reborrow()) } } } ///////////////////////////////////////////////////////////////////////////////////////////// - - #[derive(StableAbi)] #[repr(C)] -#[sabi( - kind(Prefix), - missing_field(panic), -)] -pub struct OccupiedVTable{ - drop_entry:unsafe extern "C" fn(RMut<'_, ErasedOccupiedEntry>), - key:extern "C" fn(RRef<'_, ErasedOccupiedEntry>)->&K, - get_elem:extern "C" fn(RRef<'_, ErasedOccupiedEntry>)->&V, - get_mut_elem:extern "C" fn(RMut<'_, ErasedOccupiedEntry>)->&mut V, - fn_into_mut_elem:extern "C" fn(ROccupiedEntry<'_,K,V>)->&'_ mut V, - insert_elem:extern "C" fn(RMut<'_, ErasedOccupiedEntry>,V)->V, - remove:extern "C" fn(ROccupiedEntry<'_,K,V>)->V, +#[sabi(kind(Prefix), missing_field(panic))] +pub struct OccupiedVTable { + drop_entry: unsafe extern "C" fn(RMut<'_, ErasedOccupiedEntry>), + key: extern "C" fn(RRef<'_, ErasedOccupiedEntry>) -> &K, + get_elem: extern "C" fn(RRef<'_, ErasedOccupiedEntry>) -> &V, + get_mut_elem: extern "C" fn(RMut<'_, ErasedOccupiedEntry>) -> &mut V, + fn_into_mut_elem: extern "C" fn(ROccupiedEntry<'_, K, V>) -> &'_ mut V, + insert_elem: extern "C" fn(RMut<'_, ErasedOccupiedEntry>, V) -> V, + remove: extern "C" fn(ROccupiedEntry<'_, K, V>) -> V, } +impl OccupiedVTable { + const VTABLE_REF: OccupiedVTable_Ref = OccupiedVTable_Ref(Self::WM_VTABLE.as_prefix()); -impl OccupiedVTable{ - const VTABLE_REF: OccupiedVTable_Ref = OccupiedVTable_Ref(Self::WM_VTABLE.as_prefix()); - - staticref!{ - const WM_VTABLE: WithMetadata> = + staticref! { + const WM_VTABLE: WithMetadata> = WithMetadata::new(PrefixTypeTrait::METADATA, Self::VTABLE) } - const VTABLE:OccupiedVTable=OccupiedVTable{ - drop_entry :ErasedOccupiedEntry::drop_entry, - key :ErasedOccupiedEntry::key, - get_elem :ErasedOccupiedEntry::get_elem, - get_mut_elem :ErasedOccupiedEntry::get_mut_elem, - fn_into_mut_elem:ErasedOccupiedEntry::fn_into_mut_elem, - insert_elem :ErasedOccupiedEntry::insert_elem, - remove :ErasedOccupiedEntry::remove, + const VTABLE: OccupiedVTable = OccupiedVTable { + drop_entry: ErasedOccupiedEntry::drop_entry, + key: ErasedOccupiedEntry::key, + get_elem: ErasedOccupiedEntry::get_elem, + get_mut_elem: ErasedOccupiedEntry::get_mut_elem, + fn_into_mut_elem: ErasedOccupiedEntry::fn_into_mut_elem, + insert_elem: ErasedOccupiedEntry::insert_elem, + remove: ErasedOccupiedEntry::remove, }; } - -impl ErasedOccupiedEntry{ - unsafe extern "C" fn drop_entry(this: RMut<'_, Self>){ - extern_fn_panic_handling!{ +impl ErasedOccupiedEntry { + unsafe extern "C" fn drop_entry(this: RMut<'_, Self>) { + extern_fn_panic_handling! { Self::run_downcast_as_mut(this, |this|{ ManuallyDrop::drop(this); - }) + }) + } + } + extern "C" fn key(this: RRef<'_, Self>) -> &K { + unsafe { + extern_fn_panic_handling! { + Self::run_downcast_as( + this, + |this| this.key().as_ref() + ) + } + } + } + extern "C" fn get_elem(this: RRef<'_, Self>) -> &V { + unsafe { + extern_fn_panic_handling! { + Self::run_downcast_as( + this, + |this| this.get() + ) + } + } + } + extern "C" fn get_mut_elem(this: RMut<'_, Self>) -> &mut V { + unsafe { + extern_fn_panic_handling! { + Self::run_downcast_as_mut( + this, + |this| this.get_mut() + ) + } + } + } + extern "C" fn fn_into_mut_elem(this: ROccupiedEntry<'_, K, V>) -> &'_ mut V { + unsafe { + extern_fn_panic_handling! { + Self::run_downcast_as_mut( + this.into_inner(), + |this| take_manuallydrop(this).into_mut() + ) + } + } + } + extern "C" fn insert_elem(this: RMut<'_, Self>, elem: V) -> V { + unsafe { + extern_fn_panic_handling! { + Self::run_downcast_as_mut( + this, + |this| this.insert(elem) + ) + } + } + } + extern "C" fn remove(this: ROccupiedEntry<'_, K, V>) -> V { + unsafe { + extern_fn_panic_handling! { + Self::run_downcast_as_mut( + this.into_inner(), + |this| take_manuallydrop(this).remove() + ) + } } } - extern "C" fn key(this: RRef<'_, Self>)->&K{ - unsafe{extern_fn_panic_handling!{ - Self::run_downcast_as( - this, - |this| this.key().as_ref() - ) - }} - } - extern "C" fn get_elem(this: RRef<'_, Self>)->&V{ - unsafe{extern_fn_panic_handling!{ - Self::run_downcast_as( - this, - |this| this.get() - ) - }} - } - extern "C" fn get_mut_elem(this: RMut<'_, Self>)->&mut V{ - unsafe{extern_fn_panic_handling!{ - Self::run_downcast_as_mut( - this, - |this| this.get_mut() - ) - }} - } - extern "C" fn fn_into_mut_elem(this:ROccupiedEntry<'_,K,V>)->&'_ mut V{ - unsafe{extern_fn_panic_handling!{ - Self::run_downcast_as_mut( - this.into_inner(), - |this| take_manuallydrop(this).into_mut() - ) - }} - } - extern "C" fn insert_elem(this: RMut<'_, Self>,elem:V)->V{ - unsafe{extern_fn_panic_handling!{ - Self::run_downcast_as_mut( - this, - |this| this.insert(elem) - ) - }} - } - extern "C" fn remove(this:ROccupiedEntry<'_,K,V>)->V{ - unsafe{extern_fn_panic_handling!{ - Self::run_downcast_as_mut( - this.into_inner(), - |this| take_manuallydrop(this).remove() - ) - }} - } } - - - - ///////////////////////////////////////////////////////////////////////////////////////////// - - - - #[derive(StableAbi)] #[repr(C)] -#[sabi( - kind(Prefix), - missing_field(panic), -)] -pub struct VacantVTable{ - drop_entry:unsafe extern "C" fn(RMut<'_, ErasedVacantEntry>), - key:extern "C" fn(RRef<'_, ErasedVacantEntry>)->&K, - fn_into_key:extern "C" fn(RVacantEntry<'_,K,V>)->K, - insert_elem:extern "C" fn(RVacantEntry<'_,K,V>,V)->&'_ mut V, +#[sabi(kind(Prefix), missing_field(panic))] +pub struct VacantVTable { + drop_entry: unsafe extern "C" fn(RMut<'_, ErasedVacantEntry>), + key: extern "C" fn(RRef<'_, ErasedVacantEntry>) -> &K, + fn_into_key: extern "C" fn(RVacantEntry<'_, K, V>) -> K, + insert_elem: extern "C" fn(RVacantEntry<'_, K, V>, V) -> &'_ mut V, } +impl VacantVTable { + const VTABLE_REF: VacantVTable_Ref = VacantVTable_Ref(Self::WM_VTABLE.as_prefix()); -impl VacantVTable{ - const VTABLE_REF: VacantVTable_Ref = VacantVTable_Ref(Self::WM_VTABLE.as_prefix()); - - staticref!{ - const WM_VTABLE: WithMetadata> = + staticref! { + const WM_VTABLE: WithMetadata> = WithMetadata::new(PrefixTypeTrait::METADATA, Self::VTABLE) } - const VTABLE:VacantVTable=VacantVTable{ - drop_entry :ErasedVacantEntry::drop_entry, - key :ErasedVacantEntry::key, - fn_into_key :ErasedVacantEntry::fn_into_key, - insert_elem :ErasedVacantEntry::insert_elem, + const VTABLE: VacantVTable = VacantVTable { + drop_entry: ErasedVacantEntry::drop_entry, + key: ErasedVacantEntry::key, + fn_into_key: ErasedVacantEntry::fn_into_key, + insert_elem: ErasedVacantEntry::insert_elem, }; } - -impl ErasedVacantEntry{ - unsafe extern "C" fn drop_entry(this: RMut<'_, Self>){ - extern_fn_panic_handling!{ +impl ErasedVacantEntry { + unsafe extern "C" fn drop_entry(this: RMut<'_, Self>) { + extern_fn_panic_handling! { Self::run_downcast_as_mut(this,|this|{ ManuallyDrop::drop(this); - }) + }) + } + } + extern "C" fn key(this: RRef<'_, Self>) -> &K { + unsafe { + extern_fn_panic_handling! { + Self::run_downcast_as( + this, + |this| this.key().as_ref() + ) + } + } + } + extern "C" fn fn_into_key(this: RVacantEntry<'_, K, V>) -> K { + unsafe { + extern_fn_panic_handling! { + Self::run_downcast_as_mut( + this.into_inner(), + |this| take_manuallydrop(this).into_key().into_inner() + ) + } + } + } + extern "C" fn insert_elem(this: RVacantEntry<'_, K, V>, elem: V) -> &'_ mut V { + unsafe { + extern_fn_panic_handling! { + Self::run_downcast_as_mut( + this.into_inner(), + |this| take_manuallydrop(this).insert(elem) + ) + } } } - extern "C" fn key(this: RRef<'_, Self>)->&K{ - unsafe{extern_fn_panic_handling!{ - Self::run_downcast_as( - this, - |this| this.key().as_ref() - ) - }} - } - extern "C" fn fn_into_key(this:RVacantEntry<'_,K,V>)->K{ - unsafe{extern_fn_panic_handling!{ - Self::run_downcast_as_mut( - this.into_inner(), - |this| take_manuallydrop(this).into_key().into_inner() - ) - }} - } - extern "C" fn insert_elem(this:RVacantEntry<'_,K,V>,elem:V)->&'_ mut V{ - unsafe{extern_fn_panic_handling!{ - Self::run_downcast_as_mut( - this.into_inner(), - |this| take_manuallydrop(this).insert(elem) - ) - }} - } } - - - ///////////////////////////////////////////////////////////////////////////////////////////// - - /// Copy paste of the unstable `ManuallyDrop::take` unsafe fn take_manuallydrop(slot: &mut ManuallyDrop) -> T { ManuallyDrop::into_inner(ptr::read(slot)) diff --git a/abi_stable/src/std_types/map/extern_fns.rs b/abi_stable/src/std_types/map/extern_fns.rs index 581a44e2..61216cab 100644 --- a/abi_stable/src/std_types/map/extern_fns.rs +++ b/abi_stable/src/std_types/map/extern_fns.rs @@ -2,162 +2,168 @@ use super::*; use crate::{ pointer_trait::TransmuteElement, - sabi_types::{RRef, RMut}, + sabi_types::{RMut, RRef}, traits::IntoReprC, }; - -impl ErasedMap -where - K:Hash+Eq, - S:BuildHasher, +impl ErasedMap +where + K: Hash + Eq, + S: BuildHasher, { - fn run<'a,F,R>(this: RRef<'a, Self>,f:F)->R - where F:FnOnce(&'a BoxedHashMap<'a,K,V,S>)->R + fn run<'a, F, R>(this: RRef<'a, Self>, f: F) -> R + where + F: FnOnce(&'a BoxedHashMap<'a, K, V, S>) -> R, { - extern_fn_panic_handling!{ + extern_fn_panic_handling! { let map = unsafe{ this.transmute_into_ref::>() }; f(map) } } - - fn run_mut<'a,F,R>(this: RMut<'a, Self>,f:F)->R - where F:FnOnce(&'a mut BoxedHashMap<'a,K,V,S>)->R + + fn run_mut<'a, F, R>(this: RMut<'a, Self>, f: F) -> R + where + F: FnOnce(&'a mut BoxedHashMap<'a, K, V, S>) -> R, { - extern_fn_panic_handling!{ + extern_fn_panic_handling! { let map = unsafe{ this.transmute_into_mut::>() }; f(map) } } - fn run_val<'a,F,R>(this:RBox,f:F)->R - where - F:FnOnce(RBox>)->R, - K:'a, - V:'a, + fn run_val<'a, F, R>(this: RBox, f: F) -> R + where + F: FnOnce(RBox>) -> R, + K: 'a, + V: 'a, { - extern_fn_panic_handling!{ + extern_fn_panic_handling! { let map = unsafe{ this.transmute_element::>() }; f( map ) } } - pub(super)extern "C" fn insert_elem(this: RMut<'_, Self>,key:K,value:V)->ROption{ - Self::run_mut(this, |this|{ - this.map.insert(MapKey::Value(key),value) - .into_c() + pub(super) extern "C" fn insert_elem(this: RMut<'_, Self>, key: K, value: V) -> ROption { + Self::run_mut(this, |this| { + this.map.insert(MapKey::Value(key), value).into_c() }) } - pub(super)extern "C" fn get_elem<'a>(this: RRef<'a, Self>, key:MapQuery<'_,K>)->Option<&'a V>{ - Self::run(this, |this|unsafe{ - this.map.get(&key.as_mapkey()) - }) - } + pub(super) extern "C" fn get_elem<'a>( + this: RRef<'a, Self>, + key: MapQuery<'_, K>, + ) -> Option<&'a V> { + Self::run(this, |this| unsafe { this.map.get(&key.as_mapkey()) }) + } - pub(super)extern "C" fn get_mut_elem<'a>(this: RMut<'a, Self>,key:MapQuery<'_,K>)->Option<&'a mut V>{ - Self::run_mut(this, |this|unsafe{ - this.map.get_mut(&key.as_mapkey()) - }) + pub(super) extern "C" fn get_mut_elem<'a>( + this: RMut<'a, Self>, + key: MapQuery<'_, K>, + ) -> Option<&'a mut V> { + Self::run_mut(this, |this| unsafe { this.map.get_mut(&key.as_mapkey()) }) } - pub(super)extern "C" fn remove_entry(this: RMut<'_, Self>,key:MapQuery<'_,K>)->ROption>{ - Self::run_mut(this, |this|{ - match this.map.remove_entry(unsafe{ &key.as_mapkey() }) { - Some(x)=>RSome(Tuple2(x.0.into_inner(),x.1)), - None=>RNone, + pub(super) extern "C" fn remove_entry( + this: RMut<'_, Self>, + key: MapQuery<'_, K>, + ) -> ROption> { + Self::run_mut(this, |this| { + match this.map.remove_entry(unsafe { &key.as_mapkey() }) { + Some(x) => RSome(Tuple2(x.0.into_inner(), x.1)), + None => RNone, } }) } - pub(super)extern "C" fn get_elem_p<'a>(this: RRef<'a, Self>, key:&K)->Option<&'a V>{ - Self::run(this, |this| this.map.get(key) ) - } + pub(super) extern "C" fn get_elem_p<'a>(this: RRef<'a, Self>, key: &K) -> Option<&'a V> { + Self::run(this, |this| this.map.get(key)) + } - pub(super)extern "C" fn get_mut_elem_p<'a>(this: RMut<'a, Self>,key:&K)->Option<&'a mut V>{ - Self::run_mut(this, |this| this.map.get_mut(key) ) + pub(super) extern "C" fn get_mut_elem_p<'a>( + this: RMut<'a, Self>, + key: &K, + ) -> Option<&'a mut V> { + Self::run_mut(this, |this| this.map.get_mut(key)) } - pub(super)extern "C" fn remove_entry_p(this: RMut<'_, Self>,key:&K)->ROption>{ - Self::run_mut(this, |this|{ - match this.map.remove_entry( key ) { - Some(x)=>RSome(Tuple2(x.0.into_inner(),x.1)), - None=>RNone, - } + pub(super) extern "C" fn remove_entry_p( + this: RMut<'_, Self>, + key: &K, + ) -> ROption> { + Self::run_mut(this, |this| match this.map.remove_entry(key) { + Some(x) => RSome(Tuple2(x.0.into_inner(), x.1)), + None => RNone, }) } - - pub(super)extern "C" fn reserve(this: RMut<'_, Self>,reserved:usize){ - Self::run_mut(this, |this| this.map.reserve(reserved) ) + pub(super) extern "C" fn reserve(this: RMut<'_, Self>, reserved: usize) { + Self::run_mut(this, |this| this.map.reserve(reserved)) } - pub(super)extern "C" fn clear_map(this: RMut<'_, Self>){ - Self::run_mut(this, |this| this.map.clear() ) + pub(super) extern "C" fn clear_map(this: RMut<'_, Self>) { + Self::run_mut(this, |this| this.map.clear()) } - pub(super)extern "C" fn len(this: RRef<'_, Self>)->usize{ - Self::run(this, |this| this.map.len() ) + pub(super) extern "C" fn len(this: RRef<'_, Self>) -> usize { + Self::run(this, |this| this.map.len()) } - pub(super)extern "C" fn capacity(this: RRef<'_, Self>)->usize{ - Self::run(this, |this| this.map.capacity() ) + pub(super) extern "C" fn capacity(this: RRef<'_, Self>) -> usize { + Self::run(this, |this| this.map.capacity()) } - pub(super)extern "C" fn iter (this: RRef<'_, Self>)->Iter<'_,K,V>{ - Self::run(this, |this|{ - let iter=this.map.iter().map(map_iter_ref); - DynTrait::from_borrowing_value(iter,RefIterInterface::NEW) + pub(super) extern "C" fn iter(this: RRef<'_, Self>) -> Iter<'_, K, V> { + Self::run(this, |this| { + let iter = this.map.iter().map(map_iter_ref); + DynTrait::from_borrowing_value(iter, RefIterInterface::NEW) }) } - pub(super)extern "C" fn iter_mut (this: RMut<'_, Self>)->IterMut<'_,K,V>{ - Self::run_mut(this, |this|{ - let iter=this.map.iter_mut().map(map_iter_ref); - DynTrait::from_borrowing_value(iter,MutIterInterface::NEW) + pub(super) extern "C" fn iter_mut(this: RMut<'_, Self>) -> IterMut<'_, K, V> { + Self::run_mut(this, |this| { + let iter = this.map.iter_mut().map(map_iter_ref); + DynTrait::from_borrowing_value(iter, MutIterInterface::NEW) }) } - pub(super)extern "C" fn drain (this: RMut<'_, Self>)->Drain<'_,K,V>{ - Self::run_mut(this, |this|{ - let iter=this.map.drain().map(map_iter_val); - DynTrait::from_borrowing_value(iter,ValIterInterface::NEW) + pub(super) extern "C" fn drain(this: RMut<'_, Self>) -> Drain<'_, K, V> { + Self::run_mut(this, |this| { + let iter = this.map.drain().map(map_iter_val); + DynTrait::from_borrowing_value(iter, ValIterInterface::NEW) }) } - pub(super)extern "C" fn iter_val(this:RBox>)->IntoIter{ - Self::run_val(this,|this|{ - let iter=this.piped(RBox::into_inner).map.into_iter().map(map_iter_val); - let iter=DynTrait::from_borrowing_value(iter,ValIterInterface::NEW); - unsafe{ IntoIter::new(iter) } + pub(super) extern "C" fn iter_val(this: RBox>) -> IntoIter { + Self::run_val(this, |this| { + let iter = this + .piped(RBox::into_inner) + .map + .into_iter() + .map(map_iter_val); + let iter = DynTrait::from_borrowing_value(iter, ValIterInterface::NEW); + unsafe { IntoIter::new(iter) } }) } - pub(super)extern "C" fn entry(this: RMut<'_, Self>,key:K)->REntry<'_,K,V>{ - Self::run_mut(this, |this|{ - this.entry=None; - let map=&mut this.map; - let entry_mut=this.entry - .get_or_insert_with(||{ - {map}.entry(MapKey::Value(key)) - .piped(BoxedREntry::from) - }); - - unsafe{ - REntry::new(entry_mut) - } + pub(super) extern "C" fn entry(this: RMut<'_, Self>, key: K) -> REntry<'_, K, V> { + Self::run_mut(this, |this| { + this.entry = None; + let map = &mut this.map; + let entry_mut = this + .entry + .get_or_insert_with(|| { map }.entry(MapKey::Value(key)).piped(BoxedREntry::from)); + + unsafe { REntry::new(entry_mut) } }) } } - -fn map_iter_ref<'a,K,V:'a>((key,val):(&'a MapKey,V))->Tuple2<&'a K,V>{ - Tuple2( key.as_ref(),val ) +fn map_iter_ref<'a, K, V: 'a>((key, val): (&'a MapKey, V)) -> Tuple2<&'a K, V> { + Tuple2(key.as_ref(), val) } -fn map_iter_val((key,val):(MapKey,V))->Tuple2{ - Tuple2( key.into_inner(),val ) +fn map_iter_val((key, val): (MapKey, V)) -> Tuple2 { + Tuple2(key.into_inner(), val) } - /////////////////////////////////////////////////////////////////////////////// diff --git a/abi_stable/src/std_types/map/iterator_stuff.rs b/abi_stable/src/std_types/map/iterator_stuff.rs index 7cf9c825..8eff31a5 100644 --- a/abi_stable/src/std_types/map/iterator_stuff.rs +++ b/abi_stable/src/std_types/map/iterator_stuff.rs @@ -2,7 +2,7 @@ use super::*; use crate::{ erased_types::IteratorItem, - utils::{transmute_reference, transmute_mut_reference}, + utils::{transmute_mut_reference, transmute_reference}, }; macro_rules! declare_iter_interface { @@ -22,15 +22,14 @@ macro_rules! declare_iter_interface { pub const NEW:Self=Self(PhantomData); } - + impl<'a,$k:'a,$v:'a> IteratorItem<'a> for $interface<$k,$v>{ type Item=$item; } ) } - -declare_iter_interface!{ +declare_iter_interface! { K=>V; /// The `InterfaceType` of the `Iter` iterator for `RHashMap`. #[sabi(impl_InterfaceType(Iterator,Clone))] @@ -38,8 +37,7 @@ declare_iter_interface!{ type Item=Tuple2<&'a K,&'a V>; } - -declare_iter_interface!{ +declare_iter_interface! { K=>V; /// The `InterfaceType` of the `IterMut` iterator for `RHashMap`. #[sabi(impl_InterfaceType(Iterator))] @@ -47,24 +45,18 @@ declare_iter_interface!{ type Item=Tuple2<&'a K,&'a mut V>; } - -declare_iter_interface!{ +declare_iter_interface! { K=>V; /// The `InterfaceType` of the `Drain` iterator for `RHashMap`. #[sabi(impl_InterfaceType(Iterator))] interface=ValIterInterface; type Item=Tuple2; - -} - +} /////////////////////////////////////////////////////////////////////////////// -type IntoIterInner<'a,K,V>= - DynTrait<'a,RBox<()>,ValIterInterface>; - - +type IntoIterInner<'a, K, V> = DynTrait<'a, RBox<()>, ValIterInterface>; /// An iterator that yields all the entries of an `RHashMap`, /// deallocating the hashmap afterwards. @@ -72,66 +64,64 @@ type IntoIterInner<'a,K,V>= /// This implements `Iterator > + !Send + !Sync` #[repr(transparent)] #[derive(StableAbi)] -pub struct IntoIter{ - iter:IntoIterInner<'static,u32,u32>, - _marker:PhantomData<(K,V,UnsafeIgnoredType>)>, +pub struct IntoIter { + iter: IntoIterInner<'static, u32, u32>, + _marker: PhantomData<(K, V, UnsafeIgnoredType>)>, } +impl IntoIter { + /** -impl IntoIter{ -/** + # Safety -# Safety - -This must be called only in `ErasedMap::into_val`. -*/ - pub(super)unsafe fn new<'a>(iter:DynTrait<'a,RBox<()>,ValIterInterface>)->Self - where - K:'a, - V:'a, + This must be called only in `ErasedMap::into_val`. + */ + pub(super) unsafe fn new<'a>(iter: DynTrait<'a, RBox<()>, ValIterInterface>) -> Self + where + K: 'a, + V: 'a, { - IntoIter{ - iter:mem::transmute::,IntoIterInner<'static,u32,u32>>(iter), - _marker:PhantomData, + IntoIter { + iter: mem::transmute::, IntoIterInner<'static, u32, u32>>(iter), + _marker: PhantomData, } } #[inline] - fn iter(&self)->&IntoIterInner<'_,K,V>{ - unsafe{ transmute_reference::,_>(&self.iter) } + fn iter(&self) -> &IntoIterInner<'_, K, V> { + unsafe { transmute_reference::, _>(&self.iter) } } #[inline] - fn iter_mut(&mut self)->&mut IntoIterInner<'_,K,V>{ - unsafe{ transmute_mut_reference::,_>(&mut self.iter) } + fn iter_mut(&mut self) -> &mut IntoIterInner<'_, K, V> { + unsafe { transmute_mut_reference::, _>(&mut self.iter) } } } - -impl Iterator for IntoIter{ - type Item=Tuple2; +impl Iterator for IntoIter { + type Item = Tuple2; #[inline] - fn next(&mut self)->Option>{ + fn next(&mut self) -> Option> { self.iter_mut().next() } #[inline] - fn nth(&mut self,nth:usize)->Option>{ + fn nth(&mut self, nth: usize) -> Option> { self.iter_mut().nth(nth) } #[inline] - fn size_hint(&self)->(usize,Option){ + fn size_hint(&self) -> (usize, Option) { self.iter().size_hint() } #[inline] - fn count(mut self)->usize{ + fn count(mut self) -> usize { self.iter_mut().by_ref().count() } #[inline] - fn last(mut self)->Option>{ + fn last(mut self) -> Option> { self.iter_mut().by_ref().last() } } diff --git a/abi_stable/src/std_types/map/map_key.rs b/abi_stable/src/std_types/map/map_key.rs index c68cc940..2d9a0965 100644 --- a/abi_stable/src/std_types/map/map_key.rs +++ b/abi_stable/src/std_types/map/map_key.rs @@ -1,71 +1,61 @@ use super::*; -pub enum MapKey{ +pub enum MapKey { Value(K), /// This is a horrible hack. - Query(NonNull>), + Query(NonNull>), } - -impl MapKey{ +impl MapKey { #[inline] - pub fn into_inner(self)->K{ + pub fn into_inner(self) -> K { match self { - MapKey::Value(v)=>v, - _=>unreachable!("This is a BUG!!!!!!!!!!!!!!!!!!!!") + MapKey::Value(v) => v, + _ => unreachable!("This is a BUG!!!!!!!!!!!!!!!!!!!!"), } } #[inline] - pub fn as_ref(&self)->&K{ + pub fn as_ref(&self) -> &K { match self { - MapKey::Value(v)=>v, - _=>unreachable!("This is a BUG!!!!!!!!!!!!!!!!!!!!") + MapKey::Value(v) => v, + _ => unreachable!("This is a BUG!!!!!!!!!!!!!!!!!!!!"), } } } - -impl From for MapKey{ +impl From for MapKey { #[inline] - fn from(value:K)->Self{ + fn from(value: K) -> Self { MapKey::Value(value) } } impl Debug for MapKey -where - K:Debug +where + K: Debug, { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - MapKey::Value(v)=>Debug::fmt(v,f), - _=>unreachable!("This is a BUG!!!!!!!!!!!!!!!!!!!!") + MapKey::Value(v) => Debug::fmt(v, f), + _ => unreachable!("This is a BUG!!!!!!!!!!!!!!!!!!!!"), } } } -impl Eq for MapKey -where - K:Eq -{} +impl Eq for MapKey where K: Eq {} impl PartialEq for MapKey where - K:PartialEq + K: PartialEq, { - fn eq<'a>(&'a self, other: &'a Self) -> bool{ - match (self,other) { - (MapKey::Value(lhs),MapKey::Query(rhs)) - |(MapKey::Query(rhs),MapKey::Value(lhs))=>{ - unsafe{ - rhs.as_ref().is_equal(lhs) - } - } - (MapKey::Value(lhs),MapKey::Value(rhs))=>{ - lhs==rhs - } - _=>{ + fn eq<'a>(&'a self, other: &'a Self) -> bool { + match (self, other) { + (MapKey::Value(lhs), MapKey::Query(rhs)) | (MapKey::Query(rhs), MapKey::Value(lhs)) => unsafe { + rhs.as_ref().is_equal(lhs) + }, + (MapKey::Value(lhs), MapKey::Value(rhs)) => lhs == rhs, + _ => { unreachable!("This is a BUG!!!!!!!!!!!!!!!!!!!!!!!!"); } } @@ -73,29 +63,26 @@ where } impl Hash for MapKey -where - K:Hash +where + K: Hash, { - fn hash(&self,hasher:&mut H) + fn hash(&self, hasher: &mut H) where - H:Hasher + H: Hasher, { match self { - MapKey::Value(this)=>{ + MapKey::Value(this) => { this.hash(hasher); } - MapKey::Query(this)=>{ - unsafe{ - this.as_ref().hash(hasher); - } - } + MapKey::Query(this) => unsafe { + this.as_ref().hash(hasher); + }, } } } - -impl Borrow for MapKey{ - fn borrow(&self)->&K{ +impl Borrow for MapKey { + fn borrow(&self) -> &K { self.as_ref() } -} \ No newline at end of file +} diff --git a/abi_stable/src/std_types/map/map_query.rs b/abi_stable/src/std_types/map/map_query.rs index 0ec1f219..dafbf1ea 100644 --- a/abi_stable/src/std_types/map/map_query.rs +++ b/abi_stable/src/std_types/map/map_query.rs @@ -3,25 +3,25 @@ use super::*; /// A trait object used in method that access map entries without replacing them. #[derive(StableAbi)] #[repr(C)] -pub struct MapQuery<'a, K>{ - _marker:NotCopyNotClone, - is_equal:extern "C" fn(&K, RRef<'_, ErasedObject>)->bool, - hash :extern "C" fn(RRef<'_, ErasedObject>,HasherObject<'_>), +pub struct MapQuery<'a, K> { + _marker: NotCopyNotClone, + is_equal: extern "C" fn(&K, RRef<'_, ErasedObject>) -> bool, + hash: extern "C" fn(RRef<'_, ErasedObject>, HasherObject<'_>), query: RRef<'a, ErasedObject>, } -impl<'a,K> MapQuery<'a,K>{ +impl<'a, K> MapQuery<'a, K> { #[inline] - pub(super) fn new(query:&'a &'a Q)->Self - where - K:Borrow, - Q:Hash + Eq + 'a+?Sized, + pub(super) fn new(query: &'a &'a Q) -> Self + where + K: Borrow, + Q: Hash + Eq + 'a + ?Sized, { - MapQuery{ + MapQuery { _marker: NotCopyNotClone, - is_equal: is_equal::, - hash : hash::, - query: unsafe{ RRef::new(query).transmute() }, + is_equal: is_equal::, + hash: hash::, + query: unsafe { RRef::new(query).transmute() }, } } @@ -29,29 +29,28 @@ impl<'a,K> MapQuery<'a,K>{ // pub(super) unsafe fn to_static(self)->MapQuery<'static,K>{ // mem::transmute::,MapQuery<'static,K>>(self) // } - + #[inline] - pub(super) unsafe fn as_static(&self)->&MapQuery<'static,K>{ + pub(super) unsafe fn as_static(&self) -> &MapQuery<'static, K> { crate::utils::transmute_reference(self) } } -impl<'a,K> MapQuery<'a,K>{ +impl<'a, K> MapQuery<'a, K> { #[inline] - pub(super) fn is_equal(&self,other:&K)->bool{ - (self.is_equal)(other,self.query) + pub(super) fn is_equal(&self, other: &K) -> bool { + (self.is_equal)(other, self.query) } #[inline] - pub(super) unsafe fn as_mapkey(&self)->MapKey{ + pub(super) unsafe fn as_mapkey(&self) -> MapKey { MapKey::Query(NonNull::from(self.as_static())) } } - -impl<'a,K> Hash for MapQuery<'a,K>{ +impl<'a, K> Hash for MapQuery<'a, K> { #[inline] - fn hash(&self,hasher:&mut H) + fn hash(&self, hasher: &mut H) where H: Hasher, { @@ -59,24 +58,22 @@ impl<'a,K> Hash for MapQuery<'a,K>{ } } - -extern "C" fn is_equal(key:&K,query:RRef<'_, ErasedObject>)->bool +extern "C" fn is_equal(key: &K, query: RRef<'_, ErasedObject>) -> bool where - K:Borrow, - Q:Eq+?Sized, + K: Borrow, + Q: Eq + ?Sized, { - extern_fn_panic_handling!{ + extern_fn_panic_handling! { let query = unsafe{ query.transmute_into_ref::<&Q>() }; key.borrow()==*query } } - -extern "C" fn hash(query:RRef<'_, ErasedObject>,mut hasher:HasherObject<'_>) +extern "C" fn hash(query: RRef<'_, ErasedObject>, mut hasher: HasherObject<'_>) where - Q:Hash+?Sized, + Q: Hash + ?Sized, { - extern_fn_panic_handling!{ + extern_fn_panic_handling! { let query = unsafe{ query.transmute_into_ref::<&Q>() }; query.hash(&mut hasher); } diff --git a/abi_stable/src/std_types/map/test.rs b/abi_stable/src/std_types/map/test.rs index 10d7697f..26e282ce 100644 --- a/abi_stable/src/std_types/map/test.rs +++ b/abi_stable/src/std_types/map/test.rs @@ -6,76 +6,62 @@ use fnv::FnvBuildHasher as FnVBH; use crate::std_types::RString; +type DefaultBH = RandomState; -type DefaultBH=RandomState; - - -fn new_stdmap()->HashMap{ - vec![ - (90,40), - (10,20), - (88,30), - (77,22), - ].into_iter() - .collect() +fn new_stdmap() -> HashMap { + vec![(90, 40), (10, 20), (88, 30), (77, 22)] + .into_iter() + .collect() } -fn new_map()->RHashMap +fn new_map() -> RHashMap where - K:FromStr+Hash+Eq, - V:FromStr, - S:BuildHasher+Default, - K::Err:Debug, - V::Err:Debug, + K: FromStr + Hash + Eq, + V: FromStr, + S: BuildHasher + Default, + K::Err: Debug, + V::Err: Debug, { - vec![ - ("90","40"), - ("10","20"), - ("88","30"), - ("77","22"), - ].into_iter() - .map(|(k,v)| (k.parse::().unwrap(),v.parse::().unwrap()) ) - .collect() + vec![("90", "40"), ("10", "20"), ("88", "30"), ("77", "22")] + .into_iter() + .map(|(k, v)| (k.parse::().unwrap(), v.parse::().unwrap())) + .collect() } - #[test] -fn test_new_map(){ - let mut map=RHashMap::new(); - map.insert(10,100); +fn test_new_map() { + let mut map = RHashMap::new(); + map.insert(10, 100); assert_eq!(map.get(&10), Some(&100)); } - #[test] -fn test_default(){ - let default_=RHashMap::::default(); - let new_=RHashMap::::new(); +fn test_default() { + let default_ = RHashMap::::default(); + let new_ = RHashMap::::new(); - assert_eq!(default_.len(),0); - assert_eq!(default_.capacity(),0); + assert_eq!(default_.len(), 0); + assert_eq!(default_.capacity(), 0); - assert_eq!(default_,new_); + assert_eq!(default_, new_); } - #[test] -fn reserve(){ - let mut map=RHashMap::::new(); - assert_eq!(map.len(),0); - assert_eq!(map.capacity(),0); +fn reserve() { + let mut map = RHashMap::::new(); + assert_eq!(map.len(), 0); + assert_eq!(map.capacity(), 0); map.reserve(100); - assert!(100 <= map.capacity(),"capacity:{}",map.capacity()); - assert_eq!(map.len(),0); + assert!(100 <= map.capacity(), "capacity:{}", map.capacity()); + assert_eq!(map.len(), 0); } - #[test] -fn test_eq(){ - let map0=new_map::(); - let map1=new_map::(); - let map2=new_map::(); +fn test_eq() { + let map0 = new_map::(); + let map1 = new_map::(); + let map2 = new_map::(); assert_eq!(map0, map1); assert_eq!(map0, map2); @@ -83,356 +69,346 @@ fn test_eq(){ } #[test] -fn clone(){ +fn clone() { macro_rules! clone_test { - ( $hasher:ty ) => ({ - let map=new_map::(); - let clone_=map.clone(); - + ( $hasher:ty ) => {{ + let map = new_map::(); + let clone_ = map.clone(); + // Cloned String should never point to the same buffer assert_ne!( - map.get("90").unwrap().as_ptr(), + map.get("90").unwrap().as_ptr(), clone_.get("90").unwrap().as_ptr(), ); assert_eq!(map, clone_); - - }) + }}; } - - clone_test!{DefaultBH} - clone_test!{FnVBH} + clone_test! {DefaultBH} + clone_test! {FnVBH} } - macro_rules! insert_test { - ( $hasher:ty ) => ({ - let mut map=RHashMap::::default(); - map.insert("what".into(),10); - map.insert("the".into(),5); - - assert_eq!( - map.insert("what".into(),33), - RSome(10), - ); - assert_eq!( - map.insert("the".into(),77), - RSome(5), - ); - }) + ( $hasher:ty ) => {{ + let mut map = RHashMap::::default(); + map.insert("what".into(), 10); + map.insert("the".into(), 5); + + assert_eq!(map.insert("what".into(), 33), RSome(10),); + assert_eq!(map.insert("the".into(), 77), RSome(5),); + }}; } #[test] -fn insert(){ - - - insert_test!{DefaultBH} - insert_test!{FnVBH} - +fn insert() { + insert_test! {DefaultBH} + insert_test! {FnVBH} } - macro_rules! remove_test { - ( $hasher:ty ) => ({ - let mut map=RHashMap::::default(); - map.insert("what".into(),10); - map.insert("the".into(),5); - map.insert("is".into(),14); - map.insert("that".into(),54); + ( $hasher:ty ) => {{ + let mut map = RHashMap::::default(); + map.insert("what".into(), 10); + map.insert("the".into(), 5); + map.insert("is".into(), 14); + map.insert("that".into(), 54); - assert_eq!( - map.remove_entry("the"), - RSome(Tuple2("the".to_string(),5)), - ); - assert_eq!( - map.remove_entry("the"), - RNone, - ); + assert_eq!(map.remove_entry("the"), RSome(Tuple2("the".to_string(), 5)),); + assert_eq!(map.remove_entry("the"), RNone,); assert_eq!( map.remove_entry_p(&"what".into()), - RSome(Tuple2("what".to_string(),10)), - ); - assert_eq!( - map.remove_entry_p(&"what".into()), - RNone, + RSome(Tuple2("what".to_string(), 10)), ); + assert_eq!(map.remove_entry_p(&"what".into()), RNone,); assert_eq!( map.remove_entry_p(&"is".into()), - RSome(Tuple2("is".to_string(),14)), - ); - assert_eq!( - map.remove_entry_p(&"is".into()), - RNone, + RSome(Tuple2("is".to_string(), 14)), ); + assert_eq!(map.remove_entry_p(&"is".into()), RNone,); assert_eq!( map.remove_entry("that"), - RSome(Tuple2("that".to_string(),54)), - ); - assert_eq!( - map.remove_entry("that"), - RNone, + RSome(Tuple2("that".to_string(), 54)), ); - }) + assert_eq!(map.remove_entry("that"), RNone,); + }}; } #[test] -fn remove(){ - remove_test!{DefaultBH} - remove_test!{FnVBH} +fn remove() { + remove_test! {DefaultBH} + remove_test! {FnVBH} } - -fn check_get(map:&mut RHashMap,key:K,value:Option) +fn check_get(map: &mut RHashMap, key: K, value: Option) where - K:Eq+Hash+Clone+Debug, - V:PartialEq+Clone+Debug, + K: Eq + Hash + Clone + Debug, + V: PartialEq + Clone + Debug, { - assert_eq!(map.get(&key).cloned(),value.clone()); - assert_eq!(map.get_p(&key).cloned(),value.clone()); - assert_eq!(map.get_mut(&key).cloned(),value.clone()); - assert_eq!(map.get_mut_p(&key).cloned(),value.clone()); - - assert_eq!(map.contains_key(&key),value.is_some(),"\nkey:{:?} value:{:?}\n",key,value ); - assert_eq!(map.contains_key_p(&key),value.is_some(),"\nkey:{:?} value:{:?}\n",key,value ); - - if let Some(mut value)=value.clone() { - assert_eq!(&map[&key],&value); - assert_eq!(map.index_p(&key),&value); - - assert_eq!((&mut map[&key]),&mut value); - assert_eq!(map.index_mut_p(&key),&mut value); + assert_eq!(map.get(&key).cloned(), value.clone()); + assert_eq!(map.get_p(&key).cloned(), value.clone()); + assert_eq!(map.get_mut(&key).cloned(), value.clone()); + assert_eq!(map.get_mut_p(&key).cloned(), value.clone()); + + assert_eq!( + map.contains_key(&key), + value.is_some(), + "\nkey:{:?} value:{:?}\n", + key, + value + ); + assert_eq!( + map.contains_key_p(&key), + value.is_some(), + "\nkey:{:?} value:{:?}\n", + key, + value + ); + + if let Some(mut value) = value.clone() { + assert_eq!(&map[&key], &value); + assert_eq!(map.index_p(&key), &value); + + assert_eq!((&mut map[&key]), &mut value); + assert_eq!(map.index_mut_p(&key), &mut value); } - } macro_rules! get_test { - ( $hasher:ty ) => ({ - let mut map=RHashMap::::default(); - map.insert("what".into(),10); - map.insert("the".into(),5); - map.insert("oof".into(),33); - map.insert("you".into(),55); - - check_get(&mut map,"what".into(),Some(10)); - check_get(&mut map,"the".into(),Some(5)); - check_get(&mut map,"oof".into(),Some(33)); - check_get(&mut map,"you".into(),Some(55)); - - check_get(&mut map,"wasdat".into(),None); - check_get(&mut map,"thasdae".into(),None); - check_get(&mut map,"ofwwf".into(),None); - check_get(&mut map,"youeeeee".into(),None); - - if let Some(x)=map.get_mut("what") { - *x=*x*2; + ( $hasher:ty ) => {{ + let mut map = RHashMap::::default(); + map.insert("what".into(), 10); + map.insert("the".into(), 5); + map.insert("oof".into(), 33); + map.insert("you".into(), 55); + + check_get(&mut map, "what".into(), Some(10)); + check_get(&mut map, "the".into(), Some(5)); + check_get(&mut map, "oof".into(), Some(33)); + check_get(&mut map, "you".into(), Some(55)); + + check_get(&mut map, "wasdat".into(), None); + check_get(&mut map, "thasdae".into(), None); + check_get(&mut map, "ofwwf".into(), None); + check_get(&mut map, "youeeeee".into(), None); + + if let Some(x) = map.get_mut("what") { + *x = *x * 2; } - if let Some(x)=map.get_mut("the") { - *x=*x*2; + if let Some(x) = map.get_mut("the") { + *x = *x * 2; } - if let Some(x)=map.get_mut("oof") { - *x=*x*2; + if let Some(x) = map.get_mut("oof") { + *x = *x * 2; } - if let Some(x)=map.get_mut("you") { - *x=*x*2; + if let Some(x) = map.get_mut("you") { + *x = *x * 2; } - assert_eq!(map.get("what"),Some(&20)); - assert_eq!(map.get("the"),Some(&10)); - assert_eq!(map.get("oof"),Some(&66)); - assert_eq!(map.get("you"),Some(&110)); - }) + assert_eq!(map.get("what"), Some(&20)); + assert_eq!(map.get("the"), Some(&10)); + assert_eq!(map.get("oof"), Some(&66)); + assert_eq!(map.get("you"), Some(&110)); + }}; } #[test] -fn get(){ - get_test!{DefaultBH} - get_test!{FnVBH} +fn get() { + get_test! {DefaultBH} + get_test! {FnVBH} } - - - #[test] -fn clear(){ - let mut map=RHashMap::::new(); - map.insert("what".into(),10); - map.insert("the".into(),5); - map.insert("oof".into(),33); - map.insert("you".into(),55); - - assert_eq!(map.get("what"),Some(&10)); - assert_eq!(map.get("the"),Some(&5)); - assert_eq!(map.get("oof"),Some(&33)); - assert_eq!(map.get("you"),Some(&55)); +fn clear() { + let mut map = RHashMap::::new(); + map.insert("what".into(), 10); + map.insert("the".into(), 5); + map.insert("oof".into(), 33); + map.insert("you".into(), 55); + + assert_eq!(map.get("what"), Some(&10)); + assert_eq!(map.get("the"), Some(&5)); + assert_eq!(map.get("oof"), Some(&33)); + assert_eq!(map.get("you"), Some(&55)); map.clear(); - assert_eq!(map.get("what"),None); - assert_eq!(map.get("the"),None); - assert_eq!(map.get("oof"),None); - assert_eq!(map.get("you"),None); + assert_eq!(map.get("what"), None); + assert_eq!(map.get("the"), None); + assert_eq!(map.get("oof"), None); + assert_eq!(map.get("you"), None); } - - #[test] -fn len_is_empty(){ - let mut map=RHashMap::::new(); +fn len_is_empty() { + let mut map = RHashMap::::new(); assert!(map.is_empty()); - assert_eq!(map.len(),0); - - map.insert("what".into(),10); + assert_eq!(map.len(), 0); + + map.insert("what".into(), 10); assert!(!map.is_empty()); - assert_eq!(map.len(),1); - - map.insert("the".into(),5); + assert_eq!(map.len(), 1); + + map.insert("the".into(), 5); assert!(!map.is_empty()); - assert_eq!(map.len(),2); - - map.insert("oof".into(),33); + assert_eq!(map.len(), 2); + + map.insert("oof".into(), 33); assert!(!map.is_empty()); - assert_eq!(map.len(),3); - - map.insert("you".into(),55); + assert_eq!(map.len(), 3); + + map.insert("you".into(), 55); assert!(!map.is_empty()); - assert_eq!(map.len(),4); + assert_eq!(map.len(), 4); map.clear(); - + assert!(map.is_empty()); - assert_eq!(map.len(),0); + assert_eq!(map.len(), 0); } - - #[test] -fn from_hashmap(){ - let mut stdmap=new_stdmap(); +fn from_hashmap() { + let mut stdmap = new_stdmap(); - let mut map:RHashMap=stdmap.clone().into(); + let mut map: RHashMap = stdmap.clone().into(); assert_eq!(map.len(), 4); - - for Tuple2(key,val) in map.drain() { - assert_eq!(stdmap.remove(&key),Some(val),"key:{:?} value:{:?}",key,val); + + for Tuple2(key, val) in map.drain() { + assert_eq!( + stdmap.remove(&key), + Some(val), + "key:{:?} value:{:?}", + key, + val + ); } assert_eq!(stdmap.len(), 0); - assert!(map.is_empty(),"map length:{:?}",map.len()); - + assert!(map.is_empty(), "map length:{:?}", map.len()); } - #[test] -fn into_hashmap(){ - let stdmap=new_stdmap(); +fn into_hashmap() { + let stdmap = new_stdmap(); - let map:RHashMap=stdmap.clone().into(); + let map: RHashMap = stdmap.clone().into(); - let stdmap2:HashMap<_,_>=map.into(); + let stdmap2: HashMap<_, _> = map.into(); - assert_eq!(stdmap2,stdmap); + assert_eq!(stdmap2, stdmap); } - #[test] -fn from_iter(){ - let mut stdmap=new_stdmap(); +fn from_iter() { + let mut stdmap = new_stdmap(); - let map:RHashMap=stdmap.clone().into_iter().collect(); + let map: RHashMap = stdmap.clone().into_iter().collect(); assert_eq!(map.len(), 4); - - let mapper=|Tuple2(k,v):Tuple2<&u32,&u32>|{ - (k.clone(),v.clone()) - }; + + let mapper = |Tuple2(k, v): Tuple2<&u32, &u32>| (k.clone(), v.clone()); assert_eq!( - map.iter().map(mapper).collect::>(), - (&map).into_iter().map(mapper).collect::>(), + map.iter().map(mapper).collect::>(), + (&map).into_iter().map(mapper).collect::>(), ); - for Tuple2(key,val) in map.iter() { - assert_eq!(stdmap.remove(&key).as_ref(),Some(val),"key:{:?} value:{:?}",key,val); + for Tuple2(key, val) in map.iter() { + assert_eq!( + stdmap.remove(&key).as_ref(), + Some(val), + "key:{:?} value:{:?}", + key, + val + ); } assert_eq!(stdmap.len(), 0); - } - #[test] -fn into_iter(){ - let mut stdmap=new_stdmap(); +fn into_iter() { + let mut stdmap = new_stdmap(); - let mut map:RHashMap=stdmap.clone().into_iter().collect(); + let mut map: RHashMap = stdmap.clone().into_iter().collect(); assert_eq!(map.len(), 4); - let mapper=|Tuple2(k,v):Tuple2<&u32,&mut u32>|{ - (k.clone(),(&*v).clone()) - }; + let mapper = |Tuple2(k, v): Tuple2<&u32, &mut u32>| (k.clone(), (&*v).clone()); assert_eq!( - map.iter_mut().map(mapper).collect::>(), - (&mut map).into_iter().map(mapper).collect::>(), + map.iter_mut().map(mapper).collect::>(), + (&mut map).into_iter().map(mapper).collect::>(), ); - - for Tuple2(key,val) in map.into_iter() { - assert_eq!(stdmap.remove(&key).as_ref(),Some(&val),"key:{:?} value:{:?}",key,val); + + for Tuple2(key, val) in map.into_iter() { + assert_eq!( + stdmap.remove(&key).as_ref(), + Some(&val), + "key:{:?} value:{:?}", + key, + val + ); } assert_eq!(stdmap.len(), 0); - } - #[test] -fn iter_mut(){ - let mut stdmap=new_stdmap(); - let mut map:RHashMap<_,_>=new_stdmap().into(); +fn iter_mut() { + let mut stdmap = new_stdmap(); + let mut map: RHashMap<_, _> = new_stdmap().into(); - for Tuple2(key,val) in map.iter_mut() { - assert_eq!(stdmap.remove(&*key).as_ref(),Some(&*val),"key:{:?} value:{:?}",key,val); - *val=*val+key; + for Tuple2(key, val) in map.iter_mut() { + assert_eq!( + stdmap.remove(&*key).as_ref(), + Some(&*val), + "key:{:?} value:{:?}", + key, + val + ); + *val = *val + key; } assert_eq!(stdmap.len(), 0); - assert_eq!(map.get(&90),Some(&130)); - assert_eq!(map.get(&10),Some(&30)); - assert_eq!(map.get(&88),Some(&118)); - assert_eq!(map.get(&77),Some(&99)); + assert_eq!(map.get(&90), Some(&130)); + assert_eq!(map.get(&10), Some(&30)); + assert_eq!(map.get(&88), Some(&118)); + assert_eq!(map.get(&77), Some(&99)); } - #[test] -fn extend(){ - let expected=new_map::(); +fn extend() { + let expected = new_map::(); { - let mut map:RHashMap=RHashMap::new(); + let mut map: RHashMap = RHashMap::new(); - map.extend(new_map::<_,_,FnVBH>()); + map.extend(new_map::<_, _, FnVBH>()); assert_eq!(map, expected); } { - let mut map:RHashMap=RHashMap::new(); + let mut map: RHashMap = RHashMap::new(); - map.extend(new_map::<_,_,DefaultBH>().into_iter().map(Tuple2::into_rust)); + map.extend( + new_map::<_, _, DefaultBH>() + .into_iter() + .map(Tuple2::into_rust), + ); assert_eq!(map, expected); } } - #[test] -fn test_serde(){ - let mut map=RHashMap::::new(); +fn test_serde() { + let mut map = RHashMap::::new(); - map.insert("90".into(),"40".into()); - map.insert("10".into(),"20".into()); - map.insert("88".into(),"30".into()); - map.insert("77".into(),"22".into()); + map.insert("90".into(), "40".into()); + map.insert("10".into(), "20".into()); + map.insert("88".into(), "30".into()); + map.insert("77".into(), "22".into()); - let json=r##" + let json = r##" { "90":"40", "10":"20", @@ -441,158 +417,151 @@ fn test_serde(){ } "##; - let deserialized=serde_json::from_str::>(json).unwrap(); + let deserialized = serde_json::from_str::>(json).unwrap(); - assert_eq!(deserialized,map); + assert_eq!(deserialized, map); - let serialized=serde_json::to_string(&map).unwrap(); + let serialized = serde_json::to_string(&map).unwrap(); - fn remove_whitespace(s:&str)->String{ - s.chars().filter(|c| !c.is_whitespace() ).collect() + fn remove_whitespace(s: &str) -> String { + s.chars().filter(|c| !c.is_whitespace()).collect() } - let removed_ws=remove_whitespace(&serialized); + let removed_ws = remove_whitespace(&serialized); - assert!(removed_ws.starts_with("{\""),"text:{}",removed_ws); - assert!(removed_ws.contains(r##""90":"40""##),"text:{}",removed_ws); - assert!(removed_ws.contains(r##""10":"20""##),"text:{}",removed_ws); - assert!(removed_ws.contains(r##""88":"30""##),"text:{}",removed_ws); - assert!(removed_ws.contains(r##""77":"22""##),"text:{}",removed_ws); - assert_eq!(removed_ws.matches("\",\"").count(),3,"text:{}",removed_ws); - assert!(removed_ws.ends_with("\"}"),"text:{}",removed_ws); - - let redeserialized=serde_json::from_str::>(&serialized).unwrap(); + assert!(removed_ws.starts_with("{\""), "text:{}", removed_ws); + assert!(removed_ws.contains(r##""90":"40""##), "text:{}", removed_ws); + assert!(removed_ws.contains(r##""10":"20""##), "text:{}", removed_ws); + assert!(removed_ws.contains(r##""88":"30""##), "text:{}", removed_ws); + assert!(removed_ws.contains(r##""77":"22""##), "text:{}", removed_ws); + assert_eq!( + removed_ws.matches("\",\"").count(), + 3, + "text:{}", + removed_ws + ); + assert!(removed_ws.ends_with("\"}"), "text:{}", removed_ws); - assert_eq!(redeserialized,map); + let redeserialized = serde_json::from_str::>(&serialized).unwrap(); + assert_eq!(redeserialized, map); } - -fn assert_is_occupied(map:&mut RHashMap,k:K,v:V) +fn assert_is_occupied(map: &mut RHashMap, k: K, v: V) where - K:Eq+Hash+Clone+Debug, - V:Clone+Debug+PartialEq, + K: Eq + Hash + Clone + Debug, + V: Clone + Debug + PartialEq, { - let mut entry=map.entry(k.clone()); - assert_matches!(REntry::Occupied{..}=entry); + let mut entry = map.entry(k.clone()); + assert_matches!(REntry::Occupied { .. } = entry); assert_eq!(entry.key(), &k); assert_eq!(entry.get().cloned(), Some(v.clone())); assert_eq!(entry.get_mut().cloned(), Some(v.clone())); } -fn assert_is_vacant(map:&mut RHashMap,k:K) +fn assert_is_vacant(map: &mut RHashMap, k: K) where - K:Eq+Hash+Clone+Debug, - V:Clone+Debug+PartialEq, + K: Eq + Hash + Clone + Debug, + V: Clone + Debug + PartialEq, { - let mut entry=map.entry(k.clone()); - assert_matches!(REntry::Vacant{..}=entry); + let mut entry = map.entry(k.clone()); + assert_matches!(REntry::Vacant { .. } = entry); assert_eq!(entry.key(), &k); assert_eq!(entry.get().cloned(), None); assert_eq!(entry.get_mut().cloned(), None); } - #[test] -fn existing_is_occupied(){ - let mut map=new_map::(); +fn existing_is_occupied() { + let mut map = new_map::(); - assert_is_occupied(&mut map,"90".into(),"40".into()); - assert_is_occupied(&mut map,"10".into(),"20".into()); - assert_is_occupied(&mut map,"88".into(),"30".into()); - assert_is_occupied(&mut map,"77".into(),"22".into()); + assert_is_occupied(&mut map, "90".into(), "40".into()); + assert_is_occupied(&mut map, "10".into(), "20".into()); + assert_is_occupied(&mut map, "88".into(), "30".into()); + assert_is_occupied(&mut map, "77".into(), "22".into()); - assert_is_vacant(&mut map,"13".into()); - assert_is_vacant(&mut map,"14".into()); + assert_is_vacant(&mut map, "13".into()); + assert_is_vacant(&mut map, "14".into()); } - #[test] -fn entry_or_insert(){ - let mut map=new_map::(); - - assert_is_vacant(&mut map,"12".into()); +fn entry_or_insert() { + let mut map = new_map::(); + + assert_is_vacant(&mut map, "12".into()); assert_eq!( *map.entry("12".into()).or_insert("100".into()), "100".into_::() ); - assert_is_occupied(&mut map,"12".into(),"100".into()); - + assert_is_occupied(&mut map, "12".into(), "100".into()); + assert_eq!( - *map.entry("12".into()).or_insert("105".into()), + *map.entry("12".into()).or_insert("105".into()), "100".into_::() ); - assert_is_occupied(&mut map,"12".into(),"100".into()); - + assert_is_occupied(&mut map, "12".into(), "100".into()); } - #[test] -fn entry_or_insert_with(){ - let mut map=new_map::(); - - assert_is_vacant(&mut map,"12".into()); +fn entry_or_insert_with() { + let mut map = new_map::(); + + assert_is_vacant(&mut map, "12".into()); assert_eq!( - *map.entry("12".into()).or_insert_with(||"100".into()), + *map.entry("12".into()).or_insert_with(|| "100".into()), "100".into_::() ); - assert_is_occupied(&mut map,"12".into(),"100".into()); - + assert_is_occupied(&mut map, "12".into(), "100".into()); + assert_eq!( - *map.entry("12".into()).or_insert_with(||unreachable!()), + *map.entry("12".into()).or_insert_with(|| unreachable!()), "100".into_::() ); - assert_is_occupied(&mut map,"12".into(),"100".into()); + assert_is_occupied(&mut map, "12".into(), "100".into()); } - #[test] -fn entry_and_modify(){ - let mut map=new_map::(); - - assert_is_vacant(&mut map,"12".into()); - - assert_matches!( - REntry::Vacant{..}= - map.entry("12".into()).and_modify(|_| unreachable!() ) - ); +fn entry_and_modify() { + let mut map = new_map::(); + + assert_is_vacant(&mut map, "12".into()); + + assert_matches!(REntry::Vacant { .. } = map.entry("12".into()).and_modify(|_| unreachable!())); assert_eq!( *map.entry("12".into()) - .and_modify(|_| unreachable!() ) - .or_insert_with(||"100".into()), + .and_modify(|_| unreachable!()) + .or_insert_with(|| "100".into()), "100".into_::() ); - assert_is_occupied(&mut map,"12".into(),"100".into()); - + assert_is_occupied(&mut map, "12".into(), "100".into()); + assert_eq!( *map.entry("12".into()) - .and_modify(|v| *v="what".into() ) - .or_insert_with(||unreachable!()), + .and_modify(|v| *v = "what".into()) + .or_insert_with(|| unreachable!()), "what".into_::() ); - assert_is_occupied(&mut map,"12".into(),"what".into()); + assert_is_occupied(&mut map, "12".into(), "what".into()); } - - #[test] -fn entry_or_default(){ - let mut map=new_map::(); - - assert_is_vacant(&mut map,"12".into()); +fn entry_or_default() { + let mut map = new_map::(); + + assert_is_vacant(&mut map, "12".into()); assert_eq!( *map.entry("12".into()) - .and_modify(|_| unreachable!() ) + .and_modify(|_| unreachable!()) .or_default(), "".into_::() ); assert_eq!( *map.entry("12".into()) - .and_modify(|v| *v="hello".into() ) + .and_modify(|v| *v = "hello".into()) .or_default(), "hello".into_::() ); diff --git a/abi_stable/src/std_types/option.rs b/abi_stable/src/std_types/option.rs index abe2abad..2cddd4f2 100644 --- a/abi_stable/src/std_types/option.rs +++ b/abi_stable/src/std_types/option.rs @@ -8,7 +8,6 @@ use core_extensions::matches; use serde::{Deserialize, Deserializer, Serialize, Serializer}; - /// Ffi-safe equivalent of the `std::option::Option` type. /// /// `Option` is also ffi-safe for NonNull/NonZero types,and references. @@ -30,7 +29,7 @@ impl ROption { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(10) .as_ref(),RSome(&10)); /// assert_eq!(RNone::.as_ref(),RNone ); @@ -49,7 +48,7 @@ impl ROption { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(10) .as_mut(),RSome(&mut 10)); /// assert_eq!(RNone::.as_mut(),RNone ); @@ -62,21 +61,21 @@ impl ROption { RNone => RNone, } } - + /// Returns whether `self` is an `RSome` /// /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(10) .is_rsome(),true); /// assert_eq!(RNone::.is_rsome(),false); /// /// ``` #[inline] - pub fn is_rsome(&self)->bool{ - matches!(self, RSome{..}) + pub fn is_rsome(&self) -> bool { + matches!(self, RSome { .. }) } /// Returns whether `self` is an `RNone` @@ -84,32 +83,31 @@ impl ROption { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(10) .is_rnone(),false); /// assert_eq!(RNone::.is_rnone(),true); /// /// ``` #[inline] - pub fn is_rnone(&self)->bool{ - matches!(self, RNone{..}) + pub fn is_rnone(&self) -> bool { + matches!(self, RNone { .. }) } - /// Returns whether `self` is an `RSome` /// /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(10) .is_some(),true); /// assert_eq!(RNone::.is_some(),false); /// /// ``` #[inline] - pub fn is_some(&self)->bool{ - matches!(self, RSome{..}) + pub fn is_some(&self) -> bool { + matches!(self, RSome { .. }) } /// Returns whether `self` is an `RNone` @@ -117,24 +115,23 @@ impl ROption { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(10) .is_none(),false); /// assert_eq!(RNone::.is_none(),true); /// /// ``` #[inline] - pub fn is_none(&self)->bool{ - matches!(self, RNone{..}) + pub fn is_none(&self) -> bool { + matches!(self, RNone { .. }) } - /// Converts from `ROption` to `Option`. /// /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(10) .into_option(),Some(10)); /// assert_eq!(RNone::.into_option(),None ); @@ -146,15 +143,15 @@ impl ROption { } /// Unwraps the `ROption`, returning its contents. - /// + /// /// # Panics - /// + /// /// Panics if `self` is `RNone`, with the `msg` message. /// /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!( RSome(100).expect("must contain a value"), 100 ); /// @@ -162,7 +159,7 @@ impl ROption { /// /// This one panics: /// ```should_panic - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// let _=RNone::<()>.expect("Oh noooo!"); /// ``` @@ -171,15 +168,15 @@ impl ROption { self.into_option().expect(msg) } /// Unwraps the ROption, returning its contents. - /// + /// /// # Panics - /// + /// /// Panics if `self` is `RNone`. /// /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!( RSome(500).unwrap(), 500 ); /// @@ -187,7 +184,7 @@ impl ROption { /// /// This one panics: /// ```should_panic - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// let _=RNone::<()>.unwrap(); /// ``` @@ -201,7 +198,7 @@ impl ROption { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(10) .unwrap_or(99),10); /// assert_eq!(RNone::.unwrap_or(99),99); @@ -220,16 +217,16 @@ impl ROption { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(10) .unwrap_or_default(),10); /// assert_eq!(RNone::.unwrap_or_default(),0); /// /// ``` #[inline] - pub fn unwrap_or_default(self) -> T - where - T:Default + pub fn unwrap_or_default(self) -> T + where + T: Default, { match self { RSome(x) => x, @@ -243,7 +240,7 @@ impl ROption { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(10) .unwrap_or_else(|| 77 ),10); /// assert_eq!(RNone::.unwrap_or_else(|| 77 ),77); @@ -266,7 +263,7 @@ impl ROption { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(10) .map(|x| x*2 ),RSome(20)); /// assert_eq!(RNone::.map(|x| x*2 ),RNone); @@ -289,7 +286,7 @@ impl ROption { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(10) .map_or(77,|x| x*2 ),20); /// assert_eq!(RNone::.map_or(77,|x| x*2 ),77); @@ -312,7 +309,7 @@ impl ROption { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(10) .map_or_else(||77,|x| x*2 ),20); /// assert_eq!(RNone::.map_or_else(||77,|x| x*2 ),77); @@ -335,7 +332,7 @@ impl ROption { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(10).filter(|x| (x%2)==0 ),RSome(10)); /// assert_eq!(RSome(10).filter(|x| (x%2)==1 ),RNone ); @@ -360,7 +357,7 @@ impl ROption { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(10).and(RSome(20)),RSome(20)); /// assert_eq!(RSome(10).and(RNone ),RNone); @@ -376,13 +373,13 @@ impl ROption { } } - /// Returns `self` if it is `RNone`, + /// Returns `self` if it is `RNone`, /// otherwise returns the result of calling `f` with the value in `RSome`. /// /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(10).and_then(|x|RSome(x * 2)),RSome(20)); /// assert_eq!(RSome(10).and_then(|_|RNone::),RNone); @@ -406,7 +403,7 @@ impl ROption { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(10).or(RSome(20)),RSome(10)); /// assert_eq!(RSome(10).or(RNone ),RSome(10)); @@ -422,13 +419,13 @@ impl ROption { } } - /// Returns `self` if it contains a value, + /// Returns `self` if it contains a value, /// otherwise calls `optb` and returns the value it evaluates to. /// /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(10).or_else(|| RSome(20) ),RSome(10)); /// assert_eq!(RSome(10).or_else(|| RNone ),RSome(10)); @@ -453,7 +450,7 @@ impl ROption { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(10).xor(RSome(20)),RNone ); /// assert_eq!(RSome(10).xor(RNone ),RSome(10)); @@ -476,7 +473,7 @@ impl ROption { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(10).get_or_insert(40),&mut 10); /// assert_eq!(RSome(20).get_or_insert(55),&mut 20); @@ -501,7 +498,7 @@ impl ROption { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(10).get_or_insert_with(||40),&mut 10); /// assert_eq!(RSome(20).get_or_insert_with(||55),&mut 20); @@ -528,7 +525,7 @@ impl ROption { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// let mut opt0=RSome(10); /// assert_eq!(opt0.take(),RSome(10)); @@ -553,7 +550,7 @@ impl ROption { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// let mut opt0=RSome(10); /// assert_eq!(opt0.replace(55),RSome(10)); @@ -573,24 +570,23 @@ impl ROption { mem::replace(self, RSome(value)) } } - -impl ROption<&T>{ +impl ROption<&T> { /// Converts an `ROption<&T>` to an `ROption` by cloning its contents. /// /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(&vec![()]).cloned(),RSome(vec![()])); /// assert_eq!(RNone::<&Vec<()>>.cloned(),RNone ); /// /// ``` #[inline] - pub fn cloned(self)->ROption - where - T:Clone + pub fn cloned(self) -> ROption + where + T: Clone, { match self { RSome(expr) => RSome(expr.clone()), @@ -603,16 +599,16 @@ impl ROption<&T>{ /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(&7).copied(),RSome(7)); /// assert_eq!(RNone::<&u32>.copied(),RNone); /// /// ``` #[inline] - pub fn copied(self)->ROption - where - T:Copy + pub fn copied(self) -> ROption + where + T: Copy, { match self { RSome(expr) => RSome(*expr), @@ -621,22 +617,22 @@ impl ROption<&T>{ } } -impl ROption<&mut T>{ +impl ROption<&mut T> { /// Converts an `ROption<&mut T>` to a `ROption` by cloning its contents. /// /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(&mut vec![()]).cloned(),RSome(vec![()])); /// assert_eq!(RNone::<&mut Vec<()>>.cloned(),RNone ); /// /// ``` #[inline] - pub fn cloned(self)->ROption - where - T:Clone + pub fn cloned(self) -> ROption + where + T: Clone, { match self { RSome(expr) => RSome(expr.clone()), @@ -649,16 +645,16 @@ impl ROption<&mut T>{ /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(&mut 7).copied(),RSome(7)); /// assert_eq!(RNone::<&mut u32>.copied(),RNone ); /// /// ``` #[inline] - pub fn copied(self)->ROption - where - T:Copy + pub fn copied(self) -> ROption + where + T: Copy, { match self { RSome(expr) => RSome(*expr), @@ -667,15 +663,13 @@ impl ROption<&mut T>{ } } - /// The default value is `RNone`. impl Default for ROption { - fn default()->Self{ + fn default() -> Self { RNone } } - impl_from_rust_repr! { impl[T] From> for ROption { fn(this){ @@ -724,19 +718,17 @@ where ///////////////////////////////////////////////////////////////////// - -#[cfg(all(test,not(feature="only_new_tests")))] +#[cfg(all(test, not(feature = "only_new_tests")))] // #[cfg(test)] -mod test{ +mod test { use super::*; #[test] - fn from_into(){ - assert_eq!(ROption::from(Some(10)),RSome(10)); - assert_eq!(ROption::from(None::),RNone ); + fn from_into() { + assert_eq!(ROption::from(Some(10)), RSome(10)); + assert_eq!(ROption::from(None::), RNone); - assert_eq!(RSome(10).into_option(),Some(10)); - assert_eq!(RNone::.into_option(),None ); + assert_eq!(RSome(10).into_option(), Some(10)); + assert_eq!(RNone::.into_option(), None); } - } diff --git a/abi_stable/src/std_types/range.rs b/abi_stable/src/std_types/range.rs index 48f5290f..ba410b22 100644 --- a/abi_stable/src/std_types/range.rs +++ b/abi_stable/src/std_types/range.rs @@ -6,28 +6,25 @@ use std::ops::{Range, RangeFrom, RangeInclusive, RangeTo, RangeToInclusive}; //////////////////////////////////////////////////////////////// - macro_rules! impl_into_iterator { - ( $from:ident,$to:ident ) => ( - impl IntoIterator for $from - where - $to:Iterator + ( $from:ident,$to:ident ) => { + impl IntoIterator for $from + where + $to: Iterator, { - type IntoIter=$to; - type Item=T; + type IntoIter = $to; + type Item = T; #[inline] - fn into_iter(self)->$to{ + fn into_iter(self) -> $to { self.into() } } - ) + }; } - //////////////////////////////////////////////////////////////// - /// Ffi-safe equivalent of `::std::ops::Range` #[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash, Deserialize, Serialize)] #[repr(C)] @@ -68,13 +65,10 @@ impl_into_rust_repr! { } } - -impl_into_iterator!{ RRange,Range } - +impl_into_iterator! { RRange,Range } //////////////////////////////////////////////////////////////// - /// Ffi-safe equivalent of `::std::ops::RangeInclusive` #[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash, Deserialize, Serialize)] #[repr(C)] @@ -101,9 +95,7 @@ impl_into_rust_repr! { } } - -impl_into_iterator!{ RRangeInclusive,RangeInclusive } - +impl_into_iterator! { RRangeInclusive,RangeInclusive } //////////////////////////////////////////////////////////////// @@ -131,13 +123,10 @@ impl_into_rust_repr! { } } - -impl_into_iterator!{ RRangeFrom,RangeFrom } - +impl_into_iterator! { RRangeFrom,RangeFrom } //////////////////////////////////////////////////////////////// - /// Ffi-safe equivalent of `::std::ops::RangeTo` #[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash, Deserialize, Serialize)] #[repr(C)] @@ -162,8 +151,6 @@ impl_into_rust_repr! { } } - - //////////////////////////////////////////////////////////////// /// Ffi-safe equivalent of `::std::ops::RangeToInclusive` @@ -190,8 +177,4 @@ impl_into_rust_repr! { } } - - - - //////////////////////////////////////////////////////////////// diff --git a/abi_stable/src/std_types/result.rs b/abi_stable/src/std_types/result.rs index 32535031..604d98a9 100644 --- a/abi_stable/src/std_types/result.rs +++ b/abi_stable/src/std_types/result.rs @@ -6,9 +6,7 @@ use std::fmt::Debug; use core_extensions::matches; -use crate::std_types::{ROption,RSome,RNone}; - - +use crate::std_types::{RNone, ROption, RSome}; /// Ffi-safe equivalent of `Result`. #[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash, Deserialize, Serialize)] @@ -29,7 +27,7 @@ impl RResult { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(ROk::(10).as_ref(),ROk(&10)); /// assert_eq!(RErr::(5).as_ref(),RErr(&5)); @@ -48,7 +46,7 @@ impl RResult { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(ROk::(10).as_mut(),ROk(&mut 10)); /// assert_eq!(RErr::(5).as_mut(),RErr(&mut 5)); @@ -67,15 +65,15 @@ impl RResult { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(ROk::(10).is_rok(),true); /// assert_eq!(RErr::(5).is_rok(),false); /// /// ``` #[inline] - pub fn is_rok(&self)->bool{ - matches!{self, ROk{..}} + pub fn is_rok(&self) -> bool { + matches! {self, ROk{..}} } /// Returns whether `self` is an `ROk` @@ -83,15 +81,15 @@ impl RResult { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(ROk::(10).is_ok(),true); /// assert_eq!(RErr::(5).is_ok(),false); /// /// ``` #[inline] - pub fn is_ok(&self)->bool{ - matches!{self, ROk{..}} + pub fn is_ok(&self) -> bool { + matches! {self, ROk{..}} } /// Returns whether `self` is an `RErr` @@ -99,15 +97,15 @@ impl RResult { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(ROk::(10).is_rerr(),false); /// assert_eq!(RErr::(5).is_rerr(),true); /// /// ``` #[inline] - pub fn is_rerr(&self)->bool{ - matches!{self, RErr{..}} + pub fn is_rerr(&self) -> bool { + matches! {self, RErr{..}} } /// Returns whether `self` is an `RErr` @@ -115,24 +113,23 @@ impl RResult { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(ROk::(10).is_err(),false); /// assert_eq!(RErr::(5).is_err(),true); /// /// ``` #[inline] - pub fn is_err(&self)->bool{ - matches!{self, RErr{..}} + pub fn is_err(&self) -> bool { + matches! {self, RErr{..}} } - /// Converts from `RResult` to `Result`. /// /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(ROk::(10).into_result(),Ok (10)); /// assert_eq!(RErr::(5).into_result(),Err(5)); @@ -143,13 +140,13 @@ impl RResult { self.into() } - /// Converts the `RResult` to a `RResult` by transforming the value in + /// Converts the `RResult` to a `RResult` by transforming the value in /// `ROk` using the `op` closure. /// /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(ROk::(10).map(|x| x*3 ),ROk(30)); /// assert_eq!(RErr::(5).map(|x| x/2 ),RErr(5)); @@ -166,13 +163,13 @@ impl RResult { } } - /// Converts the `RResult` to a `RResult` by + /// Converts the `RResult` to a `RResult` by /// transforming the value in `RErr` using the `op` closure. /// /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(ROk::(10).map_err(|x| x*3 ),ROk(10)); /// assert_eq!(RErr::(5).map_err(|x| x/2 ),RErr(2)); @@ -189,14 +186,14 @@ impl RResult { } } - /// Converts the `RResult` to a `U` by + /// Converts the `RResult` to a `U` by /// transforming the value in `ROk` using the `with_ok` closure, /// otherwise transforming the value in RErr using the `with_err` closure, /// /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(ROk::(10).map_or_else(|_|77 ,|x| x*3 ),30); /// assert_eq!(RErr::(5).map_or_else(|e|e*4,|x| x/2 ),20); @@ -217,7 +214,7 @@ impl RResult { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!( /// ROk::(10).and_then(|x| ROk ::(x*3) ), @@ -254,7 +251,7 @@ impl RResult { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(ROk::(10).or_else(|e| ROk ::(e*3) ) ,ROk(10)); /// assert_eq!(ROk::(10).or_else(|e| RErr::(e*3)) ,ROk(10)); @@ -283,7 +280,7 @@ impl RResult { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!( ROk::<_,()>(500).unwrap(), 500 ); /// @@ -291,13 +288,13 @@ impl RResult { /// /// This one panics: /// ```should_panic - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// let _=RErr::<(),_>("Oh noooo!").unwrap(); /// ``` - pub fn unwrap(self) -> T - where - E:Debug + pub fn unwrap(self) -> T + where + E: Debug, { self.into_result().unwrap() } @@ -313,7 +310,7 @@ impl RResult { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!( ROk::<_,()>(500).expect("Are you OK?"), 500 ); /// @@ -321,13 +318,13 @@ impl RResult { /// /// This one panics: /// ```should_panic - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// let _=RErr::<(),_>(()).expect("This can't be!"); /// ``` pub fn expect(self, message: &str) -> T - where - E:Debug + where + E: Debug, { self.into_result().expect(message) } @@ -342,7 +339,7 @@ impl RResult { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!( RErr::<(),u32>(0xB007).unwrap_err(), 0xB007 ); /// @@ -350,13 +347,13 @@ impl RResult { /// /// This one panics: /// ```should_panic - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// let _=ROk::<(),()>(()).unwrap_err(); /// ``` pub fn unwrap_err(self) -> E - where - T:Debug + where + T: Debug, { self.into_result().unwrap_err() } @@ -372,7 +369,7 @@ impl RResult { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!( RErr::<(),u32>(0xB001).expect_err("Murphy's law"), 0xB001 ); /// @@ -380,13 +377,13 @@ impl RResult { /// /// This one panics: /// ```should_panic - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// let _=ROk::<(),()>(()).expect_err("Everything is Ok"); /// ``` pub fn expect_err(self, message: &str) -> E - where - T:Debug + where + T: Debug, { self.into_result().expect_err(message) } @@ -396,7 +393,7 @@ impl RResult { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(ROk::(10).unwrap_or(0xEEEE),10); /// assert_eq!(RErr::(5).unwrap_or(0b101010),0b101010); @@ -416,7 +413,7 @@ impl RResult { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(ROk::(10).unwrap_or_else(|e| e*3 ),10); /// assert_eq!(RErr::(5).unwrap_or_else(|e| e/2 ),2); @@ -439,7 +436,7 @@ impl RResult { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(ROk::(10).unwrap_or_default(),10); /// assert_eq!(RErr::(5).unwrap_or_default(),0); @@ -448,7 +445,7 @@ impl RResult { #[inline] pub fn unwrap_or_default(self) -> T where - T:Default + T: Default, { match self { ROk(t) => t, @@ -462,37 +459,36 @@ impl RResult { /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(ROk::(10).ok(),RSome(10)); /// assert_eq!(RErr::(5).ok(),RNone); /// /// ``` #[inline] - pub fn ok(self)->ROption{ + pub fn ok(self) -> ROption { match self { - ROk(t) => RSome(t), + ROk(t) => RSome(t), RErr(_) => RNone, } } - /// Converts from `RResult` to `ROption`, /// `ROk` maps to `RNone`,`RErr` maps to `RSome`. /// /// # Example /// /// ``` - /// # use abi_stable::std_types::*; + /// # use abi_stable::std_types::*; /// /// assert_eq!(ROk::(10).err(),RNone); /// assert_eq!(RErr::(5).err(),RSome(5)); /// /// ``` #[inline] - pub fn err(self)->ROption{ + pub fn err(self) -> ROption { match self { - ROk(_) => RNone, + ROk(_) => RNone, RErr(v) => RSome(v), } } @@ -520,24 +516,19 @@ impl_into_rust_repr! { } } - - ///////////////////////////////////////////////////////////////////// - //#[cfg(test)] -#[cfg(all(test,not(feature="only_new_tests")))] -mod test{ +#[cfg(all(test, not(feature = "only_new_tests")))] +mod test { use super::*; - #[test] - fn from_into(){ - assert_eq!(RResult::from(Ok ::(10)),ROk(10)); - assert_eq!(RResult::from(Err::(4)),RErr(4)); + fn from_into() { + assert_eq!(RResult::from(Ok::(10)), ROk(10)); + assert_eq!(RResult::from(Err::(4)), RErr(4)); - assert_eq!(ROk::(10).into_result(),Ok(10)); - assert_eq!(RErr::(4).into_result(),Err(4)); + assert_eq!(ROk::(10).into_result(), Ok(10)); + assert_eq!(RErr::(4).into_result(), Err(4)); } - } diff --git a/abi_stable/src/std_types/slice_mut.rs b/abi_stable/src/std_types/slice_mut.rs index e954d1b4..893d82c2 100644 --- a/abi_stable/src/std_types/slice_mut.rs +++ b/abi_stable/src/std_types/slice_mut.rs @@ -3,7 +3,7 @@ Contains the ffi-safe equivalent of `&'a mut [T]`. */ use std::{ - borrow::{Borrow,BorrowMut}, + borrow::{Borrow, BorrowMut}, io::{self, Write}, marker::PhantomData, mem, @@ -20,92 +20,92 @@ use crate::std_types::{RSlice, RVec}; mod privacy { use super::*; -/** -Ffi-safe equivalent of `&'a mut [T]` + /** + Ffi-safe equivalent of `&'a mut [T]` -As of the writing this documentation the abi stability of `&mut [T]` is -not yet guaranteed. + As of the writing this documentation the abi stability of `&mut [T]` is + not yet guaranteed. -# Lifetime problems + # Lifetime problems -Because `RSliceMut` dereferences into a mutable slice,you can call slice methods on it. + Because `RSliceMut` dereferences into a mutable slice,you can call slice methods on it. -If you call a slice method that returns a borrow into the slice, -it will have the lifetime of the `let slice: RSliceMut<'a,[T]>` variable instead of the `'a` -lifetime that it's parameterized over. + If you call a slice method that returns a borrow into the slice, + it will have the lifetime of the `let slice: RSliceMut<'a,[T]>` variable instead of the `'a` + lifetime that it's parameterized over. -To get a slice with the same lifetime as an `RSliceMut`, -one must use one of the `RSliceMut::{into_slice,into_mut_slice}` methods. + To get a slice with the same lifetime as an `RSliceMut`, + one must use one of the `RSliceMut::{into_slice,into_mut_slice}` methods. -Example of what would not work: + Example of what would not work: -```compile_fail -use abi_stable::std_types::RSliceMut; + ```compile_fail + use abi_stable::std_types::RSliceMut; -fn into_slice<'a,T>(slic:RSliceMut<'a,T>)->&'a [T] { - &*slic -} + fn into_slice<'a,T>(slic:RSliceMut<'a,T>)->&'a [T] { + &*slic + } -fn into_mut_slice<'a,T>(slic:RSliceMut<'a,T>)->&'a mut [T] { - &mut *slic -} -``` + fn into_mut_slice<'a,T>(slic:RSliceMut<'a,T>)->&'a mut [T] { + &mut *slic + } + ``` -Example of what would work: + Example of what would work: -``` -use abi_stable::std_types::RSliceMut; + ``` + use abi_stable::std_types::RSliceMut; -fn into_slice<'a,T>(slic:RSliceMut<'a,T>)->&'a [T] { - slic.into_slice() -} + fn into_slice<'a,T>(slic:RSliceMut<'a,T>)->&'a [T] { + slic.into_slice() + } -fn into_mut_slice<'a,T>(slic:RSliceMut<'a,T>)->&'a mut [T] { - slic.into_mut_slice() -} -``` + fn into_mut_slice<'a,T>(slic:RSliceMut<'a,T>)->&'a mut [T] { + slic.into_mut_slice() + } + ``` -# Example + # Example -Defining an extern fn that returns a mutable reference to -the first element that compares equal to a parameter. + Defining an extern fn that returns a mutable reference to + the first element that compares equal to a parameter. -``` -use abi_stable::{ - std_types::RSliceMut, - sabi_extern_fn, -}; + ``` + use abi_stable::{ + std_types::RSliceMut, + sabi_extern_fn, + }; -#[sabi_extern_fn] -pub fn find_first_mut<'a,T>(slice_:RSliceMut<'a,T>,element:&T)->Option<&'a mut T> -where - T:std::cmp::PartialEq -{ - slice_.iter() - .position(|x| x==element ) - .map(|i| &mut slice_.into_mut_slice()[i] ) -} + #[sabi_extern_fn] + pub fn find_first_mut<'a,T>(slice_:RSliceMut<'a,T>,element:&T)->Option<&'a mut T> + where + T:std::cmp::PartialEq + { + slice_.iter() + .position(|x| x==element ) + .map(|i| &mut slice_.into_mut_slice()[i] ) + } -``` + ``` -*/ + */ #[repr(C)] #[derive(StableAbi)] #[sabi(bound = "T:'a")] pub struct RSliceMut<'a, T> { data: *mut T, length: usize, - _marker: PhantomData>, + _marker: PhantomData>, } /// Used as a workaround to make `from_raw_parts_mut` a const fn. #[repr(C)] #[derive(StableAbi)] #[sabi(bound = "T:'a")] - struct MutWorkaround<'a,T>(&'a mut T); + struct MutWorkaround<'a, T>(&'a mut T); impl_from_rust_repr! { impl['a, T] From<&'a mut [T]> for RSliceMut<'a, T> { @@ -126,21 +126,20 @@ where } /// Gets a raw pointer to the start of the slice. - pub const fn as_ptr(&self) -> *const T{ + pub const fn as_ptr(&self) -> *const T { self.data } - + /// Gets a mutable raw pointer to the start of the slice. - pub fn as_mut_ptr(&mut self) -> *mut T{ + pub fn as_mut_ptr(&mut self) -> *mut T { self.data } - + /// Gets a mutable raw pointer to the start of the slice. - pub const fn into_mut_ptr(self) -> *mut T{ + pub const fn into_mut_ptr(self) -> *mut T { self.data } - /// The length (in elements) of this slice. /// /// # Example @@ -151,14 +150,14 @@ where /// assert_eq!(RSliceMut::::from_mut_slice(&mut[]).len(), 0); /// assert_eq!(RSliceMut::from_mut_slice(&mut[0]).len(), 1); /// assert_eq!(RSliceMut::from_mut_slice(&mut[0,1]).len(), 2); - /// + /// /// /// ``` #[inline(always)] pub const fn len(&self) -> usize { self.length } - + /// Whether this slice is empty. /// /// # Example @@ -173,7 +172,7 @@ where /// ``` #[inline] pub const fn is_empty(&self) -> bool { - self.length==0 + self.length == 0 } /// Constructs an `RSliceMut<'a,T>` from a pointer to the first element, @@ -237,13 +236,11 @@ impl<'a, T> RSliceMut<'a, T> { /// assert_eq!(RSliceMut::from_mut(&mut 0), RSliceMut::from_mut_slice(&mut [0]) ); /// assert_eq!(RSliceMut::from_mut(&mut 1), RSliceMut::from_mut_slice(&mut [1]) ); /// assert_eq!(RSliceMut::from_mut(&mut 2), RSliceMut::from_mut_slice(&mut [2]) ); - /// + /// /// /// ``` - pub fn from_mut(ref_:&'a mut T)->Self{ - unsafe{ - Self::from_raw_parts_mut(ref_,1) - } + pub fn from_mut(ref_: &'a mut T) -> Self { + unsafe { Self::from_raw_parts_mut(ref_, 1) } } /// Converts a `&'a mut [T]` to a `RSliceMut<'a,T>`. @@ -258,10 +255,10 @@ impl<'a, T> RSliceMut<'a, T> { /// assert_eq!(RSliceMut::::from_mut_slice(&mut[]).as_mut_slice(), empty); /// assert_eq!(RSliceMut::from_mut_slice(&mut[0]).as_mut_slice() , &mut [0][..]); /// assert_eq!(RSliceMut::from_mut_slice(&mut[0,1]).as_mut_slice() , &mut [0,1][..]); - /// + /// /// ``` #[inline] - pub fn from_mut_slice(slic:&'a mut [T])->Self{ + pub fn from_mut_slice(slic: &'a mut [T]) -> Self { slic.into() } @@ -366,7 +363,7 @@ impl<'a, T> RSliceMut<'a, T> { /// Creates an `&'a [T]` with access to all the elements of this slice. /// - /// This is different to `as_slice` in that the returned lifetime of + /// This is different to `as_slice` in that the returned lifetime of /// this function is larger. /// /// # Example @@ -400,7 +397,7 @@ impl<'a, T> RSliceMut<'a, T> { /// Creates an `RSlice<'a, T>` with access to all the elements of this slice. /// - /// This is different to `as_rslice` in that the returned lifetime of + /// This is different to `as_rslice` in that the returned lifetime of /// this function is larger. /// /// # Example @@ -417,7 +414,7 @@ impl<'a, T> RSliceMut<'a, T> { pub fn into_rslice(self) -> RSlice<'a, T> { self.into_slice().into() } - + /// Creates a `&'_ mut [T]` with access to all the elements of this slice. /// /// # Example @@ -434,7 +431,7 @@ impl<'a, T> RSliceMut<'a, T> { /// Creates a `&'a mut [T]` with access to all the elements of this slice. /// - /// This is different to `as_mut_slice` in that the returned lifetime of + /// This is different to `as_mut_slice` in that the returned lifetime of /// this function is larger. /// /// # Example @@ -469,7 +466,7 @@ impl<'a, T> IntoIterator for RSliceMut<'a, T> { } } -slice_like_impl_cmp_traits!{ +slice_like_impl_cmp_traits! { impl[] RSliceMut<'_, T>, where[]; Vec, @@ -479,13 +476,13 @@ slice_like_impl_cmp_traits!{ } #[cfg(feature = "const_params")] -slice_like_impl_cmp_traits!{ +slice_like_impl_cmp_traits! { impl[const N: usize] RSliceMut<'_, T>, where[]; [U; N], } -slice_like_impl_cmp_traits!{ +slice_like_impl_cmp_traits! { impl[] RSliceMut<'_, T>, where[T: Clone, U: Clone]; std::borrow::Cow<'_, [U]>, @@ -522,35 +519,32 @@ impl<'a, T> Into<&'a [T]> for RSliceMut<'a, T> { } } - //////////////////// - -impl<'a,T:'a> Borrow<[T]> for RSliceMut<'a,T>{ - fn borrow(&self)->&[T]{ +impl<'a, T: 'a> Borrow<[T]> for RSliceMut<'a, T> { + fn borrow(&self) -> &[T] { self } } -impl<'a,T:'a> BorrowMut<[T]> for RSliceMut<'a,T>{ - fn borrow_mut(&mut self)->&mut [T]{ +impl<'a, T: 'a> BorrowMut<[T]> for RSliceMut<'a, T> { + fn borrow_mut(&mut self) -> &mut [T] { self } } -impl<'a,T:'a> AsRef<[T]> for RSliceMut<'a,T>{ - fn as_ref(&self)->&[T]{ +impl<'a, T: 'a> AsRef<[T]> for RSliceMut<'a, T> { + fn as_ref(&self) -> &[T] { self } } -impl<'a,T:'a> AsMut<[T]> for RSliceMut<'a,T>{ - fn as_mut(&mut self)->&mut [T]{ +impl<'a, T: 'a> AsMut<[T]> for RSliceMut<'a, T> { + fn as_mut(&mut self) -> &mut [T] { self } } - //////////////////////////// impl<'a, T> Serialize for RSliceMut<'a, T> where @@ -603,7 +597,7 @@ shared_impls! { //////////////////////////////////////////////////////////////////////////////// //#[cfg(test)] -#[cfg(all(test,not(feature="only_new_tests")))] +#[cfg(all(test, not(feature = "only_new_tests")))] mod test { use super::*; diff --git a/abi_stable/src/std_types/slices.rs b/abi_stable/src/std_types/slices.rs index fd9ecb3b..145e5e9d 100644 --- a/abi_stable/src/std_types/slices.rs +++ b/abi_stable/src/std_types/slices.rs @@ -14,78 +14,78 @@ use core_extensions::SelfOps; use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use crate::std_types::{RVec}; +use crate::std_types::RVec; mod private { use super::*; -/** -Ffi-safe equivalent of `&'a [T]` + /** + Ffi-safe equivalent of `&'a [T]` -As of the writing this documentation the abi stability of `&[T]` is -not yet guaranteed. + As of the writing this documentation the abi stability of `&[T]` is + not yet guaranteed. -# Lifetime problems + # Lifetime problems -Because `RSlice` dereferences into a slice,you can call slice methods on it. + Because `RSlice` dereferences into a slice,you can call slice methods on it. -If you call a slice method that returns a borrow into the slice, -it will have the lifetime of the `let slice: RSlice<'a,[T]>` variable instead of the `'a` -lifetime that it's parameterized over. + If you call a slice method that returns a borrow into the slice, + it will have the lifetime of the `let slice: RSlice<'a,[T]>` variable instead of the `'a` + lifetime that it's parameterized over. -To get a slice with the same lifetime as an `RSlice`, -one must use the `RSlice::as_slice` method. + To get a slice with the same lifetime as an `RSlice`, + one must use the `RSlice::as_slice` method. -Example of what would not work: + Example of what would not work: -```compile_fail -use abi_stable::std_types::RSlice; + ```compile_fail + use abi_stable::std_types::RSlice; -fn into_slice<'a,T>(slic:RSlice<'a,T>)->&'a [T] { - &*slic -} -``` + fn into_slice<'a,T>(slic:RSlice<'a,T>)->&'a [T] { + &*slic + } + ``` -Example of what would work: + Example of what would work: -``` -use abi_stable::std_types::RSlice; + ``` + use abi_stable::std_types::RSlice; -fn into_slice<'a,T>(slic:RSlice<'a,T>)->&'a [T] { - slic.as_slice() -} -``` + fn into_slice<'a,T>(slic:RSlice<'a,T>)->&'a [T] { + slic.as_slice() + } + ``` -# Example + # Example -Defining an extern fn that returns a reference to -the first element that compares equal to a parameter. + Defining an extern fn that returns a reference to + the first element that compares equal to a parameter. -``` -use abi_stable::{ - std_types::RSlice, - sabi_extern_fn, -}; + ``` + use abi_stable::{ + std_types::RSlice, + sabi_extern_fn, + }; -#[sabi_extern_fn] -pub fn find_first_mut<'a,T>(slice_:RSlice<'a,T>,element:&T)->Option<&'a T> -where - T:std::cmp::PartialEq -{ - slice_.iter() - .position(|x| x==element ) - .map(|i| &slice_.as_slice()[i] ) -} + #[sabi_extern_fn] + pub fn find_first_mut<'a,T>(slice_:RSlice<'a,T>,element:&T)->Option<&'a T> + where + T:std::cmp::PartialEq + { + slice_.iter() + .position(|x| x==element ) + .map(|i| &slice_.as_slice()[i] ) + } -``` + ``` -*/ + */ #[repr(C)] #[derive(StableAbi)] #[sabi(bound = "T:'a")] @@ -156,10 +156,7 @@ where } #[doc(hidden)] - pub const unsafe fn from_raw_parts_with_lifetime( - slice:&'a [T], - len: usize, - ) -> Self { + pub const unsafe fn from_raw_parts_with_lifetime(slice: &'a [T], len: usize) -> Self { Self { data: slice.as_ptr(), length: len, @@ -167,7 +164,7 @@ where } } } - + impl<'a, T> RSlice<'a, T> { /// Creates an `&'a [T]` with access to all the elements of this slice. /// @@ -184,10 +181,10 @@ where } /// Gets a raw pointer to the start of the slice. - pub const fn as_ptr(&self) -> *const T{ + pub const fn as_ptr(&self) -> *const T { self.data } - + /// The length (in elements) of this slice. /// /// # Example @@ -204,7 +201,7 @@ where pub const fn len(&self) -> usize { self.length } - + /// Whether this slice is empty. /// /// # Example @@ -219,7 +216,7 @@ where /// ``` #[inline] pub const fn is_empty(&self) -> bool { - self.length==0 + self.length == 0 } } } @@ -244,35 +241,32 @@ impl<'a, T> RSlice<'a, T> { /// assert_eq!(RSlice::from_ref(&0), RSlice::from_slice(&[0]) ); /// assert_eq!(RSlice::from_ref(&1), RSlice::from_slice(&[1]) ); /// assert_eq!(RSlice::from_ref(&2), RSlice::from_slice(&[2]) ); - /// + /// /// /// ``` - pub const fn from_ref(ref_:&'a T)->Self{ - unsafe{ - Self::from_raw_parts(ref_,1) - } - } + pub const fn from_ref(ref_: &'a T) -> Self { + unsafe { Self::from_raw_parts(ref_, 1) } + } /// Converts a `&[T]` to an `RSlice<'_,T>`. - /// + /// /// # Example - /// + /// /// ``` /// use abi_stable::std_types::RSlice; - /// + /// /// let empty:&[u8]=&[]; - /// + /// /// assert_eq!(RSlice::::from_slice(&[]).as_slice(), empty); /// assert_eq!(RSlice::from_slice(&[0]).as_slice() , &[0][..]); /// assert_eq!(RSlice::from_slice(&[0,1]).as_slice() , &[0,1][..]); - /// + /// /// ``` #[inline] - pub const fn from_slice(slic:&'a [T])->Self{ - unsafe{ RSlice::from_raw_parts(slic.as_ptr(),slic.len()) } + pub const fn from_slice(slic: &'a [T]) -> Self { + unsafe { RSlice::from_raw_parts(slic.as_ptr(), slic.len()) } } - /// Creates an `RSlice<'a,T>` with access to the `range` range of elements. /// /// This is an inherent method instead of an implementation of the @@ -324,19 +318,16 @@ impl<'a, T> RSlice<'a, T> { /// /// # Safety /// - /// This has the same safety requirements as calling [`std::mem::transmute`] to + /// This has the same safety requirements as calling [`std::mem::transmute`] to /// transmute a `&'a [T]` to a `&'a [U]`. /// /// [`std::mem::transmute`]: https://doc.rust-lang.org/std/mem/fn.transmute.html - pub const unsafe fn transmute(self)->RSlice<'a,U> + pub const unsafe fn transmute(self) -> RSlice<'a, U> where - U:'a + U: 'a, { - let len=self.len(); - RSlice::from_raw_parts( - self.as_ptr() as *const T as *const U, - len, - ) + let len = self.len(); + RSlice::from_raw_parts(self.as_ptr() as *const T as *const U, len) } } @@ -367,7 +358,7 @@ impl<'a, T> IntoIterator for RSlice<'a, T> { } } -slice_like_impl_cmp_traits!{ +slice_like_impl_cmp_traits! { impl[] RSlice<'_, T>, where[]; Vec, @@ -376,13 +367,13 @@ slice_like_impl_cmp_traits!{ } #[cfg(feature = "const_params")] -slice_like_impl_cmp_traits!{ +slice_like_impl_cmp_traits! { impl[const N: usize] RSlice<'_, T>, where[]; [U; N], } -slice_like_impl_cmp_traits!{ +slice_like_impl_cmp_traits! { impl[] RSlice<'_, T>, where[T: Clone, U: Clone]; std::borrow::Cow<'_, [U]>, @@ -407,21 +398,18 @@ impl_into_rust_repr! { //////////////////// - -impl<'a,T:'a> Borrow<[T]> for RSlice<'a,T>{ - fn borrow(&self)->&[T]{ +impl<'a, T: 'a> Borrow<[T]> for RSlice<'a, T> { + fn borrow(&self) -> &[T] { self } } - -impl<'a,T:'a> AsRef<[T]> for RSlice<'a,T>{ - fn as_ref(&self)->&[T]{ +impl<'a, T: 'a> AsRef<[T]> for RSlice<'a, T> { + fn as_ref(&self) -> &[T] { self } } - /////////////////// impl<'de, T> Deserialize<'de> for RSlice<'de, T> @@ -502,7 +490,7 @@ shared_impls! { //////////////////////////////////////////////////////////////////////////////// //#[cfg(test)] -#[cfg(all(test,not(feature="only_new_tests")))] +#[cfg(all(test, not(feature = "only_new_tests")))] mod test { use super::*; diff --git a/abi_stable/src/std_types/std_error.rs b/abi_stable/src/std_types/std_error.rs index 03a376bf..80256edf 100644 --- a/abi_stable/src/std_types/std_error.rs +++ b/abi_stable/src/std_types/std_error.rs @@ -13,13 +13,13 @@ use crate::{ c_functions::{adapt_std_fmt, debug_impl, display_impl}, FormattingMode, }, - marker_type::{SyncSend, UnsyncUnsend,UnsyncSend,ErasedObject}, - pointer_trait::{AsPtr, AsMutPtr}, - prefix_type::{PrefixTypeTrait,WithMetadata}, + marker_type::{ErasedObject, SyncSend, UnsyncSend, UnsyncUnsend}, + pointer_trait::{AsMutPtr, AsPtr}, + prefix_type::{PrefixTypeTrait, WithMetadata}, sabi_types::RRef, std_types::{ + utypeid::{new_utypeid, UTypeId}, RBox, ROption, RResult, RStr, RString, - utypeid::{UTypeId,new_utypeid} }, utils::transmute_reference, }; @@ -29,7 +29,7 @@ use crate::{ mod test; /** -Ffi-safe version of `Box` +Ffi-safe version of `Box` whose `Send + Sync`ness is determined by the `M` type parameter. # Examples @@ -79,7 +79,7 @@ use abi_stable::std_types::{RBox,RBoxError}; let dyn_err:Box= Box::new(parse_err.clone()); let err=RBoxError::from_box(dyn_err); - + assert_eq!( err.downcast::().unwrap(), RBox::new(parse_err) ); } @@ -87,7 +87,7 @@ use abi_stable::std_types::{RBox,RBoxError}; { let parse_err="".parse::().unwrap_err(); let err=RBoxError::new(parse_err.clone()); - + assert_eq!( err.downcast::().unwrap(), RBox::new(parse_err) ); } @@ -96,7 +96,7 @@ use abi_stable::std_types::{RBox,RBoxError}; { let parse_err="".parse::().unwrap_err(); let err=RBoxError::new(parse_err); - + assert!( err.downcast::().is_err() ); } @@ -120,7 +120,7 @@ use abi_stable::std_types::{RBox,UnsyncRBoxError}; let dyn_err:Box= Box::new(int_err.clone()); let err=UnsyncRBoxError::from_box(dyn_err); - + assert_eq!( err.downcast_ref::().unwrap(), &int_err ); } @@ -128,7 +128,7 @@ use abi_stable::std_types::{RBox,UnsyncRBoxError}; { let utf8_err=std::str::from_utf8(&[255]).unwrap_err(); let err=UnsyncRBoxError::new(utf8_err.clone()); - + assert_eq!( err.downcast_ref::().unwrap(), &utf8_err ); } @@ -137,7 +137,7 @@ use abi_stable::std_types::{RBox,UnsyncRBoxError}; { let utf8_err=std::str::from_utf8(&[255]).unwrap_err(); let err=UnsyncRBoxError::new(utf8_err); - + assert!( err.downcast_ref::().is_none() ); } @@ -148,7 +148,7 @@ use abi_stable::std_types::{RBox,UnsyncRBoxError}; ``` use std::string::{FromUtf8Error,FromUtf16Error}; - + use abi_stable::std_types::{RBox,SendRBoxError}; // Constructing a `SendRBoxError` from a `Box`, @@ -158,7 +158,7 @@ use abi_stable::std_types::{RBox,SendRBoxError}; let dyn_err:Box= Box::new(str_err()); let mut err=SendRBoxError::from_box(dyn_err); - + assert!( err.downcast_ref::().is_some() ,"part A"); } @@ -166,7 +166,7 @@ use abi_stable::std_types::{RBox,SendRBoxError}; { let str_err=|| String::from_utf8(vec![255]).unwrap_err() ; let mut err=SendRBoxError::new(str_err()); - + assert!( err.downcast_ref::().is_some() ,"part B"); } @@ -175,7 +175,7 @@ use abi_stable::std_types::{RBox,SendRBoxError}; { let str_err=|| String::from_utf16(&[0xD834]).unwrap_err() ; let mut err=SendRBoxError::new(str_err()); - + assert!( err.downcast_ref::().is_none() ,"part C"); } @@ -201,7 +201,6 @@ pub type SendRBoxError = RBoxError_; /// Ffi safe equivalent to `Box`. pub type RBoxError = RBoxError_; - impl RBoxError_ { /// Constructs a `Send + Sync` `RBoxError_` from an error. /// @@ -222,7 +221,6 @@ impl RBoxError_ { } } - impl RBoxError_ { /// Constructs a `Send + !Sync` `RBoxError_` from an error. /// @@ -243,7 +241,6 @@ impl RBoxError_ { } } - impl RBoxError_ { /// Constructs a `!Send + !Sync` `RBoxError_` from an error. /// @@ -264,7 +261,6 @@ impl RBoxError_ { } } - impl RBoxError_ { /// Constructs an RBoxError from an error, /// storing the Debug and Display messages without storing the error value. @@ -323,21 +319,17 @@ impl RBoxError_ { } fn from_debug_display(value: DebugDisplay) -> Self { - unsafe { - Self::new_with_vtable(value, MakeRErrorVTable::LIB_VTABLE_DEBUG_DISPLAY) - } + unsafe { Self::new_with_vtable(value, MakeRErrorVTable::LIB_VTABLE_DEBUG_DISPLAY) } } fn new_inner(value: T) -> Self where T: ErrorTrait + 'static, { - unsafe { - Self::new_with_vtable(value, MakeRErrorVTable::::LIB_VTABLE) - } + unsafe { Self::new_with_vtable(value, MakeRErrorVTable::::LIB_VTABLE) } } - fn new_with_vtable(value: T, vtable: RErrorVTable_Ref) -> Self{ + fn new_with_vtable(value: T, vtable: RErrorVTable_Ref) -> Self { unsafe { let value = value .piped(RBox::new) @@ -352,15 +344,15 @@ impl RBoxError_ { } } -impl RBoxError_{ - /// Converts this error to a formatted error - /// +impl RBoxError_ { + /// Converts this error to a formatted error + /// /// This is used to decouple an `RBoxError` from the dynamic library that produced it, /// in order to unload the dynamic library. - /// + /// pub fn to_formatted_error(&self) -> RBoxError_ { if let Some(dd) = self.as_debug_display() { - RBoxError_::from_debug_display(DebugDisplay{ + RBoxError_::from_debug_display(DebugDisplay { debug: dd.debug.into(), display: dd.display.into(), }) @@ -369,29 +361,26 @@ impl RBoxError_{ } } - fn as_debug_display(&self)->Option>{ - unsafe{ - self.vtable.as_debug_display()(self.value.as_rref()) - .into_option() - } + fn as_debug_display(&self) -> Option> { + unsafe { self.vtable.as_debug_display()(self.value.as_rref()).into_option() } } } impl RBoxError_ { /// Returns the `UTypeId` of the error this wraps. - pub fn type_id(&self)->UTypeId{ + pub fn type_id(&self) -> UTypeId { self.vtable.type_id()() } - fn is_type(&self)->bool{ - let self_id=self.vtable.type_id()(); - let other_id=UTypeId::new::(); - self_id==other_id + fn is_type(&self) -> bool { + let self_id = self.vtable.type_id()(); + let other_id = UTypeId::new::(); + self_id == other_id } /// The address of the `Box<_>` this wraps - pub fn heap_address(&self)->usize{ - (self.value.as_ptr())as *const _ as usize + pub fn heap_address(&self) -> usize { + (self.value.as_ptr()) as *const _ as usize } /// Casts this `&RBoxError_<_>` to `&UnsyncRBoxError`. @@ -409,10 +398,8 @@ impl RBoxError_ { /// let unsync_err:&UnsyncRBoxError=err.as_unsync(); /// /// ``` - pub fn as_unsync(&self)->&UnsyncRBoxError{ - unsafe{ - transmute_reference::,UnsyncRBoxError>(self) - } + pub fn as_unsync(&self) -> &UnsyncRBoxError { + unsafe { transmute_reference::, UnsyncRBoxError>(self) } } /// Converts this `RBoxError_<_>` to `UnsyncRBoxError`. @@ -430,15 +417,12 @@ impl RBoxError_ { /// let unsync_err:UnsyncRBoxError=err.into_unsync(); /// /// ``` - pub fn into_unsync(self)->UnsyncRBoxError{ - unsafe{ - mem::transmute::,UnsyncRBoxError>(self) - } + pub fn into_unsync(self) -> UnsyncRBoxError { + unsafe { mem::transmute::, UnsyncRBoxError>(self) } } } - -impl RBoxError_{ +impl RBoxError_ { /// Casts this `&RBoxError_<_>` to `&SendRBoxError`. /// /// # Example @@ -455,10 +439,8 @@ impl RBoxError_{ /// let unsync_err:&SendRBoxError=err.as_send(); /// /// ``` - pub fn as_send(&self)->&SendRBoxError{ - unsafe{ - transmute_reference::,SendRBoxError>(self) - } + pub fn as_send(&self) -> &SendRBoxError { + unsafe { transmute_reference::, SendRBoxError>(self) } } /// Converts this `RBoxError_<_>` to `SendRBoxError`. @@ -477,64 +459,55 @@ impl RBoxError_{ /// let unsync_err:SendRBoxError=err.into_send(); /// /// ``` - pub fn into_send(self)->SendRBoxError{ - unsafe{ - mem::transmute::,SendRBoxError>(self) - } + pub fn into_send(self) -> SendRBoxError { + unsafe { mem::transmute::, SendRBoxError>(self) } } } - - impl ErrorTrait for RBoxError_ {} impl Display for RBoxError_ { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - unsafe{ - adapt_std_fmt(self.value.as_rref(), self.vtable.display(), f) - } + unsafe { adapt_std_fmt(self.value.as_rref(), self.vtable.display(), f) } } } impl Debug for RBoxError_ { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - unsafe{ - adapt_std_fmt(self.value.as_rref(), self.vtable.debug(), f) - } + unsafe { adapt_std_fmt(self.value.as_rref(), self.vtable.debug(), f) } } } //////////////////////////////////////////////////////////////////////// - macro_rules! from_impls { ( $first_docs:expr, $boxdyn:ty, $marker:ty, - ) => ( - impl From<$boxdyn> for RBoxError_<$marker>{ + ) => { + impl From<$boxdyn> for RBoxError_<$marker> { #[doc = $first_docs] /// - /// # Behavior + /// # Behavior /// /// If the contents of the Box<_> is an erased `RBoxError_<_>` /// it will be returned directly, /// otherwise the `Box<_>` will be converted into an `RBoxError_<_>` /// using `RBoxError_::new`. /// - fn from(this:$boxdyn)->RBoxError_<$marker>{ + fn from(this: $boxdyn) -> RBoxError_<$marker> { Self::from_box(this) } } - impl RBoxError_<$marker>{ + impl RBoxError_<$marker> { #[doc = $first_docs] /// - /// `RBoxError::from_box( RBoxError::into_box( err ) )` + /// `RBoxError::from_box( RBoxError::into_box( err ) )` /// is a no-op with respect to the heap address of the RBoxError_<_>. /// - /// # Behavior + /// # Behavior /// /// If the contents of the `Box<_>` is an erased `RBoxError_<_>` /// it will be returned directly, @@ -545,26 +518,22 @@ macro_rules! from_impls { /// /// For an example of converting back and forth to a `Box` /// [here is the example](#from_to_conversion). - pub fn from_box(this:$boxdyn)->Self{ + pub fn from_box(this: $boxdyn) -> Self { match this.downcast::() { - Ok(e)=>{ - *e - } - Err(e)=>{ - Self::new_with_vtable::<$boxdyn>( - e, - MakeBoxedRErrorVTable::<$boxdyn>::LIB_VTABLE, - ) - } + Ok(e) => *e, + Err(e) => Self::new_with_vtable::<$boxdyn>( + e, + MakeBoxedRErrorVTable::<$boxdyn>::LIB_VTABLE, + ), } } /// Converts an `RBoxError_<_>` to a `Box`. /// - /// `RBoxError::from_box( RBoxError::into_box( err ) )` + /// `RBoxError::from_box( RBoxError::into_box( err ) )` /// is a no-op with respect to the heap address of the RBoxError_<_>. /// - /// # Behavior + /// # Behavior /// /// If the contents of the `RBoxError_<_>` is an erased `Box` /// it will be returned directly, @@ -575,13 +544,13 @@ macro_rules! from_impls { /// /// For an example of converting back and forth to a `Box` /// [here is the example](#from_to_conversion). - pub fn into_box(self)->$boxdyn{ + pub fn into_box(self) -> $boxdyn { if self.is_type::<$boxdyn>() { - unsafe{ - let box_=mem::transmute::, RBox<$boxdyn>>(self.value); + unsafe { + let box_ = mem::transmute::, RBox<$boxdyn>>(self.value); RBox::into_inner(box_) } - }else{ + } else { Box::new(self) } } @@ -603,27 +572,23 @@ macro_rules! from_impls { /// /// # Example /// - /// Look at the type level documentation for + /// Look at the type level documentation for /// [the example](#downcasting-by-value). /// - pub fn downcast(self)->Result,Self> + pub fn downcast(self) -> Result, Self> where - T:ErrorTrait+'static + T: ErrorTrait + 'static, { - match (self.is_type::(),self.is_type::<$boxdyn>()) { - (true,_)=>{ - unsafe{ - Ok(mem::transmute::, RBox>(self.value)) - } - } - (false,true) if self.downcast_ref::().is_some() =>{ - unsafe{ - let x=mem::transmute::,RBox<$boxdyn>>(self.value); - let x=RBox::into_inner(x); - Ok(RBox::from_box(x.downcast::().unwrap())) - } - } - (false,_)=>Err(self), + match (self.is_type::(), self.is_type::<$boxdyn>()) { + (true, _) => unsafe { + Ok(mem::transmute::, RBox>(self.value)) + }, + (false, true) if self.downcast_ref::().is_some() => unsafe { + let x = mem::transmute::, RBox<$boxdyn>>(self.value); + let x = RBox::into_inner(x); + Ok(RBox::from_box(x.downcast::().unwrap())) + }, + (false, _) => Err(self), } } @@ -647,23 +612,17 @@ macro_rules! from_impls { /// Look at the type level documentation for the example. /// [the example](#downcasting-by-reference). /// - pub fn downcast_ref(&self)->Option<&T> + pub fn downcast_ref(&self) -> Option<&T> where - T:ErrorTrait+'static + T: ErrorTrait + 'static, { - match (self.is_type::(),self.is_type::<$boxdyn>()) { - (true,_)=>{ - unsafe{ - Some(&*(self.value.as_ptr() as *const T)) - } - } - (false,true)=>{ - unsafe{ - let ref_box=&*(self.value.as_ptr() as *const $boxdyn); - (&**ref_box).downcast_ref::() - } - } - (false,false)=>None, + match (self.is_type::(), self.is_type::<$boxdyn>()) { + (true, _) => unsafe { Some(&*(self.value.as_ptr() as *const T)) }, + (false, true) => unsafe { + let ref_box = &*(self.value.as_ptr() as *const $boxdyn); + (&**ref_box).downcast_ref::() + }, + (false, false) => None, } } @@ -687,108 +646,89 @@ macro_rules! from_impls { /// Look at the type level documentation for the example. /// [the example](#downcasting-by-mutable-reference). /// - pub fn downcast_mut(&mut self)->Option<&mut T> + pub fn downcast_mut(&mut self) -> Option<&mut T> where - T:ErrorTrait+'static + T: ErrorTrait + 'static, { - match (self.is_type::(),self.is_type::<$boxdyn>()) { - (true,_)=>{ - unsafe{ - Some(&mut *(self.value.as_mut_ptr() as *mut T)) - } - } - (false,true)=>{ - unsafe{ - let mut_box = &mut *(self.value.as_mut_ptr() as *mut $boxdyn); - (&mut **mut_box).downcast_mut::() - } - } - (false,false)=>None, + match (self.is_type::(), self.is_type::<$boxdyn>()) { + (true, _) => unsafe { Some(&mut *(self.value.as_mut_ptr() as *mut T)) }, + (false, true) => unsafe { + let mut_box = &mut *(self.value.as_mut_ptr() as *mut $boxdyn); + (&mut **mut_box).downcast_mut::() + }, + (false, false) => None, } } } - ) + }; } - -from_impls!{ +from_impls! { "Converts a `Box` to a `Send + Sync` `RBoxError_`.", Box , SyncSend, } -from_impls!{ +from_impls! { "Converts a `Box` to a `Send + !Sync` `RBoxError_`.", Box , UnsyncSend, } -from_impls!{ +from_impls! { "Converts a `Box` to a `!Send + !Sync` `RBoxError_`.", Box , UnsyncUnsend, } - - //////////////////////////////////////////////////////////////////////// #[repr(C)] #[derive(StableAbi)] #[sabi(kind(Prefix))] struct RErrorVTable { - debug: - unsafe extern "C" fn( - RRef<'_, ErasedObject>, - FormattingMode, - &mut RString, - ) -> RResult<(), ()>, - - display: - unsafe extern "C" fn( - RRef<'_, ErasedObject>, - FormattingMode, - &mut RString, - ) -> RResult<(), ()>, - - as_debug_display: - unsafe extern "C" fn(RRef<'_, ErasedObject>) -> ROption>, + debug: unsafe extern "C" fn( + RRef<'_, ErasedObject>, + FormattingMode, + &mut RString, + ) -> RResult<(), ()>, + + display: unsafe extern "C" fn( + RRef<'_, ErasedObject>, + FormattingMode, + &mut RString, + ) -> RResult<(), ()>, + + as_debug_display: unsafe extern "C" fn(RRef<'_, ErasedObject>) -> ROption>, #[sabi(last_prefix_field)] - type_id: extern "C" fn()->UTypeId, + type_id: extern "C" fn() -> UTypeId, } /////////////////// struct MakeRErrorVTable(T); - impl MakeRErrorVTable -where T:ErrorTrait+'static +where + T: ErrorTrait + 'static, { - const VALUE:RErrorVTable=RErrorVTable{ + const VALUE: RErrorVTable = RErrorVTable { debug: debug_impl::, display: display_impl::, as_debug_display: not_as_debug_display, type_id: new_utypeid::, }; - const VALUE_MD: &'static WithMetadata = - &WithMetadata::new( - PrefixTypeTrait::METADATA, - Self::VALUE, - ); + const VALUE_MD: &'static WithMetadata = + &WithMetadata::new(PrefixTypeTrait::METADATA, Self::VALUE); - const LIB_VTABLE: RErrorVTable_Ref = { - RErrorVTable_Ref( - Self::VALUE_MD.static_as_prefix() - ) - }; + const LIB_VTABLE: RErrorVTable_Ref = { RErrorVTable_Ref(Self::VALUE_MD.static_as_prefix()) }; } impl MakeRErrorVTable { const WM_DEBUG_DISPLAY: &'static WithMetadata = { &WithMetadata::new( PrefixTypeTrait::METADATA, - RErrorVTable{ + RErrorVTable { debug: debug_impl::, display: display_impl::, as_debug_display, @@ -797,29 +737,26 @@ impl MakeRErrorVTable { ) }; - const LIB_VTABLE_DEBUG_DISPLAY: RErrorVTable_Ref = { - RErrorVTable_Ref( - Self::WM_DEBUG_DISPLAY.static_as_prefix() - ) - }; + const LIB_VTABLE_DEBUG_DISPLAY: RErrorVTable_Ref = + { RErrorVTable_Ref(Self::WM_DEBUG_DISPLAY.static_as_prefix()) }; } /////////////////// struct MakeBoxedRErrorVTable(T); - impl MakeBoxedRErrorVTable> -where T:?Sized+ErrorTrait+'static +where + T: ?Sized + ErrorTrait + 'static, { - const VALUE:RErrorVTable=RErrorVTable{ + const VALUE: RErrorVTable = RErrorVTable { debug: debug_impl::>, display: display_impl::>, as_debug_display: not_as_debug_display, type_id: new_utypeid::>, }; - const WM_VTABLE: &'static WithMetadata = + const WM_VTABLE: &'static WithMetadata = &WithMetadata::new(PrefixTypeTrait::METADATA, Self::VALUE); const LIB_VTABLE: RErrorVTable_Ref = RErrorVTable_Ref(Self::WM_VTABLE.static_as_prefix()); @@ -876,5 +813,3 @@ unsafe extern "C" fn not_as_debug_display( ) -> ROption> { ROption::RNone } - - diff --git a/abi_stable/src/std_types/std_error/test.rs b/abi_stable/src/std_types/std_error/test.rs index 89ef5fce..8e4d238e 100644 --- a/abi_stable/src/std_types/std_error/test.rs +++ b/abi_stable/src/std_types/std_error/test.rs @@ -2,105 +2,101 @@ use super::*; use crate::{ std_types::string::FromUtf8Error as OtherErr, - test_utils::{check_formatting_equivalence,deref_address,Stringy}, + test_utils::{check_formatting_equivalence, deref_address, Stringy}, }; - /////////////////////////////////////////////////////////////////////////////// - #[test] -fn new(){ - - let err=Stringy::new("hello\n\rworld"); +fn new() { + let err = Stringy::new("hello\n\rworld"); - let e0=RBoxError::new(err.clone()); + let e0 = RBoxError::new(err.clone()); - check_formatting_equivalence(&err,&e0); + check_formatting_equivalence(&err, &e0); } - -/// Testing that converting back and forth between +/// Testing that converting back and forth between /// `RBoxError` and `Box` gives back the object it started with. #[test] -fn identity_conversion(){ - - let err=Stringy::new("hello\n\rworld"); +fn identity_conversion() { + let err = Stringy::new("hello\n\rworld"); { - let e0=RBoxError::new(err.clone()); + let e0 = RBoxError::new(err.clone()); - let addr=e0.heap_address(); + let addr = e0.heap_address(); - let e1=e0.piped(RBoxError::into_box).piped(RBoxError::from_box); + let e1 = e0.piped(RBoxError::into_box).piped(RBoxError::from_box); - assert_eq!( - addr, - e1.heap_address() - ); + assert_eq!(addr, e1.heap_address()); } { - let e0=Box::new(err.clone()); + let e0 = Box::new(err.clone()); - let addr=e0.piped_ref(deref_address); + let addr = e0.piped_ref(deref_address); - let e1=e0.piped(|x|RBoxError::from_box(x)).piped(RBoxError::into_box); - - assert_eq!( - addr, - e1.piped_ref(deref_address) - ); + let e1 = e0 + .piped(|x| RBoxError::from_box(x)) + .piped(RBoxError::into_box); + + assert_eq!(addr, e1.piped_ref(deref_address)); } } #[test] -fn from_to_box(){ - let err=Stringy::new("hello\n\rworld"); +fn from_to_box() { + let err = Stringy::new("hello\n\rworld"); { - let e0=err.clone() + let e0 = err + .clone() .piped(RBoxError::new) .piped(RBoxError::into_box) .piped(RBoxError::from_box); - - check_formatting_equivalence(&err,&e0); + + check_formatting_equivalence(&err, &e0); } { - let e0=err.clone().piped(RBoxError::new).piped(RBoxError::into_box); - - check_formatting_equivalence(&err,&e0); + let e0 = err.clone().piped(RBoxError::new).piped(RBoxError::into_box); + + check_formatting_equivalence(&err, &e0); } } - #[test] fn downcast() { - let err=Stringy::new("hello\n\rworld"); + let err = Stringy::new("hello\n\rworld"); macro_rules! downcast_ { ( method=$method:ident, conv=$conv:expr - ) => ({ - let res0=RBoxError::new(err.clone()).$method::().piped($conv).is_some(); - let res1=RBoxError::new(err.clone()).$method::().piped($conv).is_none(); - - assert!(res0,"This RBoxError could not be downcasted to Stringy."); - - assert!(res1,"This RBoxError should only downcast to Stringy."); - }) + ) => {{ + let res0 = RBoxError::new(err.clone()) + .$method::() + .piped($conv) + .is_some(); + let res1 = RBoxError::new(err.clone()) + .$method::() + .piped($conv) + .is_none(); + + assert!(res0, "This RBoxError could not be downcasted to Stringy."); + + assert!(res1, "This RBoxError should only downcast to Stringy."); + }}; } - downcast_!{method=downcast ,conv=|x| x.ok() } - downcast_!{method=downcast_ref,conv=::std::convert::identity} - downcast_!{method=downcast_mut,conv=::std::convert::identity} + downcast_! {method=downcast ,conv=|x| x.ok() } + downcast_! {method=downcast_ref,conv=::std::convert::identity} + downcast_! {method=downcast_mut,conv=::std::convert::identity} } - #[test] -fn casts_among_rboxerrors(){ - let err=Stringy::new("hello\n\rworld"); - +fn casts_among_rboxerrors() { + let err = Stringy::new("hello\n\rworld"); + macro_rules! casts_among_rboxerrors_ { ( err_ty=$err:ty; @@ -118,55 +114,51 @@ fn casts_among_rboxerrors(){ }) } - - casts_among_rboxerrors_!{ + casts_among_rboxerrors_! { err_ty=UnsyncRBoxError; methods=[into_unsync,as_unsync]; } - casts_among_rboxerrors_!{ + casts_among_rboxerrors_! { err_ty=SendRBoxError; methods=[into_unsync,as_unsync]; } - casts_among_rboxerrors_!{ + casts_among_rboxerrors_! { err_ty=RBoxError; methods=[into_unsync,as_unsync,as_send,into_send]; } } - fn check_formatted_debug_display(str_err: &Stringy, rerr: &RBoxError) { let as_dd = rerr.as_debug_display().unwrap(); assert_eq!(format!("{:#?}", str_err), as_dd.debug.as_str()); assert_eq!(format!("{:#}", str_err), as_dd.display.as_str()); assert_eq!(str_err.str, as_dd.display.as_str()); - check_formatting_equivalence(&str_err,rerr); + check_formatting_equivalence(&str_err, rerr); } #[test] fn to_formatted() { - let str_err=Stringy::new("hello\n\rworld"); + let str_err = Stringy::new("hello\n\rworld"); { let rerr = RBoxError::new(str_err.clone()); assert_eq!(rerr.as_debug_display(), None); - check_formatting_equivalence(&str_err,&rerr); + check_formatting_equivalence(&str_err, &rerr); let rerr: RBoxError = rerr.to_formatted_error(); - check_formatted_debug_display(&str_err, &rerr); check_formatted_debug_display(&str_err, &rerr.to_formatted_error()); } - } #[test] -fn from_fmt_or_debug(){ - let str_err=Stringy::new("hello\n\rworld"); +fn from_fmt_or_debug() { + let str_err = Stringy::new("hello\n\rworld"); { let rerr = RBoxError::from_fmt(&str_err); @@ -184,4 +176,4 @@ fn from_fmt_or_debug(){ assert_eq!(format!("{:#?}", str_err), format!("{:#?}", rerr)); assert_eq!(format!("{:#?}", str_err), format!("{}", rerr)); } -} \ No newline at end of file +} diff --git a/abi_stable/src/std_types/std_io.rs b/abi_stable/src/std_types/std_io.rs index b6ba2cb2..25b34b8b 100644 --- a/abi_stable/src/std_types/std_io.rs +++ b/abi_stable/src/std_types/std_io.rs @@ -5,23 +5,22 @@ Ffi-safe equivalents of `std::io::{ErrorKind,Error,SeekFrom}`. use std::{ error::Error as ErrorTrait, fmt::{self, Debug, Display}, - io::{Error as ioError,SeekFrom, ErrorKind}, + io::{Error as ioError, ErrorKind, SeekFrom}, }; #[allow(unused_imports)] use core_extensions::SelfOps; use crate::{ - traits::{IntoReprC,IntoReprRust}, - std_types::{RBoxError,ROption,RSome,RNone}, + std_types::{RBoxError, RNone, ROption, RSome}, + traits::{IntoReprC, IntoReprRust}, }; - /////////////////////////////////////////////////////////////////////////// /// Ffi safe equivalent to `std::io::ErrorKind`. /// -/// Using a struct with associated constants is the +/// Using a struct with associated constants is the /// ffi-safe way of doing `#[non_exhaustive]` field-less enums. #[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)] #[repr(C)] @@ -30,12 +29,11 @@ pub struct RIoErrorKind { value: u8, } - macro_rules! impl_error_kind { ( $( - $variant:ident,discriminant=$value:expr , message=$as_str_msg:expr ; - )* + $variant:ident,discriminant=$value:expr , message=$as_str_msg:expr ; + )* ) => ( /// Every (visible) variant of RIoErrorKind,equivalent to that of `std::io::ErrorKind`. #[allow(non_upper_case_globals)] @@ -97,7 +95,7 @@ macro_rules! impl_error_kind { ) } -impl_error_kind!{ +impl_error_kind! { NotFound, discriminant = 1 , message="entity not found" ; PermissionDenied, discriminant = 2 , message="permission denied" ; ConnectionRefused, discriminant = 3 , message="connection refused" ; @@ -117,10 +115,8 @@ impl_error_kind!{ UnexpectedEof, discriminant = 17 , message="unexpected end of file" ; } - /////////////////////////////////////////////////////////////////////////// - /// Ffi-safe equivalent of [`std::io::SeekFrom`]. /// /// [`std::io::SeekFrom`]: https://doc.rust-lang.org/std/io/enum.SeekFrom.html @@ -145,7 +141,6 @@ impl_from_rust_repr! { } } - impl_into_rust_repr! { impl Into for RSeekFrom { fn(this){ @@ -158,8 +153,6 @@ impl_into_rust_repr! { } } - - /////////////////////////////////////////////////////////////////////////// /** @@ -226,20 +219,17 @@ impl_into_rust_repr! { } } -impl From for RIoError{ - fn from(kind:RIoErrorKind)->Self{ - Self{ - kind, - error:RNone, - } +impl From for RIoError { + fn from(kind: RIoErrorKind) -> Self { + Self { kind, error: RNone } } } -impl From for RIoError{ - fn from(kind:ErrorKind)->Self{ - Self{ - kind:kind.into(), - error:RNone +impl From for RIoError { + fn from(kind: ErrorKind) -> Self { + Self { + kind: kind.into(), + error: RNone, } } } @@ -273,7 +263,7 @@ impl RIoError { /// ``` /// use abi_stable::std_types::RIoError; /// use std::io::ErrorKind; - /// + /// /// let str_err="Timeout receiving the response from server."; /// /// let err=RIoError::new_( ErrorKind::TimedOut, str_err); @@ -283,7 +273,7 @@ impl RIoError { where E: Into>, { - Self::with_box(kind,error.into()) + Self::with_box(kind, error.into()) } /// Constructs an `RIoError` from a `std::io::ErrorKind`. @@ -293,17 +283,17 @@ impl RIoError { /// ``` /// use abi_stable::std_types::RIoError; /// use std::io::ErrorKind; - /// + /// /// let err=RIoError::from_kind( ErrorKind::AlreadyExists ); /// ``` - pub fn from_kind(kind: ErrorKind)->Self{ - Self{ - kind:kind.into_c(), - error:RNone, + pub fn from_kind(kind: ErrorKind) -> Self { + Self { + kind: kind.into_c(), + error: RNone, } } - /// Constructs an `RIoError` from a + /// Constructs an `RIoError` from a /// `Box` and a `std::io::ErrorKind`. /// /// # Example @@ -311,12 +301,12 @@ impl RIoError { /// ``` /// use abi_stable::std_types::RIoError; /// use std::io::ErrorKind; - /// + /// /// let str_err="Could not create file \"memes.txt\" because it already exists."; /// /// let err=RIoError::with_box( ErrorKind::AlreadyExists, str_err.into()); /// ``` - pub fn with_box(kind: ErrorKind, error: Box) -> Self{ + pub fn with_box(kind: ErrorKind, error: Box) -> Self { RIoError { kind: kind.into_c(), error: RSome(RBoxError::from_box(error)), @@ -330,17 +320,17 @@ impl RIoError { /// ``` /// use abi_stable::std_types::RIoError; /// use std::io::ErrorKind; - /// + /// /// type DynErr=Box; /// /// let str_err:DynErr="IP address `256.256.256.256` is already in use.".into(); /// /// let err=RIoError::with_rboxerror( ErrorKind::AddrInUse, str_err.into() ); /// ``` - pub fn with_rboxerror(kind: ErrorKind, error: RBoxError) -> Self{ + pub fn with_rboxerror(kind: ErrorKind, error: RBoxError) -> Self { RIoError { kind: kind.into_c(), - error:RSome(error), + error: RSome(error), } } @@ -351,16 +341,15 @@ impl RIoError { /// ``` /// use abi_stable::std_types::{RIoError,RIoErrorKind}; /// use std::io::ErrorKind; - /// + /// /// let err=RIoError::from_kind( ErrorKind::AlreadyExists ); /// /// assert_eq!(err.kind(), RIoErrorKind::AlreadyExists); /// ``` - pub fn kind(&self)->RIoErrorKind{ + pub fn kind(&self) -> RIoErrorKind { self.kind } - /// Gets the internal error, /// returning `None` if this was constructed with `RIoError::from_kind`. /// @@ -369,7 +358,7 @@ impl RIoError { /// ``` /// use abi_stable::std_types::{RIoError,RIoErrorKind,RBoxError}; /// use std::io::ErrorKind; - /// + /// /// { /// let err=RIoError::from_kind( ErrorKind::AlreadyExists ); /// assert_eq!(err.get_ref().map(|_|()), None); @@ -380,12 +369,12 @@ impl RIoError { /// /// assert!(err.get_ref().is_some()); /// } - /// + /// /// ``` - pub fn get_ref(&self) -> Option<&RBoxError>{ + pub fn get_ref(&self) -> Option<&RBoxError> { self.error.as_ref().into_rust() } - + /// Gets the internal error, /// returning `None` if this was constructed with `RIoError::from_kind`. /// @@ -394,7 +383,7 @@ impl RIoError { /// ``` /// use abi_stable::std_types::{RIoError,RIoErrorKind,RBoxError}; /// use std::io::ErrorKind; - /// + /// /// { /// let mut err=RIoError::from_kind( ErrorKind::AlreadyExists ); /// assert_eq!(err.get_mut().map(|_|()), None); @@ -404,9 +393,9 @@ impl RIoError { /// let mut err=RIoError::new_( ErrorKind::PermissionDenied, msg ); /// assert!(err.get_mut().is_some()); /// } - /// + /// /// ``` - pub fn get_mut(&mut self) -> Option<&mut RBoxError>{ + pub fn get_mut(&mut self) -> Option<&mut RBoxError> { self.error.as_mut().into_rust() } @@ -418,7 +407,7 @@ impl RIoError { /// ``` /// use abi_stable::std_types::RIoError; /// use std::io::ErrorKind; - /// + /// /// { /// let err=RIoError::from_kind( ErrorKind::AlreadyExists ); /// assert_eq!(err.into_inner().map(|_|()), None); @@ -428,12 +417,11 @@ impl RIoError { /// let err=RIoError::new_( ErrorKind::PermissionDenied, msg ); /// assert!(err.into_inner().is_some()); /// } - /// + /// /// ``` - pub fn into_inner(self) -> Option{ + pub fn into_inner(self) -> Option { self.error.into_rust() } - } impl Debug for RIoError { @@ -445,95 +433,90 @@ impl Debug for RIoError { } } - impl Display for RIoError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.error.as_ref() { RSome(c) => Display::fmt(&c, f), - RNone => Display::fmt(self.kind.error_message(),f), + RNone => Display::fmt(self.kind.error_message(), f), } } } impl ErrorTrait for RIoError {} - /////////////////////////////////////////////////////////////////////////////////// - -#[cfg(all(test,not(feature="only_new_tests")))] -mod error_kind_tests{ +#[cfg(all(test, not(feature = "only_new_tests")))] +mod error_kind_tests { use super::*; #[test] - fn conversions(){ - for (from,to) in - vec![ - (ErrorKind::NotConnected,RIoErrorKind::NotConnected), - (ErrorKind::AddrInUse,RIoErrorKind::AddrInUse), - (ErrorKind::Other,RIoErrorKind::Other), - ] - { - assert_eq!(RIoErrorKind::from(from) , to); - assert_eq!(to.into_::() , from); + fn conversions() { + for (from, to) in vec![ + (ErrorKind::NotConnected, RIoErrorKind::NotConnected), + (ErrorKind::AddrInUse, RIoErrorKind::AddrInUse), + (ErrorKind::Other, RIoErrorKind::Other), + ] { + assert_eq!(RIoErrorKind::from(from), to); + assert_eq!(to.into_::(), from); } } } -#[cfg(all(test,not(feature="only_new_tests")))] -mod io_error_tests{ +#[cfg(all(test, not(feature = "only_new_tests")))] +mod io_error_tests { use super::*; - use crate::test_utils::{ - check_formatting_equivalence, - deref_address, - Stringy, - }; - + use crate::test_utils::{check_formatting_equivalence, deref_address, Stringy}; #[test] - fn from_error_kind(){ - for kind in - vec![ - ErrorKind::NotConnected, - ErrorKind::AddrInUse, - ErrorKind::Other, - ] - { - let err=kind.piped(RIoError::from_kind); + fn from_error_kind() { + for kind in vec![ + ErrorKind::NotConnected, + ErrorKind::AddrInUse, + ErrorKind::Other, + ] { + let err = kind.piped(RIoError::from_kind); assert_eq!(err.kind(), kind.into_c()); } } #[test] - fn from_value(){ - let err=Stringy::new("What\nis\ra\tline"); - let e0=RIoError::new(ErrorKind::Other,err.clone()); + fn from_value() { + let err = Stringy::new("What\nis\ra\tline"); + let e0 = RIoError::new(ErrorKind::Other, err.clone()); - check_formatting_equivalence(&err,&e0); + check_formatting_equivalence(&err, &e0); } #[test] - fn from_boxerror(){ - let err=Stringy::new("What\nis\ra\tline"); - let box_=err.clone().piped(Box::new); - let addr=deref_address(&box_); - let ioerr=RIoError::with_box(ErrorKind::Other,box_); - - check_formatting_equivalence(&err,&ioerr); - - assert_eq!(addr, ioerr.into_inner().unwrap().into_box().piped_ref(deref_address)); + fn from_boxerror() { + let err = Stringy::new("What\nis\ra\tline"); + let box_ = err.clone().piped(Box::new); + let addr = deref_address(&box_); + let ioerr = RIoError::with_box(ErrorKind::Other, box_); + + check_formatting_equivalence(&err, &ioerr); + + assert_eq!( + addr, + ioerr + .into_inner() + .unwrap() + .into_box() + .piped_ref(deref_address) + ); } #[test] - fn from_rboxerror(){ - let err=Stringy::new("What\nis\ra\tline"); - let rbox=err.clone().piped(RBoxError::new); - let addr=rbox.heap_address(); - let mut ioerr=RIoError::with_rboxerror(ErrorKind::Other,rbox); + fn from_rboxerror() { + let err = Stringy::new("What\nis\ra\tline"); + let rbox = err.clone().piped(RBoxError::new); + let addr = rbox.heap_address(); + let mut ioerr = RIoError::with_rboxerror(ErrorKind::Other, rbox); - check_formatting_equivalence(&err,&ioerr); + check_formatting_equivalence(&err, &ioerr); assert_eq!(addr, ioerr.get_ref().unwrap().heap_address()); @@ -541,6 +524,4 @@ mod io_error_tests{ assert_eq!(addr, ioerr.into_inner().unwrap().heap_address()); } - - -} \ No newline at end of file +} diff --git a/abi_stable/src/std_types/str.rs b/abi_stable/src/std_types/str.rs index e463dfdb..6922f168 100644 --- a/abi_stable/src/std_types/str.rs +++ b/abi_stable/src/std_types/str.rs @@ -3,7 +3,7 @@ Contains an ffi-safe equivalent of `&'a str`. */ use std::{ - borrow::{Cow,Borrow}, + borrow::{Borrow, Cow}, fmt::{self, Display}, ops::{Deref, Index}, str, @@ -120,7 +120,7 @@ impl<'a> RStr<'a> { /// /// ``` pub const fn from_str(s: &'a str) -> Self { - unsafe{ Self::from_raw_parts( s.as_ptr(), s.len() ) } + unsafe { Self::from_raw_parts(s.as_ptr(), s.len()) } } /// For slicing `RStr`s. @@ -183,7 +183,7 @@ impl<'a> RStr<'a> { } /// Gets a raw pointer to the start of the string slice. - pub const fn as_ptr(&self) -> *const u8{ + pub const fn as_ptr(&self) -> *const u8 { self.inner.as_ptr() } @@ -216,7 +216,7 @@ impl<'a> RStr<'a> { /// assert_eq!(RStr::from("What").is_empty(),false); /// /// ``` - pub const fn is_empty(&self)->bool{ + pub const fn is_empty(&self) -> bool { self.inner.is_empty() } } @@ -239,8 +239,7 @@ impl<'a> Deref for RStr<'a> { } } - -deref_coerced_impl_cmp_traits!{ +deref_coerced_impl_cmp_traits! { RStr<'_>; coerce_to = str, [ @@ -292,20 +291,20 @@ impl_from_rust_repr! { //////////////////////////////// -impl<'a> Borrow for RStr<'a>{ - fn borrow(&self)->&str{ +impl<'a> Borrow for RStr<'a> { + fn borrow(&self) -> &str { self } } -impl AsRef for RStr<'_>{ - fn as_ref(&self)->&str{ +impl AsRef for RStr<'_> { + fn as_ref(&self) -> &str { self } } -impl AsRef<[u8]> for RStr<'_>{ - fn as_ref(&self)->&[u8]{ +impl AsRef<[u8]> for RStr<'_> { + fn as_ref(&self) -> &[u8] { self.as_bytes() } } @@ -348,7 +347,7 @@ shared_impls! { //////////////////////////////////////////////////// //#[cfg(test)] -#[cfg(all(test,not(feature="only_new_tests")))] +#[cfg(all(test, not(feature = "only_new_tests")))] mod test { use super::*; diff --git a/abi_stable/src/std_types/string.rs b/abi_stable/src/std_types/string.rs index 458e6c4c..5c58c73a 100644 --- a/abi_stable/src/std_types/string.rs +++ b/abi_stable/src/std_types/string.rs @@ -3,14 +3,14 @@ Contains an ffi-safe equivalent of `std::string::String`. */ use std::{ - borrow::{Cow,Borrow}, + borrow::{Borrow, Cow}, fmt::{self, Display, Formatter}, iter::{FromIterator, FusedIterator}, marker::PhantomData, ops::{Deref, Index, Range}, - str::{from_utf8, from_utf8_unchecked, Chars,FromStr, Utf8Error}, - string::FromUtf16Error, ptr, + str::{from_utf8, from_utf8_unchecked, Chars, FromStr, Utf8Error}, + string::FromUtf16Error, }; use serde::{Deserialize, Deserializer, Serialize, Serializer}; @@ -69,7 +69,7 @@ impl RString { /// use abi_stable::std_types::RString; /// /// let str=RString::new(); - /// + /// /// assert_eq!(&str[..],""); /// /// ``` @@ -77,7 +77,7 @@ impl RString { Self::NEW } - const NEW:Self=Self{ inner:RVec::new() }; + const NEW: Self = Self { inner: RVec::new() }; /// Creates a new, /// empty RString with the capacity for `cap` bytes without reallocating. @@ -88,12 +88,12 @@ impl RString { /// use abi_stable::std_types::RString; /// /// let str=RString::with_capacity(10); - /// + /// /// assert_eq!(&str[..],""); /// assert_eq!(str.capacity(),10); /// /// ``` - pub fn with_capacity(cap:usize) -> Self { + pub fn with_capacity(cap: usize) -> Self { String::with_capacity(cap).into() } @@ -108,7 +108,7 @@ impl RString { /// use abi_stable::std_types::{RStr,RString}; /// /// let str=RString::from("What is that."); - /// + /// /// assert_eq!(str.slice(..),RStr::from("What is that.")); /// assert_eq!(str.slice(..4),RStr::from("What")); /// assert_eq!(str.slice(4..),RStr::from(" is that.")); @@ -156,9 +156,7 @@ impl RString { /// ``` #[inline] pub const fn as_rstr(&self) -> RStr<'_> { - unsafe{ - RStr::from_raw_parts(self.as_ptr(),self.len()) - } + unsafe { RStr::from_raw_parts(self.as_ptr(), self.len()) } } /// Returns the current length (in bytes) of the RString. @@ -196,11 +194,10 @@ impl RString { } /// Gets a raw pointer to the start of this RString's buffer. - pub const fn as_ptr(&self) -> *const u8{ + pub const fn as_ptr(&self) -> *const u8 { self.inner.as_ptr() } - /// Returns the current capacity (in bytes) of the RString. /// /// # Example @@ -228,7 +225,7 @@ impl RString { /// /// # Safety /// - /// This has the same safety requirements as + /// This has the same safety requirements as /// [`String::from_utf8_unchecked` /// ](https://doc.rust-lang.org/std/string/struct.String.html#method.from_utf8_unchecked). /// @@ -245,7 +242,7 @@ impl RString { /// /// ``` #[inline] - pub const unsafe fn from_utf8_unchecked(vec: RVec) -> Self{ + pub const unsafe fn from_utf8_unchecked(vec: RVec) -> Self { RString { inner: vec } } @@ -281,19 +278,18 @@ impl RString { } } - /// Decodes a utf-16 encoded `&[u16]` to an `RString`. /// /// # Errors /// - /// This returns a `Err(::std::string::FromUtf16Error{..})` + /// This returns a `Err(::std::string::FromUtf16Error{..})` /// if `vec` is not valid utf-8. /// /// # Example /// /// ``` /// use abi_stable::std_types::RString; - /// + /// /// let str="What the 😈."; /// let str_utf16=str.encode_utf16().collect::>(); /// @@ -306,7 +302,7 @@ impl RString { String::from_utf16(s).map(From::from) } - /// Cheap conversion of this `RString` to a `RVec` + /// Cheap conversion of this `RString` to a `RVec` /// /// # Example /// @@ -358,7 +354,7 @@ impl RString { pub fn to_string(&self) -> String { self.as_str().to_string() } - + /// Reserves `àdditional` additional capacity for any extra string data. /// This may reserve more than necessary for the additional capacity. /// @@ -395,7 +391,7 @@ impl RString { } /// Reserves `àdditional` additional capacity for any extra string data. - /// + /// /// Prefer using `reserve` for most situations. /// /// # Example @@ -472,7 +468,7 @@ impl RString { /// assert_eq!(str.pop(),None); /// /// ``` - pub fn pop(&mut self)->Option{ + pub fn pop(&mut self) -> Option { // literal copy-paste of std,so if this is wrong std is wrong. let ch = self.chars().rev().next()?; @@ -484,9 +480,9 @@ impl RString { } /// Removes and returns the character starting at the `idx` byte position, - /// + /// /// # Panics - /// + /// /// Panics if the index is out of bounds or if it is not on a char boundary. /// /// # Example @@ -503,7 +499,7 @@ impl RString { /// assert_eq!(str.as_str(),"Gallo"); /// /// ``` - pub fn remove(&mut self,idx:usize)->char{ + pub fn remove(&mut self, idx: usize) -> char { // literal copy-paste of std,so if this is wrong std is wrong. let ch = match self[idx..].chars().next() { @@ -515,11 +511,7 @@ impl RString { let len = self.len(); unsafe { let ptr = self.inner.as_mut_ptr(); - ptr::copy( - ptr.add(next), - ptr.add(idx), - len - next - ); + ptr::copy(ptr.add(next), ptr.add(idx), len - next); self.inner.set_len(len - (next - idx)); } ch @@ -528,7 +520,7 @@ impl RString { /// Insert the `ch` character at the `ìdx` byte position. /// /// # Panics - /// + /// /// Panics if the index is out of bounds or if it is not on a char boundary. /// /// # Example @@ -558,7 +550,7 @@ impl RString { /// Insert the `string` at the `ìdx` byte position. /// /// # Panics - /// + /// /// Panics if the index is out of bounds or if it is not on a char boundary. /// /// # Example @@ -580,7 +572,7 @@ impl RString { /// ``` pub fn insert_str(&mut self, idx: usize, string: &str) { // literal copy-paste of std,so if this is wrong std is wrong. - + assert!(self.is_char_boundary(idx)); unsafe { @@ -592,24 +584,16 @@ impl RString { let len = self.len(); let amt = bytes.len(); self.inner.reserve(amt); - + let ptr = self.inner.as_mut_ptr(); - ptr::copy( - ptr.add(idx), - ptr.add(idx + amt), - len - idx, - ); - ptr::copy( - bytes.as_ptr(), - self.inner.as_mut_ptr().add(idx), - amt, - ); + ptr::copy(ptr.add(idx), ptr.add(idx + amt), len - idx); + ptr::copy(bytes.as_ptr(), self.inner.as_mut_ptr().add(idx), amt); self.inner.set_len(len + amt); } /// Retains only the characters that satisfy the `pred` predicate /// - /// This means that a character will be removed if `pred(that_character)` + /// This means that a character will be removed if `pred(that_character)` /// returns false. /// /// # Example @@ -636,7 +620,8 @@ impl RString { /// ``` #[inline] pub fn retain(&mut self, mut pred: F) - where F: FnMut(char) -> bool + where + F: FnMut(char) -> bool, { let len = self.len(); let mut del_bytes = 0; @@ -649,11 +634,13 @@ impl RString { let start = self.inner.as_mut_ptr(); while idx < len { - let curr = unsafe{ start.add(idx) }; + let curr = unsafe { start.add(idx) }; let ch = unsafe { RStr::from_raw_parts(curr, len - idx) - .chars().next().unwrap() + .chars() + .next() + .unwrap() }; let ch_len = ch.len_utf8(); @@ -661,11 +648,7 @@ impl RString { del_bytes += ch_len; } else if del_bytes > 0 { unsafe { - ptr::copy( - curr, - curr.sub(del_bytes), - ch_len, - ); + ptr::copy(curr, curr.sub(del_bytes), ch_len); } } @@ -688,16 +671,15 @@ impl RString { /// let mut str=RString::from("Nurse"); /// /// assert_eq!(str.as_str(),"Nurse"); - /// + /// /// str.clear(); - /// + /// /// assert_eq!(str.as_str(),""); /// /// ``` - pub fn clear(&mut self){ + pub fn clear(&mut self) { self.inner.clear(); } - } /// Returns an empty RString @@ -709,10 +691,10 @@ impl Default for RString { //////////////////// -deref_coerced_impl_cmp_traits!{ +deref_coerced_impl_cmp_traits! { RString; coerce_to = str, - [ + [ String, str, &str, @@ -722,7 +704,6 @@ deref_coerced_impl_cmp_traits!{ ] } - //////////////////// impl_into_rust_repr! { @@ -763,7 +744,6 @@ impl<'a> From> for RString { //////////////////// - impl FromStr for RString { type Err = ::Err; @@ -772,32 +752,28 @@ impl FromStr for RString { } } - //////////////////// - -impl Borrow for RString{ - fn borrow(&self)->&str{ +impl Borrow for RString { + fn borrow(&self) -> &str { self } } -impl AsRef for RString{ - fn as_ref(&self)->&str{ +impl AsRef for RString { + fn as_ref(&self) -> &str { self } } -impl AsRef<[u8]> for RString{ - fn as_ref(&self)->&[u8]{ +impl AsRef<[u8]> for RString { + fn as_ref(&self) -> &[u8] { self.as_bytes() } } - //////////////////// - impl Deref for RString { type Target = str; @@ -855,57 +831,57 @@ impl Serialize for RString { impl RString { /** -Creates an iterator that yields the chars in the `range`, -removing the characters in that range in the process. + Creates an iterator that yields the chars in the `range`, + removing the characters in that range in the process. -# Panic + # Panic -Panics if the start or end of the range are not on a on a char boundary, -or if either are out of bounds. + Panics if the start or end of the range are not on a on a char boundary, + or if either are out of bounds. -# Example + # Example -``` -use abi_stable::std_types::RString; + ``` + use abi_stable::std_types::RString; -let orig="Not a single way"; + let orig="Not a single way"; -{ - let mut str=RString::from(orig); - assert_eq!( - str.drain(..).collect::(), - orig, - ); - assert_eq!(str.as_str(),""); -} -{ - let mut str=RString::from(orig); - assert_eq!( - str.drain(..4).collect::(), - "Not ", - ); - assert_eq!(str.as_str(),"a single way"); -} -{ - let mut str=RString::from(orig); - assert_eq!( - str.drain(4..).collect::(), - "a single way", - ); - assert_eq!(str.as_str(),"Not "); -} -{ - let mut str=RString::from(orig); - assert_eq!( - str.drain(4..13).collect::(), - "a single ", - ); - assert_eq!(str.as_str(),"Not way"); -} + { + let mut str=RString::from(orig); + assert_eq!( + str.drain(..).collect::(), + orig, + ); + assert_eq!(str.as_str(),""); + } + { + let mut str=RString::from(orig); + assert_eq!( + str.drain(..4).collect::(), + "Not ", + ); + assert_eq!(str.as_str(),"a single way"); + } + { + let mut str=RString::from(orig); + assert_eq!( + str.drain(4..).collect::(), + "a single way", + ); + assert_eq!(str.as_str(),"Not "); + } + { + let mut str=RString::from(orig); + assert_eq!( + str.drain(4..13).collect::(), + "a single ", + ); + assert_eq!(str.as_str(),"Not way"); + } -``` + ``` - */ + */ pub fn drain(&mut self, range: I) -> Drain<'_> where str: Index, @@ -918,7 +894,7 @@ let orig="Not a single way"; string, removed: start..end, iter: slic_.chars(), - variance:PhantomData, + variance: PhantomData, } } } @@ -980,7 +956,7 @@ pub struct FromUtf8Error { error: Utf8Error, } -impl FromUtf8Error{ +impl FromUtf8Error { /// Unwraps this error into the bytes that failed to be converted into an `RString`. /// /// # Example @@ -995,7 +971,7 @@ impl FromUtf8Error{ /// assert_eq!( err.into_bytes(), bytes ); /// /// ``` - pub fn into_bytes(self)->RVec{ + pub fn into_bytes(self) -> RVec { self.bytes } /// Gets access to the bytes that failed to be converted into an `RString`. @@ -1012,7 +988,7 @@ impl FromUtf8Error{ /// assert_eq!( err.as_bytes(), &bytes[..] ); /// /// ``` - pub fn as_bytes(&self)->&[u8]{ + pub fn as_bytes(&self) -> &[u8] { &self.bytes } @@ -1028,7 +1004,7 @@ impl FromUtf8Error{ /// assert_eq!( err.error().valid_up_to(), 2 ); /// /// ``` - pub fn error(&self)->Utf8Error{ + pub fn error(&self) -> Utf8Error { self.error } } @@ -1039,4 +1015,4 @@ impl fmt::Display for FromUtf8Error { } } -impl std::error::Error for FromUtf8Error{} \ No newline at end of file +impl std::error::Error for FromUtf8Error {} diff --git a/abi_stable/src/std_types/string/iters.rs b/abi_stable/src/std_types/string/iters.rs index 80d42807..aebcc1d0 100644 --- a/abi_stable/src/std_types/string/iters.rs +++ b/abi_stable/src/std_types/string/iters.rs @@ -67,7 +67,7 @@ pub struct Drain<'a> { pub(super) string: *mut RString, pub(super) removed: Range, pub(super) iter: Chars<'a>, - pub(super) variance:PhantomData<&'a mut [char]>, + pub(super) variance: PhantomData<&'a mut [char]>, } impl<'a> fmt::Debug for Drain<'a> { diff --git a/abi_stable/src/std_types/string/tests.rs b/abi_stable/src/std_types/string/tests.rs index 8eeca7e2..31d6cdb5 100644 --- a/abi_stable/src/std_types/string/tests.rs +++ b/abi_stable/src/std_types/string/tests.rs @@ -4,31 +4,29 @@ use crate::test_utils::must_panic; use abi_stable_shared::file_span; - #[allow(unused_imports)] use core_extensions::{SelfOps, SliceExt}; -static TEST_STR: &str = - "hello_world.cáscara.ñ.🎊🍕👏😊😀😄😉😉😛😮🙁🙂💔👻😎."; +static TEST_STR: &str = "hello_world.cáscara.ñ.🎊🍕👏😊😀😄😉😉😛😮🙁🙂💔👻😎."; #[test] -fn from_to_string(){ - let orig="hello,world!"; - let orig_owned=orig.to_string(); - let orig_cap=orig_owned.capacity(); - +fn from_to_string() { + let orig = "hello,world!"; + let orig_owned = orig.to_string(); + let orig_cap = orig_owned.capacity(); + // Converted to an RString - let copy=orig.into_::(); + let copy = orig.into_::(); - assert_eq!(&orig[..],©[..]); + assert_eq!(&orig[..], ©[..]); - assert_eq!(copy.capacity(),orig_cap); + assert_eq!(copy.capacity(), orig_cap); // Converted back to the original - let orig_back=copy.into_::(); + let orig_back = copy.into_::(); - assert_eq!(&orig_back[..],orig); - assert_eq!(orig_back.capacity(),orig_cap); + assert_eq!(&orig_back[..], orig); + assert_eq!(orig_back.capacity(), orig_cap); } #[test] @@ -51,75 +49,80 @@ fn push() { } #[test] -fn insert_str(){ +fn insert_str() { // '💔' is 4 bytes long - let test_str="💔love💔is💔"; - let rstr=test_str.into_::(); - + let test_str = "💔love💔is💔"; + let rstr = test_str.into_::(); + { - let mut rstr=rstr.clone(); - must_panic(file_span!(),|| rstr.insert_str(1,"foo") ).unwrap(); - must_panic(file_span!(),|| rstr.insert_str(2,"foo") ).unwrap(); - must_panic(file_span!(),|| rstr.insert_str(3,"foo") ).unwrap(); - - must_panic(file_span!(),|| rstr.insert_str(9,"foo") ).unwrap(); - must_panic(file_span!(),|| rstr.insert_str(10,"foo") ).unwrap(); - must_panic(file_span!(),|| rstr.insert_str(11,"foo") ).unwrap(); - - must_panic(file_span!(),|| rstr.insert_str(15,"foo") ).unwrap(); - must_panic(file_span!(),|| rstr.insert_str(16,"foo") ).unwrap(); - must_panic(file_span!(),|| rstr.insert_str(17,"foo") ).unwrap(); + let mut rstr = rstr.clone(); + must_panic(file_span!(), || rstr.insert_str(1, "foo")).unwrap(); + must_panic(file_span!(), || rstr.insert_str(2, "foo")).unwrap(); + must_panic(file_span!(), || rstr.insert_str(3, "foo")).unwrap(); + + must_panic(file_span!(), || rstr.insert_str(9, "foo")).unwrap(); + must_panic(file_span!(), || rstr.insert_str(10, "foo")).unwrap(); + must_panic(file_span!(), || rstr.insert_str(11, "foo")).unwrap(); + + must_panic(file_span!(), || rstr.insert_str(15, "foo")).unwrap(); + must_panic(file_span!(), || rstr.insert_str(16, "foo")).unwrap(); + must_panic(file_span!(), || rstr.insert_str(17, "foo")).unwrap(); } - {// insert at the end - let mut rstr=rstr.clone(); - rstr.insert_str(18,"💔love💔is💔foo"); + { + // insert at the end + let mut rstr = rstr.clone(); + rstr.insert_str(18, "💔love💔is💔foo"); } - {// insert at the start - let mut rstr=rstr.clone(); - rstr.insert_str(0,"foo💔love💔is💔"); + { + // insert at the start + let mut rstr = rstr.clone(); + rstr.insert_str(0, "foo💔love💔is💔"); } - {// insert in the middle - let mut rstr=rstr.clone(); - rstr.insert_str(12,"💔love💔foois💔"); + { + // insert in the middle + let mut rstr = rstr.clone(); + rstr.insert_str(12, "💔love💔foois💔"); } - {// insert in the middle 2 - let mut rstr=rstr.clone(); - rstr.insert_str(14,"💔love💔isfoo💔"); + { + // insert in the middle 2 + let mut rstr = rstr.clone(); + rstr.insert_str(14, "💔love💔isfoo💔"); } } #[test] -fn remove(){ +fn remove() { // '💔' is 4 bytes long - let test_str="💔love💔is💔💔love💔is💔"; - let test_str_nohearts=test_str.chars().filter(|&c| c!='💔' ).collect::(); - let mut rstr=test_str.into_::(); - - must_panic(file_span!(),|| rstr.remove(1) ).unwrap(); - must_panic(file_span!(),|| rstr.remove(9) ).unwrap(); - must_panic(file_span!(),|| rstr.remove(10) ).unwrap(); - must_panic(file_span!(),|| rstr.remove(11) ).unwrap(); - must_panic(file_span!(),|| rstr.remove(15) ).unwrap(); - must_panic(file_span!(),|| rstr.remove(16) ).unwrap(); - must_panic(file_span!(),|| rstr.remove(17) ).unwrap(); - must_panic(file_span!(),|| rstr.remove(test_str.len()-3) ).unwrap(); - must_panic(file_span!(),|| rstr.remove(test_str.len()-2) ).unwrap(); - must_panic(file_span!(),|| rstr.remove(test_str.len()-1) ).unwrap(); - must_panic(file_span!(),|| rstr.remove(test_str.len()) ).unwrap(); - - assert_eq!(rstr.remove(32),'💔'); - assert_eq!(rstr.remove(26),'💔'); - assert_eq!(rstr.remove(18),'💔'); - assert_eq!(rstr.remove(14),'💔'); - assert_eq!(rstr.remove(8),'💔'); - assert_eq!(rstr.remove(0),'💔'); - - assert_eq!(&*rstr,&*test_str_nohearts); - - {// Removing from the end - let mut rstr=rstr.clone(); + let test_str = "💔love💔is💔💔love💔is💔"; + let test_str_nohearts = test_str.chars().filter(|&c| c != '💔').collect::(); + let mut rstr = test_str.into_::(); + + must_panic(file_span!(), || rstr.remove(1)).unwrap(); + must_panic(file_span!(), || rstr.remove(9)).unwrap(); + must_panic(file_span!(), || rstr.remove(10)).unwrap(); + must_panic(file_span!(), || rstr.remove(11)).unwrap(); + must_panic(file_span!(), || rstr.remove(15)).unwrap(); + must_panic(file_span!(), || rstr.remove(16)).unwrap(); + must_panic(file_span!(), || rstr.remove(17)).unwrap(); + must_panic(file_span!(), || rstr.remove(test_str.len() - 3)).unwrap(); + must_panic(file_span!(), || rstr.remove(test_str.len() - 2)).unwrap(); + must_panic(file_span!(), || rstr.remove(test_str.len() - 1)).unwrap(); + must_panic(file_span!(), || rstr.remove(test_str.len())).unwrap(); + + assert_eq!(rstr.remove(32), '💔'); + assert_eq!(rstr.remove(26), '💔'); + assert_eq!(rstr.remove(18), '💔'); + assert_eq!(rstr.remove(14), '💔'); + assert_eq!(rstr.remove(8), '💔'); + assert_eq!(rstr.remove(0), '💔'); + + assert_eq!(&*rstr, &*test_str_nohearts); + + { + // Removing from the end + let mut rstr = rstr.clone(); for i in (0..rstr.len()).rev() { assert_eq!( @@ -129,8 +132,9 @@ fn remove(){ } } - {// Removing from the start - let mut rstr=rstr.clone(); + { + // Removing from the start + let mut rstr = rstr.clone(); for i in 0..rstr.len() { assert_eq!( @@ -154,56 +158,55 @@ fn push_str() { } } - #[test] -fn retain(){ - let retain_test_str="abcd💔01💔efg💔23"; +fn retain() { + let retain_test_str = "abcd💔01💔efg💔23"; let rstr = retain_test_str.into_::(); - + { - let mut rstr=rstr.clone(); - rstr.retain(|c| c.is_alphabetic() ); + let mut rstr = rstr.clone(); + rstr.retain(|c| c.is_alphabetic()); assert_eq!(&*rstr, "abcdefg"); } { - let mut rstr=rstr.clone(); - rstr.retain(|c| !c.is_alphabetic() ); + let mut rstr = rstr.clone(); + rstr.retain(|c| !c.is_alphabetic()); assert_eq!(&*rstr, "💔01💔💔23"); } { - let mut rstr=rstr.clone(); - rstr.retain(|c| c.is_numeric() ); + let mut rstr = rstr.clone(); + rstr.retain(|c| c.is_numeric()); assert_eq!(&*rstr, "0123"); } { - let mut rstr=rstr.clone(); - rstr.retain(|c| c=='💔' ); + let mut rstr = rstr.clone(); + rstr.retain(|c| c == '💔'); assert_eq!(&*rstr, "💔💔💔"); } { - let mut rstr=rstr.clone(); - rstr.retain(|c| c!='💔' ); + let mut rstr = rstr.clone(); + rstr.retain(|c| c != '💔'); assert_eq!(&*rstr, "abcd01efg23"); } { - let mut i=0; - let closure=move|_|{ - let cond=i%2==0; - i+=1; + let mut i = 0; + let closure = move |_| { + let cond = i % 2 == 0; + i += 1; cond }; - let mut rstr=rstr.clone(); + let mut rstr = rstr.clone(); rstr.retain(closure.clone()); - let mut string=retain_test_str.to_string(); + let mut string = retain_test_str.to_string(); string.retain(closure.clone()); assert_eq!(&*rstr, &*string); } { // Copied from: - // https://github.com/rust-lang/rust/blob/48c4afbf9c29880dd946067d1c9aee1e7f75834a/library/alloc/tests/string.rs#L383 + // https://github.com/rust-lang/rust/blob/48c4afbf9c29880dd946067d1c9aee1e7f75834a/library/alloc/tests/string.rs#L383 let mut s = RString::from("0è0"); let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { let mut count = 0; @@ -220,88 +223,82 @@ fn retain(){ } } - #[test] fn into_iter() { - static TEST_STR: &str = - "hello_world.cáscara.ñ.🎊🍕👏😊😀😄😉😉😛😮🙁🙂💔👻😎."; + static TEST_STR: &str = "hello_world.cáscara.ñ.🎊🍕👏😊😀😄😉😉😛😮🙁🙂💔👻😎."; let rstr = TEST_STR.into_::(); assert_eq!(&*rstr, TEST_STR); assert_eq!(&*rstr.clone().into_iter().collect::(), TEST_STR); - let mut iter=rstr.clone().into_iter(); + let mut iter = rstr.clone().into_iter(); - fn compare_str_iter(expecting:&str,iter:&mut IntoIter){ - assert_eq!( - &iter.as_str()[..expecting.len()], - expecting - ); + fn compare_str_iter(expecting: &str, iter: &mut IntoIter) { + assert_eq!(&iter.as_str()[..expecting.len()], expecting); assert_eq!( - &*iter.take(expecting.chars().count()).collect::(), + &*iter.take(expecting.chars().count()).collect::(), expecting, ); } - compare_str_iter("hello_world",&mut iter); - assert_eq!(iter.next(),Some('.')); - - compare_str_iter("cáscara",&mut iter); - assert_eq!(iter.next(),Some('.')); - - compare_str_iter("ñ",&mut iter); - assert_eq!(iter.next(),Some('.')); - - compare_str_iter("🎊🍕👏😊😀😄😉😉😛😮🙁🙂💔👻",&mut iter); - assert_eq!(iter.next(),Some('😎')); - assert_eq!(iter.next(),Some('.')); - - assert_eq!(iter.next(),None); + compare_str_iter("hello_world", &mut iter); + assert_eq!(iter.next(), Some('.')); -} + compare_str_iter("cáscara", &mut iter); + assert_eq!(iter.next(), Some('.')); + + compare_str_iter("ñ", &mut iter); + assert_eq!(iter.next(), Some('.')); + compare_str_iter("🎊🍕👏😊😀😄😉😉😛😮🙁🙂💔👻", &mut iter); + assert_eq!(iter.next(), Some('😎')); + assert_eq!(iter.next(), Some('.')); + + assert_eq!(iter.next(), None); +} #[test] fn drain() { let mut rstr = TEST_STR.into_::(); - let rstr_cap=rstr.capacity(); - - // Using this to test that trying to drain in the middle of a character does not work - let broken_heart_pos=TEST_STR.char_indices().find(|(_,c)| '💔'==*c ).unwrap().0; + let rstr_cap = rstr.capacity(); - must_panic(file_span!(),|| rstr.drain(..TEST_STR.len()+1) ).unwrap(); - must_panic(file_span!(),|| rstr.drain(..broken_heart_pos+1) ).unwrap(); - must_panic(file_span!(),|| rstr.drain(broken_heart_pos..broken_heart_pos+1) ).unwrap(); - must_panic(file_span!(),|| rstr.drain(broken_heart_pos+1..broken_heart_pos+2) ).unwrap(); - must_panic(file_span!(),|| rstr.drain(broken_heart_pos+1..broken_heart_pos+3) ).unwrap(); - must_panic(file_span!(),|| rstr.drain(broken_heart_pos+1..) ).unwrap(); + // Using this to test that trying to drain in the middle of a character does not work + let broken_heart_pos = TEST_STR.char_indices().find(|(_, c)| '💔' == *c).unwrap().0; + + must_panic(file_span!(), || rstr.drain(..TEST_STR.len() + 1)).unwrap(); + must_panic(file_span!(), || rstr.drain(..broken_heart_pos + 1)).unwrap(); + must_panic(file_span!(), || { + rstr.drain(broken_heart_pos..broken_heart_pos + 1) + }) + .unwrap(); + must_panic(file_span!(), || { + rstr.drain(broken_heart_pos + 1..broken_heart_pos + 2) + }) + .unwrap(); + must_panic(file_span!(), || { + rstr.drain(broken_heart_pos + 1..broken_heart_pos + 3) + }) + .unwrap(); + must_panic(file_span!(), || rstr.drain(broken_heart_pos + 1..)).unwrap(); assert_eq!(&rstr.drain(11..).collect::(), &TEST_STR[11..]); - assert_eq!(&rstr[..],"hello_world"); - assert_eq!(rstr.len(),11); - assert_eq!(rstr.capacity(),rstr_cap); - + assert_eq!(&rstr[..], "hello_world"); + assert_eq!(rstr.len(), 11); + assert_eq!(rstr.capacity(), rstr_cap); + rstr.drain(4..8); - assert_eq!(&rstr[..],"hellrld"); - assert_eq!(rstr.len(),7); - assert_eq!(rstr.capacity(),rstr_cap); + assert_eq!(&rstr[..], "hellrld"); + assert_eq!(rstr.len(), 7); + assert_eq!(rstr.capacity(), rstr_cap); rstr.drain(..6); - assert_eq!(&rstr[..],"d"); - assert_eq!(rstr.len(),1); - assert_eq!(rstr.capacity(),rstr_cap); + assert_eq!(&rstr[..], "d"); + assert_eq!(rstr.len(), 1); + assert_eq!(rstr.capacity(), rstr_cap); rstr.drain(..1); - assert_eq!(&rstr[..],""); - assert_eq!(rstr.len(),0); - assert_eq!(rstr.capacity(),rstr_cap); + assert_eq!(&rstr[..], ""); + assert_eq!(rstr.len(), 0); + assert_eq!(rstr.capacity(), rstr_cap); } - - - - - - - - diff --git a/abi_stable/src/std_types/time.rs b/abi_stable/src/std_types/time.rs index 5d32366d..814d60d3 100644 --- a/abi_stable/src/std_types/time.rs +++ b/abi_stable/src/std_types/time.rs @@ -10,11 +10,11 @@ use std::time::Duration; /// /// ``` /// use abi_stable::std_types::RDuration; -/// +/// /// let dur=RDuration::from_millis(31416); /// assert_eq!( dur.as_secs(), 31 ); /// assert_eq!( dur.as_nanos(), 31_416_000_000 ); -/// +/// /// ``` #[derive( Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash, Deserialize, Serialize, StableAbi, @@ -32,11 +32,11 @@ impl RDuration { /// /// ``` /// use abi_stable::std_types::RDuration; - /// + /// /// let dur=RDuration::new(1,456_000_000); /// assert_eq!( dur.as_millis(), 1_456 ); /// assert_eq!( dur.as_micros(), 1_456_000 ); - /// + /// /// ``` pub const fn new(seconds: u64, subsec_nanos: u32) -> Self { Self { @@ -51,14 +51,17 @@ impl RDuration { /// /// ``` /// use abi_stable::std_types::RDuration; - /// + /// /// let dur=RDuration::from_secs(14); /// assert_eq!( dur.as_millis(), 14_000 ); /// assert_eq!( dur.as_micros(), 14_000_000 ); - /// + /// /// ``` - pub const fn from_secs(secs:u64) -> RDuration { - RDuration{ seconds:secs, subsec_nanos:0 } + pub const fn from_secs(secs: u64) -> RDuration { + RDuration { + seconds: secs, + subsec_nanos: 0, + } } /// Creates an RDuration of `milli` milliseconds. @@ -67,11 +70,11 @@ impl RDuration { /// /// ``` /// use abi_stable::std_types::RDuration; - /// + /// /// let dur=RDuration::from_millis(628); /// assert_eq!( dur.as_micros(), 628_000 ); /// assert_eq!( dur.as_nanos(), 628_000_000 ); - /// + /// /// ``` pub const fn from_millis(milli: u64) -> RDuration { RDuration { @@ -86,14 +89,14 @@ impl RDuration { /// /// ``` /// use abi_stable::std_types::RDuration; - /// + /// /// let dur=RDuration::from_micros(1024); /// assert_eq!( dur.as_millis(), 1 ); /// assert_eq!( dur.as_nanos(), 1024_000 ); - /// + /// /// ``` pub const fn from_micros(micro: u64) -> RDuration { - let million=1_000_000; + let million = 1_000_000; RDuration { seconds: micro / million, subsec_nanos: (micro % million) as u32 * 1000, @@ -106,31 +109,31 @@ impl RDuration { /// /// ``` /// use abi_stable::std_types::RDuration; - /// + /// /// let dur=RDuration::from_nanos(128_256_512); /// assert_eq!( dur.as_millis(), 128 ); /// assert_eq!( dur.as_micros(), 128_256 ); - /// + /// /// ``` pub const fn from_nanos(nano: u64) -> RDuration { - let billion=1_000_000_000; + let billion = 1_000_000_000; RDuration { seconds: nano / billion, subsec_nanos: (nano % billion) as u32, } } - /// The amount of fractional nanoseconds (total_nanoseconds % 1_000_000_000) + /// The amount of fractional nanoseconds (total_nanoseconds % 1_000_000_000) /// of this RDuration. /// /// # Example /// /// ``` /// use abi_stable::std_types::RDuration; - /// + /// /// let dur=RDuration::from_nanos(64_128_256_512); /// assert_eq!( dur.subsec_nanos(), 128_256_512 ); - /// + /// /// ``` pub const fn subsec_nanos(&self) -> u32 { self.subsec_nanos @@ -142,10 +145,10 @@ impl RDuration { /// /// ``` /// use abi_stable::std_types::RDuration; - /// + /// /// let dur=RDuration::from_nanos(64_128_256_512); /// assert_eq!( dur.seconds(), 64 ); - /// + /// /// ``` pub const fn seconds(&self) -> u64 { self.seconds @@ -157,10 +160,10 @@ impl RDuration { /// /// ``` /// use abi_stable::std_types::RDuration; - /// + /// /// let dur=RDuration::from_nanos(64_128_256_512); /// assert_eq!( dur.as_secs(), 64 ); - /// + /// /// ``` pub const fn as_secs(&self) -> u64 { self.seconds @@ -172,13 +175,13 @@ impl RDuration { /// /// ``` /// use abi_stable::std_types::RDuration; - /// + /// /// let dur=RDuration::from_nanos(64_128_256_512); /// assert_eq!( dur.as_millis(), 64_128 ); - /// + /// /// ``` pub const fn as_millis(&self) -> u128 { - self.seconds as u128 * 1_000_u128 + (self.subsec_nanos/1_000_000) as u128 + self.seconds as u128 * 1_000_u128 + (self.subsec_nanos / 1_000_000) as u128 } /// The amount of microseconds of this RDuration. @@ -187,13 +190,13 @@ impl RDuration { /// /// ``` /// use abi_stable::std_types::RDuration; - /// + /// /// let dur=RDuration::from_nanos(64_128_256_512); /// assert_eq!( dur.as_micros(), 64_128_256 ); - /// + /// /// ``` pub const fn as_micros(&self) -> u128 { - self.seconds as u128 * 1_000_000_u128 + (self.subsec_nanos/1000) as u128 + self.seconds as u128 * 1_000_000_u128 + (self.subsec_nanos / 1000) as u128 } /// The amount of nanoseconds of this RDuration. @@ -202,10 +205,10 @@ impl RDuration { /// /// ``` /// use abi_stable::std_types::RDuration; - /// + /// /// let dur=RDuration::from_micros(256); /// assert_eq!( dur.as_nanos(), 256_000 ); - /// + /// /// ``` pub const fn as_nanos(&self) -> u128 { self.seconds as u128 * 1_000_000_000_u128 + self.subsec_nanos as u128 diff --git a/abi_stable/src/std_types/tuple.rs b/abi_stable/src/std_types/tuple.rs index 7065dc84..8f28a7df 100644 --- a/abi_stable/src/std_types/tuple.rs +++ b/abi_stable/src/std_types/tuple.rs @@ -7,7 +7,7 @@ Contains ffi-safe equivalents of tuples up to 4 elements. macro_rules! declare_tuple { ( struct_attrs[ $(#[$meta:meta])* ] - + into_tuple_attrs[ $(#[$into_tuple_attrs:meta])* ] $tconstr:ident[$( $tparam:ident ),* $(,)? ] @@ -54,17 +54,17 @@ declare_tuple! { into_tuple_attrs[ /// Converts this Tuple1 to a unary tuple. - /// + /// /// # Example - /// + /// /// ``` /// use abi_stable::std_types::*; - /// + /// /// assert_eq!( Tuple1(1).into_tuple(), (1,) ); - /// + /// /// ``` ] - + Tuple1[ A, ] @@ -77,14 +77,14 @@ declare_tuple! { into_tuple_attrs[ /// Converts this Tuple2 to a pair. - /// + /// /// # Example - /// + /// /// ``` /// use abi_stable::std_types::*; - /// + /// /// assert_eq!( Tuple2(1,2).into_tuple(), (1,2) ); - /// + /// /// ``` ] @@ -101,14 +101,14 @@ declare_tuple! { into_tuple_attrs[ /// Converts this Tuple3 to a 3-tuple. - /// + /// /// # Example - /// + /// /// ``` /// use abi_stable::std_types::*; - /// + /// /// assert_eq!( Tuple3(1,2,3).into_tuple(), (1,2,3) ); - /// + /// /// ``` ] @@ -126,14 +126,14 @@ declare_tuple! { into_tuple_attrs[ /// Converts this Tuple4 to a 4-tuple. - /// + /// /// # Example - /// + /// /// ``` /// use abi_stable::std_types::*; - /// + /// /// assert_eq!( Tuple4(1,2,3,4).into_tuple(), (1,2,3,4) ); - /// + /// /// ``` ] @@ -145,27 +145,25 @@ declare_tuple! { ] } - - #[cfg(test)] -mod tests{ +mod tests { use super::*; #[test] - fn value_macro(){ + fn value_macro() { assert_eq!(rtuple!(), ()); assert_eq!(rtuple!(3), Tuple1(3)); - assert_eq!(rtuple!(3,5), Tuple2(3,5)); - assert_eq!(rtuple!(3,5,8), Tuple3(3,5,8)); - assert_eq!(rtuple!(3,5,8,9), Tuple4(3,5,8,9)); + assert_eq!(rtuple!(3, 5), Tuple2(3, 5)); + assert_eq!(rtuple!(3, 5, 8), Tuple3(3, 5, 8)); + assert_eq!(rtuple!(3, 5, 8, 9), Tuple4(3, 5, 8, 9)); } #[test] - fn type_macro(){ - let _:RTuple!()=(); - let _:RTuple!(i32)=Tuple1(3); - let _:RTuple!(i32,i32,)=Tuple2(3,5); - let _:RTuple!(i32,i32,u32,)=Tuple3(3,5,8); - let _:RTuple!(i32,i32,u32,u32)=Tuple4(3,5,8,9); + fn type_macro() { + let _: RTuple!() = (); + let _: RTuple!(i32) = Tuple1(3); + let _: RTuple!(i32, i32,) = Tuple2(3, 5); + let _: RTuple!(i32, i32, u32,) = Tuple3(3, 5, 8); + let _: RTuple!(i32, i32, u32, u32) = Tuple4(3, 5, 8, 9); } -} \ No newline at end of file +} diff --git a/abi_stable/src/std_types/utypeid.rs b/abi_stable/src/std_types/utypeid.rs index fed53353..f7d41d5f 100644 --- a/abi_stable/src/std_types/utypeid.rs +++ b/abi_stable/src/std_types/utypeid.rs @@ -11,10 +11,7 @@ use std::{ sync::atomic::AtomicUsize, }; -use crate::{ - EXECUTABLE_IDENTITY, - sabi_types::MaybeCmp, -}; +use crate::{sabi_types::MaybeCmp, EXECUTABLE_IDENTITY}; /////////////////////////////////////////////////////////////////////////////// @@ -46,7 +43,6 @@ where UTypeId::new::() } - #[doc(hidden)] pub extern "C" fn some_utypeid() -> MaybeCmp where @@ -55,13 +51,11 @@ where MaybeCmp::Just(UTypeId::new::()) } - #[doc(hidden)] -pub extern "C" fn no_utypeid() -> MaybeCmp{ +pub extern "C" fn no_utypeid() -> MaybeCmp { MaybeCmp::Nothing } - /// An ffi-safe equivalent of `std::any::TypeId` that /// can compare types across dynamic libraries. /// @@ -88,10 +82,8 @@ pub struct UTypeId { type_id_array: [u8; MAX_TYPE_ID_SIZE], } - -unsafe impl Send for UTypeId{} -unsafe impl Sync for UTypeId{} - +unsafe impl Send for UTypeId {} +unsafe impl Sync for UTypeId {} impl UTypeId { /// Constructs `UTypeId` from a type that satisfies the `'static` bound. @@ -179,4 +171,3 @@ impl Hasher for TypeIdHasher { 0 } } - diff --git a/abi_stable/src/std_types/vec.rs b/abi_stable/src/std_types/vec.rs index c177c809..bc7b20a8 100644 --- a/abi_stable/src/std_types/vec.rs +++ b/abi_stable/src/std_types/vec.rs @@ -3,7 +3,7 @@ Contains an ffi-safe equivalent of `Vec`. */ use std::{ - borrow::{Cow,Borrow,BorrowMut}, + borrow::{Borrow, BorrowMut, Cow}, cmp::Ordering, io, iter::FromIterator, @@ -18,9 +18,12 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer}; use core_extensions::{SelfOps, SliceExt}; use crate::{ + prefix_type::{PrefixTypeTrait, WithMetadata}, sabi_types::Constructor, - std_types::{RSlice, RSliceMut,utypeid::{UTypeId,new_utypeid}}, - prefix_type::{PrefixTypeTrait,WithMetadata}, + std_types::{ + utypeid::{new_utypeid, UTypeId}, + RSlice, RSliceMut, + }, }; #[cfg(test)] @@ -29,45 +32,45 @@ mod tests; mod iters; -use self::iters::{RawValIter,DrainFilter}; +use self::iters::{DrainFilter, RawValIter}; pub use self::iters::{Drain, IntoIter}; mod private { use super::*; - -/** -Ffi-safe equivalent of `std::vec::Vec`. -# Example + /** + Ffi-safe equivalent of `std::vec::Vec`. -Here is a function that partitions numbers by whether they are even or odd. + # Example -``` + Here is a function that partitions numbers by whether they are even or odd. -use abi_stable::{ - std_types::{RSlice,RVec}, - StableAbi, - sabi_extern_fn, -}; + ``` -#[repr(C)] -#[derive(StableAbi)] -pub struct Partitioned{ - pub even:RVec, - pub odd :RVec, -} + use abi_stable::{ + std_types::{RSlice,RVec}, + StableAbi, + sabi_extern_fn, + }; + + #[repr(C)] + #[derive(StableAbi)] + pub struct Partitioned{ + pub even:RVec, + pub odd :RVec, + } -#[sabi_extern_fn] -pub fn partition_evenness(numbers:RSlice<'_,u32>)->Partitioned{ - let (even,odd)=numbers.iter().cloned().partition(|n| *n % 2 == 0); + #[sabi_extern_fn] + pub fn partition_evenness(numbers:RSlice<'_,u32>)->Partitioned{ + let (even,odd)=numbers.iter().cloned().partition(|n| *n % 2 == 0); - Partitioned{even,odd} -} + Partitioned{even,odd} + } -``` + ``` -*/ + */ #[repr(C)] #[derive(StableAbi)] // #[sabi(debug_print)] @@ -96,7 +99,7 @@ pub fn partition_evenness(numbers:RSlice<'_,u32>)->Partitioned{ Self::NEW } - const NEW:Self={ + const NEW: Self = { // unsafety: // While this implementation is correct, // it would be better to do `RVec::from_vec(Vec::new())` @@ -105,7 +108,7 @@ pub fn partition_evenness(numbers:RSlice<'_,u32>)->Partitioned{ vtable: VTableGetter::::LIB_VTABLE, buffer: std::mem::align_of::() as *mut T, length: 0, - capacity: 0_usize.wrapping_sub((std::mem::size_of::()==0)as usize), + capacity: 0_usize.wrapping_sub((std::mem::size_of::() == 0) as usize), _marker: PhantomData, } }; @@ -118,7 +121,7 @@ pub fn partition_evenness(numbers:RSlice<'_,u32>)->Partitioned{ } #[inline(always)] - pub(super) fn vtable(&self) -> VecVTable_Ref{ + pub(super) fn vtable(&self) -> VecVTable_Ref { self.vtable } @@ -126,7 +129,7 @@ pub fn partition_evenness(numbers:RSlice<'_,u32>)->Partitioned{ pub(super) fn buffer(&self) -> *const T { self.buffer } - + pub(super) fn buffer_mut(&mut self) -> *mut T { self.buffer } @@ -162,11 +165,8 @@ pub fn partition_evenness(numbers:RSlice<'_,u32>)->Partitioned{ { unsafe { let mut old = mem::replace(self, RVec::new()).piped(ManuallyDrop::new); - let mut list = Vec::::from_raw_parts( - old.buffer_mut(), - old.len(), - old.capacity() - ); + let mut list = + Vec::::from_raw_parts(old.buffer_mut(), old.len(), old.capacity()); let ret = f(&mut list); ptr::write(self, list.into()); ret @@ -175,12 +175,12 @@ pub fn partition_evenness(numbers:RSlice<'_,u32>)->Partitioned{ /// Gets a raw pointer to the start of this RVec's buffer. #[inline(always)] - pub const fn as_ptr(&self) -> *const T{ + pub const fn as_ptr(&self) -> *const T { self.buffer } /// Gets a mutable raw pointer to the start of this RVec's buffer. #[inline(always)] - pub fn as_mut_ptr(&mut self) -> *mut T{ + pub fn as_mut_ptr(&mut self) -> *mut T { self.buffer } } @@ -198,13 +198,11 @@ pub fn partition_evenness(numbers:RSlice<'_,u32>)->Partitioned{ } } } - } pub use self::private::RVec; impl RVec { - /// Creates a new,empty `RVec`,with a capacity of `cap`. /// /// This function does not allocate if `cap == 0`. @@ -255,7 +253,7 @@ impl RVec { (&self[range]).into() } - /// Creates an `RSliceMut<'a,T>` with access to the `range` range of + /// Creates an `RSliceMut<'a,T>` with access to the `range` range of /// elements of the `RVec`. /// /// # Example @@ -323,7 +321,7 @@ impl RVec { /// /// ``` pub const fn as_rslice(&self) -> RSlice<'_, T> { - unsafe{ RSlice::from_raw_parts(self.as_ptr(),self.len()) } + unsafe { RSlice::from_raw_parts(self.as_ptr(), self.len()) } } /// Creates an `RSliceMut<'_,T>` with access to all the elements of the `RVec`. @@ -454,7 +452,7 @@ impl RVec { /// use abi_stable::std_types::RVec; /// /// let mut list=RVec::::new(); - /// + /// /// list.push(0); /// list.push(1); /// list.push(2); @@ -466,10 +464,10 @@ impl RVec { let mut this = ManuallyDrop::new(self); unsafe { - let this_vtable =this.vtable(); - let other_vtable=VTableGetter::LIB_VTABLE; - if ::std::ptr::eq(this_vtable.0.to_raw_ptr() ,other_vtable.0.to_raw_ptr())|| - this_vtable.type_id()==other_vtable.type_id() + let this_vtable = this.vtable(); + let other_vtable = VTableGetter::LIB_VTABLE; + if ::std::ptr::eq(this_vtable.0.to_raw_ptr(), other_vtable.0.to_raw_ptr()) + || this_vtable.type_id() == other_vtable.type_id() { Vec::from_raw_parts(this.buffer_mut(), this.len(), this.capacity()) } else { @@ -492,7 +490,7 @@ impl RVec { /// use abi_stable::std_types::RVec; /// /// let mut list=RVec::::new(); - /// + /// /// list.extend( (4..=7).rev() ); /// /// assert_eq!(list.to_vec(), vec![7,6,5,4] ); @@ -517,18 +515,18 @@ impl RVec { /// /// let slic=&[99,88,77,66]; /// let list=RVec::::from_slice(slic); - /// + /// /// assert_eq!(list.as_slice(),slic); /// ``` #[inline] - pub fn from_slice(slic:&[T])->RVec + pub fn from_slice(slic: &[T]) -> RVec where - T:Clone + T: Clone, { slic.into() } - /// Inserts the `value` value at `index` position. + /// Inserts the `value` value at `index` position. /// /// # Panics /// @@ -560,7 +558,7 @@ impl RVec { } unsafe { - let buffer=self.buffer_mut(); + let buffer = self.buffer_mut(); if index < self.length { ptr::copy( buffer.offset(index as isize), @@ -594,7 +592,7 @@ impl RVec { return None; } unsafe { - let buffer=self.buffer_mut(); + let buffer = self.buffer_mut(); self.length -= 1; let result = ptr::read(buffer.offset(index as isize)); ptr::copy( @@ -781,11 +779,9 @@ impl RVec { self.truncate_inner(0); } - - /// Retains only the elements that satisfy the `pred` predicate /// - /// This means that a element will be removed if `pred(that_element)` + /// This means that a element will be removed if `pred(that_element)` /// returns false. /// /// # Example @@ -806,11 +802,12 @@ impl RVec { /// /// ``` pub fn retain(&mut self, mut pred: F) - where F: FnMut(&T) -> bool + where + F: FnMut(&T) -> bool, { let old_len = self.len(); - unsafe { - self.set_len(0); + unsafe { + self.set_len(0); } DrainFilter { vec_len: &mut self.length, @@ -827,9 +824,10 @@ impl RVec { let old_length = self.length; self.length = to; unsafe { - ptr::drop_in_place( - std::slice::from_raw_parts_mut(self.buffer.add(to), old_length - to) - ) + ptr::drop_in_place(std::slice::from_raw_parts_mut( + self.buffer.add(to), + old_length - to, + )) } } @@ -856,7 +854,7 @@ impl RVec { } /// Reserves `àdditional` additional capacity for extra elements. - /// + /// /// Prefer using `reserve` for most situations. /// /// # Example @@ -909,13 +907,13 @@ where /// /// list.resize(5,88); /// assert_eq!( list.as_slice(), &[88,88,88,88,88] ); - /// + /// /// list.resize(3,0); /// assert_eq!( list.as_slice(), &[88,88,88] ); - /// + /// /// list.resize(6,123); /// assert_eq!( list.as_slice(), &[88,88,88,123,123,123] ); - /// + /// /// ``` pub fn resize(&mut self, new_len: usize, value: T) { let old_len = self.len(); @@ -927,14 +925,14 @@ where // Using new_len instead of the capacity because resize_capacity may // grow the capacity more than requested. // - // Also replaced usage of slice with raw pointers based on a + // Also replaced usage of slice with raw pointers based on a // comment mentioning how slices must only reference initialized memory. - let start=self.buffer_mut(); - let mut current=start.add(old_len); - let end=start.add(new_len); - while current!=end { + let start = self.buffer_mut(); + let mut current = start.add(old_len); + let end = start.add(new_len); + while current != end { ptr::write(current, value.clone()); - current=current.add(1); + current = current.add(1); } self.length = new_len; }, @@ -952,7 +950,7 @@ where /// /// list.extend_from_slice(&[99,88]); /// list.extend_from_slice(&[77,66]); - /// + /// /// assert_eq!( list.as_slice(), &[99,88,77,66] ); /// ``` pub fn extend_from_slice(&mut self, slic_: &[T]) { @@ -981,8 +979,8 @@ where /// /// list.extend_from_slice(&["foo".into_c(), "bar".into()]); /// list.extend_from_slice(&["baz".into_c(), "goo".into()]); - /// - /// assert_eq!( + /// + /// assert_eq!( /// list.as_slice(), /// &["foo".into_c(), "bar".into(), "baz".into(), "goo".into()], /// ); @@ -991,7 +989,7 @@ where self.reserve(slic_.len()); let old_len = self.len(); unsafe { - let entire:*mut T = self.buffer_mut().offset(old_len as isize); + let entire: *mut T = self.buffer_mut().offset(old_len as isize); ptr::copy_nonoverlapping(slic_.as_ptr(), entire, slic_.len()); self.length = old_len + slic_.len(); } @@ -1052,7 +1050,7 @@ impl BorrowMut<[T]> for RVec { } } -slice_like_impl_cmp_traits!{ +slice_like_impl_cmp_traits! { impl[] RVec, where[]; Vec, @@ -1063,13 +1061,13 @@ slice_like_impl_cmp_traits!{ } #[cfg(feature = "const_params")] -slice_like_impl_cmp_traits!{ +slice_like_impl_cmp_traits! { impl[const N: usize] RVec, where[]; [U; N], } -slice_like_impl_cmp_traits!{ +slice_like_impl_cmp_traits! { impl[] RVec, where[T: Clone, U: Clone]; std::borrow::Cow<'_, [U]>, @@ -1147,51 +1145,50 @@ where ///////////////////////////////////////////////////////////////////////////////////// impl RVec { - /** -Creates a draining iterator that removes the specified range in -the `RVec` and yields the removed items. + Creates a draining iterator that removes the specified range in + the `RVec` and yields the removed items. -# Panic + # Panic -Panics if the index is out of bounds or if the start of the range is -greater than the end of the range. + Panics if the index is out of bounds or if the start of the range is + greater than the end of the range. -# Consumption + # Consumption -The elements in the range will be removed even if the iterator -was dropped before yielding them. + The elements in the range will be removed even if the iterator + was dropped before yielding them. -# Example + # Example -``` -use abi_stable::std_types::{RSlice,RVec}; + ``` + use abi_stable::std_types::{RSlice,RVec}; -{ - let mut list=RVec::from(vec![0,1,2,3,4,5]); - assert_eq!( list.drain(2..4).collect::>(), vec![2,3] ); - assert_eq!( list.as_slice(), &[0,1,4,5] ); -} -{ - let mut list=RVec::from(vec![0,1,2,3,4,5]); - assert_eq!( list.drain(2..).collect::>(), vec![2,3,4,5] ); - assert_eq!( list.as_slice(), &[0,1] ); -} -{ - let mut list=RVec::from(vec![0,1,2,3,4,5]); - assert_eq!( list.drain(..2).collect::>(), vec![0,1] ); - assert_eq!( list.as_slice(), &[2,3,4,5] ); -} -{ - let mut list=RVec::from(vec![0,1,2,3,4,5]); - assert_eq!( list.drain(..).collect::>(), vec![0,1,2,3,4,5] ); - assert_eq!( list.as_rslice(), RSlice::::EMPTY ); -} + { + let mut list=RVec::from(vec![0,1,2,3,4,5]); + assert_eq!( list.drain(2..4).collect::>(), vec![2,3] ); + assert_eq!( list.as_slice(), &[0,1,4,5] ); + } + { + let mut list=RVec::from(vec![0,1,2,3,4,5]); + assert_eq!( list.drain(2..).collect::>(), vec![2,3,4,5] ); + assert_eq!( list.as_slice(), &[0,1] ); + } + { + let mut list=RVec::from(vec![0,1,2,3,4,5]); + assert_eq!( list.drain(..2).collect::>(), vec![0,1] ); + assert_eq!( list.as_slice(), &[2,3,4,5] ); + } + { + let mut list=RVec::from(vec![0,1,2,3,4,5]); + assert_eq!( list.drain(..).collect::>(), vec![0,1,2,3,4,5] ); + assert_eq!( list.as_rslice(), RSlice::::EMPTY ); + } -``` + ``` - */ + */ pub fn drain(&mut self, index: I) -> Drain<'_, T> where [T]: IndexMut, @@ -1230,7 +1227,7 @@ impl IntoIterator for RVec { let len = _buf.length; let ptr = _buf.buffer; let iter = RawValIter::new(ptr, len); - IntoIter {iter, _buf} + IntoIter { iter, _buf } } } } @@ -1302,8 +1299,6 @@ impl io::Write for RVec { //////////////////////////////////////////////////////////////////////////////// - - #[repr(C)] #[derive(Debug, Copy, Clone, PartialEq, StableAbi)] enum Exactness { @@ -1319,23 +1314,23 @@ enum Exactness { struct VTableGetter<'a, T>(&'a T); impl<'a, T: 'a> VTableGetter<'a, T> { - const DEFAULT_VTABLE:VecVTable=VecVTable{ - type_id:Constructor( new_utypeid::> ), + const DEFAULT_VTABLE: VecVTable = VecVTable { + type_id: Constructor(new_utypeid::>), destructor: destructor_vec, grow_capacity_to: grow_capacity_to_vec, shrink_to_fit: shrink_to_fit_vec, }; - staticref!{ - const WM_DEFAULT: WithMetadata> = + staticref! { + const WM_DEFAULT: WithMetadata> = WithMetadata::new(PrefixTypeTrait::METADATA, Self::DEFAULT_VTABLE); } // The VTABLE for this type in this executable/library const LIB_VTABLE: VecVTable_Ref = VecVTable_Ref(Self::WM_DEFAULT.as_prefix()); - staticref!{ - const WM_FOR_TESTING: WithMetadata> = + staticref! { + const WM_FOR_TESTING: WithMetadata> = WithMetadata::new( PrefixTypeTrait::METADATA, VecVTable { @@ -1346,9 +1341,8 @@ impl<'a, T: 'a> VTableGetter<'a, T> { } // Used to test functions that change behavior based on the vtable being used - const LIB_VTABLE_FOR_TESTING: VecVTable_Ref = + const LIB_VTABLE_FOR_TESTING: VecVTable_Ref = VecVTable_Ref(Self::WM_FOR_TESTING.as_prefix()); - } #[repr(C)] @@ -1357,14 +1351,13 @@ impl<'a, T: 'a> VTableGetter<'a, T> { #[sabi(missing_field(panic))] // #[sabi(debug_print)] struct VecVTable { - type_id:Constructor, + type_id: Constructor, destructor: extern "C" fn(&mut RVec), grow_capacity_to: extern "C" fn(&mut RVec, usize, Exactness), #[sabi(last_prefix_field)] shrink_to_fit: extern "C" fn(&mut RVec), } - extern "C" fn destructor_vec(this: &mut RVec) { extern_fn_panic_handling! { unsafe { diff --git a/abi_stable/src/std_types/vec/iters.rs b/abi_stable/src/std_types/vec/iters.rs index 04bbb72c..bbde9b17 100644 --- a/abi_stable/src/std_types/vec/iters.rs +++ b/abi_stable/src/std_types/vec/iters.rs @@ -29,25 +29,21 @@ impl RawValIter { } } - fn calculate_length(&self)->usize{ + fn calculate_length(&self) -> usize { let elem_size = mem::size_of::(); let distance = self.end as usize - self.start as usize; let stride_size = if elem_size == 0 { 1 } else { elem_size }; distance / stride_size } - fn as_slice(&self)->&[T]{ - let len=self.calculate_length(); - unsafe{ - unsafe { ::std::slice::from_raw_parts(self.start,len ) } - } + fn as_slice(&self) -> &[T] { + let len = self.calculate_length(); + unsafe { unsafe { ::std::slice::from_raw_parts(self.start, len) } } } - fn as_mut_slice(&mut self)->&mut [T]{ - let len=self.calculate_length(); - unsafe{ - unsafe { ::std::slice::from_raw_parts_mut(self.start as *mut T,len ) } - } + fn as_mut_slice(&mut self) -> &mut [T] { + let len = self.calculate_length(); + unsafe { unsafe { ::std::slice::from_raw_parts_mut(self.start as *mut T, len) } } } } @@ -102,8 +98,7 @@ pub struct IntoIter { pub(super) iter: RawValIter, } - -impl IntoIter{ +impl IntoIter { /// Returns a slice over the remainder of the `Vec` that is being iterated over. /// /// # Example @@ -122,7 +117,7 @@ impl IntoIter{ /// assert_eq!( iter.as_slice(), &[1,2] ); /// /// ``` - pub fn as_slice(&self)->&[T]{ + pub fn as_slice(&self) -> &[T] { self.iter.as_slice() } @@ -144,7 +139,7 @@ impl IntoIter{ /// assert_eq!( iter.as_mut_slice(), &mut [1,2] ); /// /// ``` - pub fn as_mut_slice(&mut self)->&mut [T]{ + pub fn as_mut_slice(&mut self) -> &mut [T] { self.iter.as_mut_slice() } } @@ -188,7 +183,7 @@ pub struct Drain<'a, T> { pub(super) slice_len: usize, } -impl<'a,T> Drain<'a,T>{ +impl<'a, T> Drain<'a, T> { /// Returns a slice over the remainder of the `Vec` that is being drained. /// /// # Example @@ -212,7 +207,7 @@ impl<'a,T> Drain<'a,T>{ /// assert_eq!(list.as_slice(),&[0,1,2,7]); /// /// ``` - pub fn as_slice(&self)->&[T]{ + pub fn as_slice(&self) -> &[T] { self.iter.as_slice() } @@ -239,7 +234,7 @@ impl<'a,T> Drain<'a,T>{ /// assert_eq!(list.as_slice(),&[0,1,2,7]); /// /// ``` - pub fn as_mut_slice(&mut self)->&mut [T]{ + pub fn as_mut_slice(&mut self) -> &mut [T] { self.iter.as_mut_slice() } } @@ -266,24 +261,22 @@ impl<'a, T> Drop for Drain<'a, T> { unsafe { let removed_start = self.removed_start; let removed_end = self.removed_start.offset(self.slice_len as isize); - let end_index = - distance_from(self.allocation_start, removed_start).unwrap_or(0)+self.slice_len; + let end_index = + distance_from(self.allocation_start, removed_start).unwrap_or(0) + self.slice_len; ptr::copy(removed_end, removed_start, self.len - end_index); *self.vec_len = self.len - self.slice_len; } } } - /////////////////////////////////////////////////// - - // copy of the std library DrainFilter, without the allocator parameter. // (from rustc 1.50.0-nightly (eb4fc71dc 2020-12-17)) #[derive(Debug)] pub(crate) struct DrainFilter<'a, T, F> - where F: FnMut(&mut T) -> bool, +where + F: FnMut(&mut T) -> bool, { // pub(super) vec: &'a mut RVec, pub(super) allocation_start: *mut T, diff --git a/abi_stable/src/std_types/vec/tests.rs b/abi_stable/src/std_types/vec/tests.rs index fa79c8fe..1e557650 100644 --- a/abi_stable/src/std_types/vec/tests.rs +++ b/abi_stable/src/std_types/vec/tests.rs @@ -2,7 +2,7 @@ use super::*; use abi_stable_shared::file_span; -use std::{iter,sync::Arc}; +use std::{iter, sync::Arc}; #[allow(unused_imports)] use core_extensions::SelfOps; @@ -26,7 +26,7 @@ fn vec_drain() { ($range:expr,$after_drain:expr) => { let range = $range; { - let after_drain:Vec=$after_drain; + let after_drain: Vec = $after_drain; let mut list = list.clone(); let list_2 = list.drain(range.clone()).collect::>(); assert_eq!(&*list_2, &original[range.clone()], ""); @@ -128,7 +128,7 @@ fn push_pop() { assert_eq!(&*list, &[10]); assert_eq!(list.pop(), Some(10)); - assert_eq!(&*list, <&[u32]>::default() ); + assert_eq!(&*list, <&[u32]>::default()); assert_eq!(list.pop(), None); } @@ -164,77 +164,62 @@ fn truncate() { } #[test] -fn retain(){ +fn retain() { let orig = vec![2, 3, 4, 5, 6, 7, 8]; let copy = orig.clone().piped(RVec::from); { - let mut copy=copy.clone(); - copy.retain(|&v| v%2==0 ); - assert_eq!( - &*copy, - &[2,4,6,8][..] - ); + let mut copy = copy.clone(); + copy.retain(|&v| v % 2 == 0); + assert_eq!(&*copy, &[2, 4, 6, 8][..]); } { - let mut copy=copy.clone(); - copy.retain(|&v| v%2==1 ); - assert_eq!( - &*copy, - &[3,5,7][..] - ); + let mut copy = copy.clone(); + copy.retain(|&v| v % 2 == 1); + assert_eq!(&*copy, &[3, 5, 7][..]); } { - let mut copy=copy.clone(); - copy.retain(|_| true ); - assert_eq!( - &*copy, - &*orig - ); + let mut copy = copy.clone(); + copy.retain(|_| true); + assert_eq!(&*copy, &*orig); } { - let mut copy=copy.clone(); - copy.retain(|_| false ); - assert_eq!( - &*copy, - <&[i32]>::default() - ); + let mut copy = copy.clone(); + copy.retain(|_| false); + assert_eq!(&*copy, <&[i32]>::default()); } { - let mut copy=copy.clone(); - let mut i=0; - copy.retain(|_|{ - let cond=i%2==0; - i+=1; + let mut copy = copy.clone(); + let mut i = 0; + copy.retain(|_| { + let cond = i % 2 == 0; + i += 1; cond }); - assert_eq!( - &*copy, - &[2,4,6,8][..] - ); + assert_eq!(&*copy, &[2, 4, 6, 8][..]); } { - let mut copy=copy.clone(); - let mut i=0; - copy.retain(|_|{ - let cond=i%3==0; - i+=1; + let mut copy = copy.clone(); + let mut i = 0; + copy.retain(|_| { + let cond = i % 3 == 0; + i += 1; cond }); - assert_eq!( - &*copy, - &[2,5,8][..] - ); + assert_eq!(&*copy, &[2, 5, 8][..]); } { - let mut copy=copy.clone(); - let mut i=0; - must_panic(file_span!(), ||{ - copy.retain(|_|{ - i+=1; - if i==4 {panic!()} + let mut copy = copy.clone(); + let mut i = 0; + must_panic(file_span!(), || { + copy.retain(|_| { + i += 1; + if i == 4 { + panic!() + } true }); - }).unwrap(); + }) + .unwrap(); assert_eq!(©[..], &orig[..]); } } @@ -327,16 +312,18 @@ fn into_iter() { } #[test] -fn into_iter_as_str(){ +fn into_iter_as_str() { let mut orig = vec![10, 11, 12, 13]; let mut iter = orig.clone().into_c().into_iter(); - let mut i=0; + let mut i = 0; loop { - assert_eq!(&orig[i..],iter.as_slice()); - assert_eq!(&mut orig[i..],iter.as_mut_slice()); - i+=1; - if iter.next().is_none() {break;} + assert_eq!(&orig[i..], iter.as_slice()); + assert_eq!(&mut orig[i..], iter.as_mut_slice()); + i += 1; + if iter.next().is_none() { + break; + } } } @@ -391,21 +378,19 @@ fn into_vec() { } #[test] -fn rvec_macro(){ +fn rvec_macro() { assert_eq!(RVec::::new(), rvec![]); assert_eq!(RVec::from(vec![0]), rvec![0]); - assert_eq!(RVec::from(vec![0,3]), rvec![0,3]); - assert_eq!(RVec::from(vec![0,3,6]), rvec![0,3,6]); - assert_eq!(RVec::from(vec![1;10]), rvec![1;10]); + assert_eq!(RVec::from(vec![0, 3]), rvec![0, 3]); + assert_eq!(RVec::from(vec![0, 3, 6]), rvec![0, 3, 6]); + assert_eq!(RVec::from(vec![1; 10]), rvec![1;10]); } -// Adapted from Vec tests +// Adapted from Vec tests // (from rustc 1.50.0-nightly (eb4fc71dc 2020-12-17)) #[test] fn retain_panic() { - use std::rc::Rc; - use std::sync::Mutex; - use std::panic::AssertUnwindSafe; + use std::{panic::AssertUnwindSafe, rc::Rc, sync::Mutex}; struct Check { index: usize, @@ -422,7 +407,10 @@ fn retain_panic() { let check_count = 10; let drop_counts = Rc::new(Mutex::new(rvec![0_usize; check_count])); let mut data: RVec = (0..check_count) - .map(|index| Check { index, drop_counts: Rc::clone(&drop_counts) }) + .map(|index| Check { + index, + drop_counts: Rc::clone(&drop_counts), + }) .collect(); let _ = std::panic::catch_unwind(AssertUnwindSafe(move || { @@ -445,8 +433,10 @@ fn retain_panic() { assert_eq!(check_count, drop_counts.len()); for (index, count) in drop_counts.iter().cloned().enumerate() { - assert_eq!(1, count, "unexpected drop count at index: {} (count: {})", index, count); + assert_eq!( + 1, count, + "unexpected drop count at index: {} (count: {})", + index, count + ); } } - - diff --git a/abi_stable/src/test_utils.rs b/abi_stable/src/test_utils.rs index 274cfca7..0d8ad390 100644 --- a/abi_stable/src/test_utils.rs +++ b/abi_stable/src/test_utils.rs @@ -6,98 +6,84 @@ use std::{ }; #[allow(unused_imports)] -pub use abi_stable_shared::test_utils::{ - FileSpan, - ThreadError, - ShouldHavePanickedAt, - must_panic, -}; +pub use abi_stable_shared::test_utils::{must_panic, FileSpan, ShouldHavePanickedAt, ThreadError}; #[allow(unused_imports)] pub use abi_stable_shared::file_span; - ////////////////////////////////////////////////////////////////// - /// Checks that `left` and `right` produce the exact same Display and Debug output. -pub fn check_formatting_equivalence(left:&T,right:&U) -where - T:Debug+Display+?Sized, - U:Debug+Display+?Sized, +pub fn check_formatting_equivalence(left: &T, right: &U) +where + T: Debug + Display + ?Sized, + U: Debug + Display + ?Sized, { - assert_eq!(format!("{:?}",left), format!("{:?}",right)); - assert_eq!(format!("{:#?}",left), format!("{:#?}",right)); - assert_eq!(format!("{}",left), format!("{}",right)); - assert_eq!(format!("{:#}",left), format!("{:#}",right)); + assert_eq!(format!("{:?}", left), format!("{:?}", right)); + assert_eq!(format!("{:#?}", left), format!("{:#?}", right)); + assert_eq!(format!("{}", left), format!("{}", right)); + assert_eq!(format!("{:#}", left), format!("{:#}", right)); } /// Returns the address this dereferences to. -pub fn deref_address(ptr:&D)->usize +pub fn deref_address(ptr: &D) -> usize where D: ::std::ops::Deref, { - (&**ptr)as *const _ as *const u8 as usize + (&**ptr) as *const _ as *const u8 as usize } - ////////////////////////////////////////////////////////////////// - /// A wrapper type which uses `T`'s Display formatter in its Debug impl #[repr(transparent)] -#[derive(Copy,Clone,PartialEq,Eq,Ord,PartialOrd,Hash,StableAbi)] +#[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash, StableAbi)] pub struct AlwaysDisplay(pub T); -impl Display for AlwaysDisplay +impl Display for AlwaysDisplay where - T:Display + T: Display, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - Display::fmt(&self.0,f) + Display::fmt(&self.0, f) } } - -impl Debug for AlwaysDisplay +impl Debug for AlwaysDisplay where - T:Display + T: Display, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - Display::fmt(&self.0,f) + Display::fmt(&self.0, f) } } ////////////////////////////////////////////////////////////////// - #[derive(Clone)] -pub struct Stringy{ - pub str:String +pub struct Stringy { + pub str: String, } -impl Stringy{ - pub fn new(str:S)->Self - where S:Into +impl Stringy { + pub fn new(str: S) -> Self + where + S: Into, { - Stringy{ - str:str.into(), - } + Stringy { str: str.into() } } } - -impl Debug for Stringy{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Debug::fmt(&self.str,f) +impl Debug for Stringy { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Debug::fmt(&self.str, f) } } -impl Display for Stringy{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Display::fmt(&self.str,f) +impl Display for Stringy { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Display::fmt(&self.str, f) } } -impl ErrorTrait for Stringy{} - +impl ErrorTrait for Stringy {} diff --git a/abi_stable/src/traits.rs b/abi_stable/src/traits.rs index f83e5e63..db26076d 100644 --- a/abi_stable/src/traits.rs +++ b/abi_stable/src/traits.rs @@ -6,17 +6,16 @@ Where miscellaneous traits reside. use core_extensions::SelfOps; use crate::{ - pointer_trait::{CanTransmuteElement,TransmuteElement}, - sabi_types::{RRef, RMut}, + pointer_trait::{CanTransmuteElement, TransmuteElement}, + sabi_types::{RMut, RRef}, }; - /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// /// Converts a `#[repr(Rust)]` type into its `#[repr(C)]` equivalent. -/// +/// /// `#[repr(Rust)]` is the default representation for data types. pub trait IntoReprC { /// The `#[repr(C)]` equivalent. @@ -111,70 +110,57 @@ macro_rules! impl_into_rust_repr { ) } - /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// - - -pub(crate) unsafe trait ErasedType<'a>:Sized{ +pub(crate) unsafe trait ErasedType<'a>: Sized { type Unerased; #[inline] - unsafe fn from_unerased

(p:P)->P::TransmutedPtr - where - P: CanTransmuteElement + unsafe fn from_unerased

(p: P) -> P::TransmutedPtr + where + P: CanTransmuteElement, { p.transmute_element::() } #[inline] - unsafe fn downcast_into

(p:P)->P::TransmutedPtr - where + unsafe fn downcast_into

(p: P) -> P::TransmutedPtr + where P: CanTransmuteElement, { p.transmute_element::() } - #[inline] - unsafe fn run_downcast_as<'b, F,R>(p: RRef<'b, Self>,func:F)->R - where + unsafe fn run_downcast_as<'b, F, R>(p: RRef<'b, Self>, func: F) -> R + where Self::Unerased: 'b, - F:FnOnce(&'b Self::Unerased)->R, + F: FnOnce(&'b Self::Unerased) -> R, { func(p.transmute_into_ref::()) } #[inline] - unsafe fn run_downcast_as_mut<'b, F, R>(p: RMut<'b, Self>,func:F)->R - where + unsafe fn run_downcast_as_mut<'b, F, R>(p: RMut<'b, Self>, func: F) -> R + where Self::Unerased: 'b, - F:FnOnce(&'b mut Self::Unerased)->R, + F: FnOnce(&'b mut Self::Unerased) -> R, { func(p.transmute_into_mut()) } - - } - - /////////////////////////////////////////////////////////////////////////// /// Unwraps a type into its owned value. -pub trait IntoInner{ +pub trait IntoInner { /// The type of the value this owns. type Element; /// Unwraps this type into its owned value. - fn into_inner_(self)->Self::Element; + fn into_inner_(self) -> Self::Element; } - /////////////////////////////////////////////////////////////////////////// - - - - diff --git a/abi_stable/src/type_layout.rs b/abi_stable/src/type_layout.rs index 4f8f9403..ed983deb 100644 --- a/abi_stable/src/type_layout.rs +++ b/abi_stable/src/type_layout.rs @@ -3,35 +3,33 @@ Types for modeling the layout of a datatype */ use std::{ - cmp::{PartialEq,Eq}, cell::RefCell, + cmp::{Eq, PartialEq}, collections::HashSet, fmt::{self, Debug, Display, Formatter}, - mem::{self,ManuallyDrop}, + mem::{self, ManuallyDrop}, }; -use core_extensions::{matches,StringExt}; +use core_extensions::{matches, StringExt}; use crate::{ abi_stability::{ - extra_checks::{StoredExtraChecks,ExtraChecksStaticRef}, - stable_abi_trait::{TypeLayoutCtor,AbiConsts}, + extra_checks::{ExtraChecksStaticRef, StoredExtraChecks}, + stable_abi_trait::{AbiConsts, TypeLayoutCtor}, }, - const_utils::log2_usize, - sabi_types::VersionStrings, - sabi_types::{CmpIgnored,Constructor,NulStr}, - std_types::{RStr,RSlice,UTypeId}, - prefix_type::{FieldAccessibility,FieldConditionality}, + const_utils::log2_usize, + prefix_type::{FieldAccessibility, FieldConditionality}, reflection::ModReflMode, + sabi_types::{CmpIgnored, Constructor, NulStr, VersionStrings}, + std_types::{RSlice, RStr, UTypeId}, }; - mod construction; pub mod data_structures; mod iterators; +mod printing; mod shared_vars; mod small_types; -mod printing; pub mod tagging; mod tl_data; mod tl_enums; @@ -44,167 +42,99 @@ mod tl_other; mod tl_prefix; mod tl_reflection; -pub(crate) use self::{ - iterators::ChainOnce, -}; +pub(crate) use self::iterators::ChainOnce; pub use self::{ - construction::{ - _private_TypeLayoutDerive, - _private_MonoTypeLayoutDerive, - ItemInfo, - }, - shared_vars::{ - SharedVars, - MonoSharedVars, - }, - small_types::{ - StartLen, - StartLenRepr, - StartLenConverter, - OptionU16, - OptionU8, - }, - tl_data::{ - GenericTLData, - MismatchedTLDataVariant, - MonoTLData, - TLData, - TLDataDiscriminant, - }, + construction::{ItemInfo, _private_MonoTypeLayoutDerive, _private_TypeLayoutDerive}, + shared_vars::{MonoSharedVars, SharedVars}, + small_types::{OptionU16, OptionU8, StartLen, StartLenConverter, StartLenRepr}, + tagging::Tag, + tl_data::{GenericTLData, MismatchedTLDataVariant, MonoTLData, TLData, TLDataDiscriminant}, tl_enums::{ - DiscriminantRepr, - GenericTLEnum, - IncompatibleWithNonExhaustive, - IsExhaustive, - MonoTLEnum, - TLDiscriminant, - TLDiscriminants, - TLEnum, - TLNonExhaustive, - MakeTLNonExhaustive, - }, - tl_field::{ - CompTLField, - CompTLFieldRepr, - TLField, - }, - tl_fields::{ - CompTLFields, - TLFields, - TLFieldsIterator, - }, - tl_functions::{ - TLFunctionIter, - TLFunctions, - TLFunctionSlice, - CompTLFunction, - TLFunction, + DiscriminantRepr, GenericTLEnum, IncompatibleWithNonExhaustive, IsExhaustive, + MakeTLNonExhaustive, MonoTLEnum, TLDiscriminant, TLDiscriminants, TLEnum, TLNonExhaustive, }, + tl_field::{CompTLField, CompTLFieldRepr, TLField}, + tl_fields::{CompTLFields, TLFields, TLFieldsIterator}, + tl_functions::{CompTLFunction, TLFunction, TLFunctionIter, TLFunctionSlice, TLFunctions}, tl_lifetimes::{ - LifetimeArrayOrSlice, - LifetimeIndex, - LifetimeIndexArray, - LifetimeIndexPair, - LifetimeIndexPairRepr, - LifetimeRange, - }, - tl_multi_tl::{ - TypeLayoutIndex, - TypeLayoutRange, - MultipleTypeLayouts, - MTLIterator, + LifetimeArrayOrSlice, LifetimeIndex, LifetimeIndexArray, LifetimeIndexPair, + LifetimeIndexPairRepr, LifetimeRange, }, + tl_multi_tl::{MTLIterator, MultipleTypeLayouts, TypeLayoutIndex, TypeLayoutRange}, tl_other::{ - CompGenericParams, - FmtFullType, - GenericParams, - ModPath, - ReprAttr, - TLFieldOrFunction, + CompGenericParams, FmtFullType, GenericParams, ModPath, ReprAttr, TLFieldOrFunction, TLPrimitive, }, - tl_prefix::{ - GenericTLPrefixType, - MonoTLPrefixType, - TLPrefixType, - }, - tl_reflection::{ - CompFieldAccessor, - FieldAccessor, - }, - tagging::Tag, + tl_prefix::{GenericTLPrefixType, MonoTLPrefixType, TLPrefixType}, + tl_reflection::{CompFieldAccessor, FieldAccessor}, }; - //////////////////////////////////////////////////////////////////////////////// - /// The layout of a type, /// also includes metadata about where the type was defined. #[repr(C)] -#[derive(Copy, Clone,StableAbi)] +#[derive(Copy, Clone, StableAbi)] // I am specifically applying this attribute to TypeLayout to make // ExtraChecks take less time checking its own layout. // // Also because checking the layout of TypeLayout is redundant, -// since I have to trust that it's correct to be able to use it +// since I have to trust that it's correct to be able to use it // to check the layout of anything(including itself). #[sabi(unsafe_sabi_opaque_fields)] pub struct TypeLayout { shared_vars: &'static SharedVars, - + /// The parts of the type layout that never change based on generic parameters. - mono:&'static MonoTypeLayout, - + mono: &'static MonoTypeLayout, + /// Whether the type uses non-zero value optimization, /// if true then an Option implements StableAbi. - is_nonzero: bool, + is_nonzero: bool, /// The alignment of the type represented as (1 << self.alignment_power_of_two). alignment_power_of_two: u8, /// The size of the type size: usize, - - tag:Option<&'static Tag>, - data:GenericTLData, - + tag: Option<&'static Tag>, + + data: GenericTLData, + /// A json-like data structure used to add extra checks. - extra_checks:CmpIgnored>>, + extra_checks: CmpIgnored>>, /// A function to get the unique identifier for some type - type_id:Constructor, + type_id: Constructor, } -unsafe impl Send for TypeLayout{} -unsafe impl Sync for TypeLayout{} - -unsafe impl Send for MonoTypeLayout{} -unsafe impl Sync for MonoTypeLayout{} +unsafe impl Send for TypeLayout {} +unsafe impl Sync for TypeLayout {} +unsafe impl Send for MonoTypeLayout {} +unsafe impl Sync for MonoTypeLayout {} /////////////////////////// impl TypeLayout { - pub(crate) const fn from_std( shared_vars: &'static SharedVars, - mono:&'static MonoTypeLayout, - abi_consts:AbiConsts, + mono: &'static MonoTypeLayout, + abi_consts: AbiConsts, data: GenericTLData, ) -> Self { Self { shared_vars, mono, - is_nonzero:abi_consts.is_nonzero, - type_id:abi_consts.type_id, + is_nonzero: abi_consts.is_nonzero, + type_id: abi_consts.type_id, alignment_power_of_two: log2_usize(mem::align_of::()), size: mem::size_of::(), data, - extra_checks:CmpIgnored::new(None), - tag:None, + extra_checks: CmpIgnored::new(None), + tag: None, } } @@ -218,21 +148,21 @@ impl TypeLayout { alignment_power_of_two: log2_usize(mem::align_of::()), size: mem::size_of::(), data: p.data, - extra_checks:CmpIgnored::new(p.extra_checks), - tag:p.tag, + extra_checks: CmpIgnored::new(p.extra_checks), + tag: p.tag, } } /// Gets the SharedVars of the type, /// containing the slices that many types inside TypeLayout contain ranges into. - pub const fn shared_vars(&self)->&'static SharedVars{ + pub const fn shared_vars(&self) -> &'static SharedVars { self.shared_vars } /// Gets a type used to print the type(ie:`Foo<'a,'b,u32,RString,1,2>`) #[doc(hidden)] pub fn full_type(&self) -> FmtFullType { - FmtFullType{ + FmtFullType { name: self.mono.name(), generics: self.generics(), primitive: self.mono.data.to_primitive(), @@ -241,88 +171,85 @@ impl TypeLayout { } /// Gets the package and package version where the type was declared. - pub fn package_and_version(&self)->(RStr<'static>,VersionStrings){ - let (package,version)=self.item_info().package_and_version(); + pub fn package_and_version(&self) -> (RStr<'static>, VersionStrings) { + let (package, version) = self.item_info().package_and_version(); - ( - RStr::from_str(package), - VersionStrings::new(version) - ) + (RStr::from_str(package), VersionStrings::new(version)) } /// Gets the package where the type was declared. - pub fn package(&self)->RStr<'static>{ - let (package,_)=self.item_info().package_and_version(); + pub fn package(&self) -> RStr<'static> { + let (package, _) = self.item_info().package_and_version(); RStr::from_str(package) } /// Gets the package version for the package where the type was declared. - pub fn package_version(&self)->VersionStrings{ - let (_,version)=self.item_info().package_and_version(); + pub fn package_version(&self) -> VersionStrings { + let (_, version) = self.item_info().package_and_version(); VersionStrings::new(version) } /// Gets which line the type was defined in. - pub fn line(&self)->u32{ + pub fn line(&self) -> u32 { self.item_info().line } /// Gets the full path to the module where the type was defined. - pub fn mod_path(&self)->ModPath{ + pub fn mod_path(&self) -> ModPath { self.item_info().mod_path } /// Gets a trait object used to check extra properties about the type. #[inline] - pub fn extra_checks(&self)->Option{ - self.extra_checks.value.map(|x| x.sabi_reborrow() ) + pub fn extra_checks(&self) -> Option { + self.extra_checks.value.map(|x| x.sabi_reborrow()) } -/** -Gets the fields of the type. + /** + Gets the fields of the type. -# Return value + # Return value -If this a: + If this a: -- primitive or opaque type: - It returns `None`. + - primitive or opaque type: + It returns `None`. -- enum: - It returns `Some()` with all the fields in the order that they were declared, - ignoring variants. + - enum: + It returns `Some()` with all the fields in the order that they were declared, + ignoring variants. -- structs/unions/prefix types: - It returns `Some()` with all the fields in the order that they were declared. + - structs/unions/prefix types: + It returns `Some()` with all the fields in the order that they were declared. -*/ - pub fn get_fields(&self)->Option{ - let fields=self.mono.get_fields()?; + */ + pub fn get_fields(&self) -> Option { + let fields = self.mono.get_fields()?; Some(fields.expand(self.shared_vars)) } /// Whether this is a prefix-type(module or vtable). - pub fn is_prefix_kind(&self)->bool{ - matches!(self.data, GenericTLData::PrefixType{..}) + pub fn is_prefix_kind(&self) -> bool { + matches!(self.data, GenericTLData::PrefixType { .. }) } /// Gets the name of the type. #[inline] - pub fn name(&self)->&'static str{ + pub fn name(&self) -> &'static str { self.mono.name() } /// Gets whether the type is a NonZero type, /// which can be put in an `Option` while being ffi-safe. #[inline] - pub fn is_nonzero(&self)->bool{ + pub fn is_nonzero(&self) -> bool { self.is_nonzero } #[doc(hidden)] #[cfg(feature = "testing")] - pub const fn _set_is_nonzero(mut self,is_nonzero:bool)->Self{ - self.is_nonzero=is_nonzero; + pub const fn _set_is_nonzero(mut self, is_nonzero: bool) -> Self { + self.is_nonzero = is_nonzero; self } @@ -330,132 +257,126 @@ If this a: #[cfg(feature = "testing")] pub const fn _set_extra_checks( mut self, - extra_checks:CmpIgnored>> - )->Self{ - self.extra_checks=extra_checks; + extra_checks: CmpIgnored>>, + ) -> Self { + self.extra_checks = extra_checks; self } #[doc(hidden)] #[cfg(feature = "testing")] - pub const fn _set_type_id( - mut self, - type_id:Constructor, - )->Self{ - self.type_id=type_id; + pub const fn _set_type_id(mut self, type_id: Constructor) -> Self { + self.type_id = type_id; self } /// Gets the `UTypeId` for the type, /// which is an ffi safe equivalent of `TypeId`. #[inline] - pub fn get_utypeid(&self)->UTypeId{ + pub fn get_utypeid(&self) -> UTypeId { self.type_id.get() } /// Gets information about where a type was declared. #[inline] - pub fn item_info(&self)->&ItemInfo{ + pub fn item_info(&self) -> &ItemInfo { &self.mono.item_info() } /// Gets the alignment of the type. #[inline] - pub fn alignment(&self)->usize{ + pub fn alignment(&self) -> usize { 1_usize << (self.alignment_power_of_two as u32) } /// Gets the size of the type. #[inline] - pub fn size(&self)->usize{ + pub fn size(&self) -> usize { self.size } /// Gets the `Tag` associated with a type, - /// a JSON-like datastructure which is another way to + /// a JSON-like datastructure which is another way to /// check extra properties about a type. - pub fn tag(&self)->&'static Tag{ + pub fn tag(&self) -> &'static Tag { self.tag.unwrap_or(Tag::NULL) } /// Gets the representation attribute of the type. - pub fn repr_attr(&self)->ReprAttr{ + pub fn repr_attr(&self) -> ReprAttr { self.mono.repr_attr() } /// Gets the `ModReflMode` for the type, /// whether this is a module whose definition can be reflected on at runtime. - pub const fn mod_refl_mode(&self)->ModReflMode{ + pub const fn mod_refl_mode(&self) -> ModReflMode { self.mono.mod_refl_mode() } /// The interior of the type definition, /// describing whether the type is a primitive/enum/struct/union and its contents. - pub fn data(&self)-> TLData { - self.mono.data - .expand(self.data,self.shared_vars) - .unwrap_or_else(|e|{ - panic!("\nError inside of '{}' type \n{}",self.full_type(),e); + pub fn data(&self) -> TLData { + self.mono + .data + .expand(self.data, self.shared_vars) + .unwrap_or_else(|e| { + panic!("\nError inside of '{}' type \n{}", self.full_type(), e); }) } /// Describes whether the type is a primitive/enum/struct/union, /// every variant corresponds to a `TLData` variant of the same name. - pub fn data_discriminant(&self)-> TLDataDiscriminant { + pub fn data_discriminant(&self) -> TLDataDiscriminant { self.mono.data.as_discriminant() } /// Gets the virtual fields that aren't part of th type definition, /// but are checked as part of the type #[inline] - pub fn phantom_fields(&self)->TLFields{ - unsafe{ - let slice=std::slice::from_raw_parts( + pub fn phantom_fields(&self) -> TLFields { + unsafe { + let slice = std::slice::from_raw_parts( self.mono.phantom_fields, self.mono.phantom_fields_len as usize, ); - TLFields::from_fields(slice,self.shared_vars) + TLFields::from_fields(slice, self.shared_vars) } } /// Gets the generic parameters of the type. - pub fn generics(&self)->GenericParams{ + pub fn generics(&self) -> GenericParams { self.mono.generics.expand(self.shared_vars) } /// Gets the parts of the type layout that don't change with generic parameters. - pub fn mono_type_layout(&self)->&MonoTypeLayout{ + pub fn mono_type_layout(&self) -> &MonoTypeLayout { &self.mono } } - -impl PartialEq for TypeLayout{ - fn eq(&self,other:&TypeLayout)->bool{ - self.get_utypeid()==other.get_utypeid() +impl PartialEq for TypeLayout { + fn eq(&self, other: &TypeLayout) -> bool { + self.get_utypeid() == other.get_utypeid() } } - -impl Eq for TypeLayout{} - +impl Eq for TypeLayout {} //////////////////////////////////////////////////////////////////////////////// - /// The data in the type layout that does not depend on generic parameters. #[repr(C)] -#[derive(Copy, Clone,StableAbi)] +#[derive(Copy, Clone, StableAbi)] #[sabi(unsafe_sabi_opaque_fields)] -pub struct MonoTypeLayout{ - shared_vars:MonoSharedVars, +pub struct MonoTypeLayout { + shared_vars: MonoSharedVars, /// The name of the type. name: *const u8, /// Contains information about where the type was defined. /// - item_info:CmpIgnored, + item_info: CmpIgnored, /// What kind of type this is,Primitive/Struct/Enum/PrefixType. data: MonoTLData, @@ -468,32 +389,31 @@ pub struct MonoTypeLayout{ phantom_fields_len: u8, /// The representation attribute(s) of the type. - repr_attr:ReprAttr, + repr_attr: ReprAttr, /// How the type is treated when interpreted as a module. - mod_refl_mode:ModReflMode, - + mod_refl_mode: ModReflMode, + name_len: u16, } - #[allow(clippy::too_many_arguments)] -impl MonoTypeLayout{ +impl MonoTypeLayout { pub(crate) const fn new( - shared_vars:MonoSharedVars, + shared_vars: MonoSharedVars, name: RStr<'static>, - item_info:ItemInfo, + item_info: ItemInfo, data: MonoTLData, generics: CompGenericParams, - repr_attr:ReprAttr, - mod_refl_mode:ModReflMode, - phantom_fields:RSlice<'static,CompTLField>, - )->Self{ - Self{ + repr_attr: ReprAttr, + mod_refl_mode: ModReflMode, + phantom_fields: RSlice<'static, CompTLField>, + ) -> Self { + Self { shared_vars, - name :name.as_ptr(), - name_len:name.len() as u16, - item_info:CmpIgnored::new(item_info), + name: name.as_ptr(), + name_len: name.len() as u16, + item_info: CmpIgnored::new(item_info), data, generics, repr_attr, @@ -504,12 +424,11 @@ impl MonoTypeLayout{ } #[doc(hidden)] - pub const fn from_derive(p:_private_MonoTypeLayoutDerive)->Self{ - Self{ - name : p.name.as_ptr(), + pub const fn from_derive(p: _private_MonoTypeLayoutDerive) -> Self { + Self { + name: p.name.as_ptr(), name_len: p.name.len() as u16, - phantom_fields : p.phantom_fields.as_ptr() - as *const CompTLFieldRepr + phantom_fields: p.phantom_fields.as_ptr() as *const CompTLFieldRepr as *const CompTLField, phantom_fields_len: p.phantom_fields.len() as u8, item_info: CmpIgnored::new(p.item_info), @@ -522,96 +441,95 @@ impl MonoTypeLayout{ } /// Gets the name of the type. - pub fn name(&self)->&'static str{ - unsafe{ - let slic=std::slice::from_raw_parts( self.name, self.name_len as usize ); + pub fn name(&self) -> &'static str { + unsafe { + let slic = std::slice::from_raw_parts(self.name, self.name_len as usize); std::str::from_utf8_unchecked(slic) } } /// Gets the representation attribute of the type. - pub const fn repr_attr(&self)->ReprAttr{ + pub const fn repr_attr(&self) -> ReprAttr { self.repr_attr } /// Gets the `ModReflMode` for the type, /// whether this is a module whose definition can be reflected on at runtime. - pub const fn mod_refl_mode(&self)->ModReflMode{ + pub const fn mod_refl_mode(&self) -> ModReflMode { self.mod_refl_mode } /// Gets information about where a type was declared. - pub const fn item_info(&self)->&ItemInfo{ + pub const fn item_info(&self) -> &ItemInfo { &self.item_info.value } /// Gets the SharedVars of the type, /// containing the slices that many types inside TypeLayout contain ranges into. - pub const fn shared_vars(&self)->&MonoSharedVars{ + pub const fn shared_vars(&self) -> &MonoSharedVars { &self.shared_vars } /// Gets the SharedVars of the type, /// containing the slices that many types inside TypeLayout contain ranges into. - /// + /// /// This was defined as a workaround for an internal compiler error in nightly. - pub const fn shared_vars_static(&'static self)->&'static MonoSharedVars{ + pub const fn shared_vars_static(&'static self) -> &'static MonoSharedVars { &self.shared_vars } -/** -Gets the compressed versions of the fields of the type. + /** + Gets the compressed versions of the fields of the type. -# Return value + # Return value -If this a: + If this a: -- primitive or opaque type: - It returns `None`. + - primitive or opaque type: + It returns `None`. -- enum: - It returns `Some()` with all the fields in the order that they were declared, - ignoring variants. + - enum: + It returns `Some()` with all the fields in the order that they were declared, + ignoring variants. -- structs/unions/prefix types: - It returns `Some()` with all the fields in the order that they were declared. + - structs/unions/prefix types: + It returns `Some()` with all the fields in the order that they were declared. -*/ - pub fn get_fields(&self)->Option{ + */ + pub fn get_fields(&self) -> Option { match self.data { - MonoTLData::Primitive{..}=>None, - MonoTLData::Opaque=>None, - MonoTLData::Struct{fields}=>Some(fields), - MonoTLData::Union{fields}=>Some(fields), - MonoTLData::Enum (tlenum)=>Some(tlenum.fields), - MonoTLData::PrefixType(prefix)=>Some(prefix.fields), + MonoTLData::Primitive { .. } => None, + MonoTLData::Opaque => None, + MonoTLData::Struct { fields } => Some(fields), + MonoTLData::Union { fields } => Some(fields), + MonoTLData::Enum(tlenum) => Some(tlenum.fields), + MonoTLData::PrefixType(prefix) => Some(prefix.fields), } } /// Gets an iterator over all the names of the fields in the type. - pub fn field_names(&self)->impl ExactSizeIterator+Clone+'static{ + pub fn field_names(&self) -> impl ExactSizeIterator + Clone + 'static { self.get_fields() .unwrap_or(CompTLFields::EMPTY) - .field_names( &self.shared_vars ) + .field_names(&self.shared_vars) } /// Gets the name of the `nth` field in the type. /// Returns `None` if there is no `nth` field. - pub fn get_field_name(&self,nth:usize)->Option<&'static str>{ + pub fn get_field_name(&self, nth: usize) -> Option<&'static str> { self.get_fields() .unwrap_or(CompTLFields::EMPTY) - .get_field_name( nth, &self.shared_vars ) + .get_field_name(nth, &self.shared_vars) } } - -impl Debug for MonoTypeLayout{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ +impl Debug for MonoTypeLayout { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("MonoTypeLayout") - .field("name",&self.name()) - .field("item_info",self.item_info()) - .field("repr_attr",&self.repr_attr()) - .field("mod_refl_mode",&self.mod_refl_mode()) - .finish() + .field("name", &self.name()) + .field("item_info", self.item_info()) + .field("repr_attr", &self.repr_attr()) + .field("mod_refl_mode", &self.mod_refl_mode()) + .finish() } -} \ No newline at end of file +} diff --git a/abi_stable/src/type_layout/construction.rs b/abi_stable/src/type_layout/construction.rs index ba421a81..0b5a9f04 100644 --- a/abi_stable/src/type_layout/construction.rs +++ b/abi_stable/src/type_layout/construction.rs @@ -1,6 +1,5 @@ use super::*; - //////////////////////////////////////////////////////////////////////////////// #[allow(non_camel_case_types)] @@ -9,10 +8,10 @@ use super::*; pub struct _private_TypeLayoutDerive { pub shared_vars: &'static SharedVars, pub mono: &'static MonoTypeLayout, - pub abi_consts:AbiConsts, + pub abi_consts: AbiConsts, pub data: GenericTLData, - pub tag:Option<&'static Tag>, - pub extra_checks:Option<&'static ManuallyDrop>, + pub tag: Option<&'static Tag>, + pub extra_checks: Option<&'static ManuallyDrop>, } #[allow(non_camel_case_types)] @@ -20,60 +19,55 @@ pub struct _private_TypeLayoutDerive { #[derive(Copy, Clone)] pub struct _private_MonoTypeLayoutDerive { pub name: RStr<'static>, - pub item_info:ItemInfo, + pub item_info: ItemInfo, pub data: MonoTLData, pub generics: CompGenericParams, - pub repr_attr:ReprAttr, - pub mod_refl_mode:ModReflMode, - pub phantom_fields:RSlice<'static,CompTLFieldRepr>, - pub shared_vars:MonoSharedVars, + pub repr_attr: ReprAttr, + pub mod_refl_mode: ModReflMode, + pub phantom_fields: RSlice<'static, CompTLFieldRepr>, + pub shared_vars: MonoSharedVars, } - /// Information about where a type was declared. #[repr(C)] -#[derive(Debug, Copy, Clone, PartialEq,StableAbi)] +#[derive(Debug, Copy, Clone, PartialEq, StableAbi)] #[sabi(unsafe_sabi_opaque_fields)] -pub struct ItemInfo{ +pub struct ItemInfo { /// The package where the type was defined,and the version string. /// With the `package;version_number` format. - package_and_version:RStr<'static>, + package_and_version: RStr<'static>, /// The line in the file where the type was defined. - pub line:u32, + pub line: u32, /// The full path to the module where the type was defined, /// including the package name - pub mod_path:ModPath, + pub mod_path: ModPath, } -impl ItemInfo{ +impl ItemInfo { #[doc(hidden)] - pub const fn new( - package_and_version:&'static str, - line:u32, - mod_path:ModPath, - )->Self{ - Self{ - package_and_version:RStr::from_str(package_and_version), + pub const fn new(package_and_version: &'static str, line: u32, mod_path: ModPath) -> Self { + Self { + package_and_version: RStr::from_str(package_and_version), line, mod_path, } } /// Constructs an ItemInfo for a std primitive - pub const fn primitive()->Self{ - Self{ + pub const fn primitive() -> Self { + Self { package_and_version: RStr::from_str("std;1.0.0"), - line:0, - mod_path:ModPath::PRELUDE, + line: 0, + mod_path: ModPath::PRELUDE, } } /// Constructs an ItemInfo for an std type with a path. - pub const fn std_type_in(mod_path:NulStr<'static>)->Self{ - Self{ + pub const fn std_type_in(mod_path: NulStr<'static>) -> Self { + Self { package_and_version: RStr::from_str("std;1.0.0"), - line:0, - mod_path:ModPath::inside(mod_path), + line: 0, + mod_path: ModPath::inside(mod_path), } } @@ -83,36 +77,32 @@ impl ItemInfo{ /// /// `mod_path` must include the crate name. pub const fn package_and_mod( - package_and_version:&'static str, - mod_path:NulStr<'static> - )->Self{ - Self{ - package_and_version:RStr::from_str(package_and_version), - line:0, - mod_path:ModPath::inside(mod_path), + package_and_version: &'static str, + mod_path: NulStr<'static>, + ) -> Self { + Self { + package_and_version: RStr::from_str(package_and_version), + line: 0, + mod_path: ModPath::inside(mod_path), } } /// Gets the package name and an unparsed package version. - pub fn package_and_version(&self)->(&'static str,&'static str){ - let pav=self.package_and_version.as_str(); + pub fn package_and_version(&self) -> (&'static str, &'static str) { + let pav = self.package_and_version.as_str(); match pav.find(';') { - Some(separator)=>{ - (&pav[..separator],&pav[(separator+1)..]) - } - None=>{ - (&pav[..],"") - } + Some(separator) => (&pav[..separator], &pav[(separator + 1)..]), + None => (&pav[..], ""), } } /// Gets the package name. - pub fn package(&self)->&'static str{ + pub fn package(&self) -> &'static str { self.package_and_version().0 } /// Gets the unparsed package version. - pub fn version(&self)->&'static str{ + pub fn version(&self) -> &'static str { self.package_and_version().1 } -} \ No newline at end of file +} diff --git a/abi_stable/src/type_layout/data_structures.rs b/abi_stable/src/type_layout/data_structures.rs index af8d4834..d268e8d7 100644 --- a/abi_stable/src/type_layout/data_structures.rs +++ b/abi_stable/src/type_layout/data_structures.rs @@ -1,9 +1,6 @@ //! Helper types for type_layout types. -use std::{ - cmp::{PartialEq,Eq}, -}; - +use std::cmp::{Eq, PartialEq}; //////////////////////////////////////////////////////////////////////////////// @@ -11,14 +8,14 @@ use std::{ /// which is treated as a slice of `0..self.len` in all its impls. #[repr(C)] #[derive(Debug, Copy, Clone, StableAbi)] -pub struct ArrayLen{ - pub len:u16, - pub array:A, +pub struct ArrayLen { + pub len: u16, + pub array: A, } impl ArrayLen { /// The `len` field casted to usize. - pub const fn len(&self)->usize{ + pub const fn len(&self) -> usize { self.len as usize } pub const fn is_empty(&self) -> bool { @@ -26,34 +23,32 @@ impl ArrayLen { } } - -impl PartialEq for ArrayLen +impl PartialEq for ArrayLen where - A:ArrayTrait, - T:PartialEq, + A: ArrayTrait, + T: PartialEq, { - fn eq(&self,other:&Self)->bool{ - let t_slice=&self.array.as_slice()[..self.len as usize]; - let o_slice=&other.array.as_slice()[..other.len as usize]; - t_slice==o_slice + fn eq(&self, other: &Self) -> bool { + let t_slice = &self.array.as_slice()[..self.len as usize]; + let o_slice = &other.array.as_slice()[..other.len as usize]; + t_slice == o_slice } } - -impl Eq for ArrayLen +impl Eq for ArrayLen where - A:ArrayTrait, - T:Eq, -{} + A: ArrayTrait, + T: Eq, +{ +} //////////////////////////////////////////////////////////////////////////////// - -mod array_trait{ - pub trait ArrayTrait{ +mod array_trait { + pub trait ArrayTrait { type Elem; - fn as_slice(&self)->&[Self::Elem]; + fn as_slice(&self) -> &[Self::Elem]; } } use self::array_trait::ArrayTrait; @@ -71,7 +66,7 @@ macro_rules! impl_stable_abi_array { )* } } - + impl_stable_abi_array! { 00,01,02,03,04,05,06,07,08 -} \ No newline at end of file +} diff --git a/abi_stable/src/type_layout/iterators.rs b/abi_stable/src/type_layout/iterators.rs index d4a8d955..e67adada 100644 --- a/abi_stable/src/type_layout/iterators.rs +++ b/abi_stable/src/type_layout/iterators.rs @@ -1,47 +1,42 @@ - -#[derive(Debug,Clone)] -pub(crate)struct ChainOnce{ - iter:I, - once:Option, +#[derive(Debug, Clone)] +pub(crate) struct ChainOnce { + iter: I, + once: Option, } -impl ChainOnce +impl ChainOnce where - I:ExactSizeIterator + I: ExactSizeIterator, { - pub(crate) fn new(iter:I,once:I::Item)->Self{ - Self{ + pub(crate) fn new(iter: I, once: I::Item) -> Self { + Self { iter, - once:Some(once), + once: Some(once), } } - fn length(&self)->usize{ - self.iter.len()+(self.once.is_some() as usize) + fn length(&self) -> usize { + self.iter.len() + (self.once.is_some() as usize) } } -impl Iterator for ChainOnce +impl Iterator for ChainOnce where - I:ExactSizeIterator + I: ExactSizeIterator, { - type Item=I::Item; - fn next(&mut self) -> Option{ - if let ret@Some(_)=self.iter.next() { + type Item = I::Item; + fn next(&mut self) -> Option { + if let ret @ Some(_) = self.iter.next() { return ret; } self.once.take() } fn size_hint(&self) -> (usize, Option) { - let len=self.length(); - (len,Some(len)) + let len = self.length(); + (len, Some(len)) } fn count(self) -> usize { self.length() } } - -impl std::iter::ExactSizeIterator for ChainOnce -where - I:ExactSizeIterator -{} \ No newline at end of file +impl std::iter::ExactSizeIterator for ChainOnce where I: ExactSizeIterator {} diff --git a/abi_stable/src/type_layout/printing.rs b/abi_stable/src/type_layout/printing.rs index eab6ceb3..b87984f0 100644 --- a/abi_stable/src/type_layout/printing.rs +++ b/abi_stable/src/type_layout/printing.rs @@ -1,45 +1,37 @@ use super::*; use std::{ - collections::{HashSet,HashMap}, - cell::{Cell,RefCell}, + cell::{Cell, RefCell}, + collections::{HashMap, HashSet}, }; use core_extensions::SelfOps; - #[cfg(test)] mod tests; - - /** A function which recursively traverses a type layout, calling `callback` for every `TypeLayout` it goes over. */ -fn traverse_type_layouts<'a,F>(layout:&'a TypeLayout,mut callback:F) +fn traverse_type_layouts<'a, F>(layout: &'a TypeLayout, mut callback: F) where - F:FnMut(&'a TypeLayout) + F: FnMut(&'a TypeLayout), { - let mut state=RecursionState{ - visited:HashSet::new(), + let mut state = RecursionState { + visited: HashSet::new(), }; - traverse_type_layouts_inner( - layout, - &mut state, - &mut callback, - ); + traverse_type_layouts_inner(layout, &mut state, &mut callback); } - -fn traverse_type_layouts_inner<'a,F>( - layout:&'a TypeLayout, - state:&mut RecursionState, - callback:&mut F, -)where - F:FnMut(&'a TypeLayout) +fn traverse_type_layouts_inner<'a, F>( + layout: &'a TypeLayout, + state: &mut RecursionState, + callback: &mut F, +) where + F: FnMut(&'a TypeLayout), { if state.visited.replace(layout.get_utypeid()).is_none() { callback(layout); @@ -48,7 +40,7 @@ fn traverse_type_layouts_inner<'a,F>( traverse_type_layouts_inner(layout.get(), state, callback); } - if let Some(extra_checks)=layout.extra_checks() { + if let Some(extra_checks) = layout.extra_checks() { for layout in &*extra_checks.nested_type_layouts() { traverse_type_layouts_inner(layout, state, callback); } @@ -56,24 +48,20 @@ fn traverse_type_layouts_inner<'a,F>( } } - - -struct RecursionState{ - visited:HashSet, +struct RecursionState { + visited: HashSet, } - //////////////////////////////////////////////////////////////////////////////// -struct DebugState{ - counter:Cell, - map:RefCell>>, - display_stack:RefCell>, - full_type_stack:RefCell>, +struct DebugState { + counter: Cell, + map: RefCell>>, + display_stack: RefCell>, + full_type_stack: RefCell>, } - -thread_local!{ +thread_local! { static DEBUG_STATE:DebugState=DebugState{ counter:Cell::new(0), map:RefCell::new(HashMap::new()), @@ -82,104 +70,99 @@ thread_local!{ }; } -const GET_ERR:&str= +const GET_ERR: &str = "Expected DEBUG_STATE.map to contain the UTypeId of all recursive `TypeLayout`s"; -impl Debug for TypeLayout{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - let mut current_level=!0; - DEBUG_STATE.with(|state|{ - current_level=state.counter.get(); +impl Debug for TypeLayout { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut current_level = !0; + DEBUG_STATE.with(|state| { + current_level = state.counter.get(); if current_level < 1 { - state.counter.set(current_level+1); + state.counter.set(current_level + 1); } }); - if current_level>=1 { - let mut index=None; - DEBUG_STATE.with(|state|{ - index=*state.map.borrow().get(&self.get_utypeid()).expect(GET_ERR) ; + if current_level >= 1 { + let mut index = None; + DEBUG_STATE.with(|state| { + index = *state.map.borrow().get(&self.get_utypeid()).expect(GET_ERR); }); - let ptr=TypeLayoutPointer{ - key_in_map:index, - type_:self.full_type(), + let ptr = TypeLayoutPointer { + key_in_map: index, + type_: self.full_type(), }; - return Debug::fmt(&ptr,f); + return Debug::fmt(&ptr, f); } - let mut type_infos=Vec::<&'static TypeLayout>::new(); + let mut type_infos = Vec::<&'static TypeLayout>::new(); + + if current_level == 0 { + DEBUG_STATE.with(|state| { + let mut i = 0usize; - if current_level==0 { - DEBUG_STATE.with(|state|{ - let mut i=0usize; + let mut map = state.map.borrow_mut(); - let mut map=state.map.borrow_mut(); - - traverse_type_layouts(self,|this|{ + traverse_type_layouts(self, |this| { map.entry(this.get_utypeid()) .or_insert(None) - .get_or_insert_with(||{ + .get_or_insert_with(|| { type_infos.push(this); - let index=i; - i+=1; + let index = i; + i += 1; index }); }); }) } - - // This guard is used to uninitialize the map when returning from this function, // even on panics. - let _guard=DecrementLevel; - + let _guard = DecrementLevel; f.debug_struct("TypeLayout") - .field("name",&self.name()) - .field("full_type",&self.full_type()) - .field("is_nonzero",&self.is_nonzero()) - .field("alignment",&self.alignment()) - .field("size",&self.size()) - .field("data",&self.data()) - .field("extra_checks",&self.extra_checks()) - .field("type_id",&self.get_utypeid()) - .field("item_info",&self.item_info()) - .field("phantom_fields",&self.phantom_fields()) - .field("tag",&self.tag()) - .field("repr_attr",&self.repr_attr()) - .field("mod_refl_mode",&self.mod_refl_mode()) - .observe(|_| drop(_guard) ) - .field("nested_type_layouts",&WithIndices(&type_infos)) + .field("name", &self.name()) + .field("full_type", &self.full_type()) + .field("is_nonzero", &self.is_nonzero()) + .field("alignment", &self.alignment()) + .field("size", &self.size()) + .field("data", &self.data()) + .field("extra_checks", &self.extra_checks()) + .field("type_id", &self.get_utypeid()) + .field("item_info", &self.item_info()) + .field("phantom_fields", &self.phantom_fields()) + .field("tag", &self.tag()) + .field("repr_attr", &self.repr_attr()) + .field("mod_refl_mode", &self.mod_refl_mode()) + .observe(|_| drop(_guard)) + .field("nested_type_layouts", &WithIndices(&type_infos)) .finish() } } - //////////////// - -const RECURSIVE_INDICATOR:&str="<{recursive}>"; +const RECURSIVE_INDICATOR: &str = "<{recursive}>"; impl Display for TypeLayout { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let mut is_cyclic=false; + let mut is_cyclic = false; - DEBUG_STATE.with(|state|{ - let mut stack=state.display_stack.borrow_mut(); - let tid=self.get_utypeid(); - is_cyclic=stack.contains(&tid); + DEBUG_STATE.with(|state| { + let mut stack = state.display_stack.borrow_mut(); + let tid = self.get_utypeid(); + is_cyclic = stack.contains(&tid); if !is_cyclic { stack.push(tid); } }); if is_cyclic { - write!(f,"{}{}",self.name(),RECURSIVE_INDICATOR)?; - }else{ - let _guard=DisplayGuard; + write!(f, "{}{}", self.name(), RECURSIVE_INDICATOR)?; + } else { + let _guard = DisplayGuard; - let (package,version)=self.item_info().package_and_version(); + let (package, version) = self.item_info().package_and_version(); writeln!( f, "--- Type Layout ---\n\ @@ -187,53 +170,48 @@ impl Display for TypeLayout { size:{size} align:{align}\n\ package:'{package}' version:'{version}'\n\ line:{line} mod:{mod_path}", - ty =self.full_type(), - size =self.size(), - align=self.alignment(), - package=package, - version=version, - line=self.item_info().line, - mod_path=self.item_info().mod_path, + ty = self.full_type(), + size = self.size(), + align = self.alignment(), + package = package, + version = version, + line = self.item_info().line, + mod_path = self.item_info().mod_path, )?; - writeln!(f,"data:\n{}",self.data().to_string().left_padder(4))?; - let phantom_fields=self.phantom_fields(); + writeln!(f, "data:\n{}", self.data().to_string().left_padder(4))?; + let phantom_fields = self.phantom_fields(); if !phantom_fields.is_empty() { - writeln!(f,"Phantom fields:\n")?; + writeln!(f, "Phantom fields:\n")?; for field in phantom_fields { - write!(f,"{}",field.to_string().left_padder(4))?; + write!(f, "{}", field.to_string().left_padder(4))?; } } - writeln!(f,"Tag:\n{}",self.tag().to_string().left_padder(4))?; - let extra_checks= - match self.extra_checks() { - Some(x)=>x.to_string(), - None=>"".to_string(), - }; - writeln!(f,"Extra checks:\n{}",extra_checks.left_padder(4))?; - writeln!(f,"Repr attribute:{:?}",self.repr_attr())?; - writeln!(f,"Module reflection mode:{:?}",self.mod_refl_mode())?; + writeln!(f, "Tag:\n{}", self.tag().to_string().left_padder(4))?; + let extra_checks = match self.extra_checks() { + Some(x) => x.to_string(), + None => "".to_string(), + }; + writeln!(f, "Extra checks:\n{}", extra_checks.left_padder(4))?; + writeln!(f, "Repr attribute:{:?}", self.repr_attr())?; + writeln!(f, "Module reflection mode:{:?}", self.mod_refl_mode())?; } - Ok(()) } } - struct DisplayGuard; -impl Drop for DisplayGuard{ - fn drop(&mut self){ - DEBUG_STATE.with(|state|{ +impl Drop for DisplayGuard { + fn drop(&mut self) { + DEBUG_STATE.with(|state| { state.display_stack.borrow_mut().pop(); }); } } - //////////////// - impl Display for FmtFullType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Debug::fmt(self, f) @@ -241,37 +219,35 @@ impl Display for FmtFullType { } impl Debug for FmtFullType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let mut is_cyclic=false; + let mut is_cyclic = false; - DEBUG_STATE.with(|state|{ - let mut stack=state.full_type_stack.borrow_mut(); - let tid=self.utypeid; - is_cyclic=stack.contains(&tid); + DEBUG_STATE.with(|state| { + let mut stack = state.full_type_stack.borrow_mut(); + let tid = self.utypeid; + is_cyclic = stack.contains(&tid); if !is_cyclic { stack.push(tid); } }); if is_cyclic { - write!(f,"{}{}",self.name,RECURSIVE_INDICATOR)?; - }else{ + write!(f, "{}{}", self.name, RECURSIVE_INDICATOR)?; + } else { use self::TLPrimitive as TLP; - let _guard=FmtFullTypeGuard; + let _guard = FmtFullTypeGuard; let (typename, start_gen, before_ty, ty_sep, end_gen) = match self.primitive { Some(TLP::SharedRef) => ("&", "", " ", " ", " "), Some(TLP::MutRef) => ("&", "", " mut ", " ", " "), Some(TLP::ConstPtr) => ("*const", " ", "", " ", " "), Some(TLP::MutPtr) => ("*mut", " ", "", " ", " "), - Some(TLP::Array{..}) => ("", "[", "", ";", "]"), - Some(TLP::U8)|Some(TLP::I8) - |Some(TLP::U16)|Some(TLP::I16) - |Some(TLP::U32)|Some(TLP::I32) - |Some(TLP::U64)|Some(TLP::I64) - |Some(TLP::Usize)|Some(TLP::Isize) - |Some(TLP::Bool) - |None => (self.name, "<", "", ", ", ">"), + Some(TLP::Array { .. }) => ("", "[", "", ";", "]"), + Some(TLP::U8) | Some(TLP::I8) | Some(TLP::U16) | Some(TLP::I16) + | Some(TLP::U32) | Some(TLP::I32) | Some(TLP::U64) | Some(TLP::I64) + | Some(TLP::Usize) | Some(TLP::Isize) | Some(TLP::Bool) | None => { + (self.name, "<", "", ", ", ">") + } }; fmt::Display::fmt(typename, f)?; @@ -281,36 +257,36 @@ impl Debug for FmtFullType { fmt::Display::fmt(start_gen, f)?; let post_iter = |i: usize, len: usize, f: &mut Formatter<'_>| -> fmt::Result { - if i+1 < len { + if i + 1 < len { fmt::Display::fmt(ty_sep, f)?; } Ok(()) }; - let mut i=0; + let mut i = 0; - let total_generics_len= - generics.lifetime_count()+generics.types.len()+generics.consts.len(); + let total_generics_len = + generics.lifetime_count() + generics.types.len() + generics.consts.len(); for param in self.generics.lifetimes() { fmt::Display::fmt(param, &mut *f)?; - post_iter(i,total_generics_len, &mut *f)?; - i+=1; + post_iter(i, total_generics_len, &mut *f)?; + i += 1; } for param in generics.types.iter().cloned() { - let layout=param.get(); + let layout = param.get(); if is_before_ty { fmt::Display::fmt(before_ty, &mut *f)?; is_before_ty = false; } fmt::Debug::fmt(&layout.full_type(), &mut *f)?; - post_iter(i,total_generics_len, &mut *f)?; - i+=1; + post_iter(i, total_generics_len, &mut *f)?; + i += 1; } for param in generics.consts.iter() { fmt::Debug::fmt(param, &mut *f)?; - post_iter(i,total_generics_len, &mut *f)?; - i+=1; + post_iter(i, total_generics_len, &mut *f)?; + i += 1; } fmt::Display::fmt(end_gen, f)?; } @@ -319,30 +295,26 @@ impl Debug for FmtFullType { } } - struct FmtFullTypeGuard; -impl Drop for FmtFullTypeGuard{ - fn drop(&mut self){ - DEBUG_STATE.with(|state|{ +impl Drop for FmtFullTypeGuard { + fn drop(&mut self) { + DEBUG_STATE.with(|state| { state.full_type_stack.borrow_mut().pop(); }); } } - - //////////////// - struct DecrementLevel; -impl Drop for DecrementLevel{ - fn drop(&mut self){ - DEBUG_STATE.with(|state|{ - let current=state.counter.get(); - if current==0 { - let mut map=state.map.borrow_mut(); +impl Drop for DecrementLevel { + fn drop(&mut self) { + DEBUG_STATE.with(|state| { + let current = state.counter.get(); + if current == 0 { + let mut map = state.map.borrow_mut(); map.clear(); map.shrink_to_fit(); } @@ -351,29 +323,23 @@ impl Drop for DecrementLevel{ } } - - //////////////// #[derive(Debug)] -struct TypeLayoutPointer{ - key_in_map:Option, - type_:FmtFullType, +struct TypeLayoutPointer { + key_in_map: Option, + type_: FmtFullType, } - //////////////// +struct WithIndices<'a, T>(&'a [T]); -struct WithIndices<'a,T>(&'a [T]); - -impl<'a,T> Debug for WithIndices<'a,T> +impl<'a, T> Debug for WithIndices<'a, T> where - T:Debug + T: Debug, { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - f.debug_map() - .entries(self.0.iter().enumerate()) - .finish() + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_map().entries(self.0.iter().enumerate()).finish() } } diff --git a/abi_stable/src/type_layout/printing/tests.rs b/abi_stable/src/type_layout/printing/tests.rs index 827d43db..63a36bfa 100644 --- a/abi_stable/src/type_layout/printing/tests.rs +++ b/abi_stable/src/type_layout/printing/tests.rs @@ -1,131 +1,111 @@ use super::RECURSIVE_INDICATOR; use crate::{ - abi_stability::stable_abi_trait::get_type_layout, - sabi_types::Constructor, - std_types::RSlice, - test_utils::AlwaysDisplay, - type_layout::TypeLayout, - StableAbi, + abi_stability::stable_abi_trait::get_type_layout, sabi_types::Constructor, std_types::RSlice, + test_utils::AlwaysDisplay, type_layout::TypeLayout, StableAbi, }; - -mod display{ +mod display { use super::*; #[repr(C)] #[derive(StableAbi)] - #[sabi(phantom_const_param="STRUCT_0_LAYS")] + #[sabi(phantom_const_param = "STRUCT_0_LAYS")] pub(super) struct Struct0; #[repr(C)] #[derive(StableAbi)] - #[sabi(phantom_const_param="STRUCT_1_LAYS")] + #[sabi(phantom_const_param = "STRUCT_1_LAYS")] pub(super) struct Struct1; #[repr(C)] #[derive(StableAbi)] - #[sabi(phantom_const_param="STRUCT_2_LAYS")] + #[sabi(phantom_const_param = "STRUCT_2_LAYS")] pub(super) struct Struct2; - const STRUCT_0_LAYS: RSlice<'static,AlwaysDisplay>>= + const STRUCT_0_LAYS: RSlice<'static, AlwaysDisplay>> = rslice![]; - const STRUCT_1_LAYS: RSlice<'static,AlwaysDisplay>>= - rslice![ - AlwaysDisplay(Constructor(get_type_layout::)), - ]; + const STRUCT_1_LAYS: RSlice<'static, AlwaysDisplay>> = + rslice![AlwaysDisplay(Constructor(get_type_layout::)),]; - const STRUCT_2_LAYS: RSlice<'static,AlwaysDisplay>>= - rslice![ - AlwaysDisplay(Constructor(get_type_layout::)), - AlwaysDisplay(Constructor(get_type_layout::)), - ]; + const STRUCT_2_LAYS: RSlice<'static, AlwaysDisplay>> = rslice![ + AlwaysDisplay(Constructor(get_type_layout::)), + AlwaysDisplay(Constructor(get_type_layout::)), + ]; } - #[test] -fn recursive_display(){ - let list=vec![ +fn recursive_display() { + let list = vec![ ::LAYOUT, ::LAYOUT, ::LAYOUT, ]; - for (i,layout) in list.into_iter().enumerate() { - let matches=layout.to_string().matches(RECURSIVE_INDICATOR).count(); + for (i, layout) in list.into_iter().enumerate() { + let matches = layout.to_string().matches(RECURSIVE_INDICATOR).count(); assert_eq!(matches, i); { - let full_type=layout.full_type(); - let matches=full_type.to_string().matches(RECURSIVE_INDICATOR).count(); - assert_eq!(matches, i,"\n{}\n",full_type); - let name_matches=full_type.to_string().matches("align").count(); - assert_eq!(name_matches, i,"\n{}\n",full_type); + let full_type = layout.full_type(); + let matches = full_type.to_string().matches(RECURSIVE_INDICATOR).count(); + assert_eq!(matches, i, "\n{}\n", full_type); + let name_matches = full_type.to_string().matches("align").count(); + assert_eq!(name_matches, i, "\n{}\n", full_type); } } } - -mod debug{ +mod debug { use super::*; #[repr(C)] #[derive(StableAbi)] - #[sabi(phantom_const_param="STRUCT_0_LAYS")] + #[sabi(phantom_const_param = "STRUCT_0_LAYS")] pub(super) struct Struct0; #[repr(C)] #[derive(StableAbi)] - #[sabi(phantom_const_param="STRUCT_1_LAYS")] + #[sabi(phantom_const_param = "STRUCT_1_LAYS")] pub(super) struct Struct1; #[repr(C)] #[derive(StableAbi)] - #[sabi(phantom_const_param="STRUCT_2_LAYS")] + #[sabi(phantom_const_param = "STRUCT_2_LAYS")] pub(super) struct Struct2; - const STRUCT_0_LAYS: RSlice<'static,Constructor<&'static TypeLayout>>= - rslice![]; + const STRUCT_0_LAYS: RSlice<'static, Constructor<&'static TypeLayout>> = rslice![]; - const STRUCT_1_LAYS: RSlice<'static,Constructor<&'static TypeLayout>>= - rslice![ - Constructor(get_type_layout::), - ]; + const STRUCT_1_LAYS: RSlice<'static, Constructor<&'static TypeLayout>> = + rslice![Constructor(get_type_layout::),]; - const STRUCT_2_LAYS: RSlice<'static,Constructor<&'static TypeLayout>>= - rslice![ - Constructor(get_type_layout::), - Constructor(get_type_layout::), - ]; + const STRUCT_2_LAYS: RSlice<'static, Constructor<&'static TypeLayout>> = rslice![ + Constructor(get_type_layout::), + Constructor(get_type_layout::), + ]; } - - #[test] -fn recursive_debug(){ - let list=vec![ +fn recursive_debug() { + let list = vec![ ::LAYOUT, ::LAYOUT, ::LAYOUT, ]; - for (i,layout) in list.into_iter().enumerate() { + for (i, layout) in list.into_iter().enumerate() { { - let formatted=format!("{:#?}",layout); - let matches=formatted.matches(RECURSIVE_INDICATOR).count(); - assert_eq!(matches, i*2,"\n{}\n",formatted); + let formatted = format!("{:#?}", layout); + let matches = formatted.matches(RECURSIVE_INDICATOR).count(); + assert_eq!(matches, i * 2, "\n{}\n", formatted); } { - let full_type=layout.full_type(); - let formatted=format!("{:#?}",full_type); - let matches=formatted.matches(RECURSIVE_INDICATOR).count(); - assert_eq!(matches, i,"\n{}\n",formatted); - let name_matches=formatted.to_string().matches("align").count(); - assert_eq!(name_matches, i,"\n{}\n",formatted); + let full_type = layout.full_type(); + let formatted = format!("{:#?}", full_type); + let matches = formatted.matches(RECURSIVE_INDICATOR).count(); + assert_eq!(matches, i, "\n{}\n", formatted); + let name_matches = formatted.to_string().matches("align").count(); + assert_eq!(name_matches, i, "\n{}\n", formatted); } } } - - - - diff --git a/abi_stable/src/type_layout/shared_vars.rs b/abi_stable/src/type_layout/shared_vars.rs index 426c959d..a02844a9 100644 --- a/abi_stable/src/type_layout/shared_vars.rs +++ b/abi_stable/src/type_layout/shared_vars.rs @@ -3,8 +3,8 @@ use super::*; use crate::abi_stability::ConstGeneric; use std::{ + fmt::{self, Debug}, slice, - fmt::{self,Debug}, }; //////////////////////////////////////////////////////////////////////////////// @@ -13,25 +13,25 @@ use std::{ /// requiring this type to be passed as a parameter. #[repr(C)] #[derive(StableAbi)] -pub struct SharedVars{ +pub struct SharedVars { mono: &'static MonoSharedVars, type_layouts: *const TypeLayoutCtor, constants: *const ConstGeneric, type_layouts_len: u16, - constants_len:u16, + constants_len: u16, } unsafe impl Sync for SharedVars {} unsafe impl Send for SharedVars {} -impl SharedVars{ +impl SharedVars { /// Constructs a `SharedVars`. pub const fn new( mono: &'static MonoSharedVars, - type_layouts: RSlice<'static,TypeLayoutCtor>, - constants: RSlice<'static,ConstGeneric>, - )->Self{ - Self{ + type_layouts: RSlice<'static, TypeLayoutCtor>, + constants: RSlice<'static, ConstGeneric>, + ) -> Self { + Self { mono, type_layouts: type_layouts.as_ptr(), @@ -42,50 +42,44 @@ impl SharedVars{ } } - /// A string containing many strings that types in the `type_layout` + /// A string containing many strings that types in the `type_layout` /// module store substrings inside of. #[inline] - pub fn strings(&self)->&'static str{ + pub fn strings(&self) -> &'static str { self.mono.strings() } /// Many lifetimes that types in the `type_layout` module reference. #[inline] - pub fn lifetime_indices(&self)->&'static [LifetimeIndexPair]{ + pub fn lifetime_indices(&self) -> &'static [LifetimeIndexPair] { self.mono.lifetime_indices() } - /// Many `TypeLayoutCtor`s that types in the `type_layout` + /// Many `TypeLayoutCtor`s that types in the `type_layout` /// module reference. /// - /// The `StableAbi` derive macro deduplicates identical looking types + /// The `StableAbi` derive macro deduplicates identical looking types /// when constructing SharedVars. #[inline] - pub fn type_layouts(&self)->&'static [TypeLayoutCtor]{ - unsafe{ - slice::from_raw_parts( self.type_layouts, self.type_layouts_len as usize ) - } + pub fn type_layouts(&self) -> &'static [TypeLayoutCtor] { + unsafe { slice::from_raw_parts(self.type_layouts, self.type_layouts_len as usize) } } /// Many constants that types in the `type_layout` module contain ranges into. #[inline] - pub fn constants(&self)->&'static [ConstGeneric]{ - unsafe{ - slice::from_raw_parts( self.constants, self.constants_len as usize ) - } + pub fn constants(&self) -> &'static [ConstGeneric] { + unsafe { slice::from_raw_parts(self.constants, self.constants_len as usize) } } } -impl Debug for SharedVars{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ +impl Debug for SharedVars { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("SharedVars").finish() } } - /// A few static slices that many types in the `type_layout` module contain ranges into, /// requiring this type to be passed as a parameter. #[repr(C)] -#[derive(StableAbi)] -#[derive(Copy,Clone)] -pub struct MonoSharedVars{ +#[derive(StableAbi, Copy, Clone)] +pub struct MonoSharedVars { /// Many strings,separated with ";". strings: *const u8, /// Stores the lifetime indices for lifetimes referenced in a type. @@ -104,18 +98,17 @@ pub struct MonoSharedVars{ lifetime_indices_len: u16, } -impl MonoSharedVars{ +impl MonoSharedVars { /// Constructs a `MonoSharedVars`. pub const fn new( strings: RStr<'static>, - lifetime_indices: RSlice<'static,LifetimeIndexPairRepr>, - )->Self{ - Self{ + lifetime_indices: RSlice<'static, LifetimeIndexPairRepr>, + ) -> Self { + Self { strings: strings.as_ptr(), strings_len: strings.len() as u16, - lifetime_indices: lifetime_indices.as_ptr() - as *const LifetimeIndexPairRepr + lifetime_indices: lifetime_indices.as_ptr() as *const LifetimeIndexPairRepr as *const LifetimeIndexPair, lifetime_indices_len: lifetime_indices.len() as u16, } @@ -123,18 +116,16 @@ impl MonoSharedVars{ /// A string that types in the `type_layout` module store substrings inside of. #[inline] - pub fn strings(&self)->&'static str{ - unsafe{ - let slice=slice::from_raw_parts( self.strings, self.strings_len as usize); + pub fn strings(&self) -> &'static str { + unsafe { + let slice = slice::from_raw_parts(self.strings, self.strings_len as usize); std::str::from_utf8_unchecked(slice) } } /// Many lifetimes that types in the `type_layout` module reference. #[inline] - pub fn lifetime_indices(&self)->&'static [LifetimeIndexPair]{ - unsafe{ - slice::from_raw_parts( self.lifetime_indices, self.lifetime_indices_len as usize ) - } + pub fn lifetime_indices(&self) -> &'static [LifetimeIndexPair] { + unsafe { slice::from_raw_parts(self.lifetime_indices, self.lifetime_indices_len as usize) } } } diff --git a/abi_stable/src/type_layout/small_types.rs b/abi_stable/src/type_layout/small_types.rs index a9bc26fd..918edfc1 100644 --- a/abi_stable/src/type_layout/small_types.rs +++ b/abi_stable/src/type_layout/small_types.rs @@ -1,40 +1,38 @@ use super::*; -use crate::const_utils::{min_u16,min_u8}; +use crate::const_utils::{min_u16, min_u8}; -use std::{ - ops::{Range,RangeInclusive}, -}; +use std::ops::{Range, RangeInclusive}; //////////////////////////////////////////////////////////////////////////////// /// The start and length of a slice into `TLFunctions`. #[repr(transparent)] -#[derive(Copy,Clone,Debug,PartialEq,Eq,Ord,PartialOrd,StableAbi)] -pub struct StartLen{ - bits:u32 +#[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd, StableAbi)] +pub struct StartLen { + bits: u32, } /// The internal representation of `StartLen`. -pub type StartLenRepr=u32; +pub type StartLenRepr = u32; -impl StartLen{ +impl StartLen { /// Constructs a range. #[inline] - pub const fn new(start:u16,len:u16)->Self{ - Self{ - bits:(start as u32)|((len as u32) << 16) + pub const fn new(start: u16, len: u16) -> Self { + Self { + bits: (start as u32) | ((len as u32) << 16), } } /// Gets the start of the range. #[inline] - pub const fn start(self)->u16{ + pub const fn start(self) -> u16 { self.bits as u16 } /// Gets the length of the range. #[inline] - pub const fn len(self)->u16{ + pub const fn len(self) -> u16 { (self.bits >> 16) as u16 } @@ -45,199 +43,191 @@ impl StartLen{ /// Gets the start of the range as a usize. #[inline] - pub const fn start_usize(self)->usize{ - (self.bits&0xffff) as usize + pub const fn start_usize(self) -> usize { + (self.bits & 0xffff) as usize } #[inline] /// Gets the length of the range as a usize. - pub const fn len_usize(self)->usize{ + pub const fn len_usize(self) -> usize { (self.bits >> 16) as usize } /// Gets the exclusive end of the range as a usize. #[inline] - pub const fn end_usize(self)->usize{ - self.start_usize()+self.len_usize() + pub const fn end_usize(self) -> usize { + self.start_usize() + self.len_usize() } /// Converts this range to a `std::ops::Range`. #[inline] - pub const fn to_range(self)->Range{ - self.start_usize() ..self.end_usize() + pub const fn to_range(self) -> Range { + self.start_usize()..self.end_usize() } /// Constructs this `StartLen` from its internal representation. #[inline] - pub const fn from_u32(n:StartLenRepr)->Self{ - Self{bits:n} + pub const fn from_u32(n: StartLenRepr) -> Self { + Self { bits: n } } /// An empty range. - pub const EMPTY:Self=Self::new(0,0); + pub const EMPTY: Self = Self::new(0, 0); - abi_stable_shared::declare_start_len_bit_methods!{} + abi_stable_shared::declare_start_len_bit_methods! {} } - - /// Used to convert the arguments passed to the `tl_genparams` macro to a `StartLen`. pub struct StartLenConverter(pub T); #[allow(clippy::wrong_self_convention)] -impl StartLenConverter<()>{ +impl StartLenConverter<()> { /// Constructs an empty `StartLen`. - pub const fn to_start_len(self)->StartLen{ + pub const fn to_start_len(self) -> StartLen { StartLen::EMPTY } } #[allow(clippy::wrong_self_convention)] -impl StartLenConverter{ +impl StartLenConverter { /// Constructs a `StartLen` from `0` to `self.0` exclusive. - pub const fn to_start_len(self)->StartLen{ - StartLen::new(self.0 as u16,1) + pub const fn to_start_len(self) -> StartLen { + StartLen::new(self.0 as u16, 1) } } #[allow(clippy::wrong_self_convention)] -impl StartLenConverter>{ +impl StartLenConverter> { /// Constructs a `StartLen` from the `Range`. - pub const fn to_start_len(self)->StartLen{ - let start=self.0.start as u16; - let len=(self.0.end-self.0.start) as u16; - StartLen::new(start,len) + pub const fn to_start_len(self) -> StartLen { + let start = self.0.start as u16; + let len = (self.0.end - self.0.start) as u16; + StartLen::new(start, len) } } #[allow(clippy::wrong_self_convention)] -impl StartLenConverter>{ +impl StartLenConverter> { /// Constructs a `StartLen` from the `RangeInclusive`. - pub const fn to_start_len(self)->StartLen{ - let start=*self.0.start(); - let end=*self.0.end()+1; - StartLen::new(start as u16,(end-start)as u16) + pub const fn to_start_len(self) -> StartLen { + let start = *self.0.start(); + let end = *self.0.end() + 1; + StartLen::new(start as u16, (end - start) as u16) } } #[allow(clippy::wrong_self_convention)] -impl StartLenConverter{ +impl StartLenConverter { /// Unwraps this back into a `StartLen`. - pub const fn to_start_len(self)->StartLen{ + pub const fn to_start_len(self) -> StartLen { self.0 } } - ///////////////////////////////////////////////////////////////////////////////////////////// /// An optional u16 which represents None as `u16::max_value()` #[repr(transparent)] -#[derive(Copy,Clone,PartialEq,Eq,Ord,PartialOrd,StableAbi)] +#[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd, StableAbi)] pub struct OptionU16(u16); -impl OptionU16{ +impl OptionU16 { /// Equivalent to Option::None #[allow(non_upper_case_globals)] - pub const None:Self=OptionU16(!0); + pub const None: Self = OptionU16(!0); + + const MAX_VAL: u16 = !0 - 1; - const MAX_VAL:u16=!0-1; - /// Constructs the equivalent of `Some(value)`, /// which saturates the `u16::max_value()` value down to `u16::max_value()-1` - pub const fn some(value:u16)->Self{ - OptionU16( min_u16(value,Self::MAX_VAL)) + pub const fn some(value: u16) -> Self { + OptionU16(min_u16(value, Self::MAX_VAL)) } - + /// Whether this is the Some variant. - pub fn is_some(self)->bool{ - self!=Self::None + pub fn is_some(self) -> bool { + self != Self::None } /// Whether this is the None variant. - pub fn is_none(self)->bool{ - self==Self::None + pub fn is_none(self) -> bool { + self == Self::None } - + /// Converts this to an `Option`. - pub fn to_option(self)->Option{ + pub fn to_option(self) -> Option { if self.is_some() { Some(self.0) - }else{ + } else { None } } } - -impl Debug for OptionU16{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Debug::fmt(&self.to_option(),f) +impl Debug for OptionU16 { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Debug::fmt(&self.to_option(), f) } } -impl Display for OptionU16{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ +impl Display for OptionU16 { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.is_some() { - Display::fmt("None",f) - }else{ - Display::fmt(&self.0,f) - } + Display::fmt("None", f) + } else { + Display::fmt(&self.0, f) + } } } - ///////////////////////////////////////////////////////////////////////////////////////////// /// An optional u8 which represents None as `u8::max_value()` #[repr(transparent)] -#[derive(Copy,Clone,PartialEq,Eq,Ord,PartialOrd,StableAbi)] +#[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd, StableAbi)] pub struct OptionU8(u8); -impl OptionU8{ +impl OptionU8 { /// Equivalent to Option::None #[allow(non_upper_case_globals)] - pub const None:Self=OptionU8(!0); - - const MAX_VAL:u8=!0-1; + pub const None: Self = OptionU8(!0); + + const MAX_VAL: u8 = !0 - 1; /// Constructs the equivalent of `Some(value)`, /// which saturates the `u8::max_value()` value down to `u8::max_value()-1` - pub const fn some(value:u8)->Self{ - OptionU8( min_u8(value,Self::MAX_VAL)) + pub const fn some(value: u8) -> Self { + OptionU8(min_u8(value, Self::MAX_VAL)) } /// Whether this is the Some variant. - pub fn is_some(self)->bool{ - self!=Self::None + pub fn is_some(self) -> bool { + self != Self::None } /// Whether this is the None variant. - pub fn is_none(self)->bool{ - self==Self::None + pub fn is_none(self) -> bool { + self == Self::None } /// Converts this to an `Option`. - pub fn to_option(self)->Option{ + pub fn to_option(self) -> Option { if self.is_some() { Some(self.0) - }else{ + } else { None } } } - -impl Debug for OptionU8{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Debug::fmt(&self.to_option(),f) +impl Debug for OptionU8 { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Debug::fmt(&self.to_option(), f) } } -impl Display for OptionU8{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ +impl Display for OptionU8 { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.is_some() { - Display::fmt("None",f) - }else{ - Display::fmt(&self.0,f) - } + Display::fmt("None", f) + } else { + Display::fmt(&self.0, f) + } } } - - diff --git a/abi_stable/src/type_layout/tagging.rs b/abi_stable/src/type_layout/tagging.rs index d8bde317..e8f2539e 100644 --- a/abi_stable/src/type_layout/tagging.rs +++ b/abi_stable/src/type_layout/tagging.rs @@ -1,64 +1,64 @@ -//! Tag is a dynamically typed data structure used to encode extra properties +//! Tag is a dynamically typed data structure used to encode extra properties //! about a type in its layout constant. -//! +//! //! # Comparison semantics -//! +//! //! Tags don't use strict equality when doing layout checking , -//! here is an exhaustive list on what is considered compatible +//! here is an exhaustive list on what is considered compatible //! for each variant **in the interface**: -//! +//! //! - Null: //! A Tag which is compatible with any other one. //! Note that Nulls are stripped from arrays,set,and map keys. -//! +//! //! - Integers/bools/strings: //! They must be strictly equal. -//! +//! //! - Arrays: //! They must have the same length, and have elements that compare equal. -//! +//! //! - Sets/Maps: //! The set/map in the interface must be a subset of the implementation, -//! +//! //! # Examples -//! -//! -//! ### Declaring a unit type with a tag. -//! +//! +//! +//! ### Declaring a unit type with a tag. +//! #![cfg_attr(not(feature = "no_tagging_doctest"), doc = "```rust")] #![cfg_attr(feature = "no_tagging_doctest", doc = "```ignore")] -//! +//! //! use abi_stable::{tag,StableAbi}; -//! +//! //! #[repr(C)] //! #[derive(StableAbi)] //! #[sabi( tag = r##" tag!("WAT") "## )] //! struct UnitType; -//! -//! +//! +//! //! # fn main(){} -//! -//! +//! +//! //! ``` -//! -//! ### Emulating const generics for strings -//! +//! +//! ### Emulating const generics for strings +//! //! This emulates a `const NAME:&'static str` parameter, //! which is checked as being the same between the interface and implementation. -//! -//! +//! +//! #![cfg_attr(not(feature = "no_tagging_doctest"), doc = "```rust")] #![cfg_attr(feature = "no_tagging_doctest", doc = "```ignore")] //! use abi_stable::{tag,StableAbi,marker_type::UnsafeIgnoredType}; -//! -//! +//! +//! //! trait Name{ //! const NAME:&'static str; //! } -//! +//! //! /// //! /// The layout of `StringParameterized` is determined by `::NAME`, -//! /// allowing the interface crate to have a different `S` +//! /// allowing the interface crate to have a different `S` //! /// type parameter than the implementation crate, //! /// so long as they have the same associated `&'static str`. //! /// @@ -68,74 +68,74 @@ //! /// //! #[repr(C)] //! #[derive(StableAbi)] -//! #[sabi( +//! #[sabi( //! bound="S:Name", //! tag = r##" tag!( S::NAME ) "## , //! )] //! struct StringParameterized{ //! _marker:UnsafeIgnoredType //! } -//! +//! //! #[repr(C)] //! #[derive(StableAbi)] //! struct Foo; -//! +//! //! impl Name for Foo{ //! const NAME:&'static str="Hello, World!"; //! } -//! -//! +//! +//! //! #[repr(C)] //! #[derive(StableAbi)] //! struct Bar; -//! +//! //! impl Name for Bar{ //! const NAME:&'static str="Hello, Helloooooo!"; //! } -//! -//! +//! +//! //! #[repr(C)] //! #[derive(StableAbi)] //! struct Boor; -//! +//! //! impl Name for Boor{ //! const NAME:&'static str="This is a different string!"; //! } -//! +//! //! # fn main(){} -//! +//! //! ``` -//! -//! ### Declaring each variant. -//! +//! +//! ### Declaring each variant. +//! #![cfg_attr(not(feature = "no_tagging_doctest"), doc = "```rust")] #![cfg_attr(feature = "no_tagging_doctest", doc = "```ignore")] //! use abi_stable::{ //! rslice,tag, //! type_layout::Tag, //! }; -//! +//! //! const NULL:Tag=Tag::null(); -//! -//! +//! +//! //! const BOOL_MACRO:Tag=tag!( false ); //! const BOOL_FN :Tag=Tag::bool_(false); -//! -//! +//! +//! //! const INT_MACRO_0:Tag=tag!( 100 ); //! const INT_FN_0 :Tag=Tag::int(100); -//! +//! //! const INT_MACRO_1:Tag=tag!( -100 ); //! const INT_FN_1 :Tag=Tag::int(-100); -//! -//! +//! +//! //! // This can only be declared using the function for now. //! const UINT:Tag=Tag::uint(100); -//! -//! +//! +//! //! const STR_0_MACRO:Tag=tag!("Hello,World!"); //! const STR_0_FN:Tag=Tag::str("Hello,World!"); -//! +//! //! const ARR_0_MACRO:Tag=tag![[ 0,1,2,3 ]]; //! const ARR_0_FN:Tag=Tag::arr(rslice![ //! Tag::int(0), @@ -143,8 +143,8 @@ //! Tag::int(2), //! Tag::int(3), //! ]); -//! -//! +//! +//! //! const SET_0_MACRO:Tag=tag!{{ 0,1,2,3 }}; //! const SET_0_FN:Tag=Tag::set(rslice![ //! Tag::int(0), @@ -152,8 +152,8 @@ //! Tag::int(2), //! Tag::int(3), //! ]); -//! -//! +//! +//! //! const MAP_0_MACRO:Tag=tag!{{ //! 0=>"a", //! 1=>"b", @@ -166,21 +166,21 @@ //! Tag::kv( Tag::int(2), Tag::bool_(false)), //! Tag::kv( Tag::int(3), Tag::int(100)), //! ]); -//! +//! //! # fn main(){} -//! +//! //! ``` -//! -//! ### Creating a complex data structure. -//! -//! +//! +//! ### Creating a complex data structure. +//! +//! #![cfg_attr(not(feature = "no_tagging_doctest"), doc = "```rust")] #![cfg_attr(feature = "no_tagging_doctest", doc = "```ignore")] //! use abi_stable::{ //! tag, //! type_layout::Tag, //! }; -//! +//! //! const TAG:Tag=tag!{{ //! // This must match exactly, //! // adding required traits on the interface or the implementation @@ -193,77 +193,64 @@ //! "Debug", //! "Display", //! }}, -//! -//! +//! +//! //! "maps"=>tag!{{ //! 0=>"Zero", //! 1=>"One", //! }} //! }}; -//! -//! +//! +//! //! ``` - - use std::{ collections::BTreeMap, - fmt::{self,Display}, + fmt::{self, Display}, mem, }; - -use core_extensions::{ - matches, - SelfOps -}; +use core_extensions::{matches, SelfOps}; use crate::{ - StableAbi, abi_stability::extra_checks::{ - TypeCheckerMut, - ExtraChecks,ForExtraChecksImplementor,ExtraChecksError, + ExtraChecks, ExtraChecksError, ForExtraChecksImplementor, TypeCheckerMut, }, - std_types::{RSlice,RStr,RBox,RCow,RVec,ROption,RSome,RNone,RResult}, + std_types::{RBox, RCow, RNone, ROption, RResult, RSlice, RSome, RStr, RVec}, traits::IntoReprC, - utils::FmtPadding, type_layout::TypeLayout, + utils::FmtPadding, + StableAbi, }; - - - - -/// Tag is a dynamically typed data structure used to encode extra properties +/// Tag is a dynamically typed data structure used to encode extra properties /// about a type in its layout constant. /// /// For more information [look at the module-level documentation](./index.html) #[repr(C)] -#[derive(Debug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,Hash,StableAbi)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, StableAbi)] #[sabi(unsafe_sabi_opaque_fields)] -pub struct Tag{ - variant:TagVariant, +pub struct Tag { + variant: TagVariant, } - /// All the Tag variants. #[repr(u8)] -#[derive(Debug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,Hash,StableAbi)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, StableAbi)] #[sabi(unsafe_sabi_opaque_fields)] -pub enum TagVariant{ +pub enum TagVariant { Primitive(Primitive), Ignored(&'static Tag), - Array(RSlice<'static,Tag>), - Set(RSlice<'static,Tag>), - Map(RSlice<'static,KeyValue>), + Array(RSlice<'static, Tag>), + Set(RSlice<'static, Tag>), + Map(RSlice<'static, KeyValue>), } - /// The primitive types of a variant,which do not contain other nested tags. #[repr(u8)] -#[derive(Debug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,Hash,StableAbi)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, StableAbi)] #[sabi(unsafe_sabi_opaque_fields)] -pub enum Primitive{ +pub enum Primitive { Null, Bool(bool), Int(i64), @@ -273,17 +260,17 @@ pub enum Primitive{ /// A tag that can be checked for compatibility with another tag. #[repr(C)] -#[derive(Debug,Clone,PartialEq,Eq,PartialOrd,Ord,Hash,StableAbi)] +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, StableAbi)] #[sabi(unsafe_sabi_opaque_fields)] -pub struct CheckableTag{ - variant:CTVariant, +pub struct CheckableTag { + variant: CTVariant, } /// The possible variants of CheckableTag. #[repr(u8)] -#[derive(Debug,Clone,PartialEq,Eq,PartialOrd,Ord,Hash,StableAbi)] +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, StableAbi)] #[sabi(unsafe_sabi_opaque_fields)] -pub enum CTVariant{ +pub enum CTVariant { Primitive(Primitive), Ignored(RBox), Array(RVec), @@ -291,672 +278,640 @@ pub enum CTVariant{ Map(RVec>), } - - /// A key-value pair,used when constructing a map. #[repr(C)] -#[derive(Debug,Copy,Clone,PartialEq,Eq,PartialOrd,Ord,Hash,StableAbi)] -pub struct KeyValue{ - pub key:T, - pub value:T, +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, StableAbi)] +pub struct KeyValue { + pub key: T, + pub value: T, } #[doc(hidden)] -pub trait TagTrait{ - fn is_null(&self)->bool; +pub trait TagTrait { + fn is_null(&self) -> bool; } -impl TagTrait for Tag{ - fn is_null(&self)->bool{ - self.variant==TagVariant::Primitive(Primitive::Null) +impl TagTrait for Tag { + fn is_null(&self) -> bool { + self.variant == TagVariant::Primitive(Primitive::Null) } } -impl<'a> TagTrait for &'a Tag{ - fn is_null(&self)->bool{ - self.variant==TagVariant::Primitive(Primitive::Null) +impl<'a> TagTrait for &'a Tag { + fn is_null(&self) -> bool { + self.variant == TagVariant::Primitive(Primitive::Null) } } -impl TagTrait for CheckableTag{ - fn is_null(&self)->bool{ - self.variant==CTVariant::Primitive(Primitive::Null) +impl TagTrait for CheckableTag { + fn is_null(&self) -> bool { + self.variant == CTVariant::Primitive(Primitive::Null) } } impl TagTrait for KeyValue -where - KV:TagTrait +where + KV: TagTrait, { - fn is_null(&self)->bool{ + fn is_null(&self) -> bool { self.key.is_null() } } -impl<'a,KV> TagTrait for &'a KeyValue -where - KV:TagTrait +impl<'a, KV> TagTrait for &'a KeyValue +where + KV: TagTrait, { - fn is_null(&self)->bool{ + fn is_null(&self) -> bool { self.key.is_null() } } -impl<'a> TagTrait for &'a CheckableTag{ - fn is_null(&self)->bool{ - *self==&Tag::null().to_checkable() +impl<'a> TagTrait for &'a CheckableTag { + fn is_null(&self) -> bool { + *self == &Tag::null().to_checkable() } } - -impl Tag{ - const fn new(variant:TagVariant)->Self{ - Self{ - variant, - } +impl Tag { + const fn new(variant: TagVariant) -> Self { + Self { variant } } - pub const NULL:&'static Tag=&Tag::null(); + pub const NULL: &'static Tag = &Tag::null(); /// Constructs the Null variant. - pub const fn null()->Self{ + pub const fn null() -> Self { Self::new(TagVariant::Primitive(Primitive::Null)) } /// Constructs the Bool variant. - pub const fn bool_(b:bool)->Self{ + pub const fn bool_(b: bool) -> Self { Self::new(TagVariant::Primitive(Primitive::Bool(b))) } /// Constructs the Int variant. - pub const fn int(n:i64)->Self{ + pub const fn int(n: i64) -> Self { Self::new(TagVariant::Primitive(Primitive::Int(n))) } /// Constructs the UInt variant. - pub const fn uint(n:u64)->Self{ + pub const fn uint(n: u64) -> Self { Self::new(TagVariant::Primitive(Primitive::UInt(n))) } /// Constructs the String_ variant. - pub const fn str(s:&'static str)->Self{ + pub const fn str(s: &'static str) -> Self { Self::new(TagVariant::Primitive(Primitive::String_(RStr::from_str(s)))) } /// Constructs the String_ variant. - pub const fn rstr(s:RStr<'static>)->Self{ + pub const fn rstr(s: RStr<'static>) -> Self { Self::new(TagVariant::Primitive(Primitive::String_(s))) } /// Constructs the Ignored variant. - pub const fn ignored(ignored:&'static Tag)->Self{ + pub const fn ignored(ignored: &'static Tag) -> Self { Self::new(TagVariant::Ignored(ignored)) } /// Constructs the Array variant. - pub const fn arr(s:RSlice<'static,Tag>)->Self{ + pub const fn arr(s: RSlice<'static, Tag>) -> Self { Self::new(TagVariant::Array(s)) } /// Constructs the Set variant. - pub const fn set(s:RSlice<'static,Tag>)->Self{ + pub const fn set(s: RSlice<'static, Tag>) -> Self { Self::new(TagVariant::Set(s)) } /// Constructs a KeyValue. - pub const fn kv(key:Tag,value:Tag)->KeyValue{ - KeyValue{key,value} + pub const fn kv(key: Tag, value: Tag) -> KeyValue { + KeyValue { key, value } } /// Constructs the Map variant. - pub const fn map(s:RSlice<'static,KeyValue>)->Self{ + pub const fn map(s: RSlice<'static, KeyValue>) -> Self { Self::new(TagVariant::Map(s)) } } -impl Tag{ +impl Tag { /// Converts the `Tag` into a `CheckableTag`, /// so as to check `Tag`s for compatibility. - pub fn to_checkable(self)->CheckableTag{ - let variant=match self.variant { - TagVariant::Primitive(prim)=> - CTVariant::Primitive(prim), - TagVariant::Ignored(ignored)=>{ - (*ignored).to_checkable() - .piped(RBox::new) - .piped(CTVariant::Ignored) - } - TagVariant::Array(arr)=>{ - arr.iter().cloned() - .filter(|x| *x!=Tag::null() ) - .map(Self::to_checkable) - .collect::>() - .piped(CTVariant::Array) - } - TagVariant::Set(arr)=>{ - arr.iter().cloned() - .filter(|x| !x.is_null() ) - .map(|x| (x.to_checkable(),Tag::null().to_checkable()) ) - .piped(sorted_ct_vec_from_iter) - .piped(CTVariant::Set) - } - TagVariant::Map(arr)=>{ - arr.iter().cloned() - .filter(|kv| !kv.key.is_null() ) - .map(|x| x.map(|y|y.to_checkable()).into_pair() ) - .piped(sorted_ct_vec_from_iter) - .piped(CTVariant::Map) - } + pub fn to_checkable(self) -> CheckableTag { + let variant = match self.variant { + TagVariant::Primitive(prim) => CTVariant::Primitive(prim), + TagVariant::Ignored(ignored) => (*ignored) + .to_checkable() + .piped(RBox::new) + .piped(CTVariant::Ignored), + TagVariant::Array(arr) => arr + .iter() + .cloned() + .filter(|x| *x != Tag::null()) + .map(Self::to_checkable) + .collect::>() + .piped(CTVariant::Array), + TagVariant::Set(arr) => arr + .iter() + .cloned() + .filter(|x| !x.is_null()) + .map(|x| (x.to_checkable(), Tag::null().to_checkable())) + .piped(sorted_ct_vec_from_iter) + .piped(CTVariant::Set), + TagVariant::Map(arr) => arr + .iter() + .cloned() + .filter(|kv| !kv.key.is_null()) + .map(|x| x.map(|y| y.to_checkable()).into_pair()) + .piped(sorted_ct_vec_from_iter) + .piped(CTVariant::Map), }; - CheckableTag{ - variant, - } + CheckableTag { variant } } } - -fn sorted_ct_vec_from_iter(iter:I)->RVec> -where I:IntoIterator +fn sorted_ct_vec_from_iter(iter: I) -> RVec> +where + I: IntoIterator, { iter.into_iter() - .collect::>() + .collect::>() .into_iter() .map(KeyValue::from_pair) .collect::>>() } - -impl CheckableTag{ +impl CheckableTag { /// Checks that this `CheckableTag` is compatible with another one, /// returning `Ok` if it is compatible, `Err` if it was not. - pub fn check_compatible(&self,other:&Self)->Result<(),TagErrors>{ + pub fn check_compatible(&self, other: &Self) -> Result<(), TagErrors> { use self::CTVariant as CTV; - let err_with_variant=|vari:TagErrorVariant|{ - TagErrors{ - expected:self.clone(), - found:other.clone(), - backtrace:vec![].into(), - errors:vec![vari].into(), - } + let err_with_variant = |vari: TagErrorVariant| TagErrors { + expected: self.clone(), + found: other.clone(), + backtrace: vec![].into(), + errors: vec![vari].into(), }; - let mismatched_val_err=|cond:bool|{ + let mismatched_val_err = |cond: bool| { if cond { Ok(()) - }else{ + } else { Err(err_with_variant(TagErrorVariant::MismatchedValue)) } }; - let same_variant=match (&self.variant,&other.variant) { - (CTV::Primitive(Primitive::Null),_)=> - return Ok(()), - (CTV::Primitive(l),CTV::Primitive(r))=> - mem::discriminant(l)==mem::discriminant(r), - (l,r)=> - mem::discriminant(l)==mem::discriminant(r), + let same_variant = match (&self.variant, &other.variant) { + (CTV::Primitive(Primitive::Null), _) => return Ok(()), + (CTV::Primitive(l), CTV::Primitive(r)) => mem::discriminant(l) == mem::discriminant(r), + (l, r) => mem::discriminant(l) == mem::discriminant(r), }; if !same_variant { - return Err(err_with_variant(TagErrorVariant::MismatchedDiscriminant)) + return Err(err_with_variant(TagErrorVariant::MismatchedDiscriminant)); } - let is_map=matches!(self.variant, CTV::Map{..}); - - match (&self.variant,&other.variant) { - (CTV::Primitive(l),CTV::Primitive(r))=>{ - match (l,r) { - (Primitive::Null,Primitive::Null)=>(), - (Primitive::Null,_)=>(), - - (Primitive::Bool(l_cond),Primitive::Bool(r_cond))=> - mismatched_val_err(l_cond==r_cond)?, - (Primitive::Bool(_),_)=>{}, - - (Primitive::Int(l_num),Primitive::Int(r_num))=> - mismatched_val_err(l_num==r_num)?, - (Primitive::Int(_),_)=>{}, - - (Primitive::UInt(l_num),Primitive::UInt(r_num))=> - mismatched_val_err(l_num==r_num)?, - (Primitive::UInt(_),_)=>{}, - - (Primitive::String_(l_str),Primitive::String_(r_str))=> - mismatched_val_err(l_str.as_str()==r_str.as_str())?, - (Primitive::String_(_),_)=>{}, - } + let is_map = matches!(self.variant, CTV::Map { .. }); + + match (&self.variant, &other.variant) { + (CTV::Primitive(l), CTV::Primitive(r)) => match (l, r) { + (Primitive::Null, Primitive::Null) => (), + (Primitive::Null, _) => (), + + (Primitive::Bool(l_cond), Primitive::Bool(r_cond)) => { + mismatched_val_err(l_cond == r_cond)? + } + (Primitive::Bool(_), _) => {} + + (Primitive::Int(l_num), Primitive::Int(r_num)) => { + mismatched_val_err(l_num == r_num)? + } + (Primitive::Int(_), _) => {} + + (Primitive::UInt(l_num), Primitive::UInt(r_num)) => { + mismatched_val_err(l_num == r_num)? + } + (Primitive::UInt(_), _) => {} + + (Primitive::String_(l_str), Primitive::String_(r_str)) => { + mismatched_val_err(l_str.as_str() == r_str.as_str())? + } + (Primitive::String_(_), _) => {} }, - (CTV::Primitive(_),_)=>{} - - (CTV::Ignored(_),_)=>{} - - (CTV::Array(l_arr),CTV::Array(r_arr))=>{ - let l_arr=l_arr.as_slice(); - let r_arr=r_arr.as_slice(); - - if l_arr.len()!=r_arr.len() { - let e=TagErrorVariant::MismatchedArrayLength{ - expected:l_arr.len(), - found:r_arr.len(), + (CTV::Primitive(_), _) => {} + + (CTV::Ignored(_), _) => {} + + (CTV::Array(l_arr), CTV::Array(r_arr)) => { + let l_arr = l_arr.as_slice(); + let r_arr = r_arr.as_slice(); + + if l_arr.len() != r_arr.len() { + let e = TagErrorVariant::MismatchedArrayLength { + expected: l_arr.len(), + found: r_arr.len(), }; return Err(err_with_variant(e)); } - for (l_elem,r_elem) in l_arr.iter().zip(r_arr.iter()) { - l_elem.check_compatible(r_elem) - .map_err(|errs| errs.context(l_elem.clone()) )?; + for (l_elem, r_elem) in l_arr.iter().zip(r_arr.iter()) { + l_elem + .check_compatible(r_elem) + .map_err(|errs| errs.context(l_elem.clone()))?; } } - (CTV::Array(_),_)=>{}, - - (CTV::Set(l_map),CTV::Set(r_map)) - |(CTV::Map(l_map),CTV::Map(r_map))=>{ + (CTV::Array(_), _) => {} + + (CTV::Set(l_map), CTV::Set(r_map)) | (CTV::Map(l_map), CTV::Map(r_map)) => { if l_map.len() > r_map.len() { - let e=TagErrorVariant::MismatchedAssocLength{ - expected:l_map.len(), - found:r_map.len(), + let e = TagErrorVariant::MismatchedAssocLength { + expected: l_map.len(), + found: r_map.len(), }; return Err(err_with_variant(e)); } - let mut r_iter=r_map.iter().map(KeyValue::as_pair); + let mut r_iter = r_map.iter().map(KeyValue::as_pair); + + 'outer: for (l_key, l_elem) in l_map.iter().map(KeyValue::as_pair) { + let mut first_err = None::>; - 'outer:for (l_key,l_elem) in l_map.iter().map(KeyValue::as_pair) { - let mut first_err=None::>; - - 'inner:loop { - let (r_key,r_elem)=match r_iter.next() { - Some(x)=>x, - None=>break 'inner, + 'inner: loop { + let (r_key, r_elem) = match r_iter.next() { + Some(x) => x, + None => break 'inner, }; - match l_key.check_compatible(r_key) - .and_then(|_| l_elem.check_compatible(r_elem) ) + match l_key + .check_compatible(r_key) + .and_then(|_| l_elem.check_compatible(r_elem)) { - Ok(_)=>continue 'outer, - Err(_)=>{ - first_err.get_or_insert( KeyValue::new(r_key,r_elem) ); - }, + Ok(_) => continue 'outer, + Err(_) => { + first_err.get_or_insert(KeyValue::new(r_key, r_elem)); + } } } - let e=if is_map { - TagErrorVariant::MismatchedMapEntry{ - expected:KeyValue::new(l_key.clone(),l_elem.clone()), - found:first_err.map(|x|x.map(Clone::clone)).into_c(), + let e = if is_map { + TagErrorVariant::MismatchedMapEntry { + expected: KeyValue::new(l_key.clone(), l_elem.clone()), + found: first_err.map(|x| x.map(Clone::clone)).into_c(), } - }else{ - TagErrorVariant::MissingSetValue{ - expected:l_key.clone(), - found:first_err.map(|x|x.key).cloned().into_c(), + } else { + TagErrorVariant::MissingSetValue { + expected: l_key.clone(), + found: first_err.map(|x| x.key).cloned().into_c(), } }; return Err(err_with_variant(e)); } } - (CTV::Set(_),_)=>{}, - (CTV::Map(_),_)=>{}, + (CTV::Set(_), _) => {} + (CTV::Map(_), _) => {} } Ok(()) } - } - ///////////////////////////////////////////////////////////////// -impl KeyValue{ +impl KeyValue { /// Constructs a KeyValue with `key`,`value` - pub const fn new(key:T,value:T)->Self{ - Self{ key,value } + pub const fn new(key: T, value: T) -> Self { + Self { key, value } } /// Transforms the `KeyValue` to `KeyValue`, /// using `f` to convert `T` to `U`. - pub fn map(self,mut f:F)->KeyValue - where F:FnMut(T)->U + pub fn map(self, mut f: F) -> KeyValue + where + F: FnMut(T) -> U, { - KeyValue{ - key:f(self.key), - value:f(self.value), + KeyValue { + key: f(self.key), + value: f(self.value), } } /// Converts the KeyValue into a `(key, value)` pair. - pub fn into_pair(self)->(T,T){ - (self.key,self.value) + pub fn into_pair(self) -> (T, T) { + (self.key, self.value) } /// Casts a &KeyValue into a `(key, value)` pair of references. - pub fn as_pair(&self)->(&T,&T){ - ( - &self.key, - &self.value, - ) + pub fn as_pair(&self) -> (&T, &T) { + (&self.key, &self.value) } /// Converts a `(key, value)` pair into a KeyValue. - pub fn from_pair((key,value):(T,T))->Self{ - Self{ key,value } + pub fn from_pair((key, value): (T, T)) -> Self { + Self { key, value } } } -impl Display for KeyValue -where T:Display+TagTrait +impl Display for KeyValue +where + T: Display + TagTrait, { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - write!(f,"{}",self.key)?; + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.key)?; if !self.value.is_null() { - write!(f,"=>{}",self.value)?; + write!(f, "=>{}", self.value)?; } Ok(()) } } - ///////////////////////////////////////////////////////////////// - /// Used to convert many types to `Tag`. pub struct FromLiteral(pub T); #[allow(clippy::wrong_self_convention)] -impl FromLiteral{ +impl FromLiteral { /// Converts the wrapped `bool` into a Tag. - pub const fn to_tag(self)->Tag{ + pub const fn to_tag(self) -> Tag { Tag::bool_(self.0) } } #[allow(clippy::wrong_self_convention)] -impl FromLiteral<&'static str>{ +impl FromLiteral<&'static str> { /// Converts the wrapped `&'static str` into a Tag. - pub const fn to_tag(self)->Tag{ + pub const fn to_tag(self) -> Tag { Tag::str(self.0) } } #[allow(clippy::wrong_self_convention)] -impl FromLiteral>{ +impl FromLiteral> { /// Converts the wrapped `RStr<'static>` into a Tag. - pub const fn to_tag(self)->Tag{ + pub const fn to_tag(self) -> Tag { Tag::rstr(self.0) } } #[allow(clippy::wrong_self_convention)] -impl FromLiteral{ +impl FromLiteral { /// Converts the wrapped `i64` into a Tag. - pub const fn to_tag(self)->Tag{ + pub const fn to_tag(self) -> Tag { Tag::int(self.0) } } #[allow(clippy::wrong_self_convention)] -impl FromLiteral{ +impl FromLiteral { /// Converts the wrapped `Tag` into a Tag. - pub const fn to_tag(self)->Tag{ + pub const fn to_tag(self) -> Tag { self.0 } } - ///////////////////////////////////////////////////////////////// - -fn display_iter(iter:I,f:&mut fmt::Formatter<'_>,indent:usize)->fmt::Result +fn display_iter(iter: I, f: &mut fmt::Formatter<'_>, indent: usize) -> fmt::Result where - I:IntoIterator, - I::Item:Display+TagTrait, + I: IntoIterator, + I::Item: Display + TagTrait, { - let mut buffer=String::new(); - for elem in iter.into_iter().filter(|x| !x.is_null() ) { - Display::fmt(&buffer.display_pad(indent,&elem)?,f)?; - writeln!(f,",")?; + let mut buffer = String::new(); + for elem in iter.into_iter().filter(|x| !x.is_null()) { + Display::fmt(&buffer.display_pad(indent, &elem)?, f)?; + writeln!(f, ",")?; } Ok(()) } - - - impl Display for Primitive { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - Primitive::Null=>{ - write!(f,"null")?; - }, - Primitive::Bool(cond)=>{ - write!(f,"{}",cond)?; - }, - Primitive::Int(num)=>{ - write!(f,"{}",num)?; - }, - Primitive::UInt(num)=>{ - write!(f,"{}",num)?; - }, - Primitive::String_(s)=>{ - write!(f,"'{}'",s)?; - }, + Primitive::Null => { + write!(f, "null")?; + } + Primitive::Bool(cond) => { + write!(f, "{}", cond)?; + } + Primitive::Int(num) => { + write!(f, "{}", num)?; + } + Primitive::UInt(num) => { + write!(f, "{}", num)?; + } + Primitive::String_(s) => { + write!(f, "'{}'", s)?; + } } Ok(()) } } - impl Display for Tag { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match &self.variant { - TagVariant::Primitive(prim)=>{ - Display::fmt(prim,f)?; - }, - TagVariant::Ignored(ignored)=>{ - Display::fmt(ignored,f)?; + TagVariant::Primitive(prim) => { + Display::fmt(prim, f)?; + } + TagVariant::Ignored(ignored) => { + Display::fmt(ignored, f)?; + } + TagVariant::Array(arr) => { + writeln!(f, "[")?; + display_iter(&**arr, f, 4)?; + write!(f, "]")?; + } + TagVariant::Set(map) => { + writeln!(f, "{{")?; + display_iter(map.iter(), f, 4)?; + write!(f, "}}")?; + } + TagVariant::Map(map) => { + writeln!(f, "{{")?; + display_iter(map.iter(), f, 4)?; + write!(f, "}}")?; } - TagVariant::Array(arr)=>{ - writeln!(f,"[")?; - display_iter(&**arr,f,4)?; - write!(f,"]")?; - }, - TagVariant::Set(map)=>{ - writeln!(f,"{{")?; - display_iter(map.iter(),f,4)?; - write!(f,"}}")?; - }, - TagVariant::Map(map)=>{ - writeln!(f,"{{")?; - display_iter(map.iter(),f,4)?; - write!(f,"}}")?; - }, } Ok(()) } } impl Display for CheckableTag { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match &self.variant { - CTVariant::Primitive(prim)=>{ - Display::fmt(prim,f)?; - }, - CTVariant::Ignored(ignored)=>{ - Display::fmt(ignored,f)?; + CTVariant::Primitive(prim) => { + Display::fmt(prim, f)?; + } + CTVariant::Ignored(ignored) => { + Display::fmt(ignored, f)?; + } + CTVariant::Array(arr) => { + writeln!(f, "[")?; + display_iter(&*arr, f, 4)?; + write!(f, "]")?; + } + CTVariant::Set(map) | CTVariant::Map(map) => { + writeln!(f, "{{")?; + display_iter(map.iter(), f, 4)?; + write!(f, "}}")?; } - CTVariant::Array(arr)=>{ - writeln!(f,"[")?; - display_iter(&*arr,f,4)?; - write!(f,"]")?; - }, - CTVariant::Set(map)|CTVariant::Map(map)=>{ - writeln!(f,"{{")?; - display_iter(map.iter(),f,4)?; - write!(f,"}}")?; - }, } Ok(()) } } - ///////////////////////////////////////////////////////////////// - - ///////////////////////////////////////////////////////////////// - /// The error produced when checking `CheckableTag`s. -#[derive(Debug,Clone,PartialEq)] -pub struct TagErrors{ - expected:CheckableTag, - found:CheckableTag, - backtrace:RVec, - errors:RVec, +#[derive(Debug, Clone, PartialEq)] +pub struct TagErrors { + expected: CheckableTag, + found: CheckableTag, + backtrace: RVec, + errors: RVec, } - -impl TagErrors{ - fn context(mut self,current:CheckableTag)->Self{ +impl TagErrors { + fn context(mut self, current: CheckableTag) -> Self { self.backtrace.push(current); self } } - impl Display for TagErrors { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - let mut buffer=String::new(); + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut buffer = String::new(); - writeln!(f,"Stacktrace:")?; + writeln!(f, "Stacktrace:")?; if self.backtrace.is_empty() { - writeln!(f," Empty.")?; - }else{ + writeln!(f, " Empty.")?; + } else { for stack in self.backtrace.iter().rev() { - writeln!(f," Inside:\n{},",buffer.display_pad(8,stack)? )?; + writeln!(f, " Inside:\n{},", buffer.display_pad(8, stack)?)?; } } - writeln!(f,"Expected:\n{}",buffer.display_pad(4,&self.expected)? )?; - writeln!(f,"Found:\n{}",buffer.display_pad(4,&self.found)? )?; - writeln!(f,"Errors:\n")?; + writeln!(f, "Expected:\n{}", buffer.display_pad(4, &self.expected)?)?; + writeln!(f, "Found:\n{}", buffer.display_pad(4, &self.found)?)?; + writeln!(f, "Errors:\n")?; for err in self.errors.iter().rev() { - writeln!(f,"\n{},",buffer.display_pad(4,err)? )?; + writeln!(f, "\n{},", buffer.display_pad(4, err)?)?; } Ok(()) } } -impl std::error::Error for TagErrors{} - +impl std::error::Error for TagErrors {} ///////////////////////////////////////////////////////////////// - unsafe impl ExtraChecks for Tag { - fn type_layout(&self)->&'static TypeLayout{ + fn type_layout(&self) -> &'static TypeLayout { Self::LAYOUT } fn check_compatibility( &self, - _layout_containing_self:&'static TypeLayout, - layout_containing_other:&'static TypeLayout, - checker:TypeCheckerMut<'_>, - )->RResult<(), ExtraChecksError> { - Self::downcast_with_layout(layout_containing_other,checker,|other,_|{ - let t_tag=self.to_checkable(); - let o_tag=other.to_checkable(); + _layout_containing_self: &'static TypeLayout, + layout_containing_other: &'static TypeLayout, + checker: TypeCheckerMut<'_>, + ) -> RResult<(), ExtraChecksError> { + Self::downcast_with_layout(layout_containing_other, checker, |other, _| { + let t_tag = self.to_checkable(); + let o_tag = other.to_checkable(); t_tag.check_compatible(&o_tag) }) } - fn nested_type_layouts(&self)->RCow<'_,[&'static TypeLayout]>{ + fn nested_type_layouts(&self) -> RCow<'_, [&'static TypeLayout]> { RCow::from_slice(&[]) } } - ///////////////////////////////////////////////////////////////// - #[repr(u8)] -#[derive(Debug,Clone,PartialEq,StableAbi)] -pub(crate) enum TagErrorVariant{ +#[derive(Debug, Clone, PartialEq, StableAbi)] +pub(crate) enum TagErrorVariant { MismatchedDiscriminant, MismatchedValue, - MismatchedArrayLength{ - expected:usize, - found:usize, + MismatchedArrayLength { + expected: usize, + found: usize, }, - MismatchedAssocLength{ - expected:usize, - found:usize, + MismatchedAssocLength { + expected: usize, + found: usize, }, - MissingSetValue{ - expected:CheckableTag, - found:ROption, + MissingSetValue { + expected: CheckableTag, + found: ROption, }, - MismatchedMapEntry{ - expected:KeyValue, - found:ROption>, + MismatchedMapEntry { + expected: KeyValue, + found: ROption>, }, } - impl Display for TagErrorVariant { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - TagErrorVariant::MismatchedDiscriminant=>{ - writeln!(f,"Mismatched Tag variant.")?; + TagErrorVariant::MismatchedDiscriminant => { + writeln!(f, "Mismatched Tag variant.")?; } - TagErrorVariant::MismatchedValue=>{ - writeln!(f,"Mitmatched Value.")?; + TagErrorVariant::MismatchedValue => { + writeln!(f, "Mitmatched Value.")?; } - TagErrorVariant::MismatchedArrayLength{expected,found}=>{ - writeln!(f,"Mismatched length expected:{} found:{}",expected,found)?; + TagErrorVariant::MismatchedArrayLength { expected, found } => { + writeln!( + f, + "Mismatched length expected:{} found:{}", + expected, found + )?; } - TagErrorVariant::MismatchedAssocLength{expected,found}=>{ + TagErrorVariant::MismatchedAssocLength { expected, found } => { writeln!( f, "Mismatched length expected at least:{} found:{}", - expected, - found, + expected, found, )?; } - TagErrorVariant::MissingSetValue{expected,found}=>{ - let mut buffer=String::new(); + TagErrorVariant::MissingSetValue { expected, found } => { + let mut buffer = String::new(); writeln!( f, "Mismatched value in set\nExpected:\n{}", - buffer.display_pad(4,&expected)? + buffer.display_pad(4, &expected)? )?; match found { - RSome(found) => writeln!(f,"Found:\n{}",buffer.display_pad(4,&found)?), - RNone => writeln!(f,"Found:\n Nothing",), + RSome(found) => writeln!(f, "Found:\n{}", buffer.display_pad(4, &found)?), + RNone => writeln!(f, "Found:\n Nothing",), }?; - }, - TagErrorVariant::MismatchedMapEntry{expected,found}=>{ - let mut buffer=String::new(); + } + TagErrorVariant::MismatchedMapEntry { expected, found } => { + let mut buffer = String::new(); writeln!( f, "Mismatched entry in map\nExpected:\n{}", - buffer.display_pad(4,&expected)? + buffer.display_pad(4, &expected)? )?; match found { - RSome(found) => writeln!(f,"Found:\n{}",buffer.display_pad(4,&found)?), - RNone => writeln!(f,"Found:\n Nothing",), + RSome(found) => writeln!(f, "Found:\n{}", buffer.display_pad(4, &found)?), + RNone => writeln!(f, "Found:\n Nothing",), }?; - }, + } } Ok(()) } } - - - //////////////////////////////////////////////////////////////////////////////// - - -#[cfg(all(test,not(feature="only_new_tests"), not(feature = "no_fn_promotion")))] +#[cfg(all( + test, + not(feature = "only_new_tests"), + not(feature = "no_fn_promotion") +))] mod test; diff --git a/abi_stable/src/type_layout/tagging/test.rs b/abi_stable/src/type_layout/tagging/test.rs index e2661894..4733990d 100644 --- a/abi_stable/src/type_layout/tagging/test.rs +++ b/abi_stable/src/type_layout/tagging/test.rs @@ -1,97 +1,91 @@ use super::*; -/// Asserts that all elements are compatible with themselves and +/// Asserts that all elements are compatible with themselves and /// not equal to the other elements -fn assert_distinct_elements(array:&[Tag]){ - let array=array.iter().cloned() +fn assert_distinct_elements(array: &[Tag]) { + let array = array + .iter() + .cloned() .map(Tag::to_checkable) .collect::>(); - for (index,value) in array.iter().enumerate() { + for (index, value) in array.iter().enumerate() { assert_eq!(value.check_compatible(value), Ok(())); - for (_,incomp) in array.iter().enumerate().filter(|(i,_)| *i!=index ) { - assert_ne!( - value.check_compatible(incomp), - Ok(()), - ); + for (_, incomp) in array.iter().enumerate().filter(|(i, _)| *i != index) { + assert_ne!(value.check_compatible(incomp), Ok(()),); } } } +const TAG_SET_EMPTY: Tag = Tag::set(rslice![]); +const TAG_ARR_EMPTY: Tag = Tag::arr(rslice![]); +const TAG_SET_0: Tag = Tag::set(rslice![Tag::bool_(false)]); +const TAG_ARR_0: Tag = Tag::arr(rslice![Tag::bool_(false)]); -const TAG_SET_EMPTY:Tag=Tag::set(rslice![]); -const TAG_ARR_EMPTY:Tag=Tag::arr(rslice![]); - -const TAG_SET_0:Tag=Tag::set(rslice![Tag::bool_(false)]); -const TAG_ARR_0:Tag=Tag::arr(rslice![Tag::bool_(false)]); - - - -const TAG_1_ORDER_0_VALUE:RSlice<'static,Tag>=rslice![ +const TAG_1_ORDER_0_VALUE: RSlice<'static, Tag> = rslice![ Tag::bool_(false), Tag::bool_(true), - Tag::arr(rslice![Tag::uint(0),Tag::int(-100)]), + Tag::arr(rslice![Tag::uint(0), Tag::int(-100)]), Tag::int(-100), Tag::int(100), - Tag::set(rslice![ Tag::str("Cap'n Rogers"),Tag::str("ironman") ]), + Tag::set(rslice![Tag::str("Cap'n Rogers"), Tag::str("ironman")]), Tag::uint(!0), Tag::uint(100), ]; -const TAG_SET_1_ORDER_0:Tag=Tag::set(TAG_1_ORDER_0_VALUE); -const TAG_ARR_1_ORDER_0:Tag=Tag::arr(TAG_1_ORDER_0_VALUE); +const TAG_SET_1_ORDER_0: Tag = Tag::set(TAG_1_ORDER_0_VALUE); +const TAG_ARR_1_ORDER_0: Tag = Tag::arr(TAG_1_ORDER_0_VALUE); - -const TAG_1_ORDER_1_VALUE:RSlice<'static,Tag>=rslice![ +const TAG_1_ORDER_1_VALUE: RSlice<'static, Tag> = rslice![ Tag::uint(!0), Tag::int(100), Tag::bool_(true), - Tag::set(rslice![ Tag::str("ironman"),Tag::str("Cap'n Rogers") ]), + Tag::set(rslice![Tag::str("ironman"), Tag::str("Cap'n Rogers")]), Tag::uint(100), Tag::int(-100), Tag::bool_(false), - Tag::arr(rslice![Tag::uint(0),Tag::int(-100)]), + Tag::arr(rslice![Tag::uint(0), Tag::int(-100)]), ]; -const TAG_SET_1_ORDER_1:Tag=Tag::set(TAG_1_ORDER_1_VALUE); -const TAG_ARR_1_ORDER_1:Tag=Tag::arr(TAG_1_ORDER_1_VALUE); +const TAG_SET_1_ORDER_1: Tag = Tag::set(TAG_1_ORDER_1_VALUE); +const TAG_ARR_1_ORDER_1: Tag = Tag::arr(TAG_1_ORDER_1_VALUE); -const TAG_2_VALUE:RSlice<'static,Tag>=rslice![ +const TAG_2_VALUE: RSlice<'static, Tag> = rslice![ Tag::uint(!0), Tag::int(100), - Tag::arr(rslice![Tag::uint(0),Tag::int(-100)]), + Tag::arr(rslice![Tag::uint(0), Tag::int(-100)]), Tag::bool_(true), - Tag::set(rslice![ Tag::str("Cap'n Rogers"),Tag::str("ironman"),Tag::str("Fe-male") ]), + Tag::set(rslice![ + Tag::str("Cap'n Rogers"), + Tag::str("ironman"), + Tag::str("Fe-male") + ]), Tag::uint(100), Tag::int(-100), Tag::bool_(false), Tag::str("what the [redacted_for_g]"), ]; -const TAG_SET_2:Tag=Tag::set(TAG_2_VALUE); -const TAG_ARR_2:Tag=Tag::arr(TAG_2_VALUE); - - +const TAG_SET_2: Tag = Tag::set(TAG_2_VALUE); +const TAG_ARR_2: Tag = Tag::arr(TAG_2_VALUE); -const TAG_MAP_EMPTY:Tag=Tag::map(rslice![]); +const TAG_MAP_EMPTY: Tag = Tag::map(rslice![]); - -const TAG_MAP_0A:Tag=tag!({ +const TAG_MAP_0A: Tag = tag!({ Tag::null()=>"baz", "world"=>"hello", "hello"=>"huh?", "hello"=>"world", }); -const TAG_MAP_0B:Tag=tag!({ +const TAG_MAP_0B: Tag = tag!({ "hello"=>"world", "world"=>"hello", }); -const TAG_MAP_0E:Tag=tag!({ 0=>"what", 1=>"foo" }); -const TAG_MAP_0F:Tag=tag!({ 0=>"foo", 1=>"what" }); -const TAG_MAP_0G:Tag=tag!({ 1=>"foo", 2=>"what" }); - +const TAG_MAP_0E: Tag = tag!({ 0=>"what", 1=>"foo" }); +const TAG_MAP_0F: Tag = tag!({ 0=>"foo", 1=>"what" }); +const TAG_MAP_0G: Tag = tag!({ 1=>"foo", 2=>"what" }); -const TAG_MAP_1A:Tag=tag!({ +const TAG_MAP_1A: Tag = tag!({ "world"=>"hello", "foo"=>"bar", "foo"=>"baz", @@ -99,14 +93,13 @@ const TAG_MAP_1A:Tag=tag!({ "hello"=>"world", }); -const TAG_MAP_1B:Tag=tag!({ +const TAG_MAP_1B: Tag = tag!({ "hello"=>"world", "world"=>"hello", "foo"=>"baz", }); - -const TAG_MAP_2A:Tag=tag!({ +const TAG_MAP_2A: Tag = tag!({ Tag::null()=>"baz", "world"=>"hello", Tag::null()=>"baz", @@ -120,7 +113,7 @@ const TAG_MAP_2A:Tag=tag!({ "hello"=>"world", }); -const TAG_MAP_2B:Tag=tag!({ +const TAG_MAP_2B: Tag = tag!({ "hello"=>"world", "world"=>"hello", "foo"=>"baz", @@ -128,57 +121,54 @@ const TAG_MAP_2B:Tag=tag!({ Tag::uint(100)=>"the", }); -fn assert_subsets(array:&[(u32,Tag)]){ - let array=array.iter().cloned() - .map(|(i,v)| ( i , Tag::to_checkable(v) ) ) +fn assert_subsets(array: &[(u32, Tag)]) { + let array = array + .iter() + .cloned() + .map(|(i, v)| (i, Tag::to_checkable(v))) .collect::>(); - for (l_index,(l_ident,l_value)) in array.iter().enumerate() { - for (r_index,(r_ident,r_value)) in array.iter().enumerate() { - let res=l_value.check_compatible(r_value); + for (l_index, (l_ident, l_value)) in array.iter().enumerate() { + for (r_index, (r_ident, r_value)) in array.iter().enumerate() { + let res = l_value.check_compatible(r_value); if l_index <= r_index || l_ident == r_ident { - assert_eq!(res,Ok(()),"left:{}\n\nright:{}",l_value,r_value); - }else{ - assert_ne!(res,Ok(()),"left:{}\n\nright:{}",l_value,r_value); + assert_eq!(res, Ok(()), "left:{}\n\nright:{}", l_value, r_value); + } else { + assert_ne!(res, Ok(()), "left:{}\n\nright:{}", l_value, r_value); } } } } #[test] -fn check_set_compatibility(){ +fn check_set_compatibility() { assert_subsets(&[ - (0,TAG_SET_EMPTY), - (1,TAG_SET_0), - (2,TAG_SET_1_ORDER_0), - (2,TAG_SET_1_ORDER_1), - (3,TAG_SET_2), + (0, TAG_SET_EMPTY), + (1, TAG_SET_0), + (2, TAG_SET_1_ORDER_0), + (2, TAG_SET_1_ORDER_1), + (3, TAG_SET_2), ]); } #[test] -fn check_map_compatibility(){ +fn check_map_compatibility() { assert_subsets(&[ - (0,TAG_MAP_EMPTY), - (1,TAG_MAP_0A), - (1,TAG_MAP_0B), - (2,TAG_MAP_1A), - (2,TAG_MAP_1B), - (3,TAG_MAP_2A), - (3,TAG_MAP_2B), + (0, TAG_MAP_EMPTY), + (1, TAG_MAP_0A), + (1, TAG_MAP_0B), + (2, TAG_MAP_1A), + (2, TAG_MAP_1B), + (3, TAG_MAP_2A), + (3, TAG_MAP_2B), ]); - assert_distinct_elements(&[ - TAG_MAP_0E, - TAG_MAP_0F, - TAG_MAP_0G, - ]); + assert_distinct_elements(&[TAG_MAP_0E, TAG_MAP_0F, TAG_MAP_0G]); } - #[test] -fn check_arr_compatibility(){ +fn check_arr_compatibility() { assert_distinct_elements(&[ TAG_ARR_EMPTY, TAG_ARR_0, @@ -188,31 +178,21 @@ fn check_arr_compatibility(){ ]); } - -const TAG_BOOLS:&[Tag]=&[ - Tag::bool_(false), - Tag::bool_(true ), -]; - +const TAG_BOOLS: &[Tag] = &[Tag::bool_(false), Tag::bool_(true)]; #[test] -fn check_bool(){ +fn check_bool() { assert_distinct_elements(TAG_BOOLS); } -const TAG_UINTS:&[Tag]=&[ - Tag::uint(0), - Tag::uint(1), - Tag::uint(2), -]; +const TAG_UINTS: &[Tag] = &[Tag::uint(0), Tag::uint(1), Tag::uint(2)]; #[test] -fn check_uint(){ +fn check_uint() { assert_distinct_elements(TAG_UINTS); } - -const TAG_INTS:&[Tag]=&[ +const TAG_INTS: &[Tag] = &[ Tag::int(-2), Tag::int(-1), Tag::int(0), @@ -221,12 +201,11 @@ const TAG_INTS:&[Tag]=&[ ]; #[test] -fn check_int(){ +fn check_int() { assert_distinct_elements(TAG_INTS); } - -const TAG_STRS:&[Tag]=&[ +const TAG_STRS: &[Tag] = &[ Tag::str("what"), Tag::str("the"), Tag::str("is"), @@ -235,13 +214,12 @@ const TAG_STRS:&[Tag]=&[ ]; #[test] -fn check_str(){ +fn check_str() { assert_distinct_elements(TAG_STRS); } - #[test] -fn check_different_same_variant(){ +fn check_different_same_variant() { assert_distinct_elements(&[ Tag::bool_(false), Tag::int(0), @@ -253,10 +231,9 @@ fn check_different_same_variant(){ ]); } - #[test] -fn check_null(){ - let mut list=vec![ +fn check_null() { + let mut list = vec![ TAG_SET_EMPTY, TAG_SET_0, TAG_SET_1_ORDER_0, @@ -273,19 +250,16 @@ fn check_null(){ list.extend_from_slice(TAG_INTS); list.extend_from_slice(TAG_STRS); - let null_checkable=Tag::null().to_checkable(); + let null_checkable = Tag::null().to_checkable(); - let list=list.into_iter().map(Tag::to_checkable).collect::>(); + let list = list + .into_iter() + .map(Tag::to_checkable) + .collect::>(); for elems in &list { - assert_eq!( - null_checkable.check_compatible(elems), - Ok(()) - ); - - assert_ne!( - elems.check_compatible(&null_checkable), - Ok(()) - ); + assert_eq!(null_checkable.check_compatible(elems), Ok(())); + + assert_ne!(elems.check_compatible(&null_checkable), Ok(())); } -} \ No newline at end of file +} diff --git a/abi_stable/src/type_layout/tl_data.rs b/abi_stable/src/type_layout/tl_data.rs index 017bda50..98db1948 100644 --- a/abi_stable/src/type_layout/tl_data.rs +++ b/abi_stable/src/type_layout/tl_data.rs @@ -1,9 +1,7 @@ use super::*; - //////////////////////////////////////////////////////////////////////////////// - /// The parts of TLData that don't change based on generic parameters. #[repr(u8)] #[derive(Copy, Clone, StableAbi)] @@ -11,41 +9,32 @@ use super::*; pub enum MonoTLData { Primitive(TLPrimitive), Opaque, - Struct { - fields: CompTLFields - }, - Union { - fields: CompTLFields - }, - Enum (MonoTLEnum), + Struct { fields: CompTLFields }, + Union { fields: CompTLFields }, + Enum(MonoTLEnum), PrefixType(MonoTLPrefixType), } - - impl MonoTLData { /// Teh `MonoTLData` for an empty struct. - pub const EMPTY:Self= - MonoTLData::Struct { - fields: CompTLFields::EMPTY, - }; - + pub const EMPTY: Self = MonoTLData::Struct { + fields: CompTLFields::EMPTY, + }; + /// Constructs `MonoTLData::Struct` from a slice of its fields. - pub const fn struct_(fields: RSlice<'static,CompTLField>) -> Self { + pub const fn struct_(fields: RSlice<'static, CompTLField>) -> Self { MonoTLData::Struct { fields: CompTLFields::from_fields(fields), } } - + #[doc(hidden)] pub const fn derive_struct(fields: CompTLFields) -> Self { - MonoTLData::Struct { - fields, - } + MonoTLData::Struct { fields } } - + /// Constructs `MonoTLData::Union` from a slice of its fields. - pub const fn union_(fields: RSlice<'static,CompTLField>) -> Self { + pub const fn union_(fields: RSlice<'static, CompTLField>) -> Self { MonoTLData::Union { fields: CompTLFields::from_fields(fields), } @@ -53,19 +42,17 @@ impl MonoTLData { #[doc(hidden)] pub const fn derive_union(fields: CompTLFields) -> Self { - MonoTLData::Union { - fields, - } + MonoTLData::Union { fields } } /// Constructs a `MonoTLData::PrefixType` pub const fn prefix_type( - first_suffix_field:usize, - conditional_prefix_fields:FieldConditionality, - fields: RSlice<'static,CompTLField>, - )->Self{ - MonoTLData::PrefixType(MonoTLPrefixType{ - first_suffix_field:first_suffix_field as u8, + first_suffix_field: usize, + conditional_prefix_fields: FieldConditionality, + fields: RSlice<'static, CompTLField>, + ) -> Self { + MonoTLData::PrefixType(MonoTLPrefixType { + first_suffix_field: first_suffix_field as u8, conditional_prefix_fields, fields: CompTLFields::from_fields(fields), }) @@ -73,27 +60,23 @@ impl MonoTLData { /// Constructs `MonoTLData::Struct` from a slice of its fields. pub const fn struct_derive(fields: CompTLFields) -> Self { - MonoTLData::Struct { - fields, - } + MonoTLData::Struct { fields } } - + /// Constructs `MonoTLData::Union` from a slice of its fields. pub const fn union_derive(fields: CompTLFields) -> Self { - MonoTLData::Union { - fields, - } + MonoTLData::Union { fields } } /// Constructs a `MonoTLData::PrefixType` pub const fn prefix_type_derive( - first_suffix_field:usize, - conditional_prefix_fields:u64, + first_suffix_field: usize, + conditional_prefix_fields: u64, fields: CompTLFields, - )->Self{ - MonoTLData::PrefixType(MonoTLPrefixType{ - first_suffix_field:first_suffix_field as u8, - conditional_prefix_fields:FieldConditionality::from_u64(conditional_prefix_fields), + ) -> Self { + MonoTLData::PrefixType(MonoTLPrefixType { + first_suffix_field: first_suffix_field as u8, + conditional_prefix_fields: FieldConditionality::from_u64(conditional_prefix_fields), fields, }) } @@ -111,10 +94,10 @@ impl MonoTLData { } } - pub(super) fn to_primitive(&self)->Option{ + pub(super) fn to_primitive(&self) -> Option { match self { - MonoTLData::Primitive(x)=>Some(*x), - _=>None, + MonoTLData::Primitive(x) => Some(*x), + _ => None, } } @@ -122,75 +105,60 @@ impl MonoTLData { /// /// # Errors /// - /// This returns a `MismatchedTLDataVariant` if `self` and `generic` + /// This returns a `MismatchedTLDataVariant` if `self` and `generic` /// are variant of different names. pub fn expand( self, - generic:GenericTLData, - shared_vars:&'static SharedVars - )-> Result { - Ok(match (self,generic) { - ( MonoTLData::Primitive(prim), GenericTLData::Primitive )=>{ - TLData::Primitive(prim) - }, - ( MonoTLData::Opaque, GenericTLData::Opaque )=>{ - TLData::Opaque + generic: GenericTLData, + shared_vars: &'static SharedVars, + ) -> Result { + Ok(match (self, generic) { + (MonoTLData::Primitive(prim), GenericTLData::Primitive) => TLData::Primitive(prim), + (MonoTLData::Opaque, GenericTLData::Opaque) => TLData::Opaque, + (MonoTLData::Struct { fields }, GenericTLData::Struct) => TLData::Struct { + fields: fields.expand(shared_vars), }, - ( MonoTLData::Struct{fields}, GenericTLData::Struct )=>{ - TLData::Struct{ - fields:fields.expand(shared_vars) - } + (MonoTLData::Union { fields }, GenericTLData::Union) => TLData::Union { + fields: fields.expand(shared_vars), }, - ( MonoTLData::Union{fields}, GenericTLData::Union )=>{ - TLData::Union{ - fields:fields.expand(shared_vars) - } - }, - ( MonoTLData::Enum(nongeneric), GenericTLData::Enum(generic) )=>{ - TLData::Enum(nongeneric.expand(generic,shared_vars)) - }, - ( MonoTLData::PrefixType(nongeneric), GenericTLData::PrefixType(generic) )=>{ - TLData::PrefixType(nongeneric.expand(generic,shared_vars)) - }, - _=>{ - return Err(MismatchedTLDataVariant{ + (MonoTLData::Enum(nongeneric), GenericTLData::Enum(generic)) => { + TLData::Enum(nongeneric.expand(generic, shared_vars)) + } + (MonoTLData::PrefixType(nongeneric), GenericTLData::PrefixType(generic)) => { + TLData::PrefixType(nongeneric.expand(generic, shared_vars)) + } + _ => { + return Err(MismatchedTLDataVariant { nongeneric: self.as_discriminant(), generic: generic.as_discriminant(), }) } }) } - } - /////////////////////////// - -/// An error returned by `MonoTLData::expand` because +/// An error returned by `MonoTLData::expand` because /// the `GenericTLData` it tried to combine itself with was a different variant. -#[derive(Debug,Clone)] -pub struct MismatchedTLDataVariant{ +#[derive(Debug, Clone)] +pub struct MismatchedTLDataVariant { nongeneric: TLDataDiscriminant, generic: TLDataDiscriminant, } - -impl Display for MismatchedTLDataVariant{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result { +impl Display for MismatchedTLDataVariant { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { writeln!( f, "Error combining TLData::{:?} and GenericTLData::{:?}", - self.nongeneric, - self.generic, + self.nongeneric, self.generic, ) } } - /////////////////////////// - /// A discriminant-only version of TLData. #[repr(u8)] #[derive(Debug, Copy, Clone, PartialEq, Eq, StableAbi)] @@ -204,11 +172,8 @@ pub enum TLDataDiscriminant { PrefixType, } - - ///////////////////////////////////////////////////// - /// The part of TLData that can change based on generic parameters. #[repr(C)] #[derive(Copy, Clone, StableAbi)] @@ -222,8 +187,7 @@ pub enum GenericTLData { PrefixType(GenericTLPrefixType), } - -impl GenericTLData{ +impl GenericTLData { /// Converts this into a `TLDataDiscriminant`, /// allowing one to query which discriminant this is. pub fn as_discriminant(&self) -> TLDataDiscriminant { @@ -238,23 +202,17 @@ impl GenericTLData{ } #[doc(hidden)] - pub const fn prefix_type_derive( - accessible_fields:FieldAccessibility, - )->Self{ - GenericTLData::PrefixType(GenericTLPrefixType{ - accessible_fields, - }) + pub const fn prefix_type_derive(accessible_fields: FieldAccessibility) -> Self { + GenericTLData::PrefixType(GenericTLPrefixType { accessible_fields }) } } - - ///////////////////////////////////////////////////// /// The interior of the type definition, /// describing whether the type is a primitive/enum/struct/union and its contents. -#[derive(Debug,Copy,Clone,PartialEq,Eq)] -pub enum TLData{ +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub enum TLData { /// Types defined in the compiler. Primitive(TLPrimitive), /// The type can't be inspected,and has no properties other than size/alignment. @@ -264,48 +222,47 @@ pub enum TLData{ /// with the same byte length as this layout . Opaque, /// For structs. - Struct { - fields: TLFields - }, + Struct { fields: TLFields }, /// For unions. - Union { - fields: TLFields - }, + Union { fields: TLFields }, /// For enums. Enum(TLEnum), /// vtables and modules that can be extended in minor versions. PrefixType(TLPrefixType), } - - impl Display for TLData { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - TLData::Primitive(prim)=>{ - writeln!(f,"Primitive:{:?}",prim)?; - }, - TLData::Opaque=>{ - writeln!(f,"Opaque data")?; - }, - TLData::Struct{fields}=>{ - writeln!(f,"Struct with Fields:\n{}",fields.to_string().left_padder(4))?; - }, - TLData::Union{fields}=>{ - writeln!(f,"Union with Fields:\n{}",fields.to_string().left_padder(4))?; - }, - TLData::Enum (enum_)=>{ - writeln!(f,"Enum:")?; - Display::fmt(enum_,f)?; - }, - TLData::PrefixType(prefix)=>{ - writeln!(f,"Prefix type:")?; - Display::fmt(prefix,f)?; + TLData::Primitive(prim) => { + writeln!(f, "Primitive:{:?}", prim)?; + } + TLData::Opaque => { + writeln!(f, "Opaque data")?; + } + TLData::Struct { fields } => { + writeln!( + f, + "Struct with Fields:\n{}", + fields.to_string().left_padder(4) + )?; + } + TLData::Union { fields } => { + writeln!( + f, + "Union with Fields:\n{}", + fields.to_string().left_padder(4) + )?; + } + TLData::Enum(enum_) => { + writeln!(f, "Enum:")?; + Display::fmt(enum_, f)?; + } + TLData::PrefixType(prefix) => { + writeln!(f, "Prefix type:")?; + Display::fmt(prefix, f)?; } } Ok(()) } } - - - diff --git a/abi_stable/src/type_layout/tl_enums.rs b/abi_stable/src/type_layout/tl_enums.rs index e6b0834a..d055447f 100644 --- a/abi_stable/src/type_layout/tl_enums.rs +++ b/abi_stable/src/type_layout/tl_enums.rs @@ -1,28 +1,24 @@ use super::*; use crate::{ - abi_stability::{ - abi_checking::{AbiInstability,push_err}, - }, + abi_stability::abi_checking::{push_err, AbiInstability}, const_utils::log2_usize, - std_types::{RSlice,RVec,RString}, + std_types::{RSlice, RString, RVec}, }; - /////////////////////////// - /// The parts of the layout of an enum,that don't depend on generic parameters. #[repr(C)] #[derive(Copy, Clone, StableAbi)] #[sabi(unsafe_sabi_opaque_fields)] -pub struct MonoTLEnum{ +pub struct MonoTLEnum { /// The amount of fields of each variant. - field_count:*const u8, - field_count_len:u16, + field_count: *const u8, + field_count_len: u16, /// A ';' separated list of all variant names - variant_names:StartLen, + variant_names: StartLen, /// All the fields of the enums,not separated by variant. pub(super) fields: CompTLFields, @@ -31,40 +27,37 @@ pub struct MonoTLEnum{ unsafe impl Sync for MonoTLEnum {} unsafe impl Send for MonoTLEnum {} - -impl MonoTLEnum{ +impl MonoTLEnum { /// Constructs a `MonoTLEnum`. pub const fn new( - variant_names:StartLen, - field_count:RSlice<'static,u8>, + variant_names: StartLen, + field_count: RSlice<'static, u8>, fields: CompTLFields, ) -> Self { Self { - field_count:field_count.as_ptr(), - field_count_len:field_count.len() as u16, + field_count: field_count.as_ptr(), + field_count_len: field_count.len() as u16, variant_names, fields, } } /// Gets the amount of variants in the enum. - pub fn variant_count(&self)->usize{ + pub fn variant_count(&self) -> usize { self.field_count_len as usize } /// Gets a slice with the amount of fields for each variant in the enum. - pub fn field_count(&self)->RSlice<'static,u8>{ - unsafe{ - RSlice::from_raw_parts( self.field_count, self.field_count_len as usize ) - } + pub fn field_count(&self) -> RSlice<'static, u8> { + unsafe { RSlice::from_raw_parts(self.field_count, self.field_count_len as usize) } } /// Expands this into a TLEnum,with all the properties of an enum definition. - pub fn expand(self,other:GenericTLEnum,shared_vars:&'static SharedVars)->TLEnum{ - TLEnum{ - field_count:self.field_count(), - variant_names:(&shared_vars.strings()[self.variant_names.to_range()]).into(), - fields:self.fields.expand(shared_vars), + pub fn expand(self, other: GenericTLEnum, shared_vars: &'static SharedVars) -> TLEnum { + TLEnum { + field_count: self.field_count(), + variant_names: (&shared_vars.strings()[self.variant_names.to_range()]).into(), + fields: self.fields.expand(shared_vars), exhaustiveness: other.exhaustiveness, discriminants: other.discriminants, } @@ -77,20 +70,16 @@ impl MonoTLEnum{ #[repr(C)] #[derive(Debug, Copy, Clone, StableAbi)] #[sabi(unsafe_sabi_opaque_fields)] -pub struct GenericTLEnum{ +pub struct GenericTLEnum { /// The exhaustiveness of this enum. exhaustiveness: IsExhaustive, /// The discriminants of the variants in the enum. discriminants: TLDiscriminants, } - -impl GenericTLEnum{ +impl GenericTLEnum { /// Constructs a `GenericTLEnum`. - pub const fn new( - exhaustiveness:IsExhaustive, - discriminants:TLDiscriminants, - ) -> Self { + pub const fn new(exhaustiveness: IsExhaustive, discriminants: TLDiscriminants) -> Self { Self { exhaustiveness, discriminants, @@ -98,22 +87,21 @@ impl GenericTLEnum{ } /// Constructs a `GenericTLEnum` for an exhaustive enum. - pub const fn exhaustive(discriminants:TLDiscriminants)->Self{ - Self::new(IsExhaustive::exhaustive(),discriminants) + pub const fn exhaustive(discriminants: TLDiscriminants) -> Self { + Self::new(IsExhaustive::exhaustive(), discriminants) } } - /////////////////////////// /// Every property about an enum specifically. -#[derive(Debug,Copy,Clone,PartialEq,Eq)] -pub struct TLEnum{ +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct TLEnum { /// The amount of fields of each variant. - pub field_count:RSlice<'static,u8>, + pub field_count: RSlice<'static, u8>, /// A ';' separated list of all variant names - pub variant_names:RStr<'static>, + pub variant_names: RStr<'static>, /// All the fields of the enums,not separated by variant. pub fields: TLFields, @@ -125,57 +113,50 @@ pub struct TLEnum{ pub discriminants: TLDiscriminants, } -impl TLEnum{ +impl TLEnum { /// Returns the amount of variants in the enum. - pub fn variant_count(&self)->usize{ + pub fn variant_count(&self) -> usize { self.field_count.len() } /// Returns an iterator over the names of the variants in this enum. pub fn variant_names_iter( - &self - )->impl ExactSizeIterator+Clone+Debug+'static{ - GetVariantNames{ - split:self.variant_names.as_str().split(';'), - length:self.field_count.len(), - current:0, + &self, + ) -> impl ExactSizeIterator + Clone + Debug + 'static { + GetVariantNames { + split: self.variant_names.as_str().split(';'), + length: self.field_count.len(), + current: 0, } } /// Returns `self` and `other` sorted in a `(maximum,minimum)` pair, /// based on the amount of variants. - pub fn max_min<'a>(&'a self,other:&'a TLEnum)->(&'a TLEnum,&'a TLEnum){ + pub fn max_min<'a>(&'a self, other: &'a TLEnum) -> (&'a TLEnum, &'a TLEnum) { if self.variant_count() < other.variant_count() { - (self,other) - }else{ - (other,self) + (self, other) + } else { + (other, self) } } - } - impl Display for TLEnum { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - writeln!(f,"variants:{:?}",self.variant_names)?; + writeln!(f, "variants:{:?}", self.variant_names)?; writeln!( f, "fields(all variants combined):\n{}", self.fields.to_string().left_padder(4) )?; - writeln!(f,"field counts(per-variant):{:?}",self.field_count)?; - writeln!(f,"exhaustiveness:{:?}",self.exhaustiveness)?; - writeln!(f,"discriminants:{:?}",self.discriminants)?; - Ok(()) + writeln!(f, "field counts(per-variant):{:?}", self.field_count)?; + writeln!(f, "exhaustiveness:{:?}", self.exhaustiveness)?; + writeln!(f, "discriminants:{:?}", self.discriminants)?; + Ok(()) } } - - /////////////////////////// - - - macro_rules! declare_tl_discriminants { ( $(( @@ -201,7 +182,7 @@ macro_rules! declare_tl_discriminants { enum TLDiscrsInner{ $( $(#[$variant_attr])* - // Storing the length and pointer like this so that the enum + // Storing the length and pointer like this so that the enum // is only 2 usize large. $variant{ len:u16, @@ -232,10 +213,10 @@ macro_rules! declare_tl_discriminants { TLDiscrsInner::$variant{discriminants: o_discr_ptr, len:o_len } )=>{ let t_discrs=unsafe{ - RSlice::from_raw_parts(t_discr_ptr,t_len as usize) + RSlice::from_raw_parts(t_discr_ptr,t_len as usize) }; let o_discrs=unsafe{ - RSlice::from_raw_parts(o_discr_ptr,o_len as usize) + RSlice::from_raw_parts(o_discr_ptr,o_len as usize) }; t_discrs==o_discrs } @@ -272,7 +253,7 @@ macro_rules! declare_tl_discriminants { /// Compares this `TLDiscriminants` with another, /// /// # Errors - /// + /// /// This returns errors if: /// /// - The discriminant is of a different type @@ -288,13 +269,13 @@ macro_rules! declare_tl_discriminants { TLDiscrsInner::$variant{discriminants: o_discr_ptr, len:o_len } )=>{ let t_discrs=unsafe{ - RSlice::from_raw_parts(t_discr_ptr,t_len as usize) + RSlice::from_raw_parts(t_discr_ptr,t_len as usize) }; let o_discrs=unsafe{ - RSlice::from_raw_parts(o_discr_ptr,o_len as usize) + RSlice::from_raw_parts(o_discr_ptr,o_len as usize) }; - for (&t_discr,&o_discr) in + for (&t_discr,&o_discr) in t_discrs.as_slice().iter().zip(o_discrs.as_slice()) { if t_discr!=o_discr { @@ -329,77 +310,74 @@ macro_rules! declare_tl_discriminants { ) } - -declare_tl_discriminants!{ - ( +declare_tl_discriminants! { + ( U8(u8) , - Signed , + Signed , /// Constructs the variant from an `RSlice<'static,u8>`. from_u8_slice ) - ( + ( I8(i8) , - Unsigned, + Unsigned, /// Constructs the variant from an `RSlice<'static,i8>`. from_i8_slice ) - ( + ( U16(u16) , - Signed , + Signed , /// Constructs the variant from an `RSlice<'static,u16>`. from_u16_slice ) - ( + ( I16(i16) , - Unsigned, + Unsigned, /// Constructs the variant from an `RSlice<'static,i16>`. from_i16_slice ) - ( + ( U32(u32) , - Signed , + Signed , /// Constructs the variant from an `RSlice<'static,u32>`. from_u32_slice ) - ( + ( I32(i32) , - Unsigned, + Unsigned, /// Constructs the variant from an `RSlice<'static,i32>`. from_i32_slice ) - ( + ( U64(u64) , - Signed , + Signed , /// Constructs the variant from an `RSlice<'static,u64>`. from_u64_slice ) - ( + ( I64(i64) , - Unsigned, + Unsigned, /// Constructs the variant from an `RSlice<'static,i64>`. from_i64_slice ) - ( + ( Usize(usize) , - Usize, + Usize, /// Constructs the variant from an `RSlice<'static,usize>`. from_usize_slice ) - ( + ( Isize(isize) , - Isize, + Isize, /// Constructs the variant from an `RSlice<'static,isize>`. from_isize_slice ) } - - /// A discriminant of an enum variant. #[repr(u8)] #[derive(Debug, Copy, Clone, PartialEq, StableAbi)] #[sabi(unsafe_sabi_opaque_fields)] -pub enum TLDiscriminant{ +pub enum TLDiscriminant { /// The assigned value of a discriminant in a `#[repr(isize)]` enum. Isize(isize), /// The assigned value of a discriminant in a `#[repr(usize)]` enum. @@ -410,9 +388,6 @@ pub enum TLDiscriminant{ Unsigned(u64), } - - - /// How the discriminant of an enum is represented. #[repr(u8)] #[derive(Debug, Copy, Clone, PartialEq, Eq, StableAbi)] @@ -446,91 +421,90 @@ pub enum DiscriminantRepr { Isize, } - /// Whether this enum is exhaustive,if it is,it can add variants in minor versions. #[repr(transparent)] #[derive(Debug, Copy, Clone, PartialEq, Eq, StableAbi)] #[sabi(unsafe_sabi_opaque_fields)] -pub struct IsExhaustive{ - value:Option<&'static TLNonExhaustive>, +pub struct IsExhaustive { + value: Option<&'static TLNonExhaustive>, } - -impl IsExhaustive{ +impl IsExhaustive { /// Constructs this `IsExhaustive` as being exhaustive. - pub const fn exhaustive()->IsExhaustive{ - IsExhaustive{value:None} + pub const fn exhaustive() -> IsExhaustive { + IsExhaustive { value: None } } /// Constructs this `IsExhaustive` as being nonexhaustive. - pub const fn nonexhaustive(nonexhaustive:&'static TLNonExhaustive)->IsExhaustive{ - IsExhaustive{value:Some(nonexhaustive)} + pub const fn nonexhaustive(nonexhaustive: &'static TLNonExhaustive) -> IsExhaustive { + IsExhaustive { + value: Some(nonexhaustive), + } } /// Whether this is an exhaustive enum. - pub fn is_exhaustive(&self)->bool{ + pub fn is_exhaustive(&self) -> bool { self.value.is_none() } /// Whether this is an nonexhaustive enum. - pub fn is_nonexhaustive(&self)->bool{ + pub fn is_nonexhaustive(&self) -> bool { self.value.is_some() } /// Converts this to a TLNonExhaustive.Returning None if it is exhaustive. - pub fn as_nonexhaustive(&self)->Option<&'static TLNonExhaustive>{ + pub fn as_nonexhaustive(&self) -> Option<&'static TLNonExhaustive> { self.value } } - /// Properties exclusive to nonexhaustive enums. #[repr(C)] #[derive(Debug, Copy, Clone, PartialEq, Eq, StableAbi)] #[sabi(unsafe_sabi_opaque_fields)] -pub struct TLNonExhaustive{ - original_size:usize, - original_alignment_pow2:u8, +pub struct TLNonExhaustive { + original_size: usize, + original_alignment_pow2: u8, } - -impl TLNonExhaustive{ +impl TLNonExhaustive { /// Constructs a `TLNonExhaustive` from the size and alignment of `T` - pub const fn new()->Self{ - Self{ - original_size:std::mem::size_of::(), - original_alignment_pow2:log2_usize(mem::align_of::()), + pub const fn new() -> Self { + Self { + original_size: std::mem::size_of::(), + original_alignment_pow2: log2_usize(mem::align_of::()), } } #[inline] - fn original_size(&self)->usize{ + fn original_size(&self) -> usize { self.original_size } #[inline] - fn original_alignment(&self)->usize{ + fn original_alignment(&self) -> usize { 1_usize << (self.original_alignment_pow2 as u32) } /// Checks that `layout` is compatible with `self.size` and `self.alignment`, /// returning an error if it's not. - pub fn check_compatible(&self,layout:&TypeLayout)->Result<(),IncompatibleWithNonExhaustive>{ - let err= - layout.size() < self.original_size() || - layout.alignment() < self.original_alignment(); + pub fn check_compatible( + &self, + layout: &TypeLayout, + ) -> Result<(), IncompatibleWithNonExhaustive> { + let err = + layout.size() < self.original_size() || layout.alignment() < self.original_alignment(); if err { - Err(IncompatibleWithNonExhaustive{ - full_type:layout.full_type().to_string().into(), - module_path:layout.mod_path(), - type_size:self.original_size(), - type_alignment:self.original_alignment(), - storage_size:layout.size(), - storage_alignment:layout.alignment(), + Err(IncompatibleWithNonExhaustive { + full_type: layout.full_type().to_string().into(), + module_path: layout.mod_path(), + type_size: self.original_size(), + type_alignment: self.original_alignment(), + storage_size: layout.size(), + storage_alignment: layout.alignment(), }) - }else{ + } else { Ok(()) } } } - #[doc(hidden)] pub struct MakeTLNonExhaustive(T); @@ -538,30 +512,26 @@ impl MakeTLNonExhaustive { pub const NEW: TLNonExhaustive = TLNonExhaustive::new::(); } - //////////////////////////// - - /** -An error declaring that the Storage of a nonexhaustive enum is +An error declaring that the Storage of a nonexhaustive enum is not compatible with the enum. */ #[repr(C)] -#[derive(Debug,Clone,PartialEq,Eq,StableAbi)] +#[derive(Debug, Clone, PartialEq, Eq, StableAbi)] #[sabi(unsafe_sabi_opaque_fields)] -pub struct IncompatibleWithNonExhaustive{ - full_type:RString, - module_path:ModPath, - type_size:usize, - type_alignment:usize, - storage_size:usize, - storage_alignment:usize, +pub struct IncompatibleWithNonExhaustive { + full_type: RString, + module_path: ModPath, + type_size: usize, + type_alignment: usize, + storage_size: usize, + storage_alignment: usize, } - -impl Display for IncompatibleWithNonExhaustive{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ +impl Display for IncompatibleWithNonExhaustive { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "Type '{ty}' has an incompatible layout for the storage.\n\ @@ -569,77 +539,122 @@ impl Display for IncompatibleWithNonExhaustive{ Storage size:{s_size} alignment:{s_align} module_path:{mod_} ", - ty=self.full_type, - t_size=self.type_size, - t_align=self.type_alignment, - s_size=self.storage_size, - s_align=self.storage_alignment, - mod_=self.module_path, + ty = self.full_type, + t_size = self.type_size, + t_align = self.type_alignment, + s_size = self.storage_size, + s_align = self.storage_alignment, + mod_ = self.module_path, ) } } -impl std::error::Error for IncompatibleWithNonExhaustive{} - +impl std::error::Error for IncompatibleWithNonExhaustive {} ///////////////////////////////////////////////////////////////////////////// - /** An iterator that yields the names of an enum's variants. */ -#[derive(Debug,Clone)] -struct GetVariantNames{ - split:std::str::Split<'static,char>, - length:usize, - current:usize, +#[derive(Debug, Clone)] +struct GetVariantNames { + split: std::str::Split<'static, char>, + length: usize, + current: usize, } -impl Iterator for GetVariantNames{ - type Item=&'static str; - fn next(&mut self) -> Option{ - if self.length==self.current { +impl Iterator for GetVariantNames { + type Item = &'static str; + fn next(&mut self) -> Option { + if self.length == self.current { return None; } - let current=self.current; - self.current+=1; - match self.split.next().filter(|&x| !x.is_empty()||x=="_" ) { - Some(x)=>Some(x), - None=>Some(VARIANT_INDEX[current]), + let current = self.current; + self.current += 1; + match self.split.next().filter(|&x| !x.is_empty() || x == "_") { + Some(x) => Some(x), + None => Some(VARIANT_INDEX[current]), } } fn size_hint(&self) -> (usize, Option) { - let len=self.length-self.current; - (len,Some(len)) + let len = self.length - self.current; + (len, Some(len)) } fn count(self) -> usize { - self.length-self.current + self.length - self.current } } - -impl std::iter::ExactSizeIterator for GetVariantNames{} - +impl std::iter::ExactSizeIterator for GetVariantNames {} static VARIANT_INDEX: [&str; 68] = [ - "Variant0", "Variant1", "Variant2", "Variant3", - "Variant4", "Variant5", "Variant6", "Variant7", - "Variant8", "Variant9", "Variant10", "Variant11", - "Variant12", "Variant13", "Variant14", "Variant15", - "Variant16", "Variant17", "Variant18", "Variant19", - "Variant20", "Variant21", "Variant22", "Variant23", - "Variant24", "Variant25", "Variant26", "Variant27", - "Variant28", "Variant29", "Variant30", "Variant31", - "Variant32", "Variant33", "Variant34", "Variant35", - "Variant36", "Variant37", "Variant38", "Variant39", - "Variant40", "Variant41", "Variant42", "Variant43", - "Variant44", "Variant45", "Variant46", "Variant47", - "Variant48", "Variant49", "Variant50", "Variant51", - "Variant52", "Variant53", "Variant54", "Variant55", - "Variant56", "Variant57", "Variant58", "Variant59", - "Variant60", "Variant61", "Variant62", "Variant63", - "Variant64", "Variant65", "Variant66", "Variant67", + "Variant0", + "Variant1", + "Variant2", + "Variant3", + "Variant4", + "Variant5", + "Variant6", + "Variant7", + "Variant8", + "Variant9", + "Variant10", + "Variant11", + "Variant12", + "Variant13", + "Variant14", + "Variant15", + "Variant16", + "Variant17", + "Variant18", + "Variant19", + "Variant20", + "Variant21", + "Variant22", + "Variant23", + "Variant24", + "Variant25", + "Variant26", + "Variant27", + "Variant28", + "Variant29", + "Variant30", + "Variant31", + "Variant32", + "Variant33", + "Variant34", + "Variant35", + "Variant36", + "Variant37", + "Variant38", + "Variant39", + "Variant40", + "Variant41", + "Variant42", + "Variant43", + "Variant44", + "Variant45", + "Variant46", + "Variant47", + "Variant48", + "Variant49", + "Variant50", + "Variant51", + "Variant52", + "Variant53", + "Variant54", + "Variant55", + "Variant56", + "Variant57", + "Variant58", + "Variant59", + "Variant60", + "Variant61", + "Variant62", + "Variant63", + "Variant64", + "Variant65", + "Variant66", + "Variant67", ]; - - diff --git a/abi_stable/src/type_layout/tl_field.rs b/abi_stable/src/type_layout/tl_field.rs index 89695e0d..30eeca08 100644 --- a/abi_stable/src/type_layout/tl_field.rs +++ b/abi_stable/src/type_layout/tl_field.rs @@ -1,6 +1,5 @@ use super::*; - /// The layout of a field. #[repr(C)] #[derive(Debug, Copy, Clone, StableAbi)] @@ -18,106 +17,107 @@ pub struct TLField { layout: TypeLayoutCtor, /// The function pointer types within the field. - function_range:TLFunctionSlice, + function_range: TLFunctionSlice, /// Whether this field is only a function pointer. - is_function:bool, + is_function: bool, /// How this field is accessed. - field_accessor:FieldAccessor, + field_accessor: FieldAccessor, } - /////////////////////////// impl TLField { - /// Constructs a field which does not contain function pointers,or lifetime indices. pub const fn new( name: RStr<'static>, layout: TypeLayoutCtor, - vars:&'static SharedVars, + vars: &'static SharedVars, ) -> Self { Self { name, - lifetime_indices:LifetimeArrayOrSlice::EMPTY, + lifetime_indices: LifetimeArrayOrSlice::EMPTY, layout, - function_range:TLFunctionSlice::empty(vars), - is_function:false, - field_accessor:FieldAccessor::Direct, + function_range: TLFunctionSlice::empty(vars), + is_function: false, + field_accessor: FieldAccessor::Direct, } } /// Gets a printable version of the field type. - pub fn full_type(&self)->FmtFullType{ + pub fn full_type(&self) -> FmtFullType { self.layout.get().full_type() } /// Gets the name of the field - pub fn name(&self)->&'static str{ + pub fn name(&self) -> &'static str { self.name.as_str() } /// Gets the lifetimes that the field references. - pub fn lifetime_indices(&self)->LifetimeArrayOrSlice<'static>{ + pub fn lifetime_indices(&self) -> LifetimeArrayOrSlice<'static> { self.lifetime_indices } /// Gets the layout of the field type - pub fn layout(&self)->&'static TypeLayout{ + pub fn layout(&self) -> &'static TypeLayout { self.layout.get() } /// Gets all the function pointer types in the field. - pub fn function_range(&self)->TLFunctionSlice{ + pub fn function_range(&self) -> TLFunctionSlice { self.function_range } /// Gets whether the field is itself a function pointer. - pub fn is_function(&self)->bool{ + pub fn is_function(&self) -> bool { self.is_function } /// Gets the `FieldAccessor` for the type, /// which describes whether a field is accessible,and how it is accessed. - pub fn field_accessor(&self)->FieldAccessor{ + pub fn field_accessor(&self) -> FieldAccessor { self.field_accessor } - /// Used for calling recursive methods, /// so as to avoid infinite recursion in types that reference themselves(even indirectly). fn recursive(self, f: F) -> U where - F: FnOnce(usize,TLFieldShallow) -> U, + F: FnOnce(usize, TLFieldShallow) -> U, { let mut already_recursed = false; - let mut recursion_depth=!0; - let mut visited_nodes=!0; + let mut recursion_depth = !0; + let mut visited_nodes = !0; ALREADY_RECURSED.with(|state| { let mut state = state.borrow_mut(); - recursion_depth=state.recursion_depth; - visited_nodes=state.visited_nodes; - state.recursion_depth+=1; - state.visited_nodes+=1; + recursion_depth = state.recursion_depth; + visited_nodes = state.visited_nodes; + state.recursion_depth += 1; + state.visited_nodes += 1; already_recursed = state.visited.replace(self.layout.get()).is_some(); }); - let _guard=if visited_nodes==0 { Some(ResetRecursion) }else{ None }; + let _guard = if visited_nodes == 0 { + Some(ResetRecursion) + } else { + None + }; - let field=TLFieldShallow::new(self, !already_recursed ); - let res = f( recursion_depth, field); + let field = TLFieldShallow::new(self, !already_recursed); + let res = f(recursion_depth, field); ALREADY_RECURSED.with(|state| { let mut state = state.borrow_mut(); - state.recursion_depth-=1; + state.recursion_depth -= 1; }); res } } -impl Eq for TLField{} +impl Eq for TLField {} impl PartialEq for TLField { fn eq(&self, other: &Self) -> bool { - self.recursive(|_,this| { + self.recursive(|_, this| { let r = TLFieldShallow::new(*other, this.layout.is_some()); this == r }) @@ -126,64 +126,58 @@ impl PartialEq for TLField { impl Display for TLField { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let layout=self.layout.get(); - let (package,version)=layout.item_info().package_and_version(); + let layout = self.layout.get(); + let (package, version) = layout.item_info().package_and_version(); writeln!( f, "field_name:{name}\n\ type:{ty}\n\ size:{size} align:{align}\n\ package:'{package}' version:'{version}'", - name =self.name, - ty =layout.full_type(), - size =layout.size(), - align=layout.alignment(), - package=package, - version=version, + name = self.name, + ty = layout.full_type(), + size = layout.size(), + align = layout.alignment(), + package = package, + version = version, )?; if !self.function_range.is_empty() { - writeln!(f,"fn pointer(s):")?; + writeln!(f, "fn pointer(s):")?; for func in self.function_range.iter() { - writeln!(f,"{}",func.to_string().left_padder(4))?; + writeln!(f, "{}", func.to_string().left_padder(4))?; } } if !self.lifetime_indices.is_empty() { - writeln!(f,"lifetime indices:{:?}",self.lifetime_indices)?; + writeln!(f, "lifetime indices:{:?}", self.lifetime_indices)?; } Ok(()) } } - - - /////////////////////////// - struct ResetRecursion; -impl Drop for ResetRecursion{ - fn drop(&mut self){ - ALREADY_RECURSED.with(|state|{ +impl Drop for ResetRecursion { + fn drop(&mut self) { + ALREADY_RECURSED.with(|state| { let mut state = state.borrow_mut(); - state.recursion_depth=0; - state.visited_nodes=0; + state.recursion_depth = 0; + state.visited_nodes = 0; state.visited.clear(); }); } } - -struct RecursionState{ - recursion_depth:usize, - visited_nodes:u64, - visited:HashSet<*const TypeLayout>, +struct RecursionState { + recursion_depth: usize, + visited_nodes: u64, + visited: HashSet<*const TypeLayout>, } - thread_local! { static ALREADY_RECURSED: RefCell = RefCell::new(RecursionState{ recursion_depth:0, @@ -192,12 +186,10 @@ thread_local! { }); } - //////////////////////////////////// #[derive(Debug, Copy, Clone, PartialEq)] struct TLFieldShallow { - name: RStr<'static>, full_type: FmtFullType, @@ -207,11 +199,11 @@ struct TLFieldShallow { /// This is None if it already printed that TypeLayout layout: Option<&'static TypeLayout>, - function_range:TLFunctionSlice, + function_range: TLFunctionSlice, - is_function:bool, + is_function: bool, - field_accessor:FieldAccessor, + field_accessor: FieldAccessor, } impl TLFieldShallow { @@ -227,68 +219,65 @@ impl TLFieldShallow { }, full_type: layout.full_type(), - function_range:field.function_range, - is_function:field.is_function, - field_accessor:field.field_accessor, + function_range: field.function_range, + is_function: field.is_function, + field_accessor: field.field_accessor, } } } - //////////////////////////////////// -abi_stable_shared::declare_comp_tl_field!{ - attrs=[ +abi_stable_shared::declare_comp_tl_field! { + attrs=[ derive(StableAbi), sabi(unsafe_sabi_opaque_fields), ] } - - -impl CompTLField{ - +impl CompTLField { /// Gets the name of the field from `SharedVars`'s string slice. - pub fn name(&self,strings:&'static str)->&'static str{ + pub fn name(&self, strings: &'static str) -> &'static str { &strings[self.name_start_len().to_range()] } /// Gets the name of the field from `SharedVars`'s slice of lifetime indices. pub fn lifetime_indices( &self, - indices:&'static [LifetimeIndexPair] - )-> LifetimeArrayOrSlice<'static> { - let comp=LifetimeRange::from_u21(self.lifetime_indices_bits()); + indices: &'static [LifetimeIndexPair], + ) -> LifetimeArrayOrSlice<'static> { + let comp = LifetimeRange::from_u21(self.lifetime_indices_bits()); comp.slicing(indices) } /// Gets the `FieldAccessor` for the type from `SharedVars`'s string slice, /// which describes whether a field is accessible,and how it is accessed.. - pub fn field_accessor(&self,strings:&'static str)->FieldAccessor{ - let name_end=self.name_start_len().end(); - let comp=CompFieldAccessor::from_u3((self.bits0>>Self::FIELD_ACCESSOR_OFFSET) as u8); - let accessor_payload=if comp.requires_payload() { + pub fn field_accessor(&self, strings: &'static str) -> FieldAccessor { + let name_end = self.name_start_len().end(); + let comp = CompFieldAccessor::from_u3((self.bits0 >> Self::FIELD_ACCESSOR_OFFSET) as u8); + let accessor_payload = if comp.requires_payload() { strings[name_end..].split(';').next().unwrap_or("") - }else{ + } else { "" }; - comp.expand(accessor_payload).unwrap_or(FieldAccessor::Opaque) + comp.expand(accessor_payload) + .unwrap_or(FieldAccessor::Opaque) } /// Gets the name of the field from `SharedVars`'s slice of `TypeLayoutCtor`. - pub fn type_layout(&self,type_layouts:&'static [TypeLayoutCtor])-> TypeLayoutCtor { + pub fn type_layout(&self, type_layouts: &'static [TypeLayoutCtor]) -> TypeLayoutCtor { type_layouts[self.type_layout_index()] } /// Expands this CompTLField into a TLField. pub fn expand( &self, - field_index:usize, - functions:Option<&'static TLFunctions >, - vars:&'static SharedVars, - )->TLField{ - let strings=vars.strings(); - let function_range=TLFunctionSlice::for_field(field_index,functions,vars); + field_index: usize, + functions: Option<&'static TLFunctions>, + vars: &'static SharedVars, + ) -> TLField { + let strings = vars.strings(); + let function_range = TLFunctionSlice::for_field(field_index, functions, vars); // println!( // "field:{:b}\n\ @@ -306,72 +295,55 @@ impl CompTLField{ // ); TLField { - name:self.name(strings).into(), - lifetime_indices:self.lifetime_indices(vars.lifetime_indices()), - layout:self.type_layout(vars.type_layouts()), + name: self.name(strings).into(), + lifetime_indices: self.lifetime_indices(vars.lifetime_indices()), + layout: self.type_layout(vars.type_layouts()), function_range, - is_function:self.is_function(), - field_accessor:self.field_accessor(strings), + is_function: self.is_function(), + field_accessor: self.field_accessor(strings), } } } - - #[cfg(test)] -mod tests{ +mod tests { use super::*; - use crate::{ - abi_stability::stable_abi_trait::GetTypeLayoutCtor, - std_types::RString, - }; + use crate::{abi_stability::stable_abi_trait::GetTypeLayoutCtor, std_types::RString}; #[test] - fn roundtrip(){ - const UNIT_CTOR:TypeLayoutCtor=GetTypeLayoutCtor::<()>::STABLE_ABI; - const U32_CTOR:TypeLayoutCtor=GetTypeLayoutCtor::::STABLE_ABI; - const RSTRING_CTOR:TypeLayoutCtor=GetTypeLayoutCtor::::STABLE_ABI; + fn roundtrip() { + const UNIT_CTOR: TypeLayoutCtor = GetTypeLayoutCtor::<()>::STABLE_ABI; + const U32_CTOR: TypeLayoutCtor = GetTypeLayoutCtor::::STABLE_ABI; + const RSTRING_CTOR: TypeLayoutCtor = GetTypeLayoutCtor::::STABLE_ABI; - const MONO_VARS: &MonoSharedVars = &MonoSharedVars::new( - rstr!("foo;bar; baz; "), - rslice![], - ); + const MONO_VARS: &MonoSharedVars = &MonoSharedVars::new(rstr!("foo;bar; baz; "), rslice![]); const VARS: &SharedVars = &SharedVars::new( MONO_VARS, - rslice![UNIT_CTOR,U32_CTOR,RSTRING_CTOR], + rslice![UNIT_CTOR, U32_CTOR, RSTRING_CTOR], rslice![], ); let vars = VARS; - let mut arr=[LifetimeIndex::NONE;5]; - arr[0]=LifetimeIndex::STATIC; - let lifetime_range=LifetimeRange::from_array(arr); + let mut arr = [LifetimeIndex::NONE; 5]; + arr[0] = LifetimeIndex::STATIC; + let lifetime_range = LifetimeRange::from_array(arr); - let field=CompTLField::new( - StartLen::new(9,3), + let field = CompTLField::new( + StartLen::new(9, 3), lifetime_range, CompFieldAccessor::DIRECT, TypeLayoutIndex::from_u10(2), false, ); - - assert_eq!( - field.name(vars.strings()), - "baz", - ); + + assert_eq!(field.name(vars.strings()), "baz",); assert_eq!( field.lifetime_indices(vars.lifetime_indices()), lifetime_range.slicing(vars.lifetime_indices()), ); - assert_eq!( - field.type_layout(vars.type_layouts()), - RSTRING_CTOR, - ); - assert_eq!( - field.field_accessor(vars.strings()), - FieldAccessor::Direct, - ); + assert_eq!(field.type_layout(vars.type_layouts()), RSTRING_CTOR,); + assert_eq!(field.field_accessor(vars.strings()), FieldAccessor::Direct,); } -} \ No newline at end of file +} diff --git a/abi_stable/src/type_layout/tl_fields.rs b/abi_stable/src/type_layout/tl_fields.rs index c650f83c..a39c0d98 100644 --- a/abi_stable/src/type_layout/tl_fields.rs +++ b/abi_stable/src/type_layout/tl_fields.rs @@ -1,9 +1,6 @@ use super::*; -use std::{ - iter, - slice, -}; +use std::{iter, slice}; /// The layout of all compressed fields in a type definition, /// one can access the expanded fields by calling the expand method. @@ -12,86 +9,78 @@ use std::{ #[sabi(unsafe_sabi_opaque_fields)] pub struct CompTLFields { /// All TLField fields which map 1:1. - comp_fields:*const CompTLField, + comp_fields: *const CompTLField, /// All the function pointer types in the field. - functions:Option<&'static TLFunctions >, + functions: Option<&'static TLFunctions>, - comp_fields_len:u16, + comp_fields_len: u16, } - unsafe impl Sync for CompTLFields {} unsafe impl Send for CompTLFields {} - -impl CompTLFields{ +impl CompTLFields { /// A `CompTLFields` with no fields. - pub const EMPTY:Self=Self::from_fields(rslice![]); + pub const EMPTY: Self = Self::from_fields(rslice![]); /// Constructs a `CompTLFields`. pub const fn new( - comp_fields:RSlice<'static,CompTLFieldRepr>, - functions:Option<&'static TLFunctions >, - )->Self{ - Self{ - comp_fields:comp_fields.as_ptr() - as *const CompTLFieldRepr - as *const CompTLField, - comp_fields_len:comp_fields.len() as u16, + comp_fields: RSlice<'static, CompTLFieldRepr>, + functions: Option<&'static TLFunctions>, + ) -> Self { + Self { + comp_fields: comp_fields.as_ptr() as *const CompTLFieldRepr as *const CompTLField, + comp_fields_len: comp_fields.len() as u16, functions, } } /// Constructs a `CompTLFields` with fields,and without functions. - pub const fn from_fields( - comp_fields:RSlice<'static,CompTLField>, - )->Self{ - Self{ - comp_fields:comp_fields.as_ptr(), - comp_fields_len:comp_fields.len() as u16, - - functions:None, + pub const fn from_fields(comp_fields: RSlice<'static, CompTLField>) -> Self { + Self { + comp_fields: comp_fields.as_ptr(), + comp_fields_len: comp_fields.len() as u16, + + functions: None, } } /// Accesses a slice of all the compressed fields in this `CompTLFields`. - pub fn comp_fields(&self)->&'static [CompTLField] { - unsafe{ - slice::from_raw_parts(self.comp_fields,self.comp_fields_len as usize) - } + pub fn comp_fields(&self) -> &'static [CompTLField] { + unsafe { slice::from_raw_parts(self.comp_fields, self.comp_fields_len as usize) } } /// Accesses a slice of all the compressed fields in this `CompTLFields`. - pub fn comp_fields_rslice(&self)->RSlice<'static,CompTLField> { - unsafe{ - RSlice::from_raw_parts(self.comp_fields,self.comp_fields_len as usize) - } + pub fn comp_fields_rslice(&self) -> RSlice<'static, CompTLField> { + unsafe { RSlice::from_raw_parts(self.comp_fields, self.comp_fields_len as usize) } } /// Constructs an iterator over all the field names. pub fn field_names( &self, - shared_vars:&MonoSharedVars, - )->impl ExactSizeIterator+Clone+'static{ - let fields=self.comp_fields(); - let strings=shared_vars.strings(); + shared_vars: &MonoSharedVars, + ) -> impl ExactSizeIterator + Clone + 'static { + let fields = self.comp_fields(); + let strings = shared_vars.strings(); - fields.iter().map(move|field| field.name(strings) ) + fields.iter().map(move |field| field.name(strings)) } /// Gets the name of the nth field. - pub fn get_field_name(&self,index:usize,shared_vars:&MonoSharedVars)-> Option<&'static str> { - let strings=shared_vars.strings(); + pub fn get_field_name( + &self, + index: usize, + shared_vars: &MonoSharedVars, + ) -> Option<&'static str> { + let strings = shared_vars.strings(); - self.comp_fields() - .get(index) - .map(|f| f.name(strings) ) + self.comp_fields().get(index).map(|f| f.name(strings)) } /// The amount of fields this represents - pub fn len(&self)->usize{ + pub fn len(&self) -> usize { self.comp_fields_len as usize } @@ -99,155 +88,140 @@ impl CompTLFields{ pub fn is_empty(&self) -> bool { self.comp_fields_len == 0 } - + /// Expands this into a TLFields,allowing access to expanded fields. - pub fn expand(self,shared_vars:&'static SharedVars)->TLFields{ - TLFields{ + pub fn expand(self, shared_vars: &'static SharedVars) -> TLFields { + TLFields { shared_vars, - comp_fields:self.comp_fields_rslice(), - functions:self.functions, + comp_fields: self.comp_fields_rslice(), + functions: self.functions, } } } - /////////////////////////////////////////////////////////////////////////////// /// The layout of all the fields in a type definition. #[repr(C)] #[derive(Copy, Clone, StableAbi)] pub struct TLFields { - shared_vars:&'static SharedVars, + shared_vars: &'static SharedVars, - comp_fields:RSlice<'static,CompTLField>, + comp_fields: RSlice<'static, CompTLField>, /// All the function pointer types in the field. - functions:Option<&'static TLFunctions >, - + functions: Option<&'static TLFunctions>, } - - -impl TLFields{ +impl TLFields { /// Constructs a TLFields from the compressed fields,without any functions. pub fn from_fields( - comp_fields:&'static [CompTLField], - shared_vars:&'static SharedVars, - )->Self{ - Self{ - comp_fields:comp_fields.into(), + comp_fields: &'static [CompTLField], + shared_vars: &'static SharedVars, + ) -> Self { + Self { + comp_fields: comp_fields.into(), shared_vars, - functions:None, + functions: None, } } - + /// The amount of fields this represents - pub fn len(&self)->usize{ + pub fn len(&self) -> usize { self.comp_fields.len() } /// Whether this contains any fields - pub fn is_empty(&self)->bool{ + pub fn is_empty(&self) -> bool { self.comp_fields.is_empty() } /// Gets the ith expanded field.Returns None there is no ith field. - pub fn get(&self,i:usize)->Option{ - self.comp_fields.get(i) - .map(|field| field.expand(i,self.functions,self.shared_vars) ) - + pub fn get(&self, i: usize) -> Option { + self.comp_fields + .get(i) + .map(|field| field.expand(i, self.functions, self.shared_vars)) } /// Gets an iterator over the expanded fields. - pub fn iter(&self)->TLFieldsIterator{ - TLFieldsIterator{ - shared_vars:self.shared_vars, - comp_fields:self.comp_fields.as_slice().iter().enumerate(), - functions:self.functions, + pub fn iter(&self) -> TLFieldsIterator { + TLFieldsIterator { + shared_vars: self.shared_vars, + comp_fields: self.comp_fields.as_slice().iter().enumerate(), + functions: self.functions, } } - + /// Collects the expanded fields into a `Vec`. - pub fn to_vec(&self)->Vec{ + pub fn to_vec(&self) -> Vec { self.iter().collect() } } - impl IntoIterator for TLFields { - type IntoIter=TLFieldsIterator; - type Item=TLField; + type IntoIter = TLFieldsIterator; + type Item = TLField; #[inline] - fn into_iter(self)->Self::IntoIter{ + fn into_iter(self) -> Self::IntoIter { self.iter() } } -impl Debug for TLFields{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - f.debug_list() - .entries(self.iter()) - .finish() +impl Debug for TLFields { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.iter()).finish() } } - impl Display for TLFields { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for field in self.iter() { - Display::fmt(&field,f)?; + Display::fmt(&field, f)?; writeln!(f)?; } Ok(()) } } - -impl Eq for TLFields{} -impl PartialEq for TLFields{ - fn eq(&self,other:&Self)->bool{ +impl Eq for TLFields {} +impl PartialEq for TLFields { + fn eq(&self, other: &Self) -> bool { self.iter().eq(other.iter()) } } - /////////////////////////////////////////////////////////////////////////////// - /** An iterator over all the fields in a type definition. */ -#[derive(Clone,Debug)] +#[derive(Clone, Debug)] pub struct TLFieldsIterator { - shared_vars:&'static SharedVars, + shared_vars: &'static SharedVars, - comp_fields:iter::Enumerate>, + comp_fields: iter::Enumerate>, /// All the function pointer types in the field. - functions:Option<&'static TLFunctions >, - + functions: Option<&'static TLFunctions>, } -impl Iterator for TLFieldsIterator{ - type Item=TLField; +impl Iterator for TLFieldsIterator { + type Item = TLField; - fn next(&mut self)->Option{ - self.comp_fields.next() - .map(|(i,field)|{ - field.expand(i,self.functions,self.shared_vars) - }) + fn next(&mut self) -> Option { + self.comp_fields + .next() + .map(|(i, field)| field.expand(i, self.functions, self.shared_vars)) } - fn size_hint(&self)->(usize,Option){ - let len=self.comp_fields.len(); - (len,Some(len)) + fn size_hint(&self) -> (usize, Option) { + let len = self.comp_fields.len(); + (len, Some(len)) } fn count(self) -> usize { self.comp_fields.len() } } - -impl std::iter::ExactSizeIterator for TLFieldsIterator{} - +impl std::iter::ExactSizeIterator for TLFieldsIterator {} diff --git a/abi_stable/src/type_layout/tl_functions.rs b/abi_stable/src/type_layout/tl_functions.rs index 8142b67e..94fdc547 100644 --- a/abi_stable/src/type_layout/tl_functions.rs +++ b/abi_stable/src/type_layout/tl_functions.rs @@ -1,13 +1,11 @@ use super::*; use crate::{ - abi_stability::stable_abi_trait::GetTypeLayoutCtor, - traits::IntoReprC, - std_types::RVec, + abi_stability::stable_abi_trait::GetTypeLayoutCtor, std_types::RVec, traits::IntoReprC, }; use std::{ - cmp::{PartialEq,Eq}, + cmp::{Eq, PartialEq}, ops::Range, }; @@ -15,55 +13,48 @@ use std::{ /// All the function pointer types in a type declaration. #[repr(C)] -#[derive(Debug,Copy, Clone, StableAbi)] +#[derive(Debug, Copy, Clone, StableAbi)] #[sabi(unsafe_sabi_opaque_fields)] -pub struct TLFunctions{ - functions:*const CompTLFunction, +pub struct TLFunctions { + functions: *const CompTLFunction, /// The range of `CompTLFunction` that each field in TLFields owns. - field_fn_ranges:*const StartLen, - - functions_len:u16, - field_fn_ranges_len:u16, -} - -unsafe impl Sync for TLFunctions{} -unsafe impl Send for TLFunctions{} - + field_fn_ranges: *const StartLen, + functions_len: u16, + field_fn_ranges_len: u16, +} +unsafe impl Sync for TLFunctions {} +unsafe impl Send for TLFunctions {} impl TLFunctions { /// Constructs a TLFunctions. pub const fn new( - functions:RSlice<'static,CompTLFunction>, - field_fn_ranges:RSlice<'static,StartLenRepr>, - )->Self{ - Self{ - functions:functions.as_ptr(), - functions_len:functions.len() as u16, - field_fn_ranges:field_fn_ranges.as_ptr() - as *const StartLenRepr - as *const StartLen, - field_fn_ranges_len:field_fn_ranges.len() as u16, + functions: RSlice<'static, CompTLFunction>, + field_fn_ranges: RSlice<'static, StartLenRepr>, + ) -> Self { + Self { + functions: functions.as_ptr(), + functions_len: functions.len() as u16, + field_fn_ranges: field_fn_ranges.as_ptr() as *const StartLenRepr as *const StartLen, + field_fn_ranges_len: field_fn_ranges.len() as u16, } } - fn functions(&self)->&'static [CompTLFunction]{ - unsafe { - std::slice::from_raw_parts(self.functions,self.functions_len as usize) - } + fn functions(&self) -> &'static [CompTLFunction] { + unsafe { std::slice::from_raw_parts(self.functions, self.functions_len as usize) } } - fn field_fn_ranges(&self)->&'static [StartLen]{ + fn field_fn_ranges(&self) -> &'static [StartLen] { unsafe { - std::slice::from_raw_parts(self.field_fn_ranges,self.field_fn_ranges_len as usize) + std::slice::from_raw_parts(self.field_fn_ranges, self.field_fn_ranges_len as usize) } } /// Gets the `nth` `TLFunction` in this `TLFunctions`. /// Returns None if there is not `nth` TLFunction. - pub fn get(&'static self,nth:usize,shared_vars:&'static SharedVars)->Option{ - let func=self.functions().get(nth)?; + pub fn get(&'static self, nth: usize, shared_vars: &'static SharedVars) -> Option { + let func = self.functions().get(nth)?; Some(func.expand(shared_vars)) } @@ -73,75 +64,78 @@ impl TLFunctions { /// /// This function panics if `nth` is out of bounds /// (when `nth` is greater than or equal to `self.len()`) - pub fn index(&'static self,nth:usize,shared_vars:&'static SharedVars)->TLFunction{ + pub fn index(&'static self, nth: usize, shared_vars: &'static SharedVars) -> TLFunction { self.functions()[nth].expand(shared_vars) } /// Gets the amount of `TLFunction` in this `TLFunctions`. #[inline] - pub fn len(&'static self)->usize{ + pub fn len(&'static self) -> usize { self.functions_len as usize } /// Whether this is empty. - pub fn is_empty(&'static self) -> bool{ + pub fn is_empty(&'static self) -> bool { self.functions_len == 0 } } - /////////////////////////////////////////////////////////////////////////////// /** A slice of functions from a `TLFunctions`. */ #[repr(C)] -#[derive(Copy,Clone,StableAbi)] +#[derive(Copy, Clone, StableAbi)] #[sabi(unsafe_sabi_opaque_fields)] -pub struct TLFunctionSlice{ - functions:Option<&'static TLFunctions>, - shared_vars:&'static SharedVars, - fn_range:StartLen, +pub struct TLFunctionSlice { + functions: Option<&'static TLFunctions>, + shared_vars: &'static SharedVars, + fn_range: StartLen, } - -impl TLFunctionSlice{ +impl TLFunctionSlice { /// Constructs an empty `TLFunctionSlice`. - pub const fn empty(shared_vars:&'static SharedVars,)->Self{ - Self{ - functions:None, + pub const fn empty(shared_vars: &'static SharedVars) -> Self { + Self { + functions: None, shared_vars, - fn_range:StartLen::EMPTY, + fn_range: StartLen::EMPTY, } } /// Constructs the `TLFunctionSlice` for the function pointers in the `i`th field. pub fn for_field( - i:usize, - functions:Option<&'static TLFunctions>, - shared_vars:&'static SharedVars, - )->Self{ - let fn_range=functions - .and_then(|fns| fns.field_fn_ranges().get(i).cloned() ) + i: usize, + functions: Option<&'static TLFunctions>, + shared_vars: &'static SharedVars, + ) -> Self { + let fn_range = functions + .and_then(|fns| fns.field_fn_ranges().get(i).cloned()) .unwrap_or(StartLen::EMPTY); - Self{functions,fn_range,shared_vars} + Self { + functions, + fn_range, + shared_vars, + } } - + /// Gets the `&'static SharedVars` associated with this slice. - pub const fn shared_vars(&self)->&'static SharedVars{ + pub const fn shared_vars(&self) -> &'static SharedVars { self.shared_vars } /// Returns an iterator over the `TLFunction`s in the slice. #[inline] - pub fn iter(self)->TLFunctionIter{ - TLFunctionIter::new(self.fn_range,self.functions,self.shared_vars) + pub fn iter(self) -> TLFunctionIter { + TLFunctionIter::new(self.fn_range, self.functions, self.shared_vars) } /// Gets a `TLFunction` at the `index`. /// This returns `None` if `index` is outside the slice. - pub fn get(self,index:usize)->Option{ - self.functions?.get( self.fn_range.start_usize()+index, self.shared_vars ) + pub fn get(self, index: usize) -> Option { + self.functions? + .get(self.fn_range.start_usize() + index, self.shared_vars) } /// Gets a `TLFunction` at the `index`. @@ -149,87 +143,79 @@ impl TLFunctionSlice{ /// # Panic /// /// This panics if the `TLFunction` is outside the slice. - pub fn index(self,index:usize)->TLFunction{ + pub fn index(self, index: usize) -> TLFunction { self.functions .expect("self.functions must be Some(..) to index a TLFunctionSlice") - .index( self.fn_range.start_usize()+index, self.shared_vars ) + .index(self.fn_range.start_usize() + index, self.shared_vars) } /// Gets the length of this slice. #[inline] - pub fn len(self)->usize{ + pub fn len(self) -> usize { self.fn_range.len_usize() } /// Gets whether this slice is empty. #[inline] - pub fn is_empty(self)->bool{ - self.fn_range.len()==0 + pub fn is_empty(self) -> bool { + self.fn_range.len() == 0 } } - -impl IntoIterator for TLFunctionSlice{ - type IntoIter=TLFunctionIter; - type Item=TLFunction; +impl IntoIterator for TLFunctionSlice { + type IntoIter = TLFunctionIter; + type Item = TLFunction; #[inline] - fn into_iter(self)->TLFunctionIter{ + fn into_iter(self) -> TLFunctionIter { self.iter() } } - -impl Debug for TLFunctionSlice{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - f.debug_list() - .entries(self.iter()) - .finish() +impl Debug for TLFunctionSlice { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.iter()).finish() } } -impl Eq for TLFunctionSlice{} +impl Eq for TLFunctionSlice {} -impl PartialEq for TLFunctionSlice{ - fn eq(&self,other:&Self)->bool{ - self.fn_range.len()==other.fn_range.len()&& - self.iter().eq(other.iter()) +impl PartialEq for TLFunctionSlice { + fn eq(&self, other: &Self) -> bool { + self.fn_range.len() == other.fn_range.len() && self.iter().eq(other.iter()) } } - /////////////////////////////////////////////////////////////////////////////// /// A compressed version of `TLFunction`, /// which can be expanded into a `TLFunction` by calling the `expand` method. #[repr(C)] -#[derive(Copy,Clone,Debug,PartialEq,Eq,Ord,PartialOrd,StableAbi)] +#[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd, StableAbi)] #[sabi(unsafe_sabi_opaque_fields)] -pub struct CompTLFunction{ - name:StartLen, - contiguous_strings_offset:u16, - bound_lifetimes_len:u16, - param_names_len:u16, +pub struct CompTLFunction { + name: StartLen, + contiguous_strings_offset: u16, + bound_lifetimes_len: u16, + param_names_len: u16, /// Stores `!0` if the return type is `()`. - return_type_layout:u16, - paramret_lifetime_range:LifetimeRange, - param_type_layouts:TypeLayoutRange, + return_type_layout: u16, + paramret_lifetime_range: LifetimeRange, + param_type_layouts: TypeLayoutRange, } - - -impl CompTLFunction{ +impl CompTLFunction { /// Constructs a CompTLFunction. pub const fn new( - name:StartLenRepr, - contiguous_strings_offset:u16, - bound_lifetimes_len:u16, - param_names_len:u16, - return_type_layout:u16, - paramret_lifetime_range:u32, - param_type_layouts:u64, - )->Self{ - Self{ - name:StartLen::from_u32(name), + name: StartLenRepr, + contiguous_strings_offset: u16, + bound_lifetimes_len: u16, + param_names_len: u16, + return_type_layout: u16, + paramret_lifetime_range: u32, + param_type_layouts: u64, + ) -> Self { + Self { + name: StartLen::from_u32(name), contiguous_strings_offset, bound_lifetimes_len, param_names_len, @@ -240,19 +226,19 @@ impl CompTLFunction{ } /// Decompresses this CompTLFunction into a TLFunction. - pub fn expand(&self,shared_vars:&'static SharedVars)->TLFunction{ - let strings=shared_vars.strings().into_c(); - let lifetime_indices=shared_vars.lifetime_indices(); - let type_layouts=shared_vars.type_layouts(); + pub fn expand(&self, shared_vars: &'static SharedVars) -> TLFunction { + let strings = shared_vars.strings().into_c(); + let lifetime_indices = shared_vars.lifetime_indices(); + let type_layouts = shared_vars.type_layouts(); - let cs_offset=self.contiguous_strings_offset as usize; + let cs_offset = self.contiguous_strings_offset as usize; - let bound_lifetimes=cs_offset..cs_offset+(self.bound_lifetimes_len as usize); - let param_names= - bound_lifetimes.end..bound_lifetimes.end+(self.param_names_len as usize); + let bound_lifetimes = cs_offset..cs_offset + (self.bound_lifetimes_len as usize); + let param_names = + bound_lifetimes.end..bound_lifetimes.end + (self.param_names_len as usize); - TLFunction{ - shared_vars:CmpIgnored::new(shared_vars), + TLFunction { + shared_vars: CmpIgnored::new(shared_vars), name: strings.slice(self.name.to_range()), bound_lifetimes: strings.slice(bound_lifetimes), param_names: strings.slice(param_names), @@ -263,22 +249,18 @@ impl CompTLFunction{ } } - - - /////////////////////////////////////////////////////////////////////////////// - /// A function pointer in a field. #[repr(C)] -#[derive(Copy,Clone,Debug,Eq,StableAbi)] +#[derive(Copy, Clone, Debug, Eq, StableAbi)] #[sabi(unsafe_sabi_opaque_fields)] -pub struct TLFunction{ - pub(super) shared_vars:CmpIgnored<&'static SharedVars>, +pub struct TLFunction { + pub(super) shared_vars: CmpIgnored<&'static SharedVars>, /// The name of the field this is used inside of. pub name: RStr<'static>, - + /// The named lifetime parameters of the function itself (declared in `for<>`), /// separated by ';'. pub bound_lifetimes: RStr<'static>, @@ -292,47 +274,39 @@ pub struct TLFunction{ pub paramret_lifetime_indices: LifetimeArrayOrSlice<'static>, /// The return type of the function. - pub return_type_layout:Option, - + pub return_type_layout: Option, } - - - - -impl PartialEq for TLFunction{ - fn eq(&self,other:&Self)->bool{ - self.name==other.name&& - self.bound_lifetimes==other.bound_lifetimes&& - self.param_names==other.param_names&& - self.get_params_ret_iter().eq(other.get_params_ret_iter())&& - self.paramret_lifetime_indices==other.paramret_lifetime_indices&& - self.return_type_layout.map(|x| x.get() )==other.return_type_layout.map(|x| x.get() ) +impl PartialEq for TLFunction { + fn eq(&self, other: &Self) -> bool { + self.name == other.name + && self.bound_lifetimes == other.bound_lifetimes + && self.param_names == other.param_names + && self.get_params_ret_iter().eq(other.get_params_ret_iter()) + && self.paramret_lifetime_indices == other.paramret_lifetime_indices + && self.return_type_layout.map(|x| x.get()) == other.return_type_layout.map(|x| x.get()) } } - -impl TLFunction{ - pub(crate) fn get_param_names(&self)->GetParamNames{ - GetParamNames{ - split:self.param_names.as_str().split(';'), - length:self.param_type_layouts.len(), - current:0, +impl TLFunction { + pub(crate) fn get_param_names(&self) -> GetParamNames { + GetParamNames { + split: self.param_names.as_str().split(';'), + length: self.param_type_layouts.len(), + current: 0, } } /// Gets the parameter types - pub(crate) fn get_params(&self)->impl ExactSizeIterator+Clone+Debug { - let shared_vars=*self.shared_vars; + pub(crate) fn get_params(&self) -> impl ExactSizeIterator + Clone + Debug { + let shared_vars = *self.shared_vars; self.get_param_names() .zip(self.param_type_layouts.iter()) - .map(move|(param_name,layout)|{ - TLField::new(param_name.into(),layout,shared_vars) - }) + .map(move |(param_name, layout)| TLField::new(param_name.into(), layout, shared_vars)) } - - pub(crate) fn get_return(&self)->TLField{ - const UNIT_GET_ABI_INFO:TypeLayoutCtor=GetTypeLayoutCtor::<()>::STABLE_ABI; + + pub(crate) fn get_return(&self) -> TLField { + const UNIT_GET_ABI_INFO: TypeLayoutCtor = GetTypeLayoutCtor::<()>::STABLE_ABI; TLField::new( rstr!("__returns"), self.return_type_layout.unwrap_or(UNIT_GET_ABI_INFO), @@ -340,39 +314,41 @@ impl TLFunction{ ) } - /// Gets the parameters and return types - pub(crate) fn get_params_ret_iter(&self)->impl ExactSizeIterator+Clone+Debug{ - ChainOnce::new(self.get_params(),self.get_return()) + /// Gets the parameters and return types + pub(crate) fn get_params_ret_iter( + &self, + ) -> impl ExactSizeIterator + Clone + Debug { + ChainOnce::new(self.get_params(), self.get_return()) } - /// Gets the parameters and return types + /// Gets the parameters and return types #[allow(dead_code)] - pub(crate) fn get_params_ret_vec(&self)->RVec{ + pub(crate) fn get_params_ret_vec(&self) -> RVec { self.get_params_ret_iter().collect() } } -impl Display for TLFunction{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - write!(f,"fn(")?; - let params=self.get_params(); - let param_count=params.len(); - for (param_i,param) in params.enumerate() { - Display::fmt(¶m.name(),f)?; - Display::fmt(&": ",f)?; - Display::fmt(¶m.full_type(),f)?; - if param_i+1!=param_count { - Display::fmt(&", ",f)?; +impl Display for TLFunction { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "fn(")?; + let params = self.get_params(); + let param_count = params.len(); + for (param_i, param) in params.enumerate() { + Display::fmt(¶m.name(), f)?; + Display::fmt(&": ", f)?; + Display::fmt(¶m.full_type(), f)?; + if param_i + 1 != param_count { + Display::fmt(&", ", f)?; } } - write!(f,")")?; - - let returns=self.get_return(); - Display::fmt(&"->",f)?; - Display::fmt(&returns.full_type(),f)?; + write!(f, ")")?; + + let returns = self.get_return(); + Display::fmt(&"->", f)?; + Display::fmt(&returns.full_type(), f)?; if !self.paramret_lifetime_indices.is_empty() { - writeln!(f,"\nlifetime indices:{:?}",self.paramret_lifetime_indices)?; + writeln!(f, "\nlifetime indices:{:?}", self.paramret_lifetime_indices)?; } Ok(()) @@ -381,102 +357,95 @@ impl Display for TLFunction{ /////////////////////////////////////////////////////////////////////////////// - /// An iterator over a range of `TLFunction`s. -pub struct TLFunctionIter{ - start:usize, - end:usize, - functions:Option<&'static TLFunctions>, - shared_vars:&'static SharedVars, +pub struct TLFunctionIter { + start: usize, + end: usize, + functions: Option<&'static TLFunctions>, + shared_vars: &'static SharedVars, } - -impl TLFunctionIter{ +impl TLFunctionIter { fn new( - start_len:StartLen, - functions:Option<&'static TLFunctions>, - shared_vars:&'static SharedVars, - )->Self{ - let Range{start,end}=start_len.to_range(); - if let Some(functions)=functions { - assert!(start <= functions.len(),"{} < {}",start,functions.len()); - assert!(end <= functions.len(),"{} < {}",end ,functions.len()); + start_len: StartLen, + functions: Option<&'static TLFunctions>, + shared_vars: &'static SharedVars, + ) -> Self { + let Range { start, end } = start_len.to_range(); + if let Some(functions) = functions { + assert!(start <= functions.len(), "{} < {}", start, functions.len()); + assert!(end <= functions.len(), "{} < {}", end, functions.len()); } - Self{ + Self { start, end, functions, shared_vars, } } - fn length(&self)->usize{ - self.end-self.start + fn length(&self) -> usize { + self.end - self.start } } -impl Iterator for TLFunctionIter{ - type Item=TLFunction; +impl Iterator for TLFunctionIter { + type Item = TLFunction; - fn next(&mut self)->Option{ - let functions=self.functions?; - if self.start>=self.end { + fn next(&mut self) -> Option { + let functions = self.functions?; + if self.start >= self.end { return None; } - let ret=functions.index(self.start,self.shared_vars); - self.start+=1; + let ret = functions.index(self.start, self.shared_vars); + self.start += 1; Some(ret) } - fn size_hint(&self)->(usize,Option){ - let len=self.length(); - (len,Some(len)) + fn size_hint(&self) -> (usize, Option) { + let len = self.length(); + (len, Some(len)) } - fn count(self)->usize{ + fn count(self) -> usize { self.length() } } -impl ExactSizeIterator for TLFunctionIter{} - - +impl ExactSizeIterator for TLFunctionIter {} //////////////////////////////////// - -#[derive(Debug,Clone)] -pub struct GetParamNames{ - split:std::str::Split<'static,char>, - length:usize, - current:usize, +#[derive(Debug, Clone)] +pub struct GetParamNames { + split: std::str::Split<'static, char>, + length: usize, + current: usize, } -impl Iterator for GetParamNames{ - type Item=&'static str; - fn next(&mut self) -> Option{ - if self.length==self.current{ +impl Iterator for GetParamNames { + type Item = &'static str; + fn next(&mut self) -> Option { + if self.length == self.current { return None; } - let current=self.current; - self.current+=1; - match self.split.next().filter(|&x| !x.is_empty()||x=="_" ) { - Some(x)=>Some(x), - None=>Some(PARAM_INDEX[current]), + let current = self.current; + self.current += 1; + match self.split.next().filter(|&x| !x.is_empty() || x == "_") { + Some(x) => Some(x), + None => Some(PARAM_INDEX[current]), } } fn size_hint(&self) -> (usize, Option) { - let len=self.length-self.current; - (len,Some(len)) + let len = self.length - self.current; + (len, Some(len)) } fn count(self) -> usize { - self.length-self.current + self.length - self.current } } - -impl std::iter::ExactSizeIterator for GetParamNames{} - +impl std::iter::ExactSizeIterator for GetParamNames {} static PARAM_INDEX: [&str; 64] = [ "param_0", "param_1", "param_2", "param_3", "param_4", "param_5", "param_6", "param_7", @@ -488,4 +457,3 @@ static PARAM_INDEX: [&str; 64] = [ "param_48", "param_49", "param_50", "param_51", "param_52", "param_53", "param_54", "param_55", "param_56", "param_57", "param_58", "param_59", "param_60", "param_61", "param_62", "param_63", ]; - diff --git a/abi_stable/src/type_layout/tl_lifetimes.rs b/abi_stable/src/type_layout/tl_lifetimes.rs index 24168efe..ae0ad9f3 100644 --- a/abi_stable/src/type_layout/tl_lifetimes.rs +++ b/abi_stable/src/type_layout/tl_lifetimes.rs @@ -1,12 +1,10 @@ -use super::*; -use super::data_structures::ArrayLen; +use super::{data_structures::ArrayLen, *}; -use std::ops::{Deref,Index}; +use std::ops::{Deref, Index}; - -abi_stable_shared::declare_tl_lifetime_types!{ +abi_stable_shared::declare_tl_lifetime_types! { repr=u8, - attrs=[ + attrs=[ derive(StableAbi), ] } @@ -14,14 +12,13 @@ abi_stable_shared::declare_tl_lifetime_types!{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// - -impl Display for LifetimeIndex{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ +impl Display for LifetimeIndex { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - LifetimeIndex::STATIC=>f.write_str("'static"), - LifetimeIndex::ANONYMOUS=>f.write_str("'_"), - LifetimeIndex::NONE=>f.write_str("'NONE"), - LifetimeIndex{bits:n}=>write!(f,"'{}",n-Self::START_OF_LIFETIMES), + LifetimeIndex::STATIC => f.write_str("'static"), + LifetimeIndex::ANONYMOUS => f.write_str("'_"), + LifetimeIndex::NONE => f.write_str("'NONE"), + LifetimeIndex { bits: n } => write!(f, "'{}", n - Self::START_OF_LIFETIMES), } } } @@ -30,16 +27,16 @@ impl Display for LifetimeIndex{ impl LifetimeRange { /// Expands this `LifetimeRange` into a `LifetimeArrayOrSlice` - pub fn slicing(self,lifetime_indices:&[LifetimeIndexPair])->LifetimeArrayOrSlice<'_>{ - let len=(self.len()+1)/2; + pub fn slicing(self, lifetime_indices: &[LifetimeIndexPair]) -> LifetimeArrayOrSlice<'_> { + let len = (self.len() + 1) / 2; if self.is_range() { - let start=(self.bits&Self::START_MASK) as usize; - let end =start+len; - let x=RSlice::from_slice(&lifetime_indices[start..end]); + let start = (self.bits & Self::START_MASK) as usize; + let end = start + len; + let x = RSlice::from_slice(&lifetime_indices[start..end]); LifetimeArrayOrSlice::Slice(x) - }else{ - LifetimeArrayOrSlice::Array(ArrayLen{ - len:len as u16, + } else { + LifetimeArrayOrSlice::Array(ArrayLen { + len: len as u16, array: LifetimeIndexArray::from_u20(self.bits).to_array(), }) } @@ -51,57 +48,50 @@ impl LifetimeRange { /// Either an array of 3 `LifetimeIndexPair`,or a slice of `LifetimeIndexPair`. #[repr(u8)] #[derive(Debug, Copy, Clone, PartialEq, Eq, StableAbi)] -pub enum LifetimeArrayOrSlice<'a>{ - Slice(RSlice<'a,LifetimeIndexPair>), - Array(ArrayLen<[LifetimeIndexPair;3]>), +pub enum LifetimeArrayOrSlice<'a> { + Slice(RSlice<'a, LifetimeIndexPair>), + Array(ArrayLen<[LifetimeIndexPair; 3]>), } - -impl<'a> LifetimeArrayOrSlice<'a>{ +impl<'a> LifetimeArrayOrSlice<'a> { /// An empty `LifetimeArrayOrSlice`. - pub const EMPTY:Self=LifetimeArrayOrSlice::Array(ArrayLen{ - len:0, - array:[LifetimeIndexPair::NONE,LifetimeIndexPair::NONE,LifetimeIndexPair::NONE] + pub const EMPTY: Self = LifetimeArrayOrSlice::Array(ArrayLen { + len: 0, + array: [ + LifetimeIndexPair::NONE, + LifetimeIndexPair::NONE, + LifetimeIndexPair::NONE, + ], }); /// Gets a slice of the `LifetimeIndexPair` this contains. - pub fn as_slice(&self)->&[LifetimeIndexPair]{ + pub fn as_slice(&self) -> &[LifetimeIndexPair] { match self { - LifetimeArrayOrSlice::Slice(slice)=>{ - slice.as_slice() - } - LifetimeArrayOrSlice::Array(arraylen)=>{ - &arraylen.array[..arraylen.len as usize] - } + LifetimeArrayOrSlice::Slice(slice) => slice.as_slice(), + LifetimeArrayOrSlice::Array(arraylen) => &arraylen.array[..arraylen.len as usize], } } } - -impl<'a> Deref for LifetimeArrayOrSlice<'a>{ - type Target=[LifetimeIndexPair]; +impl<'a> Deref for LifetimeArrayOrSlice<'a> { + type Target = [LifetimeIndexPair]; #[inline] - fn deref(&self)->&[LifetimeIndexPair]{ + fn deref(&self) -> &[LifetimeIndexPair] { self.as_slice() } } - -impl<'a,I,Output:?Sized> Index for LifetimeArrayOrSlice<'a> +impl<'a, I, Output: ?Sized> Index for LifetimeArrayOrSlice<'a> where - [LifetimeIndexPair]:Index, + [LifetimeIndexPair]: Index, { - type Output=Output; + type Output = Output; #[inline] - fn index(&self,i:I)->&Output{ + fn index(&self, i: I) -> &Output { &self.as_slice()[i] } } - //////////////////////////////////////////////////////////////////////////////// - - - diff --git a/abi_stable/src/type_layout/tl_multi_tl.rs b/abi_stable/src/type_layout/tl_multi_tl.rs index 40452331..c3a592ce 100644 --- a/abi_stable/src/type_layout/tl_multi_tl.rs +++ b/abi_stable/src/type_layout/tl_multi_tl.rs @@ -1,133 +1,123 @@ use crate::{ - abi_stability::stable_abi_trait::TypeLayoutCtor, - std_types::RSlice, + abi_stability::stable_abi_trait::TypeLayoutCtor, std_types::RSlice, type_layout::data_structures::ArrayLen, }; - - //////////////////////////////////////////////////////////////////////////////// - -abi_stable_shared::declare_type_layout_index!{ +abi_stable_shared::declare_type_layout_index! { attrs=[ derive(StableAbi), sabi(unsafe_sabi_opaque_fields), ] } - //////////////////////////////////////////////////////////////////////////////// -abi_stable_shared::declare_multi_tl_types!{ +abi_stable_shared::declare_multi_tl_types! { attrs=[ derive(StableAbi), sabi(unsafe_sabi_opaque_fields), ] } - -impl TypeLayoutRange{ - pub(crate) fn to_array(&self)->[u16;Self::STORED_INLINE]{ +impl TypeLayoutRange { + pub(crate) fn to_array(&self) -> [u16; Self::STORED_INLINE] { [ - ((self.bits0>>Self::INDEX_0_OFFSET)&Self::INDEX_MASK)as u16, - ((self.bits0>>Self::INDEX_1_OFFSET)&Self::INDEX_MASK)as u16, - ((self.bits1>>Self::INDEX_2_OFFSET)&Self::INDEX_MASK)as u16, - ((self.bits1>>Self::INDEX_3_OFFSET)&Self::INDEX_MASK)as u16, - ((self.bits1>>Self::INDEX_4_OFFSET)&Self::INDEX_MASK)as u16, + ((self.bits0 >> Self::INDEX_0_OFFSET) & Self::INDEX_MASK) as u16, + ((self.bits0 >> Self::INDEX_1_OFFSET) & Self::INDEX_MASK) as u16, + ((self.bits1 >> Self::INDEX_2_OFFSET) & Self::INDEX_MASK) as u16, + ((self.bits1 >> Self::INDEX_3_OFFSET) & Self::INDEX_MASK) as u16, + ((self.bits1 >> Self::INDEX_4_OFFSET) & Self::INDEX_MASK) as u16, ] } /// Expands this `TypeLayoutRange` into a `MultipleTypeLayouts<'a>`. - pub fn expand<'a>(&self,type_layouts:&'a [TypeLayoutCtor])->MultipleTypeLayouts<'a>{ - let indices=self.to_array(); - let len=self.len(); + pub fn expand<'a>(&self, type_layouts: &'a [TypeLayoutCtor]) -> MultipleTypeLayouts<'a> { + let indices = self.to_array(); + let len = self.len(); - let first=ArrayLen{ - array:[ + let first = ArrayLen { + array: [ type_layouts[indices[0] as usize], type_layouts[indices[1] as usize], type_layouts[indices[2] as usize], type_layouts[indices[3] as usize], type_layouts[indices[4] as usize], - ], + ], len: len.min(Self::STORED_INLINE) as u16, }; - let remaining=if len <= Self::STORED_INLINE { + let remaining = if len <= Self::STORED_INLINE { RSlice::EMPTY - }else{ - let start_rem=(indices[Self::STORED_INLINE-1]+1)as usize; - let len_rem=len-Self::STORED_INLINE; - RSlice::from_slice(&type_layouts[start_rem..start_rem+len_rem]) + } else { + let start_rem = (indices[Self::STORED_INLINE - 1] + 1) as usize; + let len_rem = len - Self::STORED_INLINE; + RSlice::from_slice(&type_layouts[start_rem..start_rem + len_rem]) }; - - MultipleTypeLayouts{first,remaining} + + MultipleTypeLayouts { first, remaining } } } - //////////////////////////////////////////////////////////////////////////////// - /// This stores multiple `TypeLayoutCtor`,some inline and some in a borrowed slice. #[repr(C)] #[derive(Debug, Copy, Clone, PartialEq, Eq, StableAbi)] -pub struct MultipleTypeLayouts<'a>{ - first:ArrayLen<[TypeLayoutCtor;TypeLayoutRange::STORED_INLINE]>, - remaining:RSlice<'a,TypeLayoutCtor>, +pub struct MultipleTypeLayouts<'a> { + first: ArrayLen<[TypeLayoutCtor; TypeLayoutRange::STORED_INLINE]>, + remaining: RSlice<'a, TypeLayoutCtor>, } - -impl<'a> MultipleTypeLayouts<'a>{ +impl<'a> MultipleTypeLayouts<'a> { /// The amount of `TypeLayoutCtor` this contains. - pub fn len(&self)->usize{ - self.first.len as usize+self.remaining.len() + pub fn len(&self) -> usize { + self.first.len as usize + self.remaining.len() } /// Whether this is empty. - pub fn is_empty(&self)->bool{ + pub fn is_empty(&self) -> bool { self.len() == 0 } /// Gets an iterator over the `TypeLayoutCtor` this contains. - pub fn iter(&self)->MTLIterator<'a> { - MTLIterator{ - this:*self, - index:0, + pub fn iter(&self) -> MTLIterator<'a> { + MTLIterator { + this: *self, + index: 0, } } } /// An iterator over a list of `TypeLayoutCtor`. -#[derive(Clone,Debug)] -pub struct MTLIterator<'a>{ - this:MultipleTypeLayouts<'a>, - index:usize, +#[derive(Clone, Debug)] +pub struct MTLIterator<'a> { + this: MultipleTypeLayouts<'a>, + index: usize, } +impl<'a> Iterator for MTLIterator<'a> { + type Item = TypeLayoutCtor; -impl<'a> Iterator for MTLIterator<'a>{ - type Item=TypeLayoutCtor; - - fn next(&mut self)->Option{ + fn next(&mut self) -> Option { if self.index < self.this.len() { - let ret=if self.index < TypeLayoutRange::STORED_INLINE { + let ret = if self.index < TypeLayoutRange::STORED_INLINE { self.this.first.array[self.index] - }else{ - self.this.remaining[self.index-TypeLayoutRange::STORED_INLINE] + } else { + self.this.remaining[self.index - TypeLayoutRange::STORED_INLINE] }; - self.index+=1; + self.index += 1; Some(ret) - }else{ + } else { None } } - fn size_hint(&self)->(usize,Option){ - let len=self.this.len()-self.index; - (len,Some(len)) + fn size_hint(&self) -> (usize, Option) { + let len = self.this.len() - self.index; + (len, Some(len)) } } -impl<'a> ExactSizeIterator for MTLIterator<'a>{} \ No newline at end of file +impl<'a> ExactSizeIterator for MTLIterator<'a> {} diff --git a/abi_stable/src/type_layout/tl_other.rs b/abi_stable/src/type_layout/tl_other.rs index 9c23c567..eb413f24 100644 --- a/abi_stable/src/type_layout/tl_other.rs +++ b/abi_stable/src/type_layout/tl_other.rs @@ -1,11 +1,6 @@ - use super::*; -use crate::{ - abi_stability::ConstGeneric, -}; - - +use crate::abi_stability::ConstGeneric; ///////////////////////////////////////////////////// @@ -13,7 +8,7 @@ use crate::{ #[repr(u8)] #[derive(Debug, Copy, Clone, PartialEq, Eq, StableAbi)] #[sabi(unsafe_sabi_opaque_fields)] -pub enum ReprAttr{ +pub enum ReprAttr { /// This is an Option. /// In which the size and alignment of the Option<_> is exactly that of its contents. /// @@ -32,53 +27,47 @@ pub enum ReprAttr{ Int(DiscriminantRepr), // Added just in case that I add support for it #[doc(hidden)] - Packed{ + Packed { /// The alignment represented as a `1 << alignment_power_of_two`. - alignment_power_of_two:u8, - } + alignment_power_of_two: u8, + }, } - ///////////////////////////////////////////////////// - /** A module path. */ #[repr(transparent)] -#[derive(Debug, Copy, Clone,Eq,PartialEq, StableAbi)] +#[derive(Debug, Copy, Clone, Eq, PartialEq, StableAbi)] #[sabi(unsafe_sabi_opaque_fields)] pub struct ModPath(NulStr<'static>); -impl ModPath{ - +impl ModPath { /// An item without a path - pub const NO_PATH:Self=ModPath(nul_str!("")); + pub const NO_PATH: Self = ModPath(nul_str!("")); /// An item in the prelude. - pub const PRELUDE:Self=ModPath(nul_str!("")); + pub const PRELUDE: Self = ModPath(nul_str!("")); /// Constructs a ModPath from a string with a module path. - pub const fn inside(path:NulStr<'static>)->Self{ + pub const fn inside(path: NulStr<'static>) -> Self { ModPath(path) } } - -impl Display for ModPath{ +impl Display for ModPath { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - Display::fmt(&self.0,f) + Display::fmt(&self.0, f) } } - ///////////////////////////////////////////////////// - /// The compressed generic parameters of a type, /// which can be expanded into a `GenericParams` by calling `expand`. #[repr(C)] -#[derive(Debug, Copy, Clone, PartialEq, Eq,StableAbi)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, StableAbi)] #[sabi(unsafe_sabi_opaque_fields)] pub struct CompGenericParams { /// The names of the lifetimes declared by a type. @@ -87,18 +76,18 @@ pub struct CompGenericParams { types: StartLen, /// The const parameters of a type,getting them from the containing TypeLayout. consts: StartLen, - lifetime_count:u8, + lifetime_count: u8, } -impl CompGenericParams{ +impl CompGenericParams { /// Constructs a CompGenericParams. pub const fn new( lifetime: NulStr<'static>, - lifetime_count:u8, - types:StartLen, - consts:StartLen, - )->Self{ - Self{ + lifetime_count: u8, + types: StartLen, + consts: StartLen, + ) -> Self { + Self { lifetime, lifetime_count, types, @@ -107,26 +96,26 @@ impl CompGenericParams{ } /// Expands this `CompGenericParams` into a `GenericParams`. - pub fn expand(self,shared_vars:&'static SharedVars)->GenericParams{ - GenericParams{ + pub fn expand(self, shared_vars: &'static SharedVars) -> GenericParams { + GenericParams { lifetime: self.lifetime, types: &shared_vars.type_layouts()[self.types.to_range()], consts: &shared_vars.constants()[self.consts.to_range()], - lifetime_count:self.lifetime_count, + lifetime_count: self.lifetime_count, } } } /// The generic parameters of a type. -#[derive(Copy,Clone,PartialEq,Eq)] -pub struct GenericParams{ +#[derive(Copy, Clone, PartialEq, Eq)] +pub struct GenericParams { /// The names of the lifetimes declared by a type. pub(super) lifetime: NulStr<'static>, /// The type parameters of a type,getting them from the containing TypeLayout. pub(super) types: &'static [TypeLayoutCtor], /// The const parameters of a type,getting them from the containing TypeLayout. pub(super) consts: &'static [ConstGeneric], - pub(super) lifetime_count:u8, + pub(super) lifetime_count: u8, } impl GenericParams { @@ -136,19 +125,19 @@ impl GenericParams { } /// Gets an iterator over the names of the lifetime parameters of the type. - pub fn lifetimes(&self)-> impl Iterator+Clone+Send+Sync+'static { - self.lifetime.to_str().split(',').filter(|x| !x.is_empty() ) + pub fn lifetimes(&self) -> impl Iterator + Clone + Send + Sync + 'static { + self.lifetime.to_str().split(',').filter(|x| !x.is_empty()) } /// The amount of lifetimes of the type. - pub fn lifetime_count(&self)->usize{ + pub fn lifetime_count(&self) -> usize { self.lifetime_count as usize } /// The type parameters of the type. - pub fn type_params(&self)->&'static [TypeLayoutCtor]{ + pub fn type_params(&self) -> &'static [TypeLayoutCtor] { self.types } /// The const parameters of the type. - pub fn const_params(&self)->&'static [ConstGeneric]{ + pub fn const_params(&self) -> &'static [ConstGeneric] { self.consts } } @@ -163,8 +152,8 @@ impl Display for GenericParams { } Ok(()) }; - - for (i, param) in self.lifetimes().enumerate() { + + for (i, param) in self.lifetimes().enumerate() { fmt::Display::fmt(param, &mut *f)?; post_iter(i, self.lifetime_count(), &mut *f)?; } @@ -181,15 +170,13 @@ impl Display for GenericParams { } } - /////////////////////////////////////////////////////////////////////////////// - /// Types defined in the compiler #[repr(u8)] -#[derive(Debug, Copy, Clone, PartialEq, Eq,StableAbi)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, StableAbi)] #[sabi(unsafe_sabi_opaque_fields)] -pub enum TLPrimitive{ +pub enum TLPrimitive { U8, I8, U16, @@ -210,85 +197,76 @@ pub enum TLPrimitive{ /// A `*mut T` MutPtr, /// An array. - Array{ - len:usize, + Array { + len: usize, }, } - /////////////////////////// - /// The typename and generics of the type this layout is associated to, /// used for printing types (eg: `RVec` ). -#[derive(Copy,Clone,PartialEq,Eq)] +#[derive(Copy, Clone, PartialEq, Eq)] pub struct FmtFullType { - pub(super) name:&'static str, - pub(super) generics:GenericParams, - pub(super) primitive:Option, - pub(super) utypeid:UTypeId, + pub(super) name: &'static str, + pub(super) generics: GenericParams, + pub(super) primitive: Option, + pub(super) utypeid: UTypeId, } -impl FmtFullType{ +impl FmtFullType { /// The name of a type. - pub fn name(&self)->&'static str{ + pub fn name(&self) -> &'static str { self.name } /// The generic parmaters of a type. - pub fn generics(&self)->GenericParams{ + pub fn generics(&self) -> GenericParams { self.generics } } - //////////////////////////////////// - /** Either a TLField or a TLFunction. */ #[repr(u8)] -#[derive(Copy,Clone,Debug,Eq,PartialEq,StableAbi)] +#[derive(Copy, Clone, Debug, Eq, PartialEq, StableAbi)] #[sabi(unsafe_sabi_opaque_fields)] -pub enum TLFieldOrFunction{ +pub enum TLFieldOrFunction { Field(TLField), Function(TLFunction), } - -impl From for TLFieldOrFunction{ - fn from(x:TLField)->Self{ +impl From for TLFieldOrFunction { + fn from(x: TLField) -> Self { TLFieldOrFunction::Field(x) } } -impl From for TLFieldOrFunction{ - fn from(x:TLFunction)->Self{ +impl From for TLFieldOrFunction { + fn from(x: TLFunction) -> Self { TLFieldOrFunction::Function(x) } } - -impl Display for TLFieldOrFunction{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ +impl Display for TLFieldOrFunction { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - TLFieldOrFunction::Field(x)=>Display::fmt(x,f), - TLFieldOrFunction::Function(x)=>Display::fmt(x,f), + TLFieldOrFunction::Field(x) => Display::fmt(x, f), + TLFieldOrFunction::Function(x) => Display::fmt(x, f), } } } - -impl TLFieldOrFunction{ +impl TLFieldOrFunction { /// Outputs this into a String with `Display` formatting. - pub fn formatted_layout(&self)->String{ + pub fn formatted_layout(&self) -> String { match self { - TLFieldOrFunction::Field(x)=>x.layout().to_string(), - TLFieldOrFunction::Function(x)=>x.to_string(), + TLFieldOrFunction::Field(x) => x.layout().to_string(), + TLFieldOrFunction::Function(x) => x.to_string(), } } } - - ////////////////////////////////////////////////////////////////////////////// diff --git a/abi_stable/src/type_layout/tl_prefix.rs b/abi_stable/src/type_layout/tl_prefix.rs index 9c53538f..b8406582 100644 --- a/abi_stable/src/type_layout/tl_prefix.rs +++ b/abi_stable/src/type_layout/tl_prefix.rs @@ -1,53 +1,51 @@ use super::*; - //////////////////////////////////////////////////////////////////////////////// - - /// Properties of prefix types /// (vtables and modules) that don't change with generic parameters. #[repr(C)] #[derive(Copy, Clone, StableAbi)] pub struct MonoTLPrefixType { /// The first field in the suffix, - /// the index to the field after + /// the index to the field after /// the one to which `#[sabi(last_prefix_field)]` was applied to - pub first_suffix_field:u8, - /// Which fields in the prefix + pub first_suffix_field: u8, + /// Which fields in the prefix /// (the ones up to the one with the `#[sabi(last_prefix_field)]` attribute) - /// are conditionally accessible + /// are conditionally accessible /// (with the `#[sabi(accessible_if=" expression ")]` attribute). - pub conditional_prefix_fields:FieldConditionality, + pub conditional_prefix_fields: FieldConditionality, /// All the fields of the prefix-type,even if they are inaccessible. pub fields: CompTLFields, } - -impl MonoTLPrefixType{ +impl MonoTLPrefixType { /// Expands this into a `TLPrefixType`. - pub fn expand(self,other:GenericTLPrefixType,shared_vars:&'static SharedVars)->TLPrefixType{ - TLPrefixType{ - first_suffix_field:self.first_suffix_field, - conditional_prefix_fields:self.conditional_prefix_fields, - fields:self.fields.expand(shared_vars), - accessible_fields:other.accessible_fields, + pub fn expand( + self, + other: GenericTLPrefixType, + shared_vars: &'static SharedVars, + ) -> TLPrefixType { + TLPrefixType { + first_suffix_field: self.first_suffix_field, + conditional_prefix_fields: self.conditional_prefix_fields, + fields: self.fields.expand(shared_vars), + accessible_fields: other.accessible_fields, } } } - ///////////////////////////////////////////////////// - /// Properties of prefix types /// (vtables and modules) that depends on generic parameters. #[repr(C)] #[derive(Copy, Clone, StableAbi)] pub struct GenericTLPrefixType { - /// Which fields are accessible when the prefix type is instantiated in + /// Which fields are accessible when the prefix type is instantiated in /// the same dynlib/binary. - pub accessible_fields:FieldAccessibility, + pub accessible_fields: FieldAccessibility, } ///////////////////////////////////////////////////// @@ -58,38 +56,35 @@ pub struct GenericTLPrefixType { #[derive(Debug, Copy, Clone, PartialEq, Eq, StableAbi)] pub struct TLPrefixType { /// The first field in the suffix, - /// the index to the field after + /// the index to the field after /// the one to which `#[sabi(last_prefix_field)]` was applied to - pub first_suffix_field:u8, - /// Which fields in the prefix + pub first_suffix_field: u8, + /// Which fields in the prefix /// (the ones up to the one with the `#[sabi(last_prefix_field)]` attribute) - /// are conditionally accessible + /// are conditionally accessible /// (with the `#[sabi(accessible_if=" expression ")]` attribute). - pub conditional_prefix_fields:FieldConditionality, + pub conditional_prefix_fields: FieldConditionality, /// All the fields of the prefix-type,even if they are inaccessible. pub fields: TLFields, - /// Which fields are accessible when the prefix type is instantiated in + /// Which fields are accessible when the prefix type is instantiated in /// the same dynlib/binary. - pub accessible_fields:FieldAccessibility, - + pub accessible_fields: FieldAccessibility, } - impl Display for TLPrefixType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - writeln!(f,"first_suffix_field:{}",self.first_suffix_field)?; + writeln!(f, "first_suffix_field:{}", self.first_suffix_field)?; writeln!( f, "conditional_prefix_fields:\n {:b}", self.conditional_prefix_fields.bits(), )?; - writeln!(f,"fields:\n{}",self.fields.to_string().left_padder(4))?; - write!(f,"accessible_fields:\n ")?; + writeln!(f, "fields:\n{}", self.fields.to_string().left_padder(4))?; + write!(f, "accessible_fields:\n ")?; f.debug_list() - .entries(self.accessible_fields.iter_count(self.fields.len())) - .finish()?; + .entries(self.accessible_fields.iter_count(self.fields.len())) + .finish()?; Ok(()) } } - diff --git a/abi_stable/src/type_layout/tl_reflection.rs b/abi_stable/src/type_layout/tl_reflection.rs index 444f5626..b1032a72 100644 --- a/abi_stable/src/type_layout/tl_reflection.rs +++ b/abi_stable/src/type_layout/tl_reflection.rs @@ -1,6 +1,5 @@ use crate::std_types::RStr; - //////////////////////////////////////////////////////////////////////////////// /// Whether a field is accessible,and how it is accessed. @@ -13,58 +12,45 @@ pub enum FieldAccessor { /// Accessible with `fn field_name(&self)->FieldType` Method, /// Accessible with `fn name(&self)->FieldType` - MethodNamed{ - name:RStr<'static>, - }, + MethodNamed { name: RStr<'static> }, /// Accessible with `fn field_name(&self)->Option` MethodOption, /// This field is completely inaccessible. Opaque, } - -impl FieldAccessor{ +impl FieldAccessor { /// Constructs a FieldAccessor for a method named `name`. - pub const fn method_named(name:RStr<'static>)->Self{ - FieldAccessor::MethodNamed{name} + pub const fn method_named(name: RStr<'static>) -> Self { + FieldAccessor::MethodNamed { name } } } - //////////////////////////////////////////////////////////////////////////////// - -abi_stable_shared::declare_comp_field_accessor!{ - attrs=[ +abi_stable_shared::declare_comp_field_accessor! { + attrs=[ derive(StableAbi), sabi(unsafe_sabi_opaque_fields), ] } - -impl CompFieldAccessor{ +impl CompFieldAccessor { /// Expands this `CompFieldAccessor` into a `FieldAccessor`, /// using the string slice contained in the `SharedVars` of /// the `TypeLayout` this is stored inside of. - pub fn expand(self,string:&'static str)->Option{ + pub fn expand(self, string: &'static str) -> Option { Some(match self { - Self::DIRECT=> - FieldAccessor::Direct, - Self::METHOD=> - FieldAccessor::Method, - Self::METHOD_NAMED=> - FieldAccessor::MethodNamed{name:string.into()}, - Self::METHOD_OPTION=> - FieldAccessor::MethodOption, - Self::OPAQUE=> - FieldAccessor::Opaque, - _=>return None, + Self::DIRECT => FieldAccessor::Direct, + Self::METHOD => FieldAccessor::Method, + Self::METHOD_NAMED => FieldAccessor::MethodNamed { + name: string.into(), + }, + Self::METHOD_OPTION => FieldAccessor::MethodOption, + Self::OPAQUE => FieldAccessor::Opaque, + _ => return None, }) } } - //////////////////////////////////////////////////////////////////////////////// - - - diff --git a/abi_stable/src/type_level.rs b/abi_stable/src/type_level.rs index dc7c4796..03623492 100644 --- a/abi_stable/src/type_level.rs +++ b/abi_stable/src/type_level.rs @@ -9,23 +9,21 @@ This is a re-export from `core_extensions::type_level_bool`, so as to allow glob imports (`abi_stable::type_level::bools::*`) without worrying about importing too many items. */ -pub mod bools{ +pub mod bools { #[doc(no_inline)] - pub use core_extensions::type_level_bool::{True,False,Boolean}; + pub use core_extensions::type_level_bool::{Boolean, False, True}; } - // Uncomment if I have a use for type-level `Option`s // pub mod option; -/// Type-level enum representing whether a +/// Type-level enum representing whether a /// `DynTrait`/`RObject`/`#[sabi_trait]`-generated trait object /// can be converted back into the concrete type they were constructed with. pub mod downcasting; - /// Marker types representing traits. -pub mod trait_marker{ +pub mod trait_marker { pub struct Send; pub struct Sync; pub struct Clone; @@ -43,122 +41,115 @@ pub mod trait_marker{ /// Represents the `serde::Serialize` trait. pub struct Serialize; - + pub struct Iterator; pub struct DoubleEndedIterator; - + /// Represents the `std::fmt::Write` trait. pub struct FmtWrite; - + /// Represents the `std::io::Write` trait. pub struct IoWrite; - + /// Represents the `std::io::Seek` trait. pub struct IoSeek; - + /// Represents the `std::io::Read` trait. pub struct IoRead; /// Represents the `std::io::BufRead` trait. pub struct IoBufRead; - + /// Represents the `std::error::Error` trait. pub struct Error; - + #[doc(hidden)] #[allow(non_camel_case_types)] pub struct define_this_in_the_impl_InterfaceType_macro; } - /// Type-level-enum representing whether a trait is implemented or not implemented. -pub mod impl_enum{ +pub mod impl_enum { use crate::marker_type::NonOwningPhantom; - use core_extensions::type_level_bool::{True,False}; + use core_extensions::type_level_bool::{False, True}; - mod sealed{ - pub trait Sealed{} + mod sealed { + pub trait Sealed {} } use self::sealed::Sealed; /// Queries whether this type is `Implemented` - pub trait Implementability:Sealed{ + pub trait Implementability: Sealed { /// Whether the trait represented by the type parameter must be implemented. - const IS_IMPLD:bool; + const IS_IMPLD: bool; } - /// Converts a type to either `Unimplemented` or `Implemented`. /// /// The `T` type parameter represents the (un)required trait. /// - pub trait ImplFrom_{ + pub trait ImplFrom_ { /// Either `Unimplemented` or `Implemented`. - type Impl:?Sized; - + type Impl: ?Sized; + /// Either `Unimplemented` or `Implemented`. - const IMPL:Self::Impl; + const IMPL: Self::Impl; } - impl ImplFrom_ for False { - type Impl=Unimplemented; - const IMPL:Unimplemented=Unimplemented::NEW; + impl ImplFrom_ for False { + type Impl = Unimplemented; + const IMPL: Unimplemented = Unimplemented::NEW; } - impl ImplFrom_ for True { - type Impl=Implemented; - const IMPL:Implemented=Implemented::NEW; + impl ImplFrom_ for True { + type Impl = Implemented; + const IMPL: Implemented = Implemented::NEW; } - impl ImplFrom_ for Unimplemented { - type Impl=Unimplemented; - const IMPL:Unimplemented=Unimplemented::NEW; + impl ImplFrom_ for Unimplemented { + type Impl = Unimplemented; + const IMPL: Unimplemented = Unimplemented::NEW; } - impl ImplFrom_ for Implemented { - type Impl=Implemented; - const IMPL:Implemented=Implemented::NEW; + impl ImplFrom_ for Implemented { + type Impl = Implemented; + const IMPL: Implemented = Implemented::NEW; } /// Converts `B` to either `Unimplemented` or `Implemented`. /// /// The `T` type parameter represents the (un)required trait. - pub type ImplFrom= - >::Impl; - - + pub type ImplFrom = >::Impl; /// Describes that a trait must be implemented. /// /// The `T` type parameter represents the required trait. - pub struct Implemented(NonOwningPhantom); + pub struct Implemented(NonOwningPhantom); - impl Implemented{ + impl Implemented { /// Constructs an `Implemented`. - pub const NEW:Implemented=Implemented(NonOwningPhantom::NEW); + pub const NEW: Implemented = Implemented(NonOwningPhantom::NEW); } - impl Sealed for Implemented{} - impl Implementability for Implemented{ - const IS_IMPLD:bool=true; + impl Sealed for Implemented {} + impl Implementability for Implemented { + const IS_IMPLD: bool = true; } - - /// Describes that a trait does not need to be implemented. /// /// The `T` type parameter represents the trait. - pub struct Unimplemented(NonOwningPhantom); + pub struct Unimplemented(NonOwningPhantom); - impl Unimplemented{ + impl Unimplemented { /// Constructs an `Unimplemented`. - pub const NEW:Unimplemented=Unimplemented(NonOwningPhantom::NEW); + pub const NEW: Unimplemented = Unimplemented(NonOwningPhantom::NEW); } - impl Sealed for Unimplemented{} - impl Implementability for Unimplemented{ - const IS_IMPLD:bool=false; + impl Sealed for Unimplemented {} + impl Implementability for Unimplemented { + const IS_IMPLD: bool = false; } -} \ No newline at end of file +} diff --git a/abi_stable/src/type_level/downcasting.rs b/abi_stable/src/type_level/downcasting.rs index d544e8ae..fbfc836c 100644 --- a/abi_stable/src/type_level/downcasting.rs +++ b/abi_stable/src/type_level/downcasting.rs @@ -1,94 +1,89 @@ use crate::{ - sabi_types::{Constructor,MaybeCmp}, - std_types::utypeid::{UTypeId,no_utypeid,some_utypeid}, + sabi_types::{Constructor, MaybeCmp}, + std_types::utypeid::{no_utypeid, some_utypeid, UTypeId}, }; - -/// Passed to trait object constructors to make the +/// Passed to trait object constructors to make the /// trait object downcast capable, -/// as opposed to [`TD_Opaque`](./struct.TD_Opaque.html). -/// +/// as opposed to [`TD_Opaque`](./struct.TD_Opaque.html). +/// /// [The `from_value`/`from_ptr`/`from_const` methods here /// ](../../docs/sabi_trait_inherent/index.html#methods) take this type. -/// +/// /// # Example -/// +/// /// ```rust /// use abi_stable::{ /// sabi_trait::doc_examples::Action_TO, /// std_types::RBox, /// type_level::downcasting::TD_CanDowncast, /// }; -/// +/// /// // The type annotation is purely for the reader. /// let mut object: Action_TO<'static, RBox<()>> = /// Action_TO::from_value(100_usize, TD_CanDowncast); -/// +/// /// assert_eq!(object.obj.downcast_as::().ok(), None); /// assert_eq!(object.obj.downcast_as::().ok(), None); /// assert_eq!(object.obj.downcast_as::().ok(), Some(&100_usize)); -/// +/// /// ``` #[allow(non_camel_case_types)] -#[derive(Copy,Clone)] +#[derive(Copy, Clone)] pub struct TD_CanDowncast; -/// Passed to trait object constructors to make it impossible to downcast the +/// Passed to trait object constructors to make it impossible to downcast the /// trait object, -/// as opposed to [`TD_CanDowncast`](./struct.TD_CanDowncast.html). -/// +/// as opposed to [`TD_CanDowncast`](./struct.TD_CanDowncast.html). +/// /// [The `from_value`/`from_ptr`/`from_const` methods here /// ](../../docs/sabi_trait_inherent/index.html#methods) take this type. /// /// # Example -/// +/// /// ```rust /// use abi_stable::{ /// sabi_trait::doc_examples::Action_TO, /// std_types::RBox, /// type_level::downcasting::TD_Opaque, /// }; -/// +/// /// // The type annotation is purely for the reader. /// let mut object: Action_TO<'static, RBox<()>> = /// Action_TO::from_value(100_usize, TD_Opaque); -/// +/// /// assert_eq!(object.obj.downcast_as::().ok(), None); -/// +/// /// assert_eq!(object.obj.downcast_as::().ok(), None); -/// +/// /// // Because `Action_TO::from-value` was passed `TD_Opaque`, /// // the trait object can't be downcasted /// assert_eq!(object.obj.downcast_as::().ok(), None); -/// +/// /// ``` #[allow(non_camel_case_types)] -#[derive(Copy,Clone)] +#[derive(Copy, Clone)] pub struct TD_Opaque; - - - - /// Gets a function optionally returning the `UTypeId` of `T`. /// /// Whether the function returns `MaybeCmp::Just(typeid)` is determined by implementors: -/// +/// /// - `TD_CanDowncast`: the function always returns `MaybeCmp::Just(typeid)`. -/// +/// /// - `TD_Opaque`: the function always returns `MaybeCmp::Nothing`. pub trait GetUTID { /// A struct wrapping the function. - const UID:Constructor>; + const UID: Constructor>; } - impl GetUTID for TD_CanDowncast -where T:'static +where + T: 'static, { - const UID:Constructor>=Constructor( some_utypeid:: ); + const UID: Constructor> = Constructor(some_utypeid::); } -impl GetUTID for TD_Opaque{ - const UID:Constructor>=Constructor( no_utypeid ); -} \ No newline at end of file +impl GetUTID for TD_Opaque { + const UID: Constructor> = Constructor(no_utypeid); +} diff --git a/abi_stable/src/utils.rs b/abi_stable/src/utils.rs index 0893ad5d..92c7bdcb 100644 --- a/abi_stable/src/utils.rs +++ b/abi_stable/src/utils.rs @@ -4,40 +4,32 @@ Utility functions. use std::{ cmp::Ord, - fmt::{self,Debug,Display}, - mem::{self,ManuallyDrop}, + fmt::{self, Debug, Display}, + mem::{self, ManuallyDrop}, ptr::NonNull, }; - -use core_extensions::{ - strings::LeftPadder, - TypeIdentity, - StringExt, -}; +use core_extensions::{strings::LeftPadder, StringExt, TypeIdentity}; use crate::{ sabi_types::RMut, - std_types::{RString,RStr} + std_types::{RStr, RString}, }; - ////////////////////////////////////// - -/// Information about a panic,used in `ffi_panic_message`. -#[derive(Debug,Copy,Clone)] -pub struct PanicInfo{ - pub file:&'static str, - pub line:u32, +/// Information about a panic,used in `ffi_panic_message`. +#[derive(Debug, Copy, Clone)] +pub struct PanicInfo { + pub file: &'static str, + pub line: u32, } - -/// Prints an error message for attempting to panic across the +/// Prints an error message for attempting to panic across the /// ffi boundary and aborts the process. #[inline(never)] #[cold] -pub fn ffi_panic_message(info:&'static PanicInfo) -> ! { +pub fn ffi_panic_message(info: &'static PanicInfo) -> ! { eprintln!("\nfile:{}\nline:{}", info.file, info.line); eprintln!("Attempted to panic across the ffi boundary."); eprintln!("Aborting to handle the panic...\n"); @@ -46,62 +38,52 @@ pub fn ffi_panic_message(info:&'static PanicInfo) -> ! { ////////////////////////////////// - -/// Coverts a `&T` to a `NonNull`. -/// +/// Coverts a `&T` to a `NonNull`. +/// /// # Eaxmple -/// +/// /// ```rust /// use abi_stable::utils::ref_as_nonnull; /// /// use std::ptr::NonNull; -/// +/// /// const NUMBER: NonNull = ref_as_nonnull(&100); -/// +/// /// ``` pub const fn ref_as_nonnull(reference: &T) -> NonNull { - unsafe{ - NonNull::new_unchecked(reference as *const T as *mut T) - } + unsafe { NonNull::new_unchecked(reference as *const T as *mut T) } } /// Casts a `&'a mut ManuallyDrop` to `RMut<'a, T>` pub fn manuallydrop_as_rmut(this: &mut ManuallyDrop) -> RMut<'_, T> { - unsafe{ - RMut::new(this).transmute() - } + unsafe { RMut::new(this).transmute() } } /// Casts a `&'a mut ManuallyDrop` to `*mut T` pub fn manuallydrop_as_raw_mut(this: &mut ManuallyDrop) -> *mut T { - unsafe{ - this as *mut ManuallyDrop as *mut T - } + unsafe { this as *mut ManuallyDrop as *mut T } } - ////////////////////////////////// - #[doc(hidden)] -pub struct AbortBomb{ - pub fuse:&'static PanicInfo, +pub struct AbortBomb { + pub fuse: &'static PanicInfo, } -impl Drop for AbortBomb{ - fn drop(&mut self){ +impl Drop for AbortBomb { + fn drop(&mut self) { ffi_panic_message(self.fuse); } } - ////////////////////////////////// /// Helper type for transmuting between `Copy` types /// without adding any overhead in debug builds. -/// +/// /// # Safety -/// +/// /// Be aware that using this type is equivalent to using [`std::mem::transmute_copy`], /// which doesn't check that `T` and `U` have the same size. /// @@ -115,162 +97,153 @@ pub union Transmuter { ////////////////////////////////// /// Leaks `value` into the heap,and returns a reference to it. -/// +/// /// # Warning -/// +/// /// You must be careful when calling this function, /// since this leak is ignored by [miri](https://github.com/rust-lang/miri). -/// +/// #[inline] -pub fn leak_value<'a,T>(value:T)->&'a T -where T:'a // T:'a is for the docs +pub fn leak_value<'a, T>(value: T) -> &'a T +where + T: 'a, // T:'a is for the docs { let x = Box::new(value); let leaked: &'a T = Box::leak(x); #[cfg(miri)] - unsafe{ + unsafe { crate::miri_static_root(leaked as *const T as *const u8); } leaked } - /// Transmute a reference to another reference, /// changing the referent's type. -/// +/// /// # Safety /// /// This has the same safety concerns that `std::mem::transmute` has,including that /// `T` has to have an alignment and be compatible with `U`. #[inline] #[allow(clippy::needless_lifetimes)] -pub unsafe fn transmute_reference(ref_:&T)->&U{ +pub unsafe fn transmute_reference(ref_: &T) -> &U { &*(ref_ as *const _ as *const U) } - /// Transmute a mutable reference to another mutable reference, /// changing the referent's type. -/// +/// /// # Safety /// /// This has the same safety concerns that `std::mem::transmute` has,including that /// `T` has to have an alignment and be compatible with `U`. #[inline] #[allow(clippy::needless_lifetimes)] -pub unsafe fn transmute_mut_reference<'a,T,U>(ref_:&'a mut T)->&'a mut U{ +pub unsafe fn transmute_mut_reference<'a, T, U>(ref_: &'a mut T) -> &'a mut U { &mut *(ref_ as *mut _ as *mut U) } ////////////////////////////////////// - #[allow(dead_code)] -pub(crate) fn min_by(l:T,r:T,mut f:F)->T -where - F:FnMut(&T)->K, - K:Ord, +pub(crate) fn min_by(l: T, r: T, mut f: F) -> T +where + F: FnMut(&T) -> K, + K: Ord, { if f(&l) < f(&r) { l - }else{ + } else { r } } - #[allow(dead_code)] -pub(crate) fn max_by(l:T,r:T,mut f:F)->T -where - F:FnMut(&T)->K, - K:Ord, +pub(crate) fn max_by(l: T, r: T, mut f: F) -> T +where + F: FnMut(&T) -> K, + K: Ord, { if f(&l) > f(&r) { l - }else{ + } else { r } } #[doc(hidden)] -pub fn min_max_by(l:T,r:T,mut f:F)->(T,T) -where - F:FnMut(&T)->K, - K:Ord, +pub fn min_max_by(l: T, r: T, mut f: F) -> (T, T) +where + F: FnMut(&T) -> K, + K: Ord, { if f(&l) < f(&r) { - (l,r) - }else{ - (r,l) + (l, r) + } else { + (r, l) } } - - ////////////////////////////////////// - - - -pub(crate) trait FmtPadding{ - fn display_pad<'a,T>(&'a mut self,padding:usize,v:&T)->Result ,fmt::Error> - where T:Display; - - fn debug_pad<'a,T>(&'a mut self,padding:usize,v:&T)->Result ,fmt::Error> - where T:Debug; +pub(crate) trait FmtPadding { + fn display_pad<'a, T>( + &'a mut self, + padding: usize, + v: &T, + ) -> Result, fmt::Error> + where + T: Display; + + fn debug_pad<'a, T>(&'a mut self, padding: usize, v: &T) -> Result, fmt::Error> + where + T: Debug; } - macro_rules! impl_fmt_padding { - ($ty:ty) => ( - impl FmtPadding for $ty{ - fn display_pad<'a,T>( + ($ty:ty) => { + impl FmtPadding for $ty { + fn display_pad<'a, T>( &'a mut self, - padding:usize, - v:&T - )->Result ,fmt::Error> - where T:Display + padding: usize, + v: &T, + ) -> Result, fmt::Error> + where + T: Display, { use std::fmt::Write; - let this=self.as_type_mut(); + let this = self.as_type_mut(); this.clear(); - writeln!(this,"{}",v)?; + writeln!(this, "{}", v)?; Ok(this.left_padder(padding)) } - fn debug_pad<'a,T>( + fn debug_pad<'a, T>( &'a mut self, - padding:usize, - v:&T - )->Result ,fmt::Error> - where T:Debug + padding: usize, + v: &T, + ) -> Result, fmt::Error> + where + T: Debug, { use std::fmt::Write; - let this=self.as_type_mut(); + let this = self.as_type_mut(); this.clear(); - writeln!(this,"{:#?}",v)?; + writeln!(this, "{:#?}", v)?; Ok(this.left_padder(padding)) - } + } } + }; +} - ) - } - - - - - -impl_fmt_padding!{ String } -impl_fmt_padding!{ RString } - - - +impl_fmt_padding! { String } +impl_fmt_padding! { RString } ////////////////////////////////////////////////////////////////////// @@ -278,7 +251,7 @@ impl_fmt_padding!{ RString } /// /// # Safety /// -/// After this function is called `slot` will become uninitialized and +/// After this function is called `slot` will become uninitialized and /// must not be read again. pub unsafe fn take_manuallydrop(slot: &mut ManuallyDrop) -> T { #[cfg(feature = "rust_1_42")] @@ -291,72 +264,68 @@ pub unsafe fn take_manuallydrop(slot: &mut ManuallyDrop) -> T { } } - #[doc(hidden)] #[inline(always)] -pub fn assert_fnonce(_:&F) +pub fn assert_fnonce(_: &F) where - F:FnOnce()->R -{} - + F: FnOnce() -> R, +{ +} /// This function allows calculating the distance (in `T`s) from `from` to `to`. -/// +/// /// This returns `None` if `from` has a higher address than `to`, /// or if `T` is a zero sized type. -/// +/// /// # Example -/// +/// /// ``` /// use abi_stable::utils; -/// +/// /// let arr=["hello","world","foo","bar","baz"]; -/// +/// /// assert_eq!(utils::distance_from(&arr[0],&arr[0]),Some(0)); /// assert_eq!(utils::distance_from(&arr[0],&arr[4]),Some(4)); /// /// assert_eq!(utils::distance_from(&arr[4],&arr[0]),None); -/// +/// /// ``` -pub fn distance_from(from:*const T,to:*const T)->Option{ +pub fn distance_from(from: *const T, to: *const T) -> Option { (to as usize) .checked_sub(from as usize)? .checked_div(mem::size_of::()) } - ////////////////////////////////////////////////////////////////////// #[doc(hidden)] -pub extern "C" fn get_type_name()->RStr<'static>{ +pub extern "C" fn get_type_name() -> RStr<'static> { RStr::from(std::any::type_name::()) } - #[cfg(test)] -mod tests{ +mod tests { use super::*; #[test] - fn distance_from_(){ - let int_array=[0,1,2,3,4]; - let unit_array=[(),(),(),(),()]; + fn distance_from_() { + let int_array = [0, 1, 2, 3, 4]; + let unit_array = [(), (), (), (), ()]; - for (ix,x) in int_array.iter().enumerate() { - for (iy,y) in int_array.iter().enumerate() { + for (ix, x) in int_array.iter().enumerate() { + for (iy, y) in int_array.iter().enumerate() { if ix <= iy { - assert_eq!(distance_from(x,y), Some(iy-ix)); - }else{ - assert_eq!(distance_from(x,y), None); + assert_eq!(distance_from(x, y), Some(iy - ix)); + } else { + assert_eq!(distance_from(x, y), None); } } } for x in &unit_array { for y in &unit_array { - assert_eq!(distance_from(x,y), None); + assert_eq!(distance_from(x, y), None); } } - } -} \ No newline at end of file +} diff --git a/abi_stable/tests/layout_tests/const_params.rs b/abi_stable/tests/layout_tests/const_params.rs index bf82f754..3c6daad4 100644 --- a/abi_stable/tests/layout_tests/const_params.rs +++ b/abi_stable/tests/layout_tests/const_params.rs @@ -1,107 +1,83 @@ use abi_stable::{ - StableAbi, - abi_stability::abi_checking::{AbiInstability,check_layout_compatibility}, + abi_stability::abi_checking::{check_layout_compatibility, AbiInstability}, type_layout::TypeLayout, + StableAbi, }; -#[cfg(feature="const_params")] +#[cfg(feature = "const_params")] mod with_const_generics; - -mod one_phantom{ - use abi_stable::{ - const_utils::AssocStr, - marker_type::UnsafeIgnoredType, - }; - +mod one_phantom { + use abi_stable::{const_utils::AssocStr, marker_type::UnsafeIgnoredType}; #[repr(C)] #[derive(abi_stable::StableAbi)] - #[sabi( - bound="T:AssocStr", - phantom_const_param="T::STR", - )] + #[sabi(bound = "T:AssocStr", phantom_const_param = "T::STR")] pub struct Struct(UnsafeIgnoredType); } -mod one_phantom_u8{ - use abi_stable::{ - const_utils::AssocInt, - marker_type::UnsafeIgnoredType, - }; - +mod one_phantom_u8 { + use abi_stable::{const_utils::AssocInt, marker_type::UnsafeIgnoredType}; #[repr(C)] #[derive(abi_stable::StableAbi)] - #[sabi( - bound="T:AssocInt", - phantom_const_param="T::NUM", - )] + #[sabi(bound = "T:AssocInt", phantom_const_param = "T::NUM")] pub struct Struct(UnsafeIgnoredType); } -mod two_phantom{ - use abi_stable::{ - const_utils::AssocStr, - marker_type::UnsafeIgnoredType, - std_types::*, - }; - +mod two_phantom { + use abi_stable::{const_utils::AssocStr, marker_type::UnsafeIgnoredType, std_types::*}; #[repr(C)] #[derive(abi_stable::StableAbi)] #[sabi( - bound="T:AssocStr", - bound="U:AssocStr", - phantom_const_param="T::STR", - phantom_const_param="U::STR", + bound = "T:AssocStr", + bound = "U:AssocStr", + phantom_const_param = "T::STR", + phantom_const_param = "U::STR" )] - pub struct Struct(UnsafeIgnoredType>); + pub struct Struct(UnsafeIgnoredType>); } - - -fn check_imcompatible_with_others(list:&[&'static TypeLayout],mut f:F) +fn check_imcompatible_with_others(list: &[&'static TypeLayout], mut f: F) where - F:FnMut(&[AbiInstability]) + F: FnMut(&[AbiInstability]), { - for (l_i,l_abi) in list.iter().enumerate() { - for (r_i,r_abi) in list.iter().enumerate() { - - let res=check_layout_compatibility(l_abi,r_abi); + for (l_i, l_abi) in list.iter().enumerate() { + for (r_i, r_abi) in list.iter().enumerate() { + let res = check_layout_compatibility(l_abi, r_abi); if l_i == r_i { - assert_eq!(res,Ok(())); - }else{ + assert_eq!(res, Ok(())); + } else { // dbg!(l_abi.full_type(),r_abi.full_type()); - let errs=res.unwrap_err().flatten_errors(); + let errs = res.unwrap_err().flatten_errors(); - let mut had_some_err=false; + let mut had_some_err = false; for err in &*errs { match err { - AbiInstability::GenericParamCount{..}=>{ - had_some_err=true; + AbiInstability::GenericParamCount { .. } => { + had_some_err = true; } - AbiInstability::MismatchedConstParam{..}=>{ - had_some_err=true; + AbiInstability::MismatchedConstParam { .. } => { + had_some_err = true; } - _=>{} + _ => {} } } - assert!(had_some_err,"\nerrors:{:#?}\n",errs); + assert!(had_some_err, "\nerrors:{:#?}\n", errs); f(&*errs); } } } } - /// Takes too long #[test] #[cfg(not(miri))] -fn test_compatibility(){ +fn test_compatibility() { #[allow(unused_mut)] - let mut list=vec![ + let mut list = vec![ as StableAbi>::LAYOUT, as StableAbi>::LAYOUT, as StableAbi>::LAYOUT, @@ -110,59 +86,53 @@ fn test_compatibility(){ as StableAbi>::LAYOUT, as StableAbi>::LAYOUT, as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, ]; - #[cfg(feature="const_params")] + #[cfg(feature = "const_params")] { - use self::with_const_generics::{ - single_integer, - two_integer, - single_integer_one_phantom, - }; + use self::with_const_generics::{single_integer, single_integer_one_phantom, two_integer}; list.extend(vec![ as StableAbi>::LAYOUT, as StableAbi>::LAYOUT, as StableAbi>::LAYOUT, as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, ]); } - - check_imcompatible_with_others(&list,|_|()); -} - + check_imcompatible_with_others(&list, |_| ()); +} #[test] -fn test_compatibility_for_miri(){ +fn test_compatibility_for_miri() { let list = [ - as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, ]; - - check_imcompatible_with_others(&list,|_|()); + + check_imcompatible_with_others(&list, |_| ()); } diff --git a/abi_stable/tests/layout_tests/const_params/with_const_generics.rs b/abi_stable/tests/layout_tests/const_params/with_const_generics.rs index be67384f..e83a9bd6 100644 --- a/abi_stable/tests/layout_tests/const_params/with_const_generics.rs +++ b/abi_stable/tests/layout_tests/const_params/with_const_generics.rs @@ -2,27 +2,20 @@ pub(super) mod single_integer { #[repr(C)] #[derive(abi_stable::StableAbi)] // #[sabi(debug_print)] - pub struct Struct; + pub struct Struct; } pub(super) mod two_integer { #[repr(C)] #[derive(abi_stable::StableAbi)] - pub struct Struct; + pub struct Struct; } -pub(super) mod single_integer_one_phantom{ - use abi_stable::{ - const_utils::AssocStr, - marker_type::UnsafeIgnoredType, - }; - +pub(super) mod single_integer_one_phantom { + use abi_stable::{const_utils::AssocStr, marker_type::UnsafeIgnoredType}; #[repr(C)] #[derive(abi_stable::StableAbi)] - #[sabi( - bound="T:AssocStr", - phantom_const_param="T::STR", - )] - pub struct Struct(UnsafeIgnoredType); -} \ No newline at end of file + #[sabi(bound = "T:AssocStr", phantom_const_param = "T::STR")] + pub struct Struct(UnsafeIgnoredType); +} diff --git a/abi_stable/tests/layout_tests/erased_types.rs b/abi_stable/tests/layout_tests/erased_types.rs index dc60f937..d6bcd95f 100644 --- a/abi_stable/tests/layout_tests/erased_types.rs +++ b/abi_stable/tests/layout_tests/erased_types.rs @@ -1,101 +1,87 @@ #![allow(dead_code)] - - #[allow(unused_imports)] use core_extensions::matches; use abi_stable::{ - abi_stability::{ - abi_checking::{check_layout_compatibility}, - }, - StableAbi, - DynTrait, - erased_types::IteratorItem, - std_types::*, + abi_stability::abi_checking::check_layout_compatibility, erased_types::IteratorItem, + std_types::*, DynTrait, StableAbi, }; - macro_rules! mod_iter_ty { ( mod $module:ident; type Item<$lt:lifetime>=$ty:ty; - ) => ( - pub mod $module{ + ) => { + pub mod $module { use super::*; #[repr(C)] #[derive(abi_stable::StableAbi)] - #[sabi(impl_InterfaceType(Send,Sync,Iterator))] + #[sabi(impl_InterfaceType(Send, Sync, Iterator))] pub struct Interface; - impl<$lt> IteratorItem<$lt> for Interface{ - type Item=$ty; + impl<$lt> IteratorItem<$lt> for Interface { + type Item = $ty; } } - ) + }; } - - -mod no_iterator_interface{ +mod no_iterator_interface { #[repr(C)] #[derive(abi_stable::StableAbi)] - #[sabi(impl_InterfaceType(Send,Sync))] + #[sabi(impl_InterfaceType(Send, Sync))] pub struct Interface; } - -mod_iter_ty!{ +mod_iter_ty! { mod rstr_interface; type Item<'a>=RStr<'a>; } -mod_iter_ty!{ +mod_iter_ty! { mod rstring_interface; type Item<'a>=RString; } -mod_iter_ty!{ +mod_iter_ty! { mod u8_interface; type Item<'a>=u8; } -mod_iter_ty!{ +mod_iter_ty! { mod unit_interface; type Item<'a>=(); } - -type BoxTrait<'a,I>=DynTrait<'a,RBox<()>,I>; +type BoxTrait<'a, I> = DynTrait<'a, RBox<()>, I>; #[cfg(not(miri))] #[test] -fn check_subsets(){ +fn check_subsets() { + let pref_zero = , no_iterator_interface::Interface>>::LAYOUT; - let pref_zero=,no_iterator_interface::Interface>>::LAYOUT; + let pref_iter_0 = >::LAYOUT; + let pref_iter_1 = >::LAYOUT; + let pref_iter_2 = >::LAYOUT; + let pref_iter_3 = >::LAYOUT; - let pref_iter_0=>::LAYOUT; - let pref_iter_1=>::LAYOUT; - let pref_iter_2=>::LAYOUT; - let pref_iter_3=>::LAYOUT; + let prefs = vec![pref_iter_0, pref_iter_1, pref_iter_2, pref_iter_3]; - let prefs=vec![pref_iter_0,pref_iter_1,pref_iter_2,pref_iter_3]; + assert_eq!(check_layout_compatibility(pref_zero, pref_zero), Ok(())); - assert_eq!(check_layout_compatibility(pref_zero, pref_zero), Ok(()) ); - for impl_ in prefs.iter().cloned() { - - assert_eq!(check_layout_compatibility(pref_zero, impl_), Ok(()) ); + assert_eq!(check_layout_compatibility(pref_zero, impl_), Ok(())); - assert_ne!(check_layout_compatibility(impl_, pref_zero), Ok(()) ); + assert_ne!(check_layout_compatibility(impl_, pref_zero), Ok(())); } - for (interf_i,interf) in prefs.iter().cloned().enumerate() { - for (impl_i,impl_) in prefs.iter().cloned().enumerate() { - if interf_i==impl_i { - assert_eq!(check_layout_compatibility(interf, impl_), Ok(()) ); - }else{ + for (interf_i, interf) in prefs.iter().cloned().enumerate() { + for (impl_i, impl_) in prefs.iter().cloned().enumerate() { + if interf_i == impl_i { + assert_eq!(check_layout_compatibility(interf, impl_), Ok(())); + } else { assert_ne!( check_layout_compatibility(interf, impl_), Ok(()), @@ -110,11 +96,10 @@ fn check_subsets(){ #[cfg(miri)] #[test] -fn check_subsets_for_miri(){ - let pref_iter_0=>::LAYOUT; - let pref_iter_1=>::LAYOUT; +fn check_subsets_for_miri() { + let pref_iter_0 = >::LAYOUT; + let pref_iter_1 = >::LAYOUT; - assert_eq!(check_layout_compatibility(pref_iter_0, pref_iter_0), Ok(()) ); - assert_ne!(check_layout_compatibility(pref_iter_0, pref_iter_1), Ok(()) ); + assert_eq!(check_layout_compatibility(pref_iter_0, pref_iter_0), Ok(())); + assert_ne!(check_layout_compatibility(pref_iter_0, pref_iter_1), Ok(())); } - diff --git a/abi_stable/tests/layout_tests/extra_checks_combined.rs b/abi_stable/tests/layout_tests/extra_checks_combined.rs index 616db6eb..72b98763 100644 --- a/abi_stable/tests/layout_tests/extra_checks_combined.rs +++ b/abi_stable/tests/layout_tests/extra_checks_combined.rs @@ -1,58 +1,50 @@ use abi_stable::{ abi_stability::{ - abi_checking::{ - AbiInstability,CheckingGlobals, - check_layout_compatibility_with_globals, - }, + abi_checking::{check_layout_compatibility_with_globals, AbiInstability, CheckingGlobals}, extra_checks::{ - TypeCheckerMut, - ExtraChecks,ExtraChecksBox,ExtraChecksRef, - StoredExtraChecks,ExtraChecks_MV, - ForExtraChecksImplementor,ExtraChecksError, + ExtraChecks, ExtraChecksBox, ExtraChecksError, ExtraChecksRef, ExtraChecks_MV, + ForExtraChecksImplementor, StoredExtraChecks, TypeCheckerMut, }, stable_abi_trait::get_type_layout, }, const_utils::abs_sub_usize, external_types::ROnce, marker_type::UnsafeIgnoredType, - type_layout::TypeLayout, sabi_trait::prelude::TD_Opaque, - sabi_types::{Constructor,CmpIgnored}, + sabi_types::{CmpIgnored, Constructor}, std_types::*, - utils::{self,leak_value}, - GetStaticEquivalent, - StableAbi, + type_layout::TypeLayout, + utils::{self, leak_value}, + GetStaticEquivalent, StableAbi, }; use std::{ - fmt::{self,Display}, + fmt::{self, Display}, marker::PhantomData, mem::ManuallyDrop, ptr, }; -use core_extensions::{matches,SelfOps}; - +use core_extensions::{matches, SelfOps}; #[cfg(not(miri))] -fn check_subsets(list:&[&'static TypeLayout],mut f:F) +fn check_subsets(list: &[&'static TypeLayout], mut f: F) where - F:FnMut(&[AbiInstability]) + F: FnMut(&[AbiInstability]), { - let globals=CheckingGlobals::new(); - for (l_i,l_abi) in list.iter().enumerate() { - for (r_i,r_abi) in list.iter().enumerate() { - - let res=check_layout_compatibility_with_globals(l_abi,r_abi,&globals); + let globals = CheckingGlobals::new(); + for (l_i, l_abi) in list.iter().enumerate() { + for (r_i, r_abi) in list.iter().enumerate() { + let res = check_layout_compatibility_with_globals(l_abi, r_abi, &globals); if l_i <= r_i { - assert_eq!(res,Ok(()),"\n\nl_i:{} r_i:{}\n\n",l_i,r_i); - }else{ - if let Ok(_)=res { - let _=dbg!(l_i); - let _=dbg!(r_i); + assert_eq!(res, Ok(()), "\n\nl_i:{} r_i:{}\n\n", l_i, r_i); + } else { + if let Ok(_) = res { + let _ = dbg!(l_i); + let _ = dbg!(r_i); } - let errs=res.unwrap_err().flatten_errors(); + let errs = res.unwrap_err().flatten_errors(); f(&*errs); } @@ -60,104 +52,99 @@ where } } - -const LAYOUT0:&'static TypeLayout= as StableAbi>::LAYOUT; -const LAYOUT1:&'static TypeLayout= as StableAbi>::LAYOUT; -const LAYOUT1B:&'static TypeLayout= as StableAbi>::LAYOUT; -const LAYOUT2:&'static TypeLayout= as StableAbi>::LAYOUT; -const LAYOUT3:&'static TypeLayout= as StableAbi>::LAYOUT; -const LAYOUT3B:&'static TypeLayout= as StableAbi>::LAYOUT; - +const LAYOUT0: &'static TypeLayout = as StableAbi>::LAYOUT; +const LAYOUT1: &'static TypeLayout = as StableAbi>::LAYOUT; +const LAYOUT1B: &'static TypeLayout = as StableAbi>::LAYOUT; +const LAYOUT2: &'static TypeLayout = as StableAbi>::LAYOUT; +const LAYOUT3: &'static TypeLayout = as StableAbi>::LAYOUT; +const LAYOUT3B: &'static TypeLayout = as StableAbi>::LAYOUT; #[test] -fn test_subsets(){ - fn asserts(errs: &[AbiInstability]){ - assert!( - errs +fn test_subsets() { + fn asserts(errs: &[AbiInstability]) { + assert!(errs .iter() - .any(|err| matches!(err, AbiInstability::ExtraCheckError{..})) - ); + .any(|err| matches!(err, AbiInstability::ExtraCheckError { .. }))); } #[cfg(not(miri))] - check_subsets(&[LAYOUT0,LAYOUT1,LAYOUT2,LAYOUT3],asserts); - + check_subsets(&[LAYOUT0, LAYOUT1, LAYOUT2, LAYOUT3], asserts); + #[cfg(miri)] { - let globals=CheckingGlobals::new(); + let globals = CheckingGlobals::new(); + + assert_eq!( + check_layout_compatibility_with_globals(LAYOUT0, LAYOUT0, &globals), + Ok(()) + ); - assert_eq!(check_layout_compatibility_with_globals(LAYOUT0, LAYOUT0, &globals), Ok(())); - asserts( &check_layout_compatibility_with_globals(LAYOUT1, LAYOUT0, &globals) .unwrap_err() - .flatten_errors() + .flatten_errors(), ); } } #[cfg(not(miri))] #[test] -fn test_incompatible(){ +fn test_incompatible() { { - let globals=CheckingGlobals::new(); + let globals = CheckingGlobals::new(); - check_layout_compatibility_with_globals(LAYOUT0,LAYOUT1,&globals).unwrap(); - check_layout_compatibility_with_globals(LAYOUT1,LAYOUT1B,&globals).unwrap_err(); - check_layout_compatibility_with_globals(LAYOUT1B,LAYOUT1B,&globals).unwrap(); - check_layout_compatibility_with_globals(LAYOUT1,LAYOUT2,&globals).unwrap(); + check_layout_compatibility_with_globals(LAYOUT0, LAYOUT1, &globals).unwrap(); + check_layout_compatibility_with_globals(LAYOUT1, LAYOUT1B, &globals).unwrap_err(); + check_layout_compatibility_with_globals(LAYOUT1B, LAYOUT1B, &globals).unwrap(); + check_layout_compatibility_with_globals(LAYOUT1, LAYOUT2, &globals).unwrap(); } { - let globals=CheckingGlobals::new(); + let globals = CheckingGlobals::new(); - check_layout_compatibility_with_globals(LAYOUT1,LAYOUT2,&globals).unwrap(); - check_layout_compatibility_with_globals(LAYOUT0,LAYOUT1,&globals).unwrap(); + check_layout_compatibility_with_globals(LAYOUT1, LAYOUT2, &globals).unwrap(); + check_layout_compatibility_with_globals(LAYOUT0, LAYOUT1, &globals).unwrap(); } { - let globals=CheckingGlobals::new(); + let globals = CheckingGlobals::new(); - check_layout_compatibility_with_globals(LAYOUT0,LAYOUT1B,&globals).unwrap(); - check_layout_compatibility_with_globals(LAYOUT1,LAYOUT2,&globals).unwrap(); - check_layout_compatibility_with_globals(LAYOUT0,LAYOUT2,&globals).unwrap_err(); + check_layout_compatibility_with_globals(LAYOUT0, LAYOUT1B, &globals).unwrap(); + check_layout_compatibility_with_globals(LAYOUT1, LAYOUT2, &globals).unwrap(); + check_layout_compatibility_with_globals(LAYOUT0, LAYOUT2, &globals).unwrap_err(); } { - let globals=CheckingGlobals::new(); + let globals = CheckingGlobals::new(); - check_layout_compatibility_with_globals(LAYOUT0,LAYOUT3,&globals).unwrap(); - check_layout_compatibility_with_globals(LAYOUT0,LAYOUT3B,&globals).unwrap_err(); + check_layout_compatibility_with_globals(LAYOUT0, LAYOUT3, &globals).unwrap(); + check_layout_compatibility_with_globals(LAYOUT0, LAYOUT3B, &globals).unwrap_err(); - check_layout_compatibility_with_globals(LAYOUT1,LAYOUT3B,&globals).unwrap(); - check_layout_compatibility_with_globals(LAYOUT1,LAYOUT3,&globals).unwrap_err(); + check_layout_compatibility_with_globals(LAYOUT1, LAYOUT3B, &globals).unwrap(); + check_layout_compatibility_with_globals(LAYOUT1, LAYOUT3, &globals).unwrap_err(); - check_layout_compatibility_with_globals(LAYOUT2,LAYOUT3,&globals).unwrap(); - check_layout_compatibility_with_globals(LAYOUT3,LAYOUT3B,&globals).unwrap_err(); - - check_layout_compatibility_with_globals(LAYOUT0,LAYOUT1,&globals).unwrap_err(); - check_layout_compatibility_with_globals(LAYOUT1,LAYOUT2,&globals).unwrap_err(); + check_layout_compatibility_with_globals(LAYOUT2, LAYOUT3, &globals).unwrap(); + check_layout_compatibility_with_globals(LAYOUT3, LAYOUT3B, &globals).unwrap_err(); - check_layout_compatibility_with_globals(LAYOUT0,LAYOUT0,&globals).unwrap(); - check_layout_compatibility_with_globals(LAYOUT1,LAYOUT1,&globals).unwrap(); - check_layout_compatibility_with_globals(LAYOUT2,LAYOUT2,&globals).unwrap(); - check_layout_compatibility_with_globals(LAYOUT3,LAYOUT3,&globals).unwrap(); - check_layout_compatibility_with_globals(LAYOUT3B,LAYOUT3B,&globals).unwrap(); - + check_layout_compatibility_with_globals(LAYOUT0, LAYOUT1, &globals).unwrap_err(); + check_layout_compatibility_with_globals(LAYOUT1, LAYOUT2, &globals).unwrap_err(); + check_layout_compatibility_with_globals(LAYOUT0, LAYOUT0, &globals).unwrap(); + check_layout_compatibility_with_globals(LAYOUT1, LAYOUT1, &globals).unwrap(); + check_layout_compatibility_with_globals(LAYOUT2, LAYOUT2, &globals).unwrap(); + check_layout_compatibility_with_globals(LAYOUT3, LAYOUT3, &globals).unwrap(); + check_layout_compatibility_with_globals(LAYOUT3B, LAYOUT3B, &globals).unwrap(); } } - #[cfg(miri)] #[test] -fn test_incompatible(){ - let globals=CheckingGlobals::new(); +fn test_incompatible() { + let globals = CheckingGlobals::new(); - check_layout_compatibility_with_globals(LAYOUT0,LAYOUT1,&globals).unwrap(); - check_layout_compatibility_with_globals(LAYOUT1,LAYOUT1B,&globals).unwrap_err(); + check_layout_compatibility_with_globals(LAYOUT0, LAYOUT1, &globals).unwrap(); + check_layout_compatibility_with_globals(LAYOUT1, LAYOUT1B, &globals).unwrap_err(); } ////////////////////////////////////////////////////////////////////////////////// - #[repr(C)] #[derive(abi_stable::StableAbi)] #[sabi( @@ -167,25 +154,23 @@ fn test_incompatible(){ bound="C:GetConstant", extra_checks="Self::CHECKER" )] -struct WithConstant{ +struct WithConstant { // UnsafeIgnoredType is equivalent to PhantomData, // except that all `UnsafeIgnoredType` are considered the same type by `StableAbi`. - _marker:UnsafeIgnoredType, + _marker: UnsafeIgnoredType, } impl WithConstant -where - C:GetConstant +where + C: GetConstant, { - const CHECKER:ConstChecker= - ConstChecker{ - chars:RStr::from_str(C::CHARS) - }; + const CHECKER: ConstChecker = ConstChecker { + chars: RStr::from_str(C::CHARS), + }; } - -trait GetConstant{ - const CHARS:&'static str; +trait GetConstant { + const CHARS: &'static str; } macro_rules! declare_consts { @@ -203,7 +188,7 @@ macro_rules! declare_consts { ) } -declare_consts!{ +declare_consts! { const V1_0="ab"; const V1_1="abc"; const V1_1_Incompatible="abd"; @@ -212,19 +197,16 @@ declare_consts!{ const V1_3_Incompatible="abcdf"; } - - ///////////////////////////////////////// #[repr(C)] -#[derive(Debug,Clone,StableAbi)] -pub struct ConstChecker{ - chars:RStr<'static>, +#[derive(Debug, Clone, StableAbi)] +pub struct ConstChecker { + chars: RStr<'static>, } - -impl Display for ConstChecker{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ +impl Display for ConstChecker { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { writeln!( f, "ConstChecker: \ @@ -236,62 +218,59 @@ impl Display for ConstChecker{ } } - impl ConstChecker { - fn check_compatible_inner(&self,other:&ConstChecker)->Result<(), UnequalConstError> { + fn check_compatible_inner(&self, other: &ConstChecker) -> Result<(), UnequalConstError> { if other.chars.starts_with(&*self.chars) { Ok(()) - }else{ - Err(UnequalConstError{ - expected:self.chars, - found:other.chars, + } else { + Err(UnequalConstError { + expected: self.chars, + found: other.chars, }) } } } unsafe impl ExtraChecks for ConstChecker { - fn type_layout(&self)->&'static TypeLayout{ + fn type_layout(&self) -> &'static TypeLayout { ::LAYOUT } fn check_compatibility( &self, - _layout_containing_self:&'static TypeLayout, - layout_containing_other:&'static TypeLayout, - checker:TypeCheckerMut<'_>, - )->RResult<(), ExtraChecksError> { - Self::downcast_with_layout(layout_containing_other,checker,|other,_|{ + _layout_containing_self: &'static TypeLayout, + layout_containing_other: &'static TypeLayout, + checker: TypeCheckerMut<'_>, + ) -> RResult<(), ExtraChecksError> { + Self::downcast_with_layout(layout_containing_other, checker, |other, _| { self.check_compatible_inner(other) }) } - fn nested_type_layouts(&self)->RCow<'_,[&'static TypeLayout]>{ + fn nested_type_layouts(&self) -> RCow<'_, [&'static TypeLayout]> { RCow::from_slice(&[]) } fn combine( &self, - other:ExtraChecksRef<'_>, - checker:TypeCheckerMut<'_> - )->RResult, ExtraChecksError>{ - Self::downcast_with_object(other,checker,|other,_|{ - let (min,max)=utils::min_max_by(self,other,|x|x.chars.len()); + other: ExtraChecksRef<'_>, + checker: TypeCheckerMut<'_>, + ) -> RResult, ExtraChecksError> { + Self::downcast_with_object(other, checker, |other, _| { + let (min, max) = utils::min_max_by(self, other, |x| x.chars.len()); min.check_compatible_inner(max) - .map(|_| RSome( ExtraChecksBox::from_value(max.clone(),TD_Opaque) ) ) + .map(|_| RSome(ExtraChecksBox::from_value(max.clone(), TD_Opaque))) }) } } - - -#[derive(Debug,Clone)] -pub struct UnequalConstError{ - expected:RStr<'static>, - found:RStr<'static>, +#[derive(Debug, Clone)] +pub struct UnequalConstError { + expected: RStr<'static>, + found: RStr<'static>, } -impl Display for UnequalConstError{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ +impl Display for UnequalConstError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { writeln!( f, "Expected the `GetConstant::CHARS` associated constant to be compatible with:\ @@ -299,101 +278,101 @@ impl Display for UnequalConstError{ \nFound:\ \n {}\ ", - self.expected, - self.found, + self.expected, self.found, ) } } -impl std::error::Error for UnequalConstError{} +impl std::error::Error for UnequalConstError {} ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// - /// This is used to check that type checking within ExtraChecks works as expected. #[repr(C)] -#[derive(Debug,Clone,StableAbi)] -pub struct IdentityChecker{ - type_layout:Constructor<&'static TypeLayout>, +#[derive(Debug, Clone, StableAbi)] +pub struct IdentityChecker { + type_layout: Constructor<&'static TypeLayout>, } -impl Display for IdentityChecker{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Display::fmt(&self.type_layout,f) +impl Display for IdentityChecker { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Display::fmt(&self.type_layout, f) } } - unsafe impl ExtraChecks for IdentityChecker { - fn type_layout(&self)->&'static TypeLayout{ + fn type_layout(&self) -> &'static TypeLayout { ::LAYOUT } fn check_compatibility( &self, - _layout_containing_self:&'static TypeLayout, - layout_containing_other:&'static TypeLayout, - ty_checker:TypeCheckerMut<'_>, - )->RResult<(), ExtraChecksError> { - Self::downcast_with_layout(layout_containing_other,ty_checker,|other,mut ty_checker|{ - let t_lay=self.type_layout.get(); - let o_lay=other.type_layout.get(); - ty_checker.check_compatibility(t_lay,o_lay).into_result() - }).observe(|res|{ + _layout_containing_self: &'static TypeLayout, + layout_containing_other: &'static TypeLayout, + ty_checker: TypeCheckerMut<'_>, + ) -> RResult<(), ExtraChecksError> { + Self::downcast_with_layout( + layout_containing_other, + ty_checker, + |other, mut ty_checker| { + let t_lay = self.type_layout.get(); + let o_lay = other.type_layout.get(); + ty_checker.check_compatibility(t_lay, o_lay).into_result() + }, + ) + .observe(|res| { assert!( - matches!(res, ROk(_)|RErr(ExtraChecksError::TypeChecker)), + matches!(res, ROk(_) | RErr(ExtraChecksError::TypeChecker)), "It isn't either ROk or an RErr(TypeChecker):\n{:?}", res ) }) } - fn nested_type_layouts(&self)->RCow<'_,[&'static TypeLayout]>{ + fn nested_type_layouts(&self) -> RCow<'_, [&'static TypeLayout]> { vec![self.type_layout.get()].into() } } - #[repr(transparent)] #[derive(abi_stable::StableAbi)] struct Blah(T); - struct WrapTypeLayout(T); impl WrapTypeLayout where - T:StableAbi + T: StableAbi, { - const EXTRA_CHECKS:&'static ManuallyDrop= + const EXTRA_CHECKS: &'static ManuallyDrop = &ManuallyDrop::new(StoredExtraChecks::from_const( - &IdentityChecker{ - type_layout:Constructor(get_type_layout::) + &IdentityChecker { + type_layout: Constructor(get_type_layout::), }, TD_Opaque, ExtraChecks_MV::VTABLE, )); } -fn wrap_type_layout()->&'static TypeLayout +fn wrap_type_layout() -> &'static TypeLayout where - T:StableAbi + T: StableAbi, { - <()>::LAYOUT.clone() + <()>::LAYOUT + .clone() ._set_extra_checks( WrapTypeLayout::::EXTRA_CHECKS - .piped(Some) - .piped(CmpIgnored::new) + .piped(Some) + .piped(CmpIgnored::new), ) ._set_type_id(Constructor( - abi_stable::std_types::utypeid::new_utypeid::> + abi_stable::std_types::utypeid::new_utypeid::>, )) .piped(leak_value) } - #[cfg(not(miri))] #[test] fn test_identity_extra_checker() { @@ -413,10 +392,10 @@ fn test_identity_extra_checker() { wrap_type_layout::<&'static &'static mut ()>(), wrap_type_layout::>(), wrap_type_layout::>(), - wrap_type_layout::>(), - wrap_type_layout::>(), - wrap_type_layout::>(), - wrap_type_layout::>(), + wrap_type_layout::>(), + wrap_type_layout::>(), + wrap_type_layout::>(), + wrap_type_layout::>(), wrap_type_layout::>(), wrap_type_layout::>(), wrap_type_layout::>(), @@ -435,12 +414,12 @@ fn test_identity_extra_checker() { wrap_type_layout::(), ]; - let globals=CheckingGlobals::new(); + let globals = CheckingGlobals::new(); { for (i, this) in list.iter().cloned().enumerate() { for (j, other) in list.iter().cloned().enumerate() { - let res=check_layout_compatibility_with_globals(this, other, &globals); + let res = check_layout_compatibility_with_globals(this, other, &globals); if i == j { assert_eq!(res, Ok(())); @@ -453,15 +432,13 @@ fn test_identity_extra_checker() { other, ); - let found_extra_checks_error=res + let found_extra_checks_error = res .unwrap_err() .flatten_errors() .into_iter() - .any(|err| matches!(err, AbiInstability::ExtraCheckError{..}) ); + .any(|err| matches!(err, AbiInstability::ExtraCheckError { .. })); assert!(!found_extra_checks_error); - - } } } @@ -471,159 +448,154 @@ fn test_identity_extra_checker() { #[cfg(miri)] #[test] fn test_identity_extra_checker() { - let globals=CheckingGlobals::new(); - - let interf0=wrap_type_layout::>(); - let interf1=wrap_type_layout::(); - - assert_eq!(check_layout_compatibility_with_globals(interf0, interf0, &globals), Ok(())); - assert_ne!(check_layout_compatibility_with_globals(interf0, interf1, &globals), Ok(())); + let globals = CheckingGlobals::new(); + + let interf0 = wrap_type_layout::>(); + let interf1 = wrap_type_layout::(); + + assert_eq!( + check_layout_compatibility_with_globals(interf0, interf0, &globals), + Ok(()) + ); + assert_ne!( + check_layout_compatibility_with_globals(interf0, interf1, &globals), + Ok(()) + ); } - ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// - #[repr(C)] #[derive(abi_stable::StableAbi)] -#[sabi(extra_checks="Self::NEW")] +#[sabi(extra_checks = "Self::NEW")] struct WithCyclicExtraChecker; impl WithCyclicExtraChecker { - const NEW:IdentityChecker= - IdentityChecker{ type_layout:Constructor(get_type_layout::) }; + const NEW: IdentityChecker = IdentityChecker { + type_layout: Constructor(get_type_layout::), + }; } - -/// This is used to check that ExtraChecks that contain the type that they are checking +/// This is used to check that ExtraChecks that contain the type that they are checking /// alway return an error. #[test] fn test_cyclic_extra_checker() { - let layout = ::LAYOUT; - let globals=CheckingGlobals::new(); + let globals = CheckingGlobals::new(); - let res=check_layout_compatibility_with_globals(layout, layout, &globals); + let res = check_layout_compatibility_with_globals(layout, layout, &globals); - assert_ne!(res,Ok(()),"layout:{:#?}",layout); + assert_ne!(res, Ok(()), "layout:{:#?}", layout); - let found_extra_checks_error=res + let found_extra_checks_error = res .unwrap_err() .flatten_errors() .into_iter() - .any(|err| matches!(err, AbiInstability::CyclicTypeChecking{..}) ); + .any(|err| matches!(err, AbiInstability::CyclicTypeChecking { .. })); assert!(found_extra_checks_error); } - ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// - - #[repr(C)] #[derive(abi_stable::StableAbi)] -#[sabi(extra_checks="Self::EXTRA_CHECKER")] -struct WithLocalExtraChecker{ - _marker:UnsafeIgnoredType<(C0,C1)> +#[sabi(extra_checks = "Self::EXTRA_CHECKER")] +struct WithLocalExtraChecker { + _marker: UnsafeIgnoredType<(C0, C1)>, } -impl WithLocalExtraChecker +impl WithLocalExtraChecker where - C0:StableAbi, - C1:StableAbi, + C0: StableAbi, + C1: StableAbi, { - const EXTRA_CHECKER:LocalExtraChecker= - LocalExtraChecker{ - comp0:::LAYOUT, - comp1:::LAYOUT, - }; + const EXTRA_CHECKER: LocalExtraChecker = LocalExtraChecker { + comp0: ::LAYOUT, + comp1: ::LAYOUT, + }; } - #[repr(C)] -#[derive(Debug,Clone,StableAbi)] -pub struct LocalExtraChecker{ - comp0:&'static TypeLayout, - comp1:&'static TypeLayout, +#[derive(Debug, Clone, StableAbi)] +pub struct LocalExtraChecker { + comp0: &'static TypeLayout, + comp1: &'static TypeLayout, } -impl Display for LocalExtraChecker{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ +impl Display for LocalExtraChecker { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { writeln!( f, "\ncomp0 type_layout:\n{}\ncomp1 type_layout:\n{}\n", - self.comp0, - self.comp1, + self.comp0, self.comp1, ) } } - unsafe impl ExtraChecks for LocalExtraChecker { - fn type_layout(&self)->&'static TypeLayout{ + fn type_layout(&self) -> &'static TypeLayout { ::LAYOUT } fn check_compatibility( &self, - _layout_containing_self:&'static TypeLayout, - layout_containing_other:&'static TypeLayout, - ty_checker:TypeCheckerMut<'_>, - )->RResult<(), ExtraChecksError> { - Self::downcast_with_layout(layout_containing_other,ty_checker,|other,mut ty_checker|{ - ty_checker.local_check_compatibility(self.comp0,other.comp0) - .or_else(|_| ty_checker.local_check_compatibility(self.comp0,other.comp1) ) - .or_else(|_| ty_checker.local_check_compatibility(self.comp1,other.comp0) ) - .or_else(|_| ty_checker.local_check_compatibility(self.comp1,other.comp1) ) - .into_result() - }) + _layout_containing_self: &'static TypeLayout, + layout_containing_other: &'static TypeLayout, + ty_checker: TypeCheckerMut<'_>, + ) -> RResult<(), ExtraChecksError> { + Self::downcast_with_layout( + layout_containing_other, + ty_checker, + |other, mut ty_checker| { + ty_checker + .local_check_compatibility(self.comp0, other.comp0) + .or_else(|_| ty_checker.local_check_compatibility(self.comp0, other.comp1)) + .or_else(|_| ty_checker.local_check_compatibility(self.comp1, other.comp0)) + .or_else(|_| ty_checker.local_check_compatibility(self.comp1, other.comp1)) + .into_result() + }, + ) } - fn nested_type_layouts(&self)->RCow<'_,[&'static TypeLayout]>{ - vec![self.comp0,self.comp1].into() + fn nested_type_layouts(&self) -> RCow<'_, [&'static TypeLayout]> { + vec![self.comp0, self.comp1].into() } } - - - -/// This is used to check that ExtraChecks that contain the type that they are checking +/// This is used to check that ExtraChecks that contain the type that they are checking /// alway return an error. #[cfg(not(miri))] #[test] fn test_local_extra_checker() { - - use abi_stable::{ - external_types::ROnce, - }; + use abi_stable::external_types::ROnce; let list = vec![ - WithLocalExtraChecker::::LAYOUT, - WithLocalExtraChecker::::LAYOUT, - WithLocalExtraChecker::<(),RString>::LAYOUT, - WithLocalExtraChecker::,()>::LAYOUT, - WithLocalExtraChecker::>::LAYOUT, + WithLocalExtraChecker::::LAYOUT, + WithLocalExtraChecker::::LAYOUT, + WithLocalExtraChecker::<(), RString>::LAYOUT, + WithLocalExtraChecker::, ()>::LAYOUT, + WithLocalExtraChecker::>::LAYOUT, ]; - let globals=CheckingGlobals::new(); + let globals = CheckingGlobals::new(); for window in list.windows(2) { - let res=check_layout_compatibility_with_globals(window[0], window[1], &globals); - assert_eq!(res,Ok(())); + let res = check_layout_compatibility_with_globals(window[0], window[1], &globals); + assert_eq!(res, Ok(())); } for (i, this) in list.iter().cloned().enumerate() { for (j, other) in list.iter().cloned().enumerate() { - let res=check_layout_compatibility_with_globals(this, other, &globals); + let res = check_layout_compatibility_with_globals(this, other, &globals); - if abs_sub_usize(j,i)<=1 { - assert_eq!(res, Ok(()), "j:{} i:{}",j,i); + if abs_sub_usize(j, i) <= 1 { + assert_eq!(res, Ok(()), "j:{} i:{}", j, i); } else { assert_ne!( res, @@ -633,18 +605,18 @@ fn test_local_extra_checker() { other, ); - let mut found_extra_checks_error=false; - let mut found_name_error=false; + let mut found_extra_checks_error = false; + let mut found_name_error = false; for err in res.unwrap_err().flatten_errors().into_iter() { match err { - AbiInstability::ExtraCheckError{..}=>found_extra_checks_error=true, - AbiInstability::Name{..}=>found_name_error=true, - _=>{} + AbiInstability::ExtraCheckError { .. } => found_extra_checks_error = true, + AbiInstability::Name { .. } => found_name_error = true, + _ => {} } } assert!( - !found_extra_checks_error&&found_name_error, + !found_extra_checks_error && found_name_error, "\n\nInterface:{:#?}\n\nimplementation:{:#?}", this, other, @@ -657,18 +629,18 @@ fn test_local_extra_checker() { #[cfg(miri)] #[test] fn test_local_extra_checker() { - let globals=CheckingGlobals::new(); - - let interf0=WithLocalExtraChecker::::LAYOUT; - let interf1=WithLocalExtraChecker::::LAYOUT; - let interf2=WithLocalExtraChecker::<(),RString>::LAYOUT; - - assert_eq!(check_layout_compatibility_with_globals(interf0, interf1, &globals), Ok(())); - assert_ne!(check_layout_compatibility_with_globals(interf0, interf2, &globals), Ok(())); + let globals = CheckingGlobals::new(); + + let interf0 = WithLocalExtraChecker::::LAYOUT; + let interf1 = WithLocalExtraChecker::::LAYOUT; + let interf2 = WithLocalExtraChecker::<(), RString>::LAYOUT; + + assert_eq!( + check_layout_compatibility_with_globals(interf0, interf1, &globals), + Ok(()) + ); + assert_ne!( + check_layout_compatibility_with_globals(interf0, interf2, &globals), + Ok(()) + ); } - - - - - - diff --git a/abi_stable/tests/layout_tests/get_static_equivalent.rs b/abi_stable/tests/layout_tests/get_static_equivalent.rs index db5445cd..3b3c24ce 100644 --- a/abi_stable/tests/layout_tests/get_static_equivalent.rs +++ b/abi_stable/tests/layout_tests/get_static_equivalent.rs @@ -1,116 +1,105 @@ use abi_stable::{ abi_stability::{ - abi_checking::{check_layout_compatibility}, - get_static_equivalent::{GetStaticEquivalent_,Unsized}, + abi_checking::check_layout_compatibility, + get_static_equivalent::{GetStaticEquivalent_, Unsized}, }, - std_types::{RStr,RVec}, + std_types::{RStr, RVec}, type_layout::TypeLayout, StableAbi, }; - - -mod unit_type{ +mod unit_type { use abi_stable::GetStaticEquivalent; - + #[derive(GetStaticEquivalent)] pub(super) struct Struct; - impl super::UniqueId for Struct{ - const UID:i64= -4_000_000; + impl super::UniqueId for Struct { + const UID: i64 = -4_000_000; } } - -mod single_ty_param{ +mod single_ty_param { use abi_stable::GetStaticEquivalent; - + #[derive(GetStaticEquivalent)] pub(super) struct Struct(T); impl super::UniqueId for Struct where - T:super::UniqueId + T: super::UniqueId, { - const UID:i64=4_000_000_000_000i64+T::UID; + const UID: i64 = 4_000_000_000_000i64 + T::UID; } } - -mod single_lt_param{ +mod single_lt_param { use abi_stable::GetStaticEquivalent; - + #[derive(GetStaticEquivalent)] pub(super) struct Struct<'a>(&'a ()); - impl super::UniqueId for Struct<'_>{ - const UID:i64= -1_000_000; + impl super::UniqueId for Struct<'_> { + const UID: i64 = -1_000_000; } } - -mod single_lt_ty_param{ +mod single_lt_ty_param { use abi_stable::GetStaticEquivalent; - + #[derive(GetStaticEquivalent)] - pub(super) struct Struct<'a,T>(&'a (),T); + pub(super) struct Struct<'a, T>(&'a (), T); - impl super::UniqueId for Struct<'_,T> + impl super::UniqueId for Struct<'_, T> where - T:super::UniqueId + T: super::UniqueId, { - const UID:i64=1_000_000_000_000i64+T::UID; + const UID: i64 = 1_000_000_000_000i64 + T::UID; } } - - -mod sabi_with_0_ty_params{ +mod sabi_with_0_ty_params { use abi_stable::StableAbi; - + #[repr(C)] #[derive(StableAbi)] pub(super) struct Struct; } #[cfg(not(feature = "no_fn_promotion"))] -mod sabi_with_1_ty_params{ - use abi_stable::{StableAbi,marker_type::UnsafeIgnoredType,tag}; +mod sabi_with_1_ty_params { use super::UniqueId; - + use abi_stable::{marker_type::UnsafeIgnoredType, tag, StableAbi}; + #[repr(C)] #[derive(StableAbi)] - #[sabi( - not_stableabi(T), - bound="T:UniqueId", - tag=" tag!{ T::UID } " - )] - pub(super) struct Struct{ - _inner:UnsafeIgnoredType, + #[sabi(not_stableabi(T), bound = "T:UniqueId", tag = " tag!{ T::UID } ")] + pub(super) struct Struct { + _inner: UnsafeIgnoredType, } } #[cfg(not(feature = "no_fn_promotion"))] -mod sabi_with_2_ty_params{ - use abi_stable::{StableAbi,marker_type::UnsafeIgnoredType,tag}; +mod sabi_with_2_ty_params { use super::UniqueId; - + use abi_stable::{marker_type::UnsafeIgnoredType, tag, StableAbi}; + #[repr(C)] #[derive(StableAbi)] #[sabi( not_stableabi(T), not_stableabi(U), - bound="T:UniqueId", - bound="U:UniqueId", - tag=" tag![[ tag!(T::UID) , tag!(U::UID) ]] " + bound = "T:UniqueId", + bound = "U:UniqueId", + tag = " tag![[ tag!(T::UID) , tag!(U::UID) ]] " )] - pub(super) struct Struct{ - _inner:UnsafeIgnoredType<(T,U)>, + pub(super) struct Struct { + _inner: UnsafeIgnoredType<(T, U)>, } } -trait UniqueId{ - const UID:i64; +trait UniqueId { + const UID: i64; } macro_rules! declare_uids { @@ -123,7 +112,7 @@ macro_rules! declare_uids { ) } -declare_uids!{ +declare_uids! { ( &'a Unsized , 1 ) ( &'a Unsized<[u8]>, 3 ) ( (), 7 ) @@ -132,70 +121,69 @@ declare_uids!{ ( RStr<'a>, 64 ) } - #[cfg(not(miri))] -fn type_layout_of()->&'static TypeLayout +fn type_layout_of() -> &'static TypeLayout where - T:StableAbi + T: StableAbi, { ::LAYOUT } - #[cfg(not(feature = "no_fn_promotion"))] #[cfg(not(miri))] -fn get_list_inner()->Vec<&'static TypeLayout> +fn get_list_inner() -> Vec<&'static TypeLayout> where - T:GetStaticEquivalent_+UniqueId, - U:GetStaticEquivalent_+UniqueId, + T: GetStaticEquivalent_ + UniqueId, + U: GetStaticEquivalent_ + UniqueId, { vec![ - type_layout_of::< sabi_with_1_ty_params::Struct >(), - type_layout_of::< sabi_with_2_ty_params::Struct >(), + type_layout_of::>(), + type_layout_of::>(), ] } #[cfg(not(feature = "no_fn_promotion"))] #[cfg(not(miri))] -fn get_list<'a,T>(_:&'a T)->Vec<&'static TypeLayout>{ - type Ty0=unit_type::Struct; - type Ty1<'a>=single_ty_param::Struct<&'a Unsized>; - type Ty2<'a>=single_lt_param::Struct<'a>; - type Ty3<'a>=single_lt_ty_param::Struct<'a,&'a Unsized<[u8]>>; - type Ty4=single_ty_param::Struct<()>; - type Ty5=single_ty_param::Struct; - type Ty6=single_ty_param::Struct>; - type Ty7<'a>=single_ty_param::Struct>; +fn get_list<'a, T>(_: &'a T) -> Vec<&'static TypeLayout> { + type Ty0 = unit_type::Struct; + type Ty1<'a> = single_ty_param::Struct<&'a Unsized>; + type Ty2<'a> = single_lt_param::Struct<'a>; + type Ty3<'a> = single_lt_ty_param::Struct<'a, &'a Unsized<[u8]>>; + type Ty4 = single_ty_param::Struct<()>; + type Ty5 = single_ty_param::Struct; + type Ty6 = single_ty_param::Struct>; + type Ty7<'a> = single_ty_param::Struct>; vec![ - vec![ - type_layout_of::< sabi_with_0_ty_params::Struct >(), - ], - get_list_inner::< Ty0,Ty1<'a> >(), - get_list_inner::< Ty1<'a>,Ty2<'a> >(), - get_list_inner::< Ty2<'a>,Ty3<'a> >(), - get_list_inner::< Ty3<'a>,Ty4 >(), - get_list_inner::< Ty4,Ty5 >(), - get_list_inner::< Ty5,Ty6 >(), - get_list_inner::< Ty6,Ty7<'a> >(), - get_list_inner::< Ty7<'a>,Ty7<'a> >(), - ].into_iter().flatten().collect() + vec![type_layout_of::()], + get_list_inner::>(), + get_list_inner::, Ty2<'a>>(), + get_list_inner::, Ty3<'a>>(), + get_list_inner::, Ty4>(), + get_list_inner::(), + get_list_inner::(), + get_list_inner::>(), + get_list_inner::, Ty7<'a>>(), + ] + .into_iter() + .flatten() + .collect() } #[cfg(not(feature = "no_fn_promotion"))] #[cfg(not(miri))] #[test] -fn check_not_stableabi(){ - let hello=Vec::::new(); +fn check_not_stableabi() { + let hello = Vec::::new(); - let list=get_list(&hello); + let list = get_list(&hello); - for (interf_i,interf) in list.iter().cloned().enumerate() { - for (impl_i,impl_) in list.iter().cloned().enumerate() { - let res=check_layout_compatibility(interf, impl_); - if interf_i==impl_i { - assert_eq!(res, Ok(()) ); - }else{ + for (interf_i, interf) in list.iter().cloned().enumerate() { + for (impl_i, impl_) in list.iter().cloned().enumerate() { + let res = check_layout_compatibility(interf, impl_); + if interf_i == impl_i { + assert_eq!(res, Ok(())); + } else { assert_ne!( res, Ok(()), @@ -208,4 +196,4 @@ fn check_not_stableabi(){ } } } -} \ No newline at end of file +} diff --git a/abi_stable/tests/layout_tests/get_type_layout.rs b/abi_stable/tests/layout_tests/get_type_layout.rs index 2b9746a5..9f337e53 100644 --- a/abi_stable/tests/layout_tests/get_type_layout.rs +++ b/abi_stable/tests/layout_tests/get_type_layout.rs @@ -1,20 +1,15 @@ - use std::marker::PhantomData; #[allow(unused_imports)] use core_extensions::SelfOps; #[allow(unused_imports)] -use abi_stable::std_types::{Tuple1,Tuple2,Tuple3,Tuple4}; +use abi_stable::std_types::{Tuple1, Tuple2, Tuple3, Tuple4}; use abi_stable::{ abi_stability::{ - stable_abi_trait::{ - TypeLayoutCtor, - GetTypeLayoutCtor, - get_type_layout, - }, check_layout_compatibility, + stable_abi_trait::{get_type_layout, GetTypeLayoutCtor, TypeLayoutCtor}, }, std_types::*, type_layout::TypeLayout, @@ -22,178 +17,177 @@ use abi_stable::{ }; use super::shared_types::{ - basic_enum, - gen_basic, - enum_extra_fields_b, - extra_variant, + basic_enum, enum_extra_fields_b, extra_variant, gen_basic, gen_more_lts_b, mod_5, mod_7, swapped_fields_first, - gen_more_lts_b, - mod_5, - mod_7, }; //////////////////////////////////////////////////////////////////////////////// - - /// This is to test that function pointers with 5 or more parameters /// store the TypeLayoutCtor for the remaining parameters after the 5th one. pub(super) mod many_params { use super::RString; #[repr(C)] #[derive(abi_stable::StableAbi)] - pub struct Mod{ - pub function_0: extern "C" fn()->RString, - pub function_1: extern "C" fn(&mut u32,u64,RString,i8,u32,i64), - pub function_2: extern "C" fn((),i64,(),(),()), - pub function_3: extern "C" fn(u32,u64,i8,RString)->&'static mut u32, - pub function_4: extern "C" fn((),(),(),(),(),()), + pub struct Mod { + pub function_0: extern "C" fn() -> RString, + pub function_1: extern "C" fn(&mut u32, u64, RString, i8, u32, i64), + pub function_2: extern "C" fn((), i64, (), (), ()), + pub function_3: extern "C" fn(u32, u64, i8, RString) -> &'static mut u32, + pub function_4: extern "C" fn((), (), (), (), (), ()), } } - //////////////////////////////////////////////////////////////////////////////// -struct FnTest{ - params:Vec, - ret:usize, +struct FnTest { + params: Vec, + ret: usize, } -struct TypeTest{ - layout:&'static TypeLayout, - vars_types:Vec, - field_types:Vec, - functions:Vec>, +struct TypeTest { + layout: &'static TypeLayout, + vars_types: Vec, + field_types: Vec, + functions: Vec>, } #[cfg(not(miri))] -fn get_tlc()->TypeLayoutCtor +fn get_tlc() -> TypeLayoutCtor where - T:StableAbi + T: StableAbi, { GetTypeLayoutCtor::::STABLE_ABI } #[cfg(not(miri))] #[test] -fn assert_types(){ - let list=vec![ - TypeTest{ - layout:get_type_layout::>(), - vars_types:vec![get_tlc::()], - field_types:vec![0], - functions:vec![vec![]], +fn assert_types() { + let list = vec![ + TypeTest { + layout: get_type_layout::>(), + vars_types: vec![get_tlc::()], + field_types: vec![0], + functions: vec![vec![]], }, - - TypeTest{ - layout:get_type_layout::>(), - vars_types:vec![get_tlc::(), get_tlc::()], - field_types:vec![0,1], - functions:vec![vec![]], + TypeTest { + layout: get_type_layout::>(), + vars_types: vec![get_tlc::(), get_tlc::()], + field_types: vec![0, 1], + functions: vec![vec![]], }, - TypeTest{ - layout:get_type_layout::>>(), - vars_types:vec![get_tlc::(), get_tlc::>()], - field_types:vec![0,1], - functions:vec![vec![]], + TypeTest { + layout: get_type_layout::>>(), + vars_types: vec![get_tlc::(), get_tlc::>()], + field_types: vec![0, 1], + functions: vec![vec![]], }, - - TypeTest{ - layout:get_type_layout::>(), - vars_types:vec![ get_tlc::(), get_tlc::(), get_tlc::() ], - field_types:vec![0,1,2], - functions:vec![vec![]], + TypeTest { + layout: get_type_layout::>(), + vars_types: vec![get_tlc::(), get_tlc::(), get_tlc::()], + field_types: vec![0, 1, 2], + functions: vec![vec![]], }, - TypeTest{ - layout:get_type_layout::>(), - vars_types:vec![ get_tlc::(), get_tlc::(), get_tlc::() ], - field_types:vec![0,1,2], - functions:vec![vec![]], + TypeTest { + layout: get_type_layout::>(), + vars_types: vec![get_tlc::(), get_tlc::(), get_tlc::()], + field_types: vec![0, 1, 2], + functions: vec![vec![]], }, - - TypeTest{ - layout:get_type_layout::>(), - vars_types:vec![ get_tlc::<&i32>(), get_tlc::>() ], - field_types:vec![0,0,1], - functions:vec![vec![]], + TypeTest { + layout: get_type_layout::>(), + vars_types: vec![get_tlc::<&i32>(), get_tlc::>()], + field_types: vec![0, 0, 1], + functions: vec![vec![]], }, - TypeTest{ - layout:get_type_layout::>(), - vars_types:vec![ get_tlc::<&RString>(), get_tlc::>() ], - field_types:vec![0,0,1], - functions:vec![vec![]], + TypeTest { + layout: get_type_layout::>(), + vars_types: vec![get_tlc::<&RString>(), get_tlc::>()], + field_types: vec![0, 0, 1], + functions: vec![vec![]], }, - - TypeTest{ - layout:get_type_layout::(), - vars_types:vec![ get_tlc::() ], - field_types:vec![0], - functions:vec![vec![]], + TypeTest { + layout: get_type_layout::(), + vars_types: vec![get_tlc::()], + field_types: vec![0], + functions: vec![vec![]], }, - - TypeTest{ - layout:get_type_layout::(), - vars_types:vec![ get_tlc::() ], - field_types:vec![0,0,0], - functions:vec![vec![]], + TypeTest { + layout: get_type_layout::(), + vars_types: vec![get_tlc::()], + field_types: vec![0, 0, 0], + functions: vec![vec![]], }, - - TypeTest{ - layout:get_type_layout::(), - vars_types:vec![ get_tlc::(), get_tlc::() ], - field_types:vec![0,1], - functions:vec![vec![]], + TypeTest { + layout: get_type_layout::(), + vars_types: vec![get_tlc::(), get_tlc::()], + field_types: vec![0, 1], + functions: vec![vec![]], }, - - TypeTest{ - layout:get_type_layout::(), - vars_types:vec![ get_tlc::(), get_tlc::() ], - field_types:vec![0,0,1,0], - functions:vec![vec![]], + TypeTest { + layout: get_type_layout::(), + vars_types: vec![get_tlc::(), get_tlc::()], + field_types: vec![0, 0, 1, 0], + functions: vec![vec![]], }, - - TypeTest{ - layout:get_type_layout::>(), - vars_types:vec![ get_tlc::<&()>() ], - field_types:vec![0,0], - functions:vec![vec![]], + TypeTest { + layout: get_type_layout::>(), + vars_types: vec![get_tlc::<&()>()], + field_types: vec![0, 0], + functions: vec![vec![]], }, - - TypeTest{ - layout:get_type_layout::(), - vars_types:vec![ + TypeTest { + layout: get_type_layout::(), + vars_types: vec![ get_tlc::(), get_tlc::(), get_tlc::<&mut u32>(), get_tlc::(), ], - field_types:vec![0,0,0], - functions:vec![ - vec![ FnTest{ params:vec![] ,ret:1 } ], - vec![ FnTest{ params:vec![2,3,1] ,ret:!0 } ], - vec![ FnTest{ params:vec![2,3,1] ,ret:!0 } ], + field_types: vec![0, 0, 0], + functions: vec![ + vec![FnTest { + params: vec![], + ret: 1, + }], + vec![FnTest { + params: vec![2, 3, 1], + ret: !0, + }], + vec![FnTest { + params: vec![2, 3, 1], + ret: !0, + }], ], }, - - TypeTest{ - layout:get_type_layout::(), - vars_types:vec![ + TypeTest { + layout: get_type_layout::(), + vars_types: vec![ get_tlc::(), get_tlc::(), get_tlc::<&mut u32>(), get_tlc::(), get_tlc::<()>(), ], - field_types:vec![0,0,0], - functions:vec![ - vec![ FnTest{ params:vec![] ,ret:1 } ], - vec![ FnTest{ params:vec![2,3,1] ,ret:!0} ], - vec![ FnTest{ params:vec![4,4,4] ,ret:!0 } ], + field_types: vec![0, 0, 0], + functions: vec![ + vec![FnTest { + params: vec![], + ret: 1, + }], + vec![FnTest { + params: vec![2, 3, 1], + ret: !0, + }], + vec![FnTest { + params: vec![4, 4, 4], + ret: !0, + }], ], }, - TypeTest{ - layout:get_type_layout::(), - vars_types:vec![ + TypeTest { + layout: get_type_layout::(), + vars_types: vec![ get_tlc::(), get_tlc::(), get_tlc::<&mut u32>(), @@ -205,19 +199,34 @@ fn assert_types(){ get_tlc::<()>(), get_tlc::<()>(), ], - field_types:vec![0,0,0,0,0], - functions:vec![ - vec![ FnTest{ params:vec![] ,ret:1 } ], - vec![ FnTest{ params:vec![2,3,1,5,6,7] ,ret:!0} ], - vec![ FnTest{ params:vec![4,7,4,4,4] ,ret:!0 } ], - vec![ FnTest{ params:vec![6,3,5,1] ,ret:2 } ], - vec![ FnTest{ params:vec![4,4,4,4,8,9] ,ret:!0 } ], + field_types: vec![0, 0, 0, 0, 0], + functions: vec![ + vec![FnTest { + params: vec![], + ret: 1, + }], + vec![FnTest { + params: vec![2, 3, 1, 5, 6, 7], + ret: !0, + }], + vec![FnTest { + params: vec![4, 7, 4, 4, 4], + ret: !0, + }], + vec![FnTest { + params: vec![6, 3, 5, 1], + ret: 2, + }], + vec![FnTest { + params: vec![4, 4, 4, 4, 8, 9], + ret: !0, + }], ], }, ]; - let test_layout=|field_layout,expected_layout|{ - let res=check_layout_compatibility(field_layout,expected_layout); + let test_layout = |field_layout, expected_layout| { + let res = check_layout_compatibility(field_layout, expected_layout); assert!( res.is_ok(), @@ -227,42 +236,46 @@ fn assert_types(){ ); }; - let empty_vec=Vec::new(); + let empty_vec = Vec::new(); for ty_test in list { - let shared_vars=ty_test.layout.shared_vars(); - let vars_types=&ty_test.vars_types; - - let fields=ty_test.layout.get_fields().unwrap(); - let mut expected_fns_list=ty_test.functions.iter(); - for (field_i,field) in fields.iter().enumerate() { - let field_layout=field.layout(); - let expected_layout={ - let x=ty_test.field_types[field_i]; + let shared_vars = ty_test.layout.shared_vars(); + let vars_types = &ty_test.vars_types; + + let fields = ty_test.layout.get_fields().unwrap(); + let mut expected_fns_list = ty_test.functions.iter(); + for (field_i, field) in fields.iter().enumerate() { + let field_layout = field.layout(); + let expected_layout = { + let x = ty_test.field_types[field_i]; vars_types[x].get() }; - test_layout(field_layout,expected_layout); - - let mut expected_fns=expected_fns_list.next().unwrap_or(&empty_vec).iter(); + test_layout(field_layout, expected_layout); + + let mut expected_fns = expected_fns_list.next().unwrap_or(&empty_vec).iter(); for field_func in field.function_range() { - let expected_fn=expected_fns.next().unwrap(); + let expected_fn = expected_fns.next().unwrap(); - let mut expected_params=expected_fn.params.iter(); + let mut expected_params = expected_fn.params.iter(); for param in field_func.param_type_layouts.iter() { - let expected_param=expected_params.next() - .and_then(|x| vars_types.get(*x) ) - .unwrap_or_else(|| panic!("mismatched parameter type: {}",field_func) ); - test_layout( param.get(), expected_param.get() ); + let expected_param = expected_params + .next() + .and_then(|x| vars_types.get(*x)) + .unwrap_or_else(|| panic!("mismatched parameter type: {}", field_func)); + test_layout(param.get(), expected_param.get()); } - match ( field_func.return_type_layout, vars_types.get(expected_fn.ret) ) { - (Some(found_ret),Some(expected_ret))=>{ - test_layout( found_ret.get(), expected_ret.get() ); + match ( + field_func.return_type_layout, + vars_types.get(expected_fn.ret), + ) { + (Some(found_ret), Some(expected_ret)) => { + test_layout(found_ret.get(), expected_ret.get()); } - (None,None)=>{} - _=>panic!( + (None, None) => {} + _ => panic!( "mismatched return type: {}\n\ shared_vars.type_layouts:{:#?}\n\ found function parameter/ret:{:#?} {:?} @@ -272,20 +285,18 @@ fn assert_types(){ type_layouts_fmt(shared_vars.type_layouts().iter().cloned()), type_layouts_fmt(field_func.param_type_layouts.iter()), type_layouts_fmt(field_func.return_type_layout), - type_layouts_fmt(expected_fn.params.iter().map(|x| vars_types[*x] )), + type_layouts_fmt(expected_fn.params.iter().map(|x| vars_types[*x])), type_layouts_fmt(vars_types.get(expected_fn.ret).cloned()), - ) + ), } } } - } } - #[cfg(not(miri))] -fn type_layouts_fmt(iter:impl IntoIterator)->Vec{ +fn type_layouts_fmt(iter: impl IntoIterator) -> Vec { iter.into_iter() - .map(|x|x.get().full_type().to_string()) + .map(|x| x.get().full_type().to_string()) .collect::>() -} \ No newline at end of file +} diff --git a/abi_stable/tests/layout_tests/lifetime_indices_tests.rs b/abi_stable/tests/layout_tests/lifetime_indices_tests.rs index da492f5f..836c7888 100644 --- a/abi_stable/tests/layout_tests/lifetime_indices_tests.rs +++ b/abi_stable/tests/layout_tests/lifetime_indices_tests.rs @@ -1,382 +1,400 @@ #[allow(unused_imports)] -use core_extensions::{SelfOps,matches}; +use core_extensions::{matches, SelfOps}; #[allow(unused_imports)] -use abi_stable::std_types::{Tuple1,Tuple2,Tuple3,Tuple4}; +use abi_stable::std_types::{Tuple1, Tuple2, Tuple3, Tuple4}; use abi_stable::{ - std_types::{RStr,RSlice}, + std_types::{RSlice, RStr}, type_layout::{ - LifetimeArrayOrSlice, - LifetimeIndex, - LifetimeIndexPair, - LifetimeIndexPair as LAP, - LifetimeRange, - TypeLayout, + LifetimeArrayOrSlice, LifetimeIndex, LifetimeIndexPair, LifetimeIndexPair as LAP, + LifetimeRange, TypeLayout, }, StableAbi, }; - -const LR0:LifetimeIndex=LifetimeIndex::Param(0); -const LR1:LifetimeIndex=LifetimeIndex::Param(1); -const LR2:LifetimeIndex=LifetimeIndex::Param(2); -const LR3:LifetimeIndex=LifetimeIndex::Param(3); -const LRA:LifetimeIndex=LifetimeIndex::ANONYMOUS; -const LRS:LifetimeIndex=LifetimeIndex::STATIC; -const LRN:LifetimeIndex=LifetimeIndex::NONE; - +const LR0: LifetimeIndex = LifetimeIndex::Param(0); +const LR1: LifetimeIndex = LifetimeIndex::Param(1); +const LR2: LifetimeIndex = LifetimeIndex::Param(2); +const LR3: LifetimeIndex = LifetimeIndex::Param(3); +const LRA: LifetimeIndex = LifetimeIndex::ANONYMOUS; +const LRS: LifetimeIndex = LifetimeIndex::STATIC; +const LRN: LifetimeIndex = LifetimeIndex::NONE; #[derive(Debug)] -pub struct LRTestParam{ - pub layout:&'static TypeLayout, - pub shared_vars_lifetimes:Vec, - pub paramret_lifetimes:Vec, - pub field_lt_indices:Vec>, +pub struct LRTestParam { + pub layout: &'static TypeLayout, + pub shared_vars_lifetimes: Vec, + pub paramret_lifetimes: Vec, + pub field_lt_indices: Vec>, } - - - -mod loads_of_params{ +mod loads_of_params { #[repr(C)] #[derive(abi_stable::StableAbi)] - pub struct Struct{ - func:for<'a> extern - fn(&'a u8,&u8,&u8,&u8,&u8,&u8,&u8,&u8,&u8,&u8,&u8,&u8,&u8,&u8)->&'a u8, + pub struct Struct { + func: for<'a> extern "C" fn( + &'a u8, + &u8, + &u8, + &u8, + &u8, + &u8, + &u8, + &u8, + &u8, + &u8, + &u8, + &u8, + &u8, + &u8, + ) -> &'a u8, } } -mod loads_of_lifetimes_single_param{ +mod loads_of_lifetimes_single_param { #[repr(C)] #[derive(abi_stable::StableAbi)] - pub struct Struct{ - func:for<'a> extern "C" fn(&'a&&&&&u8)->&'a u8, + pub struct Struct { + func: for<'a> extern "C" fn(&'a &&&&&u8) -> &'a u8, } } -mod four_lifetimes_single_param{ +mod four_lifetimes_single_param { #[repr(C)] #[derive(abi_stable::StableAbi)] - pub struct Struct{ - func:for<'a> extern "C" fn(&'a&&u8)->&'a u8, + pub struct Struct { + func: for<'a> extern "C" fn(&'a &&u8) -> &'a u8, } } -mod three_lifetimes_single_param{ +mod three_lifetimes_single_param { #[repr(C)] #[derive(abi_stable::StableAbi)] - pub struct Struct{ - func:for<'a> extern "C" fn(&'a&u8)->&'a u8, + pub struct Struct { + func: for<'a> extern "C" fn(&'a &u8) -> &'a u8, } } -mod lifetimes_rep_a_single_param{ +mod lifetimes_rep_a_single_param { #[repr(C)] #[derive(abi_stable::StableAbi)] - pub struct Struct{ - func:for<'a,'b> extern "C" fn(&'a&'a&'b&u8)->&'b u8, + pub struct Struct { + func: for<'a, 'b> extern "C" fn(&'a &'a &'b &u8) -> &'b u8, } } -mod lifetimes_rep_b_single_param{ +mod lifetimes_rep_b_single_param { #[repr(C)] #[derive(abi_stable::StableAbi)] - pub struct Struct{ - func:for<'a> extern "C" fn(&'a&'a u8), + pub struct Struct { + func: for<'a> extern "C" fn(&'a &'a u8), } } -mod lifetimes_four_params{ +mod lifetimes_four_params { use super::*; #[repr(C)] #[derive(abi_stable::StableAbi)] - #[sabi(bound="'lt1:'lt0")] - pub struct Struct<'lt0,'lt1>{ - reference_a:&'static (), - reference_b:&'lt0 (), - reference_c:&'lt0 &'lt1 &'lt1 &'lt1 &'static &'static (), - func_abba:for<'a,'b> - extern "C" fn( &'b (), &'static (), RSlice<'a,RStr<'_>>, RStr<'a>)->&'static (), + #[sabi(bound = "'lt1:'lt0")] + pub struct Struct<'lt0, 'lt1> { + reference_a: &'static (), + reference_b: &'lt0 (), + reference_c: &'lt0 &'lt1 &'lt1 &'lt1 &'static &'static (), + func_abba: for<'a, 'b> extern "C" fn( + &'b (), + &'static (), + RSlice<'a, RStr<'_>>, + RStr<'a>, + ) -> &'static (), } - } -mod many_bound_lifetimes{ +mod many_bound_lifetimes { use super::*; #[repr(C)] #[derive(abi_stable::StableAbi)] // #[sabi(debug_print)] - pub struct Struct<'lt0,'lt1>{ - func_abba:for<'a,'b,'c,'d,'e,'f,'g,'h,'i,'j,'k,'l,'m,'n,'o> - extern "C" fn( - &'a (),&'b (), - &'c (),&'d (), - &'e (),&'f (), - &'g (),&'h (), - &'i (),&'j (), - &'k (),&'l (), - &'m (),&'n (), - &'o (),&'o () + pub struct Struct<'lt0, 'lt1> { + func_abba: + for<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k, 'l, 'm, 'n, 'o> extern "C" fn( + &'a (), + &'b (), + &'c (), + &'d (), + &'e (), + &'f (), + &'g (), + &'h (), + &'i (), + &'j (), + &'k (), + &'l (), + &'m (), + &'n (), + &'o (), + &'o (), ), - _marker:std::marker::PhantomData, - Tuple4<&'lt0(),&'static(),&'static(),&'lt1()>, - >> + _marker: std::marker::PhantomData< + Tuple2< + Tuple4<&'lt0 (), &'lt1 (), &'static (), &'lt1 ()>, + Tuple4<&'lt0 (), &'static (), &'static (), &'lt1 ()>, + >, + >, } } -mod many_bound_lifetimes_b{ +mod many_bound_lifetimes_b { use super::*; #[repr(C)] #[derive(abi_stable::StableAbi)] // #[sabi(debug_print)] - pub struct Struct<'lt0,'lt1>{ - func_abba:for<'a,'b,'c,'d,'e,'f,'g,'h,'i,'j,'k,'l,'m,'n,'o,'p> - extern "C" fn( - &'a (),&'b (), - &'c (),&'d (), - &'e (),&'f (), - &'g (),&'h (), - &'i (),&'j (), - &'k (),&'l (), - &'m (),&'n (), - &'o (),&'o (), - &'p (),&'static (), - &'p (),&'lt0 (), + pub struct Struct<'lt0, 'lt1> { + func_abba: + for<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k, 'l, 'm, 'n, 'o, 'p> extern "C" fn( + &'a (), + &'b (), + &'c (), + &'d (), + &'e (), + &'f (), + &'g (), + &'h (), + &'i (), + &'j (), + &'k (), + &'l (), + &'m (), + &'n (), + &'o (), + &'o (), + &'p (), + &'static (), + &'p (), + &'lt0 (), ), - _marker:std::marker::PhantomData, - Tuple4<&'lt0(),&'static(),&'static(),&'lt1()>, - >> + _marker: std::marker::PhantomData< + Tuple2< + Tuple4<&'lt0 (), &'lt1 (), &'static (), &'lt1 ()>, + Tuple4<&'lt0 (), &'static (), &'static (), &'lt1 ()>, + >, + >, } } -mod nested_fn_pointer{ +mod nested_fn_pointer { use super::*; #[repr(C)] #[derive(abi_stable::StableAbi)] - #[sabi(bound="'lt1:'lt0")] + #[sabi(bound = "'lt1:'lt0")] // #[sabi(debug_print)] - pub struct Struct<'lt0,'lt1>{ - funcs:Tuple2< + pub struct Struct<'lt0, 'lt1> { + funcs: Tuple2< Tuple2< &'lt0 &'static (), - for<'a,'b> extern "C" fn(&'a &'a &'a (),RStr<'b>,&'lt0 &'lt1 (),&()), + for<'a, 'b> extern "C" fn(&'a &'a &'a (), RStr<'b>, &'lt0 &'lt1 (), &()), >, Tuple2< - &'lt0 &'lt0 &'lt1 &'static &'static (), - for<'a,'b> extern "C" fn(&'b &'b &'a (),RStr<'a>,&&'lt1 (),&()), + &'lt0 &'lt0 &'lt1 &'static &'static (), + for<'a, 'b> extern "C" fn(&'b &'b &'a (), RStr<'a>, &&'lt1 (), &()), >, >, - hello: Tuple4< - &'lt0 RSlice<'lt1,RStr<'static>>, - &'static (), - &'lt0 (), - &'lt1 (), - >, - world:Tuple3< - &'lt0 RSlice<'lt1,RStr<'static>>, - &'static (), - &'lt0 (), - >, - func_b:for<'a,'b,'c,'d,'e,'f,'g,'h,'i,'j,'k,'l,'m,'n,'o> - extern "C" fn( - &'a (),&'b (), - &'c (),&'d (), - &'e (),&'f (), - &'g (),&'h (), - &'i (),&'j (), - &'o (),&'o (), - &'k (),&'l (), - &'m (),&'n (), - ), + hello: Tuple4<&'lt0 RSlice<'lt1, RStr<'static>>, &'static (), &'lt0 (), &'lt1 ()>, + world: Tuple3<&'lt0 RSlice<'lt1, RStr<'static>>, &'static (), &'lt0 ()>, + func_b: for<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k, 'l, 'm, 'n, 'o> extern "C" fn( + &'a (), + &'b (), + &'c (), + &'d (), + &'e (), + &'f (), + &'g (), + &'h (), + &'i (), + &'j (), + &'o (), + &'o (), + &'k (), + &'l (), + &'m (), + &'n (), + ), } } #[test] -fn test_single_function_lifetime_ranges(){ - - let list=vec![ - LRTestParam{ - layout:::LAYOUT, - shared_vars_lifetimes:vec![ - LAP::new(LR0,LRA), - LAP::new(LRA,LRA), - LAP::new(LRA,LRA), - LAP::new(LRA,LRA), - LAP::new(LRA,LRA), - LAP::new(LRA,LRA), - LAP::new(LRA,LRA), - LAP::new(LR0,LRN), +fn test_single_function_lifetime_ranges() { + let list = vec![ + LRTestParam { + layout: ::LAYOUT, + shared_vars_lifetimes: vec![ + LAP::new(LR0, LRA), + LAP::new(LRA, LRA), + LAP::new(LRA, LRA), + LAP::new(LRA, LRA), + LAP::new(LRA, LRA), + LAP::new(LRA, LRA), + LAP::new(LRA, LRA), + LAP::new(LR0, LRN), ], - paramret_lifetimes:vec![LifetimeRange::from_range(0..8)], - field_lt_indices:vec![vec![]], + paramret_lifetimes: vec![LifetimeRange::from_range(0..8)], + field_lt_indices: vec![vec![]], }, - LRTestParam{ - layout:::LAYOUT, - shared_vars_lifetimes:vec![ - LAP::new(LR0,LRA), - LAP::new(LRA,LRA), - LAP::new(LRA,LRA), - LAP::new(LR0,LRN), + LRTestParam { + layout: ::LAYOUT, + shared_vars_lifetimes: vec![ + LAP::new(LR0, LRA), + LAP::new(LRA, LRA), + LAP::new(LRA, LRA), + LAP::new(LR0, LRN), ], - paramret_lifetimes:vec![LifetimeRange::from_range(0..4)], - field_lt_indices:vec![vec![]], + paramret_lifetimes: vec![LifetimeRange::from_range(0..4)], + field_lt_indices: vec![vec![]], }, - LRTestParam{ - layout:::LAYOUT, - shared_vars_lifetimes:vec![], - paramret_lifetimes:vec![LifetimeRange::from_array([LR0,LRA,LRA,LR0,LRN])], - field_lt_indices:vec![vec![]], + LRTestParam { + layout: ::LAYOUT, + shared_vars_lifetimes: vec![], + paramret_lifetimes: vec![LifetimeRange::from_array([LR0, LRA, LRA, LR0, LRN])], + field_lt_indices: vec![vec![]], }, - LRTestParam{ - layout:::LAYOUT, - shared_vars_lifetimes:vec![], - paramret_lifetimes:vec![LifetimeRange::from_array([LR0,LRA,LR0,LRN,LRN])], - field_lt_indices:vec![vec![]], + LRTestParam { + layout: ::LAYOUT, + shared_vars_lifetimes: vec![], + paramret_lifetimes: vec![LifetimeRange::from_array([LR0, LRA, LR0, LRN, LRN])], + field_lt_indices: vec![vec![]], }, - LRTestParam{ - layout:::LAYOUT, - shared_vars_lifetimes:vec![], - paramret_lifetimes:vec![LifetimeRange::from_array([LR0,LR0,LR1,LRA,LR1])], - field_lt_indices:vec![vec![]], + LRTestParam { + layout: ::LAYOUT, + shared_vars_lifetimes: vec![], + paramret_lifetimes: vec![LifetimeRange::from_array([LR0, LR0, LR1, LRA, LR1])], + field_lt_indices: vec![vec![]], }, - LRTestParam{ - layout:::LAYOUT, - shared_vars_lifetimes:vec![], - paramret_lifetimes:vec![LifetimeRange::from_array([LR0,LR0,LRN,LRN,LRN])], - field_lt_indices:vec![vec![]], + LRTestParam { + layout: ::LAYOUT, + shared_vars_lifetimes: vec![], + paramret_lifetimes: vec![LifetimeRange::from_array([LR0, LR0, LRN, LRN, LRN])], + field_lt_indices: vec![vec![]], }, - LRTestParam{ - layout: as StableAbi>::LAYOUT, - shared_vars_lifetimes:vec![ - LAP::new(LR0,LR1), - LAP::new(LR1,LR1), - LAP::new(LRS,LRS), - LAP::new(LRA,LRS), - LAP::new(LR2,LRA), - LAP::new(LR2,LRS), + LRTestParam { + layout: as StableAbi>::LAYOUT, + shared_vars_lifetimes: vec![ + LAP::new(LR0, LR1), + LAP::new(LR1, LR1), + LAP::new(LRS, LRS), + LAP::new(LRA, LRS), + LAP::new(LR2, LRA), + LAP::new(LR2, LRS), ], - paramret_lifetimes:vec![LifetimeRange::from_range(3..6)], - field_lt_indices:vec![ - vec![LAP::new(LRS,LRN)], - vec![LAP::new(LR0,LRN)], - vec![LAP::new(LR0,LR1),LAP::new(LR1,LR1),LAP::new(LRS,LRS)], + paramret_lifetimes: vec![LifetimeRange::from_range(3..6)], + field_lt_indices: vec![ + vec![LAP::new(LRS, LRN)], + vec![LAP::new(LR0, LRN)], + vec![LAP::new(LR0, LR1), LAP::new(LR1, LR1), LAP::new(LRS, LRS)], vec![], ], }, - LRTestParam{ - layout: as StableAbi>::LAYOUT, - shared_vars_lifetimes:vec![ - LAP::new(LRA,LRA), - LAP::new(LRA,LRA), - LAP::new(LRA,LRA), - LAP::new(LRA,LRA), - LAP::new(LRA,LRA), - LAP::new(LRA,LRA), - LAP::new(LRA,LRA), - LAP::new(LR2,LR2), - LAP::new(LR0,LR1), - LAP::new(LRS,LR1), - LAP::new(LR0,LRS), - LAP::new(LRS,LR1), + LRTestParam { + layout: as StableAbi>::LAYOUT, + shared_vars_lifetimes: vec![ + LAP::new(LRA, LRA), + LAP::new(LRA, LRA), + LAP::new(LRA, LRA), + LAP::new(LRA, LRA), + LAP::new(LRA, LRA), + LAP::new(LRA, LRA), + LAP::new(LRA, LRA), + LAP::new(LR2, LR2), + LAP::new(LR0, LR1), + LAP::new(LRS, LR1), + LAP::new(LR0, LRS), + LAP::new(LRS, LR1), ], - paramret_lifetimes:vec![LifetimeRange::from_range(0..8)], - field_lt_indices:vec![ + paramret_lifetimes: vec![LifetimeRange::from_range(0..8)], + field_lt_indices: vec![ vec![], vec![ - LAP::new(LR0,LR1), - LAP::new(LRS,LR1), - LAP::new(LR0,LRS), - LAP::new(LRS,LR1), + LAP::new(LR0, LR1), + LAP::new(LRS, LR1), + LAP::new(LR0, LRS), + LAP::new(LRS, LR1), ], ], }, - LRTestParam{ - layout: as StableAbi>::LAYOUT, - shared_vars_lifetimes:vec![ - LAP::new(LRA,LRA), - LAP::new(LRA,LRA), - LAP::new(LRA,LRA), - LAP::new(LRA,LRA), - LAP::new(LRA,LRA), - LAP::new(LRA,LRA), - LAP::new(LRA,LRA), - LAP::new(LR2,LR2), - LAP::new(LR3,LRS), - LAP::new(LR3,LR0), - LAP::new(LR0,LR1), - LAP::new(LRS,LR1), - LAP::new(LR0,LRS), - LAP::new(LRS,LR1), + LRTestParam { + layout: as StableAbi>::LAYOUT, + shared_vars_lifetimes: vec![ + LAP::new(LRA, LRA), + LAP::new(LRA, LRA), + LAP::new(LRA, LRA), + LAP::new(LRA, LRA), + LAP::new(LRA, LRA), + LAP::new(LRA, LRA), + LAP::new(LRA, LRA), + LAP::new(LR2, LR2), + LAP::new(LR3, LRS), + LAP::new(LR3, LR0), + LAP::new(LR0, LR1), + LAP::new(LRS, LR1), + LAP::new(LR0, LRS), + LAP::new(LRS, LR1), ], - paramret_lifetimes:vec![LifetimeRange::from_range(0..10)], - field_lt_indices:vec![ + paramret_lifetimes: vec![LifetimeRange::from_range(0..10)], + field_lt_indices: vec![ vec![], vec![ - LAP::new(LR0,LR1), - LAP::new(LRS,LR1), - LAP::new(LR0,LRS), - LAP::new(LRS,LR1), + LAP::new(LR0, LR1), + LAP::new(LRS, LR1), + LAP::new(LR0, LRS), + LAP::new(LRS, LR1), ], ], }, - LRTestParam{ - layout: as StableAbi>::LAYOUT, - shared_vars_lifetimes:vec![ + LRTestParam { + layout: as StableAbi>::LAYOUT, + shared_vars_lifetimes: vec![ // funcs field lifetimes(outside function pointers) - LAP::new(LR0,LRS), - LAP::new(LR0,LR0), - LAP::new(LR1,LRS), - LAP::new(LRS,LRN), + LAP::new(LR0, LRS), + LAP::new(LR0, LR0), + LAP::new(LR1, LRS), + LAP::new(LRS, LRN), // Function pointer 0 lifetiems - LAP::new(LR2,LR2), - LAP::new(LR2,LRA), - LAP::new(LR0,LR1), - LAP::new(LRA,LRN), + LAP::new(LR2, LR2), + LAP::new(LR2, LRA), + LAP::new(LR0, LR1), + LAP::new(LRA, LRN), // Function pointer 1 lifetiems - LAP::new(LR3,LR3), - LAP::new(LR2,LR2), - LAP::new(LRA,LR1), - LAP::new(LRA,LRN), + LAP::new(LR3, LR3), + LAP::new(LR2, LR2), + LAP::new(LRA, LR1), + LAP::new(LRA, LRN), // hello field - LAP::new(LR0,LR1), - LAP::new(LRS,LRS), - LAP::new(LR0,LR1), + LAP::new(LR0, LR1), + LAP::new(LRS, LRS), + LAP::new(LR0, LR1), // func_b function pointer - LAP::new(LRA,LRA), - LAP::new(LRA,LRA), - LAP::new(LRA,LRA), - LAP::new(LRA,LRA), - LAP::new(LRA,LRA), - LAP::new(LR2,LR2), - LAP::new(LRA,LRA), - LAP::new(LRA,LRA), - + LAP::new(LRA, LRA), + LAP::new(LRA, LRA), + LAP::new(LRA, LRA), + LAP::new(LRA, LRA), + LAP::new(LRA, LRA), + LAP::new(LR2, LR2), + LAP::new(LRA, LRA), + LAP::new(LRA, LRA), ], - paramret_lifetimes:vec![ + paramret_lifetimes: vec![ LifetimeRange::from_range(4..8), LifetimeRange::from_range(8..12), LifetimeRange::from_range(15..23), ], - field_lt_indices:vec![ - vec![ - LAP::new(LR0,LRS), - LAP::new(LR0,LR0), - LAP::new(LR1,LRS), - LAP::new(LRS,LRN), - ], + field_lt_indices: vec![ vec![ - LAP::new(LR0,LR1), - LAP::new(LRS,LRS), - LAP::new(LR0,LR1), - ], - vec![ - LAP::new(LR0,LR1), - LAP::new(LRS,LRS), - LAP::new(LR0,LRN), + LAP::new(LR0, LRS), + LAP::new(LR0, LR0), + LAP::new(LR1, LRS), + LAP::new(LRS, LRN), ], + vec![LAP::new(LR0, LR1), LAP::new(LRS, LRS), LAP::new(LR0, LR1)], + vec![LAP::new(LR0, LR1), LAP::new(LRS, LRS), LAP::new(LR0, LRN)], vec![], ], }, @@ -390,10 +408,10 @@ fn test_single_function_lifetime_ranges(){ test.layout.mod_path(), ); - let fields=test.layout.get_fields().unwrap(); - let functions=fields.iter().flat_map(|f| f.function_range() ); + let fields = test.layout.get_fields().unwrap(); + let functions = fields.iter().flat_map(|f| f.function_range()); - for (func,paramret_lifetimes) in functions.zip(test.paramret_lifetimes){ + for (func, paramret_lifetimes) in functions.zip(test.paramret_lifetimes) { assert_eq!( &func.paramret_lifetime_indices[..], ¶mret_lifetimes.slicing(&test.shared_vars_lifetimes[..])[..], @@ -402,9 +420,9 @@ fn test_single_function_lifetime_ranges(){ ); } - let iter=fields.iter().zip(test.field_lt_indices).enumerate(); - for (field_i,(field,expected_lt_indices)) in iter { - let lifetime_indices=field.lifetime_indices(); + let iter = fields.iter().zip(test.field_lt_indices).enumerate(); + for (field_i, (field, expected_lt_indices)) in iter { + let lifetime_indices = field.lifetime_indices(); assert_eq!( &lifetime_indices[..], &expected_lt_indices[..], @@ -415,10 +433,10 @@ fn test_single_function_lifetime_ranges(){ ); assert_eq!( - lifetime_indices.len()<=2 || - lifetime_indices.len()==3 && lifetime_indices[2].second()==LRN , - matches!(lifetime_indices, LifetimeArrayOrSlice::Array{..}), + lifetime_indices.len() <= 2 + || lifetime_indices.len() == 3 && lifetime_indices[2].second() == LRN, + matches!(lifetime_indices, LifetimeArrayOrSlice::Array { .. }), ); } } -} \ No newline at end of file +} diff --git a/abi_stable/tests/layout_tests/nonexhaustive_enums.rs b/abi_stable/tests/layout_tests/nonexhaustive_enums.rs index 00fd3f30..0a0b6ab2 100644 --- a/abi_stable/tests/layout_tests/nonexhaustive_enums.rs +++ b/abi_stable/tests/layout_tests/nonexhaustive_enums.rs @@ -1,85 +1,70 @@ use abi_stable::{ - StableAbi, - abi_stability::{ - abi_checking::{ - AbiInstability,AbiInstabilityErrors, - check_layout_compatibility_with_globals, - CheckingGlobals, - }, + abi_stability::abi_checking::{ + check_layout_compatibility_with_globals, AbiInstability, AbiInstabilityErrors, + CheckingGlobals, }, nonexhaustive_enum::{ examples::{ - command_one, - command_one_more_traits_1, - command_one_more_traits_2, - command_one_more_traits_3, - command_a, - command_a_exhaustive, - command_b, - command_c, - command_c_mismatched_field, - command_h, - command_h_mismatched_discriminant, - too_large, + command_a, command_a_exhaustive, command_b, command_c, command_c_mismatched_field, + command_h, command_h_mismatched_discriminant, command_one, command_one_more_traits_1, + command_one_more_traits_2, command_one_more_traits_3, too_large, }, NonExhaustiveFor, }, type_layout::TypeLayout, + StableAbi, }; -use core_extensions::{matches,SelfOps}; +use core_extensions::{matches, SelfOps}; - -mod with_2_enums_a{ +mod with_2_enums_a { use super::*; #[repr(C)] #[derive(abi_stable::StableAbi)] - pub struct Struct{ - a:command_a::Foo_NE, - b:command_a::Foo_NE, + pub struct Struct { + a: command_a::Foo_NE, + b: command_a::Foo_NE, } } -mod with_2_enums_b{ +mod with_2_enums_b { use super::*; #[repr(C)] #[derive(abi_stable::StableAbi)] - pub struct Struct{ - a:command_a::Foo_NE, - b:command_b::Foo_NE, + pub struct Struct { + a: command_a::Foo_NE, + b: command_b::Foo_NE, } } -mod with_2_enums_c{ +mod with_2_enums_c { use super::*; #[repr(C)] #[derive(abi_stable::StableAbi)] - pub struct Struct{ - a:command_a::Foo_NE, - b:command_c::Foo_NE, + pub struct Struct { + a: command_a::Foo_NE, + b: command_c::Foo_NE, } } - #[cfg(not(miri))] -fn check_subsets(list:&[&'static TypeLayout],mut f:F) +fn check_subsets(list: &[&'static TypeLayout], mut f: F) where - F:FnMut(&[AbiInstability]) + F: FnMut(&[AbiInstability]), { - let globals=CheckingGlobals::new(); - for (l_i,l_abi) in list.iter().enumerate() { - for (r_i,r_abi) in list.iter().enumerate() { - - let res=check_layout_compatibility_with_globals(l_abi,r_abi,&globals); + let globals = CheckingGlobals::new(); + for (l_i, l_abi) in list.iter().enumerate() { + for (r_i, r_abi) in list.iter().enumerate() { + let res = check_layout_compatibility_with_globals(l_abi, r_abi, &globals); if l_i <= r_i { - assert_eq!(res,Ok(()),"\n\nl_i:{} r_i:{}\n\n",l_i,r_i); - }else{ - if let Ok(_)=res { - let _=dbg!(l_i); - let _=dbg!(r_i); + assert_eq!(res, Ok(()), "\n\nl_i:{} r_i:{}\n\n", l_i, r_i); + } else { + if let Ok(_) = res { + let _ = dbg!(l_i); + let _ = dbg!(r_i); } - let errs=res.unwrap_err().flatten_errors(); + let errs = res.unwrap_err().flatten_errors(); f(&*errs); } @@ -87,230 +72,227 @@ where } } - - #[cfg(not(miri))] #[test] -fn check_enum_subsets(){ - let list=vec![ +fn check_enum_subsets() { + let list = vec![ as StableAbi>::LAYOUT, as StableAbi>::LAYOUT, as StableAbi>::LAYOUT, ]; - check_subsets(&list,|errs|{ - assert!( - errs + check_subsets(&list, |errs| { + assert!(errs .iter() - .any(|err| matches!(err, AbiInstability::TooManyVariants{..})) - ); + .any(|err| matches!(err, AbiInstability::TooManyVariants { .. }))); }) } #[cfg(miri)] #[test] -fn check_enum_subsets(){ - let globals=CheckingGlobals::new(); +fn check_enum_subsets() { + let globals = CheckingGlobals::new(); let inter0 = as StableAbi>::LAYOUT; let inter1 = as StableAbi>::LAYOUT; - assert_eq!(check_layout_compatibility_with_globals(inter0, inter1, &globals), Ok(())); - assert_ne!(check_layout_compatibility_with_globals(inter1, inter0, &globals), Ok(())); + assert_eq!( + check_layout_compatibility_with_globals(inter0, inter1, &globals), + Ok(()) + ); + assert_ne!( + check_layout_compatibility_with_globals(inter1, inter0, &globals), + Ok(()) + ); } - // This test ensures that a struct with 2 nonexhaustive enums works as expected. // -// This test is partly to ensure that a `NonExhaustive<>` produces different +// This test is partly to ensure that a `NonExhaustive<>` produces different // `UTypeId`s with different enums, -// that is a bug I discovered while testing out type errors in +// that is a bug I discovered while testing out type errors in // the 2_nonexhaustive example crates. -// This bug was caused by `#[sabi(unconstrained(T))]` +// This bug was caused by `#[sabi(unconstrained(T))]` // causing the type parameter to be ignored when generating the UTypeId, // meaning that even if the type parameter changed the UTypeId wouldn't. #[cfg(not(miri))] #[test] -fn check_2_enum_subsets(){ - let list=vec![ +fn check_2_enum_subsets() { + let list = vec![ ::LAYOUT, ::LAYOUT, ::LAYOUT, ]; - check_subsets(&list,|errs|{ - assert!( - errs + check_subsets(&list, |errs| { + assert!(errs .iter() - .any(|err| matches!(err, AbiInstability::TooManyVariants{..})) - ); + .any(|err| matches!(err, AbiInstability::TooManyVariants { .. }))); }) } #[cfg(miri)] #[test] -fn check_2_enum_subsets(){ - let globals=CheckingGlobals::new(); +fn check_2_enum_subsets() { + let globals = CheckingGlobals::new(); let inter0 = ::LAYOUT; let inter1 = ::LAYOUT; - assert_eq!(check_layout_compatibility_with_globals(inter0, inter1, &globals), Ok(())); - assert_ne!(check_layout_compatibility_with_globals(inter1, inter0, &globals), Ok(())); + assert_eq!( + check_layout_compatibility_with_globals(inter0, inter1, &globals), + Ok(()) + ); + assert_ne!( + check_layout_compatibility_with_globals(inter1, inter0, &globals), + Ok(()) + ); } - - #[cfg(not(miri))] #[test] -fn check_impld_traits_subsets(){ - let list=vec![ +fn check_impld_traits_subsets() { + let list = vec![ as StableAbi>::LAYOUT, as StableAbi>::LAYOUT, as StableAbi>::LAYOUT, as StableAbi>::LAYOUT, ]; - check_subsets(&list,|errs|{ - assert!( - errs + check_subsets(&list, |errs| { + assert!(errs .iter() - .any(|err| matches!(err, AbiInstability::ExtraCheckError{..})) - ); + .any(|err| matches!(err, AbiInstability::ExtraCheckError { .. }))); }) } #[cfg(miri)] #[test] -fn check_impld_traits_subsets(){ - let globals=CheckingGlobals::new(); +fn check_impld_traits_subsets() { + let globals = CheckingGlobals::new(); let inter0 = as StableAbi>::LAYOUT; let inter1 = as StableAbi>::LAYOUT; - assert_eq!(check_layout_compatibility_with_globals(inter0, inter1, &globals), Ok(())); - assert_ne!(check_layout_compatibility_with_globals(inter1, inter0, &globals), Ok(())); + assert_eq!( + check_layout_compatibility_with_globals(inter0, inter1, &globals), + Ok(()) + ); + assert_ne!( + check_layout_compatibility_with_globals(inter1, inter0, &globals), + Ok(()) + ); } - - #[test] -fn exhaustiveness(){ - let globals=CheckingGlobals::new(); +fn exhaustiveness() { + let globals = CheckingGlobals::new(); - let unwrapped=::LAYOUT; - let wrapped= as StableAbi>::LAYOUT; + let unwrapped = ::LAYOUT; + let wrapped = as StableAbi>::LAYOUT; - for (l,r) in vec![ (unwrapped,wrapped), (wrapped,unwrapped) ] { + for (l, r) in vec![(unwrapped, wrapped), (wrapped, unwrapped)] { check_layout_compatibility_with_globals(l, r, &globals) .unwrap_err() .flatten_errors() .iter() - .any(|err| matches!(err, AbiInstability::MismatchedExhaustiveness{..})); + .any(|err| matches!(err, AbiInstability::MismatchedExhaustiveness { .. })); } } - #[test] -fn mismatched_discriminant(){ - let globals=CheckingGlobals::new(); +fn mismatched_discriminant() { + let globals = CheckingGlobals::new(); - let regular = as StableAbi>::LAYOUT; - let mismatched= + let regular = as StableAbi>::LAYOUT; + let mismatched = as StableAbi>::LAYOUT; - + check_layout_compatibility_with_globals(regular, mismatched, &globals) .unwrap_err() .flatten_errors() .iter() - .any(|err| matches!(err, AbiInstability::EnumDiscriminant{..})); + .any(|err| matches!(err, AbiInstability::EnumDiscriminant { .. })); } - #[test] -fn check_storage_unstorable(){ - let globals=CheckingGlobals::new(); +fn check_storage_unstorable() { + let globals = CheckingGlobals::new(); - let abi_a= as StableAbi>::LAYOUT; + let abi_a = as StableAbi>::LAYOUT; #[cfg(not(miri))] - let abi_b= as StableAbi>::LAYOUT; - let abi_large= as StableAbi>::LAYOUT; + let abi_b = as StableAbi>::LAYOUT; + let abi_large = as StableAbi>::LAYOUT; #[cfg(not(miri))] - let checks=vec![ - (abi_a,abi_large), - (abi_b,abi_large), - (abi_large,abi_large), - (abi_large,abi_a), - (abi_large,abi_b), + let checks = vec![ + (abi_a, abi_large), + (abi_b, abi_large), + (abi_large, abi_large), + (abi_large, abi_a), + (abi_large, abi_b), ]; #[cfg(miri)] - let checks=vec![ - (abi_a,abi_large), - ]; + let checks = vec![(abi_a, abi_large)]; - for (l,r) in checks { + for (l, r) in checks { check_layout_compatibility_with_globals(l, r, &globals) .unwrap_err() .flatten_errors() .iter() - .any(|err| matches!(err, AbiInstability::IncompatibleWithNonExhaustive{..})); + .any(|err| matches!(err, AbiInstability::IncompatibleWithNonExhaustive { .. })); } } - #[test] -fn incompatible_overlapping_variants(){ - let abi_one= as StableAbi>::LAYOUT; - let abi_a= as StableAbi>::LAYOUT; - let abi_b= as StableAbi>::LAYOUT; - let abi_c= as StableAbi>::LAYOUT; - let abi_c_mf= as StableAbi>::LAYOUT; - - fn unwrap_the_err(errs:Result<(), AbiInstabilityErrors>){ - let mut found_mismatch=false; +fn incompatible_overlapping_variants() { + let abi_one = as StableAbi>::LAYOUT; + let abi_a = as StableAbi>::LAYOUT; + let abi_b = as StableAbi>::LAYOUT; + let abi_c = as StableAbi>::LAYOUT; + let abi_c_mf = as StableAbi>::LAYOUT; + + fn unwrap_the_err(errs: Result<(), AbiInstabilityErrors>) { + let mut found_mismatch = false; for e in errs.clone().unwrap_err().flatten_errors().into_iter() { - if let AbiInstability::Name(ef)=&e { - found_mismatch=true; - for full_type in vec![&ef.expected,&ef.found] { + if let AbiInstability::Name(ef) = &e { + found_mismatch = true; + for full_type in vec![&ef.expected, &ef.found] { assert!( - full_type.name()=="RVec"|| - full_type.name()=="RString", + full_type.name() == "RVec" || full_type.name() == "RString", "err:{:?}", e ); } } } - assert!(found_mismatch,"errs:{:#?}",errs); + assert!(found_mismatch, "errs:{:#?}", errs); } #[cfg(not(miri))] { - let globals=CheckingGlobals::new(); - check_layout_compatibility_with_globals(abi_a,abi_b,&globals).unwrap(); - check_layout_compatibility_with_globals(abi_b,abi_c,&globals).unwrap(); - check_layout_compatibility_with_globals(abi_b,abi_c_mf,&globals) - .piped(unwrap_the_err); + let globals = CheckingGlobals::new(); + check_layout_compatibility_with_globals(abi_a, abi_b, &globals).unwrap(); + check_layout_compatibility_with_globals(abi_b, abi_c, &globals).unwrap(); + check_layout_compatibility_with_globals(abi_b, abi_c_mf, &globals).piped(unwrap_the_err); } { - let globals=CheckingGlobals::new(); - check_layout_compatibility_with_globals(abi_a,abi_b,&globals).unwrap(); - - check_layout_compatibility_with_globals(abi_b,abi_c_mf,&globals).unwrap(); - - check_layout_compatibility_with_globals(abi_b,abi_c,&globals) - .piped(unwrap_the_err); + let globals = CheckingGlobals::new(); + check_layout_compatibility_with_globals(abi_a, abi_b, &globals).unwrap(); + + check_layout_compatibility_with_globals(abi_b, abi_c_mf, &globals).unwrap(); + + check_layout_compatibility_with_globals(abi_b, abi_c, &globals).piped(unwrap_the_err); } #[cfg(not(miri))] { - let globals=CheckingGlobals::new(); - check_layout_compatibility_with_globals(abi_one,abi_c,&globals).unwrap(); - assert_eq!(globals.nonexhaustive_map.lock().unwrap().value_len(),1); - check_layout_compatibility_with_globals(abi_a,abi_b,&globals).unwrap(); - assert_eq!(globals.nonexhaustive_map.lock().unwrap().value_len(),2); - check_layout_compatibility_with_globals(abi_one,abi_a,&globals).unwrap(); - assert_eq!(globals.nonexhaustive_map.lock().unwrap().value_len(),1); + let globals = CheckingGlobals::new(); + check_layout_compatibility_with_globals(abi_one, abi_c, &globals).unwrap(); + assert_eq!(globals.nonexhaustive_map.lock().unwrap().value_len(), 1); + check_layout_compatibility_with_globals(abi_a, abi_b, &globals).unwrap(); + assert_eq!(globals.nonexhaustive_map.lock().unwrap().value_len(), 2); + check_layout_compatibility_with_globals(abi_one, abi_a, &globals).unwrap(); + assert_eq!(globals.nonexhaustive_map.lock().unwrap().value_len(), 1); } -} \ No newline at end of file +} diff --git a/abi_stable/tests/layout_tests/pointer_types.rs b/abi_stable/tests/layout_tests/pointer_types.rs index b3e55ded..35f313a5 100644 --- a/abi_stable/tests/layout_tests/pointer_types.rs +++ b/abi_stable/tests/layout_tests/pointer_types.rs @@ -1,14 +1,11 @@ // Types to test use abi_stable::{ - for_examples::{Module_Ref, Module_Prefix}, + for_examples::{Module_Prefix, Module_Ref}, prefix_type::PrefixRef, - sabi_types::{Constructor, MovePtr, RRef, NulStr, StaticRef}, + sabi_types::{Constructor, MovePtr, NulStr, RRef, StaticRef}, }; -use abi_stable::{ - reexports::True, - StableAbi, -}; +use abi_stable::{reexports::True, StableAbi}; use std::ptr::NonNull; @@ -30,19 +27,18 @@ where assert_eq!(std::mem::align_of::>(), PTR_ALIGN, "{}", name); } - #[cfg(not(miri))] #[test] fn test_nonnullable() { test_case::(); - + test_case::>(); - + test_case::>(); - test_case::>(); - test_case::>(); + test_case::>(); + test_case::>(); test_case::>(); test_case::>(); test_case::>(); -} \ No newline at end of file +} diff --git a/abi_stable/tests/layout_tests/prefix_types.rs b/abi_stable/tests/layout_tests/prefix_types.rs index dc3360f6..59f33672 100644 --- a/abi_stable/tests/layout_tests/prefix_types.rs +++ b/abi_stable/tests/layout_tests/prefix_types.rs @@ -1,37 +1,28 @@ #![allow(dead_code)] - - #[allow(unused_imports)] -use core_extensions::{ - matches, - SelfOps, -}; +use core_extensions::{matches, SelfOps}; -use rand::{ - thread_rng, - seq::SliceRandom, -}; +use rand::{seq::SliceRandom, thread_rng}; use abi_stable::{ - abi_stability::{ - abi_checking::{AbiInstability,CheckingGlobals,check_layout_compatibility_with_globals}, + abi_stability::abi_checking::{ + check_layout_compatibility_with_globals, AbiInstability, CheckingGlobals, }, - prefix_type::{__PrefixTypeMetadata,PrefixTypeTrait, WithMetadata}, - *, + prefix_type::{PrefixTypeTrait, WithMetadata, __PrefixTypeMetadata}, test_utils::{file_span, must_panic}, type_layout::TypeLayout, type_level::bools::*, + *, }; - -fn custom_default()->T -where T:From +fn custom_default() -> T +where + T: From, { 101.into() } - mod prefix0 { #[repr(C)] #[derive(abi_stable::StableAbi)] @@ -74,7 +65,7 @@ mod prefix2 { // Prefix types have to keep the same alignment when fields are added mod prefix2_misaligned { - #[repr(C,align(16))] + #[repr(C, align(16))] #[derive(abi_stable::StableAbi)] // #[sabi(debug_print)] #[sabi(kind(Prefix))] @@ -112,343 +103,310 @@ mod prefix3 { } } - /// Dereferences the TypeLayout of a `&T` to the layout of `T` -fn dereference_abi(abi:&'static TypeLayout)->&'static TypeLayout{ +fn dereference_abi(abi: &'static TypeLayout) -> &'static TypeLayout { abi.phantom_fields().get(0).unwrap().layout() } +static PREF_0: &'static TypeLayout = ::LAYOUT; +static PREF_1: &'static TypeLayout = ::LAYOUT; +static PREF_2: &'static TypeLayout = ::LAYOUT; +static PREF_3: &'static TypeLayout = ::LAYOUT; - -static PREF_0:&'static TypeLayout = ::LAYOUT; -static PREF_1:&'static TypeLayout = ::LAYOUT; -static PREF_2:&'static TypeLayout = ::LAYOUT; -static PREF_3:&'static TypeLayout = ::LAYOUT; - - -fn new_list()->Vec<&'static TypeLayout>{ +fn new_list() -> Vec<&'static TypeLayout> { vec![PREF_0, PREF_1, PREF_2, PREF_3] } -#[cfg_attr(not(miri),test)] +#[cfg_attr(not(miri), test)] fn prefixes_test() { let list = new_list(); - let mut rng=thread_rng(); + let mut rng = thread_rng(); fn gen_elem_from( - abi_wrapper:&'static TypeLayout - )->(&'static TypeLayout,__PrefixTypeMetadata){ - let prefix=abi_wrapper + abi_wrapper: &'static TypeLayout, + ) -> (&'static TypeLayout, __PrefixTypeMetadata) { + let prefix = abi_wrapper .piped(dereference_abi) .piped(__PrefixTypeMetadata::new); - (abi_wrapper,prefix) + (abi_wrapper, prefix) } - let mut gen_generation=|skip_first:usize|{ - let mut ret=Vec::<(&'static TypeLayout,__PrefixTypeMetadata)>::new(); + let mut gen_generation = |skip_first: usize| { + let mut ret = Vec::<(&'static TypeLayout, __PrefixTypeMetadata)>::new(); for _ in 0..list.len() { - let pushed=gen_elem_from(list.choose(&mut rng).unwrap().clone()); + let pushed = gen_elem_from(list.choose(&mut rng).unwrap().clone()); ret.push(pushed); } - let max_size=ret.iter().map(|(_,x)|x.fields.len()).max().unwrap(); + let max_size = ret.iter().map(|(_, x)| x.fields.len()).max().unwrap(); ret.extend( - list.iter().cloned() + list.iter() + .cloned() .skip(skip_first) .take(max_size) - .map(gen_elem_from) + .map(gen_elem_from), ); ret }; - for _ in 0..200{ - let globals=CheckingGlobals::new(); + for _ in 0..200 { + let globals = CheckingGlobals::new(); - let t_list=gen_generation(0); - let o_list=gen_generation(1); + let t_list = gen_generation(0); + let o_list = gen_generation(1); - for ((this,t_prefix),(other,o_prefix)) in + for ((this, t_prefix), (other, o_prefix)) in t_list.iter().cloned().zip(o_list.iter().cloned()) { - let prefix_type_map=globals.prefix_type_map.lock().unwrap(); - let value_len=prefix_type_map.value_len(); - let key_len=prefix_type_map.key_len(); - // Not dropping it here causes a deadlock inside + let prefix_type_map = globals.prefix_type_map.lock().unwrap(); + let value_len = prefix_type_map.value_len(); + let key_len = prefix_type_map.key_len(); + // Not dropping it here causes a deadlock inside // check_layout_compatibility_with_globals. drop(prefix_type_map); - let res = check_layout_compatibility_with_globals(this, other,&globals); + let res = check_layout_compatibility_with_globals(this, other, &globals); - let prefix_type_map=globals.prefix_type_map.lock().unwrap(); + let prefix_type_map = globals.prefix_type_map.lock().unwrap(); if t_prefix.fields.len() <= o_prefix.fields.len() { - res.unwrap_or_else(|e| panic!("{:#?}",e) ); - + res.unwrap_or_else(|e| panic!("{:#?}", e)); - let deref_this=dereference_abi(this); - let deref_other=dereference_abi(other); - let t_id=deref_this.get_utypeid(); - let o_id=deref_other.get_utypeid(); + let deref_this = dereference_abi(this); + let deref_other = dereference_abi(other); + let t_id = deref_this.get_utypeid(); + let o_id = deref_other.get_utypeid(); - let t_map_prefix=prefix_type_map.get(&t_id); - let o_map_prefix=prefix_type_map.get(&o_id); + let t_map_prefix = prefix_type_map.get(&t_id); + let o_map_prefix = prefix_type_map.get(&o_id); - let t_map_prefix=t_map_prefix.unwrap(); - let o_map_prefix=o_map_prefix.unwrap(); + let t_map_prefix = t_map_prefix.unwrap(); + let o_map_prefix = o_map_prefix.unwrap(); - for pre in vec![o_prefix.clone(),t_map_prefix.clone(),o_map_prefix.clone()] { - assert_eq!( - t_prefix.prefix_field_count, - pre.prefix_field_count, - ); - for (l_field,r_field) in - t_prefix.fields.iter().zip(pre.fields.iter()) - { - assert_eq!(l_field,r_field); + for pre in vec![o_prefix.clone(), t_map_prefix.clone(), o_map_prefix.clone()] { + assert_eq!(t_prefix.prefix_field_count, pre.prefix_field_count,); + for (l_field, r_field) in t_prefix.fields.iter().zip(pre.fields.iter()) { + assert_eq!(l_field, r_field); } } - assert!(t_prefix.fields.len()<=t_map_prefix.fields.len()); - assert!(o_prefix.fields.len()<=o_map_prefix.fields.len()); + assert!(t_prefix.fields.len() <= t_map_prefix.fields.len()); + assert!(o_prefix.fields.len() <= o_map_prefix.fields.len()); - assert_eq!(t_map_prefix as *const _,o_map_prefix as *const _); + assert_eq!(t_map_prefix as *const _, o_map_prefix as *const _); } else { - assert_eq!(value_len,prefix_type_map.value_len()); - assert_eq!(key_len,prefix_type_map.key_len()); - + assert_eq!(value_len, prefix_type_map.value_len()); + assert_eq!(key_len, prefix_type_map.key_len()); + let errs = res.unwrap_err().flatten_errors(); - assert!( - errs.iter() - .any(|err| matches!(err, AbiInstability::FieldCountMismatch{..})), - ); + assert!(errs + .iter() + .any(|err| matches!(err, AbiInstability::FieldCountMismatch { .. })),); } } - let prefix_type_map=globals.prefix_type_map.lock().unwrap(); + let prefix_type_map = globals.prefix_type_map.lock().unwrap(); - let max_prefix=t_list.iter().zip(o_list.iter()) - .map(|((_,l_prefix),(_,r_prefix))| (l_prefix.clone(),r_prefix.clone()) ) - .filter(|(l,r)| l.fields.len() <= r.fields.len() ) - .map(|(l,r)| __PrefixTypeMetadata::max(l,r) ) - .max_by_key(|prefix| prefix.fields.len() ) + let max_prefix = t_list + .iter() + .zip(o_list.iter()) + .map(|((_, l_prefix), (_, r_prefix))| (l_prefix.clone(), r_prefix.clone())) + .filter(|(l, r)| l.fields.len() <= r.fields.len()) + .map(|(l, r)| __PrefixTypeMetadata::max(l, r)) + .max_by_key(|prefix| prefix.fields.len()) .unwrap(); // Asserting that the layout they all map to is the one with the most fields for this in list.iter().cloned() { - let id=dereference_abi(this).get_utypeid(); + let id = dereference_abi(this).get_utypeid(); // The random sanpling did not include this type. - let prefix=match prefix_type_map.get(&id) { - Some(x)=>x, - None=>continue, + let prefix = match prefix_type_map.get(&id) { + Some(x) => x, + None => continue, }; - for (l_field,r_field) in prefix.fields.iter().zip(max_prefix.fields.iter()) { - assert_eq!(l_field,r_field); + for (l_field, r_field) in prefix.fields.iter().zip(max_prefix.fields.iter()) { + assert_eq!(l_field, r_field); } - assert_eq!( - prefix.fields.len(), - max_prefix.fields.len(), - ); + assert_eq!(prefix.fields.len(), max_prefix.fields.len(),); } } } - fn check_interface_impl_pair( - globals:&CheckingGlobals, - this :&'static TypeLayout, - other:&'static TypeLayout, -){ - let deref_this=dereference_abi(this); - let deref_other=dereference_abi(other); + globals: &CheckingGlobals, + this: &'static TypeLayout, + other: &'static TypeLayout, +) { + let deref_this = dereference_abi(this); + let deref_other = dereference_abi(other); - let t_prefix=__PrefixTypeMetadata::new(deref_this); - let o_prefix=__PrefixTypeMetadata::new(deref_other); + let t_prefix = __PrefixTypeMetadata::new(deref_this); + let o_prefix = __PrefixTypeMetadata::new(deref_other); - if let Err(e)=check_layout_compatibility_with_globals(this,other,&globals) { + if let Err(e) = check_layout_compatibility_with_globals(this, other, &globals) { if t_prefix.fields.len() <= o_prefix.fields.len() { - panic!("{:#?}",e); - }else{ + panic!("{:#?}", e); + } else { return; } } - let prefix_type_map=globals.prefix_type_map.lock().unwrap(); - + let prefix_type_map = globals.prefix_type_map.lock().unwrap(); - let t_id=deref_this.get_utypeid(); - let o_id=deref_other.get_utypeid(); + let t_id = deref_this.get_utypeid(); + let o_id = deref_other.get_utypeid(); - let t_map_prefix=prefix_type_map.get(&t_id); - let o_map_prefix=prefix_type_map.get(&o_id); + let t_map_prefix = prefix_type_map.get(&t_id); + let o_map_prefix = prefix_type_map.get(&o_id); + let t_map_prefix = t_map_prefix.unwrap(); + let o_map_prefix = o_map_prefix.unwrap(); - let t_map_prefix=t_map_prefix.unwrap(); - let o_map_prefix=o_map_prefix.unwrap(); - - for pre in vec![o_prefix.clone(),t_map_prefix.clone(),o_map_prefix.clone()] { - assert_eq!( - t_prefix.prefix_field_count, - pre.prefix_field_count, - ); - for (field_i,(l_field,r_field)) in - t_prefix.fields.iter().zip(pre.fields.iter()).enumerate() + for pre in vec![o_prefix.clone(), t_map_prefix.clone(), o_map_prefix.clone()] { + assert_eq!(t_prefix.prefix_field_count, pre.prefix_field_count,); + for (field_i, (l_field, r_field)) in + t_prefix.fields.iter().zip(pre.fields.iter()).enumerate() { if t_prefix.accessible_fields.is_accessible(field_i) - &&o_prefix.accessible_fields.is_accessible(field_i) + && o_prefix.accessible_fields.is_accessible(field_i) { - assert_eq!(l_field,r_field,"\nleft:{:#?}\n\nright:{:#?}\n",l_field,r_field); + assert_eq!( + l_field, r_field, + "\nleft:{:#?}\n\nright:{:#?}\n", + l_field, r_field + ); } } } - assert!(t_prefix.fields.len()<=t_map_prefix.fields.len()); - assert!(o_prefix.fields.len()<=o_map_prefix.fields.len()); + assert!(t_prefix.fields.len() <= t_map_prefix.fields.len()); + assert!(o_prefix.fields.len() <= o_map_prefix.fields.len()); - assert_eq!(t_map_prefix as *const _,o_map_prefix as *const _); + assert_eq!(t_map_prefix as *const _, o_map_prefix as *const _); } +#[cfg_attr(not(miri), test)] +fn hierarchical_prefix_test() { + let library_00 = PREF_2; + let library_01 = PREF_1; + let library_02 = PREF_0; -#[cfg_attr(not(miri),test)] -fn hierarchical_prefix_test(){ - let library_00=PREF_2; - let library_01=PREF_1; - let library_02=PREF_0; + let library_10 = PREF_2; + let library_11 = PREF_2; + let library_12 = PREF_3; - let library_10=PREF_2; - let library_11=PREF_2; - let library_12=PREF_3; + let library_0 = PREF_0; + let library_1 = PREF_1; - let library_0=PREF_0; - let library_1=PREF_1; + let binary = PREF_0; - let binary=PREF_0; - - let mut rng=thread_rng(); + let mut rng = thread_rng(); for _ in 0..100 { - let globals=CheckingGlobals::new(); - let mut checks=vec![ - (binary,library_0), - (binary,library_1), - (library_0,library_00), - (library_0,library_01), - (library_0,library_02), - (library_1,library_10), - (library_1,library_11), - (library_1,library_12), + let globals = CheckingGlobals::new(); + let mut checks = vec![ + (binary, library_0), + (binary, library_1), + (library_0, library_00), + (library_0, library_01), + (library_0, library_02), + (library_1, library_10), + (library_1, library_11), + (library_1, library_12), ]; checks.shuffle(&mut rng); - for (this,other) in checks { - check_interface_impl_pair(&globals,this,other); + for (this, other) in checks { + check_interface_impl_pair(&globals, this, other); } } } - -#[cfg_attr(not(miri),test)] -fn prefix_is_same_alignment(){ - let globals=CheckingGlobals::new(); +#[cfg_attr(not(miri), test)] +fn prefix_is_same_alignment() { + let globals = CheckingGlobals::new(); let misaligned = ::LAYOUT; - for pref in vec![ PREF_0,PREF_1 ] { - let errs = check_layout_compatibility_with_globals(pref, misaligned,&globals) + for pref in vec![PREF_0, PREF_1] { + let errs = check_layout_compatibility_with_globals(pref, misaligned, &globals) .unwrap_err() .flatten_errors(); - assert!( - errs + assert!(errs .iter() - .any(|err| matches!(err, AbiInstability::Alignment{..})) - ); + .any(|err| matches!(err, AbiInstability::Alignment { .. }))); } } - -#[cfg_attr(not(miri),test)] -fn prefix_is_same_size(){ - let globals=CheckingGlobals::new(); - let list=new_list(); +#[cfg_attr(not(miri), test)] +fn prefix_is_same_size() { + let globals = CheckingGlobals::new(); + let list = new_list(); for pref in list.iter().cloned() { - let mismatched_prefix=::LAYOUT; - let errs = check_layout_compatibility_with_globals(pref,mismatched_prefix ,&globals) + let mismatched_prefix = ::LAYOUT; + let errs = check_layout_compatibility_with_globals(pref, mismatched_prefix, &globals) .unwrap_err() .flatten_errors(); - assert!( - errs + assert!(errs .iter() - .any(|err| matches!(err, AbiInstability::MismatchedPrefixSize{..})) - ); + .any(|err| matches!(err, AbiInstability::MismatchedPrefixSize { .. }))); } } - - -#[cfg_attr(not(miri),test)] +#[cfg_attr(not(miri), test)] fn prefix_on_nonexistent_field() { - - pub const MOD_VAL: &WithMetadata = &WithMetadata::new( - PrefixTypeTrait::METADATA, - prefix0::Prefix{ - field0:1, - }, - ); + pub const MOD_VAL: &WithMetadata = + &WithMetadata::new(PrefixTypeTrait::METADATA, prefix0::Prefix { field0: 1 }); let prefix0 = MOD_VAL.static_as_prefix(); { - let value1:prefix1::Prefix_Ref=unsafe{ std::mem::transmute(prefix0) }; - assert_eq!(value1.field0(),1); - assert_eq!(value1.field1(),custom_default::()); + let value1: prefix1::Prefix_Ref = unsafe { std::mem::transmute(prefix0) }; + assert_eq!(value1.field0(), 1); + assert_eq!(value1.field1(), custom_default::()); } { - let value2:prefix2::Prefix_Ref=unsafe{ std::mem::transmute(prefix0) }; - assert_eq!(value2.field0(),1); - assert_eq!(value2.field1(),0); - assert_eq!(value2.field2(),0); + let value2: prefix2::Prefix_Ref = unsafe { std::mem::transmute(prefix0) }; + assert_eq!(value2.field0(), 1); + assert_eq!(value2.field1(), 0); + assert_eq!(value2.field2(), 0); } { - let value3:prefix3::Prefix_Ref=unsafe{ std::mem::transmute(prefix0) }; - assert_eq!(value3.field0(),1); - must_panic(file_span!(),||value3.field1()).unwrap(); - must_panic(file_span!(),||value3.field2()).unwrap(); - must_panic(file_span!(),||value3.field3()).unwrap(); + let value3: prefix3::Prefix_Ref = unsafe { std::mem::transmute(prefix0) }; + assert_eq!(value3.field0(), 1); + must_panic(file_span!(), || value3.field1()).unwrap(); + must_panic(file_span!(), || value3.field2()).unwrap(); + must_panic(file_span!(), || value3.field3()).unwrap(); } } - - ///////////////////////////////////////////////////////////////////////// - - -pub trait EnabledFields{ - const ENABLE_FIELD_0:bool=true; - const ENABLE_FIELD_1:bool=true; - const ENABLE_FIELD_2:bool=true; - const ENABLE_FIELD_3:bool=true; +pub trait EnabledFields { + const ENABLE_FIELD_0: bool = true; + const ENABLE_FIELD_1: bool = true; + const ENABLE_FIELD_2: bool = true; + const ENABLE_FIELD_3: bool = true; } - -impl EnabledFields for (B0,B1,B2,B3) +impl EnabledFields for (B0, B1, B2, B3) where - B0:Boolean, - B1:Boolean, - B2:Boolean, - B3:Boolean, + B0: Boolean, + B1: Boolean, + B2: Boolean, + B3: Boolean, { - const ENABLE_FIELD_0:bool=::VALUE; - const ENABLE_FIELD_1:bool=::VALUE; - const ENABLE_FIELD_2:bool=::VALUE; - const ENABLE_FIELD_3:bool=::VALUE; + const ENABLE_FIELD_0: bool = ::VALUE; + const ENABLE_FIELD_1: bool = ::VALUE; + const ENABLE_FIELD_2: bool = ::VALUE; + const ENABLE_FIELD_3: bool = ::VALUE; } - macro_rules! declare_enabled_fields { - ( + ( $struct:ident { $($trait_definition:tt)* } @@ -461,7 +419,7 @@ macro_rules! declare_enabled_fields { } } -declare_enabled_fields!{ +declare_enabled_fields! { ACCESSIBLE_ALL { const ENABLE_FIELD_0:bool=true; const ENABLE_FIELD_1:bool=true; @@ -470,7 +428,7 @@ declare_enabled_fields!{ } } -declare_enabled_fields!{ +declare_enabled_fields! { ACCESSIBLE_ALL_EXCEPT_0 { const ENABLE_FIELD_0:bool=false; const ENABLE_FIELD_1:bool=true; @@ -479,7 +437,7 @@ declare_enabled_fields!{ } } -declare_enabled_fields!{ +declare_enabled_fields! { ACCESSIBLE_ALL_EXCEPT_1 { const ENABLE_FIELD_0:bool=true; const ENABLE_FIELD_1:bool=false; @@ -488,8 +446,7 @@ declare_enabled_fields!{ } } - -declare_enabled_fields!{ +declare_enabled_fields! { ACCESSIBLE_ALL_EXCEPT_2 { const ENABLE_FIELD_0:bool=true; const ENABLE_FIELD_1:bool=true; @@ -498,8 +455,7 @@ declare_enabled_fields!{ } } - -declare_enabled_fields!{ +declare_enabled_fields! { ACCESSIBLE_ALL_EXCEPT_3 { const ENABLE_FIELD_0:bool=true; const ENABLE_FIELD_1:bool=true; @@ -508,186 +464,172 @@ declare_enabled_fields!{ } } -static COND_FIELD_0_ALL:&'static TypeLayout = - >::LAYOUT; - -static COND_FIELD_1_ALL:&'static TypeLayout = - >::LAYOUT; +static COND_FIELD_0_ALL: &'static TypeLayout = >::LAYOUT; -static COND_FIELD_2_ALL:&'static TypeLayout = - >::LAYOUT; +static COND_FIELD_1_ALL: &'static TypeLayout = >::LAYOUT; -static COND_FIELD_3_ALL:&'static TypeLayout = - >::LAYOUT; +static COND_FIELD_2_ALL: &'static TypeLayout = >::LAYOUT; +static COND_FIELD_3_ALL: &'static TypeLayout = >::LAYOUT; -static COND_FIELD_0_EXCEPT_0:&'static TypeLayout = +static COND_FIELD_0_EXCEPT_0: &'static TypeLayout = >::LAYOUT; -static COND_FIELD_1_EXCEPT_0:&'static TypeLayout = +static COND_FIELD_1_EXCEPT_0: &'static TypeLayout = >::LAYOUT; -static COND_FIELD_2_EXCEPT_0:&'static TypeLayout = +static COND_FIELD_2_EXCEPT_0: &'static TypeLayout = >::LAYOUT; -static COND_FIELD_3_EXCEPT_0:&'static TypeLayout = +static COND_FIELD_3_EXCEPT_0: &'static TypeLayout = >::LAYOUT; - -static COND_FIELD_1_EXCEPT_1:&'static TypeLayout = +static COND_FIELD_1_EXCEPT_1: &'static TypeLayout = >::LAYOUT; -static COND_FIELD_2_EXCEPT_1:&'static TypeLayout = +static COND_FIELD_2_EXCEPT_1: &'static TypeLayout = >::LAYOUT; -static COND_FIELD_3_EXCEPT_1:&'static TypeLayout = +static COND_FIELD_3_EXCEPT_1: &'static TypeLayout = >::LAYOUT; - -static COND_FIELD_2_EXCEPT_2:&'static TypeLayout = +static COND_FIELD_2_EXCEPT_2: &'static TypeLayout = >::LAYOUT; -static COND_FIELD_3_EXCEPT_2:&'static TypeLayout = +static COND_FIELD_3_EXCEPT_2: &'static TypeLayout = >::LAYOUT; - -static COND_FIELD_3_EXCEPT_3:&'static TypeLayout = +static COND_FIELD_3_EXCEPT_3: &'static TypeLayout = >::LAYOUT; - - - - - - mod cond_fields_0 { - use abi_stable::marker_type::UnsafeIgnoredType; use super::EnabledFields; + use abi_stable::marker_type::UnsafeIgnoredType; #[repr(C)] #[derive(abi_stable::StableAbi)] #[sabi( kind(Prefix), - prefix_bound="C:EnabledFields", - unsafe_unconstrained(C), + prefix_bound = "C:EnabledFields", + unsafe_unconstrained(C) )] pub struct Prefix { - pub _marker:UnsafeIgnoredType, - #[sabi(accessible_if=" ::ENABLE_FIELD_0 ")] + pub _marker: UnsafeIgnoredType, + #[sabi(accessible_if = " ::ENABLE_FIELD_0 ")] #[sabi(last_prefix_field)] pub field0: u8, } } mod cond_fields_1 { - use abi_stable::marker_type::UnsafeIgnoredType; use super::EnabledFields; - + use abi_stable::marker_type::UnsafeIgnoredType; + #[repr(C)] #[derive(abi_stable::StableAbi)] #[sabi( kind(Prefix), - prefix_bound="C:EnabledFields", - unsafe_unconstrained(C), + prefix_bound = "C:EnabledFields", + unsafe_unconstrained(C) )] - pub struct Prefix { - pub _marker:UnsafeIgnoredType, - - #[sabi(accessible_if=" ::ENABLE_FIELD_0 ")] - #[sabi(accessor_bound="Copy")] + pub struct Prefix { + pub _marker: UnsafeIgnoredType, + + #[sabi(accessible_if = " ::ENABLE_FIELD_0 ")] + #[sabi(accessor_bound = "Copy")] #[sabi(last_prefix_field)] pub field0: T, - - #[sabi(accessible_if=" ::ENABLE_FIELD_1 ")] - #[sabi(accessor_bound="Copy")] + + #[sabi(accessible_if = " ::ENABLE_FIELD_1 ")] + #[sabi(accessor_bound = "Copy")] pub field1: U, } } mod cond_fields_2 { - use abi_stable::marker_type::UnsafeIgnoredType; use super::EnabledFields; + use abi_stable::marker_type::UnsafeIgnoredType; #[repr(C)] #[derive(abi_stable::StableAbi)] #[sabi( kind(Prefix), - prefix_bound="C:EnabledFields", - unsafe_unconstrained(C), + prefix_bound = "C:EnabledFields", + unsafe_unconstrained(C) )] - pub struct Prefix { - pub _marker:UnsafeIgnoredType, - - #[sabi(accessible_if=" ::ENABLE_FIELD_0 ")] + pub struct Prefix { + pub _marker: UnsafeIgnoredType, + + #[sabi(accessible_if = " ::ENABLE_FIELD_0 ")] #[sabi(last_prefix_field)] - #[sabi(accessor_bound="Copy")] + #[sabi(accessor_bound = "Copy")] pub field0: T, - - #[sabi(accessible_if=" ::ENABLE_FIELD_1 ")] - #[sabi(accessor_bound="Copy")] + + #[sabi(accessible_if = " ::ENABLE_FIELD_1 ")] + #[sabi(accessor_bound = "Copy")] pub field1: U, - - #[sabi(accessible_if=" ::ENABLE_FIELD_2 ")] - #[sabi(accessor_bound="Copy")] + + #[sabi(accessible_if = " ::ENABLE_FIELD_2 ")] + #[sabi(accessor_bound = "Copy")] pub field2: V, } } // Prefix types have to keep the same alignment when fields are added mod cond_fields_2_misaligned { - use abi_stable::marker_type::UnsafeIgnoredType; use super::EnabledFields; - #[repr(C,align(16))] + use abi_stable::marker_type::UnsafeIgnoredType; + #[repr(C, align(16))] #[derive(abi_stable::StableAbi)] #[sabi( kind(Prefix), - prefix_bound="C:EnabledFields", - unsafe_unconstrained(C), + prefix_bound = "C:EnabledFields", + unsafe_unconstrained(C) )] pub struct Prefix { - pub _marker:UnsafeIgnoredType, - - #[sabi(accessible_if=" ::ENABLE_FIELD_0 ")] + pub _marker: UnsafeIgnoredType, + + #[sabi(accessible_if = " ::ENABLE_FIELD_0 ")] #[sabi(last_prefix_field)] pub field0: u8, - - #[sabi(accessible_if=" ::ENABLE_FIELD_1 ")] + + #[sabi(accessible_if = " ::ENABLE_FIELD_1 ")] pub field1: u16, - - #[sabi(accessible_if=" ::ENABLE_FIELD_2 ")] + + #[sabi(accessible_if = " ::ENABLE_FIELD_2 ")] pub field2: u32, } } mod cond_fields_2_different_prefix { - use abi_stable::marker_type::UnsafeIgnoredType; use super::EnabledFields; + use abi_stable::marker_type::UnsafeIgnoredType; #[repr(C)] #[derive(abi_stable::StableAbi)] #[sabi( kind(Prefix), - prefix_bound="C:EnabledFields", - unsafe_unconstrained(C), + prefix_bound = "C:EnabledFields", + unsafe_unconstrained(C) )] - pub struct Prefix { - pub _marker:UnsafeIgnoredType, - - #[sabi(accessible_if=" ::ENABLE_FIELD_0 ")] - #[sabi(accessor_bound="Copy")] + pub struct Prefix { + pub _marker: UnsafeIgnoredType, + + #[sabi(accessible_if = " ::ENABLE_FIELD_0 ")] + #[sabi(accessor_bound = "Copy")] pub field0: T, - - #[sabi(accessible_if=" ::ENABLE_FIELD_1 ")] + + #[sabi(accessible_if = " ::ENABLE_FIELD_1 ")] #[sabi(last_prefix_field)] - #[sabi(accessor_bound="Copy")] + #[sabi(accessor_bound = "Copy")] pub field1: U, - - #[sabi(accessible_if=" ::ENABLE_FIELD_2 ")] - #[sabi(accessor_bound="Copy")] + + #[sabi(accessible_if = " ::ENABLE_FIELD_2 ")] + #[sabi(accessor_bound = "Copy")] pub field2: V, } } mod cond_fields_3 { - use abi_stable::marker_type::UnsafeIgnoredType; use super::EnabledFields; + use abi_stable::marker_type::UnsafeIgnoredType; #[repr(C)] #[derive(abi_stable::StableAbi)] #[sabi( @@ -696,31 +638,31 @@ mod cond_fields_3 { prefix_bound="C:EnabledFields", unsafe_unconstrained(C), )] - pub struct Prefix { - pub _marker:UnsafeIgnoredType<(C,T,U,V,W)>, - - #[sabi(accessible_if=" ::ENABLE_FIELD_0 ")] + pub struct Prefix { + pub _marker: UnsafeIgnoredType<(C, T, U, V, W)>, + + #[sabi(accessible_if = " ::ENABLE_FIELD_0 ")] #[sabi(last_prefix_field)] - #[sabi(accessor_bound="Copy")] + #[sabi(accessor_bound = "Copy")] pub field0: T, - - #[sabi(accessible_if=" ::ENABLE_FIELD_1 ")] - #[sabi(accessor_bound="Copy")] + + #[sabi(accessible_if = " ::ENABLE_FIELD_1 ")] + #[sabi(accessor_bound = "Copy")] pub field1: U, - - #[sabi(accessible_if=" ::ENABLE_FIELD_2 ")] - #[sabi(accessor_bound="Copy")] + + #[sabi(accessible_if = " ::ENABLE_FIELD_2 ")] + #[sabi(accessor_bound = "Copy")] pub field2: V, - - #[sabi(accessible_if=" ::ENABLE_FIELD_3 ")] - #[sabi(accessor_bound="Copy")] + + #[sabi(accessible_if = " ::ENABLE_FIELD_3 ")] + #[sabi(accessor_bound = "Copy")] pub field3: W, } } mod cond_fields_3_uncond_prefix { - use abi_stable::marker_type::UnsafeIgnoredType; use super::EnabledFields; + use abi_stable::marker_type::UnsafeIgnoredType; #[repr(C)] #[derive(abi_stable::StableAbi)] #[sabi( @@ -729,180 +671,165 @@ mod cond_fields_3_uncond_prefix { prefix_bound="C:EnabledFields", unsafe_unconstrained(C), )] - pub struct Prefix { - pub _marker:UnsafeIgnoredType<(C,T,U,V,W)>, - + pub struct Prefix { + pub _marker: UnsafeIgnoredType<(C, T, U, V, W)>, + #[sabi(last_prefix_field)] - #[sabi(accessor_bound="Copy")] + #[sabi(accessor_bound = "Copy")] pub field0: T, - - #[sabi(accessible_if=" ::ENABLE_FIELD_1 ")] - #[sabi(accessor_bound="Copy")] + + #[sabi(accessible_if = " ::ENABLE_FIELD_1 ")] + #[sabi(accessor_bound = "Copy")] pub field1: U, - - #[sabi(accessible_if=" ::ENABLE_FIELD_2 ")] - #[sabi(accessor_bound="Copy")] + + #[sabi(accessible_if = " ::ENABLE_FIELD_2 ")] + #[sabi(accessor_bound = "Copy")] pub field2: V, - - #[sabi(accessible_if=" ::ENABLE_FIELD_3 ")] - #[sabi(accessor_bound="Copy")] + + #[sabi(accessible_if = " ::ENABLE_FIELD_3 ")] + #[sabi(accessor_bound = "Copy")] pub field3: W, } } +#[cfg_attr(not(miri), test)] +fn prefix_cond_field_test() { + let mut rng = thread_rng(); + use abi_stable::type_level::bools::{False as F, True as T}; -#[cfg_attr(not(miri),test)] -fn prefix_cond_field_test(){ - let mut rng=thread_rng(); - - use abi_stable::type_level::bools::{True as T,False as F}; - - use self::cond_fields_2::Prefix_Ref as Prefix2; - use self::cond_fields_3::Prefix_Ref as Prefix3; - use self::cond_fields_3_uncond_prefix::Prefix_Ref as Prefix3UncondPrefix; + use self::{ + cond_fields_2::Prefix_Ref as Prefix2, cond_fields_3::Prefix_Ref as Prefix3, + cond_fields_3_uncond_prefix::Prefix_Ref as Prefix3UncondPrefix, + }; - type au32=[u32;1]; - type ai32=[i32;1]; + type au32 = [u32; 1]; + type ai32 = [i32; 1]; - let mut valid_lists=vec![ + let mut valid_lists = vec![ vec![ - >::LAYOUT, - >::LAYOUT, - >::LAYOUT, - >::LAYOUT, - >::LAYOUT, - >::LAYOUT, + >::LAYOUT, + >::LAYOUT, + >::LAYOUT, + >::LAYOUT, + >::LAYOUT, + >::LAYOUT, ], vec![ - >::LAYOUT, - >::LAYOUT, - >::LAYOUT, - >::LAYOUT, - >::LAYOUT, - >::LAYOUT, - >::LAYOUT, + >::LAYOUT, + >::LAYOUT, + >::LAYOUT, + >::LAYOUT, + >::LAYOUT, + >::LAYOUT, + >::LAYOUT, ], vec![ - >::LAYOUT, - >::LAYOUT, - >::LAYOUT, - >::LAYOUT, + >::LAYOUT, + >::LAYOUT, + >::LAYOUT, + >::LAYOUT, ], ]; - - let invalid=vec![ + let invalid = vec![ ( - >::LAYOUT, - >::LAYOUT, + >::LAYOUT, + >::LAYOUT, ), ( - >::LAYOUT, - >::LAYOUT, + >::LAYOUT, + >::LAYOUT, ), ( - >::LAYOUT, - >::LAYOUT, + >::LAYOUT, + >::LAYOUT, ), ( - >::LAYOUT, - >::LAYOUT, + >::LAYOUT, + >::LAYOUT, ), ( - >::LAYOUT, - >::LAYOUT, + >::LAYOUT, + >::LAYOUT, ), ]; - for valid_list in &valid_lists { - let globals=CheckingGlobals::new(); + let globals = CheckingGlobals::new(); for window in valid_list.windows(2) { - check_interface_impl_pair(&globals,window[0],window[1]); + check_interface_impl_pair(&globals, window[0], window[1]); } } - for _ in 0..50{ + for _ in 0..50 { for valid_list in &mut valid_lists { - let globals=CheckingGlobals::new(); + let globals = CheckingGlobals::new(); valid_list.shuffle(&mut rng); for window in valid_list.windows(2) { - check_interface_impl_pair(&globals,window[0],window[1]); + check_interface_impl_pair(&globals, window[0], window[1]); } } } + const CHECKED_ERRORS: usize = 3; - const CHECKED_ERRORS:usize=3; - - - let mut err_counts=vec![0;CHECKED_ERRORS]; - + let mut err_counts = vec![0; CHECKED_ERRORS]; { - let mut inc_on_err=|conds:[bool;CHECKED_ERRORS]|->bool{ - let mut any=false; - for (i,&cond) in conds.iter().enumerate() { - any=any||cond; - err_counts[i]+=cond as usize; + let mut inc_on_err = |conds: [bool; CHECKED_ERRORS]| -> bool { + let mut any = false; + for (i, &cond) in conds.iter().enumerate() { + any = any || cond; + err_counts[i] += cond as usize; } any }; - let globals=CheckingGlobals::new(); - for (interf,impl_) in invalid { - let errs = check_layout_compatibility_with_globals(interf,impl_ ,&globals) + let globals = CheckingGlobals::new(); + for (interf, impl_) in invalid { + let errs = check_layout_compatibility_with_globals(interf, impl_, &globals) .unwrap_err() .flatten_errors(); - assert!( - errs - .iter() - .any(|e|{ - inc_on_err([ - matches!(e, AbiInstability::FieldCountMismatch{..}), - matches!(e, AbiInstability::Name{..}), - matches!(e, AbiInstability::MismatchedPrefixConditionality{..}), - ]) - }), - ); + assert!(errs.iter().any(|e| { + inc_on_err([ + matches!(e, AbiInstability::FieldCountMismatch { .. }), + matches!(e, AbiInstability::Name { .. }), + matches!(e, AbiInstability::MismatchedPrefixConditionality { .. }), + ]) + }),); } } assert!( - err_counts.iter().all(|&x| x!=0 ), + err_counts.iter().all(|&x| x != 0), "err_counts:{:#?}", err_counts, ); - } +#[cfg_attr(not(miri), test)] +fn hierarchical_prefix_cond_field_test() { + let mut rng = thread_rng(); -#[cfg_attr(not(miri),test)] -fn hierarchical_prefix_cond_field_test(){ - let mut rng=thread_rng(); - - let fields_0=vec![ - COND_FIELD_0_ALL, - COND_FIELD_0_EXCEPT_0, - ]; + let fields_0 = vec![COND_FIELD_0_ALL, COND_FIELD_0_EXCEPT_0]; - let fields_1=vec![ + let fields_1 = vec![ COND_FIELD_1_ALL, COND_FIELD_1_EXCEPT_0, COND_FIELD_1_EXCEPT_1, ]; - let fields_2=vec![ + let fields_2 = vec![ COND_FIELD_2_ALL, COND_FIELD_2_EXCEPT_0, COND_FIELD_2_EXCEPT_1, COND_FIELD_2_EXCEPT_2, ]; - let fields_3=vec![ + let fields_3 = vec![ COND_FIELD_3_ALL, COND_FIELD_3_EXCEPT_0, COND_FIELD_3_EXCEPT_1, @@ -911,158 +838,161 @@ fn hierarchical_prefix_cond_field_test(){ ]; for _ in 0..500 { - let globals=CheckingGlobals::new(); - - let library_00=fields_2.choose(&mut rng).unwrap().clone(); - let library_01=fields_1.choose(&mut rng).unwrap().clone(); - let library_02=fields_0.choose(&mut rng).unwrap().clone(); - - let library_10=fields_2.choose(&mut rng).unwrap().clone(); - let library_11=fields_2.choose(&mut rng).unwrap().clone(); - let library_12=fields_3.choose(&mut rng).unwrap().clone(); - - let library_0=fields_0.choose(&mut rng).unwrap().clone(); - let library_1=fields_1.choose(&mut rng).unwrap().clone(); - - let binary=fields_0.choose(&mut rng).unwrap().clone(); - - - let mut checks=vec![ - (binary,library_0), - (binary,library_1), - (library_0,library_00), - (library_0,library_01), - (library_0,library_02), - (library_1,library_10), - (library_1,library_11), - (library_1,library_12), + let globals = CheckingGlobals::new(); + + let library_00 = fields_2.choose(&mut rng).unwrap().clone(); + let library_01 = fields_1.choose(&mut rng).unwrap().clone(); + let library_02 = fields_0.choose(&mut rng).unwrap().clone(); + + let library_10 = fields_2.choose(&mut rng).unwrap().clone(); + let library_11 = fields_2.choose(&mut rng).unwrap().clone(); + let library_12 = fields_3.choose(&mut rng).unwrap().clone(); + + let library_0 = fields_0.choose(&mut rng).unwrap().clone(); + let library_1 = fields_1.choose(&mut rng).unwrap().clone(); + + let binary = fields_0.choose(&mut rng).unwrap().clone(); + + let mut checks = vec![ + (binary, library_0), + (binary, library_1), + (library_0, library_00), + (library_0, library_01), + (library_0, library_02), + (library_1, library_10), + (library_1, library_11), + (library_1, library_12), ]; checks.shuffle(&mut rng); - for (this,other) in checks { - check_interface_impl_pair(&globals,this,other); + for (this, other) in checks { + check_interface_impl_pair(&globals, this, other); } } } - #[test] fn prefix_on_conditional_fields() { - use abi_stable::{ - type_level::bools::{True as T,False as F}, marker_type::UnsafeIgnoredType, + type_level::bools::{False as F, True as T}, }; - - type Prefix1_Ref=cond_fields_1::Prefix_Ref; - type Prefix2_Ref=cond_fields_2::Prefix_Ref; - type Prefix3_Ref=cond_fields_3::Prefix_Ref; - type Prefix3UncondPrefix_Ref= - cond_fields_3_uncond_prefix::Prefix_Ref; - - {// Casting Prefix0 to Prefix1 with different field accessibilities - pub const MOD_VAL: &WithMetadata> = - &WithMetadata::new( - PrefixTypeTrait::METADATA, - cond_fields_0::Prefix{ - _marker:UnsafeIgnoredType::DEFAULT, - field0:1, - }, - ); + type Prefix1_Ref = cond_fields_1::Prefix_Ref; + type Prefix2_Ref = cond_fields_2::Prefix_Ref; + type Prefix3_Ref = cond_fields_3::Prefix_Ref; + type Prefix3UncondPrefix_Ref = + cond_fields_3_uncond_prefix::Prefix_Ref; + + { + // Casting Prefix0 to Prefix1 with different field accessibilities + pub const MOD_VAL: &WithMetadata> = &WithMetadata::new( + PrefixTypeTrait::METADATA, + cond_fields_0::Prefix { + _marker: UnsafeIgnoredType::DEFAULT, + field0: 1, + }, + ); let prefix0 = MOD_VAL.static_as_prefix(); - {// The field cannot be accessed even though it was initialized. - let value:Prefix1_Ref<(F,F,F,F)>=unsafe{ std::mem::transmute(prefix0) }; + { + // The field cannot be accessed even though it was initialized. + let value: Prefix1_Ref<(F, F, F, F)> = unsafe { std::mem::transmute(prefix0) }; - assert_eq!(value.field0(),None); - assert_eq!(value.field1(),None); + assert_eq!(value.field0(), None); + assert_eq!(value.field1(), None); } - {// The first field can be accessed. - let value:Prefix1_Ref<(T,F,F,F)>=unsafe{ std::mem::transmute(prefix0) }; + { + // The first field can be accessed. + let value: Prefix1_Ref<(T, F, F, F)> = unsafe { std::mem::transmute(prefix0) }; - assert_eq!(value.field0(),Some(1)); - assert_eq!(value.field1(),None); + assert_eq!(value.field0(), Some(1)); + assert_eq!(value.field1(), None); } } - pub const MOD_VAL_P3: &WithMetadata> = + pub const MOD_VAL_P3: &WithMetadata> = &WithMetadata::new( PrefixTypeTrait::METADATA, - cond_fields_3::Prefix{ - _marker:UnsafeIgnoredType::DEFAULT, - field0:1, - field1:3, - field2:7, - field3:12, + cond_fields_3::Prefix { + _marker: UnsafeIgnoredType::DEFAULT, + field0: 1, + field1: 3, + field2: 7, + field3: 12, }, ); let prefix3 = MOD_VAL_P3.static_as_prefix(); - {// Casting Prefix3 to Prefix2 with different field accessibilities + { + // Casting Prefix3 to Prefix2 with different field accessibilities { - let value:Prefix2_Ref<(F,F,F,F)>=unsafe{ std::mem::transmute(prefix3) }; + let value: Prefix2_Ref<(F, F, F, F)> = unsafe { std::mem::transmute(prefix3) }; - assert_eq!(value.field0(),None); - assert_eq!(value.field1(),None); - assert_eq!(value.field2(),None); + assert_eq!(value.field0(), None); + assert_eq!(value.field1(), None); + assert_eq!(value.field2(), None); } { - let value:Prefix2_Ref<(T,F,F,F)>=unsafe{ std::mem::transmute(prefix3) }; + let value: Prefix2_Ref<(T, F, F, F)> = unsafe { std::mem::transmute(prefix3) }; - assert_eq!(value.field0(),Some(1)); - assert_eq!(value.field1(),None); - assert_eq!(value.field2(),None); + assert_eq!(value.field0(), Some(1)); + assert_eq!(value.field1(), None); + assert_eq!(value.field2(), None); } { - let value:Prefix2_Ref<(F,T,F,F)>=unsafe{ std::mem::transmute(prefix3) }; + let value: Prefix2_Ref<(F, T, F, F)> = unsafe { std::mem::transmute(prefix3) }; - assert_eq!(value.field0(),None); - assert_eq!(value.field1(),Some(3)); - assert_eq!(value.field2(),None); + assert_eq!(value.field0(), None); + assert_eq!(value.field1(), Some(3)); + assert_eq!(value.field2(), None); } { - let value:Prefix2_Ref<(F,F,T,F)>=unsafe{ std::mem::transmute(prefix3) }; + let value: Prefix2_Ref<(F, F, T, F)> = unsafe { std::mem::transmute(prefix3) }; - assert_eq!(value.field0(),None); - assert_eq!(value.field1(),None); - assert_eq!(value.field2(),Some(7)); + assert_eq!(value.field0(), None); + assert_eq!(value.field1(), None); + assert_eq!(value.field2(), Some(7)); } { - let value:Prefix2_Ref<(T,T,T,T)>=unsafe{ std::mem::transmute(prefix3) }; + let value: Prefix2_Ref<(T, T, T, T)> = unsafe { std::mem::transmute(prefix3) }; - assert_eq!(value.field0(),Some(1)); - assert_eq!(value.field1(),Some(3)); - assert_eq!(value.field2(),Some(7)); + assert_eq!(value.field0(), Some(1)); + assert_eq!(value.field1(), Some(3)); + assert_eq!(value.field2(), Some(7)); } } - {// Casting Prefix3 to Prefix3UncondPrefix with different field accessibilities + { + // Casting Prefix3 to Prefix3UncondPrefix with different field accessibilities { - let value:Prefix3UncondPrefix_Ref<(F,F,F,F)>=unsafe{ std::mem::transmute(prefix3) }; + let value: Prefix3UncondPrefix_Ref<(F, F, F, F)> = + unsafe { std::mem::transmute(prefix3) }; - assert_eq!(value.field0(),1); - assert_eq!(value.field1(),None); - assert_eq!(value.field2(),None); - assert_eq!(value.field2(),None); + assert_eq!(value.field0(), 1); + assert_eq!(value.field1(), None); + assert_eq!(value.field2(), None); + assert_eq!(value.field2(), None); } { - let value:Prefix3UncondPrefix_Ref<(F,F,T,F)>=unsafe{ std::mem::transmute(prefix3) }; + let value: Prefix3UncondPrefix_Ref<(F, F, T, F)> = + unsafe { std::mem::transmute(prefix3) }; - assert_eq!(value.field0(),1); - assert_eq!(value.field1(),None); - assert_eq!(value.field2(),Some(7)); - assert_eq!(value.field3(),None); + assert_eq!(value.field0(), 1); + assert_eq!(value.field1(), None); + assert_eq!(value.field2(), Some(7)); + assert_eq!(value.field3(), None); } { - let value:Prefix3UncondPrefix_Ref<(T,T,T,T)>=unsafe{ std::mem::transmute(prefix3) }; + let value: Prefix3UncondPrefix_Ref<(T, T, T, T)> = + unsafe { std::mem::transmute(prefix3) }; - assert_eq!(value.field0(),1); - assert_eq!(value.field1(),Some(3)); - assert_eq!(value.field2(),Some(7)); - assert_eq!(value.field3(),Some(12)); + assert_eq!(value.field0(), 1); + assert_eq!(value.field1(), Some(3)); + assert_eq!(value.field2(), Some(7)); + assert_eq!(value.field3(), Some(12)); } } } diff --git a/abi_stable/tests/layout_tests/repr_and_discr.rs b/abi_stable/tests/layout_tests/repr_and_discr.rs index 1b1f47db..58d85bc2 100644 --- a/abi_stable/tests/layout_tests/repr_and_discr.rs +++ b/abi_stable/tests/layout_tests/repr_and_discr.rs @@ -1,19 +1,16 @@ use abi_stable::{ - StableAbi, - abi_stability::{ - abi_checking::{AbiInstability,check_layout_compatibility}, - }, + abi_stability::abi_checking::{check_layout_compatibility, AbiInstability}, type_layout::TypeLayout, + StableAbi, }; - macro_rules! declare_int_repr { - ( - mod=$mod_ident:ident - repr=$repr:ident - discriminants( $($discr_a:expr)* , $($discr_b:expr)* , $($discr_c:expr)* ) + ( + mod=$mod_ident:ident + repr=$repr:ident + discriminants( $($discr_a:expr)* , $($discr_b:expr)* , $($discr_c:expr)* ) discr_ty=$discr_ty:ty, - check=( $($variant:ident=$discr_value:expr),* $(,)* ) + check=( $($variant:ident=$discr_value:expr),* $(,)* ) ) => ( mod $mod_ident{ use abi_stable::StableAbi; @@ -37,23 +34,23 @@ macro_rules! declare_int_repr { ) } -declare_int_repr!{ +declare_int_repr! { mod=c_repr_a repr=C discriminants(,,) discr_ty=isize, - check=( A=0,B=1,C=2, ) + check=( A=0,B=1,C=2, ) } -declare_int_repr!{ +declare_int_repr! { mod=c_repr_b repr=C discriminants(10,,) discr_ty=isize, - check=( A=10,B=11,C=12, ) + check=( A=10,B=11,C=12, ) } -declare_int_repr!{ +declare_int_repr! { mod=u8_repr_a repr=u8 discriminants(,,) @@ -61,7 +58,7 @@ declare_int_repr!{ check=( A=0,B=1,C=2, ) } -declare_int_repr!{ +declare_int_repr! { mod=u8_repr_b repr=u8 discriminants(10,,) @@ -69,7 +66,7 @@ declare_int_repr!{ check=( A=10,B=11,C=12, ) } -declare_int_repr!{ +declare_int_repr! { mod=u16_repr_a repr=u16 discriminants(,,) @@ -77,7 +74,7 @@ declare_int_repr!{ check=( A=0,B=1,C=2, ) } -declare_int_repr!{ +declare_int_repr! { mod=usize_repr_a repr=usize discriminants(,,) @@ -85,7 +82,7 @@ declare_int_repr!{ check=( A=0,B=1,C=2, ) } -declare_int_repr!{ +declare_int_repr! { mod=i8_repr_a repr=i8 discriminants(,,) @@ -93,7 +90,7 @@ declare_int_repr!{ check=( A=0,B=1,C=2, ) } -declare_int_repr!{ +declare_int_repr! { mod=i8_repr_b repr=i8 discriminants(10,,) @@ -101,7 +98,7 @@ declare_int_repr!{ check=( A=10,B=11,C=12, ) } -declare_int_repr!{ +declare_int_repr! { mod=i8_repr_c repr=i8 discriminants(,10,) @@ -109,7 +106,7 @@ declare_int_repr!{ check=( A=0,B=10,C=11, ) } -declare_int_repr!{ +declare_int_repr! { mod=i8_repr_d repr=i8 discriminants(,,10) @@ -117,7 +114,7 @@ declare_int_repr!{ check=( A=0,B=1,C=10, ) } -declare_int_repr!{ +declare_int_repr! { mod=i16_repr_a repr=i16 discriminants(,,) @@ -125,7 +122,7 @@ declare_int_repr!{ check=( A=0,B=1,C=2, ) } -declare_int_repr!{ +declare_int_repr! { mod=isize_repr_a repr=isize discriminants(,,) @@ -133,51 +130,46 @@ declare_int_repr!{ check=( A=0,B=1,C=2, ) } - #[cfg(not(miri))] -fn check_imcompatible_with_others(list:&[&'static TypeLayout],mut f:F) +fn check_imcompatible_with_others(list: &[&'static TypeLayout], mut f: F) where - F:FnMut(&[AbiInstability]) + F: FnMut(&[AbiInstability]), { - for (l_i,l_abi) in list.iter().enumerate() { - for (r_i,r_abi) in list.iter().enumerate() { - - let res=check_layout_compatibility(l_abi,r_abi); + for (l_i, l_abi) in list.iter().enumerate() { + for (r_i, r_abi) in list.iter().enumerate() { + let res = check_layout_compatibility(l_abi, r_abi); if l_i == r_i { - assert_eq!(res,Ok(())); - }else{ - let errs=res.unwrap_err().flatten_errors(); + assert_eq!(res, Ok(())); + } else { + let errs = res.unwrap_err().flatten_errors(); f(&*errs); } } } - } - fn assert_discr_error(errs: &[AbiInstability]) { - let mut had_some_err=false; + let mut had_some_err = false; for err in errs { match err { - AbiInstability::ReprAttr{..}=>{ - had_some_err=true; + AbiInstability::ReprAttr { .. } => { + had_some_err = true; } - AbiInstability::EnumDiscriminant{..}=>{ - had_some_err=true; + AbiInstability::EnumDiscriminant { .. } => { + had_some_err = true; } - _=>{} + _ => {} } } - assert!(had_some_err,"\nerrors:{:#?}\n",errs); + assert!(had_some_err, "\nerrors:{:#?}\n", errs); } - #[cfg(not(miri))] #[test] -fn check_discriminant_repr_enums(){ - let list=&[ +fn check_discriminant_repr_enums() { + let list = &[ ::LAYOUT, ::LAYOUT, ::LAYOUT, @@ -190,20 +182,27 @@ fn check_discriminant_repr_enums(){ ::LAYOUT, ]; - check_imcompatible_with_others(list,assert_discr_error) + check_imcompatible_with_others(list, assert_discr_error) } - #[cfg(miri)] #[test] -fn check_discriminant_repr_enums(){ +fn check_discriminant_repr_enums() { let l0 = ::LAYOUT; let l1 = ::LAYOUT; let l2 = ::LAYOUT; - + assert_eq!(check_layout_compatibility(l0, l0), Ok(())); - - assert_discr_error(&check_layout_compatibility(l0, l1).unwrap_err().flatten_errors()); - - assert_discr_error(&check_layout_compatibility(l0, l2).unwrap_err().flatten_errors()); + + assert_discr_error( + &check_layout_compatibility(l0, l1) + .unwrap_err() + .flatten_errors(), + ); + + assert_discr_error( + &check_layout_compatibility(l0, l2) + .unwrap_err() + .flatten_errors(), + ); } diff --git a/abi_stable/tests/layout_tests/sabi_trait.rs b/abi_stable/tests/layout_tests/sabi_trait.rs index 9e35b2d7..3a31928f 100644 --- a/abi_stable/tests/layout_tests/sabi_trait.rs +++ b/abi_stable/tests/layout_tests/sabi_trait.rs @@ -1,51 +1,49 @@ use abi_stable::{ - sabi_trait, - StableAbi, - abi_stability::{ - abi_checking::{ - AbiInstability,check_layout_compatibility, - check_layout_compatibility_with_globals, - CheckingGlobals, - }, + abi_stability::abi_checking::{ + check_layout_compatibility, check_layout_compatibility_with_globals, AbiInstability, + CheckingGlobals, }, - std_types::{RBox}, + sabi_trait, + std_types::RBox, type_layout::TypeLayout, + StableAbi, }; +use core_extensions::matches; -use core_extensions::{matches}; - - -fn check_subsets(list:&[&'static TypeLayout],mut f:F) +fn check_subsets(list: &[&'static TypeLayout], mut f: F) where - F:FnMut(&[AbiInstability]) + F: FnMut(&[AbiInstability]), { - let globals=CheckingGlobals::new(); - + let globals = CheckingGlobals::new(); + #[cfg(miri)] { - assert_eq!(check_layout_compatibility_with_globals(&list[0], &list[0], &globals), Ok(())); - + assert_eq!( + check_layout_compatibility_with_globals(&list[0], &list[0], &globals), + Ok(()) + ); + f( &check_layout_compatibility_with_globals(&list[1], &list[0], &globals) .unwrap_err() - .flatten_errors() + .flatten_errors(), ); } #[cfg(not(miri))] - for (l_i,l_abi) in list.iter().enumerate() { - for (r_i,r_abi) in list.iter().enumerate() { - let res=check_layout_compatibility_with_globals(l_abi,r_abi,&globals); + for (l_i, l_abi) in list.iter().enumerate() { + for (r_i, r_abi) in list.iter().enumerate() { + let res = check_layout_compatibility_with_globals(l_abi, r_abi, &globals); if l_i <= r_i { - assert_eq!(res,Ok(())); - }else{ - if let Ok(_)=res { - let _=dbg!(l_i); - let _=dbg!(r_i); + assert_eq!(res, Ok(())); + } else { + if let Ok(_) = res { + let _ = dbg!(l_i); + let _ = dbg!(r_i); } - let errs=res.unwrap_err().flatten_errors(); + let errs = res.unwrap_err().flatten_errors(); f(&*errs); } @@ -53,32 +51,32 @@ where } } - -fn check_equality(list:&[&'static TypeLayout],mut f:F) +fn check_equality(list: &[&'static TypeLayout], mut f: F) where - F:FnMut(&[AbiInstability]) + F: FnMut(&[AbiInstability]), { #[cfg(miri)] { assert_eq!(check_layout_compatibility(&list[0], &list[0]), Ok(())); - - f(&check_layout_compatibility(&list[1], &list[0]).unwrap_err().flatten_errors()); + + f(&check_layout_compatibility(&list[1], &list[0]) + .unwrap_err() + .flatten_errors()); } #[cfg(not(miri))] - for (l_i,l_abi) in list.iter().enumerate() { - for (r_i,r_abi) in list.iter().enumerate() { - - let res=check_layout_compatibility(l_abi,r_abi); + for (l_i, l_abi) in list.iter().enumerate() { + for (r_i, r_abi) in list.iter().enumerate() { + let res = check_layout_compatibility(l_abi, r_abi); if l_i == r_i { - assert_eq!(res,Ok(())); - }else{ - if let Ok(_)=res { - let _=dbg!(l_i); - let _=dbg!(r_i); + assert_eq!(res, Ok(())); + } else { + if let Ok(_) = res { + let _ = dbg!(l_i); + let _ = dbg!(r_i); } - let errs=res.unwrap_err().flatten_errors(); + let errs = res.unwrap_err().flatten_errors(); f(&*errs); } @@ -86,132 +84,121 @@ where } } - - -mod one_method{ +mod one_method { use super::*; #[sabi_trait] // #[sabi(debug_print_trait)] - pub trait Trait{ + pub trait Trait { #[sabi(last_prefix_field)] - fn apply(&self,l:u32,r:u32)->u32; + fn apply(&self, l: u32, r: u32) -> u32; } } -mod two_methods{ +mod two_methods { use super::*; #[sabi_trait] - pub trait Trait{ + pub trait Trait { #[sabi(last_prefix_field)] - fn apply(&self,l:u32,r:u32)->u32; - fn apply2(&self,l:u32,r:u32)->u32; + fn apply(&self, l: u32, r: u32) -> u32; + fn apply2(&self, l: u32, r: u32) -> u32; } } -mod three_methods{ +mod three_methods { use super::*; #[sabi_trait] - pub trait Trait{ + pub trait Trait { #[sabi(last_prefix_field)] - fn apply(&self,l:u32,r:u32)->u32; - fn apply2(&self,l:u32,r:u32)->u32; - fn apply3(&self,l:u32,r:u32)->u32; + fn apply(&self, l: u32, r: u32) -> u32; + fn apply2(&self, l: u32, r: u32) -> u32; + fn apply3(&self, l: u32, r: u32) -> u32; } } -mod one_method_debug{ +mod one_method_debug { use super::*; #[sabi_trait] - pub trait Trait:Debug{ + pub trait Trait: Debug { #[sabi(last_prefix_field)] - fn apply(&self,l:u32,r:u32)->u32; + fn apply(&self, l: u32, r: u32) -> u32; } } -mod one_method_clone_debug{ +mod one_method_clone_debug { use super::*; #[sabi_trait] - pub trait Trait:Clone+Debug{ + pub trait Trait: Clone + Debug { #[sabi(last_prefix_field)] - fn apply(&self,l:u32,r:u32)->u32; + fn apply(&self, l: u32, r: u32) -> u32; } } -mod one_method_sync{ +mod one_method_sync { use super::*; #[sabi_trait] - pub trait Trait:Sync{ + pub trait Trait: Sync { #[sabi(last_prefix_field)] - fn apply(&self,l:u32,r:u32)->u32; + fn apply(&self, l: u32, r: u32) -> u32; } } -mod one_method_send{ +mod one_method_send { use super::*; #[sabi_trait] - pub trait Trait:Send{ + pub trait Trait: Send { #[sabi(last_prefix_field)] - fn apply(&self,l:u32,r:u32)->u32; + fn apply(&self, l: u32, r: u32) -> u32; } } -mod one_method_sync_send{ +mod one_method_sync_send { use super::*; #[sabi_trait] - pub trait Trait:Sync+Send{ + pub trait Trait: Sync + Send { #[sabi(last_prefix_field)] - fn apply(&self,l:u32,r:u32)->u32; + fn apply(&self, l: u32, r: u32) -> u32; } } #[test] -fn adding_methods_at_the_end(){ - let list=vec![ - > as StableAbi>::LAYOUT, - > as StableAbi>::LAYOUT, - > as StableAbi>::LAYOUT, +fn adding_methods_at_the_end() { + let list = vec![ + > as StableAbi>::LAYOUT, + > as StableAbi>::LAYOUT, + > as StableAbi>::LAYOUT, ]; - check_subsets(&list[..],|errs|{ - assert!( - errs + check_subsets(&list[..], |errs| { + assert!(errs .iter() - .any(|err| matches!(err, AbiInstability::FieldCountMismatch{..})) - ); + .any(|err| matches!(err, AbiInstability::FieldCountMismatch { .. }))); }); } - - #[test] -fn adding_supertraits(){ - let list=vec![ - > as StableAbi>::LAYOUT, - > as StableAbi>::LAYOUT, - > as StableAbi>::LAYOUT, +fn adding_supertraits() { + let list = vec![ + > as StableAbi>::LAYOUT, + > as StableAbi>::LAYOUT, + > as StableAbi>::LAYOUT, ]; - check_subsets(&list[..],|errs|{ - assert!( - errs + check_subsets(&list[..], |errs| { + assert!(errs .iter() - .any(|err| matches!(err, AbiInstability::ExtraCheckError{..})) - ); + .any(|err| matches!(err, AbiInstability::ExtraCheckError { .. }))); }); } - #[test] -fn incompatible_supertraits(){ - let list=vec![ - > as StableAbi>::LAYOUT, - > as StableAbi>::LAYOUT, - > as StableAbi>::LAYOUT, - > as StableAbi>::LAYOUT, +fn incompatible_supertraits() { + let list = vec![ + > as StableAbi>::LAYOUT, + > as StableAbi>::LAYOUT, + > as StableAbi>::LAYOUT, + > as StableAbi>::LAYOUT, ]; - check_equality(&list[..],|errs|{ - assert!( - errs + check_equality(&list[..], |errs| { + assert!(errs .iter() - .any(|err| matches!(err, AbiInstability::ExtraCheckError{..})) - ); + .any(|err| matches!(err, AbiInstability::ExtraCheckError { .. }))); }); } diff --git a/abi_stable/tests/layout_tests/shared_types.rs b/abi_stable/tests/layout_tests/shared_types.rs index 3d070148..38d45ec5 100644 --- a/abi_stable/tests/layout_tests/shared_types.rs +++ b/abi_stable/tests/layout_tests/shared_types.rs @@ -7,13 +7,10 @@ use core_extensions::matches; #[allow(unused_imports)] use abi_stable::{ - external_types::{ - RMutex,RRwLock,ROnce - }, + external_types::{RMutex, ROnce, RRwLock}, std_types::*, }; - pub(super) mod basic_enum { #[repr(C)] #[derive(abi_stable::StableAbi)] @@ -51,7 +48,7 @@ pub(super) mod enum_extra_fields_b { #[derive(abi_stable::StableAbi)] pub enum Enum { Variant0, - Variant1 { a: u32,b:u32,c:u32 }, + Variant1 { a: u32, b: u32, c: u32 }, } } @@ -66,7 +63,6 @@ pub(super) mod extra_variant { } } - pub(super) mod swapped_fields_first { #[repr(C)] #[derive(abi_stable::StableAbi)] @@ -78,7 +74,6 @@ pub(super) mod swapped_fields_first { } } - pub(super) mod gen_more_lts_b { #[repr(C)] #[derive(abi_stable::StableAbi)] @@ -88,26 +83,24 @@ pub(super) mod gen_more_lts_b { } } - pub(super) mod mod_5 { use super::RString; #[repr(C)] #[derive(abi_stable::StableAbi)] - pub struct Mod{ - pub function_0: extern "C" fn()->RString, - pub function_1: extern "C" fn(&mut u32,u64,RString), - pub function_2: extern "C" fn(&mut u32,u64,RString), + pub struct Mod { + pub function_0: extern "C" fn() -> RString, + pub function_1: extern "C" fn(&mut u32, u64, RString), + pub function_2: extern "C" fn(&mut u32, u64, RString), } } - pub(super) mod mod_7 { use super::RString; #[repr(C)] #[derive(abi_stable::StableAbi)] - pub struct Mod{ - pub function_0: extern "C" fn()->RString, - pub function_1: extern "C" fn(&mut u32,u64,RString), - pub function_2: extern "C" fn((),(),()), + pub struct Mod { + pub function_0: extern "C" fn() -> RString, + pub function_1: extern "C" fn(&mut u32, u64, RString), + pub function_2: extern "C" fn((), (), ()), } -} \ No newline at end of file +} diff --git a/abi_stable/tests/layout_tests/stable_abi_attributes.rs b/abi_stable/tests/layout_tests/stable_abi_attributes.rs index 6164f273..d820729b 100644 --- a/abi_stable/tests/layout_tests/stable_abi_attributes.rs +++ b/abi_stable/tests/layout_tests/stable_abi_attributes.rs @@ -1,173 +1,163 @@ use abi_stable::{ - StableAbi, abi_stability::check_layout_compatibility, - type_layout::{TypeLayout,TLData}, - RTuple,tag, + tag, + type_layout::{TLData, TypeLayout}, + RTuple, StableAbi, }; - /// Tests that `#[sabi(bound="")]` on a field works. #[cfg(not(feature = "no_fn_promotion"))] #[repr(C)] #[derive(abi_stable::StableAbi)] -#[sabi(tag="tag![ ::STR ]")] +#[sabi(tag = "tag![ ::STR ]")] #[allow(dead_code)] -pub struct FieldBound{ - #[sabi(bound="abi_stable::const_utils::AssocStr")] - pub value:T, +pub struct FieldBound { + #[sabi(bound = "abi_stable::const_utils::AssocStr")] + pub value: T, } /// Tests that `#[sabi(bound="")]` on a type definition works. #[cfg(not(feature = "no_fn_promotion"))] #[repr(C)] #[derive(abi_stable::StableAbi)] -#[sabi(bound="T:abi_stable::const_utils::AssocStr")] -#[sabi(tag="tag![ ::STR ]")] +#[sabi(bound = "T:abi_stable::const_utils::AssocStr")] +#[sabi(tag = "tag![ ::STR ]")] #[allow(dead_code)] -pub struct TypeBound{ - pub value:T, +pub struct TypeBound { + pub value: T, } - - #[repr(C)] #[derive(abi_stable::StableAbi)] #[sabi(unsafe_opaque_fields)] -pub struct UnsafeOpaqueFields0{ - hello:T, - world:U, +pub struct UnsafeOpaqueFields0 { + hello: T, + world: U, } #[repr(C)] #[derive(abi_stable::StableAbi)] #[sabi(unsafe_sabi_opaque_fields)] -pub struct UnsafeSabiOpaqueFields0{ - hello:T, - world:U, +pub struct UnsafeSabiOpaqueFields0 { + hello: T, + world: U, } #[repr(C)] #[derive(abi_stable::StableAbi)] -pub struct UnsafeOpaqueField0{ - hello:T, +pub struct UnsafeOpaqueField0 { + hello: T, #[sabi(unsafe_opaque_field)] - world:U, + world: U, } - + #[repr(C)] #[derive(abi_stable::StableAbi)] -pub struct UnsafeSabiOpaqueField0{ - hello:T, +pub struct UnsafeSabiOpaqueField0 { + hello: T, #[sabi(unsafe_sabi_opaque_field)] - world:U, + world: U, } - #[repr(C)] #[derive(abi_stable::StableAbi)] #[sabi(unsafe_allow_type_macros)] -pub struct WithTypeMacro{ - type_:RTuple!((),(),()), +pub struct WithTypeMacro { + type_: RTuple!((), (), ()), } - //////////////////////////////////////////////////////////////////////////////// - #[test] -fn is_sabi_opaque_fields(){ - let list:Vec<(&'static TypeLayout,Vec>)>=vec![ +fn is_sabi_opaque_fields() { + let list: Vec<(&'static TypeLayout, Vec>)> = vec![ ( - UnsafeOpaqueFields0::::LAYOUT, - vec![Some("OpaqueField"),Some("OpaqueField")] + UnsafeOpaqueFields0::::LAYOUT, + vec![Some("OpaqueField"), Some("OpaqueField")], ), ( - UnsafeSabiOpaqueFields0::::LAYOUT, - vec![Some("OpaqueField"),Some("OpaqueField")] + UnsafeSabiOpaqueFields0::::LAYOUT, + vec![Some("OpaqueField"), Some("OpaqueField")], ), ( - UnsafeOpaqueField0::::LAYOUT, - vec![None,Some("OpaqueField")] + UnsafeOpaqueField0::::LAYOUT, + vec![None, Some("OpaqueField")], ), ( - UnsafeSabiOpaqueField0::::LAYOUT, - vec![None,Some("OpaqueField")] + UnsafeSabiOpaqueField0::::LAYOUT, + vec![None, Some("OpaqueField")], ), ]; - for (layout,field_typenames) in list { - let fields=match layout.data() { - TLData::Struct{fields}=>fields, - _=>unreachable!() + for (layout, field_typenames) in list { + let fields = match layout.data() { + TLData::Struct { fields } => fields, + _ => unreachable!(), }; - for (field,field_typename) in fields.into_iter().zip(field_typenames) { - if let Some(typename)=field_typename { - assert_eq!( field.layout().name(), typename ); + for (field, field_typename) in fields.into_iter().zip(field_typenames) { + if let Some(typename) = field_typename { + assert_eq!(field.layout().name(), typename); } } } } - #[test] fn same_opaque_fields() { - let lists=vec![ + let lists = vec![ vec![ - UnsafeOpaqueFields0::::LAYOUT, - UnsafeOpaqueFields0::::LAYOUT, - UnsafeOpaqueFields0::::LAYOUT, - UnsafeOpaqueFields0::::LAYOUT, + UnsafeOpaqueFields0::::LAYOUT, + UnsafeOpaqueFields0::::LAYOUT, + UnsafeOpaqueFields0::::LAYOUT, + UnsafeOpaqueFields0::::LAYOUT, ], vec![ - UnsafeSabiOpaqueFields0::::LAYOUT, - UnsafeSabiOpaqueFields0::::LAYOUT, - UnsafeSabiOpaqueFields0::::LAYOUT, - UnsafeSabiOpaqueFields0::::LAYOUT, + UnsafeSabiOpaqueFields0::::LAYOUT, + UnsafeSabiOpaqueFields0::::LAYOUT, + UnsafeSabiOpaqueFields0::::LAYOUT, + UnsafeSabiOpaqueFields0::::LAYOUT, ], vec![ - UnsafeOpaqueField0::::LAYOUT, - UnsafeOpaqueField0::::LAYOUT, + UnsafeOpaqueField0::::LAYOUT, + UnsafeOpaqueField0::::LAYOUT, ], vec![ - UnsafeSabiOpaqueField0::::LAYOUT, - UnsafeSabiOpaqueField0::::LAYOUT, + UnsafeSabiOpaqueField0::::LAYOUT, + UnsafeSabiOpaqueField0::::LAYOUT, ], ]; for list in lists { for window in list.windows(2) { - check_layout_compatibility( window[0], window[1] ).unwrap(); + check_layout_compatibility(window[0], window[1]).unwrap(); } } } - #[test] fn different_opaque_fields() { #[allow(unused_mut)] - let mut list=vec![ - UnsafeOpaqueFields0::::LAYOUT, - UnsafeOpaqueFields0::::LAYOUT, - - UnsafeSabiOpaqueFields0::::LAYOUT, - UnsafeSabiOpaqueFields0::::LAYOUT, + let mut list = vec![ + UnsafeOpaqueFields0::::LAYOUT, + UnsafeOpaqueFields0::::LAYOUT, + UnsafeSabiOpaqueFields0::::LAYOUT, + UnsafeSabiOpaqueFields0::::LAYOUT, ]; #[cfg(not(miri))] list.extend_from_slice(&[ - UnsafeOpaqueField0::::LAYOUT, - UnsafeOpaqueField0::::LAYOUT, - UnsafeOpaqueField0::::LAYOUT, - - UnsafeSabiOpaqueField0::::LAYOUT, - UnsafeSabiOpaqueField0::::LAYOUT, - UnsafeSabiOpaqueField0::::LAYOUT, + UnsafeOpaqueField0::::LAYOUT, + UnsafeOpaqueField0::::LAYOUT, + UnsafeOpaqueField0::::LAYOUT, + UnsafeSabiOpaqueField0::::LAYOUT, + UnsafeSabiOpaqueField0::::LAYOUT, + UnsafeSabiOpaqueField0::::LAYOUT, ]); for (i, this) in list.iter().cloned().enumerate() { for (j, other) in list.iter().cloned().enumerate() { - let res=check_layout_compatibility(this, other); + let res = check_layout_compatibility(this, other); if i == j { res.unwrap(); } else { diff --git a/abi_stable/tests/layout_tests/value.rs b/abi_stable/tests/layout_tests/value.rs index 957f9bf6..3790818a 100644 --- a/abi_stable/tests/layout_tests/value.rs +++ b/abi_stable/tests/layout_tests/value.rs @@ -1,38 +1,27 @@ #![allow(dead_code)] -use std::{marker::PhantomData,mem, num, ptr, sync::atomic}; +use std::{marker::PhantomData, mem, num, ptr, sync::atomic}; #[allow(unused_imports)] use core_extensions::matches; use abi_stable::{ - abi_stability::{ - abi_checking::{AbiInstability,check_layout_compatibility}, - }, + abi_stability::abi_checking::{check_layout_compatibility, AbiInstability}, external_types::{ - crossbeam_channel::{RReceiver,RSender}, - RMutex,RRwLock,ROnce + crossbeam_channel::{RReceiver, RSender}, + RMutex, ROnce, RRwLock, }, - marker_type::{NonOwningPhantom,UnsafeIgnoredType}, + marker_type::{NonOwningPhantom, UnsafeIgnoredType}, std_types::*, - type_layout::{Tag,TLData,TypeLayout}, + type_layout::{TLData, Tag, TypeLayout}, *, }; use super::shared_types::{ - basic_enum, - gen_basic, - gen_more_lts, - enum_extra_fields_b, - extra_variant, - swapped_fields_first, - gen_more_lts_b, - mod_5, - mod_7, + basic_enum, enum_extra_fields_b, extra_variant, gen_basic, gen_more_lts, gen_more_lts_b, mod_5, + mod_7, swapped_fields_first, }; - - pub(super) mod union_1a { #[repr(C)] #[derive(abi_stable::StableAbi)] @@ -116,7 +105,7 @@ pub(super) mod changed_field_name { pub struct Rectangle { x: u32, y: u32, - #[sabi(rename="w2")] + #[sabi(rename = "w2")] w: u16, h: u32, } @@ -198,7 +187,6 @@ pub(super) mod changed_alignment { } } - pub(super) mod built_in { pub use i32 as std_i32; pub use u32 as std_u32; @@ -231,7 +219,7 @@ fn assert_equal_type_layout(interface: &'static TypeLayout, impl_: &'static Type } fn assert_different_type_layout(interface: &'static TypeLayout, impl_: &'static TypeLayout) { - let res=check_layout_compatibility(interface, impl_); + let res = check_layout_compatibility(interface, impl_); assert_ne!( res, Ok(()), @@ -241,31 +229,28 @@ fn assert_different_type_layout(interface: &'static TypeLayout, impl_: &'static ); } - #[repr(transparent)] #[derive(abi_stable::StableAbi)] -pub struct UnsafeOF{ +pub struct UnsafeOF { #[sabi(unsafe_opaque_field)] - opaque:Vec, + opaque: Vec, } - #[test] -fn unsafe_opaque_fields(){ - let layout=UnsafeOF::LAYOUT; +fn unsafe_opaque_fields() { + let layout = UnsafeOF::LAYOUT; - let fields=match layout.data() { - TLData::Struct{fields}=>fields.iter().collect::>(), - _=>unreachable!(), + let fields = match layout.data() { + TLData::Struct { fields } => fields.iter().collect::>(), + _ => unreachable!(), }; - let field_0_ai=fields[0].layout(); + let field_0_ai = fields[0].layout(); assert_eq!(field_0_ai.data(), TLData::Opaque); assert_eq!(field_0_ai.size(), mem::size_of::>()); assert_eq!(field_0_ai.alignment(), mem::align_of::>()); } - #[cfg(not(miri))] #[test] fn same_different_abi_stability() { @@ -316,10 +301,10 @@ fn same_different_abi_stability() { ::LAYOUT, >::LAYOUT, >::LAYOUT, - >::LAYOUT, - >::LAYOUT, - >::LAYOUT, - >::LAYOUT, + >::LAYOUT, + >::LAYOUT, + >::LAYOUT, + >::LAYOUT, >::LAYOUT, >::LAYOUT, >::LAYOUT, @@ -343,14 +328,14 @@ fn same_different_abi_stability() { ::LAYOUT, >::LAYOUT, >::LAYOUT, - >::LAYOUT, - >::LAYOUT, + >::LAYOUT, + >::LAYOUT, >::LAYOUT, // NonOwningPhantom and PhantomData share the same type layout, // so the NonOwningPhantom types here have to be different ,)>>::LAYOUT, - ,u16)>>::LAYOUT, - ,u16,u32)>>::LAYOUT, + , u16)>>::LAYOUT, + , u16, u32)>>::LAYOUT, >>::LAYOUT, >::LAYOUT, >::LAYOUT, @@ -408,7 +393,6 @@ fn same_different_abi_stability() { ]); } - let (_dur, ()) = core_extensions::measure_time::measure(|| { for (i, this) in list.iter().cloned().enumerate() { for (j, other) in list.iter().cloned().enumerate() { @@ -420,7 +404,10 @@ fn same_different_abi_stability() { } } - for this in vec![>::LAYOUT, >::LAYOUT] { + for this in vec![ + >::LAYOUT, + >::LAYOUT, + ] { assert_equal_type_layout(>::LAYOUT, this) } }); @@ -428,7 +415,6 @@ fn same_different_abi_stability() { // println!("taken {} to check all listed layouts", dur); } - #[cfg(miri)] #[test] fn same_different_abi_stability() { @@ -438,7 +424,6 @@ fn same_different_abi_stability() { let l3 = ::LAYOUT; let l6 = >::LAYOUT; let l7 = >::LAYOUT; - assert_equal_type_layout(l0, l0); assert_different_type_layout(l0, l1); @@ -465,7 +450,7 @@ fn same_different_abi_stability() { } } -#[cfg_attr(not(miri),test)] +#[cfg_attr(not(miri), test)] fn compare_references() { let list = vec![ <&mut ()>::LAYOUT, @@ -488,19 +473,18 @@ fn compare_references() { } } - for this in vec![>::LAYOUT, >::LAYOUT] { + for this in vec![ + >::LAYOUT, + >::LAYOUT, + ] { assert_equal_type_layout(>::LAYOUT, this) } }); } - #[cfg(test)] fn different_zeroness() { - const ZEROABLE_ABI: &'static TypeLayout = &{ - <&()>::LAYOUT - ._set_is_nonzero(false) - }; + const ZEROABLE_ABI: &'static TypeLayout = &{ <&()>::LAYOUT._set_is_nonzero(false) }; let non_zero = <&()>::LAYOUT; @@ -512,7 +496,7 @@ fn different_zeroness() { .flatten_errors(); assert!(errs .iter() - .any(|err| matches!(err, AbiInstability::NonZeroness{..}))); + .any(|err| matches!(err, AbiInstability::NonZeroness { .. }))); } #[test] @@ -524,34 +508,31 @@ fn different_name() { .flatten_errors(); assert!(errs .iter() - .any(|err| matches!(err, AbiInstability::Name{..}))); + .any(|err| matches!(err, AbiInstability::Name { .. }))); } - #[test] fn different_field_name() { let regular = regular::Rectangle::LAYOUT; let other = changed_field_name::Rectangle::LAYOUT; - let fields=match other.data() { - TLData::Struct{fields}=>fields.iter().collect::>(), - _=>unreachable!(), + let fields = match other.data() { + TLData::Struct { fields } => fields.iter().collect::>(), + _ => unreachable!(), }; - assert_eq!(fields[0].name(),"x"); - assert_eq!(fields[1].name(),"y"); - assert_eq!(fields[2].name(),"w2"); + assert_eq!(fields[0].name(), "x"); + assert_eq!(fields[1].name(), "y"); + assert_eq!(fields[2].name(), "w2"); let errs = check_layout_compatibility(regular, other) .unwrap_err() .flatten_errors(); assert!(errs .iter() - .any(|err| matches!(err, AbiInstability::UnexpectedField{..}))); + .any(|err| matches!(err, AbiInstability::UnexpectedField { .. }))); } - - #[test] fn swapped_fields() { let regular = regular::Rectangle::LAYOUT; @@ -564,7 +545,7 @@ fn swapped_fields() { .flatten_errors(); assert!(errs .iter() - .any(|x| matches!(x, AbiInstability::UnexpectedField{..}))) + .any(|x| matches!(x, AbiInstability::UnexpectedField { .. }))) } } @@ -642,7 +623,7 @@ pub(super) mod gen_more_lts_d { } pub(super) mod gen_more_tys { - use super::{PhantomData,Tuple2}; + use super::{PhantomData, Tuple2}; #[repr(C)] #[derive(abi_stable::StableAbi)] pub struct Generics { @@ -679,7 +660,7 @@ fn different_generics() { .flatten_errors(); assert!(errs .iter() - .any(|err| matches!(err, AbiInstability::GenericParamCount{..}))); + .any(|err| matches!(err, AbiInstability::GenericParamCount { .. }))); } } @@ -692,7 +673,7 @@ fn different_generics() { .flatten_errors(); assert!(errs .iter() - .any(|err| matches!(err, AbiInstability::FieldLifetimeMismatch{..}))); + .any(|err| matches!(err, AbiInstability::FieldLifetimeMismatch { .. }))); } } } @@ -701,13 +682,12 @@ fn different_generics() { //// Enums ////////////////////////////////////////////////////////// - pub(super) mod enum_extra_fields_a { #[repr(C)] #[derive(abi_stable::StableAbi)] pub enum Enum { Variant0, - Variant1 { a: u32,b:u32 }, + Variant1 { a: u32, b: u32 }, } } @@ -720,7 +700,6 @@ pub(super) mod misnamed_variant { } } - #[cfg(test)] fn variant_mismatch() { let regular = basic_enum::Enum::LAYOUT; @@ -732,7 +711,7 @@ fn variant_mismatch() { .flatten_errors(); assert!(errs .iter() - .any(|err| matches!(err, AbiInstability::UnexpectedVariant{..}))); + .any(|err| matches!(err, AbiInstability::UnexpectedVariant { .. }))); } { @@ -742,12 +721,10 @@ fn variant_mismatch() { .flatten_errors(); assert!(errs .iter() - .any(|err| matches!(err, AbiInstability::TooManyVariants{..}))); + .any(|err| matches!(err, AbiInstability::TooManyVariants { .. }))); } } - - ////////////////////////////////////////////////////////////////////////////// /// Modules,with function pointers @@ -756,8 +733,8 @@ pub(super) mod mod_0 { #[repr(C)] #[derive(abi_stable::StableAbi)] - pub struct Mod{ - pub function_0: extern "C" fn(&mut u32,u64) -> RString, + pub struct Mod { + pub function_0: extern "C" fn(&mut u32, u64) -> RString, pub function_1: extern "C" fn() -> RString, } } @@ -767,42 +744,39 @@ pub(super) mod mod_0b { #[repr(C)] #[derive(abi_stable::StableAbi)] - pub struct Mod{ - pub function_0: extern "C" fn(&mut u32,u64,()) -> RString, + pub struct Mod { + pub function_0: extern "C" fn(&mut u32, u64, ()) -> RString, pub function_1: extern "C" fn() -> RString, } } - pub(super) mod mod_1 { use abi_stable::std_types::RString; #[repr(C)] #[derive(abi_stable::StableAbi)] - pub struct Mod{ - pub function_0: extern "C" fn(&mut u32,u64,RString), + pub struct Mod { + pub function_0: extern "C" fn(&mut u32, u64, RString), pub function_1: extern "C" fn(RString), } } - pub(super) mod mod_2 { use abi_stable::std_types::RString; #[repr(C)] #[derive(abi_stable::StableAbi)] - pub struct Mod{ - pub function_0: extern "C" fn(&mut u32,u64,RString)->RString, + pub struct Mod { + pub function_0: extern "C" fn(&mut u32, u64, RString) -> RString, pub function_1: extern "C" fn(), } } - pub(super) mod mod_3 { use abi_stable::std_types::RString; #[repr(C)] #[derive(abi_stable::StableAbi)] - pub struct Mod{ - pub function_0: extern "C" fn(&mut u32,u64,RString), - pub function_1: extern "C" fn()->RString, + pub struct Mod { + pub function_0: extern "C" fn(&mut u32, u64, RString), + pub function_1: extern "C" fn() -> RString, } } @@ -810,19 +784,18 @@ pub(super) mod mod_4 { use abi_stable::std_types::RString; #[repr(C)] #[derive(abi_stable::StableAbi)] - pub struct Mod{ - pub function_0: extern "C" fn()->RString, - pub function_1: extern "C" fn(&mut u32,u64,RString), + pub struct Mod { + pub function_0: extern "C" fn() -> RString, + pub function_1: extern "C" fn(&mut u32, u64, RString), } } - pub(super) mod mod_6 { use abi_stable::std_types::RString; #[repr(C)] #[derive(abi_stable::StableAbi)] - pub struct Mod{ - pub function_0: extern "C" fn()->RString, + pub struct Mod { + pub function_0: extern "C" fn() -> RString, } } @@ -830,18 +803,15 @@ pub(super) mod mod_6 { pub(super) mod mod_6b { #[repr(C)] #[derive(abi_stable::StableAbi)] - pub struct Mod{ - pub function_0: extern "C" fn()->u32, + pub struct Mod { + pub function_0: extern "C" fn() -> u32, } } - - ////////////////////////////////////////////////////////////////////////////// //// Tagged values ////////////////////////////////////////////////////////////////////////////// - #[cfg(not(feature = "no_fn_promotion"))] mod tagging_items { use super::*; @@ -851,14 +821,13 @@ mod tagging_items { #[derive(abi_stable::StableAbi)] #[sabi( not_stableabi(M), - bound="M:ToTagConst", - tag="::TAG", + bound = "M:ToTagConst", + tag = "::TAG" )] pub struct Tagged(UnsafeIgnoredType); - - pub trait ToTagConst{ - const TAG:Tag; + pub trait ToTagConst { + const TAG: Tag; } macro_rules! declare_tags { @@ -877,8 +846,7 @@ mod tagging_items { ) } - - declare_tags!{ + declare_tags! { const TAG_DEFAULT_0=Tag::null(); const TAG_DEFAULT_1=Tag::bool_(false); const TAG_DEFAULT_2=Tag::int(0); @@ -886,9 +854,9 @@ mod tagging_items { const TAG_DEFAULT_4=Tag::str(""); const TAG_DEFAULT_5=Tag::arr(RSlice::EMPTY); const TAG_DEFAULT_6=Tag::set(RSlice::EMPTY); - + const TAG_EMPTY_SET=Tag::set(RSlice::EMPTY); - + const TAG_SET_A0=Tag::set(rslice![ Tag::str("Sync"), ]); @@ -923,59 +891,69 @@ mod tagging_items { ]); } - - trait TaggedExt{ - const GET_AI:&'static TypeLayout; + trait TaggedExt { + const GET_AI: &'static TypeLayout; } - impl TaggedExt for T - where - Tagged:StableAbi, + where + Tagged: StableAbi, { - const GET_AI:&'static TypeLayout= - as StableAbi>::LAYOUT; + const GET_AI: &'static TypeLayout = as StableAbi>::LAYOUT; } - - #[cfg(not(miri))] #[test] - fn test_tag_subsets(){ - let valid_subsets=vec![ - vec![TAG_EMPTY_SET::GET_AI, TAG_SET_A0::GET_AI, TAG_SET_B0::GET_AI, TAG_SET_C0::GET_AI], - vec![TAG_EMPTY_SET::GET_AI, TAG_SET_A1::GET_AI, TAG_SET_B0::GET_AI, TAG_SET_C0::GET_AI], - vec![TAG_EMPTY_SET::GET_AI, TAG_SET_A2::GET_AI, TAG_SET_B1::GET_AI, TAG_SET_C0::GET_AI], - vec![TAG_EMPTY_SET::GET_AI, TAG_SET_A3::GET_AI, TAG_SET_B1::GET_AI, TAG_SET_C0::GET_AI], + fn test_tag_subsets() { + let valid_subsets = vec![ + vec![ + TAG_EMPTY_SET::GET_AI, + TAG_SET_A0::GET_AI, + TAG_SET_B0::GET_AI, + TAG_SET_C0::GET_AI, + ], + vec![ + TAG_EMPTY_SET::GET_AI, + TAG_SET_A1::GET_AI, + TAG_SET_B0::GET_AI, + TAG_SET_C0::GET_AI, + ], + vec![ + TAG_EMPTY_SET::GET_AI, + TAG_SET_A2::GET_AI, + TAG_SET_B1::GET_AI, + TAG_SET_C0::GET_AI, + ], + vec![ + TAG_EMPTY_SET::GET_AI, + TAG_SET_A3::GET_AI, + TAG_SET_B1::GET_AI, + TAG_SET_C0::GET_AI, + ], ]; - for subset in &valid_subsets { - for (l_i,l_abi) in subset.iter().enumerate() { - for (r_i,r_abi) in subset.iter().enumerate() { - - let res=check_layout_compatibility(l_abi,r_abi); + for (l_i, l_abi) in subset.iter().enumerate() { + for (r_i, r_abi) in subset.iter().enumerate() { + let res = check_layout_compatibility(l_abi, r_abi); if l_i <= r_i { - assert_eq!(res,Ok(())); - }else{ - let errs=res.unwrap_err().flatten_errors(); - assert!( - errs + assert_eq!(res, Ok(())); + } else { + let errs = res.unwrap_err().flatten_errors(); + assert!(errs .iter() - .any(|err| matches!(err, AbiInstability::TagError{..}) ) - ); + .any(|err| matches!(err, AbiInstability::TagError { .. }))); } } } } } - #[cfg(not(miri))] #[test] - fn test_tag_incompatible(){ - let incompatible_sets=vec![ + fn test_tag_incompatible() { + let incompatible_sets = vec![ vec![ TAG_SET_A0::GET_AI, TAG_SET_A1::GET_AI, @@ -988,19 +966,17 @@ mod tagging_items { ]; for subset in &incompatible_sets { - for (l_i,l_abi) in subset.iter().enumerate() { - for (r_i,r_abi) in subset.iter().enumerate() { - let res=check_layout_compatibility(l_abi,r_abi); + for (l_i, l_abi) in subset.iter().enumerate() { + for (r_i, r_abi) in subset.iter().enumerate() { + let res = check_layout_compatibility(l_abi, r_abi); if l_i == r_i { - assert_eq!(res,Ok(())); - }else{ - let errs=res.unwrap_err().flatten_errors(); - assert!( - errs + assert_eq!(res, Ok(())); + } else { + let errs = res.unwrap_err().flatten_errors(); + assert!(errs .iter() - .any(|err| matches!(err, AbiInstability::TagError{..}) ) - ); + .any(|err| matches!(err, AbiInstability::TagError { .. }))); } } } diff --git a/abi_stable/tests/layout_tests_modules.rs b/abi_stable/tests/layout_tests_modules.rs index 20199b3a..d19b1848 100644 --- a/abi_stable/tests/layout_tests_modules.rs +++ b/abi_stable/tests/layout_tests_modules.rs @@ -1,47 +1,45 @@ #![allow(non_camel_case_types)] #![cfg_attr(miri, allow(unused_imports))] - mod layout_tests { - #[cfg(all(test,not(feature="only_new_tests")))] - mod value; - #[cfg(all(test,not(feature="only_new_tests")))] - mod prefix_types; - #[cfg(all(test,not(feature="only_new_tests")))] + #[cfg(all(test, not(feature = "only_new_tests")))] mod erased_types; + #[cfg(all(test, not(feature = "only_new_tests")))] + mod prefix_types; + #[cfg(all(test, not(feature = "only_new_tests")))] + mod value; - #[cfg(all(test,not(feature="only_new_tests")))] + #[cfg(all(test, not(feature = "only_new_tests")))] mod pointer_types; - #[cfg(all(test,not(feature="only_new_tests")))] + #[cfg(all(test, not(feature = "only_new_tests")))] mod repr_and_discr; - #[cfg(all(test,not(feature="only_new_tests")))] + #[cfg(all(test, not(feature = "only_new_tests")))] mod sabi_trait; mod nonexhaustive_enums; - #[cfg(all(test,not(feature="only_new_tests")))] + #[cfg(all(test, not(feature = "only_new_tests")))] mod get_static_equivalent; - #[cfg(all(test,not(feature="only_new_tests")))] + #[cfg(all(test, not(feature = "only_new_tests")))] mod extra_checks_combined; - #[cfg(all(test,not(feature="only_new_tests")))] + #[cfg(all(test, not(feature = "only_new_tests")))] mod stable_abi_attributes; - #[cfg(all(test,not(feature="only_new_tests")))] + #[cfg(all(test, not(feature = "only_new_tests")))] mod const_params; - #[cfg(all(test,not(feature="only_new_tests")))] + #[cfg(all(test, not(feature = "only_new_tests")))] mod lifetime_indices_tests; // #[cfg(test)] - #[cfg(all(test,not(feature="only_new_tests")))] + #[cfg(all(test, not(feature = "only_new_tests")))] mod get_type_layout; - - #[cfg(all(test,not(feature="only_new_tests")))] - mod shared_types; + #[cfg(all(test, not(feature = "only_new_tests")))] + mod shared_types; } diff --git a/abi_stable_derive/src/arenas.rs b/abi_stable_derive/src/arenas.rs index 7c7e5642..8b6dfa9d 100644 --- a/abi_stable_derive/src/arenas.rs +++ b/abi_stable_derive/src/arenas.rs @@ -81,4 +81,3 @@ declare_arenas! { strings: String, paths: syn::Path, } - diff --git a/abi_stable_derive/src/attribute_parsing.rs b/abi_stable_derive/src/attribute_parsing.rs index 20526173..34d095f9 100644 --- a/abi_stable_derive/src/attribute_parsing.rs +++ b/abi_stable_derive/src/attribute_parsing.rs @@ -1,18 +1,5 @@ -pub(crate) use as_derive_utils::attribute_parsing::{ - with_nested_meta -}; - +pub(crate) use as_derive_utils::attribute_parsing::with_nested_meta; /////////////////////////////////////////////////////////////////////////////// - - - - - /////////////////////////////////////////////////////////////////////////////// - - - - - diff --git a/abi_stable_derive/src/common_tokens.rs b/abi_stable_derive/src/common_tokens.rs index f7620c99..9435c550 100644 --- a/abi_stable_derive/src/common_tokens.rs +++ b/abi_stable_derive/src/common_tokens.rs @@ -3,34 +3,33 @@ use proc_macro2::Span; use syn::Ident; #[derive(Debug)] -pub(crate) struct StartLenTokens{ - pub(crate) start_len:Ident, - pub(crate) new:Ident, +pub(crate) struct StartLenTokens { + pub(crate) start_len: Ident, + pub(crate) new: Ident, } -impl StartLenTokens{ - pub(crate) fn new(span:Span)->Self{ - Self{ - start_len:Ident::new("__StartLen",span), - new:Ident::new("new",span), +impl StartLenTokens { + pub(crate) fn new(span: Span) -> Self { + Self { + start_len: Ident::new("__StartLen", span), + new: Ident::new("new", span), } } } - #[derive(Debug)] -pub(crate) struct FnPointerTokens{ +pub(crate) struct FnPointerTokens { pub(crate) c_abi_lit: ::syn::LitStr, pub(crate) static_: Ident, pub(crate) underscore: Ident, } -impl FnPointerTokens{ - pub fn new(span:Span)->Self{ - Self{ - c_abi_lit:syn::parse_str(r#""C""#).expect("BUG"), - static_:Ident::new("static",span), - underscore:Ident::new("_",span), +impl FnPointerTokens { + pub fn new(span: Span) -> Self { + Self { + c_abi_lit: syn::parse_str(r#""C""#).expect("BUG"), + static_: Ident::new("static", span), + underscore: Ident::new("_", span), } } } diff --git a/abi_stable_derive/src/composite_collections.rs b/abi_stable_derive/src/composite_collections.rs index 9b6338e9..274ad015 100644 --- a/abi_stable_derive/src/composite_collections.rs +++ b/abi_stable_derive/src/composite_collections.rs @@ -9,103 +9,93 @@ whose indices fit in a u16. use std::{ borrow::Borrow, convert::TryFrom, - fmt::{Debug,Display}, + fmt::{Debug, Display}, marker::PhantomData, - ops::{Add,Range}, + ops::{Add, Range}, }; -use as_derive_utils::{ - to_stream, - return_syn_err, -}; - -use proc_macro2::{TokenStream as TokenStream2,Span}; -use quote::{ToTokens}; +use as_derive_utils::{return_syn_err, to_stream}; -use crate::{ - common_tokens::StartLenTokens, -}; +use proc_macro2::{Span, TokenStream as TokenStream2}; +use quote::ToTokens; +use crate::common_tokens::StartLenTokens; /// A `{start:16,len:u16}` range. -pub type SmallStartLen=StartLen; - +pub type SmallStartLen = StartLen; /// A `{start:N,len:N}` range. -#[derive(Copy,Clone,Debug,PartialEq,Eq,Ord,PartialOrd)] -pub struct StartLen{ - pub start:N, - pub len:N, +#[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd)] +pub struct StartLen { + pub start: N, + pub len: N, } -impl StartLen{ - abi_stable_shared::declare_start_len_bit_methods!{} +impl StartLen { + abi_stable_shared::declare_start_len_bit_methods! {} } -impl StartLen{ +impl StartLen { #[inline] - pub(crate) fn from_start_len(start:usize,len:usize)->Self + pub(crate) fn from_start_len(start: usize, len: usize) -> Self where - N:TryFrom, - N::Error:Debug, + N: TryFrom, + N::Error: Debug, { - Self{ + Self { start: N::try_from(start).unwrap(), len: N::try_from(len).unwrap(), } } #[inline] - pub const fn new(start:N,len:N)->Self{ - Self{start,len} + pub const fn new(start: N, len: N) -> Self { + Self { start, len } } #[allow(dead_code)] - pub(crate) fn into_range(self)->Range + pub(crate) fn into_range(self) -> Range where - N:Copy+Add + N: Copy + Add, { - self.start..(self.start+self.len) + self.start..(self.start + self.len) } #[inline] - pub(crate) fn tokenizer(self,ctokens:&StartLenTokens)->StartLenTokenizer<'_,N>{ - StartLenTokenizer{ - start:self.start, - len:self.len, + pub(crate) fn tokenizer(self, ctokens: &StartLenTokens) -> StartLenTokenizer<'_, N> { + StartLenTokenizer { + start: self.start, + len: self.len, ctokens, } } } -impl StartLen{ - pub const DUMMY:Self=Self{ - start:(1u16<<15)+1, - len:(1u16<<15)+1, +impl StartLen { + pub const DUMMY: Self = Self { + start: (1u16 << 15) + 1, + len: (1u16 << 15) + 1, }; - pub const EMPTY:Self=Self{ - start:0, - len:0, - }; + pub const EMPTY: Self = Self { start: 0, len: 0 }; /// The start of this range. #[inline] - pub const fn start(self)->usize{ + pub const fn start(self) -> usize { self.start as usize } #[inline] - pub const fn len(self)->usize{ + pub const fn len(self) -> usize { self.len as usize } /// Converts this StartLen to a u32. - pub const fn to_u32(self)->u32{ + pub const fn to_u32(self) -> u32 { self.start as u32 | ((self.len as u32) << 16) } - pub fn check_ident_length(&self,span:Span)->Result<(),syn::Error>{ + pub fn check_ident_length(&self, span: Span) -> Result<(), syn::Error> { if self.len > Self::IDENT_MAX_LEN { return_syn_err!( span, @@ -117,165 +107,162 @@ impl StartLen{ } } -pub struct StartLenTokenizer<'a,N>{ - start:N, - len:N, - ctokens:&'a StartLenTokens, +pub struct StartLenTokenizer<'a, N> { + start: N, + len: N, + ctokens: &'a StartLenTokens, } -impl<'a,N> ToTokens for StartLenTokenizer<'a,N> +impl<'a, N> ToTokens for StartLenTokenizer<'a, N> where - N:ToTokens + N: ToTokens, { - fn to_tokens(&self,ts: &mut TokenStream2) { - use syn::token::{Colon2,Comma,Paren}; + fn to_tokens(&self, ts: &mut TokenStream2) { + use syn::token::{Colon2, Comma, Paren}; - let ct=self.ctokens; + let ct = self.ctokens; to_stream!(ts; ct.start_len,Colon2::default(),ct.new ); - Paren::default().surround(ts,|ts|{ + Paren::default().surround(ts, |ts| { to_stream!(ts; self.start,Comma::default(),self.len ); }); } } - /////////////////////////////////////////////////////////////////////// - #[allow(dead_code)] -pub type SmallCompositeString=CompositeString; - +pub type SmallCompositeString = CompositeString; /// A String-like type, /// returning a `{start:16,len:u16}` range from methods that extend it. -pub struct CompositeString{ - buffer:String, - _integer:PhantomData, +pub struct CompositeString { + buffer: String, + _integer: PhantomData, } #[allow(dead_code)] impl CompositeString where - N:TryFrom, - N::Error:Debug, + N: TryFrom, + N::Error: Debug, { - pub fn new()->Self{ - Self{ - buffer:String::with_capacity(128), - _integer:PhantomData, + pub fn new() -> Self { + Self { + buffer: String::with_capacity(128), + _integer: PhantomData, } } - fn len(&self)->usize{ + fn len(&self) -> usize { self.buffer.len() } - pub fn push_str(&mut self,s:&str)->StartLen{ - let start=self.len(); + pub fn push_str(&mut self, s: &str) -> StartLen { + let start = self.len(); self.buffer.push_str(s); - StartLen::from_start_len(start,s.len()) + StartLen::from_start_len(start, s.len()) } - pub fn push_display(&mut self,s:&D)->StartLen - where D:Display, + pub fn push_display(&mut self, s: &D) -> StartLen + where + D: Display, { use std::fmt::Write; - let start=self.len(); - let _=write!(self.buffer,"{}",s); - StartLen::from_start_len(start,self.len()-start) + let start = self.len(); + let _ = write!(self.buffer, "{}", s); + StartLen::from_start_len(start, self.len() - start) } #[allow(dead_code)] - pub fn extend_with_str(&mut self,separator:&str,iter:I)->StartLen + pub fn extend_with_str(&mut self, separator: &str, iter: I) -> StartLen where - I:IntoIterator, - I::Item:Borrow, + I: IntoIterator, + I::Item: Borrow, { - let start=self.len(); + let start = self.len(); for s in iter { self.buffer.push_str(s.borrow()); self.buffer.push_str(separator); } - StartLen::from_start_len(start,self.len()-start) + StartLen::from_start_len(start, self.len() - start) } - pub fn extend_with_display(&mut self,separator:&str,iter:I)->StartLen + pub fn extend_with_display(&mut self, separator: &str, iter: I) -> StartLen where - I:IntoIterator, - I::Item:Display, + I: IntoIterator, + I::Item: Display, { use std::fmt::Write; - let start=self.len(); + let start = self.len(); for elem in iter { - let _=write!(self.buffer,"{}",elem); + let _ = write!(self.buffer, "{}", elem); self.buffer.push_str(separator); } - StartLen::from_start_len(start,self.len()-start) + StartLen::from_start_len(start, self.len() - start) } - pub fn into_inner(self)->String{ + pub fn into_inner(self) -> String { self.buffer } - pub fn as_inner(&self)->&str{ + pub fn as_inner(&self) -> &str { &self.buffer } } /////////////////////////////////////////////////////////////////////// -pub type SmallCompositeVec=CompositeVec; +pub type SmallCompositeVec = CompositeVec; /// A Vec-like type, /// returning a `{start:16,len:u16}` range from methods that extend it. -pub struct CompositeVec{ - list:Vec, - _integer:PhantomData, +pub struct CompositeVec { + list: Vec, + _integer: PhantomData, } - #[allow(dead_code)] -impl CompositeVec +impl CompositeVec where - N:TryFrom, - N::Error:Debug, + N: TryFrom, + N::Error: Debug, { - pub fn new()->Self{ - Self{ - list:Vec::new(), - _integer:PhantomData, + pub fn new() -> Self { + Self { + list: Vec::new(), + _integer: PhantomData, } } - pub fn with_capacity(capacity:usize)->Self{ - Self{ - list:Vec::with_capacity(capacity), - _integer:PhantomData, + pub fn with_capacity(capacity: usize) -> Self { + Self { + list: Vec::with_capacity(capacity), + _integer: PhantomData, } } - fn len(&self)->usize{ + fn len(&self) -> usize { self.list.len() } - pub fn push(&mut self,elem:T)->u16{ - let ind=self.len(); + pub fn push(&mut self, elem: T) -> u16 { + let ind = self.len(); self.list.push(elem); ind as u16 } - pub fn extend(&mut self,iter:I)->StartLen + pub fn extend(&mut self, iter: I) -> StartLen where - I:IntoIterator, + I: IntoIterator, { - let start=self.len(); + let start = self.len(); self.list.extend(iter); - StartLen::from_start_len(start,self.len()-start) + StartLen::from_start_len(start, self.len() - start) } - pub fn into_inner(self)->Vec{ + pub fn into_inner(self) -> Vec { self.list } - pub fn as_inner(&self)->&[T]{ + pub fn as_inner(&self) -> &[T] { &self.list } -} \ No newline at end of file +} diff --git a/abi_stable_derive/src/concat_and_ranges.rs b/abi_stable_derive/src/concat_and_ranges.rs index f6c8d2a4..65d81836 100644 --- a/abi_stable_derive/src/concat_and_ranges.rs +++ b/abi_stable_derive/src/concat_and_ranges.rs @@ -48,12 +48,12 @@ impl Parse for ConcatenatedStrings { } } -pub fn macro_impl(input: TokenStream2) -> Result { +pub fn macro_impl(input: TokenStream2) -> Result { let ConcatenatedStrings { concatenated: conc_ident, strings, - }=syn::parse2::(input)?; - + } = syn::parse2::(input)?; + let capacity = strings.iter().map(|sav| sav.string.len() + 1).sum(); let mut concatenated = String::with_capacity(capacity); @@ -61,10 +61,10 @@ pub fn macro_impl(input: TokenStream2) -> Result { let mut lengths = Vec::::with_capacity(strings.len()); for sav in &strings { - let start=concatenated.len() as u16; + let start = concatenated.len() as u16; starts.push(start); concatenated.push_str(&sav.string); - lengths.push(concatenated.len() as u16-start); + lengths.push(concatenated.len() as u16 - start); concatenated.push(';'); } @@ -84,4 +84,4 @@ pub fn macro_impl(input: TokenStream2) -> Result { pub const #variable:StartLen= StartLen::new(#starts,#lengths); )* )) -} \ No newline at end of file +} diff --git a/abi_stable_derive/src/constants.rs b/abi_stable_derive/src/constants.rs index e69de29b..8b137891 100644 --- a/abi_stable_derive/src/constants.rs +++ b/abi_stable_derive/src/constants.rs @@ -0,0 +1 @@ + diff --git a/abi_stable_derive/src/export_root_module_impl.rs b/abi_stable_derive/src/export_root_module_impl.rs index 00e54140..f4c555a7 100644 --- a/abi_stable_derive/src/export_root_module_impl.rs +++ b/abi_stable_derive/src/export_root_module_impl.rs @@ -4,9 +4,7 @@ The implementation of the `#[export_root_module]` attribute. use super::*; -use as_derive_utils::{ - return_spanned_err, -}; +use as_derive_utils::return_spanned_err; use syn::Ident; @@ -14,54 +12,47 @@ use proc_macro2::Span; use abi_stable_shared::mangled_root_module_loader_name; - - - #[doc(hidden)] pub fn export_root_module_attr(_attr: TokenStream1, item: TokenStream1) -> TokenStream1 { - parse_or_compile_err( item, export_root_module_inner ).into() + parse_or_compile_err(item, export_root_module_inner).into() } #[cfg(test)] -fn export_root_module_str(item: &str)-> Result { - syn::parse_str(item) - .and_then(export_root_module_inner) +fn export_root_module_str(item: &str) -> Result { + syn::parse_str(item).and_then(export_root_module_inner) } +fn export_root_module_inner(mut input: ItemFn) -> Result { + let vis = &input.vis; -fn export_root_module_inner(mut input:ItemFn)->Result{ - let vis=&input.vis; - - let unsafe_no_layout_constant_path= + let unsafe_no_layout_constant_path = syn::parse_str::("unsafe_no_layout_constant").expect("BUG"); - let mut found_unsafe_no_layout_constant=false; - input.attrs.retain(|attr|{ - let is_it=attr.path==unsafe_no_layout_constant_path; - found_unsafe_no_layout_constant=found_unsafe_no_layout_constant||is_it; + let mut found_unsafe_no_layout_constant = false; + input.attrs.retain(|attr| { + let is_it = attr.path == unsafe_no_layout_constant_path; + found_unsafe_no_layout_constant = found_unsafe_no_layout_constant || is_it; !is_it }); - let assoc_constant=Ident::new( - if found_unsafe_no_layout_constant { "CONSTANTS_NO_ABI_INFO" }else{ "CONSTANTS" }, + let assoc_constant = Ident::new( + if found_unsafe_no_layout_constant { + "CONSTANTS_NO_ABI_INFO" + } else { + "CONSTANTS" + }, Span::call_site(), ); - let ret_ty=match &input.sig.output { - syn::ReturnType::Default=> - return_spanned_err!( - input.sig.ident, - "The return type can't be `()`" - ), - syn::ReturnType::Type(_,ty)=> - ty, + let ret_ty = match &input.sig.output { + syn::ReturnType::Default => { + return_spanned_err!(input.sig.ident, "The return type can't be `()`") + } + syn::ReturnType::Type(_, ty) => ty, }; - - let original_fn_ident=&input.sig.ident; - let export_name=Ident::new( - &mangled_root_module_loader_name(), - Span::call_site(), - ); + let original_fn_ident = &input.sig.ident; + + let export_name = Ident::new(&mangled_root_module_loader_name(), Span::call_site()); Ok(quote!( #input @@ -84,27 +75,25 @@ fn export_root_module_inner(mut input:ItemFn)->Result{ )) } - - #[cfg(test)] -mod tests{ +mod tests { use super::*; #[test] - fn test_output(){ - let list=vec![ + fn test_output() { + let list = vec![ ( r##" pub fn hello()->RString{} "##, - "RootModule>::CONSTANTS" + "RootModule>::CONSTANTS", ), ( r##" #[unsafe_no_layout_constant] pub fn hello()->RString{} "##, - "RootModule>::CONSTANTS_NO_ABI_INFO" + "RootModule>::CONSTANTS_NO_ABI_INFO", ), ( r##" @@ -112,7 +101,7 @@ mod tests{ #[unsafe_no_layout_constant] pub fn hello()->RString{} "##, - "RootModule>::CONSTANTS_NO_ABI_INFO" + "RootModule>::CONSTANTS_NO_ABI_INFO", ), ( r##" @@ -121,7 +110,7 @@ mod tests{ #[hello] pub fn hello()->RString{} "##, - "RootModule>::CONSTANTS_NO_ABI_INFO" + "RootModule>::CONSTANTS_NO_ABI_INFO", ), ( r##" @@ -129,16 +118,18 @@ mod tests{ #[hello] pub fn hello()->RString{} "##, - "RootModule>::CONSTANTS_NO_ABI_INFO" + "RootModule>::CONSTANTS_NO_ABI_INFO", ), ]; - for (item,expected_const) in list { - let str_out=export_root_module_str(item).unwrap().to_string() + for (item, expected_const) in list { + let str_out = export_root_module_str(item) + .unwrap() + .to_string() .chars() - .filter(|c|!c.is_whitespace()) + .filter(|c| !c.is_whitespace()) .collect::(); assert!(str_out.contains(expected_const)); } } -} \ No newline at end of file +} diff --git a/abi_stable_derive/src/fn_pointer_extractor.rs b/abi_stable_derive/src/fn_pointer_extractor.rs index 2629ec4b..b3f168f1 100644 --- a/abi_stable_derive/src/fn_pointer_extractor.rs +++ b/abi_stable_derive/src/fn_pointer_extractor.rs @@ -1,17 +1,11 @@ /*! -Contains visitor type for +Contains visitor type for extracting function pointers and the referenced lifetimes of the fields of a type declaration. */ -use std::{ - collections::HashSet, - mem, -}; +use std::{collections::HashSet, mem}; -use as_derive_utils::{ - spanned_err, - syn_err, -}; +use as_derive_utils::{spanned_err, syn_err}; use core_extensions::SelfOps; @@ -26,15 +20,13 @@ use proc_macro2::Span; use quote::ToTokens; - - +use crate::*; use crate::{ common_tokens::FnPointerTokens, - lifetimes::{LifetimeIndex,LifetimeCounters}, ignored_wrapper::Ignored, - utils::{LinearResult,SynResultExt}, + lifetimes::{LifetimeCounters, LifetimeIndex}, + utils::{LinearResult, SynResultExt}, }; -use crate::*; /// Information about all the function pointers in a type declaration. #[derive(Clone, Debug, PartialEq, Hash)] @@ -60,18 +52,18 @@ pub(crate) struct Function<'a> { pub(crate) func_span: Ignored, /// The index of the first lifetime the function declares,if there are any. - pub(crate) first_bound_lt:usize, - + pub(crate) first_bound_lt: usize, + /// The index of the first unnamed lifetime of the function,if there are any. - pub(crate) first_unnamed_bound_lt:usize, - + pub(crate) first_unnamed_bound_lt: usize, + /// The named lifetimes for this function pointer type, /// the ones declared within `for<'a,'b,'c>`. pub(crate) named_bound_lts: Vec<&'a Ident>, /// A set version of the `named_bound_lts` field. pub(crate) named_bound_lt_set: Ignored>, /// The amount of lifetimes declared by the function pointer. - pub(crate) bound_lts_count:usize, + pub(crate) bound_lts_count: usize, pub(crate) is_unsafe: bool, @@ -84,7 +76,6 @@ pub(crate) struct Function<'a> { /// /// None if its return type is `()`. pub(crate) returns: Option>, - } #[derive(Clone, Debug, PartialEq, Hash)] @@ -101,18 +92,18 @@ pub(crate) struct FnParamRet<'a> { pub(crate) param_or_ret: ParamOrReturn, } -impl<'a> FnParamRet<'a>{ +impl<'a> FnParamRet<'a> { /// Constructs an `FnParamRet` for a `()` return type. - pub fn unit_ret(arenas:&'a Arenas)->Self{ - let unit=syn::TypeTuple{ - paren_token:Default::default(), - elems:Punctuated::default(), + pub fn unit_ret(arenas: &'a Arenas) -> Self { + let unit = syn::TypeTuple { + paren_token: Default::default(), + elems: Punctuated::default(), }; - FnParamRet{ - name:None, - lifetime_refs:Vec::new(), - ty:arenas.alloc( syn::Type::from(unit) ), - param_or_ret:ParamOrReturn::Return, + FnParamRet { + name: None, + lifetime_refs: Vec::new(), + ty: arenas.alloc(syn::Type::from(unit)), + param_or_ret: ParamOrReturn::Return, } } } @@ -122,13 +113,11 @@ pub(crate) struct VisitFieldRet<'a> { /// The lifetimes that the field references. pub(crate) referenced_lifetimes: Vec, /// The function pointer types in the field. - pub(crate) functions:Vec>, + pub(crate) functions: Vec>, } - ///////////// - #[allow(dead_code)] impl<'a> TypeVisitor<'a> { #[inline(never)] @@ -140,7 +129,7 @@ impl<'a> TypeVisitor<'a> { env_generics: generics, }, vars: Vars { - allow_type_macros:false, + allow_type_macros: false, referenced_lifetimes: Vec::default(), fn_info: FnInfo { parent_generics: &generics, @@ -148,43 +137,43 @@ impl<'a> TypeVisitor<'a> { initial_bound_lifetime: generics.lifetimes().count(), functions: Vec::new(), }, - errors:LinearResult::ok(()), + errors: LinearResult::ok(()), }, } } - pub fn allow_type_macros(&mut self){ - self.vars.allow_type_macros=true; + pub fn allow_type_macros(&mut self) { + self.vars.allow_type_macros = true; } /// Gets the arena this references. - pub fn arenas(&self)->&'a Arenas{ + pub fn arenas(&self) -> &'a Arenas { self.refs.arenas } /// Gets the CommonTokens this references. - pub fn ctokens(&self)->&'a FnPointerTokens{ + pub fn ctokens(&self) -> &'a FnPointerTokens { self.refs.ctokens } /// Gets the generic parameters this references. - pub fn env_generics(&self)->&'a Generics{ + pub fn env_generics(&self) -> &'a Generics { self.refs.env_generics } /// Visit a field type, /// returning the function pointer types and referenced lifetimes. - pub fn visit_field(&mut self,ty: &mut Type) -> VisitFieldRet<'a> { + pub fn visit_field(&mut self, ty: &mut Type) -> VisitFieldRet<'a> { self.visit_type_mut(ty); VisitFieldRet { referenced_lifetimes: mem::replace(&mut self.vars.referenced_lifetimes, Vec::new()), - functions:mem::replace(&mut self.vars.fn_info.functions, Vec::new()), + functions: mem::replace(&mut self.vars.fn_info.functions, Vec::new()), } } - pub fn get_errors(&mut self)->Result<(),syn::Error>{ + pub fn get_errors(&mut self) -> Result<(), syn::Error> { self.vars.errors.take() } - pub fn into_fn_info(self)->FnInfo<'a>{ + pub fn into_fn_info(self) -> FnInfo<'a> { self.vars.fn_info } } @@ -193,7 +182,7 @@ impl<'a> TypeVisitor<'a> { /// Whether this is a parameter or a return type/value. #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] -pub(crate)enum ParamOrReturn { +pub(crate) enum ParamOrReturn { Param, Return, } @@ -254,7 +243,7 @@ struct FnParamRetLifetimes { impl FnParamRetLifetimes { fn new(param_or_ret: ParamOrReturn, span: Option) -> Self { Self { - span:span.unwrap_or_else(Span::call_site), + span: span.unwrap_or_else(Span::call_site), lifetime_refs: Vec::new(), param_or_ret, } @@ -267,9 +256,9 @@ impl<'a> Vars<'a> { /// Registers a lifetime index, /// selecting those that come from the type declaration itself. pub fn add_referenced_env_lifetime(&mut self, ind: LifetimeIndex) { - let is_env_lt = match (ind,ind.to_param()) { - (LifetimeIndex::STATIC,_) => true, - (_,Some(index))=> index < self.fn_info.env_lifetimes.len(), + let is_env_lt = match (ind, ind.to_param()) { + (LifetimeIndex::STATIC, _) => true, + (_, Some(index)) => index < self.fn_info.env_lifetimes.len(), _ => false, }; if is_env_lt { @@ -287,24 +276,20 @@ impl<'a> VisitMut for TypeVisitor<'a> { let ctokens = self.refs.ctokens; let arenas = self.refs.arenas; - let func_span=func.span(); + let func_span = func.span(); - let is_unsafe=func.unsafety.is_some(); + let is_unsafe = func.unsafety.is_some(); - let abi = func - .abi - .as_ref() - .map(|x| x.name.as_ref()); - const ABI_ERR:&str="must write `extern \"C\" fn` for function pointer types."; + let abi = func.abi.as_ref().map(|x| x.name.as_ref()); + const ABI_ERR: &str = "must write `extern \"C\" fn` for function pointer types."; match abi { - Some(Some(abi)) if *abi==ctokens.c_abi_lit => {} + Some(Some(abi)) if *abi == ctokens.c_abi_lit => {} Some(Some(abi)) => { - self.vars.errors.push_err(spanned_err!( - abi, - "Abi not supported for function pointers", - )); + self.vars + .errors + .push_err(spanned_err!(abi, "Abi not supported for function pointers",)); return; - }, + } Some(None) => {} None => { self.vars.errors.push_err(spanned_err!( @@ -316,7 +301,6 @@ impl<'a> VisitMut for TypeVisitor<'a> { } } - let named_bound_lts: Vec<&'a Ident> = func .lifetimes .take() // Option @@ -325,46 +309,46 @@ impl<'a> VisitMut for TypeVisitor<'a> { .map(|lt| arenas.alloc(lt.lifetime.ident)) .collect::>(); - let named_bound_lt_set=named_bound_lts.iter().cloned().collect(); + let named_bound_lt_set = named_bound_lts.iter().cloned().collect(); - let first_bound_lt=self.vars.fn_info.initial_bound_lifetime; - let bound_lts_count=named_bound_lts.len(); + let first_bound_lt = self.vars.fn_info.initial_bound_lifetime; + let bound_lts_count = named_bound_lts.len(); let mut current_function = FnVisitor { refs: self.refs, vars: &mut self.vars, - lifetime_counts:LifetimeCounters::new(), + lifetime_counts: LifetimeCounters::new(), current: Function { - fn_token:func.fn_token, + fn_token: func.fn_token, func_span: Ignored::new(func_span), first_bound_lt, - first_unnamed_bound_lt: first_bound_lt+named_bound_lts.len(), + first_unnamed_bound_lt: first_bound_lt + named_bound_lts.len(), bound_lts_count, named_bound_lts, - named_bound_lt_set:Ignored::new(named_bound_lt_set), - bound_lt_spans: Ignored::new(vec![None;bound_lts_count]), + named_bound_lt_set: Ignored::new(named_bound_lt_set), + bound_lt_spans: Ignored::new(vec![None; bound_lts_count]), is_unsafe, params: Vec::new(), returns: None, }, - param_ret: FnParamRetLifetimes::new(ParamOrReturn::Param,None), + param_ret: FnParamRetLifetimes::new(ParamOrReturn::Param, None), }; // Visits a parameter or return type within a function pointer type. fn visit_param_ret<'a, 'b>( this: &mut FnVisitor<'a, 'b>, - name:Option<&'a Ident>, + name: Option<&'a Ident>, ty: &'a mut Type, param_or_ret: ParamOrReturn, ) { - let ty_span=Some(ty.span()); + let ty_span = Some(ty.span()); - this.param_ret = FnParamRetLifetimes::new(param_or_ret,ty_span); + this.param_ret = FnParamRetLifetimes::new(param_or_ret, ty_span); this.visit_type_mut(ty); let param_ret = mem::replace( - &mut this.param_ret, - FnParamRetLifetimes::new(param_or_ret,ty_span) + &mut this.param_ret, + FnParamRetLifetimes::new(param_or_ret, ty_span), ); let param_ret = FnParamRet { @@ -380,10 +364,10 @@ impl<'a> VisitMut for TypeVisitor<'a> { } } - for (i,param) in func.inputs.iter_mut().enumerate() { - let arg_name=extract_fn_arg_name(i,param,arenas); + for (i, param) in func.inputs.iter_mut().enumerate() { + let arg_name = extract_fn_arg_name(i, param, arenas); let ty = arenas.alloc_mut(param.ty.clone()); - visit_param_ret(&mut current_function,arg_name, ty, ParamOrReturn::Param); + visit_param_ret(&mut current_function, arg_name, ty, ParamOrReturn::Param); } let tmp = match mem::replace(&mut func.output, syn::ReturnType::Default) { @@ -391,11 +375,11 @@ impl<'a> VisitMut for TypeVisitor<'a> { syn::ReturnType::Type(_, ty) => Some(arenas.alloc_mut(*ty)), }; if let Some(ty) = tmp { - visit_param_ret(&mut current_function,None, ty, ParamOrReturn::Return); + visit_param_ret(&mut current_function, None, ty, ParamOrReturn::Return); } - let mut current=current_function.current; - current.anonimize_lifetimes(¤t_function.lifetime_counts,&mut self.vars.errors); + let mut current = current_function.current; + current.anonimize_lifetimes(¤t_function.lifetime_counts, &mut self.vars.errors); while func.inputs.pop().is_some() {} self.vars.fn_info.functions.push(current); } @@ -410,11 +394,15 @@ impl<'a> VisitMut for TypeVisitor<'a> { LifetimeIndex::STATIC } else { let env_lifetimes = self.vars.fn_info.env_lifetimes.iter(); - let found_lt = env_lifetimes.enumerate().position(|(_, lt_ident)| *lt_ident == lt); + let found_lt = env_lifetimes + .enumerate() + .position(|(_, lt_ident)| *lt_ident == lt); match found_lt { Some(index) => LifetimeIndex::Param(index as _), None => { - self.vars.errors.push_err(spanned_err!(lt,"unknown lifetime")); + self.vars + .errors + .push_err(spanned_err!(lt, "unknown lifetime")); LifetimeIndex::NONE } } @@ -422,9 +410,9 @@ impl<'a> VisitMut for TypeVisitor<'a> { .piped(|lt| self.vars.add_referenced_env_lifetime(lt)) } - fn visit_type_macro_mut(&mut self, i: &mut syn::TypeMacro){ - if !self.vars.allow_type_macros{ - push_type_macro_err(&mut self.vars.errors,i); + fn visit_type_macro_mut(&mut self, i: &mut syn::TypeMacro) { + if !self.vars.allow_type_macros { + push_type_macro_err(&mut self.vars.errors, i); } } } @@ -433,68 +421,63 @@ impl<'a> VisitMut for TypeVisitor<'a> { impl<'a, 'b> FnVisitor<'a, 'b> { /** -This function does these things: + This function does these things: -- Adds the lifetime as a referenced lifetime. + - Adds the lifetime as a referenced lifetime. -- If `lt` is `Some('someident)` returns `Some('_)`. + - If `lt` is `Some('someident)` returns `Some('_)`. - */ + */ #[inline(never)] - fn setup_lifetime(&mut self, lt: Option<&Ident>, span:Span) -> Option<&'a Ident> { + fn setup_lifetime(&mut self, lt: Option<&Ident>, span: Span) -> Option<&'a Ident> { let ctokens = self.refs.ctokens; let mut ret: Option<&'a Ident> = None; if lt == Some(&ctokens.static_) { LifetimeIndex::STATIC - } else if lt==None || lt==Some(&ctokens.underscore) { + } else if lt == None || lt == Some(&ctokens.underscore) { match self.param_ret.param_or_ret { - ParamOrReturn::Param => { - self.new_bound_lifetime(span) - }, - ParamOrReturn::Return => - match self.current.bound_lts_count { - 0 =>{ - self.vars.errors.push_err(syn_err!( - span, - "attempted to use an elided lifetime in the \ + ParamOrReturn::Param => self.new_bound_lifetime(span), + ParamOrReturn::Return => match self.current.bound_lts_count { + 0 => { + self.vars.errors.push_err(syn_err!( + span, + "attempted to use an elided lifetime in the \ return type when there are no lifetimes \ used in any parameter", - )); - LifetimeIndex::NONE - } - 1=> { - LifetimeIndex::Param( - self.vars.fn_info.initial_bound_lifetime as _, - ) - } - _ =>{ - self.vars.errors.push_err(syn_err!( - span, - "attempted to use an elided lifetime in the \ + )); + LifetimeIndex::NONE + } + 1 => LifetimeIndex::Param(self.vars.fn_info.initial_bound_lifetime as _), + _ => { + self.vars.errors.push_err(syn_err!( + span, + "attempted to use an elided lifetime in the \ return type when there are multiple lifetimes used \ in parameters.", - )); - LifetimeIndex::NONE - } - }, + )); + LifetimeIndex::NONE + } + }, } } else { - let lt=lt.expect("BUG"); + let lt = lt.expect("BUG"); let env_lts = self.vars.fn_info.env_lifetimes.iter(); let fn_lts = self.current.named_bound_lts.iter(); let found_lt = env_lts.chain(fn_lts).position(|ident| *ident == lt); match found_lt { Some(index) => { - if let Some(index)=index.checked_sub(self.current.first_bound_lt) { - self.current.bound_lt_spans[index].get_or_insert( span ); + if let Some(index) = index.checked_sub(self.current.first_bound_lt) { + self.current.bound_lt_spans[index].get_or_insert(span); } ret = Some(&ctokens.underscore); - LifetimeIndex::Param( index as _ ) + LifetimeIndex::Param(index as _) } None => { - self.vars.errors.push_err(spanned_err!(lt,"unknown lifetime")); + self.vars + .errors + .push_err(spanned_err!(lt, "unknown lifetime")); LifetimeIndex::NONE - }, + } } } .piped(|li| { @@ -503,13 +486,13 @@ This function does these things: }); ret } - + /// Adds a bound lifetime to the `extern "C" fn()` and returns an index to it - fn new_bound_lifetime(&mut self,span:Span) -> LifetimeIndex { - let index = self.vars.fn_info.initial_bound_lifetime+self.current.bound_lts_count; + fn new_bound_lifetime(&mut self, span: Span) -> LifetimeIndex { + let index = self.vars.fn_info.initial_bound_lifetime + self.current.bound_lts_count; self.current.bound_lt_spans.push(Some(span)); - self.current.bound_lts_count+=1; - LifetimeIndex::Param( index as _ ) + self.current.bound_lts_count += 1; + LifetimeIndex::Param(index as _) } } @@ -528,7 +511,7 @@ impl<'a, 'b> VisitMut for FnVisitor<'a, 'b> { \t}}\n\ \n\ ", - func=func.to_token_stream() + func = func.to_token_stream() )) } @@ -538,8 +521,8 @@ impl<'a, 'b> VisitMut for FnVisitor<'a, 'b> { fn visit_type_reference_mut(&mut self, ref_: &mut TypeReference) { let _ctokens = self.refs.ctokens; let lt = ref_.lifetime.as_ref().map(|x| &x.ident); - if let Some(ident) = self.setup_lifetime(lt,ref_.and_token.span()).cloned() { - if let Some(lt)=&mut ref_.lifetime { + if let Some(ident) = self.setup_lifetime(lt, ref_.and_token.span()).cloned() { + if let Some(lt) = &mut ref_.lifetime { lt.ident = ident } } @@ -551,14 +534,14 @@ impl<'a, 'b> VisitMut for FnVisitor<'a, 'b> { /// Visits a lifetime inside the function pointer type, /// and pushing the lifetime to the list of lifetime indices. fn visit_lifetime_mut(&mut self, lt: &mut Lifetime) { - if let Some(ident) = self.setup_lifetime(Some(<.ident),lt.apostrophe.span()) { + if let Some(ident) = self.setup_lifetime(Some(<.ident), lt.apostrophe.span()) { lt.ident = ident.clone(); } } - fn visit_type_macro_mut(&mut self, i: &mut syn::TypeMacro){ - if !self.vars.allow_type_macros{ - push_type_macro_err(&mut self.vars.errors,i); + fn visit_type_macro_mut(&mut self, i: &mut syn::TypeMacro) { + if !self.vars.allow_type_macros { + push_type_macro_err(&mut self.vars.errors, i); } } } @@ -566,73 +549,70 @@ impl<'a, 'b> VisitMut for FnVisitor<'a, 'b> { ///////////// fn extract_fn_arg_name<'a>( - _index:usize, - arg:&mut syn::BareFnArg, + _index: usize, + arg: &mut syn::BareFnArg, arenas: &'a Arenas, -)->Option<&'a Ident>{ +) -> Option<&'a Ident> { match arg.name.take() { - Some((name,_))=>Some(arenas.alloc(name)), - None=>None, + Some((name, _)) => Some(arenas.alloc(name)), + None => None, } } ///////////// -impl<'a> Function<'a>{ +impl<'a> Function<'a> { /// Turns lifetimes in the function parameters that aren't /// used in the return type or used only once into LifeimeIndex::ANONYMOUS, fn anonimize_lifetimes( &mut self, - lifetime_counts:&LifetimeCounters, - errors:&mut Result<(),syn::Error> - ){ - let first_bound_lt=self.first_bound_lt; - - let mut current_lt=first_bound_lt; - - let asigned_lts=(0..self.bound_lts_count) - .map(|i|{ - let lt_i:usize=first_bound_lt+i; - - if lifetime_counts.get(LifetimeIndex::Param(lt_i))<=1 { + lifetime_counts: &LifetimeCounters, + errors: &mut Result<(), syn::Error>, + ) { + let first_bound_lt = self.first_bound_lt; + + let mut current_lt = first_bound_lt; + + let asigned_lts = (0..self.bound_lts_count) + .map(|i| { + let lt_i: usize = first_bound_lt + i; + + if lifetime_counts.get(LifetimeIndex::Param(lt_i)) <= 1 { LifetimeIndex::ANONYMOUS - }else{ - if current_lt == LifetimeIndex::MAX_LIFETIME_PARAM+1 { + } else { + if current_lt == LifetimeIndex::MAX_LIFETIME_PARAM + 1 { errors.push_err(syn_err!( - self.bound_lt_spans[i].unwrap_or_else(||*self.func_span), + self.bound_lt_spans[i].unwrap_or_else(|| *self.func_span), "Cannot have more than {} non-static lifetimes \ (except for lifetimes only used once inside \ function pointer types)", - LifetimeIndex::MAX_LIFETIME_PARAM+1 + LifetimeIndex::MAX_LIFETIME_PARAM + 1 )); } - let ret=LifetimeIndex::Param(current_lt); - current_lt+=1; + let ret = LifetimeIndex::Param(current_lt); + current_lt += 1; ret } }) .collect::>(); - - for params in &mut self.params{ + for params in &mut self.params { for p_lt in &mut params.lifetime_refs { - let param=match p_lt.to_param() { - Some(param)=>(param).wrapping_sub(first_bound_lt), - None=>continue, + let param = match p_lt.to_param() { + Some(param) => (param).wrapping_sub(first_bound_lt), + None => continue, }; - - if let Some(assigned)=asigned_lts.get(param) { - *p_lt=*assigned; + + if let Some(assigned) = asigned_lts.get(param) { + *p_lt = *assigned; } } } } } - - -fn push_type_macro_err(res:&mut Result<(),syn::Error>,i: &syn::TypeMacro){ +fn push_type_macro_err(res: &mut Result<(), syn::Error>, i: &syn::TypeMacro) { res.push_err(spanned_err!( i, "\ @@ -648,6 +628,3 @@ it won't be checked by the runtime type checker. " )); } - - - diff --git a/abi_stable_derive/src/get_static_equivalent.rs b/abi_stable_derive/src/get_static_equivalent.rs index f226196f..92cd547a 100644 --- a/abi_stable_derive/src/get_static_equivalent.rs +++ b/abi_stable_derive/src/get_static_equivalent.rs @@ -2,51 +2,39 @@ Stuff related to the `GetStaticEquivalent` derive macro. */ -use proc_macro2::{Span,TokenStream as TokenStream2}; +use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::{quote, ToTokens}; -use syn::{ - punctuated::Punctuated, - DeriveInput, Generics, Ident, -}; +use syn::{punctuated::Punctuated, DeriveInput, Generics, Ident}; use as_derive_utils::{ - gen_params_in::{GenParamsIn,InWhat}, - to_token_fn::ToTokenFnMut, + gen_params_in::{GenParamsIn, InWhat}, to_stream, + to_token_fn::ToTokenFnMut, }; -use crate::{ - impl_interfacetype::impl_interfacetype_tokenizer, - parse_utils::parse_str_as_ident, -}; - +use crate::{impl_interfacetype::impl_interfacetype_tokenizer, parse_utils::parse_str_as_ident}; mod attribute_parsing; - /// The implementation of the `GetStaticEquivalent` derive macro. -pub(crate) fn derive(data: DeriveInput) -> Result { - let name=&data.ident; - let generics=&data.generics; - let config=self::attribute_parsing::parse_attrs_for_get_static_equiv(&data.attrs)?; - - let impl_it=impl_interfacetype_tokenizer( - name, - generics, - config.impl_interfacetype.as_ref(), - ); - let gse_equiv_impl=get_static_equiv_tokenizer(name,generics,quote!()); +pub(crate) fn derive(data: DeriveInput) -> Result { + let name = &data.ident; + let generics = &data.generics; + let config = self::attribute_parsing::parse_attrs_for_get_static_equiv(&data.attrs)?; + + let impl_it = impl_interfacetype_tokenizer(name, generics, config.impl_interfacetype.as_ref()); + let gse_equiv_impl = get_static_equiv_tokenizer(name, generics, quote!()); - let ret=quote!( + let ret = quote!( #impl_it #gse_equiv_impl ); if config.debug_print { - panic!("\n\n\n{}\n\n\n",ret); + panic!("\n\n\n{}\n\n\n", ret); } Ok(ret) @@ -54,50 +42,54 @@ pub(crate) fn derive(data: DeriveInput) -> Result { /// Tokenizes the `GetStaticEquivalent_` implementation for some type. fn get_static_equiv_tokenizer<'a>( - name:&'a Ident, - generics:&'a Generics, - extra_bounds:TokenStream2, -) -> impl ToTokens+'a { - ToTokenFnMut::new(move|ts|{ - let lifetimes=&generics.lifetimes().map(|x|&x.lifetime).collect::>(); - let type_params=&generics.type_params().map(|x|&x.ident).collect::>(); - let const_params=&generics.const_params().map(|x|&x.ident).collect::>(); - - let ct_gt=syn::token::Gt::default(); - let ct_lt=syn::token::Lt::default(); - let ct_static_equivalent=parse_str_as_ident("__GetStaticEquivalent"); - let ct_comma=syn::token::Comma::default(); - let ct_static_lt=syn::parse_str::("'static").expect("BUG"); - - - let lifetimes_s=lifetimes.iter().map(|_| &ct_static_lt ); - let type_params_s=ToTokenFnMut::new(|ts|{ + name: &'a Ident, + generics: &'a Generics, + extra_bounds: TokenStream2, +) -> impl ToTokens + 'a { + ToTokenFnMut::new(move |ts| { + let lifetimes = &generics + .lifetimes() + .map(|x| &x.lifetime) + .collect::>(); + let type_params = &generics.type_params().map(|x| &x.ident).collect::>(); + let const_params = &generics + .const_params() + .map(|x| &x.ident) + .collect::>(); + + let ct_gt = syn::token::Gt::default(); + let ct_lt = syn::token::Lt::default(); + let ct_static_equivalent = parse_str_as_ident("__GetStaticEquivalent"); + let ct_comma = syn::token::Comma::default(); + let ct_static_lt = syn::parse_str::("'static").expect("BUG"); + + let lifetimes_s = lifetimes.iter().map(|_| &ct_static_lt); + let type_params_s = ToTokenFnMut::new(|ts| { for ty in type_params { to_stream!(ts; ct_static_equivalent, ct_lt, ty, ct_gt, ct_comma); } }); - let const_params_s=&const_params; - + let const_params_s = &const_params; let (impl_generics, _, where_clause) = generics.split_for_impl(); - let ty_generics=GenParamsIn::new(generics,InWhat::ItemUse); - - let static_struct_name=Ident::new(&format!("_static_{}",name),Span::call_site()); + let ty_generics = GenParamsIn::new(generics, InWhat::ItemUse); - let empty_preds=Punctuated::new(); - let where_preds=where_clause.as_ref().map_or(&empty_preds,|x|&x.predicates).into_iter(); + let static_struct_name = Ident::new(&format!("_static_{}", name), Span::call_site()); - let lifetimes_a =lifetimes; - let type_params_a=type_params; - let const_param_name=generics.const_params().map(|c| &c.ident ); - let const_param_type=generics.const_params().map(|c| &c.ty ); + let empty_preds = Punctuated::new(); + let where_preds = where_clause + .as_ref() + .map_or(&empty_preds, |x| &x.predicates) + .into_iter(); - let const_ident=parse_str_as_ident(&format!( - "_impl_get_static_equivalent_constant_{}", - name, - )); + let lifetimes_a = lifetimes; + let type_params_a = type_params; + let const_param_name = generics.const_params().map(|c| &c.ident); + let const_param_type = generics.const_params().map(|c| &c.ty); + let const_ident = + parse_str_as_ident(&format!("_impl_get_static_equivalent_constant_{}", name,)); quote!( const #const_ident:()={ @@ -116,18 +108,19 @@ fn get_static_equiv_tokenizer<'a>( ); unsafe impl #impl_generics __GetStaticEquivalent_ for #name <#ty_generics> - where + where #(#where_preds,)* #(#type_params_a:__GetStaticEquivalent_,)* #extra_bounds { - type StaticEquivalent=#static_struct_name < + type StaticEquivalent=#static_struct_name < #(#lifetimes_s,)* #type_params_s - #({#const_params_s}),* + #({#const_params_s}),* >; } }; - ).to_tokens(ts); + ) + .to_tokens(ts); }) } diff --git a/abi_stable_derive/src/get_static_equivalent/attribute_parsing.rs b/abi_stable_derive/src/get_static_equivalent/attribute_parsing.rs index 750110fb..62fd913f 100644 --- a/abi_stable_derive/src/get_static_equivalent/attribute_parsing.rs +++ b/abi_stable_derive/src/get_static_equivalent/attribute_parsing.rs @@ -4,43 +4,36 @@ For parsing the helper attributess for `#[derive(GetStaticEquivalent)]`. use std::marker::PhantomData; -use as_derive_utils::{ - return_spanned_err, -}; - -use syn::{ - Attribute, Meta, MetaList, -}; +use as_derive_utils::return_spanned_err; +use syn::{Attribute, Meta, MetaList}; use crate::{ - attribute_parsing::{with_nested_meta}, - impl_interfacetype::{ImplInterfaceType,parse_impl_interfacetype}, + attribute_parsing::with_nested_meta, + impl_interfacetype::{parse_impl_interfacetype, ImplInterfaceType}, utils::SynPathExt, }; - /// This is derived from the helper attributes of the `#[derive(GetStaticEquivalent)]` macrp. #[derive(Default)] -pub(super) struct GetStaticEquivAttrs<'a>{ - pub(super) impl_interfacetype:Option, - pub(super) debug_print:bool, - _marker:PhantomData<&'a ()>, +pub(super) struct GetStaticEquivAttrs<'a> { + pub(super) impl_interfacetype: Option, + pub(super) debug_print: bool, + _marker: PhantomData<&'a ()>, } - /// Parses the helper attributes of the `#[derive(GetStaticEquivalent)]` macrp. -pub(super) fn parse_attrs_for_get_static_equiv<'a,I>( +pub(super) fn parse_attrs_for_get_static_equiv<'a, I>( attrs: I, -) -> Result,syn::Error> +) -> Result, syn::Error> where - I:IntoIterator + I: IntoIterator, { - let mut this=GetStaticEquivAttrs::default(); + let mut this = GetStaticEquivAttrs::default(); for attr in attrs { if let Meta::List(list) = attr.parse_meta()? { - parse_attr_list(&mut this,list)?; + parse_attr_list(&mut this, list)?; } } @@ -48,37 +41,27 @@ where } // Helper function of `parse_attrs_for_get_static_equiv`. -fn parse_attr_list( - this: &mut GetStaticEquivAttrs<'_>, - list: MetaList, -)-> Result<(),syn::Error> { +fn parse_attr_list(this: &mut GetStaticEquivAttrs<'_>, list: MetaList) -> Result<(), syn::Error> { if list.path.equals_str("sabi") { - with_nested_meta("sabi", list.nested, |attr| { - parse_gse_attr(this, attr) - })?; + with_nested_meta("sabi", list.nested, |attr| parse_gse_attr(this, attr))?; } Ok(()) } // Helper function of `parse_attrs_for_get_static_equiv`. -fn parse_gse_attr( - this: &mut GetStaticEquivAttrs<'_>, - attr: Meta, -)-> Result<(),syn::Error> { +fn parse_gse_attr(this: &mut GetStaticEquivAttrs<'_>, attr: Meta) -> Result<(), syn::Error> { match attr { - Meta::List(list)=>{ + Meta::List(list) => { if list.path.equals_str("impl_InterfaceType") { - this.impl_interfacetype=Some(parse_impl_interfacetype(&list.nested)?); - }else{ - return_spanned_err!(list,"Unrecodnized #[sabi(..)] attribute."); + this.impl_interfacetype = Some(parse_impl_interfacetype(&list.nested)?); + } else { + return_spanned_err!(list, "Unrecodnized #[sabi(..)] attribute."); } } - Meta::Path(ref word) if word.equals_str("debug_print")=>{ - this.debug_print=true; + Meta::Path(ref word) if word.equals_str("debug_print") => { + this.debug_print = true; } - x =>return_spanned_err!(x,"Unrecodnized #[sabi(..)] attribute."), + x => return_spanned_err!(x, "Unrecodnized #[sabi(..)] attribute."), } Ok(()) } - - diff --git a/abi_stable_derive/src/ignored_wrapper.rs b/abi_stable_derive/src/ignored_wrapper.rs index 8ca3214d..bdce01dd 100644 --- a/abi_stable_derive/src/ignored_wrapper.rs +++ b/abi_stable_derive/src/ignored_wrapper.rs @@ -3,95 +3,87 @@ Wrapper type(s) where their value is ignored in comparisons . */ use std::{ - ops::{Deref,DerefMut}, - fmt::{self,Debug,Display}, - cmp::{Ordering,Eq,PartialEq,Ord,PartialOrd}, - hash::{Hash,Hasher}, + cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}, + fmt::{self, Debug, Display}, + hash::{Hash, Hasher}, + ops::{Deref, DerefMut}, }; /// Wrapper type used to ignore its contents in comparisons. #[repr(transparent)] -#[derive(Default,Copy,Clone)] -pub struct Ignored{ - pub value:T, +#[derive(Default, Copy, Clone)] +pub struct Ignored { + pub value: T, } - -impl Ignored{ - pub fn new(value:T)->Self{ - Self{value} +impl Ignored { + pub fn new(value: T) -> Self { + Self { value } } } - -impl From for Ignored{ - fn from(value:T)->Self{ - Self{value} +impl From for Ignored { + fn from(value: T) -> Self { + Self { value } } } - impl Deref for Ignored { - type Target=T; + type Target = T; - fn deref(&self)->&Self::Target{ + fn deref(&self) -> &Self::Target { &self.value } } impl DerefMut for Ignored { - fn deref_mut(&mut self)->&mut Self::Target{ + fn deref_mut(&mut self) -> &mut Self::Target { &mut self.value } } impl Display for Ignored where - T:Display, + T: Display, { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Display::fmt(&**self,f) + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Display::fmt(&**self, f) } } - impl Debug for Ignored where - T:Debug, + T: Debug, { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - Debug::fmt(&**self,f) + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Debug::fmt(&**self, f) } } impl Eq for Ignored {} - impl PartialEq for Ignored { - fn eq(&self, _other: &Self) -> bool{ + fn eq(&self, _other: &Self) -> bool { true } } - -impl Ord for Ignored{ - fn cmp(&self, _other: &Self) -> Ordering{ +impl Ord for Ignored { + fn cmp(&self, _other: &Self) -> Ordering { Ordering::Equal } } - -impl PartialOrd for Ignored{ - fn partial_cmp(&self, _other: &Self) -> Option{ +impl PartialOrd for Ignored { + fn partial_cmp(&self, _other: &Self) -> Option { Some(Ordering::Equal) } } - -impl Hash for Ignored{ +impl Hash for Ignored { fn hash(&self, state: &mut H) where - H: Hasher + H: Hasher, { ().hash(state) } diff --git a/abi_stable_derive/src/impl_interfacetype.rs b/abi_stable_derive/src/impl_interfacetype.rs index 1a795a76..d32e0b06 100644 --- a/abi_stable_derive/src/impl_interfacetype.rs +++ b/abi_stable_derive/src/impl_interfacetype.rs @@ -5,41 +5,30 @@ and the `impl_InterfaceType!{}` macro. use std::collections::HashMap; - - #[allow(unused_imports)] use core_extensions::SelfOps; -use quote::{ToTokens,quote,quote_spanned}; +use quote::{quote, quote_spanned, ToTokens}; use syn::Ident; -use as_derive_utils::{ - to_token_fn::ToTokenFnMut, -}; - -use crate::{ - parse_utils::parse_str_as_ident, -}; - - +use as_derive_utils::to_token_fn::ToTokenFnMut; +use crate::parse_utils::parse_str_as_ident; pub(crate) mod attribute_parsing; mod macro_impl; - pub(crate) use self::{ - attribute_parsing::{ImplInterfaceType,parse_impl_interfacetype}, + attribute_parsing::{parse_impl_interfacetype, ImplInterfaceType}, macro_impl::the_macro, }; - ////////////////////// /// The default value for an associated type. -#[derive(Debug,Copy,Clone,PartialEq,Eq,PartialOrd,Ord,Hash)] -pub enum DefaultVal{ +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum DefaultVal { /// The value of the associated type is `Unimplemented` Unimplemented, /// The value of the associated type is `Implemented` @@ -49,38 +38,40 @@ pub enum DefaultVal{ Hidden, } -impl From for DefaultVal{ - fn from(b:bool)->Self{ - if b { DefaultVal::Implemented }else{ DefaultVal::Unimplemented } +impl From for DefaultVal { + fn from(b: bool) -> Self { + if b { + DefaultVal::Implemented + } else { + DefaultVal::Unimplemented + } } } ////////////////////// -/// The trait object implementations (either RObject or DynTrait) +/// The trait object implementations (either RObject or DynTrait) /// that a trait can be used with. -#[derive(Debug,Copy,Clone,PartialEq,Eq,PartialOrd,Ord,Hash)] -pub struct UsableBy{ - robject:bool, - dyn_trait:bool, +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct UsableBy { + robject: bool, + dyn_trait: bool, } - - -impl UsableBy{ - pub const DYN_TRAIT:Self=Self{ - robject:false, - dyn_trait:true, +impl UsableBy { + pub const DYN_TRAIT: Self = Self { + robject: false, + dyn_trait: true, }; - pub const ROBJECT_AND_DYN_TRAIT:Self=Self{ - robject:true, - dyn_trait:true, + pub const ROBJECT_AND_DYN_TRAIT: Self = Self { + robject: true, + dyn_trait: true, }; - pub const fn robject(&self)->bool{ + pub const fn robject(&self) -> bool { self.robject } - pub const fn dyn_trait(&self)->bool{ + pub const fn dyn_trait(&self) -> bool { self.dyn_trait } } @@ -88,16 +79,16 @@ impl UsableBy{ ////////////////////// /// Information about a trait that is usable in RObject and/or DynTrait. -#[derive(Debug,Copy,Clone)] -pub struct UsableTrait{ - pub which_trait:WhichTrait, - pub name:&'static str, - pub full_path:&'static str, +#[derive(Debug, Copy, Clone)] +pub struct UsableTrait { + pub which_trait: WhichTrait, + pub name: &'static str, + pub full_path: &'static str, } macro_rules! usable_traits { - ( - $( + ( + $( $field:ident= ( $which_trait:ident, @@ -105,7 +96,7 @@ macro_rules! usable_traits { $default_value:expr, $usable_by:expr ), - )* + )* ) => ( /// A list of all the traits usable in RObject and/or DynTrait. pub static TRAIT_LIST:&[UsableTrait]=&[$( @@ -199,9 +190,9 @@ macro_rules! usable_traits { ) } -use self::{UsableBy as UB}; +use self::UsableBy as UB; -usable_traits!{ +usable_traits! { clone=(Clone,"::std::clone::Clone",false,UB::ROBJECT_AND_DYN_TRAIT), default=(Default,"::std::default::Default",false,UB::DYN_TRAIT), display=(Display,"::std::fmt::Display",false,UB::ROBJECT_AND_DYN_TRAIT), @@ -227,45 +218,40 @@ usable_traits!{ error=(Error,"::std::error::Error",false,UB::ROBJECT_AND_DYN_TRAIT), } -pub(crate) fn private_associated_type()->syn::Ident{ +pub(crate) fn private_associated_type() -> syn::Ident { parse_str_as_ident("define_this_in_the_impl_InterfaceType_macro") } - - ////////////////////////////////////////////////////////////////////////////// - - /// Returns a tokenizer /// which prints an implementation of InterfaceType for `name`, /// with `impl_interfacetype` determining the associated types. pub(crate) fn impl_interfacetype_tokenizer<'a>( - name:&'a Ident, - generics:&'a syn::Generics, - impl_interfacetype:Option<&'a ImplInterfaceType>, -)->impl ToTokens+'a{ - ToTokenFnMut::new(move|ts|{ - let ImplInterfaceType{impld,unimpld}= - match impl_interfacetype { - Some(x) => x, - None => return, - }; - + name: &'a Ident, + generics: &'a syn::Generics, + impl_interfacetype: Option<&'a ImplInterfaceType>, +) -> impl ToTokens + 'a { + ToTokenFnMut::new(move |ts| { + let ImplInterfaceType { impld, unimpld } = match impl_interfacetype { + Some(x) => x, + None => return, + }; + let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); - - let const_ident=crate::parse_utils::parse_str_as_ident(&format!( + + let const_ident = crate::parse_utils::parse_str_as_ident(&format!( "_impl_InterfaceType_constant_{}", name, )); - let impld_a=impld; - let impld_b=impld; + let impld_a = impld; + let impld_b = impld; - let unimpld_a=unimpld; - let unimpld_b=unimpld; + let unimpld_a = unimpld; + let unimpld_b = unimpld; - let priv_assocty=private_associated_type(); + let priv_assocty = private_associated_type(); quote!( const #const_ident:()={ @@ -278,21 +264,17 @@ pub(crate) fn impl_interfacetype_tokenizer<'a>( trait_marker, }, }; - impl #impl_generics abi_stable::InterfaceType for #name #ty_generics - #where_clause + impl #impl_generics abi_stable::InterfaceType for #name #ty_generics + #where_clause { #( type #impld_a=__Implemented; )* #( type #unimpld_a=__Unimplemented; )* type #priv_assocty=(); } }; - ).to_tokens(ts); + ) + .to_tokens(ts); }) } - - - ////////////////////////////////////////////////////////////////////////////// - - diff --git a/abi_stable_derive/src/impl_interfacetype/attribute_parsing.rs b/abi_stable_derive/src/impl_interfacetype/attribute_parsing.rs index a6f5d4a2..1036b4de 100644 --- a/abi_stable_derive/src/impl_interfacetype/attribute_parsing.rs +++ b/abi_stable_derive/src/impl_interfacetype/attribute_parsing.rs @@ -1,56 +1,52 @@ -use std::{ - collections::HashMap, -}; +use std::collections::HashMap; -use as_derive_utils::{ - spanned_err, - return_spanned_err, -}; +use as_derive_utils::{return_spanned_err, spanned_err}; -use syn::{ - Meta, NestedMeta, Ident, - punctuated::Punctuated, - token::Comma, -}; +use syn::{punctuated::Punctuated, token::Comma, Ident, Meta, NestedMeta}; use crate::{ - impl_interfacetype::{TRAIT_LIST,TraitStruct,WhichTrait}, + impl_interfacetype::{TraitStruct, WhichTrait, TRAIT_LIST}, parse_utils::parse_str_as_ident, }; - /// The traits that are (un)implemented,parsed from the `#[sabi(impl_InterfaceType())]` /// helper attribute. -pub(crate) struct ImplInterfaceType{ - pub(crate) impld :Vec, - pub(crate) unimpld:Vec, +pub(crate) struct ImplInterfaceType { + pub(crate) impld: Vec, + pub(crate) unimpld: Vec, } /// Parses the `#[sabi(impl_InterfaceType())]` helper attribute. pub(crate) fn parse_impl_interfacetype( - list: &Punctuated -)-> Result { - let trait_map=TRAIT_LIST.iter() - .map(|t|{ - let ident=parse_str_as_ident(t.name); - (ident,t.which_trait) + list: &Punctuated, +) -> Result { + let trait_map = TRAIT_LIST + .iter() + .map(|t| { + let ident = parse_str_as_ident(t.name); + (ident, t.which_trait) }) - .collect::>(); + .collect::>(); - let mut impld_struct=TraitStruct::TRAITS.map(|_,_|false); + let mut impld_struct = TraitStruct::TRAITS.map(|_, _| false); - let mut impld =Vec::new(); - let mut unimpld=Vec::new(); + let mut impld = Vec::new(); + let mut unimpld = Vec::new(); - let valid_traits=||->String{ - trait_map.keys().map(|x|x.to_string()).collect::>().join("\n ") + let valid_traits = || -> String { + trait_map + .keys() + .map(|x| x.to_string()) + .collect::>() + .join("\n ") }; for subelem in list { - let trait_ident=match subelem { - NestedMeta::Meta(Meta::Path(ident))=>ident.get_ident(), + let trait_ident = match subelem { + NestedMeta::Meta(Meta::Path(ident)) => ident.get_ident(), _ => None, - }.ok_or_else(||{ + } + .ok_or_else(|| { spanned_err!( subelem, "invalid attribute inside #[sabi(impl_InterfaceType( ))].\n\ @@ -62,49 +58,47 @@ pub(crate) fn parse_impl_interfacetype( match trait_map.get(trait_ident) { Some(&which_trait) => { - impld_struct[which_trait]=true; + impld_struct[which_trait] = true; match which_trait { - WhichTrait::Iterator|WhichTrait::DoubleEndedIterator=>{ - impld_struct.iterator=true; + WhichTrait::Iterator | WhichTrait::DoubleEndedIterator => { + impld_struct.iterator = true; } - WhichTrait::Eq|WhichTrait::PartialOrd=>{ - impld_struct.partial_eq=true; + WhichTrait::Eq | WhichTrait::PartialOrd => { + impld_struct.partial_eq = true; } - WhichTrait::Ord=>{ - impld_struct.partial_eq=true; - impld_struct.eq=true; - impld_struct.partial_ord=true; + WhichTrait::Ord => { + impld_struct.partial_eq = true; + impld_struct.eq = true; + impld_struct.partial_ord = true; } - WhichTrait::IoBufRead=>{ - impld_struct.io_read=true; + WhichTrait::IoBufRead => { + impld_struct.io_read = true; } - WhichTrait::Error=>{ - impld_struct.display=true; - impld_struct.debug=true; + WhichTrait::Error => { + impld_struct.display = true; + impld_struct.debug = true; } - _=>{} + _ => {} } - }, - None =>return_spanned_err!( + } + None => return_spanned_err!( trait_ident, "invalid trait inside #[sabi(impl_InterfaceType( ))]:\n\ - Valid traits:\n {}\n", + Valid traits:\n {}\n", valid_traits(), ), } } - for (trait_,which_trait) in trait_map { + for (trait_, which_trait) in trait_map { if impld_struct[which_trait] { &mut impld - }else{ + } else { &mut unimpld - }.push(trait_); + } + .push(trait_); } - Ok(ImplInterfaceType{ - impld, - unimpld, - }) + Ok(ImplInterfaceType { impld, unimpld }) } diff --git a/abi_stable_derive/src/impl_interfacetype/macro_impl.rs b/abi_stable_derive/src/impl_interfacetype/macro_impl.rs index 499556ca..95874a8a 100644 --- a/abi_stable_derive/src/impl_interfacetype/macro_impl.rs +++ b/abi_stable_derive/src/impl_interfacetype/macro_impl.rs @@ -1,35 +1,27 @@ use super::*; -use as_derive_utils::{ - return_spanned_err, -}; +use as_derive_utils::return_spanned_err; use proc_macro2::TokenStream as TokenStream2; -use syn::{ - ItemImpl, - ImplItem, - ImplItemType, - Visibility, -}; - +use syn::{ImplItem, ImplItemType, ItemImpl, Visibility}; /// The implementation of the impl_InterfaceType!{}` proc macro. /// /// This macro takes in an impl block for the InterfaceType trait, /// and emulates defaulted associated types for the ones that weren't mentioned. -pub fn the_macro(mut impl_:ItemImpl)->Result{ - let interfacetype:syn::Ident=syn::parse_str("InterfaceType").expect("BUG"); - - let mut const_name=(&impl_.self_ty).into_token_stream().to_string(); - const_name.retain(|c| c.is_alphanumeric() ); - const_name.insert_str(0,"_impl_InterfaceType"); - let const_name=parse_str_as_ident(&const_name); - - let interface_path_s=impl_.trait_.as_ref().map(|x| &x.1.segments ); - let is_interface_type=interface_path_s - .and_then(|x| x.last() ) - .map_or(false,|path_| path_.ident==interfacetype ); +pub fn the_macro(mut impl_: ItemImpl) -> Result { + let interfacetype: syn::Ident = syn::parse_str("InterfaceType").expect("BUG"); + + let mut const_name = (&impl_.self_ty).into_token_stream().to_string(); + const_name.retain(|c| c.is_alphanumeric()); + const_name.insert_str(0, "_impl_InterfaceType"); + let const_name = parse_str_as_ident(&const_name); + + let interface_path_s = impl_.trait_.as_ref().map(|x| &x.1.segments); + let is_interface_type = interface_path_s + .and_then(|x| x.last()) + .map_or(false, |path_| path_.ident == interfacetype); if !is_interface_type { return_spanned_err!( @@ -38,64 +30,66 @@ pub fn the_macro(mut impl_:ItemImpl)->Result{ impl_.self_ty.to_token_stream(), ); } - + // The default value for each associated type. - let mut default_map=TRAIT_LIST + let mut default_map = TRAIT_LIST .iter() - .map(|ut|{ - ( parse_str_as_ident(ut.name) , DefaultVal::from(ut.which_trait.default_value()) ) + .map(|ut| { + ( + parse_str_as_ident(ut.name), + DefaultVal::from(ut.which_trait.default_value()), + ) }) - .collect::>(); + .collect::>(); // Processed the items in the impl block, // removing them from the defaulted associated type map, - // and converting the value of the associated type to + // and converting the value of the associated type to // either `Implemented` - // or `Unimplemented` + // or `Unimplemented` for item in &mut impl_.items { if let ImplItem::Type(assoc_ty) = item { assert_ne!( - assoc_ty.ident, - "define_this_in_the_impl_InterfaceType_macro", + assoc_ty.ident, "define_this_in_the_impl_InterfaceType_macro", "you are not supposed to define\n\t\ the 'define_this_in_the_impl_InterfaceType_macro' associated type yourself" ); default_map.remove(&assoc_ty.ident); - let old_ty=&assoc_ty.ty; - let name=&assoc_ty.ident; - let span=name.span(); + let old_ty = &assoc_ty.ty; + let name = &assoc_ty.ident; + let span = name.span(); - assoc_ty.ty=syn::Type::Verbatim( - quote_spanned!(span=> ImplFrom<#old_ty, trait_marker::#name> ) - ); + assoc_ty.ty = + syn::Type::Verbatim(quote_spanned!(span=> ImplFrom<#old_ty, trait_marker::#name> )); } } - default_map.insert(private_associated_type(),DefaultVal::Hidden); + default_map.insert(private_associated_type(), DefaultVal::Hidden); // Converts the defaulted associated types to the syn datastructure, // and then adds them to the list of items inside the impl block. - for (key,default_) in default_map { - let mut attrs=Vec::::new(); + for (key, default_) in default_map { + let mut attrs = Vec::::new(); - let span=key.span(); + let span = key.span(); - let ty=match default_ { - DefaultVal::Unimplemented=>quote_spanned!(span=> Unimplemented ), - DefaultVal::Implemented=>quote_spanned!(span=> Implemented ), - DefaultVal::Hidden=>{ + let ty = match default_ { + DefaultVal::Unimplemented => quote_spanned!(span=> Unimplemented ), + DefaultVal::Implemented => quote_spanned!(span=> Implemented ), + DefaultVal::Hidden => { attrs.extend(parse_syn_attributes("#[doc(hidden)]").expect("BUG")); quote_spanned!(span=> () ) - }, - }.piped(syn::Type::Verbatim); + } + } + .piped(syn::Type::Verbatim); - let defaulted=ImplItemType{ + let defaulted = ImplItemType { attrs, vis: Visibility::Inherited, defaultness: None, type_token: Default::default(), - ident:key, + ident: key, generics: Default::default(), eq_token: Default::default(), ty, @@ -115,20 +109,17 @@ pub fn the_macro(mut impl_:ItemImpl)->Result{ #impl_ }; - ).piped(Ok) + ) + .piped(Ok) } - - /// Parses an inner attribute `#[]` from a string. /// /// inner attribute as opposed to an outer attribute `#![]`. -pub fn parse_syn_attributes(str_: &str) -> Result,syn::Error> { - syn::parse_str::(str_) - .map(|x|x.attributes) +pub fn parse_syn_attributes(str_: &str) -> Result, syn::Error> { + syn::parse_str::(str_).map(|x| x.attributes) } - struct ParseOuter { attributes: Vec, } @@ -139,4 +130,4 @@ impl syn::parse::Parse for ParseOuter { attributes: syn::Attribute::parse_outer(input)?, }) } -} \ No newline at end of file +} diff --git a/abi_stable_derive/src/input_code_range_tests.rs b/abi_stable_derive/src/input_code_range_tests.rs index e69de29b..8b137891 100644 --- a/abi_stable_derive/src/input_code_range_tests.rs +++ b/abi_stable_derive/src/input_code_range_tests.rs @@ -0,0 +1 @@ + diff --git a/abi_stable_derive/src/lib.rs b/abi_stable_derive/src/lib.rs index a166fed5..48dc1944 100644 --- a/abi_stable_derive/src/lib.rs +++ b/abi_stable_derive/src/lib.rs @@ -2,7 +2,7 @@ An implementation detail of abi_stable. */ -#![recursion_limit="192"] +#![recursion_limit = "192"] // #![deny(unused_variables)] // #![deny(unused_imports)] // #![deny(unused_parens)] @@ -11,12 +11,10 @@ An implementation detail of abi_stable. #![deny(unreachable_patterns)] #![deny(unused_doc_comments)] #![deny(unconditional_recursion)] - #![allow(clippy::suspicious_assignment_formatting)] extern crate proc_macro; - /** @@ -26,19 +24,16 @@ This macro is documented in abi_stable::docs::stable_abi_derive #[proc_macro_derive(StableAbi, attributes(sabi))] pub fn derive_stable_abi(input: TokenStream1) -> TokenStream1 { - parse_or_compile_err( input, stable_abi::derive ).into() + parse_or_compile_err(input, stable_abi::derive).into() } - - - /** Allows implementing the InterfaceType trait, providing default values for associated types not specified in the impl block. -This macro has been deprecated in favor of using the `#[sabi(impl_InterfaceType())]` +This macro has been deprecated in favor of using the `#[sabi(impl_InterfaceType())]` helper attribute of both `#[derive(StableAbi)]` and `#[derive(GetStaticEquivalent)]` @@ -47,45 +42,40 @@ helper attribute of both `#[derive(StableAbi)]` and `#[derive(GetStaticEquivalen #[proc_macro] #[allow(non_snake_case)] pub fn impl_InterfaceType(input: TokenStream1) -> TokenStream1 { - parse_or_compile_err( input, impl_interfacetype::the_macro ).into() + parse_or_compile_err(input, impl_interfacetype::the_macro).into() } - #[proc_macro_attribute] pub fn export_root_module(attr: TokenStream1, item: TokenStream1) -> TokenStream1 { - crate::export_root_module_impl::export_root_module_attr(attr,item) + crate::export_root_module_impl::export_root_module_attr(attr, item) } #[proc_macro_attribute] pub fn sabi_extern_fn(attr: TokenStream1, item: TokenStream1) -> TokenStream1 { - crate::sabi_extern_fn_impl::sabi_extern_fn(attr,item) + crate::sabi_extern_fn_impl::sabi_extern_fn(attr, item) } - #[proc_macro_attribute] pub fn sabi_trait(_attr: TokenStream1, item: TokenStream1) -> TokenStream1 { - parse_or_compile_err( item, sabi_trait::derive_sabi_trait ).into() + parse_or_compile_err(item, sabi_trait::derive_sabi_trait).into() } - #[doc(hidden)] #[proc_macro] -pub fn concatenated_and_ranges( input: TokenStream1) -> TokenStream1 { - parse_or_compile_err( input, concat_and_ranges::macro_impl ).into() +pub fn concatenated_and_ranges(input: TokenStream1) -> TokenStream1 { + parse_or_compile_err(input, concat_and_ranges::macro_impl).into() } - #[proc_macro_derive(GetStaticEquivalent, attributes(sabi))] pub fn derive_get_static_equivalent(input: TokenStream1) -> TokenStream1 { - parse_or_compile_err( input, get_static_equivalent::derive ).into() + parse_or_compile_err(input, get_static_equivalent::derive).into() } - #[doc(hidden)] #[proc_macro] pub fn construct_abi_header(_: TokenStream1) -> TokenStream1 { - let abi_major=env!("CARGO_PKG_VERSION_MAJOR").parse::().unwrap(); - let abi_minor=env!("CARGO_PKG_VERSION_MINOR").parse::().unwrap(); + let abi_major = env!("CARGO_PKG_VERSION_MAJOR").parse::().unwrap(); + let abi_minor = env!("CARGO_PKG_VERSION_MINOR").parse::().unwrap(); quote!( pub const ABI_HEADER:AbiHeader=AbiHeader{ magic_string:*b"abi stable library for Rust ", @@ -93,42 +83,39 @@ pub fn construct_abi_header(_: TokenStream1) -> TokenStream1 { abi_minor:#abi_minor, _priv:(), }; - ).into() + ) + .into() } /// This is used by testing/version_compatibility to access the exported static. #[doc(hidden)] #[proc_macro] pub fn get_root_module_static(_: TokenStream1) -> TokenStream1 { - let export_name=syn::Ident::new( + let export_name = syn::Ident::new( &abi_stable_shared::mangled_root_module_loader_name(), proc_macro2::Span::call_site(), ); quote!( crate::#export_name ).into() } - - /////////////////////////////////////////////////////////////////////////////// - - #[macro_use] mod utils; mod arenas; mod attribute_parsing; -mod concat_and_ranges; mod common_tokens; mod composite_collections; +mod concat_and_ranges; mod constants; +mod export_root_module_impl; mod fn_pointer_extractor; mod get_static_equivalent; mod ignored_wrapper; mod impl_interfacetype; mod lifetimes; mod literals_constructors; -mod export_root_module_impl; mod my_visibility; mod parse_utils; mod sabi_extern_fn_impl; @@ -144,14 +131,12 @@ pub(crate) mod stable_abi; #[doc(hidden)] pub(crate) mod sabi_trait; - - use proc_macro::TokenStream as TokenStream1; use proc_macro2::TokenStream as TokenStream2; -use syn::{DeriveInput,ItemFn}; +use syn::{DeriveInput, ItemFn}; -use quote::{quote, ToTokens, quote_spanned}; +use quote::{quote, quote_spanned, ToTokens}; #[allow(unused_imports)] use core_extensions::SelfOps; @@ -162,29 +147,24 @@ use crate::{ utils::PrintDurationOnDrop, }; - #[cfg(test)] -pub(crate) fn derive_stable_abi_from_str(s: &str) -> Result { - syn::parse_str(s) - .and_then(stable_abi::derive) +pub(crate) fn derive_stable_abi_from_str(s: &str) -> Result { + syn::parse_str(s).and_then(stable_abi::derive) } #[cfg(test)] -pub(crate) fn derive_sabi_trait_str(item: &str) -> Result { - syn::parse_str(item) - .and_then(sabi_trait::derive_sabi_trait) +pub(crate) fn derive_sabi_trait_str(item: &str) -> Result { + syn::parse_str(item).and_then(sabi_trait::derive_sabi_trait) } - //////////////////////////////////////////////////////////////////////////////// - -fn parse_or_compile_err(input:TokenStream1,f:F)->TokenStream2 -where - P:syn::parse::Parse, - F:FnOnce(P)->Result +fn parse_or_compile_err(input: TokenStream1, f: F) -> TokenStream2 +where + P: syn::parse::Parse, + F: FnOnce(P) -> Result, { syn::parse::

(input) .and_then(f) - .unwrap_or_else(|e| e.to_compile_error() ) + .unwrap_or_else(|e| e.to_compile_error()) } diff --git a/abi_stable_derive/src/lifetimes.rs b/abi_stable_derive/src/lifetimes.rs index 94bc0619..1c916677 100644 --- a/abi_stable_derive/src/lifetimes.rs +++ b/abi_stable_derive/src/lifetimes.rs @@ -1,20 +1,16 @@ -abi_stable_shared::declare_tl_lifetime_types!{ +abi_stable_shared::declare_tl_lifetime_types! { repr=usize, attrs=[ derive(Hash), ] } - ///////////////////////////////////////////////////////////////////// - mod lifetime_counters; -pub(crate) use self::{ - lifetime_counters::LifetimeCounters, -}; +pub(crate) use self::lifetime_counters::LifetimeCounters; -impl LifetimeRange{ - pub const DUMMY:Self=Self::from_range(Self::MAX_START..Self::MAX_START+Self::MAX_LEN); -} \ No newline at end of file +impl LifetimeRange { + pub const DUMMY: Self = Self::from_range(Self::MAX_START..Self::MAX_START + Self::MAX_LEN); +} diff --git a/abi_stable_derive/src/lifetimes/lifetime_counters.rs b/abi_stable_derive/src/lifetimes/lifetime_counters.rs index 81f97045..4f017267 100644 --- a/abi_stable_derive/src/lifetimes/lifetime_counters.rs +++ b/abi_stable_derive/src/lifetimes/lifetime_counters.rs @@ -1,87 +1,74 @@ use super::LifetimeIndex; - -use std::fmt::{self,Debug}; - +use std::fmt::{self, Debug}; /// A set of lifetime indices. -pub(crate) struct LifetimeCounters{ - set:Vec, +pub(crate) struct LifetimeCounters { + set: Vec, } -const MASK:u8=0b11; -const MAX_VAL:u8=3; +const MASK: u8 = 0b11; +const MAX_VAL: u8 = 3; -impl LifetimeCounters{ - pub fn new()->Self{ - Self{ - set:Vec::new(), - } +impl LifetimeCounters { + pub fn new() -> Self { + Self { set: Vec::new() } } /// Increments the counter for the `lifetime` lifetime,stopping at 3. - pub fn increment(&mut self,lifetime:LifetimeIndex)->u8{ - let (i,shift)=Self::get_index_shift( lifetime.bits ); - if i>=self.set.len() { - self.set.resize(i+1,0); + pub fn increment(&mut self, lifetime: LifetimeIndex) -> u8 { + let (i, shift) = Self::get_index_shift(lifetime.bits); + if i >= self.set.len() { + self.set.resize(i + 1, 0); } - let bits=&mut self.set[i]; - let mask=MASK << shift; - if (*bits&mask)==mask { + let bits = &mut self.set[i]; + let mask = MASK << shift; + if (*bits & mask) == mask { MAX_VAL - }else{ - *bits+=1<>shift)&MASK + } else { + *bits += 1 << shift; + (*bits >> shift) & MASK } } - pub fn get(&self,lifetime:LifetimeIndex)->u8{ - let (i,shift)=Self::get_index_shift( lifetime.bits ); + pub fn get(&self, lifetime: LifetimeIndex) -> u8 { + let (i, shift) = Self::get_index_shift(lifetime.bits); match self.set.get(i) { Some(&bits) => (bits >> shift) & MASK, None => 0, } - } - - fn get_index_shift(lt:usize)->(usize,u8){ - ( - lt>>2, - ((lt&3)<<1)as u8 - ) + + fn get_index_shift(lt: usize) -> (usize, u8) { + (lt >> 2, ((lt & 3) << 1) as u8) } } - - -impl Debug for LifetimeCounters{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ +impl Debug for LifetimeCounters { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_list() - .entries(self.set.iter().cloned().map(U8Wrapper)) - .finish() + .entries(self.set.iter().cloned().map(U8Wrapper)) + .finish() } } - #[repr(transparent)] struct U8Wrapper(u8); -impl fmt::Debug for U8Wrapper{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - fmt::Binary::fmt(&self.0,f) +impl fmt::Debug for U8Wrapper { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Binary::fmt(&self.0, f) } } - - #[cfg(test)] -mod tests{ +mod tests { use super::*; #[test] - fn test_counting(){ - let mut counters=LifetimeCounters::new(); + fn test_counting() { + let mut counters = LifetimeCounters::new(); - let lts=vec![ + let lts = vec![ LifetimeIndex::Param(0), LifetimeIndex::Param(1), LifetimeIndex::Param(2), @@ -100,10 +87,10 @@ mod tests{ for lt in lts { for i in 1..=3 { - assert_eq!(counters.get(lt), i-1); + assert_eq!(counters.get(lt), i - 1); assert_eq!(counters.increment(lt), i); assert_eq!(counters.get(lt), i); } } } -} \ No newline at end of file +} diff --git a/abi_stable_derive/src/literals_constructors.rs b/abi_stable_derive/src/literals_constructors.rs index 31c49ebd..35752e20 100644 --- a/abi_stable_derive/src/literals_constructors.rs +++ b/abi_stable_derive/src/literals_constructors.rs @@ -1,21 +1,19 @@ -//! This module contains helper types/functions to output +//! This module contains helper types/functions to output //! the literals and constructors for types that don't implement ToTokens. -use as_derive_utils::{ - to_token_fn::ToTokenFnMut, -}; +use as_derive_utils::to_token_fn::ToTokenFnMut; -use quote::{ToTokens,TokenStreamExt,quote}; +use quote::{quote, ToTokens, TokenStreamExt}; /// Constructs an RSlice constant. -pub fn rslice_tokenizer<'a,I,T>(iter:I)->impl ToTokens+'a +pub fn rslice_tokenizer<'a, I, T>(iter: I) -> impl ToTokens + 'a where - I:IntoIterator+'a, - T:ToTokens, + I: IntoIterator + 'a, + T: ToTokens, { - let mut iter=iter.into_iter(); - ToTokenFnMut::new(move|ts|{ - let iter=&mut iter; + let mut iter = iter.into_iter(); + ToTokenFnMut::new(move |ts| { + let iter = &mut iter; ts.append_all(quote!( abi_stable::std_types::RSlice::from_slice(&[ #( #iter, )* ]) )); @@ -23,13 +21,13 @@ where } /// Constructs an RStr constant. -pub fn rstr_tokenizer(string:S)->impl ToTokens +pub fn rstr_tokenizer(string: S) -> impl ToTokens where - S:AsRef + S: AsRef, { - ToTokenFnMut::new(move|ts|{ - let string=string.as_ref(); + ToTokenFnMut::new(move |ts| { + let string = string.as_ref(); ts.append_all(quote!( abi_stable::std_types::RStr::from_str(#string) )); }) -} \ No newline at end of file +} diff --git a/abi_stable_derive/src/my_visibility.rs b/abi_stable_derive/src/my_visibility.rs index 759a4133..4b3ad1b5 100644 --- a/abi_stable_derive/src/my_visibility.rs +++ b/abi_stable_derive/src/my_visibility.rs @@ -7,9 +7,8 @@ use quote::ToTokens; #[allow(unused_imports)] use syn::{ self, - token::{Pub,Paren,Super,Colon2,In,Crate}, - Path, - Visibility, + token::{Colon2, Crate, In, Paren, Pub, Super}, + Path, Visibility, }; use core_extensions::SelfOps; @@ -46,14 +45,14 @@ impl<'a> VisibilityKind<'a> { let path = &restricted.path; let is_global = restricted.path.leading_colon.is_some(); let path_seg_0 = path.segments.first(); - let is_crate = path_seg_0.map_or(false,|x| x.ident == "crate"); + let is_crate = path_seg_0.map_or(false, |x| x.ident == "crate"); if is_global || is_crate { if is_crate && path.segments.len() == 1 { VisibilityKind::Crate } else { VisibilityKind::Absolute(path) } - } else if path_seg_0.map_or(false,|x| x.ident == "self") { + } else if path_seg_0.map_or(false, |x| x.ident == "self") { assert!( path.segments.len() == 1, "paths in pub(...) that start with 'self' \ @@ -62,7 +61,7 @@ impl<'a> VisibilityKind<'a> { ); VisibilityKind::Private - } else if path_seg_0.map_or(false,|x| x.ident == "super") { + } else if path_seg_0.map_or(false, |x| x.ident == "super") { assert!( path.segments.iter().all(|segment| segment.ident == "super"), "paths in pub(...) that start with 'super' \ @@ -149,7 +148,7 @@ impl<'a> ToTokens for RelativeVis<'a> { //////////////////////////////////////////////////////////////////////////////// -#[derive(Eq,PartialEq,PartialOrd,Ord)] +#[derive(Eq, PartialEq, PartialOrd, Ord)] enum VKDiscr { Private, Super, @@ -174,7 +173,6 @@ impl<'a> PartialOrd for VisibilityKind<'a> { fn partial_cmp(&self, other: &Self) -> Option { use self::VisibilityKind as VK; - match self.to_discriminant().cmp(&other.to_discriminant()) { expr @ Ordering::Less | expr @ Ordering::Greater => return Some(expr), _ => {} @@ -222,22 +220,22 @@ mod tests { }; } - new_visibility!{vis_self="pub(self)"} - new_visibility!{vis_self_b=""} + new_visibility! {vis_self="pub(self)"} + new_visibility! {vis_self_b=""} - new_visibility!{vis_super="pub(super)"} - new_visibility!{vis_super_1="pub(in super::super)"} - new_visibility!{vis_super_2="pub(in super::super::super)"} + new_visibility! {vis_super="pub(super)"} + new_visibility! {vis_super_1="pub(in super::super)"} + new_visibility! {vis_super_2="pub(in super::super::super)"} - new_visibility!{vis_mod1_mod2="pub(in ::mod1::mod2)"} - new_visibility!{vis_mod1_mod2_mod4="pub(in ::mod1::mod2::mod4)"} - new_visibility!{vis_mod1_mod3="pub(in ::mod1::mod3)"} - new_visibility!{vis_mod1="pub(in ::mod1)"} + new_visibility! {vis_mod1_mod2="pub(in ::mod1::mod2)"} + new_visibility! {vis_mod1_mod2_mod4="pub(in ::mod1::mod2::mod4)"} + new_visibility! {vis_mod1_mod3="pub(in ::mod1::mod3)"} + new_visibility! {vis_mod1="pub(in ::mod1)"} - new_visibility!{vis_crate="crate"} - new_visibility!{vis_crate_1="pub(crate)"} + new_visibility! {vis_crate="crate"} + new_visibility! {vis_crate_1="pub(crate)"} - new_visibility!{vis_pub="pub"} + new_visibility! {vis_pub="pub"} assert_eq!(vis_self, vis_self_b); assert_eq!(vis_crate, vis_crate_1); diff --git a/abi_stable_derive/src/parse_utils.rs b/abi_stable_derive/src/parse_utils.rs index 0ad55c4d..038d3dbc 100644 --- a/abi_stable_derive/src/parse_utils.rs +++ b/abi_stable_derive/src/parse_utils.rs @@ -2,95 +2,87 @@ Functions for parsing many `syn` types. */ -use as_derive_utils::{ - spanned_err, -}; +use as_derive_utils::spanned_err; use syn::{ parse, punctuated::Punctuated, token::Add, + LitStr, //Ident, TypeParamBound, - LitStr, }; use proc_macro2::Span; //use crate::utils::SynResultExt; - -pub(crate) fn parse_str_as_ident(lit:&str)->syn::Ident{ - syn::Ident::new(&lit,Span::call_site()) +pub(crate) fn parse_str_as_ident(lit: &str) -> syn::Ident { + syn::Ident::new(&lit, Span::call_site()) } -pub(crate) fn parse_str_as_path(lit:&str)-> Result { +pub(crate) fn parse_str_as_path(lit: &str) -> Result { syn::parse_str(lit) } -pub(crate) fn parse_str_as_trait_bound(lit:&str)-> Result { +pub(crate) fn parse_str_as_trait_bound(lit: &str) -> Result { syn::parse_str(lit) } -pub(crate) fn parse_str_as_type(lit:&str)-> Result { +pub(crate) fn parse_str_as_type(lit: &str) -> Result { syn::parse_str(lit) } - - -pub(crate) fn parse_lit_as_expr(lit:&syn::LitStr)-> Result{ +pub(crate) fn parse_lit_as_expr(lit: &syn::LitStr) -> Result { lit.parse() } -pub(crate) fn parse_lit_as_type(lit:&syn::LitStr)-> Result{ +pub(crate) fn parse_lit_as_type(lit: &syn::LitStr) -> Result { lit.parse() } #[allow(dead_code)] -pub(crate) fn parse_lit_as_type_bound(lit:&syn::LitStr)-> Result{ +pub(crate) fn parse_lit_as_type_bound(lit: &syn::LitStr) -> Result { lit.parse() } #[allow(dead_code)] pub(crate) fn parse_lit_as_type_bounds( - str_: &LitStr -) -> Result,syn::Error> { - str_.parse::() - .and_then(|x|{ - if x.list.is_empty() { - Err(spanned_err!(str_,"type bounds can't be empty")) - }else{ - Ok(x.list) - } - }) + str_: &LitStr, +) -> Result, syn::Error> { + str_.parse::().and_then(|x| { + if x.list.is_empty() { + Err(spanned_err!(str_, "type bounds can't be empty")) + } else { + Ok(x.list) + } + }) } - pub struct ParseBounds { list: Punctuated, } impl parse::Parse for ParseBounds { fn parse(input: parse::ParseStream) -> parse::Result { - Ok(Self{ - list:Punctuated::::parse_terminated(input)?, + Ok(Self { + list: Punctuated::::parse_terminated(input)?, }) } } - -pub struct ParsePunctuated{ - pub list:Punctuated, +pub struct ParsePunctuated { + pub list: Punctuated, } -impl parse::Parse for ParsePunctuated +impl parse::Parse for ParsePunctuated where - T:parse::Parse, - P:parse::Parse, + T: parse::Parse, + P: parse::Parse, { - fn parse(input: parse::ParseStream) -> parse::Result{ - Ok(Self{ - list: Punctuated::parse_terminated(input)? + fn parse(input: parse::ParseStream) -> parse::Result { + Ok(Self { + list: Punctuated::parse_terminated(input)?, }) } -} \ No newline at end of file +} diff --git a/abi_stable_derive/src/sabi_extern_fn_impl.rs b/abi_stable_derive/src/sabi_extern_fn_impl.rs index 4873fd63..d11f27a9 100644 --- a/abi_stable_derive/src/sabi_extern_fn_impl.rs +++ b/abi_stable_derive/src/sabi_extern_fn_impl.rs @@ -4,102 +4,83 @@ Implementation details of the `#[sabi_extern_fn]` attribute. use std::mem; -use as_derive_utils::{ - return_spanned_err, -}; +use as_derive_utils::return_spanned_err; use proc_macro::TokenStream as TokenStream1; -use proc_macro2::{Span,TokenStream as TokenStream2,TokenTree}; +use proc_macro2::{Span, TokenStream as TokenStream2, TokenTree}; use quote::{quote, ToTokens}; -use syn::{ItemFn,Expr}; - -use crate::{parse_or_compile_err}; +use syn::{Expr, ItemFn}; +use crate::parse_or_compile_err; #[doc(hidden)] pub fn sabi_extern_fn(attr: TokenStream1, item: TokenStream1) -> TokenStream1 { - parse_or_compile_err( - item, - move|item| sabi_extern_fn_inner(attr.into(),item) - ).into() + parse_or_compile_err(item, move |item| sabi_extern_fn_inner(attr.into(), item)).into() } #[cfg(test)] -pub(crate) fn sabi_extern_fn_str(attr: &str, item: &str) -> Result { - syn::parse_str(item) - .and_then(move|item|{ - let attr=syn::parse_str::(attr)?; - sabi_extern_fn_inner(attr,item) - }) +pub(crate) fn sabi_extern_fn_str(attr: &str, item: &str) -> Result { + syn::parse_str(item).and_then(move |item| { + let attr = syn::parse_str::(attr)?; + sabi_extern_fn_inner(attr, item) + }) } /// Whether the function contains an early return or not. -#[derive(Debug,Copy,Clone,PartialEq)] -pub enum WithEarlyReturn{ +#[derive(Debug, Copy, Clone, PartialEq)] +pub enum WithEarlyReturn { No, Yes, } /// Converts a function into an `extern "C" fn` which aborts on panic. -pub(crate) fn convert_to_sabi_extern_fn( - with_early_return:WithEarlyReturn, - item:&mut ItemFn, -){ - let no_early_return=match with_early_return { - WithEarlyReturn::No=>Some(quote!( no_early_return; )), - WithEarlyReturn::Yes=>None, +pub(crate) fn convert_to_sabi_extern_fn(with_early_return: WithEarlyReturn, item: &mut ItemFn) { + let no_early_return = match with_early_return { + WithEarlyReturn::No => Some(quote!( no_early_return; )), + WithEarlyReturn::Yes => None, }; - - item.sig.abi=Some(syn::Abi{ - extern_token:Default::default(), - name:Some(syn::LitStr::new("C",Span::call_site())) + + item.sig.abi = Some(syn::Abi { + extern_token: Default::default(), + name: Some(syn::LitStr::new("C", Span::call_site())), }); - let statements=mem::replace(&mut item.block.stmts,Vec::new()); + let statements = mem::replace(&mut item.block.stmts, Vec::new()); - let x=quote!{ + let x = quote! { ::abi_stable::extern_fn_panic_handling!( #no_early_return #(#statements)* ) }; - let x=Expr::Verbatim(x); - let x=syn::Stmt::Expr(x); - let x=vec![x]; - item.block.stmts=x; + let x = Expr::Verbatim(x); + let x = syn::Stmt::Expr(x); + let x = vec![x]; + item.block.stmts = x; } - -fn sabi_extern_fn_inner(attr:TokenStream2,mut item:ItemFn)->Result{ - let with_early_return=match attr.into_iter().next() { - Some(TokenTree::Ident(ref ident))if ident =="no_early_return"=> - WithEarlyReturn::No, - Some(tt)=> - return_spanned_err!( - tt, - "Unrecognized `#[sabi_extern_fn]` parameter", - ), - None=> - WithEarlyReturn::Yes, +fn sabi_extern_fn_inner(attr: TokenStream2, mut item: ItemFn) -> Result { + let with_early_return = match attr.into_iter().next() { + Some(TokenTree::Ident(ref ident)) if ident == "no_early_return" => WithEarlyReturn::No, + Some(tt) => return_spanned_err!(tt, "Unrecognized `#[sabi_extern_fn]` parameter",), + None => WithEarlyReturn::Yes, }; - - convert_to_sabi_extern_fn(with_early_return,&mut item); - - Ok(item.into_token_stream()) -} + convert_to_sabi_extern_fn(with_early_return, &mut item); + Ok(item.into_token_stream()) +} #[cfg(test)] -mod tests{ +mod tests { use super::*; #[test] - fn test_output(){ - let list=vec![ + fn test_output() { + let list = vec![ ( "", r##" @@ -110,14 +91,14 @@ mod tests{ } "##, quote!( - pub extern "C" fn hello()->RString{ + pub extern "C" fn hello() -> RString { ::abi_stable::extern_fn_panic_handling!( println!("{}",HELLO); println!(","); println!("{}",WORLD); ) } - ) + ), ), ( "no_early_return", @@ -130,7 +111,7 @@ mod tests{ } "##, quote!( - pub(crate) extern "C" fn hello()->RStr<'_>{ + pub(crate) extern "C" fn hello() -> RStr<'_> { ::abi_stable::extern_fn_panic_handling!( no_early_return; println!("{}",HELLO); @@ -139,15 +120,15 @@ mod tests{ "stuff".into() ) } - ) + ), ), ]; - for (attr,item,expected) in list { + for (attr, item, expected) in list { assert_eq!( - sabi_extern_fn_str(attr,item).unwrap().to_string(), + sabi_extern_fn_str(attr, item).unwrap().to_string(), expected.to_string() ); } } -} \ No newline at end of file +} diff --git a/abi_stable_derive/src/sabi_trait.rs b/abi_stable_derive/src/sabi_trait.rs index a35cf1be..79b79747 100644 --- a/abi_stable_derive/src/sabi_trait.rs +++ b/abi_stable_derive/src/sabi_trait.rs @@ -1,107 +1,100 @@ use crate::{ - *, impl_interfacetype::private_associated_type, - parse_utils::{parse_str_as_ident}, - my_visibility::{VisibilityKind,RelativeVis}, + my_visibility::{RelativeVis, VisibilityKind}, + parse_utils::parse_str_as_ident, workaround::token_stream_to_string, + *, }; -use std::{ - marker::PhantomData, -}; +use std::marker::PhantomData; use proc_macro2::TokenStream as TokenStream2; -use syn::{ - ItemTrait, -}; +use syn::ItemTrait; use as_derive_utils::{ - gen_params_in::{GenParamsIn,InWhat}, + gen_params_in::{GenParamsIn, InWhat}, to_token_fn::ToTokenFnMut, }; - mod attribute_parsing; mod common_tokens; mod impl_delegations; -mod method_where_clause; mod lifetime_unelider; +mod method_where_clause; +mod methods_tokenizer; mod replace_self_path; mod trait_definition; -mod methods_tokenizer; #[cfg(test)] mod tests; use self::{ attribute_parsing::SabiTraitOptions, - common_tokens::{CommonTokens,IsStaticTrait,LifetimeTokens}, + common_tokens::{CommonTokens, IsStaticTrait, LifetimeTokens}, lifetime_unelider::LifetimeUnelider, - trait_definition::{TraitDefinition,TraitMethod}, method_where_clause::MethodWhereClause, methods_tokenizer::MethodsTokenizer, + trait_definition::{TraitDefinition, TraitMethod}, }; /// Variables passed to all the `*_items` functions here. #[allow(dead_code)] -#[derive(Copy,Clone)] -struct TokenizerParams<'a>{ - arenas:&'a Arenas, - ctokens:&'a CommonTokens, - config:&'a SabiTraitOptions<'a>, - trait_def:&'a TraitDefinition<'a>, - vis:VisibilityKind<'a>, - submod_vis:RelativeVis<'a>, - totrait_def:&'a TraitDefinition<'a>, - vtable_trait_decl:&'a TraitDefinition<'a>, - vtable_trait_impl:&'a TraitDefinition<'a>, - trait_ident:&'a syn::Ident, +#[derive(Copy, Clone)] +struct TokenizerParams<'a> { + arenas: &'a Arenas, + ctokens: &'a CommonTokens, + config: &'a SabiTraitOptions<'a>, + trait_def: &'a TraitDefinition<'a>, + vis: VisibilityKind<'a>, + submod_vis: RelativeVis<'a>, + totrait_def: &'a TraitDefinition<'a>, + vtable_trait_decl: &'a TraitDefinition<'a>, + vtable_trait_impl: &'a TraitDefinition<'a>, + trait_ident: &'a syn::Ident, /// The name of `Trait_Bounds`. - trait_bounds:&'a syn::Ident, - trait_to:&'a syn::Ident, - trait_backend:&'a syn::Ident, - trait_interface:&'a syn::Ident, - make_vtable_ident:&'a syn::Ident, - trait_cto_ident:&'a syn::Ident, - /// TokenStreams that don't have a `'lt,` if the trait object requires + trait_bounds: &'a syn::Ident, + trait_to: &'a syn::Ident, + trait_backend: &'a syn::Ident, + trait_interface: &'a syn::Ident, + make_vtable_ident: &'a syn::Ident, + trait_cto_ident: &'a syn::Ident, + /// TokenStreams that don't have a `'lt,` if the trait object requires /// `'static` to be constructed. - lt_tokens:&'a LifetimeTokens, + lt_tokens: &'a LifetimeTokens, } - /// The implementation of the `#[sabi_trait]` proc-macro attribute. -pub fn derive_sabi_trait(item: ItemTrait) -> Result { +pub fn derive_sabi_trait(item: ItemTrait) -> Result { let arenas = Arenas::default(); let arenas = &arenas; let ctokens = CommonTokens::new(); let ctokens = &ctokens; - - let trait_ident=&item.ident; - - let config=&self::attribute_parsing::parse_attrs_for_sabi_trait(&item,arenas,ctokens)?; - - let trait_def=&config.trait_definition; - let lt_tokens=&LifetimeTokens::new(trait_def.is_static); - let vis=trait_def.vis; - let submod_vis=trait_def.submod_vis; - - let totrait_def=&trait_def.replace_self(WhichItem::TraitObjectImpl)?; - let vtable_trait_decl=&trait_def.replace_self(WhichItem::VtableDecl)?; - let vtable_trait_impl=&trait_def.replace_self(WhichItem::VtableImpl)?; - - - let generated_mod=&parse_str_as_ident(&format!("{}_trait",trait_ident)); - let trait_bounds=&parse_str_as_ident(&format!("{}_Bounds",trait_ident)); - let trait_to =&parse_str_as_ident(&format!("{}_TO",trait_ident)); - let trait_backend=&parse_str_as_ident(&format!("{}_Backend",trait_ident)); - let trait_interface=&parse_str_as_ident(&format!("{}_Interface",trait_ident)); - let make_vtable_ident=&parse_str_as_ident(&format!("{}_MV",trait_ident)); - let trait_cto_ident=&parse_str_as_ident(&format!("{}_CTO",trait_ident)); - - let mut mod_contents=TokenStream2::default(); - - let tokenizer_params=TokenizerParams{ + + let trait_ident = &item.ident; + + let config = &self::attribute_parsing::parse_attrs_for_sabi_trait(&item, arenas, ctokens)?; + + let trait_def = &config.trait_definition; + let lt_tokens = &LifetimeTokens::new(trait_def.is_static); + let vis = trait_def.vis; + let submod_vis = trait_def.submod_vis; + + let totrait_def = &trait_def.replace_self(WhichItem::TraitObjectImpl)?; + let vtable_trait_decl = &trait_def.replace_self(WhichItem::VtableDecl)?; + let vtable_trait_impl = &trait_def.replace_self(WhichItem::VtableImpl)?; + + let generated_mod = &parse_str_as_ident(&format!("{}_trait", trait_ident)); + let trait_bounds = &parse_str_as_ident(&format!("{}_Bounds", trait_ident)); + let trait_to = &parse_str_as_ident(&format!("{}_TO", trait_ident)); + let trait_backend = &parse_str_as_ident(&format!("{}_Backend", trait_ident)); + let trait_interface = &parse_str_as_ident(&format!("{}_Interface", trait_ident)); + let make_vtable_ident = &parse_str_as_ident(&format!("{}_MV", trait_ident)); + let trait_cto_ident = &parse_str_as_ident(&format!("{}_CTO", trait_ident)); + + let mut mod_contents = TokenStream2::default(); + + let tokenizer_params = TokenizerParams { arenas, ctokens, config, @@ -114,28 +107,28 @@ pub fn derive_sabi_trait(item: ItemTrait) -> Result { vtable_trait_impl, trait_ident, trait_bounds, - trait_to , + trait_to, trait_backend, trait_interface, make_vtable_ident, trait_cto_ident, }; - first_items(tokenizer_params,&mut mod_contents); + first_items(tokenizer_params, &mut mod_contents); + + constructor_items(tokenizer_params, &mut mod_contents); - constructor_items(tokenizer_params,&mut mod_contents); - - trait_and_impl(tokenizer_params,&mut mod_contents); + trait_and_impl(tokenizer_params, &mut mod_contents); - methods_impls(tokenizer_params,&mut mod_contents)?; + methods_impls(tokenizer_params, &mut mod_contents)?; - declare_vtable(tokenizer_params,&mut mod_contents); - - vtable_impl(tokenizer_params,&mut mod_contents); + declare_vtable(tokenizer_params, &mut mod_contents); - impl_delegations::delegated_impls(tokenizer_params,&mut mod_contents); + vtable_impl(tokenizer_params, &mut mod_contents); - let doc_hidden_attr=config.doc_hidden_attr; + impl_delegations::delegated_impls(tokenizer_params, &mut mod_contents); + + let doc_hidden_attr = config.doc_hidden_attr; let mod_docs = if doc_hidden_attr.is_none() { Some(format!( @@ -145,7 +138,8 @@ pub fn derive_sabi_trait(item: ItemTrait) -> Result { )) } else { None - }.into_iter(); + } + .into_iter(); quote!( #doc_hidden_attr @@ -163,25 +157,25 @@ pub fn derive_sabi_trait(item: ItemTrait) -> Result { #vis mod #generated_mod{ #mod_contents } - ).observe(|tokens|{ + ) + .observe(|tokens| { // drop(_measure_time1); if config.debug_print_trait { - panic!("\n\n\n{}\n\n\n",token_stream_to_string(tokens.clone())); + panic!("\n\n\n{}\n\n\n", token_stream_to_string(tokens.clone())); } }) .piped(Ok) } - /** Outputs these items: -- `Trait_Backend`: +- `Trait_Backend`: A type alias to the underlying implementation of the trait object, which is either RObject - `Trait_Interface` - A marker type describing the traits that are required when constructing + A marker type describing the traits that are required when constructing the underlying implementation of the trait object, and are then implemented by it,by implementing InterfaceType. @@ -190,7 +184,7 @@ Outputs these items: */ fn first_items( - TokenizerParams{ + TokenizerParams { config, ctokens, lt_tokens, @@ -201,49 +195,47 @@ fn first_items( trait_interface, trait_cto_ident, .. - }:TokenizerParams, - mod_:&mut TokenStream2, -){ - let trait_ident=trait_def.name; + }: TokenizerParams, + mod_: &mut TokenStream2, +) { + let trait_ident = trait_def.name; - let doc_hidden_attr=config.doc_hidden_attr; + let doc_hidden_attr = config.doc_hidden_attr; - let mut uto_params=trait_def.generics_tokenizer( + let mut uto_params = trait_def.generics_tokenizer( InWhat::ItemDecl, WithAssocTys::Yes(WhichSelf::NoSelf), <_tokens.lt_erasedptr, ); uto_params.set_no_bounds(); - - let mut gen_params_header_rref= - trait_def.generics_tokenizer( - InWhat::ImplHeader, - WithAssocTys::Yes(WhichSelf::NoSelf), - <_tokens.lt_sub_lt, - ); + + let mut gen_params_header_rref = trait_def.generics_tokenizer( + InWhat::ImplHeader, + WithAssocTys::Yes(WhichSelf::NoSelf), + <_tokens.lt_sub_lt, + ); gen_params_header_rref.set_no_bounds(); - let gen_params_use_to_rref= - trait_def.generics_tokenizer( - InWhat::ItemUse, - WithAssocTys::Yes(WhichSelf::NoSelf), - <_tokens.lt_rref, - ); + let gen_params_use_to_rref = trait_def.generics_tokenizer( + InWhat::ItemUse, + WithAssocTys::Yes(WhichSelf::NoSelf), + <_tokens.lt_rref, + ); - let uto_params_use=trait_def.generics_tokenizer( + let uto_params_use = trait_def.generics_tokenizer( InWhat::ItemUse, WithAssocTys::Yes(WhichSelf::NoSelf), <_tokens.lt_erasedptr, ); - let mut trait_interface_header=trait_def.generics_tokenizer( + let mut trait_interface_header = trait_def.generics_tokenizer( InWhat::ImplHeader, WithAssocTys::Yes(WhichSelf::NoSelf), &ctokens.ts_empty, ); trait_interface_header.set_no_bounds(); - let mut trait_interface_decl=trait_def.generics_tokenizer( + let mut trait_interface_decl = trait_def.generics_tokenizer( InWhat::ItemDecl, WithAssocTys::Yes(WhichSelf::NoSelf), &ctokens.ts_empty, @@ -251,99 +243,99 @@ fn first_items( trait_interface_decl.set_no_bounds(); // trait_interface_decl.set_unsized_types(); - let trait_interface_use=trait_def.generics_tokenizer( + let trait_interface_use = trait_def.generics_tokenizer( InWhat::ItemUse, WithAssocTys::Yes(WhichSelf::NoSelf), &ctokens.ts_empty, ); - let mut to_params=trait_def.generics_tokenizer( + let mut to_params = trait_def.generics_tokenizer( InWhat::ItemDecl, WithAssocTys::Yes(WhichSelf::NoSelf), <_tokens.lt_erasedptr, ); to_params.set_no_bounds(); - let where_preds=(&trait_def.where_preds).into_iter(); + let where_preds = (&trait_def.where_preds).into_iter(); - let vtable_args=trait_def.generics_tokenizer( + let vtable_args = trait_def.generics_tokenizer( InWhat::ItemUse, WithAssocTys::Yes(WhichSelf::NoSelf), &ctokens.ts_unit_erasedptr, ); - let impld_traits=trait_def.impld_traits.iter().map(|x|&x.ident); - let impld_traits_a=impld_traits.clone(); - let impld_traits_b=impld_traits.clone(); + let impld_traits = trait_def.impld_traits.iter().map(|x| &x.ident); + let impld_traits_a = impld_traits.clone(); + let impld_traits_b = impld_traits.clone(); - let unimpld_traits_a=trait_def.unimpld_traits.iter().cloned(); - let unimpld_traits_b=trait_def.unimpld_traits.iter().cloned(); + let unimpld_traits_a = trait_def.unimpld_traits.iter().cloned(); + let unimpld_traits_b = trait_def.unimpld_traits.iter().cloned(); - let priv_assocty=private_associated_type(); + let priv_assocty = private_associated_type(); - let object=match trait_def.which_object { - WhichObject::DynTrait=>quote!(DynTrait), - WhichObject::RObject=>quote!(RObject), + let object = match trait_def.which_object { + WhichObject::DynTrait => quote!(DynTrait), + WhichObject::RObject => quote!(RObject), }; - let vtable_argument=match trait_def.which_object { - WhichObject::DynTrait=>quote!(__sabi_re::PrefixRef>), - WhichObject::RObject=>quote!(VTable<#vtable_args>), + let vtable_argument = match trait_def.which_object { + WhichObject::DynTrait => quote!(__sabi_re::PrefixRef>), + WhichObject::RObject => quote!(VTable<#vtable_args>), }; - let dummy_struct_generics= - trait_def.generics_tokenizer( - InWhat::DummyStruct, - WithAssocTys::Yes(WhichSelf::NoSelf), - &ctokens.ts_empty, - ); + let dummy_struct_generics = trait_def.generics_tokenizer( + InWhat::DummyStruct, + WithAssocTys::Yes(WhichSelf::NoSelf), + &ctokens.ts_empty, + ); // dummy_struct_generics.set_unsized_types(); - let used_trait_object=quote!(#trait_backend<#uto_params_use>); + let used_trait_object = quote!(#trait_backend<#uto_params_use>); - let used_to_bound=format!( + let used_to_bound = format!( "{}: ::abi_stable::StableAbi", (&used_trait_object).into_token_stream() ); - let trait_flags=&trait_def.trait_flags; - let send_syncness=match (trait_flags.sync,trait_flags.send) { - (false,false)=>"UnsyncUnsend", - (false,true )=>"UnsyncSend", - (true ,false)=>"SyncUnsend", - (true ,true )=>"SyncSend", - }.piped(parse_str_as_ident); + let trait_flags = &trait_def.trait_flags; + let send_syncness = match (trait_flags.sync, trait_flags.send) { + (false, false) => "UnsyncUnsend", + (false, true) => "UnsyncSend", + (true, false) => "SyncUnsend", + (true, true) => "SyncSend", + } + .piped(parse_str_as_ident); + + let mut trait_backend_docs = String::new(); - let mut trait_backend_docs=String::new(); + let mut trait_interface_docs = String::new(); - let mut trait_interface_docs=String::new(); + let mut trait_to_docs = String::new(); - let mut trait_to_docs=String::new(); - - let mut trait_cto_docs=String::new(); + let mut trait_cto_docs = String::new(); if doc_hidden_attr.is_none() { - trait_backend_docs=format!( + trait_backend_docs = format!( "An alias for the underlying implementation of `{}`.", trait_to, ); - trait_interface_docs=format!( + trait_interface_docs = format!( "A marker type describing the traits that are required when constructing `{}`,\ and are then implemented by it, by implementing the `InterfaceType` trait.", trait_to, ); - trait_to_docs=format!( + trait_to_docs = format!( "\ The trait object for [{Trait}](trait.{Trait}.html).\n\ \n\ There are extra methods on the `obj` field.\n ", - Trait=trait_ident - ); - trait_cto_docs=format!( + Trait = trait_ident + ); + trait_cto_docs = format!( "A type alias for the const-constructible `{trait_to}`.", - trait_to=trait_to + trait_to = trait_to ); } - let one_lt=<_tokens.one_lt; + let one_lt = <_tokens.one_lt; quote!( use super::*; @@ -365,7 +357,7 @@ fn first_items( #submod_vis type #trait_cto_ident<#gen_params_header_rref>= #trait_to<#gen_params_use_to_rref>; - + #[doc=#trait_interface_docs] #[repr(C)] @@ -401,8 +393,8 @@ fn first_items( }, }; - impl<#trait_interface_header> - abi_stable::InterfaceType + impl<#trait_interface_header> + abi_stable::InterfaceType for #trait_interface<#trait_interface_use> { #( type #impld_traits_a=Implemented; )* @@ -411,64 +403,65 @@ fn first_items( } }; - ).to_tokens(mod_); + ) + .to_tokens(mod_); } - /// Outputs the trait object constructors. -fn constructor_items( - params:TokenizerParams<'_>, - mod_:&mut TokenStream2, -){ - let TokenizerParams{ - ctokens,totrait_def,submod_vis,trait_ident,trait_to,trait_backend,trait_interface, - lt_tokens,trait_bounds,make_vtable_ident, +fn constructor_items(params: TokenizerParams<'_>, mod_: &mut TokenStream2) { + let TokenizerParams { + ctokens, + totrait_def, + submod_vis, + trait_ident, + trait_to, + trait_backend, + trait_interface, + lt_tokens, + trait_bounds, + make_vtable_ident, .. - }=params; + } = params; - let doc_hidden_attr=params.config.doc_hidden_attr; + let doc_hidden_attr = params.config.doc_hidden_attr; + let trait_params = + totrait_def.generics_tokenizer(InWhat::ItemUse, WithAssocTys::No, &ctokens.empty_ts); - let trait_params=totrait_def.generics_tokenizer( - InWhat::ItemUse, - WithAssocTys::No, - &ctokens.empty_ts, - ); + let assoc_tys_a = totrait_def.assoc_tys.keys(); + let assoc_tys_b = assoc_tys_a.clone(); + let assoc_tys_c = assoc_tys_a.clone(); + let assoc_tys_d = assoc_tys_a.clone(); - let assoc_tys_a=totrait_def.assoc_tys.keys(); - let assoc_tys_b=assoc_tys_a.clone(); - let assoc_tys_c=assoc_tys_a.clone(); - let assoc_tys_d=assoc_tys_a.clone(); - - let mut make_vtable_args=totrait_def.generics_tokenizer( + let mut make_vtable_args = totrait_def.generics_tokenizer( InWhat::ItemUse, WithAssocTys::No, &ctokens.ts_make_vtable_args, ); make_vtable_args.skip_lifetimes(); - - let fn_can_it_downcast_arg=match totrait_def.which_object { - WhichObject::DynTrait=>quote!(Downcasting), - WhichObject::RObject=>quote!(), + + let fn_can_it_downcast_arg = match totrait_def.which_object { + WhichObject::DynTrait => quote!(Downcasting), + WhichObject::RObject => quote!(), }; - let trait_interface_use=totrait_def.generics_tokenizer( + let trait_interface_use = totrait_def.generics_tokenizer( InWhat::ItemUse, WithAssocTys::Yes(WhichSelf::NoSelf), &ctokens.ts_empty, ); - let one_lt=<_tokens.one_lt; + let one_lt = <_tokens.one_lt; - let extra_constraints_ptr=match totrait_def.which_object { - WhichObject::DynTrait=>quote!( + let extra_constraints_ptr = match totrait_def.which_object { + WhichObject::DynTrait => quote!( #trait_interface<#trait_interface_use>: ::abi_stable::erased_types::InterfaceBound, __sabi_re::InterfaceFor< _OrigPtr::PtrTarget, #trait_interface<#trait_interface_use>, Downcasting - >: + >: __sabi_re::GetVtable< #one_lt _OrigPtr::PtrTarget, @@ -477,15 +470,14 @@ fn constructor_items( #trait_interface<#trait_interface_use>, >, ), - WhichObject::RObject=>quote!(), + WhichObject::RObject => quote!(), }; - - let extra_constraints_value=match totrait_def.which_object { - WhichObject::DynTrait=>quote!( + let extra_constraints_value = match totrait_def.which_object { + WhichObject::DynTrait => quote!( #trait_interface<#trait_interface_use>: ::abi_stable::erased_types::InterfaceBound, - __sabi_re::InterfaceFor<_Self,#trait_interface<#trait_interface_use>,Downcasting>: + __sabi_re::InterfaceFor<_Self,#trait_interface<#trait_interface_use>,Downcasting>: __sabi_re::GetVtable< #one_lt _Self, @@ -494,99 +486,93 @@ fn constructor_items( #trait_interface<#trait_interface_use>, >, ), - WhichObject::RObject=>quote!(), + WhichObject::RObject => quote!(), }; - let gen_params_header= - totrait_def.generics_tokenizer( - InWhat::ImplHeader, - WithAssocTys::Yes(WhichSelf::NoSelf), - <_tokens.lt_erasedptr, - ); - - let gen_params_use_to= - totrait_def.generics_tokenizer( - InWhat::ItemUse, - WithAssocTys::Yes(WhichSelf::NoSelf), - <_tokens.lt_erasedptr, - ); + let gen_params_header = totrait_def.generics_tokenizer( + InWhat::ImplHeader, + WithAssocTys::Yes(WhichSelf::NoSelf), + <_tokens.lt_erasedptr, + ); - let gen_params_header_rbox= - totrait_def.generics_tokenizer( - InWhat::ImplHeader, - WithAssocTys::Yes(WhichSelf::NoSelf), - <_tokens.lt, - ); - - let gen_params_use_to_rbox= - totrait_def.generics_tokenizer( - InWhat::ItemUse, - WithAssocTys::Yes(WhichSelf::NoSelf), - <_tokens.lt_rbox, - ); + let gen_params_use_to = totrait_def.generics_tokenizer( + InWhat::ItemUse, + WithAssocTys::Yes(WhichSelf::NoSelf), + <_tokens.lt_erasedptr, + ); + + let gen_params_header_rbox = totrait_def.generics_tokenizer( + InWhat::ImplHeader, + WithAssocTys::Yes(WhichSelf::NoSelf), + <_tokens.lt, + ); + + let gen_params_use_to_rbox = totrait_def.generics_tokenizer( + InWhat::ItemUse, + WithAssocTys::Yes(WhichSelf::NoSelf), + <_tokens.lt_rbox, + ); - let uto_params_use=totrait_def.generics_tokenizer( + let uto_params_use = totrait_def.generics_tokenizer( InWhat::ItemUse, WithAssocTys::Yes(WhichSelf::NoSelf), <_tokens.lt_erasedptr, ); - let trait_interface_use= - totrait_def.generics_tokenizer( - InWhat::ItemUse, - WithAssocTys::Yes(WhichSelf::NoSelf), - &ctokens.ts_empty, - ); + let trait_interface_use = totrait_def.generics_tokenizer( + InWhat::ItemUse, + WithAssocTys::Yes(WhichSelf::NoSelf), + &ctokens.ts_empty, + ); - let mut gen_params_header_rref= - totrait_def.generics_tokenizer( - InWhat::ImplHeader, - WithAssocTys::Yes(WhichSelf::NoSelf), - <_tokens.lt_sub_lt, - ); + let mut gen_params_header_rref = totrait_def.generics_tokenizer( + InWhat::ImplHeader, + WithAssocTys::Yes(WhichSelf::NoSelf), + <_tokens.lt_sub_lt, + ); gen_params_header_rref.set_no_bounds(); - let gen_params_use_to_rref= - totrait_def.generics_tokenizer( - InWhat::ItemUse, - WithAssocTys::Yes(WhichSelf::NoSelf), - <_tokens.lt_rref, - ); + let gen_params_use_to_rref = totrait_def.generics_tokenizer( + InWhat::ItemUse, + WithAssocTys::Yes(WhichSelf::NoSelf), + <_tokens.lt_rref, + ); - let mut shared_docs=String::new(); - let mut from_ptr_docs=String::new(); - let mut from_value_docs=String::new(); - let mut from_const_docs=String::new(); + let mut shared_docs = String::new(); + let mut from_ptr_docs = String::new(); + let mut from_value_docs = String::new(); + let mut from_const_docs = String::new(); if doc_hidden_attr.is_none() { - shared_docs="\ + shared_docs = "\

\ `can_it_downcast` describes whether the trait object can be \ converted back into the original type or not.
\n\ Its possible values are `TD_CanDowncast` and `TD_Opaque`.\n\ - ".to_string(); + " + .to_string(); - from_ptr_docs=format!( + from_ptr_docs = format!( "Constructs this trait object from a pointer to a type that implements `{trait_}`.\n\ \n\ This method is automatically generated,\n\ for more documentation you can look at\n\ [`abi_stable::docs::sabi_trait_inherent#from_ptr-method`]\n\ ", - trait_=trait_ident + trait_ = trait_ident ); - from_value_docs=format!( + from_value_docs = format!( "Constructs this trait from a type that implements `{trait_}`.\n\ \n\ This method is automatically generated,\n\ for more documentation you can look at\n\ [`abi_stable::docs::sabi_trait_inherent#from_value-method`]\n\ ", - trait_=trait_ident + trait_ = trait_ident ); - from_const_docs=format!( + from_const_docs = format!( "Constructs this trait from a constant of a type that implements `{trait_}`.\n\ \n\ This method is automatically generated,\n\ @@ -595,26 +581,23 @@ fn constructor_items( \n\ You can construct the `vtable_for` parameter with `{make_vtable_ident}::VTABLE`.\n\ ", - trait_=trait_ident, - make_vtable_ident=make_vtable_ident, + trait_ = trait_ident, + make_vtable_ident = make_vtable_ident, ); - } - - let vtable_generics_rref= - totrait_def.generics_tokenizer( - InWhat::ItemUse, - WithAssocTys::Yes(WhichSelf::NoSelf), - &ctokens.ts_unit_rref_unit, - ); - let reborrow_methods=reborrow_methods_tokenizer(params); + let vtable_generics_rref = totrait_def.generics_tokenizer( + InWhat::ItemUse, + WithAssocTys::Yes(WhichSelf::NoSelf), + &ctokens.ts_unit_rref_unit, + ); + + let reborrow_methods = reborrow_methods_tokenizer(params); + + let plus_lt = <_tokens.plus_lt; - let plus_lt=<_tokens.plus_lt; - - - let vtable_type=match totrait_def.which_object { - WhichObject::DynTrait=>quote!( + let vtable_type = match totrait_def.which_object { + WhichObject::DynTrait => quote!( __sabi_re::VTableTO_DT< #one_lt _Self, @@ -625,7 +608,7 @@ fn constructor_items( VTable<#vtable_generics_rref>, > ), - WhichObject::RObject=>quote!( + WhichObject::RObject => quote!( __sabi_re::VTableTO_RO< _Self, __sabi_re::RRef<'_sub,_Self>, @@ -634,9 +617,9 @@ fn constructor_items( > ), }; - - let constructing_backend=match totrait_def.which_object { - WhichObject::DynTrait=>quote!( + + let constructing_backend = match totrait_def.which_object { + WhichObject::DynTrait => quote!( #trait_backend::from_const( ptr, can_it_downcast, @@ -644,14 +627,14 @@ fn constructor_items( vtable_for.robject_vtable(), ) ), - WhichObject::RObject=>quote!({ + WhichObject::RObject => quote!({ let _ = __sabi_re::ManuallyDrop::new(can_it_downcast); #trait_backend::with_vtable_const(ptr,vtable_for) }), }; quote!( - impl<#gen_params_header> #trait_to<#gen_params_use_to> + impl<#gen_params_header> #trait_to<#gen_params_use_to> where _ErasedPtr: __sabi_re::AsPtr, { @@ -688,7 +671,7 @@ fn constructor_items( } /// Constructs this trait object from its underlying implementation. - /// + /// /// This method is automatically generated, /// for more documentation you can look at /// [`abi_stable::docs::sabi_trait_inherent#from_sabi-method`] @@ -701,7 +684,7 @@ fn constructor_items( #reborrow_methods } - + impl<#gen_params_header_rbox> #trait_to<#gen_params_use_to_rbox> { #[doc=#from_value_docs] #[doc=#shared_docs] @@ -746,40 +729,43 @@ fn constructor_items( } } - ).to_tokens(mod_); + ) + .to_tokens(mod_); } - /// Returns a tokenizer for the reborrowing methods fn reborrow_methods_tokenizer( - TokenizerParams{totrait_def,submod_vis,trait_to,lt_tokens,..}:TokenizerParams<'_>, -)->impl ToTokens + '_{ - ToTokenFnMut::new(move|ts|{ - let traits=totrait_def.trait_flags; + TokenizerParams { + totrait_def, + submod_vis, + trait_to, + lt_tokens, + .. + }: TokenizerParams<'_>, +) -> impl ToTokens + '_ { + ToTokenFnMut::new(move |ts| { + let traits = totrait_def.trait_flags; // If the trait object doesn't have both Sync+Send as supertraits or neither, // it can't be reborrowed. - if traits.sync!=traits.send { + if traits.sync != traits.send { return; } - let gen_params_use_ref= - totrait_def.generics_tokenizer( - InWhat::ItemUse, - WithAssocTys::Yes(WhichSelf::NoSelf), - <_tokens.lt_rref, - ); - - let gen_params_use_mut= - totrait_def.generics_tokenizer( - InWhat::ItemUse, - WithAssocTys::Yes(WhichSelf::NoSelf), - <_tokens.lt_rmut, - ); + let gen_params_use_ref = totrait_def.generics_tokenizer( + InWhat::ItemUse, + WithAssocTys::Yes(WhichSelf::NoSelf), + <_tokens.lt_rref, + ); + let gen_params_use_mut = totrait_def.generics_tokenizer( + InWhat::ItemUse, + WithAssocTys::Yes(WhichSelf::NoSelf), + <_tokens.lt_rmut, + ); quote!( /// Reborrows this trait object to a reference-based trait object. - /// + /// /// This method is automatically generated, /// for more documentation you can look at /// [`abi_stable::docs::sabi_trait_inherent#sabi_reborrow-method`] @@ -794,7 +780,7 @@ fn reborrow_methods_tokenizer( } /// Reborrows this trait object to a mutable-reference-based trait object. - /// + /// /// This method is automatically generated, /// for more documentation you can look at /// [`abi_stable::docs::sabi_trait_inherent#sabi_reborrow_mut-method`] @@ -807,38 +793,44 @@ fn reborrow_methods_tokenizer( let x=unsafe{ __sabi_re::transmute(x) }; #trait_to::from_sabi(x) } - ).to_tokens(ts); + ) + .to_tokens(ts); }) } - /// Outputs the annotated trait (as modified by the proc-macro) /// and an implementation of the trait for the generated trait object. fn trait_and_impl( - TokenizerParams{ - ctokens,submod_vis,trait_def,trait_to,lt_tokens, - trait_ident,trait_bounds,.. - }:TokenizerParams, - mod_:&mut TokenStream2, -){ - let other_attrs=trait_def.other_attrs; - let gen_params_trait= - trait_def.generics_tokenizer(InWhat::ItemDecl,WithAssocTys::No,&ctokens.empty_ts); - let where_preds=(&trait_def.where_preds).into_iter(); - let where_preds_b=where_preds.clone(); - let methods_tokenizer_def=trait_def.methods_tokenizer(WhichItem::Trait); - let methods_tokenizer_impl=trait_def.methods_tokenizer(WhichItem::TraitImpl); - let lifetime_bounds_a=trait_def.lifetime_bounds.iter(); - let lifetime_bounds_b=trait_def.lifetime_bounds.iter(); - let lifetime_bounds_c=trait_def.lifetime_bounds.iter(); - let super_traits_a=trait_def.impld_traits.iter().map(|t| &t.bound ); - let super_traits_b=super_traits_a.clone(); - - let assoc_tys_a=trait_def.assoc_tys.values().map(|x| &x.assoc_ty ); - + TokenizerParams { + ctokens, + submod_vis, + trait_def, + trait_to, + lt_tokens, + trait_ident, + trait_bounds, + .. + }: TokenizerParams, + mod_: &mut TokenStream2, +) { + let other_attrs = trait_def.other_attrs; + let gen_params_trait = + trait_def.generics_tokenizer(InWhat::ItemDecl, WithAssocTys::No, &ctokens.empty_ts); + let where_preds = (&trait_def.where_preds).into_iter(); + let where_preds_b = where_preds.clone(); + let methods_tokenizer_def = trait_def.methods_tokenizer(WhichItem::Trait); + let methods_tokenizer_impl = trait_def.methods_tokenizer(WhichItem::TraitImpl); + let lifetime_bounds_a = trait_def.lifetime_bounds.iter(); + let lifetime_bounds_b = trait_def.lifetime_bounds.iter(); + let lifetime_bounds_c = trait_def.lifetime_bounds.iter(); + let super_traits_a = trait_def.impld_traits.iter().map(|t| &t.bound); + let super_traits_b = super_traits_a.clone(); + + let assoc_tys_a = trait_def.assoc_tys.values().map(|x| &x.assoc_ty); + let unsafety = trait_def.item.unsafety; - let erased_ptr_bounds=trait_def.erased_ptr_preds(); + let erased_ptr_bounds = trait_def.erased_ptr_preds(); quote!( #( #[#other_attrs] )* @@ -846,39 +838,32 @@ fn trait_and_impl( #submod_vis #unsafety trait #trait_ident< #gen_params_trait >: #( #super_traits_a + )* - where + where #(#where_preds,)* { #( #assoc_tys_a )* #methods_tokenizer_def } - ).to_tokens(mod_); + ) + .to_tokens(mod_); - let gen_params_use_trait= - trait_def.generics_tokenizer( - InWhat::ItemUse, - WithAssocTys::No, - &ctokens.empty_ts, - ); + let gen_params_use_trait = + trait_def.generics_tokenizer(InWhat::ItemUse, WithAssocTys::No, &ctokens.empty_ts); { - let gen_params_header= - trait_def.generics_tokenizer( - InWhat::ImplHeader, - WithAssocTys::No, - &ctokens.ts_uself, - ); - - let docs=format!( + let gen_params_header = + trait_def.generics_tokenizer(InWhat::ImplHeader, WithAssocTys::No, &ctokens.ts_uself); + + let docs = format!( "A trait alias for [{Trait}](trait.{Trait}.html) + the lifetime bounds that \ it had before being stripped by the `#[sabi_trait]` attribute. ", - Trait=trait_ident + Trait = trait_ident ); quote!( #[doc= #docs ] - #submod_vis trait #trait_bounds<#gen_params_trait>: + #submod_vis trait #trait_bounds<#gen_params_trait>: #trait_ident<#gen_params_use_trait> #( + #lifetime_bounds_a )* {} @@ -887,32 +872,28 @@ fn trait_and_impl( where _Self: #trait_ident<#gen_params_use_trait> #( + #lifetime_bounds_b )* {} - ).to_tokens(mod_); - + ) + .to_tokens(mod_); } + if !trait_def.disable_trait_impl { + let gen_params_header = trait_def.generics_tokenizer( + InWhat::ImplHeader, + WithAssocTys::Yes(WhichSelf::NoSelf), + <_tokens.lt_erasedptr, + ); + let gen_params_use_to = trait_def.generics_tokenizer( + InWhat::ItemUse, + WithAssocTys::Yes(WhichSelf::NoSelf), + <_tokens.lt_erasedptr, + ); - if ! trait_def.disable_trait_impl { - - let gen_params_header= - trait_def.generics_tokenizer( - InWhat::ImplHeader, - WithAssocTys::Yes(WhichSelf::NoSelf), - <_tokens.lt_erasedptr, - ); - let gen_params_use_to= - trait_def.generics_tokenizer( - InWhat::ItemUse, - WithAssocTys::Yes(WhichSelf::NoSelf), - <_tokens.lt_erasedptr, - ); - - let assoc_ty_named_a=trait_def.assoc_tys.values().map(|x| &x.assoc_ty.ident ); - let assoc_ty_named_b=assoc_ty_named_a.clone(); + let assoc_ty_named_a = trait_def.assoc_tys.values().map(|x| &x.assoc_ty.ident); + let assoc_ty_named_b = assoc_ty_named_a.clone(); quote!( #[allow(clippy::needless_lifetimes, clippy::new_ret_no_self)] - impl<#gen_params_header> #trait_ident<#gen_params_use_trait> + impl<#gen_params_header> #trait_ident<#gen_params_use_trait> for #trait_to<#gen_params_use_to> where Self:#( #super_traits_b + )* #(#lifetime_bounds_c+)* Sized , @@ -923,49 +904,49 @@ fn trait_and_impl( #methods_tokenizer_impl } - ).to_tokens(mod_); + ) + .to_tokens(mod_); } - } /// An inherent implementation of the generated trait object, /// which mirrors the trait definition. -fn methods_impls( - param:TokenizerParams, - mod_:&mut TokenStream2, -)-> Result<(),syn::Error> { - let TokenizerParams{totrait_def,trait_to,ctokens,lt_tokens,..}=param; - - let impl_where_preds=totrait_def.trait_impl_where_preds()?; - - let super_traits_a=totrait_def.impld_traits.iter().map(|t| &t.bound ); - - let gen_params_header= - totrait_def.generics_tokenizer( - InWhat::ImplHeader, - WithAssocTys::Yes(WhichSelf::NoSelf), - <_tokens.lt_erasedptr, - ); - let gen_params_use_to= - totrait_def.generics_tokenizer( - InWhat::ItemUse, - WithAssocTys::Yes(WhichSelf::NoSelf), - <_tokens.lt_erasedptr, - ); +fn methods_impls(param: TokenizerParams, mod_: &mut TokenStream2) -> Result<(), syn::Error> { + let TokenizerParams { + totrait_def, + trait_to, + ctokens, + lt_tokens, + .. + } = param; - let generics_use1= - totrait_def.generics_tokenizer( - InWhat::ItemUse, - WithAssocTys::Yes(WhichSelf::NoSelf), - &ctokens.ts_unit_erasedptr, - ); - - let methods_tokenizer_def=totrait_def.methods_tokenizer(WhichItem::TraitObjectImpl); + let impl_where_preds = totrait_def.trait_impl_where_preds()?; + + let super_traits_a = totrait_def.impld_traits.iter().map(|t| &t.bound); + + let gen_params_header = totrait_def.generics_tokenizer( + InWhat::ImplHeader, + WithAssocTys::Yes(WhichSelf::NoSelf), + <_tokens.lt_erasedptr, + ); + let gen_params_use_to = totrait_def.generics_tokenizer( + InWhat::ItemUse, + WithAssocTys::Yes(WhichSelf::NoSelf), + <_tokens.lt_erasedptr, + ); + + let generics_use1 = totrait_def.generics_tokenizer( + InWhat::ItemUse, + WithAssocTys::Yes(WhichSelf::NoSelf), + &ctokens.ts_unit_erasedptr, + ); + + let methods_tokenizer_def = totrait_def.methods_tokenizer(WhichItem::TraitObjectImpl); quote!( #[allow(clippy::needless_lifetimes, clippy::new_ret_no_self)] impl<#gen_params_header> #trait_to<#gen_params_use_to> - where + where _ErasedPtr: __sabi_re::AsPtr, Self:#( #super_traits_a + )* Sized , #impl_where_preds @@ -981,69 +962,70 @@ fn methods_impls( #methods_tokenizer_def } - ).to_tokens(mod_); + ) + .to_tokens(mod_); Ok(()) } /// Outputs the vtable struct. fn declare_vtable( - TokenizerParams{ctokens,vtable_trait_decl,submod_vis,trait_interface,..}:TokenizerParams, - mod_:&mut TokenStream2, -){ - - - let generics_decl= - vtable_trait_decl.generics_tokenizer( - InWhat::ItemDecl, - WithAssocTys::Yes(WhichSelf::NoSelf), - &ctokens.ts_self_erasedptr, - ); + TokenizerParams { + ctokens, + vtable_trait_decl, + submod_vis, + trait_interface, + .. + }: TokenizerParams, + mod_: &mut TokenStream2, +) { + let generics_decl = vtable_trait_decl.generics_tokenizer( + InWhat::ItemDecl, + WithAssocTys::Yes(WhichSelf::NoSelf), + &ctokens.ts_self_erasedptr, + ); - let mut generics_decl_unbounded=generics_decl; + let mut generics_decl_unbounded = generics_decl; generics_decl_unbounded.set_no_bounds(); - let mut generics_use0= - vtable_trait_decl.generics_tokenizer( - InWhat::DummyStruct, - WithAssocTys::Yes(WhichSelf::NoSelf), - &ctokens.ts_self_erasedptr, - ); + let mut generics_use0 = vtable_trait_decl.generics_tokenizer( + InWhat::DummyStruct, + WithAssocTys::Yes(WhichSelf::NoSelf), + &ctokens.ts_self_erasedptr, + ); generics_use0.set_no_bounds(); - let generics_use1= - vtable_trait_decl.generics_tokenizer( - InWhat::ItemUse, - WithAssocTys::Yes(WhichSelf::NoSelf), - &ctokens.ts_self_erasedptr, - ); - + let generics_use1 = vtable_trait_decl.generics_tokenizer( + InWhat::ItemUse, + WithAssocTys::Yes(WhichSelf::NoSelf), + &ctokens.ts_self_erasedptr, + ); - let derive_attrs=vtable_trait_decl.derive_attrs; + let derive_attrs = vtable_trait_decl.derive_attrs; - let methods_tokenizer=vtable_trait_decl.methods_tokenizer(WhichItem::VtableDecl); + let methods_tokenizer = vtable_trait_decl.methods_tokenizer(WhichItem::VtableDecl); - let lifetime_bounds=if vtable_trait_decl.lifetime_bounds.is_empty() { + let lifetime_bounds = if vtable_trait_decl.lifetime_bounds.is_empty() { None - }else{ + } else { use std::fmt::Write; - let mut lifetime_bounds=String::with_capacity(32); + let mut lifetime_bounds = String::with_capacity(32); lifetime_bounds.push_str("_Self:"); for lt in &vtable_trait_decl.lifetime_bounds { - let _=write!(lifetime_bounds,"{}+",lt); + let _ = write!(lifetime_bounds, "{}+", lt); } lifetime_bounds.push_str("Sized"); Some(lifetime_bounds) - }.into_iter(); + } + .into_iter(); - let trait_interface_use= - vtable_trait_decl.generics_tokenizer( - InWhat::ItemUse, - WithAssocTys::Yes(WhichSelf::NoSelf), - &ctokens.ts_empty, - ); + let trait_interface_use = vtable_trait_decl.generics_tokenizer( + InWhat::ItemUse, + WithAssocTys::Yes(WhichSelf::NoSelf), + &ctokens.ts_empty, + ); - let robject_vtable=quote!( + let robject_vtable = quote!( __sabi_re::RObjectVtable_Ref< _Self, _ErasedPtr, @@ -1051,16 +1033,16 @@ fn declare_vtable( > ); - let real_vtable_ty=format!( - "VTableInner_Ref<{}>", - generics_use1.into_token_stream(), - ); - let inner_vtable_bound=format!("{}: ::abi_stable::StableAbi",real_vtable_ty); + let real_vtable_ty = format!("VTableInner_Ref<{}>", generics_use1.into_token_stream(),); + let inner_vtable_bound = format!("{}: ::abi_stable::StableAbi", real_vtable_ty); - let vtable_bound=format!("{}: ::abi_stable::StableAbi",(&robject_vtable).into_token_stream()); + let vtable_bound = format!( + "{}: ::abi_stable::StableAbi", + (&robject_vtable).into_token_stream() + ); - let bounds={ - let mut gen_toks=vtable_trait_decl.generics_tokenizer( + let bounds = { + let mut gen_toks = vtable_trait_decl.generics_tokenizer( InWhat::ImplHeader, WithAssocTys::Yes(WhichSelf::NoSelf), &ctokens.ts_empty, @@ -1088,7 +1070,7 @@ fn declare_vtable( _sabi_tys: __sabi_re::NonOwningPhantom<(#generics_use0)>, } - + #[repr(C)] #[derive(abi_stable::StableAbi)] #[sabi(kind(Prefix))] @@ -1107,8 +1089,8 @@ fn declare_vtable( #methods_tokenizer } - ).to_tokens(mod_); - + ) + .to_tokens(mod_); } /** @@ -1120,75 +1102,72 @@ Outputs the vtable impl block with both: */ fn vtable_impl( - TokenizerParams{ - config,ctokens,vtable_trait_impl,trait_interface,trait_cto_ident, - trait_bounds,make_vtable_ident,submod_vis,lt_tokens,.. - }:TokenizerParams, - mod_:&mut TokenStream2, -){ - let struct_decl_generics= - vtable_trait_impl.generics_tokenizer( - InWhat::ItemDecl, - WithAssocTys::No, - &ctokens.ts_getvtable_params, - ); + TokenizerParams { + config, + ctokens, + vtable_trait_impl, + trait_interface, + trait_cto_ident, + trait_bounds, + make_vtable_ident, + submod_vis, + lt_tokens, + .. + }: TokenizerParams, + mod_: &mut TokenStream2, +) { + let struct_decl_generics = vtable_trait_impl.generics_tokenizer( + InWhat::ItemDecl, + WithAssocTys::No, + &ctokens.ts_getvtable_params, + ); - let dummy_struct_tys= - vtable_trait_impl.generics_tokenizer( - InWhat::DummyStruct, - WithAssocTys::No, - &ctokens.ts_getvtable_dummy_struct_fields, - ); + let dummy_struct_tys = vtable_trait_impl.generics_tokenizer( + InWhat::DummyStruct, + WithAssocTys::No, + &ctokens.ts_getvtable_dummy_struct_fields, + ); - let impl_header_generics= - vtable_trait_impl.generics_tokenizer( - InWhat::ImplHeader, - WithAssocTys::No, - &ctokens.ts_getvtable_params, - ); + let impl_header_generics = vtable_trait_impl.generics_tokenizer( + InWhat::ImplHeader, + WithAssocTys::No, + &ctokens.ts_getvtable_params, + ); - let makevtable_generics= - vtable_trait_impl.generics_tokenizer( - InWhat::ItemUse, - WithAssocTys::No, - &ctokens.ts_getvtable_params, - ); + let makevtable_generics = vtable_trait_impl.generics_tokenizer( + InWhat::ItemUse, + WithAssocTys::No, + &ctokens.ts_getvtable_params, + ); - let trait_generics= - vtable_trait_impl.generics_tokenizer( - InWhat::ItemUse, - WithAssocTys::No, - &ctokens.empty_ts - ); + let trait_generics = + vtable_trait_impl.generics_tokenizer(InWhat::ItemUse, WithAssocTys::No, &ctokens.empty_ts); - let withmetadata_generics= - vtable_trait_impl.generics_tokenizer( - InWhat::ItemUse, - WithAssocTys::Yes(WhichSelf::Underscore), - &ctokens.ts_self_erasedptr, - ); + let withmetadata_generics = vtable_trait_impl.generics_tokenizer( + InWhat::ItemUse, + WithAssocTys::Yes(WhichSelf::Underscore), + &ctokens.ts_self_erasedptr, + ); - let trait_interface_use= - vtable_trait_impl.generics_tokenizer( - InWhat::ItemUse, - WithAssocTys::Yes(WhichSelf::Underscore), - &ctokens.ts_empty, - ); + let trait_interface_use = vtable_trait_impl.generics_tokenizer( + InWhat::ItemUse, + WithAssocTys::Yes(WhichSelf::Underscore), + &ctokens.ts_empty, + ); - let method_names_a=vtable_trait_impl.methods.iter().map(|m|m.name); - let method_names_b=method_names_a.clone(); + let method_names_a = vtable_trait_impl.methods.iter().map(|m| m.name); + let method_names_b = method_names_a.clone(); - let vtable_generics= - vtable_trait_impl.generics_tokenizer( - InWhat::ItemUse, - WithAssocTys::Yes(WhichSelf::Underscore), - &ctokens.ts_unit_erasedptr, - ); + let vtable_generics = vtable_trait_impl.generics_tokenizer( + InWhat::ItemUse, + WithAssocTys::Yes(WhichSelf::Underscore), + &ctokens.ts_unit_erasedptr, + ); - let methods_tokenizer=vtable_trait_impl.methods_tokenizer(WhichItem::VtableImpl); + let methods_tokenizer = vtable_trait_impl.methods_tokenizer(WhichItem::VtableImpl); - let const_vtable_item=match vtable_trait_impl.which_object { - WhichObject::DynTrait=>quote!( + let const_vtable_item = match vtable_trait_impl.which_object { + WhichObject::DynTrait => quote!( pub const VTABLE:__sabi_re::VTableTO_DT< 'lt, _Self, @@ -1204,7 +1183,7 @@ fn vtable_impl( ) }; ), - WhichObject::RObject=>quote!( + WhichObject::RObject => quote!( pub const VTABLE:__sabi_re::VTableTO_RO< _Self, _OrigPtr, @@ -1216,17 +1195,17 @@ fn vtable_impl( ), }; - let one_lt=<_tokens.one_lt; - - let extra_constraints=match vtable_trait_impl.which_object { - WhichObject::DynTrait=>quote!( + let one_lt = <_tokens.one_lt; + + let extra_constraints = match vtable_trait_impl.which_object { + WhichObject::DynTrait => quote!( #trait_interface<#trait_interface_use>: ::abi_stable::erased_types::InterfaceBound, __sabi_re::InterfaceFor< _Self, #trait_interface<#trait_interface_use>, IA - >: + >: __sabi_re::GetVtable< #one_lt _Self, @@ -1235,18 +1214,17 @@ fn vtable_impl( #trait_interface<#trait_interface_use>, >, ), - WhichObject::RObject=>quote!(), + WhichObject::RObject => quote!(), }; - let doc_hidden_attr=config.doc_hidden_attr; + let doc_hidden_attr = config.doc_hidden_attr; - let mut trait_mv_docs=String::new(); + let mut trait_mv_docs = String::new(); if doc_hidden_attr.is_none() { - trait_mv_docs=format!( + trait_mv_docs = format!( "A helper struct for constructing the vtable for `{0}`,with `{1}::VTABLE`", - trait_cto_ident, - make_vtable_ident, + trait_cto_ident, make_vtable_ident, ); } @@ -1256,7 +1234,7 @@ fn vtable_impl( impl<#impl_header_generics> #make_vtable_ident<#makevtable_generics> - where + where _Self:#trait_bounds<#trait_generics>, _OrigPtr: __sabi_re::CanTransmuteElement<(), PtrTarget = _Self, TransmutedPtr = _ErasedPtr>, @@ -1288,25 +1266,23 @@ fn vtable_impl( #const_vtable_item #methods_tokenizer - } - ).to_tokens(mod_); + } + ) + .to_tokens(mod_); } - - - -#[derive(Debug,Clone,PartialEq,Eq)] -pub(crate) enum SelfParam<'a>{ - ByRef{ - lifetime:Option<&'a syn::Lifetime>, - is_mutable:bool, +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum SelfParam<'a> { + ByRef { + lifetime: Option<&'a syn::Lifetime>, + is_mutable: bool, }, ByVal, } /// Which item this is refering to. -#[derive(Debug,Clone,Copy,PartialEq,Eq)] -pub(crate) enum WhichItem{ +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum WhichItem { /// the method in the trait definition Trait, /// the method in the trait implemetation for the generated trait object. @@ -1319,24 +1295,22 @@ pub(crate) enum WhichItem{ VtableImpl, } - /// Which type used to implement the trait object. -#[derive(Debug,Clone,Copy,PartialEq,Eq)] -pub(crate) enum WhichObject{ +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum WhichObject { DynTrait, - RObject + RObject, } -impl Default for WhichObject{ - fn default()->Self{ +impl Default for WhichObject { + fn default() -> Self { WhichObject::RObject } } - /// Which Self type to get the associated types from. -#[derive(Debug,Clone,Copy,PartialEq,Eq)] -pub(crate) enum WhichSelf{ +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum WhichSelf { /// Self::AssocTy #[allow(dead_code)] Regular, @@ -1349,10 +1323,9 @@ pub(crate) enum WhichSelf{ NoSelf, } - -/// Whether to include associated types when printing generic parameters. -#[derive(Debug,Clone,Copy,PartialEq,Eq)] -pub(crate) enum WithAssocTys{ +/// Whether to include associated types when printing generic parameters. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum WithAssocTys { No, Yes(WhichSelf), } diff --git a/abi_stable_derive/src/sabi_trait/attribute_parsing.rs b/abi_stable_derive/src/sabi_trait/attribute_parsing.rs index 7186ae0f..c853bc05 100644 --- a/abi_stable_derive/src/sabi_trait/attribute_parsing.rs +++ b/abi_stable_derive/src/sabi_trait/attribute_parsing.rs @@ -1,219 +1,199 @@ -use super::{ - *, - TraitDefinition, -}; +use super::{TraitDefinition, *}; -use std::{iter,mem}; +use std::{iter, mem}; -use syn::{ - Attribute, Ident, Meta, MetaList, NestedMeta, - ItemTrait,TraitItem,TraitItemMethod, -}; +use syn::{Attribute, Ident, ItemTrait, Meta, MetaList, NestedMeta, TraitItem, TraitItemMethod}; #[allow(unused_imports)] use core_extensions::SelfOps; use crate::{ - attribute_parsing::with_nested_meta, arenas::Arenas, + attribute_parsing::with_nested_meta, parse_utils::parse_str_as_path, - utils::{LinearResult,SynPathExt,SynResultExt}, + utils::{LinearResult, SynPathExt, SynResultExt}, }; - /// Configuration parsed from the helper attributes of `#[sabi_trait]` pub(crate) struct SabiTraitOptions<'a> { /// Whether the output of the proc-macro is printed with println. - pub(crate) debug_print_trait:bool, - pub(crate) doc_hidden_attr:Option<&'a TokenStream2>, - pub(crate) trait_definition:TraitDefinition<'a>, + pub(crate) debug_print_trait: bool, + pub(crate) doc_hidden_attr: Option<&'a TokenStream2>, + pub(crate) trait_definition: TraitDefinition<'a>, } - impl<'a> SabiTraitOptions<'a> { fn new( - trait_: &'a ItemTrait, + trait_: &'a ItemTrait, this: SabiTraitAttrs<'a>, arenas: &'a Arenas, - ctokens:&'a CommonTokens, - ) -> Result { - let doc_hidden_attr=if this.is_hidden { + ctokens: &'a CommonTokens, + ) -> Result { + let doc_hidden_attr = if this.is_hidden { Some(arenas.alloc(quote!(#[doc(hidden)]))) - }else{ + } else { None }; - Ok(Self{ - debug_print_trait:this.debug_print_trait, + Ok(Self { + debug_print_trait: this.debug_print_trait, doc_hidden_attr, - trait_definition:TraitDefinition::new(trait_,this,arenas,ctokens)?, + trait_definition: TraitDefinition::new(trait_, this, arenas, ctokens)?, }) } } - //////////////////////////////////////////////////////////////////////////////// /// The attributes used in the vtable,and the trait. -#[derive(Debug, Clone,Default)] -pub(crate) struct OwnedDeriveAndOtherAttrs{ +#[derive(Debug, Clone, Default)] +pub(crate) struct OwnedDeriveAndOtherAttrs { /// The attributes used in the vtable. - pub(crate) derive_attrs:Vec, + pub(crate) derive_attrs: Vec, /// The attributes used in the trait. - pub(crate) other_attrs:Vec, + pub(crate) other_attrs: Vec, } - //////////////////////////////////////////////////////////////////////////////// - /// The `syn` type for methods,as well as its attributes split by where they are used. #[derive(Debug, Clone)] -pub(crate) struct MethodWithAttrs<'a>{ +pub(crate) struct MethodWithAttrs<'a> { /// The attributes used in the vtable,and the trait. - pub(crate) attrs:OwnedDeriveAndOtherAttrs, - pub(crate) item:&'a TraitItemMethod, + pub(crate) attrs: OwnedDeriveAndOtherAttrs, + pub(crate) item: &'a TraitItemMethod, } - -impl<'a> MethodWithAttrs<'a>{ +impl<'a> MethodWithAttrs<'a> { /// Constructs a `MethodWithAttrs` with no attributes. - fn new(item:&'a TraitItemMethod)->Self{ - Self{ - attrs:OwnedDeriveAndOtherAttrs{ - derive_attrs:Vec::new(), - other_attrs:Vec::new(), + fn new(item: &'a TraitItemMethod) -> Self { + Self { + attrs: OwnedDeriveAndOtherAttrs { + derive_attrs: Vec::new(), + other_attrs: Vec::new(), }, item, } } } - //////////////////////////////////////////////////////////////////////////////// - /// A datastructure used while parsing the helper attributes of #[sabi_trait]. #[derive(Default)] pub(super) struct SabiTraitAttrs<'a> { /// Whether the output of the proc-macro is printed with println. - pub(super) debug_print_trait:bool, + pub(super) debug_print_trait: bool, /// The attributes used in the vtable,and the trait. - pub(super) attrs:OwnedDeriveAndOtherAttrs, + pub(super) attrs: OwnedDeriveAndOtherAttrs, /// The `syn` type for methods,as well as their attributes split by where they are used. - pub(super) methods_with_attrs:Vec>, + pub(super) methods_with_attrs: Vec>, /// Which type to use as the underlying implementation of the trait object, /// either DynTrait or RObject. - pub(super) which_object:WhichObject, + pub(super) which_object: WhichObject, /// If true,removes the `impl Trait for Trait_TO` - pub(super) disable_trait_impl:bool, - /// If true,doesn't use the default implementation of methods when + pub(super) disable_trait_impl: bool, + /// If true,doesn't use the default implementation of methods when /// the vtable entry is absent. - pub(super) disable_inherent_default:Vec, + pub(super) disable_inherent_default: Vec, - pub(super) is_hidden:bool, + pub(super) is_hidden: bool, - pub(super) errors:LinearResult<()>, + pub(super) errors: LinearResult<()>, } - /// Used as context while parsing helper attributes of #[sabi_trait]. #[derive(Debug, Copy, Clone)] enum ParseContext<'a> { - TraitAttr{ - name:&'a Ident, - }, - Method{ - index:usize, - }, + TraitAttr { name: &'a Ident }, + Method { index: usize }, } - /// Parses the helper attributes for `#[sabi_trait]`. pub(crate) fn parse_attrs_for_sabi_trait<'a>( - trait_:&'a ItemTrait, + trait_: &'a ItemTrait, arenas: &'a Arenas, - ctokens:&'a CommonTokens, -)-> Result,syn::Error> { - let mut this=SabiTraitAttrs::default(); + ctokens: &'a CommonTokens, +) -> Result, syn::Error> { + let mut this = SabiTraitAttrs::default(); - let assoc_fns:Vec<&'a TraitItemMethod>= - trait_.items + let assoc_fns: Vec<&'a TraitItemMethod> = trait_ + .items .iter() - .filter_map(|item|{ - match item { - TraitItem::Method(x)=>Some(x), - _=>None, - } + .filter_map(|item| match item { + TraitItem::Method(x) => Some(x), + _ => None, }) .collect(); this.methods_with_attrs.reserve(assoc_fns.len()); - this.disable_inherent_default.resize(assoc_fns.len(),false); + this.disable_inherent_default.resize(assoc_fns.len(), false); parse_inner( &mut this, &*trait_.attrs, - ParseContext::TraitAttr{name:&trait_.ident}, + ParseContext::TraitAttr { + name: &trait_.ident, + }, arenas, )?; - for (index,assoc_fn) in assoc_fns.iter().cloned().enumerate() { + for (index, assoc_fn) in assoc_fns.iter().cloned().enumerate() { this.methods_with_attrs.push(MethodWithAttrs::new(assoc_fn)); parse_inner( &mut this, &*assoc_fn.attrs, - ParseContext::Method{index}, + ParseContext::Method { index }, arenas, )?; - let last_fn=this.methods_with_attrs.last_mut().expect("BUG"); + let last_fn = this.methods_with_attrs.last_mut().expect("BUG"); if !last_fn.attrs.derive_attrs.is_empty() { wrap_attrs_in_sabi_list(&mut last_fn.attrs.derive_attrs) } } - if !this.attrs.derive_attrs.is_empty() { wrap_attrs_in_sabi_list(&mut this.attrs.derive_attrs) } this.errors.take()?; - SabiTraitOptions::new(trait_,this,arenas,ctokens) + SabiTraitOptions::new(trait_, this, arenas, ctokens) } /// Parses all the attributes on an item. -fn parse_inner<'a,I>( +fn parse_inner<'a, I>( this: &mut SabiTraitAttrs<'a>, attrs: I, pctx: ParseContext<'a>, arenas: &'a Arenas, -)-> Result<(),syn::Error> +) -> Result<(), syn::Error> where - I:IntoIterator + I: IntoIterator, { for attr in attrs { match attr.parse_meta() { Ok(Meta::List(list)) => { - parse_attr_list(this,pctx, list, arenas)?; + parse_attr_list(this, pctx, list, arenas)?; } - Ok(other_attr) => { - match pctx { - ParseContext::TraitAttr{..}=>{ - this.attrs.other_attrs.push(other_attr); - } - ParseContext::Method{..}=>{ - this.methods_with_attrs.last_mut().unwrap() - .attrs.other_attrs - .push(other_attr); - } + Ok(other_attr) => match pctx { + ParseContext::TraitAttr { .. } => { + this.attrs.other_attrs.push(other_attr); } - } - Err(e)=>{ + ParseContext::Method { .. } => { + this.methods_with_attrs + .last_mut() + .unwrap() + .attrs + .other_attrs + .push(other_attr); + } + }, + Err(e) => { this.errors.push_err(e); } } @@ -225,17 +205,19 @@ where fn parse_attr_list<'a>( this: &mut SabiTraitAttrs<'a>, pctx: ParseContext<'a>, - list: MetaList, - arenas: &'a Arenas -)-> Result<(),syn::Error> { + list: MetaList, + arenas: &'a Arenas, +) -> Result<(), syn::Error> { if list.path.equals_str("sabi") { with_nested_meta("sabi", list.nested, |attr| { - parse_sabi_trait_attr(this,pctx, attr, arenas) + parse_sabi_trait_attr(this, pctx, attr, arenas) })?; - } else if let ParseContext::Method{..}=pctx { + } else if let ParseContext::Method { .. } = pctx { this.methods_with_attrs - .last_mut().unwrap() - .attrs.other_attrs + .last_mut() + .unwrap() + .attrs + .other_attrs .push(Meta::List(list)); } else if list.path.equals_str("doc") { with_nested_meta("doc", list.nested, |attr| { @@ -250,24 +232,24 @@ fn parse_attr_list<'a>( Ok(()) } - /// Parses the `#[sabi()]` attributes on an item. fn parse_sabi_trait_attr<'a>( this: &mut SabiTraitAttrs<'a>, - pctx: ParseContext<'a>, - attr: Meta, - _arenas: &'a Arenas -)-> Result<(),syn::Error> { - fn push_attr<'a>(this:&mut SabiTraitAttrs<'a>, pctx: ParseContext<'a>, attr:Meta){ - match pctx{ - ParseContext::Method{..} => { + pctx: ParseContext<'a>, + attr: Meta, + _arenas: &'a Arenas, +) -> Result<(), syn::Error> { + fn push_attr<'a>(this: &mut SabiTraitAttrs<'a>, pctx: ParseContext<'a>, attr: Meta) { + match pctx { + ParseContext::Method { .. } => { this.methods_with_attrs - .last_mut().unwrap() + .last_mut() + .unwrap() .attrs .derive_attrs .push(attr); } - ParseContext::TraitAttr{..} => { + ParseContext::TraitAttr { .. } => { this.attrs.derive_attrs.push(attr); } } @@ -275,58 +257,57 @@ fn parse_sabi_trait_attr<'a>( match (pctx, attr) { (_, Meta::Path(path)) => { - let ident=match path.into_ident() { - Ok(x)=>x, - Err(path)=>{ - push_attr(this,pctx,Meta::Path(path)); + let ident = match path.into_ident() { + Ok(x) => x, + Err(path) => { + push_attr(this, pctx, Meta::Path(path)); return Ok(()); } }; - if ident=="no_default_fallback" { + if ident == "no_default_fallback" { match pctx { - ParseContext::TraitAttr{..}=>{ + ParseContext::TraitAttr { .. } => { for is_disabled in &mut this.disable_inherent_default { - *is_disabled=true; + *is_disabled = true; } } - ParseContext::Method{index}=>{ - this.disable_inherent_default[index]=true; + ParseContext::Method { index } => { + this.disable_inherent_default[index] = true; } } - }else if ident=="debug_print_trait" { - this.debug_print_trait=true; - }else if let ParseContext::TraitAttr{..}=pctx { - if ident=="use_dyntrait"||ident=="use_dyn_trait" { - this.which_object=WhichObject::DynTrait; - }else if ident=="no_trait_impl" { - this.disable_trait_impl=true; - }else{ - push_attr(this,pctx,Meta::Path(ident.into())); + } else if ident == "debug_print_trait" { + this.debug_print_trait = true; + } else if let ParseContext::TraitAttr { .. } = pctx { + if ident == "use_dyntrait" || ident == "use_dyn_trait" { + this.which_object = WhichObject::DynTrait; + } else if ident == "no_trait_impl" { + this.disable_trait_impl = true; + } else { + push_attr(this, pctx, Meta::Path(ident.into())); } - }else{ - push_attr(this,pctx,Meta::Path(ident.into())) + } else { + push_attr(this, pctx, Meta::Path(ident.into())) } } - (pctx,attr)=>{ - push_attr(this,pctx,attr); + (pctx, attr) => { + push_attr(this, pctx, attr); } } Ok(()) } - /// Wraps a list of Meta with `#[sabi( )]` -fn wrap_attrs_in_sabi_list
(attrs:&mut A) +fn wrap_attrs_in_sabi_list(attrs: &mut A) where - A:Default+Extend+IntoIterator, + A: Default + Extend + IntoIterator, { - let older_attrs=mem::take(attrs); + let older_attrs = mem::take(attrs); - let list=Meta::List(MetaList{ - path:parse_str_as_path("sabi").expect("BUG"), - paren_token:Default::default(), - nested:older_attrs.into_iter().map(NestedMeta::Meta).collect(), + let list = Meta::List(MetaList { + path: parse_str_as_path("sabi").expect("BUG"), + paren_token: Default::default(), + nested: older_attrs.into_iter().map(NestedMeta::Meta).collect(), }); attrs.extend(iter::once(list)); diff --git a/abi_stable_derive/src/sabi_trait/common_tokens.rs b/abi_stable_derive/src/sabi_trait/common_tokens.rs index 1b0619eb..853100a2 100644 --- a/abi_stable_derive/src/sabi_trait/common_tokens.rs +++ b/abi_stable_derive/src/sabi_trait/common_tokens.rs @@ -1,10 +1,10 @@ /*! This module defines the CommonTokens type, -used to pass constants of type from `syn` to +used to pass constants of type from `syn` to many functions in the `abi_stable_derive_lib::sabi_trait` module. */ -use proc_macro2::{Span,TokenStream}; +use proc_macro2::{Span, TokenStream}; use std::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}; @@ -93,7 +93,7 @@ declare_common_tokens! { self_sized="Self:Sized,", makevtable_typarams="IA,_Self,_ErasedPtr,_OrigPtr,", vtable_typarams="_Self,_ErasedPtr,", - + ptr_ref_bound= "_ErasedPtr: __sabi_re::AsPtr,", ptr_mut_bound= @@ -161,10 +161,8 @@ declare_common_tokens! { ] } - //////////////////////////////////////////////////////// - macro_rules! declare_lifetime_tokens { ( lifetime_tokens=[ $( $ident:ident = $expr:expr ,)* ] @@ -226,7 +224,7 @@ macro_rules! declare_lifetime_tokens { ) } -declare_lifetime_tokens!{ +declare_lifetime_tokens! { lifetime_tokens=[ lt="", lt_erasedptr="_ErasedPtr,", @@ -245,4 +243,3 @@ declare_lifetime_tokens!{ staticlt_erasedptr="_ErasedPtr,", ] } - diff --git a/abi_stable_derive/src/sabi_trait/impl_delegations.rs b/abi_stable_derive/src/sabi_trait/impl_delegations.rs index 703ae93d..3c6bf6da 100644 --- a/abi_stable_derive/src/sabi_trait/impl_delegations.rs +++ b/abi_stable_derive/src/sabi_trait/impl_delegations.rs @@ -1,34 +1,30 @@ use proc_macro2::TokenStream as TokenStream2; -use quote::{ToTokens, quote_spanned}; +use quote::{quote_spanned, ToTokens}; -use as_derive_utils::{ - gen_params_in::InWhat, -}; +use as_derive_utils::gen_params_in::InWhat; -use crate::{ - sabi_trait::{ - WhichSelf, - WithAssocTys, - TokenizerParams, - }, -}; +use crate::sabi_trait::{TokenizerParams, WhichSelf, WithAssocTys}; -/// Generates the code that delegates the implementation of the traits +/// Generates the code that delegates the implementation of the traits /// to the wrapped DynTrait or RObject. pub(super) fn delegated_impls( - TokenizerParams{ - arenas:_,ctokens,totrait_def,trait_to,trait_backend,trait_interface, + TokenizerParams { + arenas: _, + ctokens, + totrait_def, + trait_to, + trait_backend, + trait_interface, lt_tokens, .. - }:TokenizerParams<'_>, - mod_:&mut TokenStream2, -){ - let where_preds=&totrait_def.where_preds; - - let impls=totrait_def.trait_flags; - let spans=&totrait_def.trait_spans; + }: TokenizerParams<'_>, + mod_: &mut TokenStream2, +) { + let where_preds = &totrait_def.where_preds; + let impls = totrait_def.trait_flags; + let spans = &totrait_def.trait_spans; // let gen_params_deser_header= // totrait_def.generics_tokenizer( @@ -37,41 +33,37 @@ pub(super) fn delegated_impls( // <_tokens.lt_de_erasedptr, // ); - let gen_params_header= - totrait_def.generics_tokenizer( - InWhat::ImplHeader, - WithAssocTys::Yes(WhichSelf::NoSelf), - <_tokens.lt_erasedptr, - ); - let gen_params_use_to= - totrait_def.generics_tokenizer( - InWhat::ItemUse, - WithAssocTys::Yes(WhichSelf::NoSelf), - <_tokens.lt_erasedptr, - ); - - let gen_params_use_to_static= - totrait_def.generics_tokenizer( - InWhat::ItemUse, - WithAssocTys::Yes(WhichSelf::NoSelf), - <_tokens.staticlt_erasedptr, - ); - - let trait_interface_header=totrait_def.generics_tokenizer( + let gen_params_header = totrait_def.generics_tokenizer( + InWhat::ImplHeader, + WithAssocTys::Yes(WhichSelf::NoSelf), + <_tokens.lt_erasedptr, + ); + let gen_params_use_to = totrait_def.generics_tokenizer( + InWhat::ItemUse, + WithAssocTys::Yes(WhichSelf::NoSelf), + <_tokens.lt_erasedptr, + ); + + let gen_params_use_to_static = totrait_def.generics_tokenizer( + InWhat::ItemUse, + WithAssocTys::Yes(WhichSelf::NoSelf), + <_tokens.staticlt_erasedptr, + ); + + let trait_interface_header = totrait_def.generics_tokenizer( InWhat::ImplHeader, WithAssocTys::Yes(WhichSelf::NoSelf), <_tokens.lt, ); - let trait_interface_use=totrait_def.generics_tokenizer( + let trait_interface_use = totrait_def.generics_tokenizer( InWhat::ItemUse, WithAssocTys::Yes(WhichSelf::NoSelf), &ctokens.ts_empty, ); - if impls.debug { - let where_preds=where_preds.into_iter(); + let where_preds = where_preds.into_iter(); quote_spanned!(spans.debug=> impl<#gen_params_header> std::fmt::Debug @@ -85,10 +77,11 @@ pub(super) fn delegated_impls( std::fmt::Debug::fmt(&self.obj,f) } } - ).to_tokens(mod_); + ) + .to_tokens(mod_); } if impls.display { - let where_preds=where_preds.into_iter(); + let where_preds = where_preds.into_iter(); quote_spanned!(spans.display=> impl<#gen_params_header> std::fmt::Display @@ -102,10 +95,11 @@ pub(super) fn delegated_impls( std::fmt::Display::fmt(&self.obj,f) } } - ).to_tokens(mod_); + ) + .to_tokens(mod_); } if impls.error { - let where_preds=where_preds.into_iter(); + let where_preds = where_preds.into_iter(); quote_spanned!(spans.error=> impl<#gen_params_header> std::error::Error @@ -114,10 +108,11 @@ pub(super) fn delegated_impls( _ErasedPtr:__sabi_re::AsPtr, #(#where_preds,)* {} - ).to_tokens(mod_); + ) + .to_tokens(mod_); } if impls.clone { - let where_preds=where_preds.into_iter(); + let where_preds = where_preds.into_iter(); quote_spanned!(spans.clone=> impl<#gen_params_header> std::clone::Clone @@ -135,10 +130,11 @@ pub(super) fn delegated_impls( } } } - ).to_tokens(mod_); + ) + .to_tokens(mod_); } if impls.hash { - let where_preds=where_preds.into_iter(); + let where_preds = where_preds.into_iter(); quote_spanned!(spans.hash=> impl<#gen_params_header> std::hash::Hash @@ -155,10 +151,11 @@ pub(super) fn delegated_impls( std::hash::Hash::hash(&self.obj,state) } } - ).to_tokens(mod_); + ) + .to_tokens(mod_); } if impls.send { - let where_preds=where_preds.into_iter(); + let where_preds = where_preds.into_iter(); quote_spanned!(spans.send=> unsafe impl<#gen_params_header> std::marker::Send @@ -167,10 +164,11 @@ pub(super) fn delegated_impls( _ErasedPtr:__GetPointerKind, #(#where_preds,)* {} - ).to_tokens(mod_); + ) + .to_tokens(mod_); } if impls.sync { - let where_preds=where_preds.into_iter(); + let where_preds = where_preds.into_iter(); quote_spanned!(spans.sync=> unsafe impl<#gen_params_header> std::marker::Sync @@ -179,10 +177,11 @@ pub(super) fn delegated_impls( _ErasedPtr:__GetPointerKind, #(#where_preds,)* {} - ).to_tokens(mod_); + ) + .to_tokens(mod_); } if impls.fmt_write { - let where_preds=where_preds.into_iter(); + let where_preds = where_preds.into_iter(); quote_spanned!(spans.fmt_write=> impl<#gen_params_header> std::fmt::Write @@ -196,10 +195,11 @@ pub(super) fn delegated_impls( std::fmt::Write::write_str(&mut self.obj,s) } } - ).to_tokens(mod_); + ) + .to_tokens(mod_); } if impls.io_write { - let where_preds=where_preds.into_iter(); + let where_preds = where_preds.into_iter(); quote_spanned!(spans.io_write=> impl<#gen_params_header> std::io::Write @@ -218,10 +218,11 @@ pub(super) fn delegated_impls( std::io::Write::write_all(&mut self.obj,buf) } } - ).to_tokens(mod_); + ) + .to_tokens(mod_); } if impls.io_read { - let where_preds=where_preds.into_iter(); + let where_preds = where_preds.into_iter(); quote_spanned!(spans.io_read=> impl<#gen_params_header> std::io::Read @@ -238,10 +239,11 @@ pub(super) fn delegated_impls( std::io::Read::read_exact(&mut self.obj,buf) } } - ).to_tokens(mod_); + ) + .to_tokens(mod_); } if impls.io_buf_read { - let where_preds=where_preds.into_iter(); + let where_preds = where_preds.into_iter(); quote_spanned!(spans.io_buf_read=> impl<#gen_params_header> std::io::BufRead @@ -258,10 +260,11 @@ pub(super) fn delegated_impls( std::io::BufRead::consume(&mut self.obj,amount) } } - ).to_tokens(mod_); + ) + .to_tokens(mod_); } if impls.io_seek { - let where_preds=where_preds.into_iter(); + let where_preds = where_preds.into_iter(); quote_spanned!(spans.io_seek=> impl<#gen_params_header> std::io::Seek @@ -274,24 +277,23 @@ pub(super) fn delegated_impls( std::io::Seek::seek(&mut self.obj,pos) } } - ).to_tokens(mod_); + ) + .to_tokens(mod_); } - let gen_params_header_and2= - totrait_def.generics_tokenizer( - InWhat::ImplHeader, - WithAssocTys::Yes(WhichSelf::NoSelf), - &ctokens.ts_erasedptr_and2, - ); - let gen_params_use_2= - totrait_def.generics_tokenizer( - InWhat::ItemUse, - WithAssocTys::Yes(WhichSelf::NoSelf), - <_tokens.staticlt_erasedptr2, - ); - - if impls.eq{ - let where_preds=where_preds.into_iter(); + let gen_params_header_and2 = totrait_def.generics_tokenizer( + InWhat::ImplHeader, + WithAssocTys::Yes(WhichSelf::NoSelf), + &ctokens.ts_erasedptr_and2, + ); + let gen_params_use_2 = totrait_def.generics_tokenizer( + InWhat::ItemUse, + WithAssocTys::Yes(WhichSelf::NoSelf), + <_tokens.staticlt_erasedptr2, + ); + + if impls.eq { + let where_preds = where_preds.into_iter(); quote_spanned!(spans.eq=> impl<#gen_params_header> std::cmp::Eq @@ -300,10 +302,11 @@ pub(super) fn delegated_impls( _ErasedPtr:__sabi_re::AsPtr, #(#where_preds,)* {} - ).to_tokens(mod_); + ) + .to_tokens(mod_); } - if impls.partial_eq{ - let where_preds=where_preds.into_iter(); + if impls.partial_eq { + let where_preds = where_preds.into_iter(); quote_spanned!(spans.partial_eq=> impl<#gen_params_header_and2> std::cmp::PartialEq<#trait_to<#gen_params_use_2>> @@ -320,11 +323,11 @@ pub(super) fn delegated_impls( ) } } - ).to_tokens(mod_); - + ) + .to_tokens(mod_); } - if impls.ord{ - let where_preds=where_preds.into_iter(); + if impls.ord { + let where_preds = where_preds.into_iter(); quote_spanned!(spans.ord=> impl<#gen_params_header> std::cmp::Ord @@ -340,10 +343,11 @@ pub(super) fn delegated_impls( ) } } - ).to_tokens(mod_); + ) + .to_tokens(mod_); } - if impls.partial_ord{ - let where_preds=where_preds.into_iter(); + if impls.partial_ord { + let where_preds = where_preds.into_iter(); quote_spanned!(spans.partial_ord=> impl<#gen_params_header_and2> std::cmp::PartialOrd<#trait_to<#gen_params_use_2>> @@ -363,7 +367,8 @@ pub(super) fn delegated_impls( ) } } - ).to_tokens(mod_); + ) + .to_tokens(mod_); } // if let Some(deserialize_bound)=&totrait_def.deserialize_bound { @@ -407,9 +412,9 @@ pub(super) fn delegated_impls( // } // ).to_tokens(mod_); // } - + // if impls.serialize{ - + // quote!( // impl<#gen_params_header> ::serde::Serialize for #trait_to<#gen_params_use_to> // where @@ -427,8 +432,8 @@ pub(super) fn delegated_impls( // ).to_tokens(mod_); // } - if let Some(iter_item)=&totrait_def.iterator_item { - let one_lt=<_tokens.one_lt; + if let Some(iter_item) = &totrait_def.iterator_item { + let one_lt = <_tokens.one_lt; quote_spanned!(spans.iterator=> impl<#trait_interface_header> abi_stable::erased_types::IteratorItem<#one_lt> @@ -438,7 +443,8 @@ pub(super) fn delegated_impls( { type Item=#iter_item; } - ).to_tokens(mod_); + ) + .to_tokens(mod_); } if impls.iterator { quote_spanned!(spans.iterator=> @@ -469,11 +475,12 @@ pub(super) fn delegated_impls( self.obj.last() } } - ).to_tokens(mod_); + ) + .to_tokens(mod_); } if impls.double_ended_iterator { quote_spanned!(spans.double_ended_iterator=> - impl<#gen_params_header> std::iter::DoubleEndedIterator + impl<#gen_params_header> std::iter::DoubleEndedIterator for #trait_to<#gen_params_use_to> where _ErasedPtr:__GetPointerKind, @@ -483,8 +490,7 @@ pub(super) fn delegated_impls( self.obj.next_back() } } - ).to_tokens(mod_); + ) + .to_tokens(mod_); } - - } diff --git a/abi_stable_derive/src/sabi_trait/lifetime_unelider.rs b/abi_stable_derive/src/sabi_trait/lifetime_unelider.rs index 71e9ed72..29264d82 100644 --- a/abi_stable_derive/src/sabi_trait/lifetime_unelider.rs +++ b/abi_stable_derive/src/sabi_trait/lifetime_unelider.rs @@ -1,23 +1,20 @@ use syn::{ visit_mut::{self, VisitMut}, - Lifetime, TypeReference, Type, + Lifetime, Type, TypeReference, }; - /// Used to unelide the lifetimes in the `&self` parameter of methods. -pub(crate) struct LifetimeUnelider<'a,'b>{ - self_lifetime:&'b mut Option<&'a syn::Lifetime>, +pub(crate) struct LifetimeUnelider<'a, 'b> { + self_lifetime: &'b mut Option<&'a syn::Lifetime>, contains_self_borrow: bool, - pub(crate) additional_lifetime_def:Option<&'a syn::LifetimeDef> + pub(crate) additional_lifetime_def: Option<&'a syn::LifetimeDef>, } - -pub(crate) struct TypeProperties<'a>{ +pub(crate) struct TypeProperties<'a> { pub(crate) additional_lifetime_def: Option<&'a syn::LifetimeDef>, pub(crate) found_borrow_kind: Option, } - #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum BorrowKind { Reference, @@ -25,21 +22,20 @@ pub(crate) enum BorrowKind { Other, } - -impl<'a,'b> LifetimeUnelider<'a,'b>{ - pub(crate) fn new(self_lifetime:&'b mut Option<&'a syn::Lifetime>)->Self{ - Self{ +impl<'a, 'b> LifetimeUnelider<'a, 'b> { + pub(crate) fn new(self_lifetime: &'b mut Option<&'a syn::Lifetime>) -> Self { + Self { self_lifetime, contains_self_borrow: false, - additional_lifetime_def:None, + additional_lifetime_def: None, } } /// Unelide the lifetimes the `&self` parameter of methods. - pub(crate) fn visit_type(mut self,ty: &mut Type)->TypeProperties<'a> { + pub(crate) fn visit_type(mut self, ty: &mut Type) -> TypeProperties<'a> { self.contains_self_borrow = false; - - visit_mut::visit_type_mut(&mut self,ty); + + visit_mut::visit_type_mut(&mut self, ty); let found_borrow_kind = if self.contains_self_borrow { let bk = match &*ty { @@ -58,36 +54,35 @@ impl<'a,'b> LifetimeUnelider<'a,'b>{ None }; - TypeProperties{ + TypeProperties { additional_lifetime_def: self.additional_lifetime_def, found_borrow_kind, } } } - -impl<'a,'b> LifetimeUnelider<'a,'b> { - fn setup_lifetime(&mut self)->Lifetime{ - let additional_lifetime_def=&mut self.additional_lifetime_def; - let x=self.self_lifetime.get_or_insert_with(||{ +impl<'a, 'b> LifetimeUnelider<'a, 'b> { + fn setup_lifetime(&mut self) -> Lifetime { + let additional_lifetime_def = &mut self.additional_lifetime_def; + let x = self.self_lifetime.get_or_insert_with(|| { let ret = syn::parse_str::("'_self").unwrap(); let ret: &'a syn::LifetimeDef = Box::leak(Box::new(ret)); - *additional_lifetime_def=Some(ret); + *additional_lifetime_def = Some(ret); &ret.lifetime }); (*x).clone() } } -impl<'a,'b> VisitMut for LifetimeUnelider<'a,'b> { +impl<'a, 'b> VisitMut for LifetimeUnelider<'a, 'b> { fn visit_type_reference_mut(&mut self, ref_: &mut TypeReference) { if is_self_borrow(self.self_lifetime, ref_) { self.contains_self_borrow = true; } - let is_elided=ref_.lifetime.as_ref().map_or(true,|x| x.ident == "_" ); + let is_elided = ref_.lifetime.as_ref().map_or(true, |x| x.ident == "_"); - if is_elided{ - ref_.lifetime=Some(self.setup_lifetime()); + if is_elided { + ref_.lifetime = Some(self.setup_lifetime()); } visit_mut::visit_type_mut(self, &mut ref_.elem) @@ -98,65 +93,64 @@ impl<'a,'b> VisitMut for LifetimeUnelider<'a,'b> { self.contains_self_borrow = true; } - if lt.ident == "_"{ - *lt=self.setup_lifetime(); + if lt.ident == "_" { + *lt = self.setup_lifetime(); } } } - - -fn is_self_lifetime(self_lifetime: &Option<&Lifetime>, lt: &Lifetime)->bool{ +fn is_self_lifetime(self_lifetime: &Option<&Lifetime>, lt: &Lifetime) -> bool { match self_lifetime { Some(sl) if sl.ident == lt.ident => true, - _=> lt.ident == "_" + _ => lt.ident == "_", } } - -fn is_self_borrow(self_lifetime: &Option<&Lifetime>, tr: &TypeReference)->bool{ +fn is_self_borrow(self_lifetime: &Option<&Lifetime>, tr: &TypeReference) -> bool { match (self_lifetime, &tr.lifetime) { (Some(sl), Some(lt)) if sl.ident == lt.ident => true, (_, Some(lt)) => lt.ident == "_", (_, None) => true, - } } - - #[cfg(test)] -mod tests{ +mod tests { use super::*; - - fn get_self_borrow_kind<'a,'b>( - mut self_lifetime:Option<&'a syn::Lifetime>, + fn get_self_borrow_kind<'a, 'b>( + mut self_lifetime: Option<&'a syn::Lifetime>, mut ty: Type, - )-> Option { + ) -> Option { let mut this = LifetimeUnelider::new(&mut self_lifetime); let ret = this.visit_type(&mut ty.clone()); ret.found_borrow_kind } fn assert_elided(self_lifetime: &Lifetime, ty: Type, expected: BorrowKind) { - assert_eq!(get_self_borrow_kind(Some(self_lifetime), ty.clone()), Some(expected.clone())); + assert_eq!( + get_self_borrow_kind(Some(self_lifetime), ty.clone()), + Some(expected.clone()) + ); assert_eq!(get_self_borrow_kind(None, ty.clone()), Some(expected)); } fn assert_unelided(self_lifetime: &Lifetime, ty: Type, expected: BorrowKind) { - assert_eq!(get_self_borrow_kind(Some(self_lifetime), ty.clone()), Some(expected.clone())); + assert_eq!( + get_self_borrow_kind(Some(self_lifetime), ty.clone()), + Some(expected.clone()) + ); assert_eq!(get_self_borrow_kind(None, ty.clone()), None); } - - fn parse_ty(s:&str) -> syn::Type { + + fn parse_ty(s: &str) -> syn::Type { syn::parse_str(s).unwrap() } #[test] fn borrow_self_detection() { let lifetime_a = &syn::parse_str::("'a").unwrap(); - + // Implicitly borrowing from self { assert_elided(lifetime_a, parse_ty("&()"), BorrowKind::Reference); @@ -164,16 +158,40 @@ mod tests{ assert_elided(lifetime_a, parse_ty("Option<&()>"), BorrowKind::Other); assert_elided(lifetime_a, parse_ty("Option<&mut ()>"), BorrowKind::Other); assert_elided(lifetime_a, parse_ty("Foo<'_>"), BorrowKind::Other); - + assert_elided(lifetime_a, parse_ty("&'_ &'b ()"), BorrowKind::Reference); - assert_elided(lifetime_a, parse_ty("&'_ mut &'b ()"), BorrowKind::MutReference); + assert_elided( + lifetime_a, + parse_ty("&'_ mut &'b ()"), + BorrowKind::MutReference, + ); assert_elided(lifetime_a, parse_ty("&'b &'_ ()"), BorrowKind::Reference); - assert_elided(lifetime_a, parse_ty("&'b mut &'_ ()"), BorrowKind::MutReference); - - assert_elided(lifetime_a, parse_ty("Option<&'_ &'b ()>"), BorrowKind::Other); - assert_elided(lifetime_a, parse_ty("Option<&'_ mut &'b ()>"), BorrowKind::Other); - assert_elided(lifetime_a, parse_ty("Option<&'b &'_ ()>"), BorrowKind::Other); - assert_elided(lifetime_a, parse_ty("Option<&'b mut &'_ ()>"), BorrowKind::Other); + assert_elided( + lifetime_a, + parse_ty("&'b mut &'_ ()"), + BorrowKind::MutReference, + ); + + assert_elided( + lifetime_a, + parse_ty("Option<&'_ &'b ()>"), + BorrowKind::Other, + ); + assert_elided( + lifetime_a, + parse_ty("Option<&'_ mut &'b ()>"), + BorrowKind::Other, + ); + assert_elided( + lifetime_a, + parse_ty("Option<&'b &'_ ()>"), + BorrowKind::Other, + ); + assert_elided( + lifetime_a, + parse_ty("Option<&'b mut &'_ ()>"), + BorrowKind::Other, + ); } // Explicitly borrowing from self @@ -181,19 +199,46 @@ mod tests{ assert_unelided(lifetime_a, parse_ty("&'a ()"), BorrowKind::Reference); assert_unelided(lifetime_a, parse_ty("&'a mut ()"), BorrowKind::MutReference); assert_unelided(lifetime_a, parse_ty("Option<&'a ()>"), BorrowKind::Other); - assert_unelided(lifetime_a, parse_ty("Option<&'a mut ()>"), BorrowKind::Other); + assert_unelided( + lifetime_a, + parse_ty("Option<&'a mut ()>"), + BorrowKind::Other, + ); assert_unelided(lifetime_a, parse_ty("Foo<'a>"), BorrowKind::Other); assert_unelided(lifetime_a, parse_ty("&'a &'b ()"), BorrowKind::Reference); - assert_unelided(lifetime_a, parse_ty("&'a mut &'b ()"), BorrowKind::MutReference); + assert_unelided( + lifetime_a, + parse_ty("&'a mut &'b ()"), + BorrowKind::MutReference, + ); assert_unelided(lifetime_a, parse_ty("&'b &'a ()"), BorrowKind::Reference); - assert_unelided(lifetime_a, parse_ty("&'b mut &'a ()"), BorrowKind::MutReference); - - assert_unelided(lifetime_a, parse_ty("Option<&'a &'b ()>"), BorrowKind::Other); - assert_unelided(lifetime_a, parse_ty("Option<&'a mut &'b ()>"), BorrowKind::Other); - assert_unelided(lifetime_a, parse_ty("Option<&'b &'a ()>"), BorrowKind::Other); - assert_unelided(lifetime_a, parse_ty("Option<&'b mut &'a ()>"), BorrowKind::Other); - + assert_unelided( + lifetime_a, + parse_ty("&'b mut &'a ()"), + BorrowKind::MutReference, + ); + + assert_unelided( + lifetime_a, + parse_ty("Option<&'a &'b ()>"), + BorrowKind::Other, + ); + assert_unelided( + lifetime_a, + parse_ty("Option<&'a mut &'b ()>"), + BorrowKind::Other, + ); + assert_unelided( + lifetime_a, + parse_ty("Option<&'b &'a ()>"), + BorrowKind::Other, + ); + assert_unelided( + lifetime_a, + parse_ty("Option<&'b mut &'a ()>"), + BorrowKind::Other, + ); } { @@ -207,4 +252,3 @@ mod tests{ } } } - diff --git a/abi_stable_derive/src/sabi_trait/method_where_clause.rs b/abi_stable_derive/src/sabi_trait/method_where_clause.rs index 9d865235..046883e5 100644 --- a/abi_stable_derive/src/sabi_trait/method_where_clause.rs +++ b/abi_stable_derive/src/sabi_trait/method_where_clause.rs @@ -4,45 +4,43 @@ use as_derive_utils::spanned_err; use quote::ToTokens; -use syn::{WhereClause,WherePredicate}; - -use crate::utils::{LinearResult,SynResultExt}; +use syn::{WhereClause, WherePredicate}; +use crate::utils::{LinearResult, SynResultExt}; /// Parses and prints the syntactically valid where clauses in object safe traits. -#[derive(Debug,Default,Clone,PartialEq,Eq)] -pub(crate) struct MethodWhereClause<'a>{ - pub requires_self_sized:bool, - _marker:PhantomData<&'a ()>, +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub(crate) struct MethodWhereClause<'a> { + pub requires_self_sized: bool, + _marker: PhantomData<&'a ()>, } +impl<'a> MethodWhereClause<'a> { + pub fn new(where_: &'a WhereClause, ctokens: &'a CommonTokens) -> Result { + let mut this = MethodWhereClause::default(); + let mut error = LinearResult::ok(()); -impl<'a> MethodWhereClause<'a>{ - pub fn new(where_:&'a WhereClause,ctokens:&'a CommonTokens)-> Result { - let mut this=MethodWhereClause::default(); - let mut error=LinearResult::ok(()); - for predicate in &where_.predicates { match predicate { - WherePredicate::Type(ty_pred)=>{ + WherePredicate::Type(ty_pred) => { if ty_pred.bounds.is_empty() { - error.push_err(spanned_err!(predicate,"The bounds are empty")); + error.push_err(spanned_err!(predicate, "The bounds are empty")); } - if ty_pred.bounded_ty==ctokens.self_ty && - ty_pred.bounds[0]==ctokens.sized_bound + if ty_pred.bounded_ty == ctokens.self_ty + && ty_pred.bounds[0] == ctokens.sized_bound { - this.requires_self_sized=true; - }else{ - error.push_err(spanned_err!(predicate,"This bound is not supported")); + this.requires_self_sized = true; + } else { + error.push_err(spanned_err!(predicate, "This bound is not supported")); } } - WherePredicate::Lifetime{..}=>{ + WherePredicate::Lifetime { .. } => { error.push_err(spanned_err!( predicate, "Lifetime constraints are not currently supported" )); } - WherePredicate::Eq{..}=>{ + WherePredicate::Eq { .. } => { error.push_err(spanned_err!( predicate, "Type equality constraints are not currently supported", @@ -50,33 +48,30 @@ impl<'a> MethodWhereClause<'a>{ } } } - error.into_result().map(|_| this ) + error.into_result().map(|_| this) } - pub fn get_tokenizer(&self,ctokens:&'a CommonTokens)->MethodWhereClauseTokenizer<'_>{ - MethodWhereClauseTokenizer{ - where_clause:self, + pub fn get_tokenizer(&self, ctokens: &'a CommonTokens) -> MethodWhereClauseTokenizer<'_> { + MethodWhereClauseTokenizer { + where_clause: self, ctokens, } } } - - -#[derive(Debug,Clone,PartialEq,Eq)] -pub(crate) struct MethodWhereClauseTokenizer<'a>{ - where_clause:&'a MethodWhereClause<'a>, - ctokens:&'a CommonTokens, +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct MethodWhereClauseTokenizer<'a> { + where_clause: &'a MethodWhereClause<'a>, + ctokens: &'a CommonTokens, } - -impl<'a> ToTokens for MethodWhereClauseTokenizer<'a>{ +impl<'a> ToTokens for MethodWhereClauseTokenizer<'a> { fn to_tokens(&self, ts: &mut TokenStream2) { - let where_clause=self.where_clause; - let ctokens=self.ctokens; + let where_clause = self.where_clause; + let ctokens = self.ctokens; if where_clause.requires_self_sized { ctokens.self_sized.to_tokens(ts); } } -} \ No newline at end of file +} diff --git a/abi_stable_derive/src/sabi_trait/methods_tokenizer.rs b/abi_stable_derive/src/sabi_trait/methods_tokenizer.rs index 8aeeb198..d65411af 100644 --- a/abi_stable_derive/src/sabi_trait/methods_tokenizer.rs +++ b/abi_stable_derive/src/sabi_trait/methods_tokenizer.rs @@ -4,95 +4,87 @@ which is used to print the definition of the method in different places. Where this is used is determined by WhichItem: -- `WhichItem::Trait`: +- `WhichItem::Trait`: outputs the method in the trait definition. -- `WhichItem::TraitImpl`: +- `WhichItem::TraitImpl`: outputs the method in the trait implemetation for the generated trait object. - `WhichItem::TraitObjectImpl`: outputs the methods in the inherent implemetation of the generated trait object. -- `WhichItem::VtableDecl`: +- `WhichItem::VtableDecl`: outputs the fields of the trait object vtable. -- `WhichItem::VtableImpl`: +- `WhichItem::VtableImpl`: outputs the methods used to construct the vtable. */ -use super::{ - *, - lifetime_unelider::BorrowKind, -}; +use super::{lifetime_unelider::BorrowKind, *}; -use as_derive_utils::{ - to_token_fn::ToTokenFnMut, -}; +use as_derive_utils::to_token_fn::ToTokenFnMut; use quote::TokenStreamExt; - -#[derive(Debug,Copy,Clone)] -pub struct MethodsTokenizer<'a>{ - pub(crate) trait_def:&'a TraitDefinition<'a>, - pub(crate) which_item:WhichItem, +#[derive(Debug, Copy, Clone)] +pub struct MethodsTokenizer<'a> { + pub(crate) trait_def: &'a TraitDefinition<'a>, + pub(crate) which_item: WhichItem, } - -#[derive(Debug,Copy,Clone)] -pub struct MethodTokenizer<'a>{ - trait_def:&'a TraitDefinition<'a>, - method:&'a TraitMethod<'a>, - which_item:WhichItem, +#[derive(Debug, Copy, Clone)] +pub struct MethodTokenizer<'a> { + trait_def: &'a TraitDefinition<'a>, + method: &'a TraitMethod<'a>, + which_item: WhichItem, } - impl<'a> ToTokens for MethodsTokenizer<'a> { fn to_tokens(&self, ts: &mut TokenStream2) { for method in &self.trait_def.methods { - MethodTokenizer{ - trait_def:self.trait_def, + MethodTokenizer { + trait_def: self.trait_def, method, - which_item:self.which_item, - }.to_tokens(ts); + which_item: self.which_item, + } + .to_tokens(ts); } } } - + impl<'a> ToTokens for MethodTokenizer<'a> { fn to_tokens(&self, ts: &mut TokenStream2) { - let which_item=self.which_item; - let method=self.method; - let trait_def=self.trait_def; - let ctokens=trait_def.ctokens; + let which_item = self.which_item; + let method = self.method; + let trait_def = self.trait_def; + let ctokens = trait_def.ctokens; // is_method: Whether this is a method,instead of an associated function or field. // // vis: the visibility of the generated method, // None if it's implicit,Some(_) if it's explicit. - let (is_method,vis)=match which_item { - WhichItem::Trait|WhichItem::TraitImpl=>{ - (true,None) - } - WhichItem::TraitObjectImpl=>{ - (true,Some(trait_def.submod_vis)) - } - WhichItem::VtableDecl|WhichItem::VtableImpl=>{ - (false,Some(trait_def.submod_vis)) - } + let (is_method, vis) = match which_item { + WhichItem::Trait | WhichItem::TraitImpl => (true, None), + WhichItem::TraitObjectImpl => (true, Some(trait_def.submod_vis)), + WhichItem::VtableDecl | WhichItem::VtableImpl => (false, Some(trait_def.submod_vis)), }; - + // The default implementation block used both by: // - the trait definition. // - the trait object inherent impl // (for the case where the method doesn't exist in the vtable). - let default_=method.default.as_ref().filter(|_| !method.disable_inherent_default ); + let default_ = method + .default + .as_ref() + .filter(|_| !method.disable_inherent_default); - let lifetimes=Some(&method.lifetimes).filter(|l| !l.is_empty() ).into_iter(); + let lifetimes = Some(&method.lifetimes) + .filter(|l| !l.is_empty()) + .into_iter(); - let method_name=method.name; - let method_span=method_name.span(); + let method_name = method.name; + let method_span = method_name.span(); let self_ty = if is_method { quote_spanned!(method_span=> Self) @@ -112,70 +104,92 @@ impl<'a> ToTokens for MethodTokenizer<'a> { } } - let self_param=match (is_method,&method.self_param) { - (true,SelfParam::ByRef{lifetime,is_mutable:false})=>{ + let self_param = match (is_method, &method.self_param) { + ( + true, + SelfParam::ByRef { + lifetime, + is_mutable: false, + }, + ) => { quote_spanned!(method_span=> & #lifetime self) } - (true,SelfParam::ByRef{lifetime,is_mutable:true})=>{ + ( + true, + SelfParam::ByRef { + lifetime, + is_mutable: true, + }, + ) => { quote_spanned!(method_span=> & #lifetime mut self) } - (true,SelfParam::ByVal)=>{ + (true, SelfParam::ByVal) => { quote_spanned!(method_span=> self) } - (false,SelfParam::ByRef{lifetime,is_mutable:false})=>{ + ( + false, + SelfParam::ByRef { + lifetime, + is_mutable: false, + }, + ) => { let lifetime = WriteLifetime(*lifetime); quote_spanned!(method_span=> _self: __sabi_re::RRef<#lifetime, ()>) } - (false,SelfParam::ByRef{lifetime,is_mutable:true})=>{ + ( + false, + SelfParam::ByRef { + lifetime, + is_mutable: true, + }, + ) => { let lifetime = WriteLifetime(*lifetime); quote_spanned!(method_span=> _self: __sabi_re::RMut<#lifetime, ()>) } - (false,SelfParam::ByVal)=>{ + (false, SelfParam::ByVal) => { quote_spanned!(method_span=> _self:*mut ()) } }; - let param_names_a=method.params.iter() - .map(move|param|ToTokenFnMut::new(move|ts|{ - match which_item { - WhichItem::Trait=>{ - param.pattern.to_tokens(ts); - } - _=>{ - param.name.to_tokens(ts); - } + let param_names_a = method.params.iter().map(move |param| { + ToTokenFnMut::new(move |ts| match which_item { + WhichItem::Trait => { + param.pattern.to_tokens(ts); } - })); - let param_ty =method.params.iter().map(|param| ¶m.ty ); - let param_names_c=param_names_a.clone(); - let param_names_d=param_names_a.clone(); - let param_names_e=method.params.iter().map(|x| x.pattern ); - let return_ty=method.output.iter(); - - let self_is_sized_bound=Some(&ctokens.self_sized) - .filter(|_| is_method&&method.self_param==SelfParam::ByVal ); - - let abi=match which_item { - WhichItem::VtableImpl=>Some(&ctokens.extern_c), - _=>method.abi, + _ => { + param.name.to_tokens(ts); + } + }) + }); + let param_ty = method.params.iter().map(|param| ¶m.ty); + let param_names_c = param_names_a.clone(); + let param_names_d = param_names_a.clone(); + let param_names_e = method.params.iter().map(|x| x.pattern); + let return_ty = method.output.iter(); + + let self_is_sized_bound = Some(&ctokens.self_sized) + .filter(|_| is_method && method.self_param == SelfParam::ByVal); + + let abi = match which_item { + WhichItem::VtableImpl => Some(&ctokens.extern_c), + _ => method.abi, }; - let user_where_clause=method.where_clause.get_tokenizer(ctokens); + let user_where_clause = method.where_clause.get_tokenizer(ctokens); - let other_attrs=if which_item==WhichItem::Trait { + let other_attrs = if which_item == WhichItem::Trait { method.other_attrs - }else{ - &[] + } else { + &[] }; if WhichItem::VtableImpl == which_item { ts.append_all(quote_spanned!(method_span=> #[doc(hidden)] )); } - if WhichItem::VtableDecl==which_item { - let optional_field=default_.as_ref().map(|_| &ctokens.missing_field_option ); - let derive_attrs=method.derive_attrs; - + if WhichItem::VtableDecl == which_item { + let optional_field = default_.as_ref().map(|_| &ctokens.missing_field_option); + let derive_attrs = method.derive_attrs; quote_spanned!( method_span=> #optional_field @@ -184,12 +198,14 @@ impl<'a> ToTokens for MethodTokenizer<'a> { #(for< #(#lifetimes,)* >)* unsafe extern "C" fn( #self_param, - #( #param_names_a:#param_ty ,)* + #( #param_names_a:#param_ty ,)* ) #(-> #return_ty )* ) - }else{ - let inherent_method_docs = ToTokenFnMut::new(|ts|{ - if WhichItem::TraitObjectImpl != which_item { return } + } else { + let inherent_method_docs = ToTokenFnMut::new(|ts| { + if WhichItem::TraitObjectImpl != which_item { + return; + } let trait_name = trait_def.name; let m_docs = format!( "This is the inherent equivalent of \ @@ -202,9 +218,9 @@ impl<'a> ToTokens for MethodTokenizer<'a> { ts.append_all(quote!(#[doc = #m_docs])); }); - let unsafety=match which_item { - WhichItem::VtableImpl=>Some(&ctokens.unsafe_), - _=>method.unsafety + let unsafety = match which_item { + WhichItem::VtableImpl => Some(&ctokens.unsafe_), + _ => method.unsafety, }; quote_spanned!(method_span=> @@ -212,47 +228,53 @@ impl<'a> ToTokens for MethodTokenizer<'a> { #(#[#other_attrs])* #inherent_method_docs #vis #unsafety #abi fn #method_name #(< #(#lifetimes,)* >)* ( - #self_param, - #( #param_names_a:#param_ty ,)* + #self_param, + #( #param_names_a:#param_ty ,)* ) #(-> #return_ty )* where #self_is_sized_bound #user_where_clause ) - }.to_tokens(ts); - - let ptr_constraint=match &method.self_param { - SelfParam::ByRef{is_mutable:false,..}=> - &ctokens.ptr_ref_bound, - SelfParam::ByRef{is_mutable:true,..}=> - &ctokens.ptr_mut_bound, - SelfParam::ByVal=> - &ctokens.ptr_val_bound, + } + .to_tokens(ts); + + let ptr_constraint = match &method.self_param { + SelfParam::ByRef { + is_mutable: false, .. + } => &ctokens.ptr_ref_bound, + SelfParam::ByRef { + is_mutable: true, .. + } => &ctokens.ptr_mut_bound, + SelfParam::ByVal => &ctokens.ptr_val_bound, }; - match (which_item,&method.self_param) { - (WhichItem::Trait,_)=>{ - method.default.as_ref().map(|x|x.block).to_tokens(ts); + match (which_item, &method.self_param) { + (WhichItem::Trait, _) => { + method.default.as_ref().map(|x| x.block).to_tokens(ts); method.semicolon.to_tokens(ts); } - (WhichItem::TraitImpl,_)=>{ + (WhichItem::TraitImpl, _) => { ts.append_all(quote_spanned!(method_span=>{ self.#method_name(#(#param_names_c,)*) })); } - (WhichItem::TraitObjectImpl,_)=>{ - let method_call=match &method.self_param { - SelfParam::ByRef{is_mutable:false,..}=>{ - quote_spanned!(method_span=> - __method(self.obj.sabi_as_rref(),#(#param_names_c,)*) + (WhichItem::TraitObjectImpl, _) => { + let method_call = match &method.self_param { + SelfParam::ByRef { + is_mutable: false, .. + } => { + quote_spanned!(method_span=> + __method(self.obj.sabi_as_rref(),#(#param_names_c,)*) ) } - SelfParam::ByRef{is_mutable:true,..}=>{ - quote_spanned!(method_span=> - __method(self.obj.sabi_as_rmut(),#(#param_names_c,)*) + SelfParam::ByRef { + is_mutable: true, .. + } => { + quote_spanned!(method_span=> + __method(self.obj.sabi_as_rmut(),#(#param_names_c,)*) ) } - SelfParam::ByVal=>{ + SelfParam::ByVal => { quote_spanned!(method_span=> self.obj.sabi_with_value( move|_self|__method( @@ -265,8 +287,8 @@ impl<'a> ToTokens for MethodTokenizer<'a> { }; match default_ { - Some(default_)=>{ - let block=&default_.block; + Some(default_) => { + let block = &default_.block; ts.append_all(quote_spanned!(method_span=> #ptr_constraint { @@ -286,7 +308,7 @@ impl<'a> ToTokens for MethodTokenizer<'a> { } )); } - None=>{ + None => { ts.append_all(quote_spanned!(method_span=> #ptr_constraint { @@ -299,26 +321,24 @@ impl<'a> ToTokens for MethodTokenizer<'a> { } } } - (WhichItem::VtableDecl,_)=>{ + (WhichItem::VtableDecl, _) => { quote_spanned!(method_span=> , ).to_tokens(ts); - } - (WhichItem::VtableImpl,SelfParam::ByRef{is_mutable,..})=>{ - - let mut_token = ToTokenFnMut::new(|ts|{ + (WhichItem::VtableImpl, SelfParam::ByRef { is_mutable, .. }) => { + let mut_token = ToTokenFnMut::new(|ts| { if *is_mutable { - syn::token::Mut{span: method_span}.to_tokens(ts); + syn::token::Mut { span: method_span }.to_tokens(ts); } }); let transmute_ret = match method.return_borrow_kind { - Some(BorrowKind::Reference)=>{ + Some(BorrowKind::Reference) => { quote_spanned!(method_span=> ::std::mem::transmute(ret) ) } - Some(BorrowKind::MutReference)=>{ + Some(BorrowKind::MutReference) => { quote_spanned!(method_span=> ::std::mem::transmute(ret) ) } - Some(BorrowKind::Other)=>{ + Some(BorrowKind::Other) => { // Motivation: // We need to use this transmute to return a borrow from `_self`, // without adding a `_Self: '_self` bound, @@ -326,10 +346,9 @@ impl<'a> ToTokens for MethodTokenizer<'a> { // The correctness of the lifetime is guaranteed by the trait definition. quote_spanned!(method_span=> __sabi_re::transmute_ignore_size(ret) ) } - None=>quote_spanned!(method_span=> ret ), + None => quote_spanned!(method_span=> ret ), }; - ts.append_all(quote_spanned!(method_span=>{ let ret = ::abi_stable::extern_fn_panic_handling!{no_early_return; __Trait::#method_name( @@ -341,7 +360,7 @@ impl<'a> ToTokens for MethodTokenizer<'a> { #transmute_ret })); } - (WhichItem::VtableImpl,SelfParam::ByVal)=>{ + (WhichItem::VtableImpl, SelfParam::ByVal) => { ts.append_all(quote_spanned!(method_span=>{ ::abi_stable::extern_fn_panic_handling!{no_early_return; __Trait::#method_name( @@ -352,4 +371,4 @@ impl<'a> ToTokens for MethodTokenizer<'a> { } } } -} \ No newline at end of file +} diff --git a/abi_stable_derive/src/sabi_trait/replace_self_path.rs b/abi_stable_derive/src/sabi_trait/replace_self_path.rs index 3bc850bf..12fe5c1b 100644 --- a/abi_stable_derive/src/sabi_trait/replace_self_path.rs +++ b/abi_stable_derive/src/sabi_trait/replace_self_path.rs @@ -1,22 +1,18 @@ /** Contains the replace_self_path function,and the ReplaceWith enum. */ - -use as_derive_utils::{ - spanned_err, -}; +use as_derive_utils::spanned_err; use syn::visit_mut::VisitMut; -use syn::{Ident, TypePath,TraitItemType}; +use syn::{Ident, TraitItemType, TypePath}; use std::mem; -use crate::utils::{LinearResult,SynResultExt}; - +use crate::utils::{LinearResult, SynResultExt}; /// What to do with the a path component when it's found. -#[derive(Debug,Clone)] -pub(crate) enum ReplaceWith{ +#[derive(Debug, Clone)] +pub(crate) enum ReplaceWith { /// Replaces the identifier of the path component with another. Ident(Ident), /// Removes the path component. @@ -26,14 +22,14 @@ pub(crate) enum ReplaceWith{ } // This is only pub(crate) because it appears as a bound of `replace_self_path`. -pub(crate)trait VisitMutWith{ - fn visit_mut_with(&mut self,other:&mut SelfReplacer) +pub(crate) trait VisitMutWith { + fn visit_mut_with(&mut self, other: &mut SelfReplacer) where F: FnMut(&Ident) -> Option; } macro_rules! impl_visit_mut_with { - ( + ( $( ($self_:ty,$method:path) ),* $(,)* ) => ( @@ -51,7 +47,7 @@ macro_rules! impl_visit_mut_with { ) } -impl_visit_mut_with!{ +impl_visit_mut_with! { (syn::WherePredicate,VisitMut::visit_where_predicate_mut), (TraitItemType,VisitMut::visit_trait_item_type_mut), (syn::Type,VisitMut::visit_type_mut), @@ -60,41 +56,40 @@ impl_visit_mut_with!{ /** Replaces all associated types of `Self` from `value`. -`replace_with` determines what happens to `Self::` when `Some()` is +`replace_with` determines what happens to `Self::` when `Some()` is returned from `is_assoc_type`. -`is_assoc_type` is used to find the associated types to replace +`is_assoc_type` is used to find the associated types to replace (when the function returns Some(_)), as well as what to replace them with. */ -pub(crate) fn replace_self_path( +pub(crate) fn replace_self_path( value: &mut V, - replace_with:ReplaceWith, - is_assoc_type: F -)-> Result<(),syn::Error> + replace_with: ReplaceWith, + is_assoc_type: F, +) -> Result<(), syn::Error> where - V:VisitMutWith, + V: VisitMutWith, F: FnMut(&Ident) -> Option, { - let mut replacer=SelfReplacer { + let mut replacer = SelfReplacer { is_assoc_type, - buffer:Vec::with_capacity(2), - replace_with, - errors:LinearResult::ok(()), + buffer: Vec::with_capacity(2), + replace_with, + errors: LinearResult::ok(()), }; value.visit_mut_with(&mut replacer); replacer.errors.into() } - // This is only pub(crate) because it is used within the VisitMutWith trait. -pub(crate)struct SelfReplacer { +pub(crate) struct SelfReplacer { is_assoc_type: F, - buffer:Vec, - replace_with:ReplaceWith, - errors:LinearResult<()>, + buffer: Vec, + replace_with: ReplaceWith, + errors: LinearResult<()>, } impl VisitMut for SelfReplacer @@ -105,59 +100,57 @@ where if let Some(qself) = i.qself.as_mut() { self.visit_type_mut(&mut qself.ty); } - - + let segments = &mut i.path.segments; for segment in &mut *segments { self.visit_path_arguments_mut(&mut segment.arguments); } - + // println!("\nbefore:{}",(&*segments).into_token_stream() ); // println!("segments[1]:{}",segments.iter().nth(1).into_token_stream() ); - let is_self= segments[0].ident == "Self"; + let is_self = segments[0].ident == "Self"; match (segments.len(), is_self) { - (0,true)|(1,true)=>{ + (0, true) | (1, true) => { self.errors.push_err(spanned_err!( segments, - "Self can't be used in a parameter,return type,or associated type.", + "Self can't be used in a parameter,return type,or associated type.", )); return; } - (2,true)=>{} - (_,true)=>{ + (2, true) => {} + (_, true) => { self.errors.push_err(spanned_err!( segments, - "Paths with 3 or more components are currently unsupported", + "Paths with 3 or more components are currently unsupported", )); return; } - (_,false)=>return, + (_, false) => return, } - let is_replaced=(self.is_assoc_type)(&segments[1].ident); + let is_replaced = (self.is_assoc_type)(&segments[1].ident); // println!("is_replaced:{:?}",is_replaced ); - if let Some(replace_assoc_with)= is_replaced{ + if let Some(replace_assoc_with) = is_replaced { let mut prev_segments = mem::take(segments).into_iter(); - + self.buffer.clear(); self.buffer.push(self.replace_with.clone()); self.buffer.push(replace_assoc_with); for replace_with in self.buffer.drain(..) { - let prev_segment=prev_segments.next(); + let prev_segment = prev_segments.next(); match replace_with { - ReplaceWith::Ident(ident)=>{ + ReplaceWith::Ident(ident) => { segments.push(ident.into()); } - ReplaceWith::Remove=>{} - ReplaceWith::Keep=>{ + ReplaceWith::Remove => {} + ReplaceWith::Keep => { segments.extend(prev_segment); } } } - } // println!("after:{}",(&*i).into_token_stream() ); } diff --git a/abi_stable_derive/src/sabi_trait/tests.rs b/abi_stable_derive/src/sabi_trait/tests.rs index 25b4822e..ca3a944d 100644 --- a/abi_stable_derive/src/sabi_trait/tests.rs +++ b/abi_stable_derive/src/sabi_trait/tests.rs @@ -1,14 +1,10 @@ -use crate::{ - derive_sabi_trait_str as derive_sabi_trait, -}; +use crate::derive_sabi_trait_str as derive_sabi_trait; use as_derive_utils::test_framework::Tests; - #[test] -fn must_not_pass(){ - - let list=vec![ +fn must_not_pass() { + let list = vec![ " trait Foo { fn foo(); @@ -34,7 +30,7 @@ fn must_not_pass(){ trait Bar { const X: usize; } - " + ", ]; for elem in list { if derive_sabi_trait(elem).is_ok() { @@ -44,13 +40,13 @@ fn must_not_pass(){ } #[test] -fn sabi_trait_test_cases(){ +fn sabi_trait_test_cases() { Tests::load("sabi_trait").run_test(derive_sabi_trait); } #[test] -fn must_pass(){ - let list=vec![ +fn must_pass() { + let list = vec![ " trait ConstBaz { fn baz(self); @@ -61,4 +57,4 @@ fn must_pass(){ for elem in list { derive_sabi_trait(elem).unwrap(); } -} \ No newline at end of file +} diff --git a/abi_stable_derive/src/sabi_trait/trait_definition.rs b/abi_stable_derive/src/sabi_trait/trait_definition.rs index 4cad6e92..2078ff32 100644 --- a/abi_stable_derive/src/sabi_trait/trait_definition.rs +++ b/abi_stable_derive/src/sabi_trait/trait_definition.rs @@ -1,141 +1,135 @@ use super::{ - *, - attribute_parsing::{MethodWithAttrs,SabiTraitAttrs}, - impl_interfacetype::{TRAIT_LIST,TraitStruct,WhichTrait}, - replace_self_path::{self,ReplaceWith}, + attribute_parsing::{MethodWithAttrs, SabiTraitAttrs}, + impl_interfacetype::{TraitStruct, WhichTrait, TRAIT_LIST}, lifetime_unelider::BorrowKind, - parse_utils::{parse_str_as_ident,parse_str_as_type,parse_str_as_trait_bound}, + parse_utils::{parse_str_as_ident, parse_str_as_trait_bound, parse_str_as_type}, + replace_self_path::{self, ReplaceWith}, + *, }; use crate::{ set_span_visitor::SetSpanVisitor, - utils::{dummy_ident,LinearResult,SynResultExt}, + utils::{dummy_ident, LinearResult, SynResultExt}, }; -use as_derive_utils::{ - syn_err, - spanned_err, - return_spanned_err, -}; +use as_derive_utils::{return_spanned_err, spanned_err, syn_err}; use std::{ - collections::{HashMap,HashSet}, + collections::{HashMap, HashSet}, iter, }; -use core_extensions::{matches,IteratorExt}; +use core_extensions::{matches, IteratorExt}; use syn::{ - token::{Comma,Colon,Semi}, punctuated::Punctuated, - Ident,ItemTrait,Visibility,FnArg,Lifetime,LifetimeDef,Meta, - TypeParamBound,Block,WherePredicate,TraitItem,Abi, - token::Unsafe, spanned::Spanned, + token::Unsafe, + token::{Colon, Comma, Semi}, visit_mut::VisitMut, + Abi, Block, FnArg, Ident, ItemTrait, Lifetime, LifetimeDef, Meta, TraitItem, TypeParamBound, + Visibility, WherePredicate, }; use proc_macro2::Span; - - -#[derive(Debug,Clone)] -pub struct AssocTyWithIndex{ - pub index:usize, - pub assoc_ty:syn::TraitItemType, +#[derive(Debug, Clone)] +pub struct AssocTyWithIndex { + pub index: usize, + pub assoc_ty: syn::TraitItemType, } - //////////////////////////////////////////////////////////////////////////////// - /// Represents a trait for use in `#[sabi_trait]`. -#[derive(Debug,Clone)] -pub(crate) struct TraitDefinition<'a>{ - pub(crate) item:&'a ItemTrait, +#[derive(Debug, Clone)] +pub(crate) struct TraitDefinition<'a> { + pub(crate) item: &'a ItemTrait, /// The name of the trait. - pub(crate) name:&'a Ident, + pub(crate) name: &'a Ident, /// What type to use the backend for the trait object,DynTrait or RObject. - pub(crate) which_object:WhichObject, + pub(crate) which_object: WhichObject, /// The where predicates in the where clause of the trait, /// if it doesn't have one this is empty. - pub(crate) where_preds:Punctuated, + pub(crate) where_preds: Punctuated, /// Attributes applied to the vtable. - pub(crate) derive_attrs:&'a [Meta], + pub(crate) derive_attrs: &'a [Meta], /// Attributes applied to the trait. - pub(crate) other_attrs:&'a [Meta], - pub(crate) generics:&'a syn::Generics, + pub(crate) other_attrs: &'a [Meta], + pub(crate) generics: &'a syn::Generics, /// The `Iterator::Item` type for this trait, /// None if it doesn't have Iterator as a supertrait. - pub(crate) iterator_item:Option<&'a syn::Type>, + pub(crate) iterator_item: Option<&'a syn::Type>, #[allow(dead_code)] - /// The path for the implemented serde::Deserialize trait + /// The path for the implemented serde::Deserialize trait /// (it may reference some trait lifetime parameter) - pub(crate) deserialize_bound:Option>, + pub(crate) deserialize_bound: Option>, /// The traits this has as supertraits. - pub(crate) impld_traits:Vec>, + pub(crate) impld_traits: Vec>, /// The traits this doesn't have as supertraits. - pub(crate) unimpld_traits:Vec<&'a Ident>, - /// A struct describing the traits this does and doesn't have as supertraits + pub(crate) unimpld_traits: Vec<&'a Ident>, + /// A struct describing the traits this does and doesn't have as supertraits /// (true means implemented,false means unimplemented) - pub(crate) trait_flags:TraitStruct, + pub(crate) trait_flags: TraitStruct, /// The region of code of the identifiers for the supertraits, /// with `Span::call_site()` for the ones that aren't supertraits. - pub(crate) trait_spans:TraitStruct, - /// The lifetimes declared in the trait generic parameter list that are used in + pub(crate) trait_spans: TraitStruct, + /// The lifetimes declared in the trait generic parameter list that are used in /// `&'lifetime self` `&'lifetime mut self` method receivers, /// or used directly as supertraits. - pub(crate) lifetime_bounds:Punctuated<&'a Lifetime,Comma>, + pub(crate) lifetime_bounds: Punctuated<&'a Lifetime, Comma>, /// The visibility of the trait. - pub(crate) vis:VisibilityKind<'a>, + pub(crate) vis: VisibilityKind<'a>, /// The visibility of the trait,inside a submodule. - pub(crate) submod_vis:RelativeVis<'a>, + pub(crate) submod_vis: RelativeVis<'a>, // The keys use the proginal identifier for the associated type. - pub(crate) assoc_tys:HashMap<&'a Ident, AssocTyWithIndex>, - /// - pub(crate) methods:Vec>, + pub(crate) assoc_tys: HashMap<&'a Ident, AssocTyWithIndex>, + /// + pub(crate) methods: Vec>, /// Whether this has by mutable reference methods. - pub(crate) has_mut_methods:bool, + pub(crate) has_mut_methods: bool, /// Whether this has by-value methods. - pub(crate) has_val_methods:bool, + pub(crate) has_val_methods: bool, /// Disables `ìmpl Trait for Trait_TO` - pub(crate) disable_trait_impl:bool, + pub(crate) disable_trait_impl: bool, /// Whether this has `'static` as a supertrait syntactically. - pub(crate) is_static:IsStaticTrait, + pub(crate) is_static: IsStaticTrait, /// A TokenStream with the equivalent of `::` - pub(crate) ts_fq_self:&'a TokenStream2, - pub(crate) ctokens:&'a CommonTokens, - pub(crate) arenas:&'a Arenas, + pub(crate) ts_fq_self: &'a TokenStream2, + pub(crate) ctokens: &'a CommonTokens, + pub(crate) arenas: &'a Arenas, } //////////////////////////////////////////////////////////////////////////////// -impl<'a> TraitDefinition<'a>{ +impl<'a> TraitDefinition<'a> { pub(super) fn new( - trait_:&'a ItemTrait, - SabiTraitAttrs{ + trait_: &'a ItemTrait, + SabiTraitAttrs { attrs, methods_with_attrs, which_object, disable_trait_impl, disable_inherent_default, .. - }:SabiTraitAttrs<'a>, + }: SabiTraitAttrs<'a>, arenas: &'a Arenas, - ctokens:&'a CommonTokens, - )-> Result { - let vis=VisibilityKind::new(&trait_.vis); - let submod_vis=vis.submodule_level(1); - let mut assoc_tys=HashMap::default(); - let mut methods=Vec::>::new(); - - let mut errors=LinearResult::ok(()); - - methods_with_attrs.into_iter().zip(disable_inherent_default) - .filter_map(|(func,disable_inh_def)|{ - match TraitMethod::new(func,disable_inh_def,&trait_.vis,ctokens,arenas) { - Ok(x)=>x, - Err(e)=>{ + ctokens: &'a CommonTokens, + ) -> Result { + let vis = VisibilityKind::new(&trait_.vis); + let submod_vis = vis.submodule_level(1); + let mut assoc_tys = HashMap::default(); + let mut methods = Vec::>::new(); + + let mut errors = LinearResult::ok(()); + + methods_with_attrs + .into_iter() + .zip(disable_inherent_default) + .filter_map(|(func, disable_inh_def)| { + match TraitMethod::new(func, disable_inh_def, &trait_.vis, ctokens, arenas) { + Ok(x) => x, + Err(e) => { errors.push_err(e); None } @@ -146,15 +140,16 @@ impl<'a> TraitDefinition<'a>{ ///////////////////////////////////////////////////// //// Processing the supertrait bounds - let mut is_static=IsStaticTrait::No; + let mut is_static = IsStaticTrait::No; - let lifetime_params:HashSet<&'a Lifetime>= - trait_.generics.lifetimes() - .map(|l| &l.lifetime ) - .chain(iter::once(&ctokens.static_lifetime)) - .collect(); + let lifetime_params: HashSet<&'a Lifetime> = trait_ + .generics + .lifetimes() + .map(|l| &l.lifetime) + .chain(iter::once(&ctokens.static_lifetime)) + .collect(); - let GetSupertraits{ + let GetSupertraits { impld_traits, unimpld_traits, mut lifetime_bounds, @@ -162,8 +157,8 @@ impl<'a> TraitDefinition<'a>{ deserialize_bound, trait_flags, trait_spans, - errors:supertrait_errors, - }=get_supertraits( + errors: supertrait_errors, + } = get_supertraits( &trait_.supertraits, &lifetime_params, which_object, @@ -172,13 +167,16 @@ impl<'a> TraitDefinition<'a>{ ); errors.combine_err(supertrait_errors.into()); - // Adding the lifetime parameters in `&'a self` and `&'a mut self` + // Adding the lifetime parameters in `&'a self` and `&'a mut self` // that were declared in the trait generic parameter list. - // This is done because those lifetime bounds are enforced as soon as + // This is done because those lifetime bounds are enforced as soon as // the vtable is created,instead of when the methods are called // (it's enforced in method calls in regular trait objects). for method in &methods { - if let SelfParam::ByRef{lifetime:Some(lt),..}=method.self_param { + if let SelfParam::ByRef { + lifetime: Some(lt), .. + } = method.self_param + { if lifetime_params.contains(lt) { lifetime_bounds.push(lt); } @@ -186,56 +184,66 @@ impl<'a> TraitDefinition<'a>{ } for lt in &lifetime_bounds { - if lt.ident=="static" { - is_static=IsStaticTrait::Yes; + if lt.ident == "static" { + is_static = IsStaticTrait::Yes; } } ///////////////////////////////////////////////////// - let mut assoc_ty_index=0; + let mut assoc_ty_index = 0; for item in &trait_.items { match item { - TraitItem::Method{..}=>{}, - TraitItem::Type(assoc_ty)=>{ - let with_index=AssocTyWithIndex{ - index:assoc_ty_index, - assoc_ty:assoc_ty.clone() + TraitItem::Method { .. } => {} + TraitItem::Type(assoc_ty) => { + let with_index = AssocTyWithIndex { + index: assoc_ty_index, + assoc_ty: assoc_ty.clone(), }; - assoc_tys.insert(&assoc_ty.ident,with_index); + assoc_tys.insert(&assoc_ty.ident, with_index); - assoc_ty_index+=1; - }, - item=>errors.push_err(spanned_err!( + assoc_ty_index += 1; + } + item => errors.push_err(spanned_err!( item, "Associated item not compatible with #[sabi_trait]", )), } } - let has_mut_methods=methods.iter() - .any(|m| matches!(&m.self_param, SelfParam::ByRef{is_mutable:true,..}) ); + let has_mut_methods = methods.iter().any(|m| { + matches!( + &m.self_param, + SelfParam::ByRef { + is_mutable: true, + .. + } + ) + }); - let has_val_methods=methods.iter() - .any(|m| matches!(&m.self_param, SelfParam::ByVal) ); - + let has_val_methods = methods + .iter() + .any(|m| matches!(&m.self_param, SelfParam::ByVal)); - let ts_fq_self={ - let (_,generics_params,_)=trait_.generics.split_for_impl(); + let ts_fq_self = { + let (_, generics_params, _) = trait_.generics.split_for_impl(); quote!( <_OrigPtr::PtrTarget as __Trait #generics_params >:: ) }; errors.into_result()?; - Ok(TraitDefinition{ - item:trait_, - name:&trait_.ident, + Ok(TraitDefinition { + item: trait_, + name: &trait_.ident, which_object, - where_preds:trait_.generics.where_clause.as_ref() - .map(|wc| wc.predicates.clone() ) + where_preds: trait_ + .generics + .where_clause + .as_ref() + .map(|wc| wc.predicates.clone()) .unwrap_or_default(), - derive_attrs:arenas.alloc(attrs.derive_attrs), - other_attrs:arenas.alloc(attrs.other_attrs), - generics:&trait_.generics, + derive_attrs: arenas.alloc(attrs.derive_attrs), + other_attrs: arenas.alloc(attrs.other_attrs), + generics: &trait_.generics, lifetime_bounds, iterator_item, deserialize_bound, @@ -250,7 +258,7 @@ impl<'a> TraitDefinition<'a>{ has_mut_methods, has_val_methods, disable_trait_impl, - ts_fq_self:arenas.alloc(ts_fq_self), + ts_fq_self: arenas.alloc(ts_fq_self), is_static, ctokens, arenas, @@ -259,38 +267,32 @@ impl<'a> TraitDefinition<'a>{ /// Returns a clone of `self`, /// where usages of associated types are replaced for use in `which_item`. - pub fn replace_self(&self,which_item:WhichItem)->Result{ - let mut this=self.clone(); + pub fn replace_self(&self, which_item: WhichItem) -> Result { + let mut this = self.clone(); - let ctokens=self.ctokens; + let ctokens = self.ctokens; - let mut errors=LinearResult::ok(()); + let mut errors = LinearResult::ok(()); - let replace_with=match which_item { - WhichItem::Trait|WhichItem::TraitImpl=>{ + let replace_with = match which_item { + WhichItem::Trait | WhichItem::TraitImpl => { return Ok(this); } - WhichItem::TraitObjectImpl=>{ - ReplaceWith::Remove - } - WhichItem::VtableDecl=>{ - ReplaceWith::Remove - } - WhichItem::VtableImpl=>{ - ReplaceWith::Ident(ctokens.u_capself.clone()) - } + WhichItem::TraitObjectImpl => ReplaceWith::Remove, + WhichItem::VtableDecl => ReplaceWith::Remove, + WhichItem::VtableImpl => ReplaceWith::Ident(ctokens.u_capself.clone()), }; - let is_assoc_type=|ident:&Ident|{ + let is_assoc_type = |ident: &Ident| { if self.assoc_tys.contains_key(ident) { Some(ReplaceWith::Keep) - }else{ + } else { None } }; for where_pred in &mut this.where_preds { - replace_self_path::replace_self_path(where_pred,replace_with.clone(),is_assoc_type) + replace_self_path::replace_self_path(where_pred, replace_with.clone(), is_assoc_type) .combine_into_err(&mut errors); } @@ -299,50 +301,57 @@ impl<'a> TraitDefinition<'a>{ &mut assoc_ty.assoc_ty, replace_with.clone(), is_assoc_type, - ).combine_into_err(&mut errors); + ) + .combine_into_err(&mut errors); } for method in &mut this.methods { - method.replace_self(replace_with.clone(),is_assoc_type) + method + .replace_self(replace_with.clone(), is_assoc_type) .combine_into_err(&mut errors); } - errors.into_result().map(|_| this ) + errors.into_result().map(|_| this) } /// Returns a tokenizer for the generic parameters in this trait. /// /// # Parameters - /// + /// /// - `in_what`: /// Determines where the generic parameters are printed. /// Eg:impl headers,trait declaration,trait usage. /// /// - `with_assoc_tys`: /// Whether associated types are printed,and how. - /// + /// /// - `after_lifetimes`: /// What will be printed after lifetime parameters. - /// + /// pub fn generics_tokenizer( &self, - in_what:InWhat, - with_assoc_tys:WithAssocTys, - after_lifetimes:&'a TokenStream2, - )->GenericsTokenizer<'_> { - let ctokens=self.ctokens; - GenericsTokenizer{ - gen_params_in: - GenParamsIn::with_after_lifetimes(self.generics,in_what,after_lifetimes), - assoc_tys:match with_assoc_tys { - WithAssocTys::Yes(WhichSelf::Regular)=> - Some((&self.assoc_tys,&ctokens.ts_self_colon2)), - WithAssocTys::Yes(WhichSelf::Underscore)=> - Some((&self.assoc_tys,&ctokens.ts_uself_colon2)), - WithAssocTys::Yes(WhichSelf::FullyQualified)=> - Some((&self.assoc_tys,self.ts_fq_self)), - WithAssocTys::Yes(WhichSelf::NoSelf)=> - Some((&self.assoc_tys,&ctokens.empty_ts)), - WithAssocTys::No =>None, + in_what: InWhat, + with_assoc_tys: WithAssocTys, + after_lifetimes: &'a TokenStream2, + ) -> GenericsTokenizer<'_> { + let ctokens = self.ctokens; + GenericsTokenizer { + gen_params_in: GenParamsIn::with_after_lifetimes( + self.generics, + in_what, + after_lifetimes, + ), + assoc_tys: match with_assoc_tys { + WithAssocTys::Yes(WhichSelf::Regular) => { + Some((&self.assoc_tys, &ctokens.ts_self_colon2)) + } + WithAssocTys::Yes(WhichSelf::Underscore) => { + Some((&self.assoc_tys, &ctokens.ts_uself_colon2)) + } + WithAssocTys::Yes(WhichSelf::FullyQualified) => { + Some((&self.assoc_tys, self.ts_fq_self)) + } + WithAssocTys::Yes(WhichSelf::NoSelf) => Some((&self.assoc_tys, &ctokens.empty_ts)), + WithAssocTys::No => None, }, } } @@ -351,35 +360,34 @@ impl<'a> TraitDefinition<'a>{ /// /// Example erased pointer types:`RBox<()>`,`RArc<()>`,`&()`,`&mut ()` /// - pub fn erased_ptr_preds(&self)->&'a TokenStream2{ - let ctokens=self.ctokens; - match (self.has_mut_methods,self.has_val_methods) { - (false,false)=> &ctokens.ptr_ref_bound, - (false,true )=> &ctokens.ptr_ref_val_bound, - (true ,false)=> &ctokens.ptr_mut_bound, - (true ,true )=> &ctokens.ptr_mut_val_bound, + pub fn erased_ptr_preds(&self) -> &'a TokenStream2 { + let ctokens = self.ctokens; + match (self.has_mut_methods, self.has_val_methods) { + (false, false) => &ctokens.ptr_ref_bound, + (false, true) => &ctokens.ptr_ref_val_bound, + (true, false) => &ctokens.ptr_mut_bound, + (true, true) => &ctokens.ptr_mut_val_bound, } } - /// Returns the where predicates of the inherent implementation of + /// Returns the where predicates of the inherent implementation of /// the ffi-safe trait object. - pub fn trait_impl_where_preds(&self)-> Result,syn::Error> { - let mut where_preds=self.where_preds.clone(); - let mut errors=LinearResult::ok(()); + pub fn trait_impl_where_preds(&self) -> Result, syn::Error> { + let mut where_preds = self.where_preds.clone(); + let mut errors = LinearResult::ok(()); for where_pred in &mut where_preds { - replace_self_path::replace_self_path( - where_pred, - ReplaceWith::Remove, - |ident| self.assoc_tys.get(ident).map(|_| ReplaceWith::Remove ) - ).combine_into_err(&mut errors); + replace_self_path::replace_self_path(where_pred, ReplaceWith::Remove, |ident| { + self.assoc_tys.get(ident).map(|_| ReplaceWith::Remove) + }) + .combine_into_err(&mut errors); } - errors.into_result().map(|_| where_preds ) + errors.into_result().map(|_| where_preds) } /// Returns a tokenizer that outputs the method definitions inside the `which_item` item. - pub fn methods_tokenizer(&self,which_item:WhichItem)->MethodsTokenizer<'_>{ - MethodsTokenizer{ - trait_def:self, + pub fn methods_tokenizer(&self, which_item: WhichItem) -> MethodsTokenizer<'_> { + MethodsTokenizer { + trait_def: self, which_item, } } @@ -387,77 +395,73 @@ impl<'a> TraitDefinition<'a>{ //////////////////////////////////////////////////////////////////////////////// - /// Represents a trait method for use in `#[sabi_trait]`. -#[derive(Debug,Clone)] -pub(crate) struct TraitMethod<'a>{ - pub(crate) disable_inherent_default:bool, +#[derive(Debug, Clone)] +pub(crate) struct TraitMethod<'a> { + pub(crate) disable_inherent_default: bool, /// A refernce to the `syn` type this was derived from. - pub(crate) item:&'a syn::TraitItemMethod, + pub(crate) item: &'a syn::TraitItemMethod, pub(crate) unsafety: Option<&'a Unsafe>, pub(crate) abi: Option<&'a Abi>, /// The visibility of the trait - pub(crate) vis:&'a Visibility, + pub(crate) vis: &'a Visibility, /// Attributes applied to the method in the vtable. - pub(crate) derive_attrs:&'a [Meta], + pub(crate) derive_attrs: &'a [Meta], /// Attributes applied to the method in the trait definition. - pub(crate) other_attrs:&'a [Meta], + pub(crate) other_attrs: &'a [Meta], /// The name of the method. - pub(crate) name:&'a Ident, - pub(crate) self_param:SelfParam<'a>, + pub(crate) name: &'a Ident, + pub(crate) self_param: SelfParam<'a>, /// The lifetime parameters of this method. pub(crate) lifetimes: Vec<&'a LifetimeDef>, pub(crate) params: Vec>, /// The return type of this method,if None this returns `()`. pub(crate) output: Option, - + /// Whether the return type borrows from self pub(crate) return_borrow_kind: Option, - - pub(crate) where_clause:MethodWhereClause<'a>, + + pub(crate) where_clause: MethodWhereClause<'a>, /// The default implementation of the method. - pub(crate) default:Option>, + pub(crate) default: Option>, /// The semicolon token for the method /// (when the method did not have a default implementation). - pub(crate) semicolon:Option<&'a Semi>, - pub(crate) ctokens:&'a CommonTokens, + pub(crate) semicolon: Option<&'a Semi>, + pub(crate) ctokens: &'a CommonTokens, } - -#[derive(Debug,Clone)] -pub(crate) struct DefaultMethod<'a>{ - pub(crate) block:&'a Block, +#[derive(Debug, Clone)] +pub(crate) struct DefaultMethod<'a> { + pub(crate) block: &'a Block, } - -#[derive(Debug,Clone,PartialEq,Eq)] -pub(crate) struct MethodParam<'a>{ +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct MethodParam<'a> { /// The name of the method parameter, /// which is `param_` if the parameter is not just an identifier /// (ie:`(left,right)`,`Rect3D{x,y,z}`) - pub(crate) name:&'a Ident, + pub(crate) name: &'a Ident, /// The parameter type. - pub(crate) ty:syn::Type, + pub(crate) ty: syn::Type, /// The pattern for the parameter - pub(crate) pattern:&'a syn::Pat, + pub(crate) pattern: &'a syn::Pat, } - -impl<'a> TraitMethod<'a>{ +impl<'a> TraitMethod<'a> { pub fn new( - mwa:MethodWithAttrs<'a>, - disable_inherent_default:bool, - vis:&'a Visibility, - ctokens:&'a CommonTokens, - arena:&'a Arenas, - )-> Result,syn::Error> { - let method_signature=&mwa.item.sig; - let decl=method_signature; - let name=&method_signature.ident; - - let mut errors=LinearResult::ok(()); - - let push_error_msg=|errors:&mut Result<(),syn::Error>|{ + mwa: MethodWithAttrs<'a>, + disable_inherent_default: bool, + vis: &'a Visibility, + ctokens: &'a CommonTokens, + arena: &'a Arenas, + ) -> Result, syn::Error> { + let method_signature = &mwa.item.sig; + let decl = method_signature; + let name = &method_signature.ident; + + let mut errors = LinearResult::ok(()); + + let push_error_msg = |errors: &mut Result<(), syn::Error>| { errors.push_err(spanned_err!( method_signature.ident, "Cannot define #[sabi_trait]traits containing methods \ @@ -468,38 +472,35 @@ impl<'a> TraitMethod<'a>{ push_error_msg(&mut errors); } - let mut input_iter=decl.inputs.iter(); - - let mut self_param=match input_iter.next() { - Some(FnArg::Receiver(receiver))=> - match &receiver.reference { - Some((_,lifetime))=> - SelfParam::ByRef{ - lifetime:lifetime.as_ref(), - is_mutable:receiver.mutability.is_some(), - }, - None=> - SelfParam::ByVal, - } - Some(FnArg::Typed{..})=>{ + let mut input_iter = decl.inputs.iter(); + + let mut self_param = match input_iter.next() { + Some(FnArg::Receiver(receiver)) => match &receiver.reference { + Some((_, lifetime)) => SelfParam::ByRef { + lifetime: lifetime.as_ref(), + is_mutable: receiver.mutability.is_some(), + }, + None => SelfParam::ByVal, + }, + Some(FnArg::Typed { .. }) => { push_error_msg(&mut errors); SelfParam::ByVal } - None=>{ + None => { push_error_msg(&mut errors); - return errors.into_result().map(|_|unreachable!()); + return errors.into_result().map(|_| unreachable!()); } }; - let mut lifetimes:Vec<&'a syn::LifetimeDef>=decl.generics.lifetimes().collect(); + let mut lifetimes: Vec<&'a syn::LifetimeDef> = decl.generics.lifetimes().collect(); let mut return_borrow_kind = None::; - let output=match &decl.output { - syn::ReturnType::Default=>None, - syn::ReturnType::Type(_,ty)=>{ - let mut ty:syn::Type=(**ty).clone(); - if let SelfParam::ByRef{lifetime,..}=&mut self_param { + let output = match &decl.output { + syn::ReturnType::Default => None, + syn::ReturnType::Type(_, ty) => { + let mut ty: syn::Type = (**ty).clone(); + if let SelfParam::ByRef { lifetime, .. } = &mut self_param { let visit_data = LifetimeUnelider::new(lifetime).visit_type(&mut ty); return_borrow_kind = visit_data.found_borrow_kind; @@ -509,52 +510,60 @@ impl<'a> TraitMethod<'a>{ } } Some(ty) - }, + } }; - let default=mwa.item.default.as_ref().map(|block| DefaultMethod{block} ); - - let where_clause=decl.generics.where_clause.as_ref() - .and_then(|wc|{ - match MethodWhereClause::new(wc,ctokens) { - Ok(x)=>Some(x), - Err(e)=>{ errors.push_err(e); None } + let default = mwa + .item + .default + .as_ref() + .map(|block| DefaultMethod { block }); + + let where_clause = decl + .generics + .where_clause + .as_ref() + .and_then(|wc| match MethodWhereClause::new(wc, ctokens) { + Ok(x) => Some(x), + Err(e) => { + errors.push_err(e); + None } }) .unwrap_or_default(); - let mut params=Vec::>::with_capacity(input_iter.len()); + let mut params = Vec::>::with_capacity(input_iter.len()); - for (param_i,param) in input_iter.enumerate(){ - let (pattern,ty)=match param { - FnArg::Receiver{..}=>unreachable!(), - FnArg::Typed(typed)=>(&*typed.pat,&*typed.ty), + for (param_i, param) in input_iter.enumerate() { + let (pattern, ty) = match param { + FnArg::Receiver { .. } => unreachable!(), + FnArg::Typed(typed) => (&*typed.pat, &*typed.ty), }; - let name=format!("param_{}",param_i); - let mut name=syn::parse_str::(&name).unwrap_or_else(|e|{ + let name = format!("param_{}", param_i); + let mut name = syn::parse_str::(&name).unwrap_or_else(|e| { errors.push_err(e); dummy_ident() }); name.set_span(param.span()); - params.push(MethodParam{ - name:arena.alloc(name), - ty:ty.clone(), + params.push(MethodParam { + name: arena.alloc(name), + ty: ty.clone(), pattern, }); - } + } errors.into_result()?; - Ok(Some(Self{ + Ok(Some(Self { disable_inherent_default, - item:&mwa.item, - unsafety:method_signature.unsafety.as_ref(), - abi:method_signature.abi.as_ref(), + item: &mwa.item, + unsafety: method_signature.unsafety.as_ref(), + abi: method_signature.abi.as_ref(), vis, - derive_attrs:arena.alloc(mwa.attrs.derive_attrs), - other_attrs:arena.alloc(mwa.attrs.other_attrs), + derive_attrs: arena.alloc(mwa.attrs.derive_attrs), + other_attrs: arena.alloc(mwa.attrs.other_attrs), name, lifetimes, self_param, @@ -563,7 +572,7 @@ impl<'a> TraitMethod<'a>{ return_borrow_kind, where_clause, default, - semicolon:mwa.item.semi_token.as_ref(), + semicolon: mwa.item.semi_token.as_ref(), ctokens, })) } @@ -575,79 +584,74 @@ impl<'a> TraitMethod<'a>{ /// which returns `Some()` with what to do with the associated type. pub fn replace_self( &mut self, - replace_with:ReplaceWith, - mut is_assoc_type: F - )->Result<(),syn::Error> + replace_with: ReplaceWith, + mut is_assoc_type: F, + ) -> Result<(), syn::Error> where F: FnMut(&Ident) -> Option, { - let mut errors=LinearResult::ok(()); + let mut errors = LinearResult::ok(()); - for param in self.params.iter_mut() - .map(|x| &mut x.ty ) + for param in self + .params + .iter_mut() + .map(|x| &mut x.ty) .chain(self.output.as_mut()) { - replace_self_path::replace_self_path( - param, - replace_with.clone(), - &mut is_assoc_type - ).combine_into_err(&mut errors); + replace_self_path::replace_self_path(param, replace_with.clone(), &mut is_assoc_type) + .combine_into_err(&mut errors); } errors.into() } } - //////////////////////////////////////////////////////////////////////////////// - /// Used to print the generic parameters of a trait, /// potentially including its associated types. -#[derive(Debug,Copy,Clone)] -pub struct GenericsTokenizer<'a>{ - gen_params_in:GenParamsIn<'a,&'a TokenStream2>, - assoc_tys:Option<(&'a HashMap<&'a Ident,AssocTyWithIndex>,&'a TokenStream2)>, +#[derive(Debug, Copy, Clone)] +pub struct GenericsTokenizer<'a> { + gen_params_in: GenParamsIn<'a, &'a TokenStream2>, + assoc_tys: Option<(&'a HashMap<&'a Ident, AssocTyWithIndex>, &'a TokenStream2)>, } -impl<'a> GenericsTokenizer<'a>{ +impl<'a> GenericsTokenizer<'a> { /// Changes type parameters to have a `?Sized` bound. #[allow(dead_code)] - pub fn set_unsized_types(&mut self){ + pub fn set_unsized_types(&mut self) { self.gen_params_in.set_unsized_types(); } /// Removes bounds on type parameters. - pub fn set_no_bounds(&mut self){ + pub fn set_no_bounds(&mut self) { self.gen_params_in.set_no_bounds(); } - pub fn skip_lifetimes(&mut self){ + pub fn skip_lifetimes(&mut self) { self.gen_params_in.skip_lifetimes(); } #[allow(dead_code)] - pub fn skip_consts(&mut self){ + pub fn skip_consts(&mut self) { self.gen_params_in.skip_consts(); } - pub fn skip_unbounded(&mut self){ + pub fn skip_unbounded(&mut self) { self.gen_params_in.skip_unbounded(); } - } - impl<'a> ToTokens for GenericsTokenizer<'a> { fn to_tokens(&self, ts: &mut TokenStream2) { let with_bounds = self.gen_params_in.outputs_bounds(); let with_default = self.gen_params_in.in_what == InWhat::ItemDecl; - let unsized_types=self.gen_params_in.are_types_unsized(); + let unsized_types = self.gen_params_in.are_types_unsized(); - let in_dummy_struct= self.gen_params_in.in_what == InWhat::DummyStruct; + let in_dummy_struct = self.gen_params_in.in_what == InWhat::DummyStruct; - let skips_unbounded=self.gen_params_in.skips_unbounded(); + let skips_unbounded = self.gen_params_in.skips_unbounded(); self.gen_params_in.to_tokens(ts); - if let Some((assoc_tys,self_tokens))=self.assoc_tys { + if let Some((assoc_tys, self_tokens)) = self.assoc_tys { for with_index in assoc_tys.values() { - let assoc_ty=&with_index.assoc_ty; + let assoc_ty = &with_index.assoc_ty; if skips_unbounded && assoc_ty.bounds.is_empty() { continue; @@ -656,14 +660,14 @@ impl<'a> ToTokens for GenericsTokenizer<'a> { self_tokens.to_tokens(ts); if in_dummy_struct { - use syn::token::{Star,Const}; + use syn::token::{Const, Star}; Star::default().to_tokens(ts); Const::default().to_tokens(ts); } assoc_ty.ident.to_tokens(ts); - let colon_token=assoc_ty.colon_token.filter(|_| with_bounds ); + let colon_token = assoc_ty.colon_token.filter(|_| with_bounds); if unsized_types { if colon_token.is_none() { @@ -671,17 +675,17 @@ impl<'a> ToTokens for GenericsTokenizer<'a> { } quote!(?Sized+).to_tokens(ts); } - if let Some(colon_token)=colon_token { + if let Some(colon_token) = colon_token { colon_token.to_tokens(ts); assoc_ty.bounds.to_tokens(ts); } match &assoc_ty.default { - Some((eq_token,default_ty))if with_default=>{ + Some((eq_token, default_ty)) if with_default => { eq_token.to_tokens(ts); default_ty.to_tokens(ts); } - _=>{} + _ => {} } Comma::default().to_tokens(ts); @@ -692,89 +696,87 @@ impl<'a> ToTokens for GenericsTokenizer<'a> { //////////////////////////////////////////////////////////////////////////////// - /// Represents a `Deserialize<'de>` supertrait bound. -#[derive(Debug,Clone)] -pub(crate) struct DeserializeBound<'a>{ - pub(crate) bound:&'a syn::TraitBound, - pub(crate) lifetime:&'a syn::Lifetime, +#[derive(Debug, Clone)] +pub(crate) struct DeserializeBound<'a> { + pub(crate) bound: &'a syn::TraitBound, + pub(crate) lifetime: &'a syn::Lifetime, } /// Used to returns the information about supertraits,to construct TraitDefinition. -struct GetSupertraits<'a>{ - impld_traits:Vec>, - unimpld_traits:Vec<&'a Ident>, - lifetime_bounds:Punctuated<&'a Lifetime,Comma>, - iterator_item:Option<&'a syn::Type>, - deserialize_bound:Option>, - trait_flags:TraitStruct, - trait_spans:TraitStruct, - errors:LinearResult<()>, +struct GetSupertraits<'a> { + impld_traits: Vec>, + unimpld_traits: Vec<&'a Ident>, + lifetime_bounds: Punctuated<&'a Lifetime, Comma>, + iterator_item: Option<&'a syn::Type>, + deserialize_bound: Option>, + trait_flags: TraitStruct, + trait_spans: TraitStruct, + errors: LinearResult<()>, } /// Contains information about a supertrait,including whether it's implemented. -#[derive(Debug,Clone)] -pub(crate) struct TraitImplness<'a>{ - pub(crate) which_trait:WhichTrait, - pub(crate) name:&'static str, - pub(crate) ident:Ident, - pub(crate) bound:syn::TraitBound, - pub(crate) is_implemented:bool, - pub(crate) _marker:PhantomData<&'a ()>, +#[derive(Debug, Clone)] +pub(crate) struct TraitImplness<'a> { + pub(crate) which_trait: WhichTrait, + pub(crate) name: &'static str, + pub(crate) ident: Ident, + pub(crate) bound: syn::TraitBound, + pub(crate) is_implemented: bool, + pub(crate) _marker: PhantomData<&'a ()>, } /// Processes the supertrait bounds of a trait definition. -fn get_supertraits<'a,I>( +fn get_supertraits<'a, I>( supertraits: I, - lifetime_params:&HashSet<&'a Lifetime>, - which_object:WhichObject, + lifetime_params: &HashSet<&'a Lifetime>, + which_object: WhichObject, arenas: &'a Arenas, - _ctokens:&'a CommonTokens, -)-> GetSupertraits<'a> + _ctokens: &'a CommonTokens, +) -> GetSupertraits<'a> where - I:IntoIterator + I: IntoIterator, { - let trait_map=TRAIT_LIST.iter() - .map(|t| (parse_str_as_ident(t.name),t.which_trait) ) - .collect::>(); + let trait_map = TRAIT_LIST + .iter() + .map(|t| (parse_str_as_ident(t.name), t.which_trait)) + .collect::>(); // A struct indexable by `WhichTrait`, // with information about all possible supertraits. - let mut trait_struct=TraitStruct::TRAITS.map(|_,t|{ - TraitImplness{ - which_trait:t.which_trait, - name:t.name, - ident:parse_str_as_ident(t.name), - bound:parse_str_as_trait_bound(t.full_path).expect("BUG"), - is_implemented:false, - _marker:PhantomData, - } + let mut trait_struct = TraitStruct::TRAITS.map(|_, t| TraitImplness { + which_trait: t.which_trait, + name: t.name, + ident: parse_str_as_ident(t.name), + bound: parse_str_as_trait_bound(t.full_path).expect("BUG"), + is_implemented: false, + _marker: PhantomData, }); - let mut lifetime_bounds=Punctuated::<&'a Lifetime,Comma>::new(); - let mut iterator_item=None; - let mut errors=LinearResult::ok(()); - let deserialize_bound=None; + let mut lifetime_bounds = Punctuated::<&'a Lifetime, Comma>::new(); + let mut iterator_item = None; + let mut errors = LinearResult::ok(()); + let deserialize_bound = None; - for supertrait_bound in supertraits{ + for supertrait_bound in supertraits { match supertrait_bound { - TypeParamBound::Trait(trait_bound)=>{ - let last_path_component=match trait_bound.path.segments.last() { - Some(x)=>x, - None=>continue, + TypeParamBound::Trait(trait_bound) => { + let last_path_component = match trait_bound.path.segments.last() { + Some(x) => x, + None => continue, }; - let trait_ident=&last_path_component.ident; + let trait_ident = &last_path_component.ident; match trait_map.get(&trait_ident) { - Some(&which_trait)=>{ - let usable_by=which_trait.usable_by(); + Some(&which_trait) => { + let usable_by = which_trait.usable_by(); match which_object { WhichObject::DynTrait if !usable_by.dyn_trait() => { errors.push_err(spanned_err!( trait_bound.path, "Cannot use this trait with DynTrait", )); - }, + } WhichObject::RObject if !usable_by.robject() => { errors.push_err(spanned_err!( trait_bound.path, @@ -785,33 +787,28 @@ where from using RObject to using DynTrait.\n\ ", )); - }, - WhichObject::DynTrait|WhichObject::RObject => {} + } + WhichObject::DynTrait | WhichObject::RObject => {} } - fn set_impld( - wtrait:&mut TraitImplness<'_>, - span:Span, - ){ - wtrait.is_implemented=true; + fn set_impld(wtrait: &mut TraitImplness<'_>, span: Span) { + wtrait.is_implemented = true; wtrait.ident.set_span(span); - SetSpanVisitor::new(span) - .visit_trait_bound_mut(&mut wtrait.bound); + SetSpanVisitor::new(span).visit_trait_bound_mut(&mut wtrait.bound); } - let span=trait_bound.span(); - - set_impld(&mut trait_struct[which_trait],span); + let span = trait_bound.span(); + set_impld(&mut trait_struct[which_trait], span); match which_trait { - WhichTrait::Iterator|WhichTrait::DoubleEndedIterator=>{ - set_impld(&mut trait_struct.iterator,span); + WhichTrait::Iterator | WhichTrait::DoubleEndedIterator => { + set_impld(&mut trait_struct.iterator, span); - let iter_item=extract_iterator_item(last_path_component,arenas); - iterator_item=iterator_item.or(iter_item); + let iter_item = extract_iterator_item(last_path_component, arenas); + iterator_item = iterator_item.or(iter_item); } - WhichTrait::Deserialize=>{ + WhichTrait::Deserialize => { // deserialize_bound=deserialize_bound.or(Some( // DeserializeBound{ // bound:trait_bound @@ -829,33 +826,34 @@ where "Deserialize is not currently supported." )); } - WhichTrait::Serialize=>{ + WhichTrait::Serialize => { errors.push_err(spanned_err!( trait_bound.path, "Serialize is not currently supported." )); } - WhichTrait::Eq|WhichTrait::PartialOrd=>{ - set_impld(&mut trait_struct.partial_eq,span); + WhichTrait::Eq | WhichTrait::PartialOrd => { + set_impld(&mut trait_struct.partial_eq, span); } - WhichTrait::Ord=>{ - set_impld(&mut trait_struct.partial_eq,span); - set_impld(&mut trait_struct.eq,span); - set_impld(&mut trait_struct.partial_ord,span); + WhichTrait::Ord => { + set_impld(&mut trait_struct.partial_eq, span); + set_impld(&mut trait_struct.eq, span); + set_impld(&mut trait_struct.partial_ord, span); } - WhichTrait::IoBufRead=>{ - set_impld(&mut trait_struct.io_read,span); + WhichTrait::IoBufRead => { + set_impld(&mut trait_struct.io_read, span); } - WhichTrait::Error=>{ - set_impld(&mut trait_struct.display,span); - set_impld(&mut trait_struct.debug,span); + WhichTrait::Error => { + set_impld(&mut trait_struct.display, span); + set_impld(&mut trait_struct.debug, span); } - _=>{} + _ => {} } - }, - None=>{ - let list=trait_map.keys() - .map(|x| x.to_string() ) + } + None => { + let list = trait_map + .keys() + .map(|x| x.to_string()) .collect::>(); errors.push_err(spanned_err!( @@ -864,13 +862,13 @@ where list.join("/"), )); break; - }, + } } } - TypeParamBound::Lifetime(lt)=>{ + TypeParamBound::Lifetime(lt) => { if lifetime_params.contains(lt) { lifetime_bounds.push(lt); - }else{ + } else { errors.push_err(spanned_err!( lt, "Lifetimes is not from the trait or `'static`.", @@ -881,48 +879,44 @@ where }; } + let iter_trait = &mut trait_struct.iterator; + let de_iter_trait = &mut trait_struct.double_ended_iterator; + if iter_trait.is_implemented || de_iter_trait.is_implemented { + let iter_item: syn::Type = iterator_item.cloned().unwrap_or_else(|| { + let span = if de_iter_trait.is_implemented { + de_iter_trait.ident.span() + } else { + iter_trait.ident.span() + }; + errors.push_err(syn_err!(span, "You must specify the Iterator item type.")); + parse_str_as_type("()").expect("BUG") + }); + let path_args = type_as_iter_path_arguments(iter_item); - let iter_trait=&mut trait_struct.iterator; - let de_iter_trait=&mut trait_struct.double_ended_iterator; - if iter_trait.is_implemented||de_iter_trait.is_implemented { - let iter_item:syn::Type=iterator_item.cloned() - .unwrap_or_else(||{ - let span=if de_iter_trait.is_implemented { - de_iter_trait.ident.span() - }else{ - iter_trait.ident.span() - }; - errors.push_err(syn_err!(span,"You must specify the Iterator item type.")); - parse_str_as_type("()").expect("BUG") - }); - let path_args=type_as_iter_path_arguments(iter_item); - - fn set_last_arguments(bounds:&mut syn::TraitBound,path_args:syn::PathArguments){ - bounds.path.segments.last_mut().expect("BUG").arguments=path_args; + fn set_last_arguments(bounds: &mut syn::TraitBound, path_args: syn::PathArguments) { + bounds.path.segments.last_mut().expect("BUG").arguments = path_args; } - if de_iter_trait.is_implemented{ - set_last_arguments(&mut de_iter_trait.bound,path_args.clone()); + if de_iter_trait.is_implemented { + set_last_arguments(&mut de_iter_trait.bound, path_args.clone()); } - set_last_arguments(&mut iter_trait.bound,path_args); + set_last_arguments(&mut iter_trait.bound, path_args); } - - let mut impld_traits=Vec::new(); - let mut unimpld_traits=Vec::new(); - let trait_flags=trait_struct.as_ref().map(|_,x| x.is_implemented ); - let trait_spans=trait_struct.as_ref().map(|_,x| x.ident.span() ); + let mut impld_traits = Vec::new(); + let mut unimpld_traits = Vec::new(); + let trait_flags = trait_struct.as_ref().map(|_, x| x.is_implemented); + let trait_spans = trait_struct.as_ref().map(|_, x| x.ident.span()); for trait_ in trait_struct.to_vec() { if trait_.is_implemented { impld_traits.push(trait_); - }else{ + } else { unimpld_traits.push(arenas.alloc(trait_.ident.clone())); } } - - GetSupertraits{ + GetSupertraits { impld_traits, unimpld_traits, lifetime_bounds, @@ -934,45 +928,42 @@ where } } - //////////////////////////////////////////////////////////////////////////////// - /// Extracts the Iterator::Item out of a path component. fn extract_iterator_item<'a>( - last_path_component:&syn::PathSegment, - arenas:&'a Arenas, -)->Option<&'a syn::Type>{ - use syn::{GenericArgument,PathArguments}; - - let angle_brackets=match &last_path_component.arguments { - PathArguments::AngleBracketed(x)=>x, - _=>return None + last_path_component: &syn::PathSegment, + arenas: &'a Arenas, +) -> Option<&'a syn::Type> { + use syn::{GenericArgument, PathArguments}; + + let angle_brackets = match &last_path_component.arguments { + PathArguments::AngleBracketed(x) => x, + _ => return None, }; for gen_arg in &angle_brackets.args { match gen_arg { - GenericArgument::Binding(bind) if bind.ident=="Item" =>{ + GenericArgument::Binding(bind) if bind.ident == "Item" => { return Some(arenas.alloc(bind.ty.clone())); } - _=>{} + _ => {} } } None } - /// Converts a type to ``. -fn type_as_iter_path_arguments(ty:syn::Type)->syn::PathArguments{ - let x=syn::Binding{ +fn type_as_iter_path_arguments(ty: syn::Type) -> syn::PathArguments { + let x = syn::Binding { ident: parse_str_as_ident("Item"), eq_token: Default::default(), ty, }; - - let x=syn::GenericArgument::Binding(x); - let x=syn::AngleBracketedGenericArguments{ + let x = syn::GenericArgument::Binding(x); + + let x = syn::AngleBracketedGenericArguments { colon2_token: None, lt_token: Default::default(), args: iter::once(x).collect(), @@ -982,18 +973,17 @@ fn type_as_iter_path_arguments(ty:syn::Type)->syn::PathArguments{ syn::PathArguments::AngleBracketed(x) } - /// Extracts the lifetime in `Deserialize<'lt>` out of a path component. #[allow(dead_code)] fn extract_deserialize_lifetime<'a>( - last_path_component:&syn::PathSegment, - arenas:&'a Arenas, -)-> Result<&'a syn::Lifetime,syn::Error> { - use syn::{GenericArgument,PathArguments}; - - let angle_brackets=match &last_path_component.arguments { - PathArguments::AngleBracketed(x)=>x, - _=>return_spanned_err!(last_path_component,"Expected a lifetime parameter inside") + last_path_component: &syn::PathSegment, + arenas: &'a Arenas, +) -> Result<&'a syn::Lifetime, syn::Error> { + use syn::{GenericArgument, PathArguments}; + + let angle_brackets = match &last_path_component.arguments { + PathArguments::AngleBracketed(x) => x, + _ => return_spanned_err!(last_path_component, "Expected a lifetime parameter inside"), }; for gen_arg in &angle_brackets.args { @@ -1001,5 +991,8 @@ fn extract_deserialize_lifetime<'a>( return Ok(arenas.alloc(lt.clone())); } } - Err(spanned_err!(last_path_component,"Expected a lifetime parameter inside")) -} \ No newline at end of file + Err(spanned_err!( + last_path_component, + "Expected a lifetime parameter inside" + )) +} diff --git a/abi_stable_derive/src/set_span_visitor.rs b/abi_stable_derive/src/set_span_visitor.rs index cd3ed8b1..6bacbdda 100644 --- a/abi_stable_derive/src/set_span_visitor.rs +++ b/abi_stable_derive/src/set_span_visitor.rs @@ -1,36 +1,28 @@ -use syn::{ - visit_mut::VisitMut, - spanned::Spanned, - Ident, -}; - +use syn::{spanned::Spanned, visit_mut::VisitMut, Ident}; use proc_macro2::Span; /// Used to set the span of all identifier of the thing it's visiting. -#[derive(Debug,Clone,Copy)] -pub struct SetSpanVisitor{ - pub span:Span, +#[derive(Debug, Clone, Copy)] +pub struct SetSpanVisitor { + pub span: Span, } -impl SetSpanVisitor{ - pub fn new(span:Span)->Self{ - Self{span} +impl SetSpanVisitor { + pub fn new(span: Span) -> Self { + Self { span } } #[allow(dead_code)] - pub fn span_of(thing:&T)->Self + pub fn span_of(thing: &T) -> Self where - T:Spanned, + T: Spanned, { - Self{ - span:thing.span() - } + Self { span: thing.span() } } } - -impl VisitMut for SetSpanVisitor{ +impl VisitMut for SetSpanVisitor { fn visit_ident_mut(&mut self, i: &mut Ident) { i.set_span(self.span); } -} \ No newline at end of file +} diff --git a/abi_stable_derive/src/stable_abi.rs b/abi_stable_derive/src/stable_abi.rs index 1caaf57f..e6b6c58c 100644 --- a/abi_stable_derive/src/stable_abi.rs +++ b/abi_stable_derive/src/stable_abi.rs @@ -1,37 +1,26 @@ - - use crate::*; use crate::{ - composite_collections::{ - SmallStartLen as StartLen, - SmallCompositeVec as CompositeVec, - }, + composite_collections::{SmallCompositeVec as CompositeVec, SmallStartLen as StartLen}, impl_interfacetype::impl_interfacetype_tokenizer, lifetimes::LifetimeIndex, - literals_constructors::{rslice_tokenizer,rstr_tokenizer}, + literals_constructors::{rslice_tokenizer, rstr_tokenizer}, }; use as_derive_utils::{ - datastructure::{DataStructure,DataVariant}, - gen_params_in::{GenParamsIn,InWhat}, + datastructure::{DataStructure, DataVariant}, + gen_params_in::{GenParamsIn, InWhat}, + return_spanned_err, return_syn_err, to_stream, to_token_fn::ToTokenFnMut, - return_syn_err, - return_spanned_err, - to_stream, }; use syn::Ident; -use proc_macro2::{TokenStream as TokenStream2,Span}; +use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::TokenStreamExt; -use core_extensions::{ - SelfOps, - IteratorExt, -}; - +use core_extensions::{IteratorExt, SelfOps}; #[doc(hidden)] pub mod reflection; @@ -56,28 +45,25 @@ mod tl_multi_tl; mod shared_vars; - #[cfg(test)] mod tests; - use self::{ attribute_parsing::{ - parse_attrs_for_stable_abi, StabilityKind, StableAbiOptions, ASTypeParamBound, - LayoutConstructor,ConstIdents, + parse_attrs_for_stable_abi, ASTypeParamBound, ConstIdents, LayoutConstructor, + StabilityKind, StableAbiOptions, }, common_tokens::CommonTokens, - nonexhaustive::{tokenize_enum_info,tokenize_nonexhaustive_items}, + nonexhaustive::{tokenize_enum_info, tokenize_nonexhaustive_items}, prefix_types::prefix_type_tokenizer, reflection::ModReflMode, + shared_vars::SharedVars, tl_field::CompTLField, - tl_function::{VisitedFieldMap,CompTLFunction}, + tl_function::{CompTLFunction, VisitedFieldMap}, tl_multi_tl::TypeLayoutRange, - shared_vars::SharedVars, }; - -pub(crate) fn derive(mut data: DeriveInput) -> Result { +pub(crate) fn derive(mut data: DeriveInput) -> Result { data.generics.make_where_clause(); // println!("\nderiving for {}",data.ident); @@ -89,119 +75,114 @@ pub(crate) fn derive(mut data: DeriveInput) -> Result { let ctokens = &ctokens; let ds = &DataStructure::new(&data); let config = &parse_attrs_for_stable_abi(ds.attrs, ds, arenas)?; - let shared_vars=&mut SharedVars::new(arenas,&config.const_idents,ctokens); - let generics=ds.generics; - let name=ds.name; + let shared_vars = &mut SharedVars::new(arenas, &config.const_idents, ctokens); + let generics = ds.generics; + let name = ds.name; - let doc_hidden_attr=config.doc_hidden_attr; + let doc_hidden_attr = config.doc_hidden_attr; // This has to come before the `VisitedFieldMap`. - let generic_params_tokens= - generic_params::GenericParams::new(ds,shared_vars,config,ctokens); + let generic_params_tokens = + generic_params::GenericParams::new(ds, shared_vars, config, ctokens); - if generics.lifetimes().count()>LifetimeIndex::MAX_LIFETIME_PARAM+1 { + if generics.lifetimes().count() > LifetimeIndex::MAX_LIFETIME_PARAM + 1 { return_syn_err!( Span::call_site(), "Cannot have more than {} lifetime parameter.", - LifetimeIndex::MAX_LIFETIME_PARAM+1 + LifetimeIndex::MAX_LIFETIME_PARAM + 1 ); } - let visited_fields=&VisitedFieldMap::new(ds,config,shared_vars,ctokens); + let visited_fields = &VisitedFieldMap::new(ds, config, shared_vars, ctokens); shared_vars.extract_errs()?; - let module=Ident::new(&format!("_sabi_{}",name),Span::call_site()); - let mono_type_layout=&Ident::new(&format!("_MONO_LAYOUT_{}",name),Span::call_site()); - + let module = Ident::new(&format!("_sabi_{}", name), Span::call_site()); + let mono_type_layout = &Ident::new(&format!("_MONO_LAYOUT_{}", name), Span::call_site()); let (_, _, where_clause) = generics.split_for_impl(); - let where_clause=(&where_clause.expect("BUG").predicates).into_iter(); - let where_clause_b=where_clause.clone(); + let where_clause = (&where_clause.expect("BUG").predicates).into_iter(); + let where_clause_b = where_clause.clone(); - let ty_generics=GenParamsIn::new(generics,InWhat::ItemUse); + let ty_generics = GenParamsIn::new(generics, InWhat::ItemUse); let impld_stable_abi_trait = match &config.kind { - StabilityKind::Value{impl_prefix_stable_abi: false} - |StabilityKind::NonExhaustive{..} - => { - Ident::new("StableAbi", Span::call_site()) - } - StabilityKind::Value{impl_prefix_stable_abi: true} - |StabilityKind::Prefix{..} - =>{ - Ident::new("PrefixStableAbi", Span::call_site()) + StabilityKind::Value { + impl_prefix_stable_abi: false, + } + | StabilityKind::NonExhaustive { .. } => Ident::new("StableAbi", Span::call_site()), + StabilityKind::Value { + impl_prefix_stable_abi: true, } + | StabilityKind::Prefix { .. } => Ident::new("PrefixStableAbi", Span::call_site()), }; // The type that implements StableAbi - let impl_ty= match &config.kind { - StabilityKind::Value{..} => - quote!(#name <#ty_generics> ), - StabilityKind::Prefix(prefix)=>{ - let n=&prefix.prefix_fields_struct; + let impl_ty = match &config.kind { + StabilityKind::Value { .. } => quote!(#name <#ty_generics> ), + StabilityKind::Prefix(prefix) => { + let n = &prefix.prefix_fields_struct; quote!(#n <#ty_generics> ) - }, - StabilityKind::NonExhaustive(nonexhaustive)=>{ - let marker=nonexhaustive.nonexhaustive_marker; + } + StabilityKind::NonExhaustive(nonexhaustive) => { + let marker = nonexhaustive.nonexhaustive_marker; quote!(#marker < #name <#ty_generics> , __Storage > ) } }; - let mut prefix_type_trait_bound=None; - let mut prefix_bounds:&[_]=&[]; + let mut prefix_type_trait_bound = None; + let mut prefix_bounds: &[_] = &[]; // The type whose size and alignment that is stored in the type layout. - let size_align_for=match &config.kind { - StabilityKind::NonExhaustive(_)=>{ + let size_align_for = match &config.kind { + StabilityKind::NonExhaustive(_) => { quote!(__Storage) - }, - StabilityKind::Prefix(prefix)=>{ - let prefix_fields_struct=prefix.prefix_fields_struct; + } + StabilityKind::Prefix(prefix) => { + let prefix_fields_struct = prefix.prefix_fields_struct; - prefix_type_trait_bound=Some(quote!( + prefix_type_trait_bound = Some(quote!( #name <#ty_generics>:__sabi_re::PrefixTypeTrait, )); - prefix_bounds=&prefix.prefix_bounds; + prefix_bounds = &prefix.prefix_bounds; quote!( #prefix_fields_struct <#ty_generics> ) } - StabilityKind::Value{..}=>quote!(Self), + StabilityKind::Value { .. } => quote!(Self), }; - - let repr=config.repr; - - let is_transparent=config.repr.is_repr_transparent(); - let is_enum=ds.data_variant==DataVariant::Enum; - let prefix=match &config.kind { - StabilityKind::Prefix(prefix)=>Some(prefix), - _=>None, + + let repr = config.repr; + + let is_transparent = config.repr.is_repr_transparent(); + let is_enum = ds.data_variant == DataVariant::Enum; + let prefix = match &config.kind { + StabilityKind::Prefix(prefix) => Some(prefix), + _ => None, }; - let nonexh_opt=match &config.kind { - StabilityKind::NonExhaustive(nonexhaustive)=>Some(nonexhaustive), - _=>None, + let nonexh_opt = match &config.kind { + StabilityKind::NonExhaustive(nonexhaustive) => Some(nonexhaustive), + _ => None, }; let tags_const; let tags_arg; // tokenizes the `Tag` data structure associated with this type. match &config.tags { - Some(tag)=>{ + Some(tag) => { tags_const = quote!( const __SABI_TAG: &'static __sabi_re::Tag = &#tag; ); - tags_arg = quote!( Some(Self::__SABI_TAG) ); + tags_arg = quote!(Some(Self::__SABI_TAG)); } - None=>{ + None => { tags_const = TokenStream2::new(); - tags_arg = quote!( None ); + tags_arg = quote!(None); } } - let extra_checks_const; let extra_checks_arg; match &config.extra_checks { - Some(extra_checks)=> { + Some(extra_checks) => { extra_checks_const = quote!( - const __SABI_EXTRA_CHECKS: + const __SABI_EXTRA_CHECKS: &'static ::std::mem::ManuallyDrop<__sabi_re::StoredExtraChecks> = &std::mem::ManuallyDrop::new( @@ -213,104 +194,93 @@ pub(crate) fn derive(mut data: DeriveInput) -> Result { ); ); - extra_checks_arg = quote!( - Some(Self::__SABI_EXTRA_CHECKS) - ); + extra_checks_arg = quote!(Some(Self::__SABI_EXTRA_CHECKS)); } - None=>{ + None => { extra_checks_const = TokenStream2::new(); - extra_checks_arg = quote!( None ); + extra_checks_arg = quote!(None); } }; - let variant_names_start_len=if is_enum { - let mut variant_names=String::new(); + let variant_names_start_len = if is_enum { + let mut variant_names = String::new(); for variant in &ds.variants { use std::fmt::Write; - let _=write!(variant_names,"{};",variant.name); + let _ = write!(variant_names, "{};", variant.name); } - shared_vars.push_str(&variant_names,None) - }else{ + shared_vars.push_str(&variant_names, None) + } else { StartLen::EMPTY }; - + // tokenizes the items for nonexhaustive enums outside of the module this generates. - let nonexhaustive_items=tokenize_nonexhaustive_items(&module,ds,config,ctokens); + let nonexhaustive_items = tokenize_nonexhaustive_items(&module, ds, config, ctokens); // tokenizes the items for nonexhaustive enums inside of the module this generates. - let nonexhaustive_tokens=tokenize_enum_info(ds,variant_names_start_len,config,ctokens)?; + let nonexhaustive_tokens = tokenize_enum_info(ds, variant_names_start_len, config, ctokens)?; + let is_nonzero = if is_transparent && !visited_fields.map.is_empty() { + let visited_field = &visited_fields.map[0]; - - let is_nonzero=if is_transparent && !visited_fields.map.is_empty() { - let visited_field=&visited_fields.map[0]; - - let is_opaque_field=visited_field.layout_ctor.is_opaque(); + let is_opaque_field = visited_field.layout_ctor.is_opaque(); if visited_field.comp_field.is_function() { - quote!( __sabi_re::True ) - }else if is_opaque_field { - quote!( __sabi_re::False ) - }else{ - let ty=visited_field.comp_field.type_(&shared_vars); + quote!(__sabi_re::True) + } else if is_opaque_field { + quote!(__sabi_re::False) + } else { + let ty = visited_field.comp_field.type_(&shared_vars); quote!( <#ty as __StableAbi>::IsNonZeroType ) } - }else{ - quote!( __sabi_re::False ) + } else { + quote!(__sabi_re::False) }; - - let ct=ctokens; + let ct = ctokens; // The tokens for the MonoTLData stored in the TypeLayout let mono_tl_data; // The tokens for the GenericTLData stored in the TypeLayout let generic_tl_data; - - match ( is_enum, prefix ) { - (false,None)=>{ - mono_tl_data={ - let fields=fields_tokenizer(ds,visited_fields,ct); + + match (is_enum, prefix) { + (false, None) => { + mono_tl_data = { + let fields = fields_tokenizer(ds, visited_fields, ct); match ds.data_variant { - DataVariant::Struct=> - quote!( __sabi_re::MonoTLData::derive_struct(#fields) ), - DataVariant::Union=> - quote!( __sabi_re::MonoTLData::derive_union(#fields) ), - DataVariant::Enum=> - unreachable!(), + DataVariant::Struct => quote!( __sabi_re::MonoTLData::derive_struct(#fields) ), + DataVariant::Union => quote!( __sabi_re::MonoTLData::derive_union(#fields) ), + DataVariant::Enum => unreachable!(), } }; - generic_tl_data={ + generic_tl_data = { match ds.data_variant { - DataVariant::Struct=> - quote!( __sabi_re::GenericTLData::Struct ), - DataVariant::Union=> - quote!( __sabi_re::GenericTLData::Union ), - DataVariant::Enum=> - unreachable!(), + DataVariant::Struct => quote!(__sabi_re::GenericTLData::Struct), + DataVariant::Union => quote!(__sabi_re::GenericTLData::Union), + DataVariant::Enum => unreachable!(), } }; - }, - (true,None)=>{ - let vn_sl=variant_names_start_len; - mono_tl_data={ - let mono_enum_tokenizer= - tokenize_mono_enum(ds,vn_sl,nonexh_opt,config,visited_fields,shared_vars); + } + (true, None) => { + let vn_sl = variant_names_start_len; + mono_tl_data = { + let mono_enum_tokenizer = + tokenize_mono_enum(ds, vn_sl, nonexh_opt, config, visited_fields, shared_vars); quote!( __sabi_re::MonoTLData::Enum(#mono_enum_tokenizer) ) }; - generic_tl_data={ - let generic_enum_tokenizer= - tokenize_generic_enum(ds,vn_sl,nonexh_opt,config,visited_fields,ct); + generic_tl_data = { + let generic_enum_tokenizer = + tokenize_generic_enum(ds, vn_sl, nonexh_opt, config, visited_fields, ct); quote!( __sabi_re::GenericTLData::Enum(#generic_enum_tokenizer) ) }; } - (false,Some(prefix))=>{ - if is_transparent{ - return_spanned_err!(name,"repr(transparent) prefix types not supported") + (false, Some(prefix)) => { + if is_transparent { + return_spanned_err!(name, "repr(transparent) prefix types not supported") } - mono_tl_data={ - let first_suffix_field=prefix.first_suffix_field.field_pos; - let fields=fields_tokenizer(ds,visited_fields,ct); - let prefix_field_conditionality_mask=prefix.prefix_field_conditionality_mask; + mono_tl_data = { + let first_suffix_field = prefix.first_suffix_field.field_pos; + let fields = fields_tokenizer(ds, visited_fields, ct); + let prefix_field_conditionality_mask = prefix.prefix_field_conditionality_mask; quote!( __sabi_re::MonoTLData::prefix_type_derive( #first_suffix_field, @@ -319,64 +289,65 @@ pub(crate) fn derive(mut data: DeriveInput) -> Result { ) ) }; - generic_tl_data={ + generic_tl_data = { quote!( __sabi_re::GenericTLData::prefix_type_derive( - <#name <#ty_generics> as + <#name <#ty_generics> as __sabi_re::PrefixTypeTrait >::PT_FIELD_ACCESSIBILITY, ) ) }; } - (true,Some(_))=>{ - return_spanned_err!(name,"enum prefix types not supported"); + (true, Some(_)) => { + return_spanned_err!(name, "enum prefix types not supported"); } }; - - let lifetimes=&generics.lifetimes().map(|x|&x.lifetime).collect::>(); - let type_params=&generics.type_params().map(|x|&x.ident).collect::>(); - let const_params=&generics.const_params().map(|x|&x.ident).collect::>(); + let lifetimes = &generics + .lifetimes() + .map(|x| &x.lifetime) + .collect::>(); + let type_params = &generics.type_params().map(|x| &x.ident).collect::>(); + let const_params = &generics + .const_params() + .map(|x| &x.ident) + .collect::>(); - // For `type StaticEquivalent= ... ;` - let lifetimes_s=lifetimes.iter().map(|_| &ctokens.static_lt ); - let type_params_s=ToTokenFnMut::new(|ts|{ - let ct=ctokens; + let lifetimes_s = lifetimes.iter().map(|_| &ctokens.static_lt); + let type_params_s = ToTokenFnMut::new(|ts| { + let ct = ctokens; - for (ty_param,bounds) in config.type_param_bounds.iter() { + for (ty_param, bounds) in config.type_param_bounds.iter() { match bounds { - ASTypeParamBound::NoBound=>{ + ASTypeParamBound::NoBound => { ct.empty_tuple.to_tokens(ts); } - ASTypeParamBound::GetStaticEquivalent - |ASTypeParamBound::StableAbi - =>{ + ASTypeParamBound::GetStaticEquivalent | ASTypeParamBound::StableAbi => { to_stream!(ts; ct.static_equivalent, ct.lt, ty_param, ct.gt); } } ct.comma.to_tokens(ts); } }); - let const_params_s=&const_params; + let const_params_s = &const_params; // The name of the struct this generates, // to use as the `GetStaticEquivalent_::StaticEquivalent` associated type. - let static_struct_name=Ident::new(&format!("_static_{}",name),Span::call_site()); - - let item_info_const=Ident::new(&format!("_item_info_const_{}",name),Span::call_site()); + let static_struct_name = Ident::new(&format!("_static_{}", name), Span::call_site()); + + let item_info_const = Ident::new(&format!("_item_info_const_{}", name), Span::call_site()); - let static_struct_decl={ - let const_param_name=generics.const_params().map(|c| &c.ident ); - let const_param_type=generics.const_params().map(|c| &c.ty ); + let static_struct_decl = { + let const_param_name = generics.const_params().map(|c| &c.ident); + let const_param_type = generics.const_params().map(|c| &c.ty); - let lifetimes_a =lifetimes ; - - let type_params_a=type_params; - + let lifetimes_a = lifetimes; - quote!{ + let type_params_a = type_params; + + quote! { #doc_hidden_attr pub struct #static_struct_name< #(#lifetimes_a,)* @@ -391,42 +362,37 @@ pub(crate) fn derive(mut data: DeriveInput) -> Result { // if the `#[sabi(impl_InterfaceType())]` attribute was used: // tokenizes the implementation of `InterfaceType` for `#name #ty_params` - let interfacetype_tokenizer= - impl_interfacetype_tokenizer( - ds.name, - ds.generics, - config.impl_interfacetype.as_ref(), - ); - + let interfacetype_tokenizer = + impl_interfacetype_tokenizer(ds.name, ds.generics, config.impl_interfacetype.as_ref()); - let stringified_name=rstr_tokenizer(name.to_string()); + let stringified_name = rstr_tokenizer(name.to_string()); - let mut stable_abi_bounded=Vec::new(); - let mut static_equiv_bounded=Vec::new(); + let mut stable_abi_bounded = Vec::new(); + let mut static_equiv_bounded = Vec::new(); - for (ident,bounds) in config.type_param_bounds.iter() { - let list=match bounds { - ASTypeParamBound::NoBound=>None, - ASTypeParamBound::GetStaticEquivalent=>Some(&mut static_equiv_bounded), - ASTypeParamBound::StableAbi=>Some(&mut stable_abi_bounded), + for (ident, bounds) in config.type_param_bounds.iter() { + let list = match bounds { + ASTypeParamBound::NoBound => None, + ASTypeParamBound::GetStaticEquivalent => Some(&mut static_equiv_bounded), + ASTypeParamBound::StableAbi => Some(&mut stable_abi_bounded), }; - if let Some(list)=list { + if let Some(list) = list { list.push(ident); } } - let stable_abi_bounded=&stable_abi_bounded; - let static_equiv_bounded=&static_equiv_bounded; + let stable_abi_bounded = &stable_abi_bounded; + let static_equiv_bounded = &static_equiv_bounded; - let extra_bounds =&config.extra_bounds; - - let prefix_type_tokenizer_= - prefix_type_tokenizer(&module,&mono_type_layout,&ds,config,ctokens)?; + let extra_bounds = &config.extra_bounds; - let mod_refl_mode=match config.mod_refl_mode { - ModReflMode::Module=>quote!( __ModReflMode::Module ), - ModReflMode::Opaque=>quote!( __ModReflMode::Opaque ), - ModReflMode::DelegateDeref(field_index)=>{ + let prefix_type_tokenizer_ = + prefix_type_tokenizer(&module, &mono_type_layout, &ds, config, ctokens)?; + + let mod_refl_mode = match config.mod_refl_mode { + ModReflMode::Module => quote!(__ModReflMode::Module), + ModReflMode::Opaque => quote!(__ModReflMode::Opaque), + ModReflMode::DelegateDeref(field_index) => { quote!( __ModReflMode::DelegateDeref{ phantom_field_index:#field_index @@ -435,35 +401,37 @@ pub(crate) fn derive(mut data: DeriveInput) -> Result { } }; - let phantom_field_tys =config.phantom_fields.iter().map(|x| x.1 ); + let phantom_field_tys = config.phantom_fields.iter().map(|x| x.1); // This has to be collected into a Vec ahead of time, // so that the names and types are stored in SharedVars. - let phantom_fields=config.phantom_fields.iter() - .map(|(name,ty)|{ + let phantom_fields = config + .phantom_fields + .iter() + .map(|(name, ty)| { CompTLField::from_expanded_std_field( name, std::iter::empty(), - shared_vars.push_type(LayoutConstructor::Regular,*ty), + shared_vars.push_type(LayoutConstructor::Regular, *ty), shared_vars, ) }) - .collect::>(); - let phantom_fields=rslice_tokenizer(&phantom_fields); + .collect::>(); + let phantom_fields = rslice_tokenizer(&phantom_fields); // The storage type parameter that is added if this is a nonexhaustive enum. - let storage_opt=nonexh_opt.map(|_| &ctokens.und_storage ); - let generics_header= - GenParamsIn::with_after_types(&ds.generics,InWhat::ImplHeader,storage_opt); + let storage_opt = nonexh_opt.map(|_| &ctokens.und_storage); + let generics_header = + GenParamsIn::with_after_types(&ds.generics, InWhat::ImplHeader, storage_opt); shared_vars.extract_errs()?; - let mono_shared_vars_tokenizer=shared_vars.mono_shared_vars_tokenizer(); + let mono_shared_vars_tokenizer = shared_vars.mono_shared_vars_tokenizer(); - let strings_const=&config.const_idents.strings; - let strings=shared_vars.strings().piped(rstr_tokenizer); + let strings_const = &config.const_idents.strings; + let strings = shared_vars.strings().piped(rstr_tokenizer); - let shared_vars_tokenizer=shared_vars.shared_vars_tokenizer(&mono_type_layout); + let shared_vars_tokenizer = shared_vars.shared_vars_tokenizer(&mono_type_layout); // drop(_measure_time0); // let _measure_time1=PrintDurationOnDrop::new(abi_stable_shared::file_span!()); @@ -477,7 +445,7 @@ pub(crate) fn derive(mut data: DeriveInput) -> Result { #prefix_type_trait_bound ); - let stable_abi_where_preds = shared_where_preds.clone().mutated(|ts|{ + let stable_abi_where_preds = shared_where_preds.clone().mutated(|ts| { ts.append_all(quote!( #(#phantom_field_tys:__StableAbi,)* )) @@ -487,7 +455,7 @@ pub(crate) fn derive(mut data: DeriveInput) -> Result { let prefix_ref = &prefix.prefix_ref; let prefix_fields_struct = &prefix.prefix_fields_struct; let lifetimes_s = lifetimes_s.clone(); - + quote!( unsafe impl<#generics_header> __sabi_re::GetStaticEquivalent_ for #prefix_ref <#ty_generics> @@ -496,27 +464,27 @@ pub(crate) fn derive(mut data: DeriveInput) -> Result { { type StaticEquivalent = __sabi_re::PrefixRef< - #static_struct_name < + #static_struct_name < #(#lifetimes_s,)* #type_params_s - #({#const_params_s}),* + #({#const_params_s}),* > >; } unsafe impl<#generics_header> __sabi_re::StableAbi for #prefix_ref <#ty_generics> - where + where #stable_abi_where_preds { type IsNonZeroType = __sabi_re::True; - const LAYOUT: &'static __sabi_re::TypeLayout = + const LAYOUT: &'static __sabi_re::TypeLayout = <__sabi_re::PrefixRef<#prefix_fields_struct <#ty_generics>> as __sabi_re::StableAbi >::LAYOUT; } ) - }else{ + } else { TokenStream2::new() }; @@ -549,14 +517,14 @@ pub(crate) fn derive(mut data: DeriveInput) -> Result { #prefix_ref_impls - unsafe impl <#generics_header> __GetStaticEquivalent_ for #impl_ty - where + unsafe impl <#generics_header> __GetStaticEquivalent_ for #impl_ty + where #shared_where_preds { - type StaticEquivalent=#static_struct_name < + type StaticEquivalent=#static_struct_name < #(#lifetimes_s,)* #type_params_s - #({#const_params_s}),* + #({#const_params_s}),* >; } @@ -575,8 +543,8 @@ pub(crate) fn derive(mut data: DeriveInput) -> Result { } ); - impl <#generics_header> #impl_ty - where + impl <#generics_header> #impl_ty + where #stable_abi_where_preds { #shared_vars_tokenizer @@ -586,10 +554,10 @@ pub(crate) fn derive(mut data: DeriveInput) -> Result { #tags_const } - unsafe impl <#generics_header> __sabi_re::#impld_stable_abi_trait for #impl_ty - where + unsafe impl <#generics_header> __sabi_re::#impld_stable_abi_trait for #impl_ty + where #stable_abi_where_preds - + { type IsNonZeroType=#is_nonzero; @@ -608,10 +576,11 @@ pub(crate) fn derive(mut data: DeriveInput) -> Result { } } - ).observe(|tokens|{ + ) + .observe(|tokens| { // drop(_measure_time1); if config.debug_print { - panic!("\n\n\n{}\n\n\n",tokens ); + panic!("\n\n\n{}\n\n\n", tokens); } }) .piped(Ok) @@ -619,25 +588,28 @@ pub(crate) fn derive(mut data: DeriveInput) -> Result { // Tokenizes a `MonoTLEnum{ .. }` fn tokenize_mono_enum<'a>( - ds:&'a DataStructure<'a>, - variant_names_start_len:StartLen, - _nonexhaustive_opt:Option<&'a nonexhaustive::NonExhaustive<'a>>, - _config:&'a StableAbiOptions<'a>, - visited_fields:&'a VisitedFieldMap<'a>, - shared_vars:&mut SharedVars<'a>, -)->impl ToTokens+'a{ - let ct=shared_vars.ctokens(); - - ToTokenFnMut::new(move|ts|{ - let variant_names_start_len=variant_names_start_len.tokenizer(ct.as_ref()); - - let variant_lengths=ds.variants.iter() - .map(|x|{ - assert!(x.fields.len() < 256,"variant '{}' has more than 255 fields.",x.name); - x.fields.len() as u8 - }); - - let fields=fields_tokenizer(ds,visited_fields,ct); + ds: &'a DataStructure<'a>, + variant_names_start_len: StartLen, + _nonexhaustive_opt: Option<&'a nonexhaustive::NonExhaustive<'a>>, + _config: &'a StableAbiOptions<'a>, + visited_fields: &'a VisitedFieldMap<'a>, + shared_vars: &mut SharedVars<'a>, +) -> impl ToTokens + 'a { + let ct = shared_vars.ctokens(); + + ToTokenFnMut::new(move |ts| { + let variant_names_start_len = variant_names_start_len.tokenizer(ct.as_ref()); + + let variant_lengths = ds.variants.iter().map(|x| { + assert!( + x.fields.len() < 256, + "variant '{}' has more than 255 fields.", + x.name + ); + x.fields.len() as u8 + }); + + let fields = fields_tokenizer(ds, visited_fields, ct); quote!( __sabi_re::MonoTLEnum::new( @@ -645,102 +617,104 @@ fn tokenize_mono_enum<'a>( abi_stable::rslice![#( #variant_lengths ),*], #fields, ) - ).to_tokens(ts); + ) + .to_tokens(ts); }) } // Tokenizes a `GenericTLEnum{ .. }` fn tokenize_generic_enum<'a>( - ds:&'a DataStructure<'a>, - _variant_names_start_len:StartLen, - nonexhaustive_opt:Option<&'a nonexhaustive::NonExhaustive<'a>>, - config:&'a StableAbiOptions<'a>, - _visited_fields:&'a VisitedFieldMap<'a>, - ct:&'a CommonTokens<'a>, -)->impl ToTokens+'a{ - ToTokenFnMut::new(move|ts|{ - let is_exhaustive=match nonexhaustive_opt { - Some(_)=>{ - let name=ds.name; - - let ty_generics=GenParamsIn::new(ds.generics,InWhat::ItemUse); + ds: &'a DataStructure<'a>, + _variant_names_start_len: StartLen, + nonexhaustive_opt: Option<&'a nonexhaustive::NonExhaustive<'a>>, + config: &'a StableAbiOptions<'a>, + _visited_fields: &'a VisitedFieldMap<'a>, + ct: &'a CommonTokens<'a>, +) -> impl ToTokens + 'a { + ToTokenFnMut::new(move |ts| { + let is_exhaustive = match nonexhaustive_opt { + Some(_) => { + let name = ds.name; + + let ty_generics = GenParamsIn::new(ds.generics, InWhat::ItemUse); // let (_, ty_generics,_) = ds.generics.split_for_impl(); quote!(nonexhaustive( &__sabi_re::MakeTLNonExhaustive::< #name <#ty_generics> >::NEW )) - }, - None=>quote!(exhaustive()), + } + None => quote!(exhaustive()), }; - let discriminants=ds.variants.iter().map(|x|x.discriminant); - let discriminants=config.repr.tokenize_discriminant_exprs(discriminants,ct); + let discriminants = ds.variants.iter().map(|x| x.discriminant); + let discriminants = config.repr.tokenize_discriminant_exprs(discriminants, ct); quote!( __sabi_re::GenericTLEnum::new( __IsExhaustive::#is_exhaustive, #discriminants, ) - ).to_tokens(ts); + ) + .to_tokens(ts); }) } /// Tokenizes a TLFields, fn fields_tokenizer<'a>( - ds:&'a DataStructure<'a>, - visited_fields:&'a VisitedFieldMap<'a>, - ctokens:&'a CommonTokens<'a>, -)->impl ToTokens+'a{ - ToTokenFnMut::new(move|ts|{ + ds: &'a DataStructure<'a>, + visited_fields: &'a VisitedFieldMap<'a>, + ctokens: &'a CommonTokens<'a>, +) -> impl ToTokens + 'a { + ToTokenFnMut::new(move |ts| { to_stream!(ts;ctokens.comp_tl_fields,ctokens.colon2,ctokens.new); - ctokens.paren.surround(ts,|ts|{ - fields_tokenizer_inner(ds,visited_fields,ctokens,ts); + ctokens.paren.surround(ts, |ts| { + fields_tokenizer_inner(ds, visited_fields, ctokens, ts); }); }) } fn fields_tokenizer_inner<'a>( - ds:&'a DataStructure<'a>, - visited_fields:&'a VisitedFieldMap<'a>, - ct:&'a CommonTokens<'a>, - ts:&mut TokenStream2, -){ - let iter=visited_fields.map.iter().map(|field| field.comp_field ); + ds: &'a DataStructure<'a>, + visited_fields: &'a VisitedFieldMap<'a>, + ct: &'a CommonTokens<'a>, + ts: &mut TokenStream2, +) { + let iter = visited_fields.map.iter().map(|field| field.comp_field); rslice_tokenizer(iter).to_tokens(ts); ct.comma.to_tokens(ts); - if visited_fields.fn_ptr_count==0 { + if visited_fields.fn_ptr_count == 0 { ct.none.to_tokens(ts); - }else{ + } else { to_stream!(ts;ct.some); - ct.paren.surround(ts,|ts|{ + ct.paren.surround(ts, |ts| { ct.and_.to_tokens(ts); - tokenize_tl_functions(ds,&visited_fields,ct,ts); + tokenize_tl_functions(ds, &visited_fields, ct, ts); }); } - to_stream!{ts; ct.comma }; - + to_stream! {ts; ct.comma }; } /// Tokenizes a TLFunctions fn tokenize_tl_functions<'a>( - ds:&'a DataStructure<'a>, - visited_fields:&'a VisitedFieldMap<'a>, - _ct:&'a CommonTokens<'a>, - ts:&mut TokenStream2, -){ - let mut functions= + ds: &'a DataStructure<'a>, + visited_fields: &'a VisitedFieldMap<'a>, + _ct: &'a CommonTokens<'a>, + ts: &mut TokenStream2, +) { + let mut functions = CompositeVec::<&'a CompTLFunction>::with_capacity(visited_fields.fn_ptr_count); - let mut field_fn_ranges=Vec::::with_capacity(ds.field_count); + let mut field_fn_ranges = Vec::::with_capacity(ds.field_count); - visited_fields.map + visited_fields + .map .iter() - .map(|field| functions.extend(&field.functions) ) + .map(|field| functions.extend(&field.functions)) .extending(&mut field_fn_ranges); - let functions=functions.into_inner(); + let functions = functions.into_inner(); - let field_fn_ranges=field_fn_ranges.into_iter().map(|sl| sl.to_u32() ); + let field_fn_ranges = field_fn_ranges.into_iter().map(|sl| sl.to_u32()); quote!({ const TLF_A: &[__CompTLFunction] = &[#(#functions),*]; @@ -749,9 +723,6 @@ fn tokenize_tl_functions<'a>( abi_stable::rslice![#(#field_fn_ranges),*], ); TLF_B - }).to_tokens(ts); - + }) + .to_tokens(ts); } - - - diff --git a/abi_stable_derive/src/stable_abi/attribute_parsing.rs b/abi_stable_derive/src/stable_abi/attribute_parsing.rs index df7a943e..d2e607e1 100644 --- a/abi_stable_derive/src/stable_abi/attribute_parsing.rs +++ b/abi_stable_derive/src/stable_abi/attribute_parsing.rs @@ -1,24 +1,16 @@ use as_derive_utils::{ datastructure::{DataStructure, DataVariant, Field, FieldMap, TypeParamMap}, - return_spanned_err, - spanned_err, - syn_err, + return_spanned_err, spanned_err, syn_err, }; use syn::{ - Attribute, Ident, Meta, MetaList, MetaNameValue, NestedMeta, - Lit,WherePredicate,Type, - punctuated::Punctuated, - token::Comma, - TypeParamBound, + punctuated::Punctuated, token::Comma, Attribute, Ident, Lit, Meta, MetaList, MetaNameValue, + NestedMeta, Type, TypeParamBound, WherePredicate, }; -use std::{ - collections::HashSet, - mem, -}; +use std::{collections::HashSet, mem}; -use core_extensions::{matches,IteratorExt}; +use core_extensions::{matches, IteratorExt}; use proc_macro2::Span; @@ -27,293 +19,274 @@ use quote::ToTokens; use crate::*; use crate::{ - attribute_parsing::{with_nested_meta}, - impl_interfacetype::{ImplInterfaceType,parse_impl_interfacetype}, + attribute_parsing::with_nested_meta, + impl_interfacetype::{parse_impl_interfacetype, ImplInterfaceType}, parse_utils::{ - parse_str_as_ident, - parse_str_as_type, - parse_lit_as_expr, - parse_lit_as_type, - parse_lit_as_type_bounds, - ParsePunctuated, + parse_lit_as_expr, parse_lit_as_type, parse_lit_as_type_bounds, parse_str_as_ident, + parse_str_as_type, ParsePunctuated, }, - utils::{LinearResult,SynPathExt,SynResultExt}, + utils::{LinearResult, SynPathExt, SynResultExt}, }; use super::{ nonexhaustive::{ - UncheckedNonExhaustive,NonExhaustive,EnumInterface,IntOrType, - UncheckedVariantConstructor, UncheckedNEVariant, + EnumInterface, IntOrType, NonExhaustive, UncheckedNEVariant, UncheckedNonExhaustive, + UncheckedVariantConstructor, }, - reflection::{ModReflMode,FieldAccessor}, prefix_types::{ - PrefixKind, PrefixKindCtor, FirstSuffixField, OnMissingField, AccessorOrMaybe, + AccessorOrMaybe, FirstSuffixField, OnMissingField, PrefixKind, PrefixKindCtor, PrefixKindField, }, + reflection::{FieldAccessor, ModReflMode}, repr_attrs::{ - DiscriminantRepr,ReprAttr,Repr,REPR_ERROR_MSG, - UncheckedReprAttr,UncheckedReprKind, + DiscriminantRepr, Repr, ReprAttr, UncheckedReprAttr, UncheckedReprKind, REPR_ERROR_MSG, }, }; - pub(crate) struct StableAbiOptions<'a> { - pub(crate) debug_print:bool, + pub(crate) debug_print: bool, pub(crate) kind: StabilityKind<'a>, pub(crate) repr: ReprAttr, - pub(crate) type_param_bounds:TypeParamMap<'a,ASTypeParamBound>, + pub(crate) type_param_bounds: TypeParamMap<'a, ASTypeParamBound>, - pub(crate) extra_bounds:Vec, + pub(crate) extra_bounds: Vec, - pub(crate) tags:Option, - pub(crate) extra_checks:Option, + pub(crate) tags: Option, + pub(crate) extra_checks: Option, - pub(crate) layout_ctor:FieldMap, + pub(crate) layout_ctor: FieldMap, - pub(crate) override_field_accessor:FieldMap>>, - - pub(crate) renamed_fields:FieldMap>, - pub(crate) changed_types:FieldMap>, + pub(crate) override_field_accessor: FieldMap>>, - pub(crate) doc_hidden_attr:Option<&'a TokenStream2>, + pub(crate) renamed_fields: FieldMap>, + pub(crate) changed_types: FieldMap>, - pub(crate) mod_refl_mode:ModReflMode, + pub(crate) doc_hidden_attr: Option<&'a TokenStream2>, - pub(crate) impl_interfacetype:Option, + pub(crate) mod_refl_mode: ModReflMode, - pub(crate) phantom_fields:Vec<(&'a Ident,&'a Type)>, - pub(crate) phantom_type_params:Vec<&'a Type>, - pub(crate) phantom_const_params:Vec<&'a syn::Expr>, + pub(crate) impl_interfacetype: Option, - pub(crate) const_idents:ConstIdents, + pub(crate) phantom_fields: Vec<(&'a Ident, &'a Type)>, + pub(crate) phantom_type_params: Vec<&'a Type>, + pub(crate) phantom_const_params: Vec<&'a syn::Expr>, - pub(crate) allow_type_macros:bool, - pub(crate) with_field_indices:bool, - -} + pub(crate) const_idents: ConstIdents, + pub(crate) allow_type_macros: bool, + pub(crate) with_field_indices: bool, +} ////////////////////// /// Identifiers of generated top-level constants. -pub struct ConstIdents{ +pub struct ConstIdents { /// The identifier of a constant where the string in MonoSharedVars will be stored. - pub(crate) strings:Ident, + pub(crate) strings: Ident, } - ////////////////////// -#[derive(Debug,Clone,Copy,Eq,PartialEq,Hash)] -pub(crate) enum ASTypeParamBound{ +#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] +pub(crate) enum ASTypeParamBound { NoBound, GetStaticEquivalent, StableAbi, } -impl Default for ASTypeParamBound{ - fn default()->Self{ +impl Default for ASTypeParamBound { + fn default() -> Self { ASTypeParamBound::StableAbi } } - ////////////////////// - -#[derive(Debug,Clone,Copy,Eq,PartialEq,Hash)] -pub(crate) enum LayoutConstructor{ +#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] +pub(crate) enum LayoutConstructor { Regular, Opaque, SabiOpaque, } -impl LayoutConstructor{ - pub(crate) fn is_opaque(self)->bool{ - matches!(self, LayoutConstructor::Opaque{..}) +impl LayoutConstructor { + pub(crate) fn is_opaque(self) -> bool { + matches!(self, LayoutConstructor::Opaque { .. }) } } -impl From for LayoutConstructor{ - fn from(bound:ASTypeParamBound)->Self{ +impl From for LayoutConstructor { + fn from(bound: ASTypeParamBound) -> Self { match bound { - ASTypeParamBound::NoBound=> - LayoutConstructor::Opaque, - ASTypeParamBound::GetStaticEquivalent=> - LayoutConstructor::Opaque, - ASTypeParamBound::StableAbi=> - LayoutConstructor::Regular, + ASTypeParamBound::NoBound => LayoutConstructor::Opaque, + ASTypeParamBound::GetStaticEquivalent => LayoutConstructor::Opaque, + ASTypeParamBound::StableAbi => LayoutConstructor::Regular, } } } -impl Default for LayoutConstructor{ - fn default()->Self{ +impl Default for LayoutConstructor { + fn default() -> Self { LayoutConstructor::Regular } } - ////////////////////// - pub(crate) enum StabilityKind<'a> { - Value{ - impl_prefix_stable_abi: bool - }, + Value { impl_prefix_stable_abi: bool }, Prefix(PrefixKind<'a>), NonExhaustive(NonExhaustive<'a>), } -impl<'a> StabilityKind<'a>{ +impl<'a> StabilityKind<'a> { pub(crate) fn field_accessor( &self, - mod_refl_mode:ModReflMode, - field:&Field<'a>, - )->FieldAccessor<'a>{ - let is_public=field.is_public() && mod_refl_mode!=ModReflMode::Opaque; - match (is_public,self) { - (false,_)=> - FieldAccessor::Opaque, - (true,StabilityKind::Value{..})|(true,StabilityKind::NonExhaustive{..})=> - FieldAccessor::Direct, - (true,StabilityKind::Prefix(prefix))=> - prefix.field_accessor(field), + mod_refl_mode: ModReflMode, + field: &Field<'a>, + ) -> FieldAccessor<'a> { + let is_public = field.is_public() && mod_refl_mode != ModReflMode::Opaque; + match (is_public, self) { + (false, _) => FieldAccessor::Opaque, + (true, StabilityKind::Value { .. }) | (true, StabilityKind::NonExhaustive { .. }) => { + FieldAccessor::Direct + } + (true, StabilityKind::Prefix(prefix)) => prefix.field_accessor(field), } } } - impl<'a> StableAbiOptions<'a> { fn new( - ds: &'a DataStructure<'a>, + ds: &'a DataStructure<'a>, mut this: StableAbiAttrs<'a>, arenas: &'a Arenas, - ) -> Result { - let mut phantom_fields=Vec::<(&'a Ident,&'a Type)>::new(); + ) -> Result { + let mut phantom_fields = Vec::<(&'a Ident, &'a Type)>::new(); let repr = ReprAttr::new(this.repr)?; - let mut errors=LinearResult::ok(()); + let mut errors = LinearResult::ok(()); let kind = match this.kind { _ if repr.is_repr_transparent() => { // let field=&ds.variants[0].fields[0]; - + // let accessor_bound=syn::parse_str::( // &format!("({}):__StableAbi",(&field.mutated_ty).into_token_stream()) // ).expect(concat!(file!(),"-",line!())); // this.extra_bounds.push(accessor_bound); - StabilityKind::Value{impl_prefix_stable_abi: false} - } - UncheckedStabilityKind::Value{impl_prefix_stable_abi} =>{ - StabilityKind::Value{impl_prefix_stable_abi} + StabilityKind::Value { + impl_prefix_stable_abi: false, + } } - UncheckedStabilityKind::Prefix(prefix)=>{ - PrefixKindCtor::<'a>{ - arenas, - struct_name: ds.name, - first_suffix_field: this.first_suffix_field, - prefix_ref: prefix.prefix_ref, - prefix_fields: prefix.prefix_fields, - fields: mem::replace(&mut this.prefix_kind_fields,FieldMap::empty()) - .map(|fi,pk_field|{ - AccessorOrMaybe::new( - fi, - this.first_suffix_field, - pk_field, - this.default_on_missing_fields.unwrap_or_default(), - ) - }), - prefix_bounds: this.prefix_bounds, - accessor_bounds: this.accessor_bounds, - }.make() - .piped(StabilityKind::Prefix) + UncheckedStabilityKind::Value { + impl_prefix_stable_abi, + } => StabilityKind::Value { + impl_prefix_stable_abi, + }, + UncheckedStabilityKind::Prefix(prefix) => PrefixKindCtor::<'a> { + arenas, + struct_name: ds.name, + first_suffix_field: this.first_suffix_field, + prefix_ref: prefix.prefix_ref, + prefix_fields: prefix.prefix_fields, + fields: mem::replace(&mut this.prefix_kind_fields, FieldMap::empty()).map( + |fi, pk_field| { + AccessorOrMaybe::new( + fi, + this.first_suffix_field, + pk_field, + this.default_on_missing_fields.unwrap_or_default(), + ) + }, + ), + prefix_bounds: this.prefix_bounds, + accessor_bounds: this.accessor_bounds, } - UncheckedStabilityKind::NonExhaustive(nonexhaustive)=>{ + .make() + .piped(StabilityKind::Prefix), + UncheckedStabilityKind::NonExhaustive(nonexhaustive) => { let ne_variants = this.ne_variants; nonexhaustive - .piped(|x| NonExhaustive::new(x,ne_variants,ds,arenas) )? + .piped(|x| NonExhaustive::new(x, ne_variants, ds, arenas))? .piped(StabilityKind::NonExhaustive) } }; match (repr.variant, ds.data_variant) { - (Repr::Transparent,DataVariant::Struct)=>{} - (Repr::Transparent,_)=>{ + (Repr::Transparent, DataVariant::Struct) => {} + (Repr::Transparent, _) => { errors.push_err(syn_err!( *repr.span, "\nAbiStable does not suport non-struct #[repr(transparent)] types.\n" )); } - (Repr::Int{..},DataVariant::Enum)=>{} - (Repr::Int{..},_)=>{ + (Repr::Int { .. }, DataVariant::Enum) => {} + (Repr::Int { .. }, _) => { errors.push_err(syn_err!( *repr.span, "AbiStable does not suport non-enum #[repr()] types." )); } - (Repr::C{..},_)=>{} + (Repr::C { .. }, _) => {} } - let mod_refl_mode=match this.mod_refl_mode { - Some(ModReflMode::Module)=>ModReflMode::Module, - Some(ModReflMode::Opaque)=>ModReflMode::Opaque, - Some(ModReflMode::DelegateDeref(()))=>{ - let index=phantom_fields.len(); - let field_ty = syn::parse_str::( - "::PtrTarget" - ) - .expect("BUG") - .piped(|x| arenas.alloc(x) ); + let mod_refl_mode = match this.mod_refl_mode { + Some(ModReflMode::Module) => ModReflMode::Module, + Some(ModReflMode::Opaque) => ModReflMode::Opaque, + Some(ModReflMode::DelegateDeref(())) => { + let index = phantom_fields.len(); + let field_ty = + syn::parse_str::("::PtrTarget") + .expect("BUG") + .piped(|x| arenas.alloc(x)); - let dt=arenas.alloc(parse_str_as_ident("deref_target")); - phantom_fields.push((dt,field_ty)); + let dt = arenas.alloc(parse_str_as_ident("deref_target")); + phantom_fields.push((dt, field_ty)); [ "Self: __sabi_re::GetPointerKind", "::Target: __StableAbi", - ].iter() - .map(|x| syn::parse_str::(x).expect("BUG") ) - .extending(&mut this.extra_bounds); + ] + .iter() + .map(|x| syn::parse_str::(x).expect("BUG")) + .extending(&mut this.extra_bounds); - ModReflMode::DelegateDeref(index) + ModReflMode::DelegateDeref(index) } - None if ds.has_public_fields() => - ModReflMode::Module, - None=> - ModReflMode::Opaque, + None if ds.has_public_fields() => ModReflMode::Module, + None => ModReflMode::Opaque, }; phantom_fields.extend(this.extra_phantom_fields); - phantom_fields.extend( - this.phantom_type_params.iter().cloned() - .enumerate() - .map(|(i,ty)|{ - let x=format!("_phantom_ty_param_{}",i); - let name=arenas.alloc(parse_str_as_ident(&x)); - (name,ty) - }) - ); - - let doc_hidden_attr=if this.is_hidden { + phantom_fields.extend(this.phantom_type_params.iter().cloned().enumerate().map( + |(i, ty)| { + let x = format!("_phantom_ty_param_{}", i); + let name = arenas.alloc(parse_str_as_ident(&x)); + (name, ty) + }, + )); + + let doc_hidden_attr = if this.is_hidden { Some(arenas.alloc(quote!(#[doc(hidden)]))) - }else{ + } else { None }; - let const_idents=ConstIdents{ - strings: parse_str_as_ident(&format!("_SHARED_VARS_STRINGS_{}",ds.name)), + let const_idents = ConstIdents { + strings: parse_str_as_ident(&format!("_SHARED_VARS_STRINGS_{}", ds.name)), }; errors.into_result()?; Ok(StableAbiOptions { debug_print: this.debug_print, - kind, repr , - extra_bounds : this.extra_bounds, + kind, + repr, + extra_bounds: this.extra_bounds, type_param_bounds: this.type_param_bounds, layout_ctor: this.layout_ctor, renamed_fields: this.renamed_fields, @@ -339,123 +312,129 @@ impl<'a> StableAbiOptions<'a> { #[derive(Default)] struct StableAbiAttrs<'a> { - debug_print:bool, + debug_print: bool, kind: UncheckedStabilityKind<'a>, repr: UncheckedReprAttr, - extra_bounds:Vec, + extra_bounds: Vec, - tags:Option, - extra_checks:Option, + tags: Option, + extra_checks: Option, + first_suffix_field: FirstSuffixField, + default_on_missing_fields: Option>, + prefix_kind_fields: FieldMap>, - first_suffix_field:FirstSuffixField, - default_on_missing_fields:Option>, - prefix_kind_fields:FieldMap>, + prefix_bounds: Vec, - prefix_bounds:Vec, + type_param_bounds: TypeParamMap<'a, ASTypeParamBound>, - type_param_bounds:TypeParamMap<'a,ASTypeParamBound>, + layout_ctor: FieldMap, - layout_ctor:FieldMap, + ne_variants: Vec, - ne_variants:Vec, + override_field_accessor: FieldMap>>, - override_field_accessor:FieldMap>>, - - renamed_fields:FieldMap>, - changed_types:FieldMap>, + renamed_fields: FieldMap>, + changed_types: FieldMap>, - accessor_bounds:FieldMap>, + accessor_bounds: FieldMap>, - extra_phantom_fields:Vec<(&'a Ident,&'a Type)>, - phantom_type_params:Vec<&'a Type>, - phantom_const_params:Vec<&'a syn::Expr>, + extra_phantom_fields: Vec<(&'a Ident, &'a Type)>, + phantom_type_params: Vec<&'a Type>, + phantom_const_params: Vec<&'a syn::Expr>, - impl_interfacetype:Option, - - mod_refl_mode:Option>, + impl_interfacetype: Option, - allow_type_macros:bool, - with_field_indices:bool, - is_hidden:bool, + mod_refl_mode: Option>, - errors:LinearResult<()>, -} + allow_type_macros: bool, + with_field_indices: bool, + is_hidden: bool, + errors: LinearResult<()>, +} #[derive(Clone)] enum UncheckedStabilityKind<'a> { - Value{ - impl_prefix_stable_abi: bool - }, + Value { impl_prefix_stable_abi: bool }, Prefix(UncheckedPrefixKind<'a>), NonExhaustive(UncheckedNonExhaustive<'a>), } #[derive(Copy, Clone)] -struct UncheckedPrefixKind<'a>{ +struct UncheckedPrefixKind<'a> { prefix_ref: Option<&'a Ident>, prefix_fields: Option<&'a Ident>, } -impl<'a> Default for UncheckedStabilityKind<'a>{ - fn default()->Self{ - UncheckedStabilityKind::Value{impl_prefix_stable_abi: false} +impl<'a> Default for UncheckedStabilityKind<'a> { + fn default() -> Self { + UncheckedStabilityKind::Value { + impl_prefix_stable_abi: false, + } } } - - -#[derive(Debug,Copy, Clone)] +#[derive(Debug, Copy, Clone)] enum ParseContext<'a> { - TypeAttr{ - name:&'a Ident, + TypeAttr { + name: &'a Ident, }, - Variant{ - variant_index:usize, + Variant { + variant_index: usize, }, - Field{ - field_index:usize, - field:&'a Field<'a>, + Field { + field_index: usize, + field: &'a Field<'a>, }, } /// Parses the attributes for the `StableAbi` derive macro. -pub(crate) fn parse_attrs_for_stable_abi<'a,I>( +pub(crate) fn parse_attrs_for_stable_abi<'a, I>( attrs: I, ds: &'a DataStructure<'a>, arenas: &'a Arenas, -) -> Result,syn::Error> +) -> Result, syn::Error> where - I:IntoIterator + I: IntoIterator, { let mut this = StableAbiAttrs::default(); - this.layout_ctor=FieldMap::defaulted(ds); - this.prefix_kind_fields=FieldMap::defaulted(ds); - this.renamed_fields=FieldMap::defaulted(ds); - this.override_field_accessor=FieldMap::defaulted(ds); - this.accessor_bounds=FieldMap::defaulted(ds); - this.changed_types=FieldMap::defaulted(ds); + this.layout_ctor = FieldMap::defaulted(ds); + this.prefix_kind_fields = FieldMap::defaulted(ds); + this.renamed_fields = FieldMap::defaulted(ds); + this.override_field_accessor = FieldMap::defaulted(ds); + this.accessor_bounds = FieldMap::defaulted(ds); + this.changed_types = FieldMap::defaulted(ds); this.ne_variants.resize( ds.variants.len(), - UncheckedNEVariant{ + UncheckedNEVariant { constructor: None, is_hidden: false, }, ); - - this.type_param_bounds=TypeParamMap::defaulted(ds); - let name=ds.name; - - parse_inner(&mut this, attrs, ParseContext::TypeAttr{name}, arenas)?; - - for (variant_index,variant) in ds.variants.iter().enumerate() { - parse_inner(&mut this, variant.attrs, ParseContext::Variant{variant_index}, arenas)?; - for (field_index,field) in variant.fields.iter().enumerate() { - parse_inner(&mut this, field.attrs, ParseContext::Field{field,field_index}, arenas)?; + this.type_param_bounds = TypeParamMap::defaulted(ds); + + let name = ds.name; + + parse_inner(&mut this, attrs, ParseContext::TypeAttr { name }, arenas)?; + + for (variant_index, variant) in ds.variants.iter().enumerate() { + parse_inner( + &mut this, + variant.attrs, + ParseContext::Variant { variant_index }, + arenas, + )?; + for (field_index, field) in variant.fields.iter().enumerate() { + parse_inner( + &mut this, + field.attrs, + ParseContext::Field { field, field_index }, + arenas, + )?; } } @@ -465,22 +444,21 @@ where } /// Parses an individual attribute -fn parse_inner<'a,I>( +fn parse_inner<'a, I>( this: &mut StableAbiAttrs<'a>, attrs: I, pctx: ParseContext<'a>, arenas: &'a Arenas, -)-> Result<(),syn::Error> +) -> Result<(), syn::Error> where - I:IntoIterator + I: IntoIterator, { for attr in attrs { match attr.parse_meta() { Ok(Meta::List(list)) => { - parse_attr_list(this,pctx, list, arenas) - .combine_into_err(&mut this.errors); + parse_attr_list(this, pctx, list, arenas).combine_into_err(&mut this.errors); } - Err(e)=>{ + Err(e) => { this.errors.push_err(e); } _ => {} @@ -493,11 +471,11 @@ where fn parse_attr_list<'a>( this: &mut StableAbiAttrs<'a>, pctx: ParseContext<'a>, - list: MetaList, - arenas: &'a Arenas -)-> Result<(),syn::Error> { + list: MetaList, + arenas: &'a Arenas, +) -> Result<(), syn::Error> { if list.path.equals_str("repr") { - fn make_err(tokens:&dyn ToTokens)->syn::Error{ + fn make_err(tokens: &dyn ToTokens) -> syn::Error { spanned_err!( tokens, "repr attribute not currently recognized by this macro.{}", @@ -505,41 +483,43 @@ fn parse_attr_list<'a>( ) } with_nested_meta("repr", list.nested, |attr| match attr { - Meta::Path(ref path)=> { - let ident=path.get_ident().ok_or_else(|| make_err(path) )?; - let span=ident.span(); - - if ident=="C" { - this.repr.set_repr_kind(UncheckedReprKind::C,span) - }else if ident=="transparent" { - this.repr.set_repr_kind(UncheckedReprKind::Transparent,span) - }else if let Some(dr)=DiscriminantRepr::from_ident(ident) { - this.repr.set_discriminant_repr(dr,span) - }else if ident=="packed" { + Meta::Path(ref path) => { + let ident = path.get_ident().ok_or_else(|| make_err(path))?; + let span = ident.span(); + + if ident == "C" { + this.repr.set_repr_kind(UncheckedReprKind::C, span) + } else if ident == "transparent" { + this.repr + .set_repr_kind(UncheckedReprKind::Transparent, span) + } else if let Some(dr) = DiscriminantRepr::from_ident(ident) { + this.repr.set_discriminant_repr(dr, span) + } else if ident == "packed" { this.repr.set_packed(None) - }else{ + } else { Err(make_err(ident)) - }.combine_into_err(&mut this.errors); + } + .combine_into_err(&mut this.errors); Ok(()) } - Meta::List(ref list) if list.path.equals_str("align") => { - match list.nested.first() { - Some(NestedMeta::Lit(Lit::Int(ref lit))) => { - let alignment = lit.base10_parse().map_err(|_| make_err(list) )?; - this.repr.set_aligned(alignment) - } - _=>Err(make_err(list)), + Meta::List(ref list) if list.path.equals_str("align") => match list.nested.first() { + Some(NestedMeta::Lit(Lit::Int(ref lit))) => { + let alignment = lit.base10_parse().map_err(|_| make_err(list))?; + this.repr.set_aligned(alignment) } - } - Meta::NameValue(MetaNameValue{lit:Lit::Str(ref value),ref path,..}) - if path.equals_str("packed") => { - let panicking = value.value().parse::().map_err(|_| make_err(value) )?; + _ => Err(make_err(list)), + }, + Meta::NameValue(MetaNameValue { + lit: Lit::Str(ref value), + ref path, + .. + }) if path.equals_str("packed") => { + let panicking = value.value().parse::().map_err(|_| make_err(value))?; this.repr.set_packed(Some(panicking)) } - x => { - Err(make_err(&x)) - } - }).combine_into_err(&mut this.errors); + x => Err(make_err(&x)), + }) + .combine_into_err(&mut this.errors); } else if list.path.equals_str("doc") { let mut is_hidden = false; let res = with_nested_meta("doc", list.nested, |attr| { @@ -552,20 +532,18 @@ fn parse_attr_list<'a>( }); match pctx { - ParseContext::TypeAttr{..} => { + ParseContext::TypeAttr { .. } => { this.is_hidden = is_hidden; } - ParseContext::Variant{variant_index,..} => { + ParseContext::Variant { variant_index, .. } => { this.ne_variants[variant_index].is_hidden = is_hidden; - } - ParseContext::Field{..} => {} + ParseContext::Field { .. } => {} } res? } else if list.path.equals_str("sabi") { with_nested_meta("sabi", list.nested, |attr| { - parse_sabi_attr(this,pctx, attr, arenas) - .combine_into_err(&mut this.errors); + parse_sabi_attr(this, pctx, attr, arenas).combine_into_err(&mut this.errors); Ok(()) })?; } @@ -575,125 +553,130 @@ fn parse_attr_list<'a>( /// Parses the contents of a `#[sabi( .. )]` attribute. fn parse_sabi_attr<'a>( this: &mut StableAbiAttrs<'a>, - pctx: ParseContext<'a>, - attr: Meta, - arenas: &'a Arenas -)-> Result<(),syn::Error> { - fn make_err(tokens:&dyn ToTokens)->syn::Error{ - spanned_err!(tokens,"unrecognized attribute") + pctx: ParseContext<'a>, + attr: Meta, + arenas: &'a Arenas, +) -> Result<(), syn::Error> { + fn make_err(tokens: &dyn ToTokens) -> syn::Error { + spanned_err!(tokens, "unrecognized attribute") } match (pctx, attr) { - (ParseContext::Field{field,field_index}, Meta::Path(path)) => { - let word=path.get_ident().ok_or_else(|| make_err(&path) )?; + (ParseContext::Field { field, field_index }, Meta::Path(path)) => { + let word = path.get_ident().ok_or_else(|| make_err(&path))?; if word == "unsafe_opaque_field" { - this.layout_ctor[field]=LayoutConstructor::Opaque; - }else if word=="unsafe_sabi_opaque_field" { - this.layout_ctor[field]=LayoutConstructor::SabiOpaque; - }else if word == "last_prefix_field" { - let field_pos=field_index+1; - this.first_suffix_field=FirstSuffixField{field_pos}; - }else{ + this.layout_ctor[field] = LayoutConstructor::Opaque; + } else if word == "unsafe_sabi_opaque_field" { + this.layout_ctor[field] = LayoutConstructor::SabiOpaque; + } else if word == "last_prefix_field" { + let field_pos = field_index + 1; + this.first_suffix_field = FirstSuffixField { field_pos }; + } else { return Err(make_err(&path)); } } ( - ParseContext::Field{field,..}, - Meta::NameValue(MetaNameValue{lit:Lit::Str(ref value),ref path,..}) + ParseContext::Field { field, .. }, + Meta::NameValue(MetaNameValue { + lit: Lit::Str(ref value), + ref path, + .. + }), ) => { - let ident=path.get_ident().ok_or_else(|| make_err(&path) )?; - - if ident=="rename" { - let renamed=value - .parse::()? - .piped(|x| arenas.alloc(x) ); - this.renamed_fields.insert(field,Some(renamed)); - }else if ident=="unsafe_change_type" { - let changed_type=parse_lit_as_type(&value)? - .piped(|x| arenas.alloc(x) ); - this.changed_types.insert(field,Some(changed_type)); - }else if ident=="accessible_if" { - let expr=arenas.alloc(parse_lit_as_expr(&value)?); - this.prefix_kind_fields[field].accessible_if=Some(expr); - }else if ident == "accessor_bound" { - let bound=parse_lit_as_type_bounds(&value)?; + let ident = path.get_ident().ok_or_else(|| make_err(&path))?; + + if ident == "rename" { + let renamed = value.parse::()?.piped(|x| arenas.alloc(x)); + this.renamed_fields.insert(field, Some(renamed)); + } else if ident == "unsafe_change_type" { + let changed_type = parse_lit_as_type(&value)?.piped(|x| arenas.alloc(x)); + this.changed_types.insert(field, Some(changed_type)); + } else if ident == "accessible_if" { + let expr = arenas.alloc(parse_lit_as_expr(&value)?); + this.prefix_kind_fields[field].accessible_if = Some(expr); + } else if ident == "accessor_bound" { + let bound = parse_lit_as_type_bounds(&value)?; this.accessor_bounds[field].extend(bound); - }else if ident == "bound" { - let bounds=parse_lit_as_type_bounds(&value)?; - let preds=where_predicate_from(field.ty.clone(), bounds); + } else if ident == "bound" { + let bounds = parse_lit_as_type_bounds(&value)?; + let preds = where_predicate_from(field.ty.clone(), bounds); this.extra_bounds.push(preds); - }else{ + } else { return Err(make_err(&path)); } } - (ParseContext::Field{field,..}, Meta::List(list)) => { - let ident=list.path.get_ident().ok_or_else(|| make_err(&list.path) )?; - - if ident=="missing_field" { - let on_missing_field=parse_missing_field(&list.nested,arenas)?; - let on_missing=&mut this.prefix_kind_fields[field].on_missing; - if on_missing.is_some(){ + (ParseContext::Field { field, .. }, Meta::List(list)) => { + let ident = list.path.get_ident().ok_or_else(|| make_err(&list.path))?; + + if ident == "missing_field" { + let on_missing_field = parse_missing_field(&list.nested, arenas)?; + let on_missing = &mut this.prefix_kind_fields[field].on_missing; + if on_missing.is_some() { return_spanned_err!( ident, "Cannot use this attribute multiple times on the same field" ); } - *on_missing=Some(on_missing_field); - }else if ident=="refl" { - parse_refl_field(this,field,list.nested,arenas)?; - }else{ - return_spanned_err!(ident,"unrecognized field attribute"); + *on_missing = Some(on_missing_field); + } else if ident == "refl" { + parse_refl_field(this, field, list.nested, arenas)?; + } else { + return_spanned_err!(ident, "unrecognized field attribute"); } } - (ParseContext::TypeAttr{..},Meta::Path(ref path)) if path.equals_str("debug_print") =>{ - this.debug_print=true; + (ParseContext::TypeAttr { .. }, Meta::Path(ref path)) if path.equals_str("debug_print") => { + this.debug_print = true; } ( - ParseContext::TypeAttr{..}, - Meta::NameValue(MetaNameValue{lit:Lit::Str(ref unparsed_lit),ref path,..}) - )=>{ - let ident=path.get_ident().ok_or_else(|| make_err(path) )?; + ParseContext::TypeAttr { .. }, + Meta::NameValue(MetaNameValue { + lit: Lit::Str(ref unparsed_lit), + ref path, + .. + }), + ) => { + let ident = path.get_ident().ok_or_else(|| make_err(path))?; - if ident=="bound"||ident=="prefix_bound" { - let ident=path.get_ident().ok_or_else(|| make_err(path) )?; + if ident == "bound" || ident == "prefix_bound" { + let ident = path.get_ident().ok_or_else(|| make_err(path))?; - let bound=unparsed_lit.parse::()?; - if ident=="bound"{ + let bound = unparsed_lit.parse::()?; + if ident == "bound" { this.extra_bounds.push(bound); - }else if ident=="prefix_bound" { + } else if ident == "prefix_bound" { this.prefix_bounds.push(bound); } - }else if ident=="bounds"||ident=="prefix_bounds" { - let ident=path.get_ident().ok_or_else(|| make_err(path) )?; + } else if ident == "bounds" || ident == "prefix_bounds" { + let ident = path.get_ident().ok_or_else(|| make_err(path))?; - let bound=unparsed_lit - .parse::>()? + let bound = unparsed_lit + .parse::>()? .list; - if ident=="bounds"{ + if ident == "bounds" { this.extra_bounds.extend(bound); - }else if ident=="prefix_bounds" { + } else if ident == "prefix_bounds" { this.prefix_bounds.extend(bound); } - }else if ident=="phantom_field"{ - let unparsed_field=unparsed_lit.value(); - let mut iter=unparsed_field.splitn(2,':'); - let name={ - let x=iter.next().unwrap_or(""); - let x=syn::parse_str::(x)?; + } else if ident == "phantom_field" { + let unparsed_field = unparsed_lit.value(); + let mut iter = unparsed_field.splitn(2, ':'); + let name = { + let x = iter.next().unwrap_or(""); + let x = syn::parse_str::(x)?; arenas.alloc(x) }; - let ty=arenas.alloc(parse_str_as_type(iter.next().unwrap_or(""))?); - this.extra_phantom_fields.push((name,ty)); - }else if ident=="phantom_type_param"{ - let ty=arenas.alloc(parse_lit_as_type(unparsed_lit)?); + let ty = arenas.alloc(parse_str_as_type(iter.next().unwrap_or(""))?); + this.extra_phantom_fields.push((name, ty)); + } else if ident == "phantom_type_param" { + let ty = arenas.alloc(parse_lit_as_type(unparsed_lit)?); this.phantom_type_params.push(ty); - }else if ident=="phantom_const_param"{ - let constant=arenas.alloc(parse_lit_as_expr(unparsed_lit)?); + } else if ident == "phantom_const_param" { + let constant = arenas.alloc(parse_lit_as_expr(unparsed_lit)?); this.phantom_const_params.push(constant); - }else if ident=="tag"||ident=="extra_checks" { - let bound=unparsed_lit.parse::(); + } else if ident == "tag" || ident == "extra_checks" { + let bound = unparsed_lit.parse::(); - if ident=="tag" { + if ident == "tag" { if this.tags.is_some() { return_spanned_err!( unparsed_lit, @@ -714,8 +697,8 @@ fn parse_sabi_attr<'a>( ", ); } - this.tags=Some(bound?); - }else if ident=="extra_checks" { + this.tags = Some(bound?); + } else if ident == "extra_checks" { if this.extra_checks.is_some() { return_spanned_err!( ident, @@ -724,102 +707,95 @@ fn parse_sabi_attr<'a>( " ); } - - this.extra_checks=Some(bound?); - } - }else{ + this.extra_checks = Some(bound?); + } + } else { return Err(make_err(path)); } } - (ParseContext::TypeAttr{name},Meta::List(list)) => { - let ident=list.path.get_ident().ok_or_else(|| make_err(&list.path) )?; + (ParseContext::TypeAttr { name }, Meta::List(list)) => { + let ident = list.path.get_ident().ok_or_else(|| make_err(&list.path))?; if ident == "missing_field" { - let on_missing=&mut this.default_on_missing_fields; - if on_missing.is_some(){ + let on_missing = &mut this.default_on_missing_fields; + if on_missing.is_some() { return_spanned_err!( ident, "Cannot use this attribute multiple times on the container" ); } - *on_missing=Some(parse_missing_field(&list.nested,arenas)?); + *on_missing = Some(parse_missing_field(&list.nested, arenas)?); } else if ident == "kind" { - with_nested_meta("kind", list.nested, |attr|{ + with_nested_meta("kind", list.nested, |attr| { match attr { Meta::Path(ref path) if path.equals_str("Value") => { - this.kind = UncheckedStabilityKind::Value{ - impl_prefix_stable_abi: false + this.kind = UncheckedStabilityKind::Value { + impl_prefix_stable_abi: false, }; } Meta::Path(ref path) if path.equals_str("Prefix") => { - let prefix=parse_prefix_type_list( + let prefix = parse_prefix_type_list( path.get_ident().unwrap(), &Punctuated::new(), arenas, )?; this.kind = UncheckedStabilityKind::Prefix(prefix); } - Meta::List(ref list)=>{ - let ident=match list.path.get_ident() { - Some(x)=>x, - None=>return_spanned_err!(list,"invalid #[kind(..)] attribute"), + Meta::List(ref list) => { + let ident = match list.path.get_ident() { + Some(x) => x, + None => return_spanned_err!(list, "invalid #[kind(..)] attribute"), }; if ident == "Prefix" { - let prefix=parse_prefix_type_list(name,&list.nested,arenas)?; + let prefix = parse_prefix_type_list(name, &list.nested, arenas)?; this.kind = UncheckedStabilityKind::Prefix(prefix); - }else if ident == "WithNonExhaustive" { - let nonexhaustive= - parse_non_exhaustive_list(name,&list.nested,arenas)?; + } else if ident == "WithNonExhaustive" { + let nonexhaustive = + parse_non_exhaustive_list(name, &list.nested, arenas)?; this.kind = UncheckedStabilityKind::NonExhaustive(nonexhaustive); - }else{ - this.errors.push_err(spanned_err!( - ident, - "invalid #[kind(..)] attribute" - )); + } else { + this.errors + .push_err(spanned_err!(ident, "invalid #[kind(..)] attribute")); } } - x => this.errors.push_err(spanned_err!( - x, - "invalid #[kind(..)] attribute", - )), + x => this + .errors + .push_err(spanned_err!(x, "invalid #[kind(..)] attribute",)), } Ok(()) })?; } else if ident == "module_reflection" { - fn mrefl_err(tokens:&dyn ToTokens)->syn::Error{ - spanned_err!( - tokens, - "invalid #[module_reflection(..)] attribute." - ) + fn mrefl_err(tokens: &dyn ToTokens) -> syn::Error { + spanned_err!(tokens, "invalid #[module_reflection(..)] attribute.") } with_nested_meta("module_reflection", list.nested, |attr| { if this.mod_refl_mode.is_some() { - return_spanned_err!(ident,"Cannot use this attribute multiple times"); + return_spanned_err!(ident, "Cannot use this attribute multiple times"); } - + match attr { - Meta::Path(ref path)=>{ - let word=path.get_ident().ok_or_else(|| mrefl_err(path) )?; + Meta::Path(ref path) => { + let word = path.get_ident().ok_or_else(|| mrefl_err(path))?; if word == "Module" { this.mod_refl_mode = Some(ModReflMode::Module); - }else if word == "Opaque" { + } else if word == "Opaque" { this.mod_refl_mode = Some(ModReflMode::Opaque); - }else if word == "Deref" { + } else if word == "Deref" { this.mod_refl_mode = Some(ModReflMode::DelegateDeref(())); - }else{ + } else { this.errors.push_err(mrefl_err(word)); } - } + } ref x => this.errors.push_err(mrefl_err(x)), } Ok(()) })?; } else if ident == "not_stableabi" { - fn nsabi_err(tokens:&dyn ToTokens)->syn::Error{ + fn nsabi_err(tokens: &dyn ToTokens) -> syn::Error { spanned_err!( tokens, "invalid #[not_stableabi(..)] attribute\ @@ -827,12 +803,12 @@ fn parse_sabi_attr<'a>( ) } - with_nested_meta("not_stableabi", list.nested, |attr|{ + with_nested_meta("not_stableabi", list.nested, |attr| { match attr { - Meta::Path(path)=>{ - let type_param=path.into_ident().map_err(|p| nsabi_err(&p) )?; + Meta::Path(path) => { + let type_param = path.into_ident().map_err(|p| nsabi_err(&p))?; - *this.type_param_bounds.get_mut(&type_param)?= + *this.type_param_bounds.get_mut(&type_param)? = ASTypeParamBound::GetStaticEquivalent; } x => this.errors.push_err(nsabi_err(&x)), @@ -840,7 +816,7 @@ fn parse_sabi_attr<'a>( Ok(()) })?; } else if ident == "unsafe_unconstrained" { - fn uu_err(tokens:&dyn ToTokens)->syn::Error{ + fn uu_err(tokens: &dyn ToTokens) -> syn::Error { spanned_err!( tokens, "invalid #[unsafe_unconstrained(..)] attribute\ @@ -850,10 +826,10 @@ fn parse_sabi_attr<'a>( with_nested_meta("unsafe_unconstrained", list.nested, |attr| { match attr { - Meta::Path(path)=>{ - let type_param=path.into_ident().map_err(|p| uu_err(&p) )?; + Meta::Path(path) => { + let type_param = path.into_ident().map_err(|p| uu_err(&p))?; - *this.type_param_bounds.get_mut(&type_param)?= + *this.type_param_bounds.get_mut(&type_param)? = ASTypeParamBound::NoBound; } x => this.errors.push_err(spanned_err!( @@ -862,106 +838,107 @@ fn parse_sabi_attr<'a>( (it must be the identifier of a type parameter)." )), } - Ok(()) + Ok(()) })?; } else if ident == "impl_InterfaceType" { if this.impl_interfacetype.is_some() { - return_spanned_err!(ident,"Cannot use this attribute multiple times") + return_spanned_err!(ident, "Cannot use this attribute multiple times") } - this.impl_interfacetype=Some(parse_impl_interfacetype(&list.nested)?); - }else{ - return_spanned_err!( - list, - "Unrecodnized #[sabi(..)] attribute", - ); + this.impl_interfacetype = Some(parse_impl_interfacetype(&list.nested)?); + } else { + return_spanned_err!(list, "Unrecodnized #[sabi(..)] attribute",); } } - (ParseContext::TypeAttr{..},Meta::Path(ref path))=>{ - let word=path.get_ident().ok_or_else(|| make_err(&path) )?; + (ParseContext::TypeAttr { .. }, Meta::Path(ref path)) => { + let word = path.get_ident().ok_or_else(|| make_err(&path))?; if word == "with_constructor" { - this.ne_variants.iter_mut() - .for_each(|x|x.constructor=Some(UncheckedVariantConstructor::Regular)); - }else if word=="with_boxed_constructor" { - this.ne_variants.iter_mut() - .for_each(|x|x.constructor=Some(UncheckedVariantConstructor::Boxed)); - }else if word=="unsafe_opaque_fields" { + this.ne_variants + .iter_mut() + .for_each(|x| x.constructor = Some(UncheckedVariantConstructor::Regular)); + } else if word == "with_boxed_constructor" { + this.ne_variants + .iter_mut() + .for_each(|x| x.constructor = Some(UncheckedVariantConstructor::Boxed)); + } else if word == "unsafe_opaque_fields" { this.layout_ctor .iter_mut() - .for_each(|(_,x)|*x=LayoutConstructor::Opaque); - }else if word=="unsafe_sabi_opaque_fields" { + .for_each(|(_, x)| *x = LayoutConstructor::Opaque); + } else if word == "unsafe_sabi_opaque_fields" { this.layout_ctor .iter_mut() - .for_each(|(_,x)|*x=LayoutConstructor::SabiOpaque); - }else if word=="unsafe_allow_type_macros" { - this.allow_type_macros=true; - }else if word=="with_field_indices" { - this.with_field_indices=true; - }else if word=="impl_prefix_stable_abi" { - this.kind = UncheckedStabilityKind::Value{ + .for_each(|(_, x)| *x = LayoutConstructor::SabiOpaque); + } else if word == "unsafe_allow_type_macros" { + this.allow_type_macros = true; + } else if word == "with_field_indices" { + this.with_field_indices = true; + } else if word == "impl_prefix_stable_abi" { + this.kind = UncheckedStabilityKind::Value { impl_prefix_stable_abi: true, }; - }else{ + } else { return Err(make_err(&path)); } } - (ParseContext::Variant{variant_index},Meta::Path(ref path))=>{ - let word=path.get_ident().ok_or_else(|| make_err(&path) )?; - - if word=="with_constructor" { - this.ne_variants[variant_index].constructor= + (ParseContext::Variant { variant_index }, Meta::Path(ref path)) => { + let word = path.get_ident().ok_or_else(|| make_err(&path))?; + + if word == "with_constructor" { + this.ne_variants[variant_index].constructor = Some(UncheckedVariantConstructor::Regular); - }else if word=="with_boxed_constructor" { - this.ne_variants[variant_index].constructor= + } else if word == "with_boxed_constructor" { + this.ne_variants[variant_index].constructor = Some(UncheckedVariantConstructor::Boxed); - }else{ + } else { return Err(make_err(&path)); } } - (_,x) => return Err(make_err(&x)), + (_, x) => return Err(make_err(&x)), } Ok(()) } - /// Parses the `#[sabi(refl="...")` attribute. fn parse_refl_field<'a>( this: &mut StableAbiAttrs<'a>, - field:&'a Field<'a>, - list: Punctuated, - arenas: &'a Arenas -)-> Result<(),syn::Error> { - fn make_err(tokens:&dyn ToTokens)->syn::Error{ - spanned_err!(tokens,"invalid #[sabi(refl(..))] attribute.") + field: &'a Field<'a>, + list: Punctuated, + arenas: &'a Arenas, +) -> Result<(), syn::Error> { + fn make_err(tokens: &dyn ToTokens) -> syn::Error { + spanned_err!(tokens, "invalid #[sabi(refl(..))] attribute.") } with_nested_meta("refl", list, |attr| { match attr { - Meta::NameValue(MetaNameValue{lit:Lit::Str(ref val),ref path,..})=>{ - let ident=path.get_ident().ok_or_else(|| make_err(path) )?; - - if ident=="pub_getter" { - let function=arenas.alloc(val.parse::()?); - this.override_field_accessor[field]= - Some(FieldAccessor::Method{ name:Some(function) }); - }else{ + Meta::NameValue(MetaNameValue { + lit: Lit::Str(ref val), + ref path, + .. + }) => { + let ident = path.get_ident().ok_or_else(|| make_err(path))?; + + if ident == "pub_getter" { + let function = arenas.alloc(val.parse::()?); + this.override_field_accessor[field] = Some(FieldAccessor::Method { + name: Some(function), + }); + } else { this.errors.push_err(make_err(path)); } } - ref x => this.errors.push_err(make_err(x)) + ref x => this.errors.push_err(make_err(x)), } Ok(()) }) } - - /// Parses the contents of #[sabi(missing_field( ... ))] fn parse_missing_field<'a>( - list: &Punctuated, - arenas: &'a Arenas -)-> Result,syn::Error> { - const ATTRIBUTE_MSG:&str=" + list: &Punctuated, + arenas: &'a Arenas, +) -> Result, syn::Error> { + const ATTRIBUTE_MSG: &str = " Valid Attributes: @@ -982,53 +959,45 @@ Valid Attributes: This returns `Default::default` if the field doesn't exist. "; - let mf_err=|tokens:&dyn ToTokens|->syn::Error{ - spanned_err!( - tokens, - "Invalid attribute.\n{}", - ATTRIBUTE_MSG, - ) + let mf_err = |tokens: &dyn ToTokens| -> syn::Error { + spanned_err!(tokens, "Invalid attribute.\n{}", ATTRIBUTE_MSG,) }; - let first_arg=list.into_iter().next(); + let first_arg = list.into_iter().next(); match first_arg { - Some(NestedMeta::Meta(Meta::NameValue(MetaNameValue{ + Some(NestedMeta::Meta(Meta::NameValue(MetaNameValue { path, - lit:Lit::Str(ref str_), + lit: Lit::Str(ref str_), .. - })))=>{ - let nv_ident=path.get_ident().ok_or_else(|| mf_err(&path) )?; - - if nv_ident=="with" { - let function=str_.parse::()? - .piped(|i| arenas.alloc(i) ); - Ok(OnMissingField::With{function}) - }else if nv_ident=="value" { - let value=str_.parse::()? - .piped(|i| arenas.alloc(i) ); - Ok(OnMissingField::Value{value}) - }else{ + }))) => { + let nv_ident = path.get_ident().ok_or_else(|| mf_err(&path))?; + + if nv_ident == "with" { + let function = str_.parse::()?.piped(|i| arenas.alloc(i)); + Ok(OnMissingField::With { function }) + } else if nv_ident == "value" { + let value = str_.parse::()?.piped(|i| arenas.alloc(i)); + Ok(OnMissingField::Value { value }) + } else { Err(mf_err(&first_arg)) } } - Some(NestedMeta::Meta(Meta::Path(ref path)))=>{ - let word=path.get_ident().ok_or_else(|| mf_err(&first_arg) )?; + Some(NestedMeta::Meta(Meta::Path(ref path))) => { + let word = path.get_ident().ok_or_else(|| mf_err(&first_arg))?; - if word=="option" { + if word == "option" { Ok(OnMissingField::ReturnOption) - }else if word=="panic" { + } else if word == "panic" { Ok(OnMissingField::Panic) - }else if word=="default" { + } else if word == "default" { Ok(OnMissingField::Default_) - }else{ + } else { Err(mf_err(word)) } } - Some(rem)=>{ - Err(mf_err(&rem)) - } - None=>Err(spanned_err!( + Some(rem) => Err(mf_err(&rem)), + None => Err(spanned_err!( list, "Error:Expected one attribute inside `missing_field(..)`\n{}", ATTRIBUTE_MSG @@ -1036,17 +1005,16 @@ Valid Attributes: } } - /// Parses the contents of #[sabi(kind(Prefix( ... )))] fn parse_prefix_type_list<'a>( - _name:&Ident, - list: &Punctuated, - arenas: &'a Arenas -)-> Result,syn::Error> { + _name: &Ident, + list: &Punctuated, + arenas: &'a Arenas, +) -> Result, syn::Error> { let mut prefix_ref = None; let mut prefix_fields = None; - fn make_err(tokens:&dyn ToTokens)->syn::Error { + fn make_err(tokens: &dyn ToTokens) -> syn::Error { spanned_err!( tokens, "invalid #[sabi(kind(Prefix( )))] attribute it must be one of:\n\ @@ -1058,41 +1026,39 @@ fn parse_prefix_type_list<'a>( for elem in list { match elem { - NestedMeta::Meta(Meta::NameValue(MetaNameValue{ + NestedMeta::Meta(Meta::NameValue(MetaNameValue { ref path, - lit:Lit::Str(ref type_str), + lit: Lit::Str(ref type_str), .. })) => { - let type_str=type_str.value(); + let type_str = type_str.value(); if path.equals_str("prefix_ref") { let ident = arenas.alloc(parse_str_as_ident(&type_str)); prefix_ref = Some(ident); - }else if path.equals_str("prefix_fields") { + } else if path.equals_str("prefix_fields") { let ident = arenas.alloc(parse_str_as_ident(&type_str)); prefix_fields = Some(ident); - }else{ + } else { return Err(make_err(path)); } } ref x => return Err(make_err(x)), } - }; + } - Ok(UncheckedPrefixKind{ + Ok(UncheckedPrefixKind { prefix_ref, prefix_fields, }) } - /// Parses the contents of #[sabi(kind(WithNonExhaustive( ... )))] fn parse_non_exhaustive_list<'a>( - _name:&'a Ident, - list: &Punctuated, - arenas: &'a Arenas -)-> Result,syn::Error> { - - fn make_err(tokens:&dyn ToTokens,param:&str)->syn::Error{ + _name: &'a Ident, + list: &Punctuated, + arenas: &'a Arenas, +) -> Result, syn::Error> { + fn make_err(tokens: &dyn ToTokens, param: &str) -> syn::Error { spanned_err!( tokens, "invalid #[sabi(kind(WithNonExhaustive({})))] attribute", @@ -1100,18 +1066,28 @@ fn parse_non_exhaustive_list<'a>( ) } - let trait_set_strs=[ - "Clone","Display","Debug", - "Eq","PartialEq","Ord","PartialOrd", - "Hash","Deserialize","Serialize","Send","Sync","Error", - ]; - - let trait_set=trait_set_strs + let trait_set_strs = [ + "Clone", + "Display", + "Debug", + "Eq", + "PartialEq", + "Ord", + "PartialOrd", + "Hash", + "Deserialize", + "Serialize", + "Send", + "Sync", + "Error", + ]; + + let trait_set = trait_set_strs .iter() - .map(|e| arenas.alloc(Ident::new(e,Span::call_site()) ) ) + .map(|e| arenas.alloc(Ident::new(e, Span::call_site()))) .collect::>(); - let trait_err=|trait_ident:&dyn ToTokens|->syn::Error{ + let trait_err = |trait_ident: &dyn ToTokens| -> syn::Error { spanned_err!( trait_ident, "Invalid trait in #[sabi(kind(WithNonExhaustive(traits())))].\n\ @@ -1121,100 +1097,102 @@ fn parse_non_exhaustive_list<'a>( ) }; - fn both_err(ident:&Ident)->syn::Error{ + fn both_err(ident: &Ident) -> syn::Error { spanned_err!( ident, "Cannot use both `interface=\"...\"` and `traits(...)`" ) } - - let mut this=UncheckedNonExhaustive::default(); + let mut this = UncheckedNonExhaustive::default(); - let mut errors=LinearResult::ok(()); + let mut errors = LinearResult::ok(()); for elem in list { match elem { - NestedMeta::Meta(Meta::NameValue(MetaNameValue{path,lit,..}))=>{ - let ident=path.get_ident().ok_or_else(|| make_err(&path,"") )?; + NestedMeta::Meta(Meta::NameValue(MetaNameValue { path, lit, .. })) => { + let ident = path.get_ident().ok_or_else(|| make_err(&path, ""))?; match lit { - Lit::Int(int_lit)=>{ - let int=IntOrType::Int(int_lit.base10_parse::()?); - if ident=="align" { - this.alignment=Some(int); - }else if ident=="size" { - this.size=Some(int); - }else{ - return Err(make_err(ident,"")) + Lit::Int(int_lit) => { + let int = IntOrType::Int(int_lit.base10_parse::()?); + if ident == "align" { + this.alignment = Some(int); + } else if ident == "size" { + this.size = Some(int); + } else { + return Err(make_err(ident, "")); } } - Lit::Str(str_lit)=>{ - let ty=arenas.alloc(parse_lit_as_type(str_lit)?); - - if ident=="align" { - this.alignment=Some(IntOrType::Type(ty)); - }else if ident=="size" { - this.size=Some(IntOrType::Type(ty)); - }else if ident=="assert_nonexhaustive" { + Lit::Str(str_lit) => { + let ty = arenas.alloc(parse_lit_as_type(str_lit)?); + + if ident == "align" { + this.alignment = Some(IntOrType::Type(ty)); + } else if ident == "size" { + this.size = Some(IntOrType::Type(ty)); + } else if ident == "assert_nonexhaustive" { this.assert_nonexh.push(ty); - }else if ident=="interface" { + } else if ident == "interface" { if this.enum_interface.is_some() { return Err(both_err(ident)); } - this.enum_interface=Some(EnumInterface::Old(ty)); - }else{ - errors.push_err(make_err(ident,"")) + this.enum_interface = Some(EnumInterface::Old(ty)); + } else { + errors.push_err(make_err(ident, "")) } } - ref x => errors.push_err(make_err(x,"")), + ref x => errors.push_err(make_err(x, "")), } } - NestedMeta::Meta(Meta::List(sublist))=>{ - let ident=sublist.path.get_ident().ok_or_else(|| make_err(&sublist,"") )?; + NestedMeta::Meta(Meta::List(sublist)) => { + let ident = sublist + .path + .get_ident() + .ok_or_else(|| make_err(&sublist, ""))?; - if ident=="assert_nonexhaustive" { + if ident == "assert_nonexhaustive" { for assertion in &sublist.nested { match assertion { - NestedMeta::Lit(Lit::Str(str_lit))=>{ - let ty=arenas.alloc(parse_lit_as_type(str_lit)?); + NestedMeta::Lit(Lit::Str(str_lit)) => { + let ty = arenas.alloc(parse_lit_as_type(str_lit)?); this.assert_nonexh.push(ty); } - x => errors.push_err(make_err(x,"assert_nonexhaustive( )")) + x => errors.push_err(make_err(x, "assert_nonexhaustive( )")), } } - }else if ident=="traits" { - let enum_interface=match &mut this.enum_interface { - Some(EnumInterface::New(x))=>x, - Some(EnumInterface::Old{..})=>{ + } else if ident == "traits" { + let enum_interface = match &mut this.enum_interface { + Some(EnumInterface::New(x)) => x, + Some(EnumInterface::Old { .. }) => { return Err(both_err(ident)); } - x@None=>{ - *x=Some(EnumInterface::New(Default::default())); + x @ None => { + *x = Some(EnumInterface::New(Default::default())); match x { - Some(EnumInterface::New(x))=>x, - _=>unreachable!() + Some(EnumInterface::New(x)) => x, + _ => unreachable!(), } } }; for subelem in &sublist.nested { - let (ident,is_impld)=match subelem { - NestedMeta::Meta(Meta::Path(path))=>{ - let ident=path.get_ident() - .ok_or_else(|| trait_err(ident) )?; - (ident,true) + let (ident, is_impld) = match subelem { + NestedMeta::Meta(Meta::Path(path)) => { + let ident = path.get_ident().ok_or_else(|| trait_err(ident))?; + (ident, true) } - NestedMeta::Meta(Meta::NameValue( - MetaNameValue{path,lit:Lit::Bool(bool_lit),..} - ))=>{ - let ident=path.get_ident() - .ok_or_else(|| trait_err(ident) )?; - (ident,bool_lit.value) + NestedMeta::Meta(Meta::NameValue(MetaNameValue { + path, + lit: Lit::Bool(bool_lit), + .. + })) => { + let ident = path.get_ident().ok_or_else(|| trait_err(ident))?; + (ident, bool_lit.value) } - x =>{ + x => { errors.push_err(trait_err(x)); - continue + continue; } }; @@ -1222,33 +1200,32 @@ fn parse_non_exhaustive_list<'a>( Some(&trait_ident) => { if is_impld { &mut enum_interface.impld - }else{ + } else { &mut enum_interface.unimpld - }.push(trait_ident); - }, - None =>errors.push_err(trait_err(ident)) + } + .push(trait_ident); + } + None => errors.push_err(trait_err(ident)), } } - }else{ - errors.push_err(make_err(ident,"")); + } else { + errors.push_err(make_err(ident, "")); } } - x => errors.push_err(make_err(x,"")) + x => errors.push_err(make_err(x, "")), } } - errors.into_result().map(|_| this ) + errors.into_result().map(|_| this) } - //////////////////////////////////////////////////////////////////////////////// - fn where_predicate_from( - ty:syn::Type, - bounds:Punctuated -) ->syn::WherePredicate { - let x=syn::PredicateType{ + ty: syn::Type, + bounds: Punctuated, +) -> syn::WherePredicate { + let x = syn::PredicateType { lifetimes: None, bounded_ty: ty, colon_token: Default::default(), @@ -1256,9 +1233,3 @@ fn where_predicate_from( }; syn::WherePredicate::Type(x) } - - - - - - diff --git a/abi_stable_derive/src/stable_abi/common_tokens.rs b/abi_stable_derive/src/stable_abi/common_tokens.rs index db1d1dff..848eeaaf 100644 --- a/abi_stable_derive/src/stable_abi/common_tokens.rs +++ b/abi_stable_derive/src/stable_abi/common_tokens.rs @@ -1,17 +1,12 @@ /*! This module defines the CommonTokens type, -used to pass constants of type from `syn` to +used to pass constants of type from `syn` to many functions in the `abi_stable_derive_lib::stable_abi` module. */ - use proc_macro2::Span; - -use crate::{ - *, - fn_pointer_extractor::FnParamRet, -}; +use crate::{fn_pointer_extractor::FnParamRet, *}; use std::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}; diff --git a/abi_stable_derive/src/stable_abi/generic_params.rs b/abi_stable_derive/src/stable_abi/generic_params.rs index 87a9cf15..5dba06b2 100644 --- a/abi_stable_derive/src/stable_abi/generic_params.rs +++ b/abi_stable_derive/src/stable_abi/generic_params.rs @@ -1,54 +1,53 @@ use super::*; -use crate::utils::{ - expr_from_ident, - type_from_ident, -}; +use crate::utils::{expr_from_ident, type_from_ident}; -pub(super) struct GenericParams<'a>{ - generics:&'a syn::Generics, +pub(super) struct GenericParams<'a> { + generics: &'a syn::Generics, type_param_range: StartLen, const_param_range: StartLen, - ctokens:&'a CommonTokens<'a>, + ctokens: &'a CommonTokens<'a>, } - -impl<'a> GenericParams<'a>{ +impl<'a> GenericParams<'a> { pub(super) fn new( - ds: &'a DataStructure<'a>, + ds: &'a DataStructure<'a>, shared_vars: &mut SharedVars<'a>, config: &'a StableAbiOptions<'a>, - ctokens:&'a CommonTokens<'a>, - )->Self{ - let generics=ds.generics; - let arenas=shared_vars.arenas(); - let type_param_range:StartLen={ - let shared_vars=std::cell::RefCell::new(&mut *shared_vars); - let phantom_type_params=config.phantom_type_params - .iter() - .map(|ty|{ - let ty:&'a syn::Type=*ty; - shared_vars.borrow_mut() - .push_type(LayoutConstructor::Regular,ty) - .to_u10() - }); + ctokens: &'a CommonTokens<'a>, + ) -> Self { + let generics = ds.generics; + let arenas = shared_vars.arenas(); + let type_param_range: StartLen = { + let shared_vars = std::cell::RefCell::new(&mut *shared_vars); + let phantom_type_params = config.phantom_type_params.iter().map(|ty| { + let ty: &'a syn::Type = *ty; + shared_vars + .borrow_mut() + .push_type(LayoutConstructor::Regular, ty) + .to_u10() + }); - let type_param_bounds=config.type_param_bounds + let type_param_bounds = config + .type_param_bounds .iter() - .filter(|(_,bounds)| **bounds==ASTypeParamBound::NoBound ) - .map(|(type_param,&bounds)|{ - let type_={ - let x=type_from_ident(type_param.clone()); + .filter(|(_, bounds)| **bounds == ASTypeParamBound::NoBound) + .map(|(type_param, &bounds)| { + let type_ = { + let x = type_from_ident(type_param.clone()); arenas.alloc(x) }; - let layout_ctor=bounds.into_::(); - shared_vars.borrow_mut().push_type(layout_ctor,type_).to_u10() + let layout_ctor = bounds.into_::(); + shared_vars + .borrow_mut() + .push_type(layout_ctor, type_) + .to_u10() }); - let mut iter=type_param_bounds.chain(phantom_type_params); - let first=iter.next().unwrap_or(0); - let mut last=first; + let mut iter = type_param_bounds.chain(phantom_type_params); + let first = iter.next().unwrap_or(0); + let mut last = first; for elem in iter { assert!( first <= elem, @@ -59,20 +58,23 @@ impl<'a> GenericParams<'a>{ last, elem, ); - last=elem; + last = elem; + } + StartLen { + start: first, + len: last - first, } - StartLen{start:first, len:last-first} }; - - let const_param_range={ - let const_params=generics.const_params() - .map(|cp| arenas.alloc(expr_from_ident(cp.ident.clone())) ) + let const_param_range = { + let const_params = generics + .const_params() + .map(|cp| arenas.alloc(expr_from_ident(cp.ident.clone()))) .chain(config.phantom_const_params.iter().cloned()); shared_vars.extend_with_constants(const_params) }; - Self{ + Self { generics, type_param_range, const_param_range, @@ -81,19 +83,20 @@ impl<'a> GenericParams<'a>{ } } - - impl<'a> ToTokens for GenericParams<'a> { fn to_tokens(&self, ts: &mut TokenStream2) { - let lifetimes=&self.generics.lifetimes().map(|x|&x.lifetime).collect::>(); - let type_param_range=self.type_param_range.tokenizer(self.ctokens.as_ref()); - let const_param_range=self.const_param_range.tokenizer(self.ctokens.as_ref()); - quote!( - abi_stable::tl_genparams!( - #(#lifetimes),*; - #type_param_range; - #const_param_range - ) - ).to_tokens(ts); + let lifetimes = &self + .generics + .lifetimes() + .map(|x| &x.lifetime) + .collect::>(); + let type_param_range = self.type_param_range.tokenizer(self.ctokens.as_ref()); + let const_param_range = self.const_param_range.tokenizer(self.ctokens.as_ref()); + quote!(abi_stable::tl_genparams!( + #(#lifetimes),*; + #type_param_range; + #const_param_range + )) + .to_tokens(ts); } } diff --git a/abi_stable_derive/src/stable_abi/nonexhaustive.rs b/abi_stable_derive/src/stable_abi/nonexhaustive.rs index d8ad18b9..5b12a3ba 100644 --- a/abi_stable_derive/src/stable_abi/nonexhaustive.rs +++ b/abi_stable_derive/src/stable_abi/nonexhaustive.rs @@ -1,93 +1,85 @@ -use std::{ - collections::HashMap, -}; +use std::collections::HashMap; use core_extensions::SelfOps; -use syn::{ - Ident, - visit_mut::VisitMut, -}; +use syn::{visit_mut::VisitMut, Ident}; -use quote::{quote,ToTokens}; +use quote::{quote, ToTokens}; -use proc_macro2::{Span,TokenStream as TokenStream2}; +use proc_macro2::{Span, TokenStream as TokenStream2}; use as_derive_utils::{ datastructure::DataStructure, - gen_params_in::{GenParamsIn,InWhat}, + gen_params_in::{GenParamsIn, InWhat}, + return_spanned_err, spanned_err, to_token_fn::ToTokenFnMut, - spanned_err, - return_spanned_err, }; use super::{ - attribute_parsing::{StabilityKind,StableAbiOptions}, + attribute_parsing::{StabilityKind, StableAbiOptions}, common_tokens::CommonTokens, StartLen, }; use crate::{ - arenas::{Arenas,AllocMethods}, - impl_interfacetype::{private_associated_type,TRAIT_LIST,UsableTrait}, + arenas::{AllocMethods, Arenas}, + impl_interfacetype::{private_associated_type, UsableTrait, TRAIT_LIST}, literals_constructors::rstr_tokenizer, - parse_utils::{parse_str_as_ident,parse_str_as_path}, + parse_utils::{parse_str_as_ident, parse_str_as_path}, set_span_visitor::SetSpanVisitor, - utils::{LinearResult,SynResultExt}, + utils::{LinearResult, SynResultExt}, }; - /// Used while parsing the `#[sabi(kind(WithNonExhaustive(...)))]` attribute. #[derive(Clone, Default)] -pub(crate) struct UncheckedNonExhaustive<'a>{ - pub(crate) alignment:Option>, - pub(crate) size:Option>, - pub(crate) enum_interface:Option>, - pub(crate) assert_nonexh:Vec<&'a syn::Type>, +pub(crate) struct UncheckedNonExhaustive<'a> { + pub(crate) alignment: Option>, + pub(crate) size: Option>, + pub(crate) enum_interface: Option>, + pub(crate) assert_nonexh: Vec<&'a syn::Type>, } - /// The configuration for code generation related to nonexhaustive enums. #[derive(Clone)] -pub(crate) struct NonExhaustive<'a>{ - pub(crate) nonexhaustive_alias:&'a Ident, +pub(crate) struct NonExhaustive<'a> { + pub(crate) nonexhaustive_alias: &'a Ident, /// The identifier for the interface parameter of `NonExhaustive<>`(the third one). - pub(crate) nonexhaustive_marker:&'a Ident, + pub(crate) nonexhaustive_marker: &'a Ident, /// The identifier for the storage space used to store the enum within `NonExhaustive<>` - pub(crate) enum_storage:&'a Ident, + pub(crate) enum_storage: &'a Ident, /// The alignment of `#enum_storage` - pub(crate) alignment:IntOrType<'a>, + pub(crate) alignment: IntOrType<'a>, /// The size of `#enum_storage` - pub(crate) size:IntOrType<'a>, + pub(crate) size: IntOrType<'a>, /// The InterfaceType-implementing marker struct this will generate, /// if this is: /// - `Some(EnumInterface::New{..})`:it will use a new struct as the InterfaceType. /// - `Some(EnumInterface::Old{..})`:it will use an existing type as the InterfaceType. /// - `None`: it will use `()` as the InterfaceType. /// rather than generate one. - pub(crate) enum_interface:Option>, + pub(crate) enum_interface: Option>, /// The identifier of the InterfaceType-implementing struct this will generate. - pub(crate) new_interface:Option<&'a Ident>, + pub(crate) new_interface: Option<&'a Ident>, /// The type used as the InterfaceType parameter of `NonExhaustive<>` by default. - pub(crate) default_interface:TokenStream2, + pub(crate) default_interface: TokenStream2, /// The types that will be tested as being compatible with their storage and interface. - pub(crate) assert_nonexh:Vec<&'a syn::Type>, - /// This is a trait aliasing the constraints required when + pub(crate) assert_nonexh: Vec<&'a syn::Type>, + /// This is a trait aliasing the constraints required when /// wrapping the enum inside `NonExhaustive<>`. - /// This is None when the enum uses a pre-existing InterfaceType as + /// This is None when the enum uses a pre-existing InterfaceType as /// its interface (the third type parameter of `NonExhaustive<>`) - pub(crate) bounds_trait:Option>, + pub(crate) bounds_trait: Option>, /// The constructor functions generated for each variant, /// with the enum wrapped inside `NonExhaustive<>` - pub(crate) ne_variants:Vec>, + pub(crate) ne_variants: Vec>, } -/// The configuration required to generate a trait aliasing the constraints required when +/// The configuration required to generate a trait aliasing the constraints required when /// wrapping the enum inside `NonExhaustive<>`. #[derive(Clone)] -pub struct BoundsTrait<'a>{ - ident:&'a Ident, - bounds:Vec<&'a syn::Path>, +pub struct BoundsTrait<'a> { + ident: &'a Ident, + bounds: Vec<&'a syn::Path>, } #[derive(Clone)] @@ -104,8 +96,8 @@ pub struct NEVariant<'a> { /// How a NonExhaustive is constructed #[derive(Clone)] -pub enum UncheckedVariantConstructor{ - /// Constructs an enum variant using a function +pub enum UncheckedVariantConstructor { + /// Constructs an enum variant using a function /// with parameters of the same type as the fields. Regular, /// Constructs an enum variant containing a pointer, @@ -115,62 +107,59 @@ pub enum UncheckedVariantConstructor{ /// How variant(s) of the enum wrapped inside `NonExhaustive<>` is constructed. #[derive(Clone)] -pub enum VariantConstructor<'a>{ - /// Constructs an enum variant using a function +pub enum VariantConstructor<'a> { + /// Constructs an enum variant using a function /// with parameters of the same type as the fields. Regular, /// Constructs an enum variant containing a pointer, /// using a function taking the referent of the pointer. /// - /// The type of the referent is extracted from the first type parameter + /// The type of the referent is extracted from the first type parameter /// in the type of the only field of a variant. - Boxed{ - referent:Option<&'a syn::Type>, - pointer:&'a syn::Type, + Boxed { + referent: Option<&'a syn::Type>, + pointer: &'a syn::Type, }, } - /// The InterfaceType of the enum,used as the third type parameter of NonExhaustive. #[derive(Clone)] -pub(crate) enum EnumInterface<'a>{ +pub(crate) enum EnumInterface<'a> { New(NewEnumInterface<'a>), Old(&'a syn::Type), } - /// The traits that are specified in `impl InterfaceType for Enum_Interface`, /// which specifies the traits that are required when wrapping the enum in `NonExhaustive<>`, /// and are then available when using it. -#[derive(Default,Clone)] -pub(crate) struct NewEnumInterface<'a>{ - pub(crate) impld:Vec<&'a Ident>, - pub(crate) unimpld:Vec<&'a Ident>, +#[derive(Default, Clone)] +pub(crate) struct NewEnumInterface<'a> { + pub(crate) impld: Vec<&'a Ident>, + pub(crate) unimpld: Vec<&'a Ident>, } - -impl<'a> NonExhaustive<'a>{ +impl<'a> NonExhaustive<'a> { pub fn new( - mut unchecked:UncheckedNonExhaustive<'a>, - ne_variants:Vec, + mut unchecked: UncheckedNonExhaustive<'a>, + ne_variants: Vec, ds: &'a DataStructure<'a>, arenas: &'a Arenas, - )-> Result { - let name=ds.name; - - let alignment=unchecked.alignment.unwrap_or(IntOrType::Usize); - - let parse_ident=move|s:&str,span:Option|->&'a Ident{ - let mut ident=parse_str_as_ident(s); - if let Some(span)=span{ + ) -> Result { + let name = ds.name; + + let alignment = unchecked.alignment.unwrap_or(IntOrType::Usize); + + let parse_ident = move |s: &str, span: Option| -> &'a Ident { + let mut ident = parse_str_as_ident(s); + if let Some(span) = span { ident.set_span(span) } arenas.alloc(ident) }; - let mut errors=LinearResult::ok(()); + let mut errors = LinearResult::ok(()); - let size=unchecked.size.unwrap_or_else(||{ + let size = unchecked.size.unwrap_or_else(|| { errors.push_err(spanned_err!( name, "\n\ @@ -182,89 +171,79 @@ impl<'a> NonExhaustive<'a>{ IntOrType::Int(0) }); - let mut bounds_trait=None::>; + let mut bounds_trait = None::>; - if let Some(EnumInterface::New(enum_interface))=&mut unchecked.enum_interface{ - let mut trait_map=TRAIT_LIST.iter() - .map(|x| ( parse_ident(x.name,None) , x ) ) - .collect::>(); - - let mut bounds_trait_inner=Vec::<&'a syn::Path>::new(); + if let Some(EnumInterface::New(enum_interface)) = &mut unchecked.enum_interface { + let mut trait_map = TRAIT_LIST + .iter() + .map(|x| (parse_ident(x.name, None), x)) + .collect::>(); + + let mut bounds_trait_inner = Vec::<&'a syn::Path>::new(); for &trait_ in &enum_interface.impld { match trait_map.remove(trait_) { Some(ut) => { use crate::impl_interfacetype::WhichTrait as WT; - if let WT::Deserialize=ut.which_trait { + if let WT::Deserialize = ut.which_trait { continue; - } - let mut full_path=parse_str_as_path(ut.full_path)?; + } + let mut full_path = parse_str_as_path(ut.full_path)?; - SetSpanVisitor::new(trait_.span()) - .visit_path_mut(&mut full_path); + SetSpanVisitor::new(trait_.span()).visit_path_mut(&mut full_path); bounds_trait_inner.push(arenas.alloc(full_path)); } - None =>{ + None => { // This is an internal error. - panic!("Trait {} was not in TRAIT_LIST.",trait_) + panic!("Trait {} was not in TRAIT_LIST.", trait_) } } } - bounds_trait=Some(BoundsTrait{ - ident:parse_ident(&format!("{}_Bounds",name),None), - bounds:bounds_trait_inner, + bounds_trait = Some(BoundsTrait { + ident: parse_ident(&format!("{}_Bounds", name), None), + bounds: bounds_trait_inner, }); - for &trait_ in &enum_interface.unimpld{ - if trait_map.remove(trait_).is_none(){ + for &trait_ in &enum_interface.unimpld { + if trait_map.remove(trait_).is_none() { // This is an internal error. - panic!("Trait {} was not in TRAIT_LIST.",trait_); + panic!("Trait {} was not in TRAIT_LIST.", trait_); } } - for (trait_,_) in trait_map { + for (trait_, _) in trait_map { enum_interface.unimpld.push(trait_); } } - let (default_interface,new_interface)=match unchecked.enum_interface { - Some(EnumInterface::New{..})=>{ - let name=parse_ident(&format!("{}_Interface",name),None); - (name.into_token_stream(),Some(name)) - }, - Some(EnumInterface::Old(ty))=>{ - ((&ty).into_token_stream(),None) - } - None=>{ - (quote!(()),None) + let (default_interface, new_interface) = match unchecked.enum_interface { + Some(EnumInterface::New { .. }) => { + let name = parse_ident(&format!("{}_Interface", name), None); + (name.into_token_stream(), Some(name)) } + Some(EnumInterface::Old(ty)) => ((&ty).into_token_stream(), None), + None => (quote!(()), None), }; - - let ne_variants=ne_variants.into_iter() + let ne_variants = ne_variants + .into_iter() .zip(&ds.variants) - .map(|(vc,variant)|{ + .map(|(vc, variant)| { let constructor = match vc.constructor { - Some(UncheckedVariantConstructor::Regular)=>{ - Some(VariantConstructor::Regular) - } - Some(UncheckedVariantConstructor::Boxed)=>{ - match variant.fields.first() { - Some(first_field) => - Some(VariantConstructor::Boxed{ - referent:extract_first_type_param(first_field.ty), - pointer:first_field.ty, - }), - None => - Some(VariantConstructor::Regular), - } - } + Some(UncheckedVariantConstructor::Regular) => Some(VariantConstructor::Regular), + Some(UncheckedVariantConstructor::Boxed) => match variant.fields.first() { + Some(first_field) => Some(VariantConstructor::Boxed { + referent: extract_first_type_param(first_field.ty), + pointer: first_field.ty, + }), + None => Some(VariantConstructor::Regular), + }, None => None, }; - NEVariant{ + NEVariant { constructor, is_hidden: vc.is_hidden, } @@ -273,59 +252,53 @@ impl<'a> NonExhaustive<'a>{ errors.into_result()?; - Ok(Self{ - nonexhaustive_alias:parse_ident(&format!("{}_NE",name),None), - nonexhaustive_marker:parse_ident(&format!("{}_NEMarker",name),None), - enum_storage:parse_ident(&format!("{}_Storage",name),None), + Ok(Self { + nonexhaustive_alias: parse_ident(&format!("{}_NE", name), None), + nonexhaustive_marker: parse_ident(&format!("{}_NEMarker", name), None), + enum_storage: parse_ident(&format!("{}_Storage", name), None), alignment, size, - enum_interface:unchecked.enum_interface, + enum_interface: unchecked.enum_interface, default_interface, new_interface, - assert_nonexh:unchecked.assert_nonexh, + assert_nonexh: unchecked.assert_nonexh, bounds_trait, ne_variants, }) } } - #[derive(Copy, Clone)] -pub enum IntOrType<'a>{ +pub enum IntOrType<'a> { Int(usize), Type(&'a syn::Type), Usize, } /// Extracts the first type parameter of a generic type. -fn extract_first_type_param(ty:&syn::Type)->Option<&syn::Type>{ +fn extract_first_type_param(ty: &syn::Type) -> Option<&syn::Type> { match ty { - syn::Type::Path(path)=>{ + syn::Type::Path(path) => { if path.qself.is_some() { return None; } - let args=&path.path.segments.last()?.arguments; - let args=match args { - syn::PathArguments::AngleBracketed(x)=>x, - _=>return None, + let args = &path.path.segments.last()?.arguments; + let args = match args { + syn::PathArguments::AngleBracketed(x) => x, + _ => return None, }; - args.args - .iter() - .find_map(|arg|{ - match arg { - syn::GenericArgument::Type(ty) => Some(ty), - _=>None, - } - }) + args.args.iter().find_map(|arg| match arg { + syn::GenericArgument::Type(ty) => Some(ty), + _ => None, + }) } - _=>None, + _ => None, } } - -fn hide_docs_if(opt: &Option, func: F) -> String +fn hide_docs_if(opt: &Option, func: F) -> String where - F: FnOnce() -> String + F: FnOnce() -> String, { if opt.is_some() { String::new() @@ -334,69 +307,64 @@ where } } - /// Outputs the nonexhausitve-enum-related items, /// outside the module generated by StableAbi. pub(crate) fn tokenize_nonexhaustive_items<'a>( - module:&'a Ident, - ds:&'a DataStructure<'a>, - config:&'a StableAbiOptions<'a>, - _ct:&'a CommonTokens<'a> -)->impl ToTokens+'a{ - ToTokenFnMut::new(move|ts|{ - - let this=match &config.kind { - StabilityKind::NonExhaustive(x)=>x, - _=>return, + module: &'a Ident, + ds: &'a DataStructure<'a>, + config: &'a StableAbiOptions<'a>, + _ct: &'a CommonTokens<'a>, +) -> impl ToTokens + 'a { + ToTokenFnMut::new(move |ts| { + let this = match &config.kind { + StabilityKind::NonExhaustive(x) => x, + _ => return, }; - let doc_hidden_attr=config.doc_hidden_attr; - let vis=ds.vis; - let nonexhaustive_alias=this.nonexhaustive_alias; - let nonexhaustive_marker=this.nonexhaustive_marker; - let enum_storage=this.enum_storage; - - let (aligner_attribute,aligner_field)=match this.alignment { - IntOrType::Int(bytes)=>{ - let bytes=crate::utils::expr_from_int(bytes as _); - ( Some(quote!(#[repr(align(#bytes))])) , None ) + let doc_hidden_attr = config.doc_hidden_attr; + let vis = ds.vis; + let nonexhaustive_alias = this.nonexhaustive_alias; + let nonexhaustive_marker = this.nonexhaustive_marker; + let enum_storage = this.enum_storage; + + let (aligner_attribute, aligner_field) = match this.alignment { + IntOrType::Int(bytes) => { + let bytes = crate::utils::expr_from_int(bytes as _); + (Some(quote!(#[repr(align(#bytes))])), None) } - IntOrType::Type(ty)=> - ( None , Some(quote!(__aligner:[#ty;0],)) ), - IntOrType::Usize=> - ( None , Some(quote!(__aligner:[usize;0],)) ), + IntOrType::Type(ty) => (None, Some(quote!(__aligner:[#ty;0],))), + IntOrType::Usize => (None, Some(quote!(__aligner: [usize; 0],))), }; - let aligner_size=match this.size { - IntOrType::Int(size)=>quote!( #size ), - IntOrType::Type(ty)=>quote!( std::mem::size_of::<#ty>() ), - IntOrType::Usize=>quote!( std::mem::size_of::() ), + let aligner_size = match this.size { + IntOrType::Int(size) => quote!( #size ), + IntOrType::Type(ty) => quote!( std::mem::size_of::<#ty>() ), + IntOrType::Usize => quote!(std::mem::size_of::()), }; - let name=ds.name; + let name = ds.name; - let generics_header= - GenParamsIn::new(&ds.generics,InWhat::ImplHeader); + let generics_header = GenParamsIn::new(&ds.generics, InWhat::ImplHeader); - let mut type_generics_decl=GenParamsIn::new(ds.generics,InWhat::ImplHeader); + let mut type_generics_decl = GenParamsIn::new(ds.generics, InWhat::ImplHeader); type_generics_decl.set_no_bounds(); - let type_generics_use=GenParamsIn::new(ds.generics,InWhat::ItemUse); + let type_generics_use = GenParamsIn::new(ds.generics, InWhat::ItemUse); - let mut storage_docs=String::new(); - let mut alias_docs=String::new(); - let mut marker_docs=String::new(); + let mut storage_docs = String::new(); + let mut alias_docs = String::new(); + let mut marker_docs = String::new(); if doc_hidden_attr.is_none() { - storage_docs=format!( + storage_docs = format!( "The default InlineStorage that `NonExhaustive` uses for \ [`{E}`](./enum.{E}.html).", E = name ); - alias_docs=format!( + alias_docs = format!( "An alias for `NonExhaustive` wrapping a [`{E}`](./enum.{E}.html).", E = name ); - marker_docs=format!( + marker_docs = format!( "A marker type which implements StableAbi with the layout of \ [`{E}`](./enum.{E}.html),\ used as a phantom field of NonExhaustive.", @@ -404,7 +372,7 @@ pub(crate) fn tokenize_nonexhaustive_items<'a>( ); } - let default_interface=&this.default_interface; + let default_interface = &this.default_interface; quote!( #[doc=#storage_docs] @@ -432,11 +400,11 @@ pub(crate) fn tokenize_nonexhaustive_items<'a>( std::marker::PhantomData, std::marker::PhantomData, ); - ).to_tokens(ts); + ) + .to_tokens(ts); - - if let Some(BoundsTrait{ident,bounds})=&this.bounds_trait{ - let trait_docs=hide_docs_if(&doc_hidden_attr, ||{ + if let Some(BoundsTrait { ident, bounds }) = &this.bounds_trait { + let trait_docs = hide_docs_if(&doc_hidden_attr, || { format!( "An alias for the traits that \ `NonExhaustive<{E},_,_>` requires to be constructed,\ @@ -445,7 +413,7 @@ pub(crate) fn tokenize_nonexhaustive_items<'a>( ) }); - quote!( + quote!( #[doc=#trait_docs] #vis trait #ident:#(#bounds+)*{} @@ -453,11 +421,12 @@ pub(crate) fn tokenize_nonexhaustive_items<'a>( where This:#(#bounds+)* {} - ).to_tokens(ts); + ) + .to_tokens(ts); } - if let Some(new_interface)=this.new_interface{ - let interface_docs=hide_docs_if(&doc_hidden_attr, ||{ + if let Some(new_interface) = this.new_interface { + let interface_docs = hide_docs_if(&doc_hidden_attr, || { format!( "Describes the traits required when constructing a \ `NonExhaustive<>` from [`{E}`](./enum.{E}.html),\ @@ -466,23 +435,25 @@ pub(crate) fn tokenize_nonexhaustive_items<'a>( ) }); - quote!( + quote!( #[doc=#interface_docs] #[repr(C)] #[derive(::abi_stable::StableAbi)] #vis struct #new_interface; - ).to_tokens(ts); + ) + .to_tokens(ts); } - if this.ne_variants.iter().any(|x| x.constructor.is_some() ) { - let constructors=this.ne_variants + if this.ne_variants.iter().any(|x| x.constructor.is_some()) { + let constructors = this + .ne_variants .iter() .cloned() .zip(&ds.variants) - .filter_map(|(vc,variant)|{ - let constructor=vc.constructor.as_ref()?; - let variant_ident=variant.name; - let mut method_name=parse_str_as_ident(&format!("{}_NE",variant.name)); + .filter_map(|(vc, variant)| { + let constructor = vc.constructor.as_ref()?; + let variant_ident = variant.name; + let mut method_name = parse_str_as_ident(&format!("{}_NE", variant.name)); method_name.set_span(variant.name.span()); let method_docs = if vc.is_hidden { @@ -490,19 +461,18 @@ pub(crate) fn tokenize_nonexhaustive_items<'a>( } else { let v_doc = format!( "Constructs the `{}::{}` variant inside a `NonExhaustive`.", - ds.name, - variant.name, + ds.name, variant.name, ); quote!(#[doc= #v_doc]) }; match constructor { - VariantConstructor::Regular=>{ - let field_names_a=variant.fields.iter().map(|x|x.pat_ident()); - let field_names_b=field_names_a.clone(); - let field_names_c=variant.fields.iter().map(|x|&x.ident); - let field_types=variant.fields.iter().map(|x|x.ty); - quote!{ + VariantConstructor::Regular => { + let field_names_a = variant.fields.iter().map(|x| x.pat_ident()); + let field_names_b = field_names_a.clone(); + let field_names_c = variant.fields.iter().map(|x| &x.ident); + let field_types = variant.fields.iter().map(|x| x.ty); + quote! { #method_docs #vis fn #method_name( #( #field_names_a : #field_types ,)* @@ -514,18 +484,17 @@ pub(crate) fn tokenize_nonexhaustive_items<'a>( } } } - VariantConstructor::Boxed{referent,pointer}=>{ - let ptr_field_ident=&variant.fields[0].ident; - let type_param=ToTokenFnMut::new(|ts|{ - match referent { - Some(x) => x.to_tokens(ts), - None => - quote!( <#pointer as __sabi_re::GetPointerKind>::PtrTarget ) - .to_tokens(ts), + VariantConstructor::Boxed { referent, pointer } => { + let ptr_field_ident = &variant.fields[0].ident; + let type_param = ToTokenFnMut::new(|ts| match referent { + Some(x) => x.to_tokens(ts), + None => { + quote!( <#pointer as __sabi_re::GetPointerKind>::PtrTarget ) + .to_tokens(ts) } }); - - quote!{ + + quote! { #method_docs #vis fn #method_name( value:#type_param, @@ -538,21 +507,20 @@ pub(crate) fn tokenize_nonexhaustive_items<'a>( } } } - }.piped(Some) + } + .piped(Some) }); - let preds=ds.generics.where_clause.as_ref().map(|w| &w.predicates ); - - let bound=match &this.bounds_trait { - Some(BoundsTrait{ident,..}) => - quote!(#ident), - None => - quote!( - #module::__sabi_re::GetNonExhaustiveVTable< - #enum_storage, - #default_interface, - > - ), + let preds = ds.generics.where_clause.as_ref().map(|w| &w.predicates); + + let bound = match &this.bounds_trait { + Some(BoundsTrait { ident, .. }) => quote!(#ident), + None => quote!( + #module::__sabi_re::GetNonExhaustiveVTable< + #enum_storage, + #default_interface, + > + ), }; quote!( @@ -564,22 +532,22 @@ pub(crate) fn tokenize_nonexhaustive_items<'a>( { #(#constructors)* } - ).to_tokens(ts); + ) + .to_tokens(ts); } - }) } /// Outputs the nonexhausitve-enum-related impl blocks, /// inside the module generated by StableAbi. pub(crate) fn tokenize_enum_info<'a>( - ds:&'a DataStructure<'a>, - variant_names_start_len:StartLen, - config:&'a StableAbiOptions<'a>, - ct:&'a CommonTokens<'a> -)-> Result { - let opt_type_ident=config.repr.type_ident(); - if let (StabilityKind::NonExhaustive{..},None)=(&config.kind,&opt_type_ident) { + ds: &'a DataStructure<'a>, + variant_names_start_len: StartLen, + config: &'a StableAbiOptions<'a>, + ct: &'a CommonTokens<'a>, +) -> Result { + let opt_type_ident = config.repr.type_ident(); + if let (StabilityKind::NonExhaustive { .. }, None) = (&config.kind, &opt_type_ident) { return_spanned_err!( ds.name, "Attempted to get type of discriminant for this representation:\n\t{:?}", @@ -587,68 +555,70 @@ pub(crate) fn tokenize_enum_info<'a>( ); } - Ok(ToTokenFnMut::new(move|ts|{ - let this=match &config.kind { - StabilityKind::NonExhaustive(x)=>x, - _=>return, + Ok(ToTokenFnMut::new(move |ts| { + let this = match &config.kind { + StabilityKind::NonExhaustive(x) => x, + _ => return, }; - let name=ds.name; - let name_str=rstr_tokenizer(ds.name.to_string()); + let name = ds.name; + let name_str = rstr_tokenizer(ds.name.to_string()); - let strings_const=&config.const_idents.strings; + let strings_const = &config.const_idents.strings; - let discriminants=ds.variants.iter().map(|x|x.discriminant) + let discriminants = ds + .variants + .iter() + .map(|x| x.discriminant) .collect::>>(); - - let discriminant_tokens=config.repr - .tokenize_discriminant_slice(discriminants.iter().cloned(),ct); - let discriminant_type=match &opt_type_ident { - Some(x)=>x, - None=>unreachable!(), + let discriminant_tokens = config + .repr + .tokenize_discriminant_slice(discriminants.iter().cloned(), ct); + + let discriminant_type = match &opt_type_ident { + Some(x) => x, + None => unreachable!(), }; - let vn_start=variant_names_start_len.start; - let vn_len =variant_names_start_len.len; + let vn_start = variant_names_start_len.start; + let vn_len = variant_names_start_len.len; - let nonexhaustive_marker=this.nonexhaustive_marker; - let enum_storage=this.enum_storage; + let nonexhaustive_marker = this.nonexhaustive_marker; + let enum_storage = this.enum_storage; - let mut start_discrs=Vec::new(); - let mut end_discrs=Vec::new(); + let mut start_discrs = Vec::new(); + let mut end_discrs = Vec::new(); if !discriminants.is_empty() { - let mut first_index=0; - - for (mut i,discr) in discriminants[1..].iter().cloned().enumerate() { - i+=1; + let mut first_index = 0; + + for (mut i, discr) in discriminants[1..].iter().cloned().enumerate() { + i += 1; if discr.is_some() { start_discrs.push(first_index); - end_discrs.push(i-1); - first_index=i; + end_discrs.push(i - 1); + first_index = i; } } start_discrs.push(first_index); - end_discrs.push(discriminants.len()-1); + end_discrs.push(discriminants.len() - 1); } + let generics_header = + GenParamsIn::with_after_types(&ds.generics, InWhat::ImplHeader, &ct.und_storage); - let generics_header= - GenParamsIn::with_after_types(&ds.generics,InWhat::ImplHeader,&ct.und_storage); - - let generics_use=GenParamsIn::new(&ds.generics,InWhat::ImplHeader); - - let default_interface=&this.default_interface; + let generics_use = GenParamsIn::new(&ds.generics, InWhat::ImplHeader); - let (impl_generics, ty_generics, where_clause) = ds.generics.split_for_impl(); + let default_interface = &this.default_interface; - let preds=where_clause.as_ref().map(|w| &w.predicates ); + let (impl_generics, ty_generics, where_clause) = ds.generics.split_for_impl(); + let preds = where_clause.as_ref().map(|w| &w.predicates); quote!( - unsafe impl #impl_generics __sabi_re::GetStaticEquivalent_ for #name #ty_generics + unsafe impl #impl_generics __sabi_re::GetStaticEquivalent_ for #name #ty_generics where #nonexhaustive_marker : __sabi_re::GetStaticEquivalent_, @@ -659,20 +629,20 @@ pub(crate) fn tokenize_enum_info<'a>( >; } - impl #impl_generics #name #ty_generics + impl #impl_generics #name #ty_generics #where_clause { const _SABI_NE_DISCR_CNSNT_STD_:&'static[#discriminant_type]= #discriminant_tokens; } - unsafe impl #impl_generics __sabi_re::GetEnumInfo for #name #ty_generics + unsafe impl #impl_generics __sabi_re::GetEnumInfo for #name #ty_generics #where_clause { type Discriminant=#discriminant_type; type DefaultStorage=#enum_storage; - + type DefaultInterface=#default_interface; const ENUM_INFO:&'static __sabi_re::EnumInfo= @@ -687,19 +657,19 @@ pub(crate) fn tokenize_enum_info<'a>( } fn is_valid_discriminant(discriminant:#discriminant_type)->bool{ - #( - ( - Self::_SABI_NE_DISCR_CNSNT_STD_[#start_discrs] <= discriminant && + #( + ( + Self::_SABI_NE_DISCR_CNSNT_STD_[#start_discrs] <= discriminant && discriminant <= Self::_SABI_NE_DISCR_CNSNT_STD_[#end_discrs] - )|| + )|| )* false } } - unsafe impl<#generics_header> - __sabi_re::GetNonExhaustive<__Storage> + unsafe impl<#generics_header> + __sabi_re::GetNonExhaustive<__Storage> for #name <#generics_use> #where_clause { @@ -707,11 +677,12 @@ pub(crate) fn tokenize_enum_info<'a>( } - ).to_tokens(ts); + ) + .to_tokens(ts); if !this.assert_nonexh.is_empty() { - let tests_function=parse_str_as_ident(&format!("{}_storage_assertions",name)); - let assertions=this.assert_nonexh.iter().cloned(); + let tests_function = parse_str_as_ident(&format!("{}_storage_assertions", name)); + let assertions = this.assert_nonexh.iter().cloned(); quote!( #[test] fn #tests_function(){ @@ -721,25 +692,24 @@ pub(crate) fn tokenize_enum_info<'a>( assert_nonexhaustive::<#assertions>(); )* } - ).to_tokens(ts); + ) + .to_tokens(ts); } match &this.enum_interface { - Some(EnumInterface::New(NewEnumInterface{impld,unimpld}))=>{ - let enum_interface=parse_str_as_ident(&format!("{}_Interface",name)); - - let priv_assocty=private_associated_type(); + Some(EnumInterface::New(NewEnumInterface { impld, unimpld })) => { + let enum_interface = parse_str_as_ident(&format!("{}_Interface", name)); + + let priv_assocty = private_associated_type(); - let impld_a=impld.iter(); - let impld_b=impld.iter(); + let impld_a = impld.iter(); + let impld_b = impld.iter(); - let unimpld_a=unimpld.iter(); - let unimpld_b=unimpld.iter(); + let unimpld_a = unimpld.iter(); + let unimpld_b = unimpld.iter(); - let const_ident=parse_str_as_ident(&format!( - "_impl_InterfaceType_constant_{}", - name, - )); + let const_ident = + parse_str_as_ident(&format!("_impl_InterfaceType_constant_{}", name,)); quote!( const #const_ident:()={ @@ -756,10 +726,11 @@ pub(crate) fn tokenize_enum_info<'a>( type #priv_assocty=(); } }; - ).to_tokens(ts); + ) + .to_tokens(ts); } - Some(EnumInterface::Old{..})=>{} - None=>{} + Some(EnumInterface::Old { .. }) => {} + None => {} } })) -} \ No newline at end of file +} diff --git a/abi_stable_derive/src/stable_abi/prefix_types.rs b/abi_stable_derive/src/stable_abi/prefix_types.rs index 4f052048..e5d5d7d9 100644 --- a/abi_stable_derive/src/stable_abi/prefix_types.rs +++ b/abi_stable_derive/src/stable_abi/prefix_types.rs @@ -4,55 +4,42 @@ Code generation for prefix-types. */ - use abi_stable_shared::const_utils::low_bit_mask_u64; -use core_extensions::{ - SelfOps, - matches, -}; +use core_extensions::{matches, SelfOps}; -use syn::{ - punctuated::Punctuated, - Ident, - WherePredicate, - TypeParamBound, - Visibility, -}; +use syn::{punctuated::Punctuated, Ident, TypeParamBound, Visibility, WherePredicate}; -use quote::{ToTokens,quote_spanned}; +use quote::{quote_spanned, ToTokens}; use as_derive_utils::{ - datastructure::{DataStructure,Field,FieldMap,FieldIndex}, - to_token_fn::ToTokenFnMut, + datastructure::{DataStructure, Field, FieldIndex, FieldMap}, return_spanned_err, + to_token_fn::ToTokenFnMut, }; use crate::*; -use crate::{ - literals_constructors::rstr_tokenizer, - parse_utils::parse_str_as_ident, -}; +use crate::{literals_constructors::rstr_tokenizer, parse_utils::parse_str_as_ident}; use super::{ - CommonTokens, - attribute_parsing::{StabilityKind,StableAbiOptions}, + attribute_parsing::{StabilityKind, StableAbiOptions}, reflection::FieldAccessor, + CommonTokens, }; /// Configuration for code generation related to prefix-types. -pub(crate) struct PrefixKind<'a>{ - pub(crate) first_suffix_field:FirstSuffixField, - pub(crate) prefix_ref:&'a Ident, +pub(crate) struct PrefixKind<'a> { + pub(crate) first_suffix_field: FirstSuffixField, + pub(crate) prefix_ref: &'a Ident, pub(crate) prefix_fields_struct: &'a Ident, - pub(crate) prefix_bounds:Vec, - pub(crate) fields:FieldMap>, - pub(crate) accessor_bounds:FieldMap>, - pub(crate) cond_field_indices:Vec, - pub(crate) enable_field_if:Vec<&'a syn::Expr>, - pub(crate) unconditional_bit_mask:u64, - pub(crate) prefix_field_conditionality_mask:u64, + pub(crate) prefix_bounds: Vec, + pub(crate) fields: FieldMap>, + pub(crate) accessor_bounds: FieldMap>, + pub(crate) cond_field_indices: Vec, + pub(crate) enable_field_if: Vec<&'a syn::Expr>, + pub(crate) unconditional_bit_mask: u64, + pub(crate) prefix_field_conditionality_mask: u64, } pub(crate) struct PrefixKindCtor<'a> { @@ -67,40 +54,39 @@ pub(crate) struct PrefixKindCtor<'a> { pub(crate) accessor_bounds: FieldMap>, } -impl<'a> PrefixKindCtor<'a>{ - pub fn make(self)->PrefixKind<'a>{ +impl<'a> PrefixKindCtor<'a> { + pub fn make(self) -> PrefixKind<'a> { let ctor = self; - let mut cond_field_indices=Vec::::new(); - let mut enable_field_if=Vec::<&syn::Expr>::new(); - let mut unconditional_bit_mask=0u64; - let mut conditional_bit_mask=0u64; - - for (index,field) in ctor.fields.iter() { - let field_i=index.pos; - match (|| field.to_maybe_accessor()?.accessible_if )() { - Some(cond)=>{ + let mut cond_field_indices = Vec::::new(); + let mut enable_field_if = Vec::<&syn::Expr>::new(); + let mut unconditional_bit_mask = 0u64; + let mut conditional_bit_mask = 0u64; + + for (index, field) in ctor.fields.iter() { + let field_i = index.pos; + match (|| field.to_maybe_accessor()?.accessible_if)() { + Some(cond) => { cond_field_indices.push(field_i); enable_field_if.push(cond); - conditional_bit_mask|=1u64<{ - unconditional_bit_mask|=1u64< { + unconditional_bit_mask |= 1u64 << field_i; } } } - let prefix_field_conditionality_mask= + let prefix_field_conditionality_mask = conditional_bit_mask & low_bit_mask_u64(ctor.first_suffix_field.field_pos as u32); - - PrefixKind{ + PrefixKind { first_suffix_field: ctor.first_suffix_field, - prefix_ref: ctor.prefix_ref.unwrap_or_else(||{ - let ident = format!("{}_Ref",ctor.struct_name); + prefix_ref: ctor.prefix_ref.unwrap_or_else(|| { + let ident = format!("{}_Ref", ctor.struct_name); ctor.arenas.alloc(parse_str_as_ident(&ident)) }), - prefix_fields_struct: ctor.prefix_fields.unwrap_or_else(||{ - let ident = format!("{}_Prefix",ctor.struct_name); + prefix_fields_struct: ctor.prefix_fields.unwrap_or_else(|| { + let ident = format!("{}_Prefix", ctor.struct_name); ctor.arenas.alloc(parse_str_as_ident(&ident)) }), prefix_bounds: ctor.prefix_bounds, @@ -114,152 +100,141 @@ impl<'a> PrefixKindCtor<'a>{ } } - - /// Used while parsing the prefix-type-related attributes on fields. -#[derive(Copy,Default, Clone)] -pub(crate) struct PrefixKindField<'a>{ - pub(crate) accessible_if:Option<&'a syn::Expr>, - pub(crate) on_missing:Option>, +#[derive(Copy, Default, Clone)] +pub(crate) struct PrefixKindField<'a> { + pub(crate) accessible_if: Option<&'a syn::Expr>, + pub(crate) on_missing: Option>, } - /// The different types of prefix-type accessors. -#[derive(Debug,Copy, Clone, PartialEq, Eq)] -pub enum AccessorOrMaybe<'a>{ +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub enum AccessorOrMaybe<'a> { /// Unconditionally returns the field. Accessor, /// Either optionally returns the field,or it does some action when it's missing. - Maybe(MaybeAccessor<'a>) + Maybe(MaybeAccessor<'a>), } -/// Describes a field accessor which is either optional or +/// Describes a field accessor which is either optional or /// does some action when the field is missing. -#[derive(Debug,Copy, Clone, Default, PartialEq, Eq)] -pub struct MaybeAccessor<'a>{ +#[derive(Debug, Copy, Clone, Default, PartialEq, Eq)] +pub struct MaybeAccessor<'a> { /// If Some,it uses a bool constant to determine whether a field is accessible. - accessible_if:Option<&'a syn::Expr>, + accessible_if: Option<&'a syn::Expr>, /// What the accessor method does when the field is missing. - on_missing:OnMissingField<'a>, + on_missing: OnMissingField<'a>, } - - #[derive(Copy, Clone, Default, PartialEq, Eq)] -pub(crate) struct FirstSuffixField{ - pub(crate) field_pos:usize, +pub(crate) struct FirstSuffixField { + pub(crate) field_pos: usize, } - /// What happens in a Prefix-type field getter if the field does not exist. -#[derive(Debug,Copy,Clone, PartialEq, Eq, Hash)] -pub(crate) enum OnMissingField<'a>{ +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +pub(crate) enum OnMissingField<'a> { /// Returns an `Option`,where it returns None if the field is absent. ReturnOption, /// Panics with a default message. Panic, /// Evaluates `function()`,and returns the return value of the function. - With{ - function:&'a syn::Path, - }, + With { function: &'a syn::Path }, /// Returns `some_expression`. - Value{ - value:&'a syn::Expr, - }, + Value { value: &'a syn::Expr }, /// Returns Default::default Default_, } -impl<'a> Default for OnMissingField<'a>{ - fn default()->Self{ +impl<'a> Default for OnMissingField<'a> { + fn default() -> Self { OnMissingField::ReturnOption } } - -impl<'a> AccessorOrMaybe<'a>{ +impl<'a> AccessorOrMaybe<'a> { pub(crate) fn new( - field_i:FieldIndex, - first_suffix_field:FirstSuffixField, - pkf:PrefixKindField<'a>, - default_omf:OnMissingField<'a>, - )->Self{ - if field_i.pos < first_suffix_field.field_pos && - pkf.accessible_if.is_none() && - pkf.on_missing!=Some(OnMissingField::ReturnOption) + field_i: FieldIndex, + first_suffix_field: FirstSuffixField, + pkf: PrefixKindField<'a>, + default_omf: OnMissingField<'a>, + ) -> Self { + if field_i.pos < first_suffix_field.field_pos + && pkf.accessible_if.is_none() + && pkf.on_missing != Some(OnMissingField::ReturnOption) { AccessorOrMaybe::Accessor - }else{ - AccessorOrMaybe::Maybe(MaybeAccessor{ - accessible_if:pkf.accessible_if, - on_missing:pkf.on_missing.unwrap_or(default_omf) + } else { + AccessorOrMaybe::Maybe(MaybeAccessor { + accessible_if: pkf.accessible_if, + on_missing: pkf.on_missing.unwrap_or(default_omf), }) } } #[allow(dead_code)] - pub(crate) fn is_conditional(&self)->bool{ - self.to_maybe_accessor().map_or(false,|x| x.accessible_if.is_some() ) + pub(crate) fn is_conditional(&self) -> bool { + self.to_maybe_accessor() + .map_or(false, |x| x.accessible_if.is_some()) } /// Converts this to a MaybeAccessor,returning None if it is not the `Maybe` variant. - pub(crate) fn to_maybe_accessor(&self)->Option>{ + pub(crate) fn to_maybe_accessor(&self) -> Option> { match *self { - AccessorOrMaybe::Maybe(x)=>Some(x), - _=>None, + AccessorOrMaybe::Maybe(x) => Some(x), + _ => None, } } #[allow(dead_code)] - pub(crate) fn is_maybe_accessor(&self)->bool{ - matches!(self, AccessorOrMaybe::Maybe{..}) + pub(crate) fn is_maybe_accessor(&self) -> bool { + matches!(self, AccessorOrMaybe::Maybe { .. }) } } - -impl<'a> PrefixKind<'a>{ +impl<'a> PrefixKind<'a> { /// Gets the accessibility for a field,used for (very basic) runtime reflection. - pub(crate) fn field_accessor(&self,field:&Field<'a>)->FieldAccessor<'a>{ - use self::{OnMissingField as OMF}; + pub(crate) fn field_accessor(&self, field: &Field<'a>) -> FieldAccessor<'a> { + use self::OnMissingField as OMF; match self.fields[field] { - AccessorOrMaybe::Accessor=> - FieldAccessor::Method{name:None}, - AccessorOrMaybe::Maybe(MaybeAccessor{on_missing,..})=> - match on_missing { - OMF::ReturnOption=> - FieldAccessor::MethodOption, - OMF::Panic{..}|OMF::With{..}|OMF::Value{..}|OMF::Default_=> - FieldAccessor::Method{name:None}, - }, + AccessorOrMaybe::Accessor => FieldAccessor::Method { name: None }, + AccessorOrMaybe::Maybe(MaybeAccessor { on_missing, .. }) => match on_missing { + OMF::ReturnOption => FieldAccessor::MethodOption, + OMF::Panic { .. } | OMF::With { .. } | OMF::Value { .. } | OMF::Default_ => { + FieldAccessor::Method { name: None } + } + }, } } } - //////////////////////////////////////////////////////////////////////////////// ///// Code generation //////////////////////////////////////////////////////////////////////////////// - /** Returns a value which for a prefix-type . */ pub(crate) fn prefix_type_tokenizer<'a>( - module:&'a Ident, - mono_type_layout:&'a Ident, - ds:&'a DataStructure<'a>, - config:&'a StableAbiOptions<'a>, - _ctokens:&'a CommonTokens<'a>, -)-> Result { - if matches!(config.kind, StabilityKind::Prefix{..}) { - if ds.variants.get(0).map_or(false,|struct_| struct_.fields.len() > 64 ) { + module: &'a Ident, + mono_type_layout: &'a Ident, + ds: &'a DataStructure<'a>, + config: &'a StableAbiOptions<'a>, + _ctokens: &'a CommonTokens<'a>, +) -> Result { + if matches!(config.kind, StabilityKind::Prefix { .. }) { + if ds + .variants + .get(0) + .map_or(false, |struct_| struct_.fields.len() > 64) + { return_spanned_err!( ds.name, "`#[sabi(kind(Prefix(..)))]` structs cannot have more than 64 fields." ); } - + if config.repr.is_packed.is_some() { return_spanned_err!( ds.name, @@ -268,48 +243,51 @@ pub(crate) fn prefix_type_tokenizer<'a>( } } - - Ok(ToTokenFnMut::new(move|ts|{ - let struct_=match ds.variants.get(0) { - Some(x)=>x, - None=>return, + Ok(ToTokenFnMut::new(move |ts| { + let struct_ = match ds.variants.get(0) { + Some(x) => x, + None => return, }; - let prefix=match &config.kind { - StabilityKind::Prefix(prefix)=>prefix, - _=>return, + let prefix = match &config.kind { + StabilityKind::Prefix(prefix) => prefix, + _ => return, }; let first_suffix_field = prefix.first_suffix_field.field_pos; let prefix_fields_struct = &prefix.prefix_fields_struct; - let doc_hidden_attr=config.doc_hidden_attr; + let doc_hidden_attr = config.doc_hidden_attr; - let deriving_name=ds.name; - let (ref impl_generics,ref ty_generics,ref where_clause) = ds.generics.split_for_impl(); + let deriving_name = ds.name; + let (ref impl_generics, ref ty_generics, ref where_clause) = ds.generics.split_for_impl(); - let empty_preds=Punctuated::new(); - let where_preds=where_clause.as_ref().map_or(&empty_preds,|x|&x.predicates).into_iter(); - let where_preds_a=where_preds.clone(); - let where_preds_b=where_preds.clone(); - let where_preds_c=where_preds.clone(); + let empty_preds = Punctuated::new(); + let where_preds = where_clause + .as_ref() + .map_or(&empty_preds, |x| &x.predicates) + .into_iter(); + let where_preds_a = where_preds.clone(); + let where_preds_b = where_preds.clone(); + let where_preds_c = where_preds.clone(); // let where_preds_d0=where_preds.clone(); // let where_preds_d1=where_preds.clone(); - let where_preds_e=where_preds.clone(); - let where_preds_f=where_preds.clone(); - let where_preds_rl=where_preds.clone(); - let where_preds_r2=where_preds.clone(); - let prefix_bounds=&prefix.prefix_bounds; + let where_preds_e = where_preds.clone(); + let where_preds_f = where_preds.clone(); + let where_preds_rl = where_preds.clone(); + let where_preds_r2 = where_preds.clone(); + let prefix_bounds = &prefix.prefix_bounds; + + let stringified_deriving_name = deriving_name.to_string(); - let stringified_deriving_name=deriving_name.to_string(); - - let stringified_generics=(&ty_generics).into_token_stream().to_string(); - let stringified_generics_tokenizer=rstr_tokenizer(&stringified_generics); + let stringified_generics = (&ty_generics).into_token_stream().to_string(); + let stringified_generics_tokenizer = rstr_tokenizer(&stringified_generics); - let is_ds_pub=matches!(ds.vis, Visibility::Public{..}) && doc_hidden_attr.is_none(); + let is_ds_pub = matches!(ds.vis, Visibility::Public { .. }) && doc_hidden_attr.is_none(); - let prefix_ref_docs=if is_ds_pub { - format!("\ + let prefix_ref_docs = if is_ds_pub { + format!( + "\ This is the pointer to the prefix of [{deriving_name}{generics}](./struct.{deriving_name}.html). @@ -328,36 +306,37 @@ or the ", //prefix_name=prefix.prefix_ref, - deriving_name=stringified_deriving_name, - generics=stringified_generics, + deriving_name = stringified_deriving_name, + generics = stringified_generics, ) - }else{ + } else { String::new() }; - let prefix_fields_docs=if is_ds_pub { - format!("\ + let prefix_fields_docs = if is_ds_pub { + format!( + "\ This is the prefix fields of [{deriving_name}{generics}](./struct.{deriving_name}.html), accessible through [`{prefix_name}`](./struct.{prefix_name}.html), with `.0.prefix()`. **This is automatically generated documentation,by the StableAbi derive macro**. ", - prefix_name=prefix.prefix_ref, - deriving_name=stringified_deriving_name, - generics=stringified_generics, + prefix_name = prefix.prefix_ref, + deriving_name = stringified_deriving_name, + generics = stringified_generics, ) - }else{ + } else { String::new() }; - - let prefix_ref=prefix.prefix_ref; + + let prefix_ref = prefix.prefix_ref; // Generating the `` struct { - let vis=ds.vis; - let generics=ds.generics; - + let vis = ds.vis; + let generics = ds.generics; + let alignemnt = if let Some(alignemnt) = config.repr.is_aligned { let alignemnt = as_derive_utils::utils::uint_lit(alignemnt.into()); quote!(, align(#alignemnt)) @@ -367,15 +346,16 @@ accessible through [`{prefix_name}`](./struct.{prefix_name}.html), with `.0.pref let prefix_field_iter = struct_.fields[..first_suffix_field].iter(); // This uses `field_` for tuple fields - let prefix_field_vis = prefix_field_iter.clone() - .map(|f|ToTokenFnMut::new(move|ts|{ + let prefix_field_vis = prefix_field_iter.clone().map(|f| { + ToTokenFnMut::new(move |ts| { let vis = f.vis; if AccessorOrMaybe::Accessor == prefix.fields[f] { vis.to_tokens(ts); } - })); - let prefix_field = prefix_field_iter.clone().map(|f| f.pat_ident() ); - let prefix_field_ty = prefix_field_iter.clone().map(|f| f.ty ); + }) + }); + let prefix_field = prefix_field_iter.clone().map(|f| f.pat_ident()); + let prefix_field_ty = prefix_field_iter.clone().map(|f| f.ty); let (_, ty_generics, where_clause) = generics.split_for_impl(); @@ -392,11 +372,11 @@ accessible through [`{prefix_name}`](./struct.{prefix_name}.html), with `.0.pref #doc_hidden_attr #[doc=#prefix_fields_docs] // A struct with all the prefix fields in the deriving type - // - // A field being in the prefix doesn't mean that it's + // + // A field being in the prefix doesn't mean that it's // unconditionally accessible, it just means that it won't cause a SEGFAULT. #[repr(C #alignemnt)] - #vis struct #prefix_fields_struct #generics + #vis struct #prefix_fields_struct #generics #where_clause { #( #prefix_field_vis #prefix_field: #prefix_field_ty,)* @@ -409,138 +389,146 @@ accessible through [`{prefix_name}`](./struct.{prefix_name}.html), with `.0.pref __sabi_usize_alignment: [usize; 0], __sabi_pt_unbounds: #module::__sabi_re::NotCopyNotClone, } - ).to_tokens(ts); + ) + .to_tokens(ts); } - - let mut accessor_buffer=String::new(); + let mut accessor_buffer = String::new(); - let mut uncond_acc_docs=Vec::::new(); - let mut cond_acc_docs=Vec::::new(); - let mut field_index_for=Vec::new(); - let offset_consts: &[syn::Ident] = &struct_.fields.iter() - .map(|f|{ - parse_str_as_ident(&format!("__sabi_offset_for_{}", f.pat_ident())) - }) + let mut uncond_acc_docs = Vec::::new(); + let mut cond_acc_docs = Vec::::new(); + let mut field_index_for = Vec::new(); + let offset_consts: &[syn::Ident] = &struct_ + .fields + .iter() + .map(|f| parse_str_as_ident(&format!("__sabi_offset_for_{}", f.pat_ident()))) .collect::>(); - // Creates the docs for the accessor functions. // Creates the identifiers for constants associated with each field. for field in struct_.fields.iter() { + use self::AccessorOrMaybe as AOM; use std::fmt::Write; - use self::{AccessorOrMaybe as AOM}; - let mut acc_doc_buffer =String::new(); - let acc_on_missing=prefix.fields[field]; - if is_ds_pub{ - let _=write!( + let mut acc_doc_buffer = String::new(); + let acc_on_missing = prefix.fields[field]; + if is_ds_pub { + let _ = write!( acc_doc_buffer, "Accessor method for the `{deriving_name}::{field_name}` field.", - deriving_name=deriving_name, - field_name=field.pat_ident(), + deriving_name = deriving_name, + field_name = field.pat_ident(), ); - match acc_on_missing { - AOM::Accessor=> - acc_doc_buffer.push_str( - "This is for a field which always exists." - ), - AOM::Maybe(MaybeAccessor{on_missing:OnMissingField::ReturnOption,..})=> - acc_doc_buffer.push_str( - "Returns `Some(field_value)` if the field exists,\ + AOM::Accessor => { + acc_doc_buffer.push_str("This is for a field which always exists.") + } + AOM::Maybe(MaybeAccessor { + on_missing: OnMissingField::ReturnOption, + .. + }) => acc_doc_buffer.push_str( + "Returns `Some(field_value)` if the field exists,\ `None` if it does not.\ - " - ), - AOM::Maybe(MaybeAccessor{on_missing:OnMissingField::Panic,..})=> - acc_doc_buffer.push_str( - "\n\n# Panic\n\nPanics if the field does not exist." - ), - AOM::Maybe(MaybeAccessor{on_missing:OnMissingField::With{function},..})=> - write!( - acc_doc_buffer, - "Returns `{function}()` if the field does not exist.", - function=(&function).into_token_stream().to_string() - ).drop_(), - AOM::Maybe(MaybeAccessor{on_missing:OnMissingField::Value{..},..})=> - acc_doc_buffer.push_str("\ + ", + ), + AOM::Maybe(MaybeAccessor { + on_missing: OnMissingField::Panic, + .. + }) => acc_doc_buffer + .push_str("\n\n# Panic\n\nPanics if the field does not exist."), + AOM::Maybe(MaybeAccessor { + on_missing: OnMissingField::With { function }, + .. + }) => write!( + acc_doc_buffer, + "Returns `{function}()` if the field does not exist.", + function = (&function).into_token_stream().to_string() + ) + .drop_(), + AOM::Maybe(MaybeAccessor { + on_missing: OnMissingField::Value { .. }, + .. + }) => acc_doc_buffer.push_str( + "\ Returns a default value (not Default::default()) \ if the field does not exist.\ - "), - AOM::Maybe(MaybeAccessor{on_missing:OnMissingField::Default_,..})=> - acc_doc_buffer.push_str( - "Returns `Default::default()` if the field does not exist." - ), + ", + ), + AOM::Maybe(MaybeAccessor { + on_missing: OnMissingField::Default_, + .. + }) => acc_doc_buffer + .push_str("Returns `Default::default()` if the field does not exist."), }; } - - if config.with_field_indices{ - let field_name=field.pat_ident(); - let mut new_ident=parse_str_as_ident(&format!("field_index_for_{}",field_name)); + + if config.with_field_indices { + let field_name = field.pat_ident(); + let mut new_ident = parse_str_as_ident(&format!("field_index_for_{}", field_name)); new_ident.set_span(field_name.span()); field_index_for.push(new_ident); } - + match acc_on_missing { - AOM::Accessor =>{ + AOM::Accessor => { uncond_acc_docs.push(acc_doc_buffer); } - AOM::Maybe{..}=>{ + AOM::Maybe { .. } => { cond_acc_docs.push(acc_doc_buffer); } } } - let mut unconditional_accessors=Vec::new(); - let mut conditional_accessors=Vec::new(); - + let mut unconditional_accessors = Vec::new(); + let mut conditional_accessors = Vec::new(); + // Creates TokenStreams for each accessor function. - for (field_i,field)in struct_.fields.iter().enumerate() { + for (field_i, field) in struct_.fields.iter().enumerate() { use std::fmt::Write; accessor_buffer.clear(); - write!(accessor_buffer,"{}",field.pat_ident()).drop_(); - let vis=field.vis; - let mut getter_name=syn::parse_str::(&*accessor_buffer).expect("BUG"); + write!(accessor_buffer, "{}", field.pat_ident()).drop_(); + let vis = field.vis; + let mut getter_name = syn::parse_str::(&*accessor_buffer).expect("BUG"); getter_name.set_span(field.pat_ident().span()); - let field_name=field.pat_ident(); - let field_span=field_name.span(); - let ty=field.ty; + let field_name = field.pat_ident(); + let field_span = field_name.span(); + let ty = field.ty; - let accessor_bounds=&prefix.accessor_bounds[field]; + let accessor_bounds = &prefix.accessor_bounds[field]; - let field_where_clause=if accessor_bounds.is_empty() { - None - }else{ - Some(quote!(where #ty:)) + let field_where_clause = if accessor_bounds.is_empty() { + None + } else { + Some(quote!(where #ty:)) }; match prefix.fields[field] { - AccessorOrMaybe::Accessor=>{ - unconditional_accessors.push(quote_spanned!{field_span=> + AccessorOrMaybe::Accessor => { + unconditional_accessors.push(quote_spanned! {field_span=> #vis fn #getter_name(&self)->#ty #field_where_clause #( #accessor_bounds+ )* { self.0.prefix().#field_name } }) - }, - AccessorOrMaybe::Maybe(maybe_accessor)=>{ + } + AccessorOrMaybe::Maybe(maybe_accessor) => { let field_offset = &offset_consts[field_i]; - let on_missing_field=maybe_accessor.on_missing; - let is_optional=on_missing_field==OnMissingField::ReturnOption; + let on_missing_field = maybe_accessor.on_missing; + let is_optional = on_missing_field == OnMissingField::ReturnOption; - let return_ty=if is_optional { + let return_ty = if is_optional { quote!( Option< #ty > ) - }else{ + } else { quote!( #ty) }; - let else_=match on_missing_field { - OnMissingField::ReturnOption=>quote_spanned!{field_span=> - return None + let else_ = match on_missing_field { + OnMissingField::ReturnOption => quote_spanned! {field_span=> + return None }, - OnMissingField::Panic=>quote_spanned!(field_span=> + OnMissingField::Panic => quote_spanned!(field_span=> __sabi_re::panic_on_missing_field_ty::< #deriving_name #ty_generics >( @@ -548,24 +536,24 @@ accessible through [`{prefix_name}`](./struct.{prefix_name}.html), with `.0.pref self._prefix_type_layout(), ) ), - OnMissingField::With{function}=>quote_spanned!{field_span=> + OnMissingField::With { function } => quote_spanned! {field_span=> #function() }, - OnMissingField::Value{value}=>quote_spanned!{field_span=> + OnMissingField::Value { value } => quote_spanned! {field_span=> (#value) }, - OnMissingField::Default_=>quote_spanned!{field_span=> + OnMissingField::Default_ => quote_spanned! {field_span=> Default::default() }, }; - let with_val=if is_optional { + let with_val = if is_optional { quote_spanned!(field_span=> Some(val) ) - }else{ + } else { quote_spanned!(field_span=> val ) }; - conditional_accessors.push(quote_spanned!{field_span=> + conditional_accessors.push(quote_spanned! {field_span=> #vis fn #getter_name(&self)->#return_ty #field_where_clause #( #accessor_bounds+ )* { @@ -587,16 +575,16 @@ accessible through [`{prefix_name}`](./struct.{prefix_name}.html), with `.0.pref } } - let cond_field_indices=&prefix.cond_field_indices; - let enable_field_if=&prefix.enable_field_if; - let unconditional_bit_mask=&prefix.unconditional_bit_mask; + let cond_field_indices = &prefix.cond_field_indices; + let enable_field_if = &prefix.enable_field_if; + let unconditional_bit_mask = &prefix.unconditional_bit_mask; + + let cond_field_indices = cond_field_indices.iter(); + let enable_field_if = enable_field_if.iter(); - let cond_field_indices=cond_field_indices.iter(); - let enable_field_if=enable_field_if.iter(); - - let field_i_a=0u8..; + let field_i_a = 0u8..; - let mut pt_layout_ident=parse_str_as_ident(&format!("__sabi_PT_LAYOUT{}",deriving_name)); + let mut pt_layout_ident = parse_str_as_ident(&format!("__sabi_PT_LAYOUT{}", deriving_name)); pt_layout_ident.set_span(deriving_name.span()); quote!(const _: () = { @@ -650,11 +638,12 @@ accessible through [`{prefix_name}`](./struct.{prefix_name}.html), with `.0.pref #field_i_a; )* } - };).to_tokens(ts); + };) + .to_tokens(ts); let first_offset = if let Some(constant) = offset_consts.first() { quote!( - const #constant: usize = + const #constant: usize = __sabi_re::next_field_offset::< __sabi_re::WithMetadata_< #prefix_fields_struct #ty_generics, @@ -662,15 +651,15 @@ accessible through [`{prefix_name}`](./struct.{prefix_name}.html), with `.0.pref >, __sabi_re::PrefixMetadata<(),()>, #prefix_fields_struct #ty_generics, - >(0); + >(0); ) - }else{ + } else { quote!() }; let prev_offsets = offset_consts.iter(); let curr_offsets = prev_offsets.clone().skip(1); - let prev_tys = struct_.fields.iter().map(|f| f.ty ); + let prev_tys = struct_.fields.iter().map(|f| f.ty); let curr_tys = prev_tys.clone().skip(1); quote!( const _: () = { @@ -774,6 +763,7 @@ accessible through [`{prefix_name}`](./struct.{prefix_name}.html), with `.0.pref } } - };).to_tokens(ts); + };) + .to_tokens(ts); })) -} \ No newline at end of file +} diff --git a/abi_stable_derive/src/stable_abi/reflection.rs b/abi_stable_derive/src/stable_abi/reflection.rs index 2ef58068..dd776878 100644 --- a/abi_stable_derive/src/stable_abi/reflection.rs +++ b/abi_stable_derive/src/stable_abi/reflection.rs @@ -1,6 +1,4 @@ -use super::{ - SharedVars, -}; +use super::SharedVars; use syn::Ident; @@ -9,50 +7,37 @@ pub enum FieldAccessor<'a> { /// Accessible with `self.field_name` Direct, /// Accessible with `fn field_name(&self)->FieldType` - Method{ - name:Option<&'a Ident>, - }, + Method { name: Option<&'a Ident> }, /// Accessible with `fn field_name(&self)->Option` MethodOption, /// This field is completely inaccessible. Opaque, } - -impl<'a> FieldAccessor<'a>{ - pub(crate) fn compress(self,shared_vars:&mut SharedVars<'a>)->CompFieldAccessor{ +impl<'a> FieldAccessor<'a> { + pub(crate) fn compress(self, shared_vars: &mut SharedVars<'a>) -> CompFieldAccessor { match self { - FieldAccessor::Direct=>{ - CompFieldAccessor::DIRECT - } - FieldAccessor::Method{name:None}=>{ - CompFieldAccessor::METHOD - } - FieldAccessor::Method{name:Some(name)}=>{ - let _=shared_vars.push_ident(name); + FieldAccessor::Direct => CompFieldAccessor::DIRECT, + FieldAccessor::Method { name: None } => CompFieldAccessor::METHOD, + FieldAccessor::Method { name: Some(name) } => { + let _ = shared_vars.push_ident(name); CompFieldAccessor::METHOD_NAMED } - FieldAccessor::MethodOption=>{ - CompFieldAccessor::METHOD_OPTION - } - FieldAccessor::Opaque=>{ - CompFieldAccessor::OPAQUE - } + FieldAccessor::MethodOption => CompFieldAccessor::METHOD_OPTION, + FieldAccessor::Opaque => CompFieldAccessor::OPAQUE, } } } -abi_stable_shared::declare_comp_field_accessor!{ +abi_stable_shared::declare_comp_field_accessor! { attrs=[] } - //////////////////////////////////////////////////////////////////////////////// - -#[derive(Debug,Copy,Clone,PartialEq,Eq)] -pub enum ModReflMode{ +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub enum ModReflMode { Module, Opaque, DelegateDeref(T), -} \ No newline at end of file +} diff --git a/abi_stable_derive/src/stable_abi/repr_attrs.rs b/abi_stable_derive/src/stable_abi/repr_attrs.rs index be151bb3..74f97bd1 100644 --- a/abi_stable_derive/src/stable_abi/repr_attrs.rs +++ b/abi_stable_derive/src/stable_abi/repr_attrs.rs @@ -1,47 +1,38 @@ #[allow(unused_imports)] -use core_extensions::{matches,SelfOps}; -use proc_macro2::{TokenStream,Span}; -use quote::{quote,ToTokens}; +use core_extensions::{matches, SelfOps}; +use proc_macro2::{Span, TokenStream}; +use quote::{quote, ToTokens}; -use as_derive_utils::{ - to_token_fn::ToTokenFnMut, - syn_err, - return_syn_err, -}; +use as_derive_utils::{return_syn_err, syn_err, to_token_fn::ToTokenFnMut}; -use crate::{ - ignored_wrapper::Ignored, - literals_constructors::rslice_tokenizer, -}; +use crate::{ignored_wrapper::Ignored, literals_constructors::rslice_tokenizer}; use super::common_tokens::CommonTokens; - /// Used to parse ReprAttr from attributes. #[derive(Debug, Copy, Clone, PartialEq, Eq)] -pub struct UncheckedReprAttr{ +pub struct UncheckedReprAttr { is_aligned: Option, is_packed: Option, - repr_kind:Option, - repr_span:Ignored, - discriminant_repr:Option, + repr_kind: Option, + repr_span: Ignored, + discriminant_repr: Option, } -impl Default for UncheckedReprAttr{ - fn default()->Self{ +impl Default for UncheckedReprAttr { + fn default() -> Self { Self { is_aligned: None, is_packed: None, - repr_kind:None, - repr_span:Ignored::new(Span::call_site()), - discriminant_repr:None, + repr_kind: None, + repr_span: Ignored::new(Span::call_site()), + discriminant_repr: None, } } } - #[derive(Debug, Copy, Clone, PartialEq, Eq)] -pub enum UncheckedReprKind{ +pub enum UncheckedReprKind { C, Transparent, /// Means that only `repr(IntegerType)` was used. @@ -65,13 +56,12 @@ pub enum DiscriminantRepr { Isize, } - /// The representation attribute of the type. /// -/// This doesn't include `#[repr(align())]` since the alignment is +/// This doesn't include `#[repr(align())]` since the alignment is /// stored as part of TypeLayout anyway. #[derive(Debug, Copy, Clone, PartialEq, Eq)] -pub enum Repr{ +pub enum Repr { C(Option), Transparent, /// Means that only `repr(IntegerType)` was used. @@ -86,8 +76,7 @@ pub struct ReprAttr { pub variant: Repr, } - -pub(crate) static REPR_ERROR_MSG:&str="\n\ +pub(crate) static REPR_ERROR_MSG: &str = "\n\ the #[repr(..)] attribute must be one of the supported attributes:\n\ \t- #[repr(C)]\n\ \t- #[repr(transparent)]\n\ @@ -97,22 +86,21 @@ pub(crate) static REPR_ERROR_MSG:&str="\n\ \t- #[repr(align())]\n\ "; - -impl UncheckedReprAttr{ - pub fn set_aligned(&mut self, alignment: u32)-> Result<(),syn::Error> { +impl UncheckedReprAttr { + pub fn set_aligned(&mut self, alignment: u32) -> Result<(), syn::Error> { self.is_aligned = Some(alignment); Ok(()) } - pub fn set_packed(&mut self, packing: Option)-> Result<(),syn::Error> { + pub fn set_packed(&mut self, packing: Option) -> Result<(), syn::Error> { self.is_packed = packing.or(Some(1)); Ok(()) } pub fn set_repr_kind( &mut self, - repr_kind:UncheckedReprKind, - repr_span:proc_macro2::Span - )-> Result<(),syn::Error> { - if let Some(from)=self.discriminant_repr { + repr_kind: UncheckedReprKind, + repr_span: proc_macro2::Span, + ) -> Result<(), syn::Error> { + if let Some(from) = self.discriminant_repr { return_syn_err!( repr_span, "Attempting to override {:?} representation with {:?}.", @@ -120,16 +108,16 @@ impl UncheckedReprAttr{ repr_kind ); } - self.repr_kind=Some(repr_kind); - self.repr_span.value=repr_span; + self.repr_kind = Some(repr_kind); + self.repr_span.value = repr_span; Ok(()) } pub fn set_discriminant_repr( &mut self, - discriminant_repr:DiscriminantRepr, - repr_span:proc_macro2::Span - )-> Result<(),syn::Error> { - if let Some(x)=self.discriminant_repr { + discriminant_repr: DiscriminantRepr, + repr_span: proc_macro2::Span, + ) -> Result<(), syn::Error> { + if let Some(x) = self.discriminant_repr { return_syn_err!( repr_span, "Attempting to override {:?} representation with {:?}.", @@ -137,73 +125,67 @@ impl UncheckedReprAttr{ discriminant_repr ); } - self.repr_kind=self.repr_kind.or(Some(UncheckedReprKind::Int)); - self.repr_span.value=repr_span; + self.repr_kind = self.repr_kind.or(Some(UncheckedReprKind::Int)); + self.repr_span.value = repr_span; - self.discriminant_repr=Some(discriminant_repr); + self.discriminant_repr = Some(discriminant_repr); Ok(()) } } - -impl DiscriminantRepr{ +impl DiscriminantRepr { /// Gets a `DiscriminantRepr` from the identifier of an integer type. /// /// Returns None if the identifier is not a supported integer type. - pub fn from_ident(ident:&syn::Ident)->Option{ - if ident=="u8" { + pub fn from_ident(ident: &syn::Ident) -> Option { + if ident == "u8" { Some(DiscriminantRepr::U8) - }else if ident=="i8" { + } else if ident == "i8" { Some(DiscriminantRepr::I8) - }else if ident=="u16" { + } else if ident == "u16" { Some(DiscriminantRepr::U16) - }else if ident=="i16" { + } else if ident == "i16" { Some(DiscriminantRepr::I16) - }else if ident=="u32" { + } else if ident == "u32" { Some(DiscriminantRepr::U32) - }else if ident=="i32" { + } else if ident == "i32" { Some(DiscriminantRepr::I32) - }else if ident=="u64" { + } else if ident == "u64" { Some(DiscriminantRepr::U64) - }else if ident=="i64" { + } else if ident == "i64" { Some(DiscriminantRepr::I64) - }else if ident=="usize" { + } else if ident == "usize" { Some(DiscriminantRepr::Usize) - }else if ident=="isize" { + } else if ident == "isize" { Some(DiscriminantRepr::Isize) - }else{ + } else { None } } } - -impl ReprAttr{ - pub fn new(unchecked:UncheckedReprAttr)-> Result { - let span=unchecked.repr_span; - let is_aligned=unchecked.is_aligned; - let is_packed=unchecked.is_packed; - let ura:UncheckedReprKind=unchecked.repr_kind.ok_or_else(||{ - syn_err!(*span,"{}",REPR_ERROR_MSG) - })?; - let dr:Option=unchecked.discriminant_repr; - let variant = match (ura,dr) { - (UncheckedReprKind::C,x)=> - Repr::C(x), - (UncheckedReprKind::Transparent,None)=> - Repr::Transparent, - (UncheckedReprKind::Transparent,Some(_))=>{ +impl ReprAttr { + pub fn new(unchecked: UncheckedReprAttr) -> Result { + let span = unchecked.repr_span; + let is_aligned = unchecked.is_aligned; + let is_packed = unchecked.is_packed; + let ura: UncheckedReprKind = unchecked + .repr_kind + .ok_or_else(|| syn_err!(*span, "{}", REPR_ERROR_MSG))?; + let dr: Option = unchecked.discriminant_repr; + let variant = match (ura, dr) { + (UncheckedReprKind::C, x) => Repr::C(x), + (UncheckedReprKind::Transparent, None) => Repr::Transparent, + (UncheckedReprKind::Transparent, Some(_)) => { return_syn_err!( *span, "repr(transparent) cannot be combined with repr(IntegerType)", ) } - (UncheckedReprKind::Int,None)=> - panic!("Bug:(UncheckedReprKind::Int,None)"), - (UncheckedReprKind::Int,Some(x))=> - Repr::Int(x), + (UncheckedReprKind::Int, None) => panic!("Bug:(UncheckedReprKind::Int,None)"), + (UncheckedReprKind::Int, Some(x)) => Repr::Int(x), }; - Ok(Self{ + Ok(Self { span, variant, is_aligned, @@ -213,207 +195,195 @@ impl ReprAttr{ /// Gets the type of the discriminant determined by this representation attribute. /// Returns None if the representation is `#[repr(transparent)]`. - pub fn type_ident(&self)->Option{ - let int_repr=match self.variant { - Repr::C(None)=> - DiscriminantRepr::Isize, - Repr::C(Some(int_repr))|Repr::Int(int_repr)=> - int_repr, - Repr::Transparent=> - return None, + pub fn type_ident(&self) -> Option { + let int_repr = match self.variant { + Repr::C(None) => DiscriminantRepr::Isize, + Repr::C(Some(int_repr)) | Repr::Int(int_repr) => int_repr, + Repr::Transparent => return None, }; - let ty_lit=match int_repr { - DiscriminantRepr::U8 =>"u8", - DiscriminantRepr::U16=>"u16", - DiscriminantRepr::U32=>"u32", - DiscriminantRepr::U64=>"u64", - DiscriminantRepr::I8 =>"i8", - DiscriminantRepr::I16=>"i16", - DiscriminantRepr::I32=>"i32", - DiscriminantRepr::I64=>"i64", - DiscriminantRepr::Usize=>"usize", - DiscriminantRepr::Isize=>"isize", + let ty_lit = match int_repr { + DiscriminantRepr::U8 => "u8", + DiscriminantRepr::U16 => "u16", + DiscriminantRepr::U32 => "u32", + DiscriminantRepr::U64 => "u64", + DiscriminantRepr::I8 => "i8", + DiscriminantRepr::I16 => "i16", + DiscriminantRepr::I32 => "i32", + DiscriminantRepr::I64 => "i64", + DiscriminantRepr::Usize => "usize", + DiscriminantRepr::Isize => "isize", }; - Some(syn::Ident::new(ty_lit,Span::call_site())) + Some(syn::Ident::new(ty_lit, Span::call_site())) } - /// Returns a type which outputs a `DiscriminantRepr` with + /// Returns a type which outputs a `DiscriminantRepr` with /// a slice of the items in the iterator, - /// where each Option is unwrapped by replacing `None`s + /// where each Option is unwrapped by replacing `None`s /// with the value of the last `Some()` incremented by the distance to the current element. - pub(crate) fn tokenize_discriminant_exprs<'a,I>( + pub(crate) fn tokenize_discriminant_exprs<'a, I>( self, - exprs:I, - ctokens:&'a CommonTokens, - )->impl ToTokens+'a + exprs: I, + ctokens: &'a CommonTokens, + ) -> impl ToTokens + 'a where - I:IntoIterator>+'a + I: IntoIterator> + 'a, { - let mut exprs=exprs.into_iter(); + let mut exprs = exprs.into_iter(); - ToTokenFnMut::new(move|ts|{ - let int_repr=match self.variant { - Repr::C(x)=>x, - Repr::Int(x)=>Some(x), - Repr::Transparent=>unreachable!(), + ToTokenFnMut::new(move |ts| { + let int_repr = match self.variant { + Repr::C(x) => x, + Repr::Int(x) => Some(x), + Repr::Transparent => unreachable!(), }; match int_repr.unwrap_or(DiscriminantRepr::Isize) { - DiscriminantRepr::U8 =>quote!(__TLDiscriminants::from_u8_slice ), - DiscriminantRepr::U16=>quote!(__TLDiscriminants::from_u16_slice ), - DiscriminantRepr::U32=>quote!(__TLDiscriminants::from_u32_slice ), - DiscriminantRepr::U64=>quote!(__TLDiscriminants::from_u64_slice ), - DiscriminantRepr::I8 =>quote!(__TLDiscriminants::from_i8_slice ), - DiscriminantRepr::I16=>quote!(__TLDiscriminants::from_i16_slice ), - DiscriminantRepr::I32=>quote!(__TLDiscriminants::from_i32_slice ), - DiscriminantRepr::I64=>quote!(__TLDiscriminants::from_i64_slice ), - DiscriminantRepr::Usize=>quote!(__TLDiscriminants::from_usize_slice ), - DiscriminantRepr::Isize=>quote!(__TLDiscriminants::from_isize_slice ), - }.to_tokens(ts); - - ctokens.paren.surround(ts,|ts|{ - tokenize_discriminant_exprs_inner(&mut exprs,SliceType::RSlice,ctokens,ts); + DiscriminantRepr::U8 => quote!(__TLDiscriminants::from_u8_slice), + DiscriminantRepr::U16 => quote!(__TLDiscriminants::from_u16_slice), + DiscriminantRepr::U32 => quote!(__TLDiscriminants::from_u32_slice), + DiscriminantRepr::U64 => quote!(__TLDiscriminants::from_u64_slice), + DiscriminantRepr::I8 => quote!(__TLDiscriminants::from_i8_slice), + DiscriminantRepr::I16 => quote!(__TLDiscriminants::from_i16_slice), + DiscriminantRepr::I32 => quote!(__TLDiscriminants::from_i32_slice), + DiscriminantRepr::I64 => quote!(__TLDiscriminants::from_i64_slice), + DiscriminantRepr::Usize => quote!(__TLDiscriminants::from_usize_slice), + DiscriminantRepr::Isize => quote!(__TLDiscriminants::from_isize_slice), + } + .to_tokens(ts); + + ctokens.paren.surround(ts, |ts| { + tokenize_discriminant_exprs_inner(&mut exprs, SliceType::RSlice, ctokens, ts); }); }) } - /// Returns a type which outputs a slice with the items in the iterator, - /// where each Option is unwrapped by replacing `None`s + /// where each Option is unwrapped by replacing `None`s /// with the value of the last `Some()` incremented by the distance to the current element. - pub(crate) fn tokenize_discriminant_slice<'a,I>( + pub(crate) fn tokenize_discriminant_slice<'a, I>( self, - exprs:I, - ctokens:&'a CommonTokens, - )->impl ToTokens+'a + exprs: I, + ctokens: &'a CommonTokens, + ) -> impl ToTokens + 'a where - I:IntoIterator>+'a + I: IntoIterator> + 'a, { - let mut exprs=exprs.into_iter(); + let mut exprs = exprs.into_iter(); - ToTokenFnMut::new(move|ts|{ - tokenize_discriminant_exprs_inner(&mut exprs,SliceType::StdSlice,ctokens,ts); + ToTokenFnMut::new(move |ts| { + tokenize_discriminant_exprs_inner(&mut exprs, SliceType::StdSlice, ctokens, ts); }) } } - #[allow(dead_code)] -impl ReprAttr{ - pub fn span(self)->Span{ +impl ReprAttr { + pub fn span(self) -> Span { *self.span } - pub fn is_repr_transparent(self)->bool{ - matches!(self.variant, Repr::Transparent{..}) + pub fn is_repr_transparent(self) -> bool { + matches!(self.variant, Repr::Transparent { .. }) } - pub fn is_repr_c(self)->bool{ - matches!(self.variant, Repr::C{..}) + pub fn is_repr_c(self) -> bool { + matches!(self.variant, Repr::C { .. }) } - pub fn is_repr_int(self)->bool{ - matches!(self.variant, Repr::Int{..}) + pub fn is_repr_int(self) -> bool { + matches!(self.variant, Repr::Int { .. }) } } - -#[derive(Copy,Clone)] -enum SliceType{ +#[derive(Copy, Clone)] +enum SliceType { StdSlice, RSlice, } - /// Outputs the items in the iterator separated by commas, -/// where each Option is unwrapped by replacing `None`s +/// where each Option is unwrapped by replacing `None`s /// with the value of the last `Some()` incremented by the distance to the current element. -fn tokenize_discriminant_exprs_inner<'a,I>( - exprs:I, - type_:SliceType, - ctokens:&'a CommonTokens, - ts:&mut TokenStream -)where - I:Iterator> +fn tokenize_discriminant_exprs_inner<'a, I>( + exprs: I, + type_: SliceType, + ctokens: &'a CommonTokens, + ts: &mut TokenStream, +) where + I: Iterator>, { - let zero_expr=crate::utils::expr_from_int(0); - let mut last_explicit_discr=&zero_expr; - let mut since_last_expr=0; - - let iter=exprs - .map(|expr|{ - match expr { - Some(discr)=>{ - let ts=quote!(#discr); - last_explicit_discr=discr; - since_last_expr=1; - ts - } - None=>{ - let offset=crate::utils::uint_lit(since_last_expr); - let ts=quote!( (#last_explicit_discr)+#offset ); - since_last_expr+=1; - ts - } - } - }); + let zero_expr = crate::utils::expr_from_int(0); + let mut last_explicit_discr = &zero_expr; + let mut since_last_expr = 0; + + let iter = exprs.map(|expr| match expr { + Some(discr) => { + let ts = quote!(#discr); + last_explicit_discr = discr; + since_last_expr = 1; + ts + } + None => { + let offset = crate::utils::uint_lit(since_last_expr); + let ts = quote!( (#last_explicit_discr)+#offset ); + since_last_expr += 1; + ts + } + }); match type_ { - SliceType::StdSlice=>{ + SliceType::StdSlice => { ctokens.and_.to_tokens(ts); - ctokens.bracket.surround(ts,|ts|{ + ctokens.bracket.surround(ts, |ts| { for elem in iter { elem.to_tokens(ts); ctokens.comma.to_tokens(ts) } }); } - SliceType::RSlice=>{ + SliceType::RSlice => { rslice_tokenizer(iter).to_tokens(ts); } } - } - - - - -impl ToTokens for ReprAttr{ +impl ToTokens for ReprAttr { fn to_tokens(&self, ts: &mut TokenStream) { match self.variant { - Repr::C(None)=>{ + Repr::C(None) => { quote!(__ReprAttr::C) } - Repr::C(Some(int_repr))=>{ - let int_repr=discr_repr_tokenizer(int_repr); + Repr::C(Some(int_repr)) => { + let int_repr = discr_repr_tokenizer(int_repr); quote!(__ReprAttr::CAndInt(#int_repr)) } - Repr::Transparent=>{ + Repr::Transparent => { quote!(__ReprAttr::Transparent) } - Repr::Int(int_repr)=>{ - let int_repr=discr_repr_tokenizer(int_repr); + Repr::Int(int_repr) => { + let int_repr = discr_repr_tokenizer(int_repr); quote!(__ReprAttr::Int(#int_repr)) } - }.to_tokens(ts); + } + .to_tokens(ts); } } -fn discr_repr_tokenizer(repr:DiscriminantRepr)->impl ToTokens{ - ToTokenFnMut::new(move|ts|{ +fn discr_repr_tokenizer(repr: DiscriminantRepr) -> impl ToTokens { + ToTokenFnMut::new(move |ts| { match repr { - DiscriminantRepr::U8=>quote!(__DiscriminantRepr::U8), - DiscriminantRepr::I8=>quote!(__DiscriminantRepr::I8), - DiscriminantRepr::U16=>quote!(__DiscriminantRepr::U16), - DiscriminantRepr::I16=>quote!(__DiscriminantRepr::I16), - DiscriminantRepr::U32=>quote!(__DiscriminantRepr::U32), - DiscriminantRepr::I32=>quote!(__DiscriminantRepr::I32), - DiscriminantRepr::U64=>quote!(__DiscriminantRepr::U64), - DiscriminantRepr::I64=>quote!(__DiscriminantRepr::I64), - DiscriminantRepr::Usize=>quote!(__DiscriminantRepr::Usize), - DiscriminantRepr::Isize=>quote!(__DiscriminantRepr::Isize), - }.to_tokens(ts); + DiscriminantRepr::U8 => quote!(__DiscriminantRepr::U8), + DiscriminantRepr::I8 => quote!(__DiscriminantRepr::I8), + DiscriminantRepr::U16 => quote!(__DiscriminantRepr::U16), + DiscriminantRepr::I16 => quote!(__DiscriminantRepr::I16), + DiscriminantRepr::U32 => quote!(__DiscriminantRepr::U32), + DiscriminantRepr::I32 => quote!(__DiscriminantRepr::I32), + DiscriminantRepr::U64 => quote!(__DiscriminantRepr::U64), + DiscriminantRepr::I64 => quote!(__DiscriminantRepr::I64), + DiscriminantRepr::Usize => quote!(__DiscriminantRepr::Usize), + DiscriminantRepr::Isize => quote!(__DiscriminantRepr::Isize), + } + .to_tokens(ts); }) -} \ No newline at end of file +} diff --git a/abi_stable_derive/src/stable_abi/shared_vars.rs b/abi_stable_derive/src/stable_abi/shared_vars.rs index 35b21d58..4d8e8fc3 100644 --- a/abi_stable_derive/src/stable_abi/shared_vars.rs +++ b/abi_stable_derive/src/stable_abi/shared_vars.rs @@ -1,59 +1,48 @@ use crate::{ arenas::Arenas, - composite_collections::{SmallStartLen as StartLen}, - lifetimes::{LifetimeIndex,LifetimeIndexPair,LifetimeRange}, + composite_collections::SmallStartLen as StartLen, + lifetimes::{LifetimeIndex, LifetimeIndexPair, LifetimeRange}, literals_constructors::rslice_tokenizer, - utils::{join_spans,LinearResult,SynResultExt}, + utils::{join_spans, LinearResult, SynResultExt}, }; use super::{ - attribute_parsing::LayoutConstructor, - tl_multi_tl::TypeLayoutIndex, - CommonTokens, - ConstIdents, + attribute_parsing::LayoutConstructor, tl_multi_tl::TypeLayoutIndex, CommonTokens, ConstIdents, }; -use as_derive_utils::{ - to_token_fn::ToTokenFnMut, - syn_err, -}; +use as_derive_utils::{syn_err, to_token_fn::ToTokenFnMut}; use core_extensions::SelfOps; use proc_macro2::Span; -use quote::{quote,ToTokens}; - -use std::{ - collections::HashMap, - fmt::Display, -}; +use quote::{quote, ToTokens}; +use std::{collections::HashMap, fmt::Display}; - -pub(crate) struct SharedVars<'a>{ - const_idents:&'a ConstIdents, - arenas:&'a Arenas, - ctokens:&'a CommonTokens<'a>, +pub(crate) struct SharedVars<'a> { + const_idents: &'a ConstIdents, + arenas: &'a Arenas, + ctokens: &'a CommonTokens<'a>, strings: String, lifetime_indices: Vec, - type_layouts_map: HashMap<(LayoutConstructor,&'a syn::Type),u16>, - type_layouts: Vec<(LayoutConstructor,&'a syn::Type)>, + type_layouts_map: HashMap<(LayoutConstructor, &'a syn::Type), u16>, + type_layouts: Vec<(LayoutConstructor, &'a syn::Type)>, constants: Vec<&'a syn::Expr>, - overflowed_strings:LinearResult<()>, - overflowed_lifetime_indices:LinearResult<()>, - overflowed_type_layouts:LinearResult<()>, - overflowed_constants:LinearResult<()>, - extra_errs:LinearResult<()>, + overflowed_strings: LinearResult<()>, + overflowed_lifetime_indices: LinearResult<()>, + overflowed_type_layouts: LinearResult<()>, + overflowed_constants: LinearResult<()>, + extra_errs: LinearResult<()>, } -impl<'a> SharedVars<'a>{ +impl<'a> SharedVars<'a> { pub(crate) fn new( - arenas:&'a Arenas, - const_idents:&'a ConstIdents, - ctokens:&'a CommonTokens, - )->Self{ - Self{ + arenas: &'a Arenas, + const_idents: &'a ConstIdents, + ctokens: &'a CommonTokens, + ) -> Self { + Self { const_idents, arenas, ctokens, @@ -62,99 +51,105 @@ impl<'a> SharedVars<'a>{ type_layouts: Vec::new(), type_layouts_map: HashMap::new(), constants: Vec::new(), - overflowed_strings:LinearResult::ok(()), - overflowed_lifetime_indices:LinearResult::ok(()), - overflowed_type_layouts:LinearResult::ok(()), - overflowed_constants:LinearResult::ok(()), - extra_errs:LinearResult::ok(()), + overflowed_strings: LinearResult::ok(()), + overflowed_lifetime_indices: LinearResult::ok(()), + overflowed_type_layouts: LinearResult::ok(()), + overflowed_constants: LinearResult::ok(()), + extra_errs: LinearResult::ok(()), } } - pub(crate) fn strings(&self)->&str{ + pub(crate) fn strings(&self) -> &str { &self.strings } - pub(crate) fn arenas(&self)->&'a Arenas{ + pub(crate) fn arenas(&self) -> &'a Arenas { self.arenas } - pub(crate) fn ctokens(&self)->&'a CommonTokens<'a>{ + pub(crate) fn ctokens(&self) -> &'a CommonTokens<'a> { self.ctokens } - pub(crate) fn extract_errs(&mut self)->Result<(),syn::Error>{ - let mut errors=Ok::<(),syn::Error>(()); + pub(crate) fn extract_errs(&mut self) -> Result<(), syn::Error> { + let mut errors = Ok::<(), syn::Error>(()); self.overflowed_strings.take().combine_into_err(&mut errors); - self.overflowed_lifetime_indices.take().combine_into_err(&mut errors); - self.overflowed_type_layouts.take().combine_into_err(&mut errors); - self.overflowed_constants.take().combine_into_err(&mut errors); + self.overflowed_lifetime_indices + .take() + .combine_into_err(&mut errors); + self.overflowed_type_layouts + .take() + .combine_into_err(&mut errors); + self.overflowed_constants + .take() + .combine_into_err(&mut errors); self.extra_errs.take().combine_into_err(&mut errors); errors } - fn push_str_inner(&mut self,f:F)->StartLen + fn push_str_inner(&mut self, f: F) -> StartLen where - F:FnOnce(&mut Self)->Option + F: FnOnce(&mut Self) -> Option, { - let start=self.strings.len(); - let span=f(self); - let len=self.strings.len()-start; + let start = self.strings.len(); + let span = f(self); + let len = self.strings.len() - start; - if start >= (1<<16) || len >=(1<<16) { + if start >= (1 << 16) || len >= (1 << 16) { self.string_overflow_err(span); StartLen::DUMMY - }else{ - StartLen::from_start_len(start,len) + } else { + StartLen::from_start_len(start, len) } } - pub(crate) fn combine_err(&mut self,r:Result<(),syn::Error>){ + pub(crate) fn combine_err(&mut self, r: Result<(), syn::Error>) { self.extra_errs.combine_err(r); } - pub(crate) fn push_ident(&mut self,ident:&syn::Ident)-> StartLen { - self.push_str_inner(|this|{ + pub(crate) fn push_ident(&mut self, ident: &syn::Ident) -> StartLen { + self.push_str_inner(|this| { use std::fmt::Write; - let _=write!(this.strings,"{}",ident); + let _ = write!(this.strings, "{}", ident); Some(ident.span()) }) } - pub(crate) fn push_str(&mut self,s:&str,span:Option)-> StartLen { - self.push_str_inner(|this|{ + pub(crate) fn push_str(&mut self, s: &str, span: Option) -> StartLen { + self.push_str_inner(|this| { this.strings.push_str(s); span }) } - pub fn extend_with_idents(&mut self,separator:&str,iter:I)->StartLen + pub fn extend_with_idents(&mut self, separator: &str, iter: I) -> StartLen where - I:IntoIterator, + I: IntoIterator, { - self.push_str_inner(|this|{ + self.push_str_inner(|this| { use std::fmt::Write; - let mut last_span=None; + let mut last_span = None; for ident in iter { - last_span=Some(ident.span()); - let _=write!(this.strings,"{}",ident); - this.push_str(separator,last_span); + last_span = Some(ident.span()); + let _ = write!(this.strings, "{}", ident); + this.push_str(separator, last_span); } last_span }) } - pub fn extend_with_display(&mut self,separator:&str,iter:I)->StartLen + pub fn extend_with_display(&mut self, separator: &str, iter: I) -> StartLen where - I:IntoIterator, - T:Display, + I: IntoIterator, + T: Display, { - self.push_str_inner(|this|{ + self.push_str_inner(|this| { use std::fmt::Write; - let mut last_span=None; - for (elem,span) in iter { - last_span=Some(span); - let _=write!(this.strings,"{}",elem); - this.push_str(separator,Some(span)); + let mut last_span = None; + for (elem, span) in iter { + last_span = Some(span); + let _ = write!(this.strings, "{}", elem); + this.push_str(separator, Some(span)); } last_span }) @@ -162,7 +157,7 @@ impl<'a> SharedVars<'a>{ #[inline(never)] #[cold] - pub(crate) fn string_overflow_err(&mut self,span:Option){ + pub(crate) fn string_overflow_err(&mut self, span: Option) { if self.overflowed_strings.is_ok() { self.overflowed_strings.push_err(syn_err!( span.unwrap_or_else(Span::call_site), @@ -173,16 +168,16 @@ impl<'a> SharedVars<'a>{ } } - pub(crate) fn extend_with_lifetime_indices(&mut self,iter:I)->LifetimeRange + pub(crate) fn extend_with_lifetime_indices(&mut self, iter: I) -> LifetimeRange where - I:IntoIterator, + I: IntoIterator, { - let start=self.lifetime_indices.len(); + let start = self.lifetime_indices.len(); self.lifetime_indices.extend(iter); - let len=self.lifetime_indices.len()-start; + let len = self.lifetime_indices.len() - start; if len <= 5 { - let mut drainer=self.lifetime_indices.drain(start..).fuse(); + let mut drainer = self.lifetime_indices.drain(start..).fuse(); LifetimeRange::from_array([ drainer.next().unwrap_or(LifetimeIndex::NONE), drainer.next().unwrap_or(LifetimeIndex::NONE), @@ -190,27 +185,27 @@ impl<'a> SharedVars<'a>{ drainer.next().unwrap_or(LifetimeIndex::NONE), drainer.next().unwrap_or(LifetimeIndex::NONE), ]) - }else{ - if (len&1)==1 { + } else { + if (len & 1) == 1 { self.lifetime_indices.push(LifetimeIndex::NONE); } - let half_len=self.lifetime_indices.len()/2; - if half_len>LifetimeRange::MAX_START { + let half_len = self.lifetime_indices.len() / 2; + if half_len > LifetimeRange::MAX_START { self.lifetime_overflow_start_err(); LifetimeRange::DUMMY - }else if half_len>LifetimeRange::MAX_LEN { + } else if half_len > LifetimeRange::MAX_LEN { self.lifetime_overflow_len_err(); LifetimeRange::DUMMY - }else{ - LifetimeRange::from_range( start/2..half_len ) + } else { + LifetimeRange::from_range(start / 2..half_len) } } } #[inline(never)] #[cold] - pub(crate) fn lifetime_overflow_start_err(&mut self){ + pub(crate) fn lifetime_overflow_start_err(&mut self) { if self.overflowed_lifetime_indices.is_ok() { self.overflowed_lifetime_indices.push_err(syn_err!( Span::call_site(), @@ -218,75 +213,73 @@ impl<'a> SharedVars<'a>{ The amount is approximate,\n since this stores 5 or fewer lifetimes in fields/function pointers inline, and those don't contribute to the lifetime arguments limit.", - LifetimeRange::MAX_START*2, + LifetimeRange::MAX_START * 2, )); } } #[inline(never)] #[cold] - pub(crate) fn lifetime_overflow_len_err(&mut self){ + pub(crate) fn lifetime_overflow_len_err(&mut self) { if self.overflowed_lifetime_indices.is_ok() { self.overflowed_lifetime_indices.push_err(syn_err!( Span::call_site(), "Cannot have more than {} lifetimes arguments within \ a field or function pointer.\n", - LifetimeRange::MAX_LEN*2, + LifetimeRange::MAX_LEN * 2, )); } } - pub(crate) fn push_type( &mut self, - layout_ctor:LayoutConstructor, - type_:&'a syn::Type, - )->TypeLayoutIndex{ - let type_layouts=&mut self.type_layouts; - - let key=(layout_ctor,type_); - - let len=*self.type_layouts_map - .entry(key) - .or_insert_with(move||{ - let len=type_layouts.len(); - type_layouts.push(key); - len as u16 - }); + layout_ctor: LayoutConstructor, + type_: &'a syn::Type, + ) -> TypeLayoutIndex { + let type_layouts = &mut self.type_layouts; + + let key = (layout_ctor, type_); + + let len = *self.type_layouts_map.entry(key).or_insert_with(move || { + let len = type_layouts.len(); + type_layouts.push(key); + len as u16 + }); if len > TypeLayoutIndex::MAX_VAL_U16 { self.construct_type_overflow_err(); TypeLayoutIndex::DUMMY - }else{ + } else { TypeLayoutIndex::from_u10(len) } } - pub(crate) fn extend_type(&mut self,layout_ctor:LayoutConstructor,types:I)->StartLen + pub(crate) fn extend_type(&mut self, layout_ctor: LayoutConstructor, types: I) -> StartLen where - I:IntoIterator, + I: IntoIterator, { - let start=self.type_layouts.len(); + let start = self.type_layouts.len(); for ty in types { - self.type_layouts.push((layout_ctor,ty)); + self.type_layouts.push((layout_ctor, ty)); } - let end=self.type_layouts.len(); + let end = self.type_layouts.len(); if end > TypeLayoutIndex::MAX_VAL { self.construct_type_overflow_err(); StartLen::DUMMY - }else{ - StartLen::from_start_len(start,end-start) + } else { + StartLen::from_start_len(start, end - start) } - } #[inline(never)] #[cold] - fn construct_type_overflow_err(&mut self){ + fn construct_type_overflow_err(&mut self) { if self.overflowed_type_layouts.is_ok() { self.overflowed_type_layouts.push_err(syn_err!( join_spans( - self.type_layouts.drain(TypeLayoutIndex::MAX_VAL..).map(|(_,ty)|ty) + self.type_layouts + .drain(TypeLayoutIndex::MAX_VAL..) + .map(|(_, ty)| ty) ), "Cannot have more than {} unique types(ignoring lifetime parameters) \ within a type definition.", @@ -295,31 +288,30 @@ impl<'a> SharedVars<'a>{ } } - - pub fn get_type(&self,index:usize)->Option<&'a syn::Type>{ - self.type_layouts.get(index).map(|(_,ty)| *ty ) + pub fn get_type(&self, index: usize) -> Option<&'a syn::Type> { + self.type_layouts.get(index).map(|(_, ty)| *ty) } - pub(crate) fn extend_with_constants(&mut self,iter:I)->StartLen + pub(crate) fn extend_with_constants(&mut self, iter: I) -> StartLen where - I:IntoIterator, + I: IntoIterator, { - let start=self.constants.len(); + let start = self.constants.len(); for expr in iter { self.constants.push(expr); } - let end=self.constants.len(); - if end>=(1<<8) { + let end = self.constants.len(); + if end >= (1 << 8) { self.construct_const_overflow_err(); StartLen::DUMMY - }else{ - StartLen::from_start_len(start,end-start) + } else { + StartLen::from_start_len(start, end - start) } } #[inline(never)] #[cold] - fn construct_const_overflow_err(&mut self){ + fn construct_const_overflow_err(&mut self) { if self.overflowed_constants.is_ok() { self.overflowed_constants.push_err(syn_err!( Span::call_site(), @@ -330,34 +322,40 @@ impl<'a> SharedVars<'a>{ } } - - pub(crate) fn mono_shared_vars_tokenizer(&self)->impl ToTokens+'_{ - ToTokenFnMut::new(move|ts|{ - let lifetime_indices=self.lifetime_indices + pub(crate) fn mono_shared_vars_tokenizer(&self) -> impl ToTokens + '_ { + ToTokenFnMut::new(move |ts| { + let lifetime_indices = self + .lifetime_indices .chunks(2) - .map(|chunk|{ - let first=chunk[0]; - let second=chunk.get(1).map_or(LifetimeIndex::NONE,|x|*x); - LifetimeIndexPair::new(first,second).to_u8() + .map(|chunk| { + let first = chunk[0]; + let second = chunk.get(1).map_or(LifetimeIndex::NONE, |x| *x); + LifetimeIndexPair::new(first, second).to_u8() }) .piped(rslice_tokenizer); - let strings=&self.const_idents.strings; + let strings = &self.const_idents.strings; quote!( abi_stable::type_layout::MonoSharedVars::new( #strings, #lifetime_indices, ) - ).to_tokens(ts); + ) + .to_tokens(ts); }) } - pub(crate) fn shared_vars_tokenizer(&self,mono_type_layout:&'a syn::Ident)->impl ToTokens+'_{ - ToTokenFnMut::new(move|ts|{ - let ct=self.ctokens; - let type_layouts= self.type_layouts.iter() - .map(|&(layout_ctor,ty)| make_get_type_layout_tokenizer(ty,layout_ctor,ct) ); + pub(crate) fn shared_vars_tokenizer( + &self, + mono_type_layout: &'a syn::Ident, + ) -> impl ToTokens + '_ { + ToTokenFnMut::new(move |ts| { + let ct = self.ctokens; + let type_layouts = self + .type_layouts + .iter() + .map(|&(layout_ctor, ty)| make_get_type_layout_tokenizer(ty, layout_ctor, ct)); let consts_i = 0..self.constants.len(); let constants = self.constants.iter().copied(); @@ -382,37 +380,36 @@ impl<'a> SharedVars<'a>{ },)* ]; - const __SABI_SHARED_VARS: &'static __sabi_re::SharedVars = + const __SABI_SHARED_VARS: &'static __sabi_re::SharedVars = &abi_stable::type_layout::SharedVars::new ( #mono_type_layout.shared_vars_static(), abi_stable::_sabi_type_layouts!( #(#type_layouts,)* ), __sabi_re::RSlice::from_slice(Self::__SABI_CONST_PARAMS_B), ); - ).to_tokens(ts); - + ) + .to_tokens(ts); }) } - } - #[must_use] -fn make_get_type_layout_tokenizer<'a,T:'a>( - ty:T, - field_transparency:LayoutConstructor, - ct:&'a CommonTokens<'a>, -)->impl ToTokens+'a -where T:ToTokens +fn make_get_type_layout_tokenizer<'a, T: 'a>( + ty: T, + field_transparency: LayoutConstructor, + ct: &'a CommonTokens<'a>, +) -> impl ToTokens + 'a +where + T: ToTokens, { - ToTokenFnMut::new(move|ts|{ + ToTokenFnMut::new(move |ts| { ty.to_tokens(ts); - let opt=match field_transparency { - LayoutConstructor::Regular=> None, - LayoutConstructor::Opaque=> Some(&ct.cap_opaque_field), - LayoutConstructor::SabiOpaque=> Some(&ct.cap_sabi_opaque_field), + let opt = match field_transparency { + LayoutConstructor::Regular => None, + LayoutConstructor::Opaque => Some(&ct.cap_opaque_field), + LayoutConstructor::SabiOpaque => Some(&ct.cap_sabi_opaque_field), }; - if let Some(assoc_const)=opt { + if let Some(assoc_const) = opt { ct.equal.to_tokens(ts); assoc_const.to_tokens(ts) } diff --git a/abi_stable_derive/src/stable_abi/tests.rs b/abi_stable_derive/src/stable_abi/tests.rs index 1ded14a2..eae487c7 100644 --- a/abi_stable_derive/src/stable_abi/tests.rs +++ b/abi_stable_derive/src/stable_abi/tests.rs @@ -1,14 +1,11 @@ -use crate::{ - derive_stable_abi_from_str as derive_sabi, -}; +use crate::derive_stable_abi_from_str as derive_sabi; -use abi_stable_shared::{file_span,test_utils::{must_panic}}; +use abi_stable_shared::{file_span, test_utils::must_panic}; use as_derive_utils::test_framework::Tests; - /// For testing that adding #[repr(C)] makes the derive macro not panic. -const RECTANGLE_DEF_REPR:&str=r##" +const RECTANGLE_DEF_REPR: &str = r##" pub struct Rectangle { x:u32, y:u32, @@ -17,46 +14,30 @@ const RECTANGLE_DEF_REPR:&str=r##" } "##; - - - #[test] -fn test_cases(){ +fn test_cases() { Tests::load("stable_abi").run_test(derive_sabi); } #[test] -fn check_struct_repr_attrs(){ - - let rect_def=RECTANGLE_DEF_REPR; - - must_panic(file_span!(),|| derive_sabi(rect_def).unwrap() ).expect("TEST BUG"); - - let invalid_reprs=vec![ - "Rust", - "u8", - "i8", - "u16", - "i16", - "u32", - "i32", - "u64", - "i64", - "usize", - "isize", +fn check_struct_repr_attrs() { + let rect_def = RECTANGLE_DEF_REPR; + + must_panic(file_span!(), || derive_sabi(rect_def).unwrap()).expect("TEST BUG"); + + let invalid_reprs = vec![ + "Rust", "u8", "i8", "u16", "i16", "u32", "i32", "u64", "i64", "usize", "isize", ]; for invalid_repr in invalid_reprs { - - let with_repr_rust=format!( + let with_repr_rust = format!( "#[repr({repr})]\n{struct_def}", - repr=invalid_repr, - struct_def=rect_def, + repr = invalid_repr, + struct_def = rect_def, ); assert!(derive_sabi(&with_repr_rust).is_err()) } - - derive_sabi(&format!("#[repr(C)]\n{}",rect_def)).unwrap(); - derive_sabi(&format!("#[repr(transparent)]\n{}",rect_def)).unwrap(); + derive_sabi(&format!("#[repr(C)]\n{}", rect_def)).unwrap(); + derive_sabi(&format!("#[repr(transparent)]\n{}", rect_def)).unwrap(); } diff --git a/abi_stable_derive/src/stable_abi/tl_field.rs b/abi_stable_derive/src/stable_abi/tl_field.rs index 1474c1ff..37e010a2 100644 --- a/abi_stable_derive/src/stable_abi/tl_field.rs +++ b/abi_stable_derive/src/stable_abi/tl_field.rs @@ -1,55 +1,53 @@ use crate::{ - composite_collections::{SmallStartLen as StartLen}, - lifetimes::{LifetimeRange,LifetimeIndex}, + composite_collections::SmallStartLen as StartLen, + lifetimes::{LifetimeIndex, LifetimeRange}, }; use super::{ - tl_multi_tl::TypeLayoutIndex, - reflection::{CompFieldAccessor,FieldAccessor}, + reflection::{CompFieldAccessor, FieldAccessor}, shared_vars::SharedVars, + tl_multi_tl::TypeLayoutIndex, }; use proc_macro2::TokenStream as TokenStream2; use quote::ToTokens; - -abi_stable_shared::declare_comp_tl_field!{ +abi_stable_shared::declare_comp_tl_field! { attrs=[] } - -impl CompTLField{ - pub(crate) fn from_expanded<'a,I>( - name:&syn::Ident, - lifetime_indices:I, - field_accessor:FieldAccessor<'a>, +impl CompTLField { + pub(crate) fn from_expanded<'a, I>( + name: &syn::Ident, + lifetime_indices: I, + field_accessor: FieldAccessor<'a>, layout: TypeLayoutIndex, - is_function:bool, - shared_vars:&mut SharedVars<'a>, - )->Self + is_function: bool, + shared_vars: &mut SharedVars<'a>, + ) -> Self where - I:IntoIterator, + I: IntoIterator, { - let (name_range,comp_field_accessor)= - Self::push_name_field_accessor(name,field_accessor,shared_vars); + let (name_range, comp_field_accessor) = + Self::push_name_field_accessor(name, field_accessor, shared_vars); Self::new( name_range, - shared_vars.extend_with_lifetime_indices( lifetime_indices ), + shared_vars.extend_with_lifetime_indices(lifetime_indices), comp_field_accessor, layout, is_function, ) } - pub(crate) fn from_expanded_std_field<'a,I>( - name:&syn::Ident, - lifetime_indices:I, + pub(crate) fn from_expanded_std_field<'a, I>( + name: &syn::Ident, + lifetime_indices: I, layout: TypeLayoutIndex, - shared_vars:&mut SharedVars<'a>, - )->Self + shared_vars: &mut SharedVars<'a>, + ) -> Self where - I:IntoIterator, + I: IntoIterator, { Self::from_expanded( name, @@ -61,25 +59,24 @@ impl CompTLField{ ) } - /// Pushes the name and field accessor payload with the + /// Pushes the name and field accessor payload with the /// `;` format. fn push_name_field_accessor<'a>( - name:&syn::Ident, - field_accessor:FieldAccessor<'a>, - shared_vars:&mut SharedVars<'a>, - )->(StartLen,CompFieldAccessor){ - let name_range=shared_vars.push_ident(name); - shared_vars.combine_err( name_range.check_ident_length(name.span()) ); - - let comp_field_accessor=field_accessor.compress(shared_vars); - shared_vars.push_str(";",None); - (name_range,comp_field_accessor) + name: &syn::Ident, + field_accessor: FieldAccessor<'a>, + shared_vars: &mut SharedVars<'a>, + ) -> (StartLen, CompFieldAccessor) { + let name_range = shared_vars.push_ident(name); + shared_vars.combine_err(name_range.check_ident_length(name.span())); + + let comp_field_accessor = field_accessor.compress(shared_vars); + shared_vars.push_str(";", None); + (name_range, comp_field_accessor) } } - impl CompTLField { - pub(crate) fn type_<'a>(&self,shared_vars:&SharedVars<'a>)-> &'a syn::Type { + pub(crate) fn type_<'a>(&self, shared_vars: &SharedVars<'a>) -> &'a syn::Type { shared_vars.get_type(self.type_layout_index()).unwrap() } } @@ -89,6 +86,3 @@ impl ToTokens for CompTLField { self.bits0.to_tokens(ts); } } - - - diff --git a/abi_stable_derive/src/stable_abi/tl_function.rs b/abi_stable_derive/src/stable_abi/tl_function.rs index 31b8160c..3e389df2 100644 --- a/abi_stable_derive/src/stable_abi/tl_function.rs +++ b/abi_stable_derive/src/stable_abi/tl_function.rs @@ -2,12 +2,10 @@ Contains types related to the type layout of function pointers. */ - use super::*; use crate::{ - composite_collections::{SmallStartLen as StartLen}, - fn_pointer_extractor::TypeVisitor, + composite_collections::SmallStartLen as StartLen, fn_pointer_extractor::TypeVisitor, lifetimes::LifetimeRange, }; @@ -19,181 +17,176 @@ use syn::Type; /// Associates extra information related to function pointers to a type declaration. #[allow(dead_code)] -pub(crate) struct VisitedFieldMap<'a>{ - pub(crate) map:Vec>, - pub(crate) fn_ptr_count:usize, - priv_:(), +pub(crate) struct VisitedFieldMap<'a> { + pub(crate) map: Vec>, + pub(crate) fn_ptr_count: usize, + priv_: (), } - -impl<'a> VisitedFieldMap<'a>{ +impl<'a> VisitedFieldMap<'a> { pub(crate) fn new( - ds:&'a DataStructure<'a>, - config:&'a StableAbiOptions<'a>, - shared_vars:&mut SharedVars<'a>, - ctokens: &'a CommonTokens<'a> - )-> Self { - let arenas=shared_vars.arenas(); + ds: &'a DataStructure<'a>, + config: &'a StableAbiOptions<'a>, + shared_vars: &mut SharedVars<'a>, + ctokens: &'a CommonTokens<'a>, + ) -> Self { + let arenas = shared_vars.arenas(); let mut tv = TypeVisitor::new(arenas, ctokens.as_ref(), ds.generics); - if config.allow_type_macros{ + if config.allow_type_macros { tv.allow_type_macros(); } let mut fn_ptr_count = 0; - let map=ds.variants.iter().flat_map(|x| &x.fields ).map(|field|{ - // The type used to get the TypeLayout of the field. - // This has all parameter and return types of function pointers removed. - // Extracted into the `functions` field of this struct. - let mut mutated_ty=config.changed_types[field].unwrap_or(field.ty).clone(); - let layout_ctor=config.layout_ctor[field]; - let is_opaque=layout_ctor.is_opaque(); - - let is_function=match mutated_ty { - Type::BareFn{..}=>!is_opaque, - _=>false, - }; - - - let visit_info = tv.visit_field(&mut mutated_ty); - - let mutated_ty=arenas.alloc(mutated_ty); - - let field_accessor=config.override_field_accessor[field] - .unwrap_or_else(|| config.kind.field_accessor(config.mod_refl_mode,field) ); - - let name=config.renamed_fields[field].unwrap_or_else(||field.pat_ident()); - - let comp_field=CompTLField::from_expanded( - name, - visit_info.referenced_lifetimes.iter().cloned(), - field_accessor, - shared_vars.push_type(layout_ctor,mutated_ty), - is_function, - shared_vars, - ); - - let iterated_functions=if is_opaque { Vec::new() }else{ visit_info.functions }; - - let functions=iterated_functions.iter().enumerate() - .map(|(fn_i,func)|{ - let name_span=name.span(); - let name_start_len=if is_function||iterated_functions.len()==1 { - comp_field.name_start_len() - }else{ - shared_vars.push_str(&format!("fn_{}",fn_i),Some(name_span)) - }; - - shared_vars.combine_err( name_start_len.check_ident_length(name_span) ); - - let bound_lifetimes_start_len=shared_vars - .extend_with_idents(",",func.named_bound_lts.iter().cloned()); - - let params_iter=func.params.iter() - .map(|p|{ - match p.name { - Some(pname) => (pname as &dyn std::fmt::Display,pname.span()), - None => (&"" as &dyn std::fmt::Display,Span::call_site()), - } + let map = ds + .variants + .iter() + .flat_map(|x| &x.fields) + .map(|field| { + // The type used to get the TypeLayout of the field. + // This has all parameter and return types of function pointers removed. + // Extracted into the `functions` field of this struct. + let mut mutated_ty = config.changed_types[field].unwrap_or(field.ty).clone(); + let layout_ctor = config.layout_ctor[field]; + let is_opaque = layout_ctor.is_opaque(); + + let is_function = match mutated_ty { + Type::BareFn { .. } => !is_opaque, + _ => false, + }; + + let visit_info = tv.visit_field(&mut mutated_ty); + + let mutated_ty = arenas.alloc(mutated_ty); + + let field_accessor = config.override_field_accessor[field] + .unwrap_or_else(|| config.kind.field_accessor(config.mod_refl_mode, field)); + + let name = config.renamed_fields[field].unwrap_or_else(|| field.pat_ident()); + + let comp_field = CompTLField::from_expanded( + name, + visit_info.referenced_lifetimes.iter().cloned(), + field_accessor, + shared_vars.push_type(layout_ctor, mutated_ty), + is_function, + shared_vars, + ); + + let iterated_functions = if is_opaque { + Vec::new() + } else { + visit_info.functions + }; + + let functions = iterated_functions + .iter() + .enumerate() + .map(|(fn_i, func)| { + let name_span = name.span(); + let name_start_len = if is_function || iterated_functions.len() == 1 { + comp_field.name_start_len() + } else { + shared_vars.push_str(&format!("fn_{}", fn_i), Some(name_span)) + }; + + shared_vars.combine_err(name_start_len.check_ident_length(name_span)); + + let bound_lifetimes_start_len = shared_vars + .extend_with_idents(",", func.named_bound_lts.iter().cloned()); + + let params_iter = func.params.iter().map(|p| match p.name { + Some(pname) => (pname as &dyn std::fmt::Display, pname.span()), + None => (&"" as &dyn std::fmt::Display, Span::call_site()), }); - let param_names_len=shared_vars - .extend_with_display(",",params_iter) - .len; - - - let param_type_layouts= - TypeLayoutRange::compress_params(&func.params,shared_vars); - - let paramret_lifetime_range=shared_vars - .extend_with_lifetime_indices( - func.params.iter() + let param_names_len = shared_vars.extend_with_display(",", params_iter).len; + + let param_type_layouts = + TypeLayoutRange::compress_params(&func.params, shared_vars); + + let paramret_lifetime_range = shared_vars.extend_with_lifetime_indices( + func.params + .iter() .chain(&func.returns) - .flat_map(|p| p.lifetime_refs.iter().cloned() ) + .flat_map(|p| p.lifetime_refs.iter().cloned()), ); - let return_type_layout=match &func.returns { - Some(ret) => shared_vars.push_type(layout_ctor,ret.ty ).to_u10(), - None => !0, - }; - - CompTLFunction{ - name:name_start_len, - contiguous_strings_offset:bound_lifetimes_start_len.start, - bound_lifetimes_len:bound_lifetimes_start_len.len, - param_names_len, - param_type_layouts, - paramret_lifetime_range, - return_type_layout, - } - }) - .collect::>(); - - fn_ptr_count+=functions.len(); - - VisitedField{ - comp_field, - layout_ctor, - functions, - _marker:PhantomData, - } - }) - .collect::>>(); - - shared_vars.combine_err( tv.get_errors() ); - - Self{ + let return_type_layout = match &func.returns { + Some(ret) => shared_vars.push_type(layout_ctor, ret.ty).to_u10(), + None => !0, + }; + + CompTLFunction { + name: name_start_len, + contiguous_strings_offset: bound_lifetimes_start_len.start, + bound_lifetimes_len: bound_lifetimes_start_len.len, + param_names_len, + param_type_layouts, + paramret_lifetime_range, + return_type_layout, + } + }) + .collect::>(); + + fn_ptr_count += functions.len(); + + VisitedField { + comp_field, + layout_ctor, + functions, + _marker: PhantomData, + } + }) + .collect::>>(); + + shared_vars.combine_err(tv.get_errors()); + + Self { map, fn_ptr_count, - priv_:(), + priv_: (), } } } - /////////////////////////////////////////////////////////////////////////////// - /// A `Field<'a>` with extra information. #[allow(dead_code)] -pub struct VisitedField<'a>{ +pub struct VisitedField<'a> { pub(crate) comp_field: CompTLField, - pub(crate) layout_ctor:LayoutConstructor, + pub(crate) layout_ctor: LayoutConstructor, /// The function pointers from this field. - pub(crate) functions:Vec, - _marker:PhantomData<&'a ()>, + pub(crate) functions: Vec, + _marker: PhantomData<&'a ()>, } - - /////////////////////////////////////////////////////////////////////////////// - /// This is how a function pointer is stored, /// in which every field is a range into `TLFunctions`. -#[derive(Copy,Clone,Debug,PartialEq,Eq,Ord,PartialOrd)] -pub struct CompTLFunction{ - name:StartLen, - contiguous_strings_offset:u16, - bound_lifetimes_len:u16, - param_names_len:u16, +#[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd)] +pub struct CompTLFunction { + name: StartLen, + contiguous_strings_offset: u16, + bound_lifetimes_len: u16, + param_names_len: u16, /// Stores `!0` if the return type is `()`. - return_type_layout:u16, - paramret_lifetime_range:LifetimeRange, - param_type_layouts:TypeLayoutRange, + return_type_layout: u16, + paramret_lifetime_range: LifetimeRange, + param_type_layouts: TypeLayoutRange, } - impl ToTokens for CompTLFunction { fn to_tokens(&self, ts: &mut TokenStream2) { - let name=self.name.to_u32(); - - let contiguous_strings_offset=self.contiguous_strings_offset; - let bound_lifetimes_len=self.bound_lifetimes_len; - let param_names_len=self.param_names_len; - let return_type_layout=self.return_type_layout; - let paramret_lifetime_range=self.paramret_lifetime_range.to_u21(); - let param_type_layouts=self.param_type_layouts.to_u64(); + let name = self.name.to_u32(); + let contiguous_strings_offset = self.contiguous_strings_offset; + let bound_lifetimes_len = self.bound_lifetimes_len; + let param_names_len = self.param_names_len; + let return_type_layout = self.return_type_layout; + let paramret_lifetime_range = self.paramret_lifetime_range.to_u21(); + let param_type_layouts = self.param_type_layouts.to_u64(); quote!( __CompTLFunction::new( @@ -205,9 +198,7 @@ impl ToTokens for CompTLFunction { #paramret_lifetime_range, #param_type_layouts, ) - ).to_tokens(ts); - - + ) + .to_tokens(ts); } } - diff --git a/abi_stable_derive/src/stable_abi/tl_multi_tl.rs b/abi_stable_derive/src/stable_abi/tl_multi_tl.rs index 673459dd..5900f53f 100644 --- a/abi_stable_derive/src/stable_abi/tl_multi_tl.rs +++ b/abi_stable_derive/src/stable_abi/tl_multi_tl.rs @@ -1,60 +1,55 @@ use super::*; -use crate::{ - fn_pointer_extractor::FnParamRet, -}; +use crate::fn_pointer_extractor::FnParamRet; - - -abi_stable_shared::declare_type_layout_index!{ +abi_stable_shared::declare_type_layout_index! { attrs=[] } -impl TypeLayoutIndex{ +impl TypeLayoutIndex { /// Used to recover from syn errors, /// this value shouldn't be used in the layout constant since it's reserved /// for errors. - pub const DUMMY:Self=Self::from_u10(!0); + pub const DUMMY: Self = Self::from_u10(!0); } - - - - -abi_stable_shared:: declare_multi_tl_types!{ +abi_stable_shared::declare_multi_tl_types! { attrs=[] } - -impl TypeLayoutRange{ +impl TypeLayoutRange { pub(crate) fn compress_params<'a>( - params:&[FnParamRet<'a>], - shared_vars:&mut SharedVars<'a>, - )->Self{ - let param_len=params.len(); + params: &[FnParamRet<'a>], + shared_vars: &mut SharedVars<'a>, + ) -> Self { + let param_len = params.len(); if param_len <= TypeLayoutRange::STORED_INLINE { - let mut arr=[0u16;TypeLayoutRange::STORED_INLINE]; + let mut arr = [0u16; TypeLayoutRange::STORED_INLINE]; - for (p_i,param) in params.iter().enumerate() { - let ty:&'a syn::Type=param.ty; - arr[p_i]=shared_vars.push_type( LayoutConstructor::Regular,ty ).to_u10(); + for (p_i, param) in params.iter().enumerate() { + let ty: &'a syn::Type = param.ty; + arr[p_i] = shared_vars + .push_type(LayoutConstructor::Regular, ty) + .to_u10(); } - Self::with_up_to_5(param_len,arr) - }else{ - const I_BEFORE:usize=TypeLayoutRange::STORED_INLINE-1; - let mut arr=[0u16;TypeLayoutRange::STORED_INLINE]; + Self::with_up_to_5(param_len, arr) + } else { + const I_BEFORE: usize = TypeLayoutRange::STORED_INLINE - 1; + let mut arr = [0u16; TypeLayoutRange::STORED_INLINE]; - let mut iter=params.iter().map(|p|->&'a syn::Type{ p.ty }); - for (p_i,ty) in iter.by_ref().take(I_BEFORE).enumerate() { - arr[p_i]=shared_vars.push_type( LayoutConstructor::Regular,ty ).to_u10(); + let mut iter = params.iter().map(|p| -> &'a syn::Type { p.ty }); + for (p_i, ty) in iter.by_ref().take(I_BEFORE).enumerate() { + arr[p_i] = shared_vars + .push_type(LayoutConstructor::Regular, ty) + .to_u10(); } - arr[I_BEFORE]=shared_vars.extend_type(LayoutConstructor::Regular,iter).start; + arr[I_BEFORE] = shared_vars + .extend_type(LayoutConstructor::Regular, iter) + .start; - Self::with_more_than_5(param_len,arr) + Self::with_more_than_5(param_len, arr) } } - - -} \ No newline at end of file +} diff --git a/abi_stable_derive/src/utils.rs b/abi_stable_derive/src/utils.rs index 0c39f8bd..06ec6365 100644 --- a/abi_stable_derive/src/utils.rs +++ b/abi_stable_derive/src/utils.rs @@ -1,13 +1,13 @@ use std::time::Instant; -use abi_stable_shared::test_utils::{FileSpan}; +use abi_stable_shared::test_utils::FileSpan; pub(crate) use as_derive_utils::utils::{ - join_spans, dummy_ident, - type_from_ident, expr_from_ident, expr_from_int, + join_spans, + type_from_ident, //take_manuallydrop, uint_lit, LinearResult, @@ -15,29 +15,26 @@ pub(crate) use as_derive_utils::utils::{ SynResultExt, }; - #[allow(dead_code)] -pub struct PrintDurationOnDrop{ - start:Instant, - file_span:FileSpan, +pub struct PrintDurationOnDrop { + start: Instant, + file_span: FileSpan, } -impl PrintDurationOnDrop{ +impl PrintDurationOnDrop { #[allow(dead_code)] - pub fn new(file_span:FileSpan)->Self{ - Self{ - start:Instant::now(), + pub fn new(file_span: FileSpan) -> Self { + Self { + start: Instant::now(), file_span, } } } -impl Drop for PrintDurationOnDrop{ - fn drop(&mut self){ +impl Drop for PrintDurationOnDrop { + fn drop(&mut self) { let span = self.file_span; let dur = self.start.elapsed(); - println!("{}-{}:taken {:?} to run",span.file,span.line,dur); + println!("{}-{}:taken {:?} to run", span.file, span.line, dur); } } - - diff --git a/abi_stable_derive/src/workaround.rs b/abi_stable_derive/src/workaround.rs index 6fdaeb5b..37a53603 100644 --- a/abi_stable_derive/src/workaround.rs +++ b/abi_stable_derive/src/workaround.rs @@ -1,80 +1,75 @@ /*! -Wrote this as a workaround for +Wrote this as a workaround for `::fmt` not working correctly for some reason. */ -use std::{ - fmt::Write, - mem, -}; +use std::{fmt::Write, mem}; -use proc_macro2::{TokenStream as TokenStream2,TokenTree,Delimiter,Spacing}; +use proc_macro2::{Delimiter, Spacing, TokenStream as TokenStream2, TokenTree}; use core_extensions::SelfOps; -struct WriteState{ - add_spacing_before:bool, +struct WriteState { + add_spacing_before: bool, } - - -fn write_token_tree_inner(tt:TokenTree,s:&mut String,state:&mut WriteState){ - let _added_spacing=mem::replace(&mut state.add_spacing_before,false); +fn write_token_tree_inner(tt: TokenTree, s: &mut String, state: &mut WriteState) { + let _added_spacing = mem::replace(&mut state.add_spacing_before, false); match tt { - TokenTree::Group(group)=>{ - let (start,end)=match group.delimiter() { - Delimiter::Parenthesis=>('(',')'), - Delimiter::Brace=>('{','}'), - Delimiter::Bracket=>('[',']'), - Delimiter::None=>(' ',' '), + TokenTree::Group(group) => { + let (start, end) = match group.delimiter() { + Delimiter::Parenthesis => ('(', ')'), + Delimiter::Brace => ('{', '}'), + Delimiter::Bracket => ('[', ']'), + Delimiter::None => (' ', ' '), }; - let _=write!(s,"{} ",start); + let _ = write!(s, "{} ", start); for nested_tt in group.stream() { - write_token_tree(nested_tt,s); + write_token_tree(nested_tt, s); } - state.add_spacing_before=false; - let _=write!(s," {}",end); - }, - TokenTree::Ident(x)=>write!(s,"{} ",x).drop_(), - TokenTree::Punct(punct)=>{ + state.add_spacing_before = false; + let _ = write!(s, " {}", end); + } + TokenTree::Ident(x) => write!(s, "{} ", x).drop_(), + TokenTree::Punct(punct) => { // if added_spacing { // s.push(' '); // } s.push(punct.as_char()); - state.add_spacing_before=match punct.spacing() { - Spacing::Alone=>{ + state.add_spacing_before = match punct.spacing() { + Spacing::Alone => { s.push(' '); true - }, + } // Spacing::Alone=>true, - Spacing::Joint=>false, + Spacing::Joint => false, } - }, - TokenTree::Literal(x)=>write!(s,"{} ",x).drop_(), + } + TokenTree::Literal(x) => write!(s, "{} ", x).drop_(), } } -fn write_token_tree(tt:TokenTree,s:&mut String){ +fn write_token_tree(tt: TokenTree, s: &mut String) { write_token_tree_inner( tt, s, - &mut WriteState{ - add_spacing_before:false, - } + &mut WriteState { + add_spacing_before: false, + }, ) } -pub fn write_token_stream(ts:TokenStream2,buffer:&mut String){ +pub fn write_token_stream(ts: TokenStream2, buffer: &mut String) { for tt in ts { - write_token_tree(tt,buffer); + write_token_tree(tt, buffer); } } -pub fn token_stream_to_string(ts:TokenStream2)->String{ - let mut buffer=String::new(); - write_token_stream(ts,&mut buffer); +pub fn token_stream_to_string(ts: TokenStream2) -> String { + let mut buffer = String::new(); + write_token_stream(ts, &mut buffer); buffer -} \ No newline at end of file +} diff --git a/abi_stable_shared/src/const_utils.rs b/abi_stable_shared/src/const_utils.rs index 576ae061..b3aa0858 100644 --- a/abi_stable_shared/src/const_utils.rs +++ b/abi_stable_shared/src/const_utils.rs @@ -1,6 +1,5 @@ - /// Gets a u64 where the lowest `bit_count` bits are ones and the rest are zeroes. -pub const fn low_bit_mask_u64(bit_count:u32)->u64{ - let (n,overflowed)=1u64.overflowing_shl(bit_count); +pub const fn low_bit_mask_u64(bit_count: u32) -> u64 { + let (n, overflowed) = 1u64.overflowing_shl(bit_count); n.wrapping_sub(1).wrapping_sub(overflowed as u64) -} \ No newline at end of file +} diff --git a/abi_stable_shared/src/lib.rs b/abi_stable_shared/src/lib.rs index 04616e7c..b446b9ad 100644 --- a/abi_stable_shared/src/lib.rs +++ b/abi_stable_shared/src/lib.rs @@ -5,7 +5,7 @@ pub mod test_utils; pub mod const_utils; #[doc(hidden)] -pub mod type_layout{ +pub mod type_layout { pub mod small_types; pub mod tl_field_accessor_macro; pub mod tl_field_macro; @@ -14,60 +14,59 @@ pub mod type_layout{ pub mod tl_type_layout_index; } - use core_extensions::StringExt; /// The name mangling scheme of `abi_stable`. #[doc(hidden)] -pub fn mangle_ident(kind:&str,name:S)->String -where S: ::std::fmt::Display +pub fn mangle_ident(kind: &str, name: S) -> String +where + S: ::std::fmt::Display, { + let unmangled = format!("_as.{}.{}", kind, name); - let unmangled=format!("_as.{}.{}",kind,name); - - let mut mangled=String::with_capacity(unmangled.len()*3/2); + let mut mangled = String::with_capacity(unmangled.len() * 3 / 2); - for kv in unmangled.split_while(|c| c.is_alphanumeric() ) { + for kv in unmangled.split_while(|c| c.is_alphanumeric()) { if kv.key { mangled.push_str(kv.str); - continue + continue; } for c in kv.str.chars() { mangled.push_str(match c { - '.'=>"_0", - '_'=>"_1", - '-'=>"_2", - '<'=>"_3", - '>'=>"_4", - '('=>"_5", - ')'=>"_6", - '['=>"_7", - ']'=>"_8", - '{'=>"_9", - '}'=>"_a", - ' '=>"_b", - ','=>"_c", - ':'=>"_d", - ';'=>"_e", - '!'=>"_f", - '#'=>"_g", - '$'=>"_h", - '%'=>"_i", - '/'=>"_j", - '='=>"_k", - '?'=>"_l", - '¿'=>"_m", - '¡'=>"_o", - '*'=>"_p", - '+'=>"_q", - '~'=>"_r", - '|'=>"_s", - '°'=>"_t", - '¬'=>"_u", - '\''=>"_x", - '\"'=>"_y", - '`'=>"_z", - c=>panic!("cannot currently mangle the '{}' character.", c), + '.' => "_0", + '_' => "_1", + '-' => "_2", + '<' => "_3", + '>' => "_4", + '(' => "_5", + ')' => "_6", + '[' => "_7", + ']' => "_8", + '{' => "_9", + '}' => "_a", + ' ' => "_b", + ',' => "_c", + ':' => "_d", + ';' => "_e", + '!' => "_f", + '#' => "_g", + '$' => "_h", + '%' => "_i", + '/' => "_j", + '=' => "_k", + '?' => "_l", + '¿' => "_m", + '¡' => "_o", + '*' => "_p", + '+' => "_q", + '~' => "_r", + '|' => "_s", + '°' => "_t", + '¬' => "_u", + '\'' => "_x", + '\"' => "_y", + '`' => "_z", + c => panic!("cannot currently mangle the '{}' character.", c), }); } } @@ -75,10 +74,7 @@ where S: ::std::fmt::Display mangled } - /// Gets the name of the static that contains the LibHeader of an abi_stable library. -pub fn mangled_root_module_loader_name()->String{ - mangle_ident("lib_header","root module loader") +pub fn mangled_root_module_loader_name() -> String { + mangle_ident("lib_header", "root module loader") } - - diff --git a/abi_stable_shared/src/test_utils.rs b/abi_stable_shared/src/test_utils.rs index de5929b9..9f8bdcb1 100644 --- a/abi_stable_shared/src/test_utils.rs +++ b/abi_stable_shared/src/test_utils.rs @@ -3,8 +3,7 @@ use std::{ panic::{catch_unwind, AssertUnwindSafe}, }; - -#[derive(Debug, Clone,Copy,Eq,PartialEq)] +#[derive(Debug, Clone, Copy, Eq, PartialEq)] pub struct FileSpan { pub file: &'static str, pub line: u32, diff --git a/abi_stable_shared/src/type_layout/small_types.rs b/abi_stable_shared/src/type_layout/small_types.rs index aa6a033e..d96aba71 100644 --- a/abi_stable_shared/src/type_layout/small_types.rs +++ b/abi_stable_shared/src/type_layout/small_types.rs @@ -1,35 +1,34 @@ #[doc(hidden)] #[macro_export] -macro_rules! declare_start_len_bit_methods {() => ( +macro_rules! declare_start_len_bit_methods { + () => { + /// The amount of bits used to represent a StartLen + pub const BIT_SIZE: u32 = 26; + const START_SR_MASK: u32 = 0xFFFF; + const LEN_SR_MASK: u32 = 0b11_1111_1111; + pub(crate) const IDENT_MAX_LEN: u16 = Self::LEN_SR_MASK as u16; + const LEN_OFFSET: u32 = 16; - /// The amount of bits used to represent a StartLen - pub const BIT_SIZE:u32=26; - const START_SR_MASK:u32=0xFFFF; - const LEN_SR_MASK:u32=0b11_1111_1111; - pub(crate) const IDENT_MAX_LEN:u16=Self::LEN_SR_MASK as u16; - const LEN_OFFSET:u32=16; + /// The exclusive end of this range. + #[inline] + pub const fn end(self) -> usize { + (self.start() + self.len()) as usize + } - /// The exclusive end of this range. - #[inline] - pub const fn end(self)->usize{ - (self.start()+self.len()) as usize - } + /// Constructs a StartLen from a bitfield encoded as + /// (start:16 bits) + (length: 10 bits) . + pub const fn from_u26(n: u32) -> Self { + Self::new( + (n & Self::START_SR_MASK) as _, + ((n >> Self::LEN_OFFSET) & Self::LEN_SR_MASK) as _, + ) + } - /// Constructs a StartLen from a bitfield encoded as - /// (start:16 bits) + (length: 10 bits) . - pub const fn from_u26(n:u32)->Self{ - Self::new( - (n & Self::START_SR_MASK) as _, - ((n>>Self::LEN_OFFSET)& Self::LEN_SR_MASK)as _, - ) - } - - /// Converts this StartLen to bitfields encoded as - /// (start:16 bits) + (length: 10 bits) . - pub const fn to_u26(self)->u32{ - (self.start() as u32)&Self::START_SR_MASK - |((self.len() as u32 & Self::LEN_SR_MASK ) << Self::LEN_OFFSET) - } - - -)} \ No newline at end of file + /// Converts this StartLen to bitfields encoded as + /// (start:16 bits) + (length: 10 bits) . + pub const fn to_u26(self) -> u32 { + (self.start() as u32) & Self::START_SR_MASK + | ((self.len() as u32 & Self::LEN_SR_MASK) << Self::LEN_OFFSET) + } + }; +} diff --git a/abi_stable_shared/src/type_layout/tl_field_accessor_macro.rs b/abi_stable_shared/src/type_layout/tl_field_accessor_macro.rs index 6262fc73..91c1b00b 100644 --- a/abi_stable_shared/src/type_layout/tl_field_accessor_macro.rs +++ b/abi_stable_shared/src/type_layout/tl_field_accessor_macro.rs @@ -1,6 +1,6 @@ #[doc(hidden)] #[macro_export] -macro_rules! declare_comp_field_accessor {( +macro_rules! declare_comp_field_accessor {( attrs=[ $($extra_attrs:meta),* $(,)* ] ) => ( @@ -10,7 +10,7 @@ macro_rules! declare_comp_field_accessor {( #[derive(Debug, Copy, Clone, PartialEq, Eq)] $(#[ $extra_attrs ])* pub struct CompFieldAccessor(u8); - + /// The type that CompFieldAccessor is represented as. pub type CompFieldAccessorRepr=u8; @@ -20,7 +20,7 @@ macro_rules! declare_comp_field_accessor {( /// Equivalent to the `FieldAccessor::Method` variant. pub const METHOD:Self=CompFieldAccessor(1); /// Equivalent to the `FieldAccessor::MethodNamed` variant, - /// in which the name is stored within SharedVars after the + /// in which the name is stored within SharedVars after the /// name of the field this is an accessor for. pub const METHOD_NAMED:Self=CompFieldAccessor(2); /// Equivalent to the `FieldAccessor::MethodOption` variant. @@ -39,7 +39,7 @@ macro_rules! declare_comp_field_accessor {( pub const fn to_u3(self)->u8{ self.0&Self::MASK } - + /// Constructs this `CompFieldAccessor` from its representation. pub const fn from_u3(n:u8)->Self{ CompFieldAccessor(n&Self::MASK) @@ -48,4 +48,4 @@ macro_rules! declare_comp_field_accessor {( core_extensions::matches!(self, Self::METHOD_NAMED) } } -)} \ No newline at end of file +)} diff --git a/abi_stable_shared/src/type_layout/tl_field_macro.rs b/abi_stable_shared/src/type_layout/tl_field_macro.rs index d5571184..e7923b35 100644 --- a/abi_stable_shared/src/type_layout/tl_field_macro.rs +++ b/abi_stable_shared/src/type_layout/tl_field_macro.rs @@ -1,9 +1,9 @@ #[doc(hidden)] #[macro_export] -macro_rules! declare_comp_tl_field {( +macro_rules! declare_comp_tl_field {( attrs=[ $($extra_attrs:meta),* $(,)* ] ) => ( - + /// A `TLField` represented as a `u64`, /// expadable to a `TLField` by calling the `expand` method. #[repr(transparent)] @@ -18,11 +18,11 @@ macro_rules! declare_comp_tl_field {( impl CompTLField{ const NAME_OFFSET:u32=0; - + const LIFETIME_INDICES_OFFSET:u32=StartLen::BIT_SIZE; - + const FIELD_ACCESSOR_OFFSET:u32=Self::LIFETIME_INDICES_OFFSET+LifetimeRange::BIT_SIZE; - + const TYPE_LAYOUT_OFFSET:u32=Self::FIELD_ACCESSOR_OFFSET+CompFieldAccessor::BIT_SIZE; const TYPE_LAYOUT_SR_MASK:u64=TypeLayoutIndex::MASK as u64; @@ -98,4 +98,4 @@ macro_rules! declare_comp_tl_field {( ) } } -)} \ No newline at end of file +)} diff --git a/abi_stable_shared/src/type_layout/tl_lifetimes_macro.rs b/abi_stable_shared/src/type_layout/tl_lifetimes_macro.rs index ac360b26..8a5f01d0 100644 --- a/abi_stable_shared/src/type_layout/tl_lifetimes_macro.rs +++ b/abi_stable_shared/src/type_layout/tl_lifetimes_macro.rs @@ -1,6 +1,6 @@ #[doc(hidden)] #[macro_export] -macro_rules! declare_tl_lifetime_types {( +macro_rules! declare_tl_lifetime_types {( repr=$repr:ty, attrs=[ $($extra_attrs:meta),* $(,)* ] ) => ( @@ -132,14 +132,14 @@ macro_rules! declare_tl_lifetime_types {( /// Converts this array into its representation. #[inline] pub const fn to_u20(self) -> u32 { - self.bits&0xF_FF_FF - } + self.bits&0xF_FF_FF + } /// Constructs this array from its representation. #[inline] pub const fn from_u20(bits: u32) -> Self { Self { - bits:bits&0xF_FF_FF + bits:bits&0xF_FF_FF } } @@ -157,7 +157,7 @@ macro_rules! declare_tl_lifetime_types {( #[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd)] $(#[ $extra_attrs ])* pub struct LifetimeRange{ - /// 21 bits: + /// 21 bits: /// (13 for the start index | 12 for the LifetimeIndexArray) /// +8 bits for the length bits:u32, @@ -166,13 +166,13 @@ macro_rules! declare_tl_lifetime_types {( impl LifetimeRange{ /// An empty `LifetimeRange`. pub const EMPTY: Self = Self { bits: 0 }; - + const IS_RANGE_BIT: u32 = 1<<20; const RANGE_LEN_OFFSET: u32 = 13; const LEN_SR_MASK: u32 = 0b111_1111; const LEN_BIT_SIZE: u32 = 7; - + const MASK: u32 = 0x1F_FF_FF; const START_MASK: u32 = 0b1_1111_1111_1111; @@ -209,7 +209,7 @@ macro_rules! declare_tl_lifetime_types {( let len=range.end-range.start; Self{ bits: - Self::IS_RANGE_BIT + Self::IS_RANGE_BIT |((range.start as u32)&Self::START_MASK) |((len as u32 & Self::LEN_SR_MASK) << Self::RANGE_LEN_OFFSET) } @@ -317,4 +317,4 @@ macro_rules! declare_tl_lifetime_types {( } } -)} \ No newline at end of file +)} diff --git a/abi_stable_shared/src/type_layout/tl_multi_tl_macro.rs b/abi_stable_shared/src/type_layout/tl_multi_tl_macro.rs index 7446e40c..fd765193 100644 --- a/abi_stable_shared/src/type_layout/tl_multi_tl_macro.rs +++ b/abi_stable_shared/src/type_layout/tl_multi_tl_macro.rs @@ -1,12 +1,12 @@ #[doc(hidden)] #[macro_export] -macro_rules! declare_multi_tl_types {( +macro_rules! declare_multi_tl_types {( attrs=[ $($extra_attrs:meta),* $(,)* ] ) => ( - /// A range of indices into a slice of `TypeLayoutCtor` + /// A range of indices into a slice of `TypeLayoutCtor` /// which can store up to five indices inline, - /// requiring additional `TypeLayoutCtor` to be stored contiguously after the + /// requiring additional `TypeLayoutCtor` to be stored contiguously after the /// fourth one in the slice. #[repr(C)] #[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd)] @@ -37,11 +37,11 @@ macro_rules! declare_multi_tl_types {( const INDEX_2_OFFSET:u32=0; const INDEX_3_OFFSET:u32=TypeLayoutIndex::BIT_SIZE; const INDEX_4_OFFSET:u32=TypeLayoutIndex::BIT_SIZE*2; - + fn size_assertions(){ let _:[(); 32-(Self::LEN_BIT_SIZE+TypeLayoutIndex::BIT_SIZE*2)as usize ]; } - + /// Constructs a `TypeLayoutRange` with up to five type layout indices. #[inline] pub const fn with_up_to_5(mut len:usize,indices:[u16;5])->Self{ @@ -49,7 +49,7 @@ macro_rules! declare_multi_tl_types {( Self::with_more_than_5(len,indices) } - /// Constructs a `TypeLayoutRange` with more + /// Constructs a `TypeLayoutRange` with more /// than five type layout indices, /// in which the indices from `indices[4]` onwards are /// stored contiguously in the slice. @@ -93,4 +93,3 @@ macro_rules! declare_multi_tl_types {( /////////////////////////////////////////////////////////////////////////////// )} - diff --git a/abi_stable_shared/src/type_layout/tl_type_layout_index.rs b/abi_stable_shared/src/type_layout/tl_type_layout_index.rs index 3891ae82..3f7c1d4a 100644 --- a/abi_stable_shared/src/type_layout/tl_type_layout_index.rs +++ b/abi_stable_shared/src/type_layout/tl_type_layout_index.rs @@ -1,6 +1,6 @@ #[doc(hidden)] #[macro_export] -macro_rules! declare_type_layout_index {( +macro_rules! declare_type_layout_index {( attrs=[ $($extra_attrs:meta),* $(,)* ] ) => ( /// An index for a slice of `TypeLayoutCtor`. @@ -15,10 +15,10 @@ macro_rules! declare_type_layout_index {( pub(crate) const MASK:u16=0b11_1111_1111; /// The amount of bits required to represent a `TypeLayoutIndex`. pub const BIT_SIZE:u32=10; - + /// The maximum value of a `TypeLayoutIndex`. pub const MAX_VAL_U16:u16=Self::MASK; - + /// The maximum value of a `TypeLayoutIndex`. pub const MAX_VAL:usize=Self::MAX_VAL_U16 as usize; @@ -27,7 +27,7 @@ macro_rules! declare_type_layout_index {( pub const fn from_u10(n:u16)->Self{ Self{bits: n & Self::MASK } } - + /// Converts this `TypeLayoutIndex` into its representation. #[inline] pub const fn to_u10(self)->u16{ @@ -41,7 +41,7 @@ macro_rules! declare_type_layout_index {( } - + mod type_layout_index_impls{ use super::*; use std::fmt::{self,Display}; @@ -53,6 +53,6 @@ macro_rules! declare_type_layout_index {( } } } - -)} \ No newline at end of file + +)} diff --git a/as_derive_utils/src/attribute_parsing.rs b/as_derive_utils/src/attribute_parsing.rs index 3483fae3..0476b60b 100644 --- a/as_derive_utils/src/attribute_parsing.rs +++ b/as_derive_utils/src/attribute_parsing.rs @@ -1,13 +1,10 @@ -use syn::{ - Meta, NestedMeta, -}; - +use syn::{Meta, NestedMeta}; /// Iterates over an iterator of syn::NestedMeta, /// unwrapping it into a syn::Meta and passing it into the `f` closure. -pub fn with_nested_meta(attr_name: &str, iter: I, mut f: F)->Result<(),syn::Error> +pub fn with_nested_meta(attr_name: &str, iter: I, mut f: F) -> Result<(), syn::Error> where - F: FnMut(Meta)->Result<(),syn::Error>, + F: FnMut(Meta) -> Result<(), syn::Error>, I: IntoIterator, { for repr in iter { @@ -26,5 +23,3 @@ where } Ok(()) } - - diff --git a/as_derive_utils/src/datastructure.rs b/as_derive_utils/src/datastructure.rs index 1f2fbeaa..7136b14c 100644 --- a/as_derive_utils/src/datastructure.rs +++ b/as_derive_utils/src/datastructure.rs @@ -9,19 +9,12 @@ use quote::ToTokens; use proc_macro2::{Span, TokenStream}; - -use std::fmt::{self,Display}; - - +use std::fmt::{self, Display}; mod field_map; mod type_param_map; -pub use self::{ - field_map::FieldMap, - type_param_map::TypeParamMap, - -}; +pub use self::{field_map::FieldMap, type_param_map::TypeParamMap}; ////////////////////////////////////////////////////////////////////////////// @@ -46,7 +39,6 @@ pub struct DataStructure<'a> { pub variants: Vec>, } - impl<'a> DataStructure<'a> { pub fn new(ast: &'a DeriveInput) -> Self { let name = &ast.ident; @@ -55,20 +47,17 @@ impl<'a> DataStructure<'a> { let mut variants = Vec::new(); - match &ast.data { Data::Enum(enum_) => { - let override_vis=Some(&ast.vis); + let override_vis = Some(&ast.vis); - for (variant,var) in enum_.variants.iter().enumerate() { + for (variant, var) in enum_.variants.iter().enumerate() { variants.push(Struct::new( - StructParams{ - discriminant:var.discriminant - .as_ref() - .map(|(_,v)| v ), + StructParams { + discriminant: var.discriminant.as_ref().map(|(_, v)| v), variant, - attrs:&var.attrs, - name:&var.ident, + attrs: &var.attrs, + name: &var.ident, override_vis, }, &var.fields, @@ -77,13 +66,13 @@ impl<'a> DataStructure<'a> { data_variant = DataVariant::Enum; } Data::Struct(struct_) => { - let override_vis=None; + let override_vis = None; variants.push(Struct::new( - StructParams{ - discriminant:None, - variant:0, - attrs:&[], + StructParams { + discriminant: None, + variant: 0, + attrs: &[], name, override_vis, }, @@ -93,19 +82,19 @@ impl<'a> DataStructure<'a> { } Data::Union(union_) => { - let override_vis=None; + let override_vis = None; let fields = Some(&union_.fields.named); let sk = StructKind::Braced; let vari = Struct::with_fields( - StructParams{ - discriminant:None, - variant:0, - attrs:&[], - name, + StructParams { + discriminant: None, + variant: 0, + attrs: &[], + name, override_vis, }, - sk, + sk, fields, ); variants.push(vari); @@ -113,12 +102,12 @@ impl<'a> DataStructure<'a> { } } - let mut field_count=0; - let mut pub_field_count=0; + let mut field_count = 0; + let mut pub_field_count = 0; for vari in &variants { - field_count+=vari.fields.len(); - pub_field_count+=vari.pub_field_count; + field_count += vari.fields.len(); + pub_field_count += vari.pub_field_count; } Self { @@ -126,7 +115,7 @@ impl<'a> DataStructure<'a> { name, attrs: &ast.attrs, generics: &ast.generics, - lifetime_count:ast.generics.lifetimes().count(), + lifetime_count: ast.generics.lifetimes().count(), data_variant, variants, field_count, @@ -134,8 +123,8 @@ impl<'a> DataStructure<'a> { } } - pub fn has_public_fields(&self)->bool{ - self.pub_field_count!=0 + pub fn has_public_fields(&self) -> bool { + self.pub_field_count != 0 } } @@ -157,23 +146,21 @@ pub enum DataVariant { Union, } - -#[derive(Copy,Clone, Debug, PartialEq, Hash)] +#[derive(Copy, Clone, Debug, PartialEq, Hash)] pub struct FieldIndex { - pub variant:usize, - pub pos:usize, + pub variant: usize, + pub pos: usize, } ////////////////////////////////////////////////////////////////////////////// - -#[derive(Copy,Clone)] -struct StructParams<'a>{ - discriminant:Option<&'a syn::Expr>, - variant:usize, +#[derive(Copy, Clone)] +struct StructParams<'a> { + discriminant: Option<&'a syn::Expr>, + variant: usize, attrs: &'a [Attribute], name: &'a Ident, - override_vis:Option<&'a Visibility>, + override_vis: Option<&'a Visibility>, } /// A struct/union or a variant of an enum. @@ -193,22 +180,19 @@ pub struct Struct<'a> { pub name: &'a Ident, pub kind: StructKind, pub fields: Vec>, - pub pub_field_count:usize, + pub pub_field_count: usize, /// The value of this discriminant. /// /// If this is a Some(_):This is an enum with an explicit discriminant value. /// /// If this is an None: /// This is either a struct/union or an enum variant without an explicit discriminant. - pub discriminant:Option<&'a syn::Expr>, + pub discriminant: Option<&'a syn::Expr>, _priv: (), } impl<'a> Struct<'a> { - fn new( - p:StructParams<'a>, - fields: &'a SynFields, - ) -> Self { + fn new(p: StructParams<'a>, fields: &'a SynFields) -> Self { let kind = match *fields { SynFields::Named { .. } => StructKind::Braced, SynFields::Unnamed { .. } => StructKind::Tuple, @@ -223,39 +207,34 @@ impl<'a> Struct<'a> { Self::with_fields(p, kind, fields) } - fn with_fields( - p:StructParams<'a>, - kind: StructKind, - fields: Option, - ) -> Self + fn with_fields(p: StructParams<'a>, kind: StructKind, fields: Option) -> Self where I: IntoIterator, { - let fields=match fields { + let fields = match fields { Some(x) => Field::from_iter(p, x), None => Vec::new(), }; - let mut pub_field_count=0usize; + let mut pub_field_count = 0usize; for field in &fields { if field.is_public() { - pub_field_count+=1; + pub_field_count += 1; } } Self { - discriminant:p.discriminant, - attrs:p.attrs, - name:p.name, + discriminant: p.discriminant, + attrs: p.attrs, + name: p.name, kind, pub_field_count, fields, _priv: (), } } - - } +} ////////////////////////////////////////////////////////////////////////////// @@ -263,7 +242,7 @@ impl<'a> Struct<'a> { /// #[derive(Clone, Debug, PartialEq, Hash)] pub struct Field<'a> { - pub index:FieldIndex, + pub index: FieldIndex, pub attrs: &'a [Attribute], pub vis: &'a Visibility, /// identifier for the field,which is either an index(in a tuple struct) or a name. @@ -276,7 +255,7 @@ impl<'a> Field<'a> { index: FieldIndex, field: &'a SynField, span: Span, - override_vis:Option<&'a Visibility>, + override_vis: Option<&'a Visibility>, ) -> Self { let ident = match field.ident.as_ref() { Some(ident) => FieldIdent::Named(ident), @@ -292,8 +271,8 @@ impl<'a> Field<'a> { } } - pub fn is_public(&self)->bool{ - matches!(self.vis, Visibility::Public{..}) + pub fn is_public(&self) -> bool { + matches!(self.vis, Visibility::Public { .. }) } /// Gets the identifier of this field usable for the variable in a pattern. @@ -311,26 +290,26 @@ impl<'a> Field<'a> { /// quote::quote!( let Foo{#field_name: #variable} = bar; ) /// } /// ``` - pub fn pat_ident(&self)->&Ident{ + pub fn pat_ident(&self) -> &Ident { match &self.ident { - FieldIdent::Index(_,ident)=>ident, - FieldIdent::Named(ident)=>ident, + FieldIdent::Index(_, ident) => ident, + FieldIdent::Named(ident) => ident, } } - fn from_iter( - p:StructParams<'a>, - fields: I, - ) -> Vec + fn from_iter(p: StructParams<'a>, fields: I) -> Vec where I: IntoIterator, { fields .into_iter() .enumerate() - .map(|(pos, f)|{ - let fi=FieldIndex{variant:p.variant,pos}; - Field::new(fi, f, p.name.span(),p.override_vis) + .map(|(pos, f)| { + let fi = FieldIndex { + variant: p.variant, + pos, + }; + Field::new(fi, f, p.name.span(), p.override_vis) }) .collect() } @@ -344,11 +323,11 @@ pub enum FieldIdent<'a> { Named(&'a Ident), } -impl<'a> Display for FieldIdent<'a>{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ +impl<'a> Display for FieldIdent<'a> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - FieldIdent::Index(x, ..) => Display::fmt(x,f), - FieldIdent::Named(x) => Display::fmt(x,f), + FieldIdent::Index(x, ..) => Display::fmt(x, f), + FieldIdent::Named(x) => Display::fmt(x, f), } } } @@ -367,4 +346,3 @@ impl<'a> FieldIdent<'a> { FieldIdent::Index(index, Ident::new(&format!("field_{}", index), span)) } } - diff --git a/as_derive_utils/src/datastructure/field_map.rs b/as_derive_utils/src/datastructure/field_map.rs index 0106505c..eb90d189 100644 --- a/as_derive_utils/src/datastructure/field_map.rs +++ b/as_derive_utils/src/datastructure/field_map.rs @@ -2,7 +2,7 @@ use super::*; use std::{ mem, - ops::{Index,IndexMut}, + ops::{Index, IndexMut}, }; /** @@ -12,142 +12,137 @@ If you put this in a type,and use Default to initialize it, you must remember to replace the `FieldMap` using either `FieldMap::defaulted` or `FieldMap::with` */ -#[derive(Default,Clone, Debug, PartialEq, Hash)] +#[derive(Default, Clone, Debug, PartialEq, Hash)] pub struct FieldMap { // The outer vec is the enum variant (if it's a struct/union it's a single element Vec), // the inner one is the field within a variant/struct/union. - fields:Vec>, + fields: Vec>, } -impl FieldMap{ +impl FieldMap { /// Constructs an empty FieldMap. - pub fn empty()->Self{ - Self{ - fields:Vec::new(), - } + pub fn empty() -> Self { + Self { fields: Vec::new() } } - /// Constructs an FieldMap which maps each field in the DataStructure + /// Constructs an FieldMap which maps each field in the DataStructure /// to the default value for `T`. - pub fn defaulted<'a>(ds:&'a DataStructure<'a>)->Self - where - T:Default + pub fn defaulted<'a>(ds: &'a DataStructure<'a>) -> Self + where + T: Default, { - Self::with(ds,|_| T::default() ) + Self::with(ds, |_| T::default()) } - + /// Constructs an FieldMap which maps each field in the DataStructure to a value /// (obtained by mapping each individual field to `T` using a closure). - pub fn with<'a,F>(ds:&'a DataStructure<'a>,mut f:F)->Self + pub fn with<'a, F>(ds: &'a DataStructure<'a>, mut f: F) -> Self where - F:FnMut(&'a Field<'a>)->T + F: FnMut(&'a Field<'a>) -> T, { - Self{ - fields:ds.variants + Self { + fields: ds + .variants .iter() - .map(|vari|{ - vari.fields.iter().map(&mut f).collect::>() - }) + .map(|vari| vari.fields.iter().map(&mut f).collect::>()) .collect::>(), } } /// Maps each value in the map to another one,using a closure. - pub fn map(self,mut f:F)->FieldMap + pub fn map(self, mut f: F) -> FieldMap where - F:FnMut(FieldIndex,T)->U + F: FnMut(FieldIndex, T) -> U, { - let fields=self.fields + let fields = self + .fields .into_iter() .enumerate() - .map(|(var_i,variant)|{ + .map(|(var_i, variant)| { variant - .into_iter() - .enumerate() - .map(|(pos,v)|{ - let index=FieldIndex{ - variant:var_i, - pos, - }; - f(index,v) - }) - .collect::>() + .into_iter() + .enumerate() + .map(|(pos, v)| { + let index = FieldIndex { + variant: var_i, + pos, + }; + f(index, v) + }) + .collect::>() }) .collect::>>(); - FieldMap{fields} + FieldMap { fields } } /// Whether the field index maps to a field. #[allow(dead_code)] - pub fn contains_index(&self,index:FieldIndex)->bool{ + pub fn contains_index(&self, index: FieldIndex) -> bool { self.fields .get(index.variant) - .map_or(false,|variant| index.pos < variant.len() ) + .map_or(false, |variant| index.pos < variant.len()) } /// Add a new field to the map along with a value that it maps into. - pub fn insert(&mut self,field:&Field<'_>,value:T)->T{ + pub fn insert(&mut self, field: &Field<'_>, value: T) -> T { mem::replace(&mut self[field], value) } - pub fn iter(&self)->impl Iterator+Clone+'_ { - self.fields - .iter().enumerate() - .flat_map(|(v_i,v)|{ - v.iter().enumerate() - .map(move|(f_i,f)|{ - let index=FieldIndex{variant:v_i as _, pos: f_i as _}; - ( index, f ) - }) + pub fn iter(&self) -> impl Iterator + Clone + '_ { + self.fields.iter().enumerate().flat_map(|(v_i, v)| { + v.iter().enumerate().map(move |(f_i, f)| { + let index = FieldIndex { + variant: v_i as _, + pos: f_i as _, + }; + (index, f) }) + }) } - pub fn iter_mut(&mut self)->impl Iterator+'_ { - self.fields - .iter_mut().enumerate() - .flat_map(|(v_i,v)|{ - v.iter_mut().enumerate() - .map(move|(f_i,f)|{ - let index=FieldIndex{variant:v_i as _, pos: f_i as _}; - ( index, f ) - }) + pub fn iter_mut(&mut self) -> impl Iterator + '_ { + self.fields.iter_mut().enumerate().flat_map(|(v_i, v)| { + v.iter_mut().enumerate().map(move |(f_i, f)| { + let index = FieldIndex { + variant: v_i as _, + pos: f_i as _, + }; + (index, f) }) + }) } - pub fn values(&self)->impl Iterator+Clone+'_ { - self.fields.iter().flat_map(|v| v.iter() ) + pub fn values(&self) -> impl Iterator + Clone + '_ { + self.fields.iter().flat_map(|v| v.iter()) } } +impl<'a, T> Index for FieldMap { + type Output = T; -impl<'a,T> Index for FieldMap{ - type Output=T; - - fn index(&self,index:FieldIndex)->&T{ + fn index(&self, index: FieldIndex) -> &T { &self.fields[index.variant][index.pos] } } -impl<'a,T> IndexMut for FieldMap{ - fn index_mut(&mut self,index:FieldIndex)->&mut T{ +impl<'a, T> IndexMut for FieldMap { + fn index_mut(&mut self, index: FieldIndex) -> &mut T { &mut self.fields[index.variant][index.pos] } } +impl<'a, 'b, T> Index<&'a Field<'b>> for FieldMap { + type Output = T; -impl<'a,'b,T> Index<&'a Field<'b>> for FieldMap{ - type Output=T; - - fn index(&self,field:&'a Field<'b>)->&T{ - let index=field.index; + fn index(&self, field: &'a Field<'b>) -> &T { + let index = field.index; &self.fields[index.variant][index.pos] } } - -impl<'a,'b,T> IndexMut<&'a Field<'b>> for FieldMap{ - fn index_mut(&mut self,field:&'a Field<'b>)->&mut T{ - let index=field.index; +impl<'a, 'b, T> IndexMut<&'a Field<'b>> for FieldMap { + fn index_mut(&mut self, field: &'a Field<'b>) -> &mut T { + let index = field.index; &mut self.fields[index.variant][index.pos] } -} \ No newline at end of file +} diff --git a/as_derive_utils/src/datastructure/type_param_map.rs b/as_derive_utils/src/datastructure/type_param_map.rs index 3eda1b9b..1ce1f7c3 100644 --- a/as_derive_utils/src/datastructure/type_param_map.rs +++ b/as_derive_utils/src/datastructure/type_param_map.rs @@ -2,7 +2,7 @@ use super::*; use std::{ collections::HashMap, - ops::{Index,IndexMut}, + ops::{Index, IndexMut}, rc::Rc, }; @@ -10,59 +10,57 @@ use std::{ This is a map from type parameters to some value. If you put this in a type,and use Default to initialize it, -you must remember to replace the `TypeParamMap` using either +you must remember to replace the `TypeParamMap` using either `TypeParamMap::defaulted` or `TypeParamMap::with` */ -#[derive(Default,Clone, Debug, PartialEq)] -pub struct TypeParamMap<'a,T> { - idents:Rc>, - ty_params:Vec, +#[derive(Default, Clone, Debug, PartialEq)] +pub struct TypeParamMap<'a, T> { + idents: Rc>, + ty_params: Vec, } - -#[derive(Default,Clone, Debug, PartialEq)] -struct Idents<'a>{ - map:HashMap<&'a Ident,usize>, - list:Vec<&'a Ident>, +#[derive(Default, Clone, Debug, PartialEq)] +struct Idents<'a> { + map: HashMap<&'a Ident, usize>, + list: Vec<&'a Ident>, } - #[allow(dead_code)] -impl<'a,T> TypeParamMap<'a,T>{ - /// Constructs an TypeParamMap which maps each type parameter in the DataStructure +impl<'a, T> TypeParamMap<'a, T> { + /// Constructs an TypeParamMap which maps each type parameter in the DataStructure /// to the default value for `T`. - pub fn defaulted(ds:&'a DataStructure<'a>)->Self - where - T:Default + pub fn defaulted(ds: &'a DataStructure<'a>) -> Self + where + T: Default, { - Self::with(ds,|_,_| T::default() ) + Self::with(ds, |_, _| T::default()) } - - /// Constructs an TypeParamMap which maps each type parameter + + /// Constructs an TypeParamMap which maps each type parameter /// in the DataStructure to a value /// (obtained by mapping each individual type parameter to `T` using a closure). - pub fn with(ds:&'a DataStructure<'a>,mut f:F)->Self + pub fn with(ds: &'a DataStructure<'a>, mut f: F) -> Self where - F:FnMut(usize,&'a Ident)->T + F: FnMut(usize, &'a Ident) -> T, { - let type_param_count=ds.generics.type_params().count(); + let type_param_count = ds.generics.type_params().count(); - let mut idents=Idents{ - map: HashMap::<&'a Ident,usize>::with_capacity(type_param_count), + let mut idents = Idents { + map: HashMap::<&'a Ident, usize>::with_capacity(type_param_count), list: Vec::<&'a Ident>::with_capacity(type_param_count), }; - let mut ty_params=Vec::::with_capacity(type_param_count); + let mut ty_params = Vec::::with_capacity(type_param_count); - for (i,type_param) in ds.generics.type_params().enumerate() { - let ident=&type_param.ident; - idents.map.insert(ident,i); + for (i, type_param) in ds.generics.type_params().enumerate() { + let ident = &type_param.ident; + idents.map.insert(ident, i); idents.list.push(ident); - ty_params.push(f(i,ident)); + ty_params.push(f(i, ident)); } - Self{ - idents:Rc::new(idents), + Self { + idents: Rc::new(idents), ty_params, } } @@ -72,142 +70,147 @@ impl<'a,T> TypeParamMap<'a,T>{ /// This operation is cheap,it only clones a reference counted pointer, /// and constructs a Vec of empty tuples(which is just a fancy counter). /// - pub fn clone_unit(&self)->TypeParamMap<'a,()>{ - TypeParamMap{ - ty_params: vec![ () ; self.ty_params.len() ], + pub fn clone_unit(&self) -> TypeParamMap<'a, ()> { + TypeParamMap { + ty_params: vec![(); self.ty_params.len()], idents: self.idents.clone(), } } - /// Maps each value in the map to another one,using a closure. - pub fn map(self,mut f:F)->TypeParamMap<'a,U> + pub fn map(self, mut f: F) -> TypeParamMap<'a, U> where - F:FnMut(usize,&'a Ident,T)->U + F: FnMut(usize, &'a Ident, T) -> U, { - TypeParamMap{ - ty_params:self.ty_params.into_iter() + TypeParamMap { + ty_params: self + .ty_params + .into_iter() .enumerate() .zip(&self.idents.list) - .map(|((i,elem),ident)| f(i,*ident,elem) ) + .map(|((i, elem), ident)| f(i, *ident, elem)) .collect(), - idents:self.idents, + idents: self.idents, } } - pub fn len(&self)->usize{ + pub fn len(&self) -> usize { self.ty_params.len() } - pub fn is_empty(&self)->bool{ + pub fn is_empty(&self) -> bool { self.ty_params.is_empty() } - pub fn get_index(&self,ident:&Ident)->Result{ + pub fn get_index(&self, ident: &Ident) -> Result { match self.idents.map.get(ident) { - Some(x)=>Ok(*x), - None=>Err(spanned_err!(ident,"identifier for an invalid type parameter")), + Some(x) => Ok(*x), + None => Err(spanned_err!( + ident, + "identifier for an invalid type parameter" + )), } } - pub fn get(&self,index:I)->Result<&T,syn::Error> + pub fn get(&self, index: I) -> Result<&T, syn::Error> where - Self:Getter, + Self: Getter, { self.get_inner(index) } - pub fn get_mut(&mut self,index:I)->Result<&mut T,syn::Error> + pub fn get_mut(&mut self, index: I) -> Result<&mut T, syn::Error> where - Self:Getter, + Self: Getter, { self.get_mut_inner(index) } #[allow(dead_code)] - pub fn iter(&self)->impl Iterator+'_ { + pub fn iter(&self) -> impl Iterator + '_ { self.idents.list.iter().cloned().zip(self.ty_params.iter()) } - pub fn iter_mut(&mut self)->impl Iterator+'_ { - self.idents.list.iter().cloned().zip(self.ty_params.iter_mut()) + pub fn iter_mut(&mut self) -> impl Iterator + '_ { + self.idents + .list + .iter() + .cloned() + .zip(self.ty_params.iter_mut()) } } +impl<'a, T> Index for TypeParamMap<'a, T> { + type Output = T; -impl<'a,T> Index for TypeParamMap<'a,T>{ - type Output=T; - - fn index(&self,index:usize)->&T{ + fn index(&self, index: usize) -> &T { &self.ty_params[index] } } -impl<'a,T> IndexMut for TypeParamMap<'a,T>{ - fn index_mut(&mut self,index:usize)->&mut T{ +impl<'a, T> IndexMut for TypeParamMap<'a, T> { + fn index_mut(&mut self, index: usize) -> &mut T { &mut self.ty_params[index] } } +impl<'a, T> Index<&Ident> for TypeParamMap<'a, T> { + type Output = T; -impl<'a,T> Index<&Ident> for TypeParamMap<'a,T>{ - type Output=T; - - fn index(&self,ident:&Ident)->&T{ - let index=self.idents.map[ident]; + fn index(&self, ident: &Ident) -> &T { + let index = self.idents.map[ident]; &self.ty_params[index] } } - -impl<'a,T> IndexMut<&Ident> for TypeParamMap<'a,T>{ - fn index_mut(&mut self,ident:&Ident)->&mut T{ - let index=self.idents.map[ident]; +impl<'a, T> IndexMut<&Ident> for TypeParamMap<'a, T> { + fn index_mut(&mut self, ident: &Ident) -> &mut T { + let index = self.idents.map[ident]; &mut self.ty_params[index] } } -pub trait Getter{ +pub trait Getter { type Elem; - fn get_inner(&self,index:Index)->Result<&Self::Elem,syn::Error>; - fn get_mut_inner(&mut self,index:Index)->Result<&mut Self::Elem,syn::Error>; + fn get_inner(&self, index: Index) -> Result<&Self::Elem, syn::Error>; + fn get_mut_inner(&mut self, index: Index) -> Result<&mut Self::Elem, syn::Error>; } -impl<'a,T> Getter for TypeParamMap<'a,T>{ - type Elem=T; +impl<'a, T> Getter for TypeParamMap<'a, T> { + type Elem = T; - fn get_inner(&self,index:usize)->Result<&Self::Elem,syn::Error>{ + fn get_inner(&self, index: usize) -> Result<&Self::Elem, syn::Error> { self.ty_params .get(index) - .ok_or_else(|| err_from_index(index,self.len()) ) + .ok_or_else(|| err_from_index(index, self.len())) } - fn get_mut_inner(&mut self,index:usize)->Result<&mut Self::Elem,syn::Error>{ - let len=self.len(); + fn get_mut_inner(&mut self, index: usize) -> Result<&mut Self::Elem, syn::Error> { + let len = self.len(); self.ty_params .get_mut(index) - .ok_or_else(|| err_from_index(index,len) ) + .ok_or_else(|| err_from_index(index, len)) } } -impl<'a,T> Getter<&Ident> for TypeParamMap<'a,T>{ - type Elem=T; +impl<'a, T> Getter<&Ident> for TypeParamMap<'a, T> { + type Elem = T; - fn get_inner(&self,ident:&Ident)->Result<&Self::Elem,syn::Error>{ - let index=self.get_index(ident)?; + fn get_inner(&self, ident: &Ident) -> Result<&Self::Elem, syn::Error> { + let index = self.get_index(ident)?; Ok(&self.ty_params[index]) } - fn get_mut_inner(&mut self,ident:&Ident)->Result<&mut Self::Elem,syn::Error>{ - let index=self.get_index(ident)?; + fn get_mut_inner(&mut self, ident: &Ident) -> Result<&mut Self::Elem, syn::Error> { + let index = self.get_index(ident)?; Ok(&mut self.ty_params[index]) } } -fn err_from_index(index:usize,len:usize)->syn::Error{ +fn err_from_index(index: usize, len: usize) -> syn::Error { syn_err!( proc_macro2::Span::call_site(), "index for type parameters is out of bounds, index={} len={}", index, len, ) -} \ No newline at end of file +} diff --git a/as_derive_utils/src/gen_params_in.rs b/as_derive_utils/src/gen_params_in.rs index 60679545..efeb2abf 100644 --- a/as_derive_utils/src/gen_params_in.rs +++ b/as_derive_utils/src/gen_params_in.rs @@ -3,13 +3,13 @@ Contains the `GenParamsIn` type,for printing generic parameters. */ use syn::{ - token::{Comma,Colon,Const,Star}, - Generics,GenericParam, + token::{Colon, Comma, Const, Star}, + GenericParam, Generics, }; use core_extensions::matches; use proc_macro2::TokenStream; -use quote::{quote,ToTokens}; +use quote::{quote, ToTokens}; use crate::utils::NoTokens; @@ -18,21 +18,21 @@ use crate::utils::NoTokens; /// /// One can also add stuff to be printed after lifetime/type parameters. #[derive(Debug, Copy, Clone)] -pub struct GenParamsIn<'a,AL=NoTokens> { +pub struct GenParamsIn<'a, AL = NoTokens> { pub generics: &'a Generics, /// Where the generic parameters are being printed. pub in_what: InWhat, /// Whether type parameters are all `?Sized` - pub unsized_types:bool, + pub unsized_types: bool, /// Whether type bounds will be printed in type parameter declarations. - pub with_bounds:bool, - skip_lifetimes:bool, + pub with_bounds: bool, + skip_lifetimes: bool, /// What will be printed after lifetime parameters - after_lifetimes:Option, + after_lifetimes: Option, /// What will be printed after type parameters - after_types:Option, - skip_consts:bool, - skip_unbounded:bool, + after_types: Option, + skip_consts: bool, + skip_unbounded: bool, } /// Where the generic parameters are being printed. @@ -45,131 +45,131 @@ pub enum InWhat { /// For when using a generic as an argument for a trait/struct/enum/union. ItemUse, /** -For defining the fields of a Dummy struct that is never instantiated, -only using its associated items. - */ + For defining the fields of a Dummy struct that is never instantiated, + only using its associated items. + */ DummyStruct, } -impl<'a> GenParamsIn<'a>{ +impl<'a> GenParamsIn<'a> { #[allow(dead_code)] - pub fn new(generics: &'a Generics,in_what: InWhat)->Self{ - Self{ + pub fn new(generics: &'a Generics, in_what: InWhat) -> Self { + Self { generics, in_what, - unsized_types:false, - with_bounds:true, - skip_lifetimes:false, - after_lifetimes:None, - after_types:None, - skip_consts:false, - skip_unbounded:false, + unsized_types: false, + with_bounds: true, + skip_lifetimes: false, + after_lifetimes: None, + after_types: None, + skip_consts: false, + skip_unbounded: false, } } - } -impl<'a,AL> GenParamsIn<'a,AL>{ +impl<'a, AL> GenParamsIn<'a, AL> { /// Constructs a GenParamsIn that prints `after lifetimes` after lifetime parameters. - pub fn with_after_lifetimes(generics: &'a Generics,in_what: InWhat,after_lifetimes:AL)->Self{ - Self{ + pub fn with_after_lifetimes( + generics: &'a Generics, + in_what: InWhat, + after_lifetimes: AL, + ) -> Self { + Self { generics, in_what, - unsized_types:false, - with_bounds:true, - skip_lifetimes:false, - after_lifetimes:Some(after_lifetimes), - after_types:None, - skip_consts:false, - skip_unbounded:false, + unsized_types: false, + with_bounds: true, + skip_lifetimes: false, + after_lifetimes: Some(after_lifetimes), + after_types: None, + skip_consts: false, + skip_unbounded: false, } } /// Constructs a GenParamsIn that prints `after types` after type parameters. - pub fn with_after_types(generics: &'a Generics,in_what: InWhat,after_types:AL)->Self{ - Self{ + pub fn with_after_types(generics: &'a Generics, in_what: InWhat, after_types: AL) -> Self { + Self { generics, in_what, - unsized_types:false, - with_bounds:true, - skip_lifetimes:false, - after_lifetimes:None, - after_types:Some(after_types), - skip_consts:false, - skip_unbounded:false, + unsized_types: false, + with_bounds: true, + skip_lifetimes: false, + after_lifetimes: None, + after_types: Some(after_types), + skip_consts: false, + skip_unbounded: false, } } /// Removes the bounds on type parameters on type parameter declarations. - pub fn set_no_bounds(&mut self){ - self.with_bounds=false; + pub fn set_no_bounds(&mut self) { + self.with_bounds = false; } /// Makes all type parameters `?Sized`. #[allow(dead_code)] - pub fn set_unsized_types(&mut self){ - self.unsized_types=true; + pub fn set_unsized_types(&mut self) { + self.unsized_types = true; } - pub fn skip_lifetimes(&mut self){ - self.skip_lifetimes=true; + pub fn skip_lifetimes(&mut self) { + self.skip_lifetimes = true; } - pub fn skip_consts(&mut self){ - self.skip_consts=true; + pub fn skip_consts(&mut self) { + self.skip_consts = true; } - pub fn skip_unbounded(&mut self){ - self.skip_unbounded=true; + pub fn skip_unbounded(&mut self) { + self.skip_unbounded = true; self.skip_consts(); self.skip_lifetimes(); } - pub fn skips_unbounded(&self)->bool{ + pub fn skips_unbounded(&self) -> bool { self.skip_unbounded } /// Queries whether bounds are printed. - pub fn outputs_bounds(&self)->bool{ - self.with_bounds && - matches!(self.in_what, InWhat::ImplHeader|InWhat::ItemDecl) + pub fn outputs_bounds(&self) -> bool { + self.with_bounds && matches!(self.in_what, InWhat::ImplHeader | InWhat::ItemDecl) } /// Queries whether all types have a `?Sized` bound. - pub fn are_types_unsized(&self)->bool{ - self.unsized_types&& - matches!(self.in_what, InWhat::ItemDecl|InWhat::ImplHeader) + pub fn are_types_unsized(&self) -> bool { + self.unsized_types && matches!(self.in_what, InWhat::ItemDecl | InWhat::ImplHeader) } } - -impl<'a,AL> ToTokens for GenParamsIn<'a,AL> +impl<'a, AL> ToTokens for GenParamsIn<'a, AL> where - AL:ToTokens, + AL: ToTokens, { fn to_tokens(&self, ts: &mut TokenStream) { let with_bounds = self.outputs_bounds(); let with_default = self.in_what == InWhat::ItemDecl; - - let in_dummy_struct= self.in_what == InWhat::DummyStruct; - let unsized_types=self.are_types_unsized(); + let in_dummy_struct = self.in_what == InWhat::DummyStruct; - let mut iter=self.generics.params.iter().peekable(); + let unsized_types = self.are_types_unsized(); - let comma=Comma::default(); - let brace=syn::token::Brace::default(); + let mut iter = self.generics.params.iter().peekable(); + + let comma = Comma::default(); + let brace = syn::token::Brace::default(); if self.skip_lifetimes { - while let Some(GenericParam::Lifetime{..})=iter.peek() { + while let Some(GenericParam::Lifetime { .. }) = iter.peek() { iter.next(); } - }else{ - while let Some(GenericParam::Lifetime(gen))=iter.peek() { + } else { + while let Some(GenericParam::Lifetime(gen)) = iter.peek() { iter.next(); - if in_dummy_struct{ + if in_dummy_struct { syn::token::And::default().to_tokens(ts); gen.lifetime.to_tokens(ts); - syn::token::Paren::default().surround(ts,|_|()); - }else{ + syn::token::Paren::default().surround(ts, |_| ()); + } else { gen.lifetime.to_tokens(ts); if with_bounds { gen.colon_token.to_tokens(ts); @@ -183,19 +183,19 @@ where self.after_lifetimes.to_tokens(ts); - while let Some(GenericParam::Type(gen))=iter.peek() { + while let Some(GenericParam::Type(gen)) = iter.peek() { iter.next(); if gen.bounds.is_empty() && self.skip_unbounded { continue; } - + if in_dummy_struct { Star::default().to_tokens(ts); Const::default().to_tokens(ts); } gen.ident.to_tokens(ts); - - if (with_bounds&&gen.colon_token.is_some())||unsized_types { + + if (with_bounds && gen.colon_token.is_some()) || unsized_types { Colon::default().to_tokens(ts); if unsized_types { quote!(?Sized+).to_tokens(ts); @@ -209,31 +209,31 @@ where gen.eq_token.to_tokens(ts); gen.default.to_tokens(ts); } - + comma.to_tokens(ts); } self.after_types.to_tokens(ts); - if !in_dummy_struct && !self.skip_consts{ - while let Some(GenericParam::Const(gen))=iter.peek() { + if !in_dummy_struct && !self.skip_consts { + while let Some(GenericParam::Const(gen)) = iter.peek() { iter.next(); - + if self.in_what != InWhat::ItemUse { gen.const_token.to_tokens(ts); } - if self.in_what == InWhat::ItemUse{ + if self.in_what == InWhat::ItemUse { // Have to surround the const parameter when it's used, // because otherwise it's interpreted as a type parameter. - // Remove this branch once outputting the identifier + // Remove this branch once outputting the identifier // for the const parameter just works. - brace.surround(ts,|ts|{ + brace.surround(ts, |ts| { gen.ident.to_tokens(ts); }); - }else{ + } else { gen.ident.to_tokens(ts); } - if self.in_what!= InWhat::ItemUse { + if self.in_what != InWhat::ItemUse { Colon::default().to_tokens(ts); gen.ty.to_tokens(ts); } @@ -241,13 +241,9 @@ where gen.eq_token.to_tokens(ts); gen.default.to_tokens(ts); } - + comma.to_tokens(ts); } } } } - - - - diff --git a/as_derive_utils/src/lib.rs b/as_derive_utils/src/lib.rs index 5cdb6f36..d31c8ec9 100644 --- a/as_derive_utils/src/lib.rs +++ b/as_derive_utils/src/lib.rs @@ -20,10 +20,8 @@ pub mod datastructure; pub mod utils; #[doc(hidden)] -pub use crate::{ - to_token_fn::ToTokenFnMut, -}; +pub use crate::to_token_fn::ToTokenFnMut; -#[cfg(feature="testing")] +#[cfg(feature = "testing")] #[doc(hidden)] -pub mod test_framework; \ No newline at end of file +pub mod test_framework; diff --git a/as_derive_utils/src/test_framework.rs b/as_derive_utils/src/test_framework.rs index 89431c5b..2be34774 100644 --- a/as_derive_utils/src/test_framework.rs +++ b/as_derive_utils/src/test_framework.rs @@ -1,5 +1,5 @@ use std::{ - fmt::{self,Display}, + fmt::{self, Display}, ops::Range, path::Path, rc::Rc, @@ -16,109 +16,104 @@ mod text_replacement; mod vec_from_map; use self::regex_wrapper::RegexWrapper; -use self::vec_from_map::deserialize_vec_pairs; use self::text_replacement::replace_text; - +use self::vec_from_map::deserialize_vec_pairs; //////////////////////////////////////////////////////////////////////////////// - -#[derive(Debug,Clone,Deserialize)] -pub struct Tests{ - cases:Vec, +#[derive(Debug, Clone, Deserialize)] +pub struct Tests { + cases: Vec, } -#[derive(Debug,Clone,Deserialize)] -pub struct TestCase{ - name:String, - code:String, - subcase:Vec>, +#[derive(Debug, Clone, Deserialize)] +pub struct TestCase { + name: String, + code: String, + subcase: Vec>, } -#[derive(Debug,Clone,Deserialize)] -pub struct Subcase{ +#[derive(Debug, Clone, Deserialize)] +pub struct Subcase { #[serde(default)] - #[serde(deserialize_with="deserialize_vec_pairs")] - replacements:Vec<(String,String)>, - + #[serde(deserialize_with = "deserialize_vec_pairs")] + replacements: Vec<(String, String)>, + /// Tries to match all these searches on the string. #[serde(default)] - find_all:Vec, - + find_all: Vec, + /// Tries to find whether there is a match for any of these searches on the string. #[serde(default)] - find_any:Vec, + find_any: Vec, - error_count:usize, + error_count: usize, } -impl Tests{ - pub fn load(text_case_name:&str)->Tests{ - let path=Path::new("./test_data/").join(format!("{}.ron",text_case_name)); - let file=std::fs::read_to_string(path).unwrap(); +impl Tests { + pub fn load(text_case_name: &str) -> Tests { + let path = Path::new("./test_data/").join(format!("{}.ron", text_case_name)); + let file = std::fs::read_to_string(path).unwrap(); ron::de::from_str(&file).unwrap() } - pub fn run_test(&self,mut f:F) + pub fn run_test(&self, mut f: F) where - F:FnMut(&str)->Result + F: FnMut(&str) -> Result, { self.run_test_inner(&mut f); } - fn run_test_inner(&self,f:&mut dyn FnMut(&str)->Result ){ - let mut had_err=false; + fn run_test_inner(&self, f: &mut dyn FnMut(&str) -> Result) { + let mut had_err = false; - let mut input=String::new(); + let mut input = String::new(); for test_case in &self.cases { - let mut test_errors=TestErrors{ - test_name:test_case.name.clone(), - expected:Vec::new(), + let mut test_errors = TestErrors { + test_name: test_case.name.clone(), + expected: Vec::new(), }; for subcase in &test_case.subcase { replace_text(&test_case.code, &subcase.replacements, &mut input); - - let mut composite_strings=String::new(); - - let result=match f(&input) { - Ok(x)=>Ok(write_display(&mut composite_strings,&x)), - Err(e)=>{ - e.into_iter() - .map(|x|{ - composite_strings.push('\0'); - write_display(&mut composite_strings,&x) - }) - .collect::>>() - .piped(Err) - }, + + let mut composite_strings = String::new(); + + let result = match f(&input) { + Ok(x) => Ok(write_display(&mut composite_strings, &x)), + Err(e) => e + .into_iter() + .map(|x| { + composite_strings.push('\0'); + write_display(&mut composite_strings, &x) + }) + .collect::>>() + .piped(Err), }; - let output=composite_strings; + let output = composite_strings; - let error_count=match &result { + let error_count = match &result { Ok(_) => 0, Err(x) => x.len(), }; - let not_found_all= - subcase.find_all.iter() - .filter(|s| !s.matches(&output) ) - .cloned() - .collect::>(); + let not_found_all = subcase + .find_all + .iter() + .filter(|s| !s.matches(&output)) + .cloned() + .collect::>(); - let not_found_any= - !subcase.find_any.iter().any(|s| s.matches(&output) ); + let not_found_any = !subcase.find_any.iter().any(|s| s.matches(&output)); - let is_success={ - subcase.error_count==error_count&& - not_found_all.is_empty()&& - not_found_any + let is_success = { + subcase.error_count == error_count && not_found_all.is_empty() && not_found_any }; if !is_success { - test_errors.expected.push(TestErr{ - input:input.clone(), + test_errors.expected.push(TestErr { + input: input.clone(), result, output, not_found_all, @@ -129,158 +124,148 @@ impl Tests{ } if !test_errors.expected.is_empty() { - eprintln!("{}",test_errors); - had_err=true; + eprintln!("{}", test_errors); + had_err = true; } } - + if had_err { panic!() } } } - - - -fn write_display(string:&mut String,disp:&D)->std::ops::Range +fn write_display(string: &mut String, disp: &D) -> std::ops::Range where - D:Display + D: Display, { use std::fmt::Write; - let start=string.len(); - let _=write!(string,"{}",disp); + let start = string.len(); + let _ = write!(string, "{}", disp); start..string.len() } - - //////////////////////////////////////////////////////////////////////////////// - -#[derive(Debug,Clone,Deserialize)] -pub enum Matcher{ - #[serde(alias="regex")] +#[derive(Debug, Clone, Deserialize)] +pub enum Matcher { + #[serde(alias = "regex")] Regex(RegexWrapper), - - #[serde(alias="str")] + + #[serde(alias = "str")] Str(String), - #[serde(alias="not")] + #[serde(alias = "not")] Not(Box), } - -impl Matcher{ - fn matches(&self,text:&str)->bool{ +impl Matcher { + fn matches(&self, text: &str) -> bool { match self { - Matcher::Regex(regex)=>{ - regex.is_match(text) - } - Matcher::Str(find)=>{ - text.contains(&*find) - } - Matcher::Not(searcher)=>{ - !searcher.matches(text) - } + Matcher::Regex(regex) => regex.is_match(text), + Matcher::Str(find) => text.contains(&*find), + Matcher::Not(searcher) => !searcher.matches(text), } } } - -impl Display for Matcher{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ +impl Display for Matcher { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Matcher::Regex(regex)=>{ - writeln!(f,"Regex:\n{}",regex.to_string().left_padder(4)) + Matcher::Regex(regex) => { + writeln!(f, "Regex:\n{}", regex.to_string().left_padder(4)) } - Matcher::Str(find)=>{ - writeln!(f,"String:\n{}",find.to_string().left_padder(4)) + Matcher::Str(find) => { + writeln!(f, "String:\n{}", find.to_string().left_padder(4)) } - Matcher::Not(searcher)=>{ - writeln!(f,"Not:\n{}",searcher.to_string().left_padder(4)) + Matcher::Not(searcher) => { + writeln!(f, "Not:\n{}", searcher.to_string().left_padder(4)) } } } } - //////////////////////////////////////////////////////////////////////////////// -#[derive(Debug,Clone)] -pub struct TestErrors{ - test_name:String, - expected:Vec, +#[derive(Debug, Clone)] +pub struct TestErrors { + test_name: String, + expected: Vec, } -#[derive(Debug,Clone)] -pub struct TestErr{ - input:String, - result:Result,Vec>>, - output:String, - not_found_all:Vec, - not_found_any:bool, - subcase:Rc, +#[derive(Debug, Clone)] +pub struct TestErr { + input: String, + result: Result, Vec>>, + output: String, + not_found_all: Vec, + not_found_any: bool, + subcase: Rc, } macro_rules! dashes { - () => ("--------------------"); + () => { + "--------------------" + }; } const DASHES: &str = concat!(dashes!(), dashes!(), dashes!(), dashes!()); -impl Display for TestErrors{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ +impl Display for TestErrors { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(DASHES)?; - writeln!(f,"These cases from test '{}' failed:\n",self.test_name)?; + writeln!(f, "These cases from test '{}' failed:\n", self.test_name)?; for test in &self.expected { - let output=&test.output; + let output = &test.output; - writeln!(f," Test:")?; + writeln!(f, " Test:")?; - writeln!(f," Test Input:\n{}",test.input.left_padder(6))?; + writeln!(f, " Test Input:\n{}", test.input.left_padder(6))?; if !test.not_found_all.is_empty() { - writeln!(f," Expected all of these to match:")?; - + writeln!(f, " Expected all of these to match:")?; + for search_for in &test.not_found_all { - Display::fmt(&search_for.to_string().left_padder(6),f)?; + Display::fmt(&search_for.to_string().left_padder(6), f)?; writeln!(f)?; } } - if test.not_found_any { for search_for in &test.subcase.find_any { - Display::fmt(&search_for.to_string().left_padder(6),f)?; + Display::fmt(&search_for.to_string().left_padder(6), f)?; } } - match &test.result { - Ok(output_r)=>{ + Ok(output_r) => { writeln!( f, " Error Count:0 Expected:{}", test.subcase.error_count, )?; - writeln!(f," Test Output:\n{}",output[output_r.clone()].left_padder(6))?; + writeln!( + f, + " Test Output:\n{}", + output[output_r.clone()].left_padder(6) + )?; } - Err(errors)=>{ + Err(errors) => { writeln!( f, " Error Count:{} Expected:{}", - errors.len(),test.subcase.error_count, + errors.len(), + test.subcase.error_count, )?; for err_r in errors { - writeln!(f," Error:\n{}",output[err_r.clone()].left_padder(8))?; + writeln!(f, " Error:\n{}", output[err_r.clone()].left_padder(8))?; } } } - + writeln!(f)?; } Ok(()) } -} \ No newline at end of file +} diff --git a/as_derive_utils/src/test_framework/regex_wrapper.rs b/as_derive_utils/src/test_framework/regex_wrapper.rs index 6bd07b44..1d1ef143 100644 --- a/as_derive_utils/src/test_framework/regex_wrapper.rs +++ b/as_derive_utils/src/test_framework/regex_wrapper.rs @@ -1,12 +1,12 @@ use std::{ - cmp::{Eq,PartialEq}, - hash::{Hash,Hasher}, - ops::{Deref}, + cmp::{Eq, PartialEq}, + hash::{Hash, Hasher}, + ops::Deref, }; use core_extensions::SelfOps; use regex::Regex; -use serde::de::{Deserialize,Deserializer,Error as deError}; +use serde::de::{Deserialize, Deserializer, Error as deError}; #[derive(Clone, Debug)] pub struct RegexWrapper(pub Regex); @@ -17,7 +17,6 @@ impl From for RegexWrapper { } } - impl Hash for RegexWrapper { #[inline] fn hash(&self, state: &mut H) { @@ -35,7 +34,7 @@ impl PartialEq for RegexWrapper { impl Deref for RegexWrapper { type Target = Regex; - + #[inline] fn deref(&self) -> &Self::Target { &self.0 @@ -53,4 +52,4 @@ impl<'de> Deserialize<'de> for RegexWrapper { .map_err(|e| format!("{}", e)) .map_err(D::Error::custom) } -} \ No newline at end of file +} diff --git a/as_derive_utils/src/test_framework/text_replacement.rs b/as_derive_utils/src/test_framework/text_replacement.rs index d5121058..683b5b18 100644 --- a/as_derive_utils/src/test_framework/text_replacement.rs +++ b/as_derive_utils/src/test_framework/text_replacement.rs @@ -1,37 +1,42 @@ -use aho_corasick::{AhoCorasick,Match}; - +use aho_corasick::{AhoCorasick, Match}; #[allow(dead_code)] -#[derive(Copy,Clone)] -struct MatchMine{ - pati :usize, - start:usize, - end :usize, +#[derive(Copy, Clone)] +struct MatchMine { + pati: usize, + start: usize, + end: usize, } -impl From for MatchMine{ - fn from(this:Match)->Self{ - MatchMine{ - pati :this.pattern() as _, - start:this.start() as _, - end :this.end() as _, +impl From for MatchMine { + fn from(this: Match) -> Self { + MatchMine { + pati: this.pattern() as _, + start: this.start() as _, + end: this.end() as _, } } } - -pub fn replace_text(text: &str, map: &[(String,String)], buffer:&mut String){ - let find_automata=AhoCorasick::new(map.iter().map(|(k,_)| k.as_bytes() )); +pub fn replace_text(text: &str, map: &[(String, String)], buffer: &mut String) { + let find_automata = AhoCorasick::new(map.iter().map(|(k, _)| k.as_bytes())); buffer.clear(); - buffer.reserve(text.len()*130/100); + buffer.reserve(text.len() * 130 / 100); - let mut last_m=MatchMine{ pati:0, start:0, end:0 }; - for m in find_automata.find_iter(text.as_bytes()).map(MatchMine::from) { + let mut last_m = MatchMine { + pati: 0, + start: 0, + end: 0, + }; + for m in find_automata + .find_iter(text.as_bytes()) + .map(MatchMine::from) + { buffer.push_str(&text[last_m.end..m.start]); buffer.push_str(&map[m.pati].1); - - last_m=m; + + last_m = m; } - buffer.push_str(&text[last_m.end .. ]); + buffer.push_str(&text[last_m.end..]); } diff --git a/as_derive_utils/src/test_framework/vec_from_map.rs b/as_derive_utils/src/test_framework/vec_from_map.rs index 23d58882..83d63497 100644 --- a/as_derive_utils/src/test_framework/vec_from_map.rs +++ b/as_derive_utils/src/test_framework/vec_from_map.rs @@ -1,24 +1,21 @@ -use std::{ - fmt, - marker::PhantomData, -}; - -use serde::de::{Deserialize, Deserializer, Visitor, MapAccess}; +use std::{fmt, marker::PhantomData}; +use serde::de::{Deserialize, Deserializer, MapAccess, Visitor}; /// Used to deserialize a list of key-value pairs from a json object. -#[derive(Clone,Debug)] -pub(crate) struct VecFromMap{ - pub(crate) vec:Vec<(K,V)>, +#[derive(Clone, Debug)] +pub(crate) struct VecFromMap { + pub(crate) vec: Vec<(K, V)>, } - struct VecFromMapVisitor { - marker: PhantomData<(K, V)> + marker: PhantomData<(K, V)>, } impl VecFromMapVisitor { - const NEW:Self=Self{marker:PhantomData}; + const NEW: Self = Self { + marker: PhantomData, + }; } impl<'de, K, V> Visitor<'de> for VecFromMapVisitor @@ -36,14 +33,14 @@ where where M: MapAccess<'de>, { - let cap=access.size_hint().unwrap_or(0); - let mut vec = Vec::<(K,V)>::with_capacity(cap); + let cap = access.size_hint().unwrap_or(0); + let mut vec = Vec::<(K, V)>::with_capacity(cap); while let Some(pair) = access.next_entry()? { vec.push(pair); } - Ok(VecFromMap{vec}) + Ok(VecFromMap { vec }) } } @@ -60,12 +57,10 @@ where } } - -pub(crate) fn deserialize_vec_pairs<'de,D,K,V>(deserializer: D) -> Result, D::Error> +pub(crate) fn deserialize_vec_pairs<'de, D, K, V>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, - VecFromMap: Deserialize<'de>, + VecFromMap: Deserialize<'de>, { - VecFromMap::::deserialize(deserializer) - .map(|x|x.vec) + VecFromMap::::deserialize(deserializer).map(|x| x.vec) } diff --git a/as_derive_utils/src/to_token_fn.rs b/as_derive_utils/src/to_token_fn.rs index 6fc34a48..28783579 100644 --- a/as_derive_utils/src/to_token_fn.rs +++ b/as_derive_utils/src/to_token_fn.rs @@ -18,9 +18,9 @@ where } } #[allow(dead_code)] - pub fn boxed<'a>(f: F) -> Box + pub fn boxed<'a>(f: F) -> Box where - F:'a, + F: 'a, { Box::new(Self::new(f)) } diff --git a/as_derive_utils/src/utils.rs b/as_derive_utils/src/utils.rs index 99a5afcd..74b0d6db 100644 --- a/as_derive_utils/src/utils.rs +++ b/as_derive_utils/src/utils.rs @@ -1,247 +1,230 @@ use std::{ fmt::Display, - ops::{Deref,DerefMut}, - mem::{self,ManuallyDrop}, + mem::{self, ManuallyDrop}, + ops::{Deref, DerefMut}, ptr, }; +use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::ToTokens; -use proc_macro2::{ - TokenStream as TokenStream2, - Span, -}; use syn::spanned::Spanned; - //////////////////////////////////////////////////////////////////////////////// -#[derive(Debug,Copy,Clone,PartialEq,Eq,Hash)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub struct NoTokens; impl ToTokens for NoTokens { fn to_tokens(&self, _: &mut TokenStream2) {} } - - //////////////////////////////////////////////////////////////////////////////// - -pub trait SynPathExt{ - fn equals_str(&self,s:&str)->bool; - fn equals_ident(&self,s:&syn::Ident)->bool; - fn into_ident(self)->Result - where Self:Sized; +pub trait SynPathExt { + fn equals_str(&self, s: &str) -> bool; + fn equals_ident(&self, s: &syn::Ident) -> bool; + fn into_ident(self) -> Result + where + Self: Sized; } -impl SynPathExt for syn::Path{ - fn equals_str(&self,s:&str)->bool{ +impl SynPathExt for syn::Path { + fn equals_str(&self, s: &str) -> bool { match self.get_ident() { - Some(ident)=>ident==s, - None=>false, + Some(ident) => ident == s, + None => false, } } - fn equals_ident(&self,s:&syn::Ident)->bool{ - self.get_ident()==Some(s) + fn equals_ident(&self, s: &syn::Ident) -> bool { + self.get_ident() == Some(s) } - fn into_ident(mut self)->Result{ - if self.segments.len()==1 { + fn into_ident(mut self) -> Result { + if self.segments.len() == 1 { Ok(self.segments.pop().expect("TEST BUG").into_value().ident) - }else{ + } else { Err(self) } } } - //////////////////////////////////////////////////////////////////////////////// - -pub trait SynResultExt{ - fn push_err(&mut self,err:syn::Error); - fn combine_err(&mut self,res:Result); - fn combine_into_err(self,into:&mut Result); +pub trait SynResultExt { + fn push_err(&mut self, err: syn::Error); + fn combine_err(&mut self, res: Result); + fn combine_into_err(self, into: &mut Result); } -impl SynResultExt for Result{ - fn push_err(&mut self,err:syn::Error){ +impl SynResultExt for Result { + fn push_err(&mut self, err: syn::Error) { match self { - this@Ok(_)=>*this=Err(err), - Err(e)=>e.combine(err), + this @ Ok(_) => *this = Err(err), + Err(e) => e.combine(err), } } - fn combine_err(&mut self,res:Result) { - if let Err(err)=res { + fn combine_err(&mut self, res: Result) { + if let Err(err) = res { self.push_err(err); } } - fn combine_into_err(self,into:&mut Result){ + fn combine_into_err(self, into: &mut Result) { into.combine_err(self); } } - //////////////////////////////////////////////////////////////////////////////// - /// A result wrapper which panics if it's the error variant is not handled, /// by calling `.into_result()`. -#[derive(Debug,Clone)] -pub struct LinearResult{ - errors:ManuallyDrop>, +#[derive(Debug, Clone)] +pub struct LinearResult { + errors: ManuallyDrop>, } -impl Drop for LinearResult{ - fn drop(&mut self){ - let res=unsafe{ take_manuallydrop(&mut self.errors) }; +impl Drop for LinearResult { + fn drop(&mut self) { + let res = unsafe { take_manuallydrop(&mut self.errors) }; res.expect("Expected LinearResult to be handled"); } } -impl LinearResult{ +impl LinearResult { #[inline] - pub fn new(res:Result)->Self{ - Self{ - errors:ManuallyDrop::new(res), + pub fn new(res: Result) -> Self { + Self { + errors: ManuallyDrop::new(res), } } #[inline] - pub fn ok(value:T)->Self{ + pub fn ok(value: T) -> Self { Self::new(Ok(value)) } } impl Default for LinearResult where - T:Default + T: Default, { - fn default()->Self{ + fn default() -> Self { Self::new(Ok(T::default())) } } -impl From> for LinearResult{ +impl From> for LinearResult { #[inline] - fn from(res:Result)->Self{ + fn from(res: Result) -> Self { Self::new(res) } } -impl Deref for LinearResult{ - type Target=Result; +impl Deref for LinearResult { + type Target = Result; - fn deref(&self)->&Result{ + fn deref(&self) -> &Result { &self.errors } } -impl DerefMut for LinearResult{ - fn deref_mut(&mut self)->&mut Result{ +impl DerefMut for LinearResult { + fn deref_mut(&mut self) -> &mut Result { &mut self.errors } } - -impl Into> for LinearResult{ +impl Into> for LinearResult { #[inline] - fn into(self)->Result{ + fn into(self) -> Result { self.into_result() } } #[allow(dead_code)] -impl LinearResult{ +impl LinearResult { #[inline] - pub fn into_result(self)->Result{ - let mut this=ManuallyDrop::new(self); - unsafe{ take_manuallydrop(&mut this.errors) } + pub fn into_result(self) -> Result { + let mut this = ManuallyDrop::new(self); + unsafe { take_manuallydrop(&mut this.errors) } } #[inline] - pub fn take(&mut self)->Result + pub fn take(&mut self) -> Result where - T:Default + T: Default, { self.replace(Ok(Default::default())) } #[inline] - pub fn replace(&mut self,other:Result)->Result{ - mem::replace(&mut *self.errors,other) + pub fn replace(&mut self, other: Result) -> Result { + mem::replace(&mut *self.errors, other) } } -impl SynResultExt for LinearResult{ +impl SynResultExt for LinearResult { #[inline] - fn push_err(&mut self,err:syn::Error){ + fn push_err(&mut self, err: syn::Error) { self.errors.push_err(err); } #[inline] - fn combine_err(&mut self,res:Result) { + fn combine_err(&mut self, res: Result) { self.errors.combine_err(res); } #[inline] - fn combine_into_err(self,into:&mut Result){ + fn combine_into_err(self, into: &mut Result) { self.into_result().combine_into_err(into); } } - //////////////////////////////////////////////////////////////////////////////// /// Takes the contents out of a `ManuallyDrop`. /// /// # Safety /// -/// After this function is called `slot` will become uninitialized and +/// After this function is called `slot` will become uninitialized and /// must not be read again. pub unsafe fn take_manuallydrop(slot: &mut ManuallyDrop) -> T { ManuallyDrop::into_inner(ptr::read(slot)) } - //////////////////////////////////////////////////////////////////////////////// - -pub fn spanned_err(tokens:&dyn ToTokens, display:&dyn Display)-> syn::Error { - syn::Error::new_spanned(tokens,display) +pub fn spanned_err(tokens: &dyn ToTokens, display: &dyn Display) -> syn::Error { + syn::Error::new_spanned(tokens, display) } #[allow(dead_code)] -pub fn syn_err(span:Span,display:&dyn Display)-> syn::Error { - syn::Error::new(span,display) +pub fn syn_err(span: Span, display: &dyn Display) -> syn::Error { + syn::Error::new(span, display) } - //////////////////////////////////////////////////////////////////////////////// - -pub fn join_spans(iter:I)->Span +pub fn join_spans(iter: I) -> Span where - I:IntoIterator, - T:Spanned, + I: IntoIterator, + T: Spanned, { - let call_site=Span::call_site(); - let mut iter=iter.into_iter(); - let first:Span=match iter.next() { - Some(x)=>x.span(), - None=>return call_site, + let call_site = Span::call_site(); + let mut iter = iter.into_iter(); + let first: Span = match iter.next() { + Some(x) => x.span(), + None => return call_site, }; - iter.fold(first,|l,r| l.join(r.span()).unwrap_or(call_site) ) + iter.fold(first, |l, r| l.join(r.span()).unwrap_or(call_site)) } - //////////////////////////////////////////////////////////////////////////////// #[inline(never)] -pub fn dummy_ident()->syn::Ident{ - syn::Ident::new("DUMMY_IDENT",Span::call_site()) +pub fn dummy_ident() -> syn::Ident { + syn::Ident::new("DUMMY_IDENT", Span::call_site()) } //////////////////////////////////////////////////////////////////////////////// @@ -252,30 +235,31 @@ pub fn type_from_ident(ident: syn::Ident) -> syn::Type { path.into() } -pub fn expr_from_ident(ident:syn::Ident)->syn::Expr{ - let x=syn::Path::from(ident); - let x=syn::ExprPath{ - attrs:Vec::new(), - qself:None, - path:x, +pub fn expr_from_ident(ident: syn::Ident) -> syn::Expr { + let x = syn::Path::from(ident); + let x = syn::ExprPath { + attrs: Vec::new(), + qself: None, + path: x, }; syn::Expr::Path(x) } /// Used to tokenize an integer without a type suffix. -pub fn expr_from_int(int:u64)->syn::Expr{ - let x=proc_macro2::Literal::u64_unsuffixed(int); - let x=syn::LitInt::from(x); - let x=syn::Lit::Int(x); - let x=syn::ExprLit{attrs:Vec::new(),lit:x}; +pub fn expr_from_int(int: u64) -> syn::Expr { + let x = proc_macro2::Literal::u64_unsuffixed(int); + let x = syn::LitInt::from(x); + let x = syn::Lit::Int(x); + let x = syn::ExprLit { + attrs: Vec::new(), + lit: x, + }; syn::Expr::Lit(x) } /// Used to tokenize an integer without a type suffix. /// This one should be cheaper than `expr_from_int`. -pub fn uint_lit(int:u64)->syn::LitInt{ - let x=proc_macro2::Literal::u64_unsuffixed(int); +pub fn uint_lit(int: u64) -> syn::LitInt { + let x = proc_macro2::Literal::u64_unsuffixed(int); syn::LitInt::from(x) } - - diff --git a/examples/0_modules_and_interface_types/impl/src/lib.rs b/examples/0_modules_and_interface_types/impl/src/lib.rs index de754ebb..ba3726dd 100644 --- a/examples/0_modules_and_interface_types/impl/src/lib.rs +++ b/examples/0_modules_and_interface_types/impl/src/lib.rs @@ -1,38 +1,31 @@ /*! This is an `implementation crate`, -It exports the root module(a struct of function pointers) required by the +It exports the root module(a struct of function pointers) required by the `example_0_interface`(the `interface crate`). */ -use std::{ - borrow::Cow, - collections::HashSet, - marker::PhantomData, -}; +use std::{borrow::Cow, collections::HashSet, marker::PhantomData}; use example_0_interface::{ - RemoveWords, CowStrIter, - TextOpsMod_Ref,TextOpsMod, - DeserializerMod, DeserializerMod_Ref, - TOState, TOStateBox,TOCommand,TOReturnValue,TOCommandBox,TOReturnValueArc, + CowStrIter, DeserializerMod, DeserializerMod_Ref, RemoveWords, TOCommand, TOCommandBox, + TOReturnValue, TOReturnValueArc, TOState, TOStateBox, TextOpsMod, TextOpsMod_Ref, }; use abi_stable::{ - external_types::RawValueBox, + erased_types::{ImplType, SerializeImplType, TypeInfo}, export_root_module, - sabi_extern_fn, + external_types::RawValueBox, impl_get_type_info, - erased_types::{ImplType,SerializeImplType,TypeInfo}, - prefix_type::{PrefixTypeTrait,WithMetadata}, - traits::{IntoReprC}, - std_types::{RCow, RStr,RBox,RVec,RArc, RString,RResult,ROk,RErr,RBoxError}, + prefix_type::{PrefixTypeTrait, WithMetadata}, + sabi_extern_fn, + std_types::{RArc, RBox, RBoxError, RCow, RErr, ROk, RResult, RStr, RString, RVec}, + traits::IntoReprC, DynTrait, }; -use core_extensions::{SelfOps,StringExt}; - -use serde::{Serialize,Deserialize}; +use core_extensions::{SelfOps, StringExt}; +use serde::{Deserialize, Serialize}; /////////////////////////////////////////////////////////////////////////////////// @@ -41,13 +34,13 @@ use serde::{Serialize,Deserialize}; /// This code isn't run until the layout of the type it returns is checked. #[export_root_module] // #[unsafe_no_layout_constant] -fn instantiate_root_module()->TextOpsMod_Ref{ +fn instantiate_root_module() -> TextOpsMod_Ref { TextOpsMod { new, - deserializers:{ + deserializers: { // Another way to instantiate a module. - const MOD_:DeserializerMod=DeserializerMod{ - something:PhantomData, + const MOD_: DeserializerMod = DeserializerMod { + something: PhantomData, deserialize_state, deserialize_command, deserialize_command_borrowing, @@ -63,14 +56,13 @@ fn instantiate_root_module()->TextOpsMod_Ref{ remove_words, get_processed_bytes, run_command, - }.leak_into_prefix() + } + .leak_into_prefix() } - /////////////////////////////////////////////////////////////////////////////////// - -#[derive(Debug,Serialize,Deserialize,PartialEq)] +#[derive(Debug, Serialize, Deserialize, PartialEq)] struct TextOperationState { processed_bytes: u64, } @@ -85,47 +77,42 @@ struct TextOperationState { impl ImplType for TextOperationState { type Interface = TOState; - const INFO: &'static TypeInfo=impl_get_type_info! { TextOperationState }; + const INFO: &'static TypeInfo = impl_get_type_info! { TextOperationState }; } /// Defines how the type is serialized in DynTrait<_>. impl<'a> SerializeImplType<'a> for TextOperationState { type Interface = TOState; - + fn serialize_impl(&'a self) -> Result { serialize_json(self) } } - ////////////////////////////////////////////////////////////////////////////////////// - /// An enum used to send commands to this library dynamically. -#[derive(Debug,Serialize,Deserialize,PartialEq)] +#[derive(Debug, Serialize, Deserialize, PartialEq)] pub enum Command<'a> { ReverseLines(RString), - RemoveWords{ - string:RString, - words:RVec, + RemoveWords { + string: RString, + words: RVec, #[serde(skip)] - _marker:PhantomData<&'a mut RString>, + _marker: PhantomData<&'a mut RString>, }, GetProcessedBytes, Batch(RVec>), } +impl<'a> Iterator for Command<'a> { + type Item = &'a mut RString; - -impl<'a> Iterator for Command<'a>{ - type Item=&'a mut RString; - - fn next(&mut self)->Option{ + fn next(&mut self) -> Option { None } } - /// Declares TOState as the `ìnterface type` of `TOCommand`. /// /// Also declares the INFO constant,with information about the type, @@ -136,25 +123,22 @@ impl<'a> Iterator for Command<'a>{ impl ImplType for Command<'static> { type Interface = TOCommand; - const INFO: &'static TypeInfo=impl_get_type_info! { Command }; + const INFO: &'static TypeInfo = impl_get_type_info! { Command }; } /// Defines how the type is serialized in DynTrait<_>. -impl<'borr,'a> SerializeImplType<'a> for Command<'borr> { +impl<'borr, 'a> SerializeImplType<'a> for Command<'borr> { type Interface = TOCommand; fn serialize_impl(&'a self) -> Result { serialize_json(self) } } - - ////////////////////////////////////////////////////////////////////////////////////// - /// The return type of `fn run_command`, /// where the returned variant corresponds to the `Command` that was passed in. -#[derive(Debug,Serialize,Deserialize,PartialEq)] +#[derive(Debug, Serialize, Deserialize, PartialEq)] pub enum ReturnValue { ReverseLines(RString), RemoveWords(RString), @@ -172,7 +156,7 @@ pub enum ReturnValue { impl ImplType for ReturnValue { type Interface = TOReturnValue; - const INFO: &'static TypeInfo=impl_get_type_info! { ReturnValue }; + const INFO: &'static TypeInfo = impl_get_type_info! { ReturnValue }; } /// Defines how the type is serialized in DynTrait<_>. @@ -183,11 +167,8 @@ impl<'a> SerializeImplType<'a> for ReturnValue { } } - - ////////////////////////////////////////////////////////////////////////////////////// - fn deserialize_json<'a, T>(s: RStr<'a>) -> RResult where T: serde::Deserialize<'a>, @@ -203,26 +184,22 @@ where T: serde::Serialize, { match serde_json::to_string::(&value) { - Ok(v)=>unsafe{ Ok(RawValueBox::from_rstring_unchecked(v.into_c())) }, - Err(e)=>Err(RBoxError::new(e)), + Ok(v) => unsafe { Ok(RawValueBox::from_rstring_unchecked(v.into_c())) }, + Err(e) => Err(RBoxError::new(e)), } } - ////////////////////////////////////////////////////////////////////////////////////// /// Defines how a TOStateBox is deserialized from json. #[sabi_extern_fn] -pub fn deserialize_state(s:RStr<'_>) -> RResult{ - deserialize_json::(s) - .map(DynTrait::from_value) +pub fn deserialize_state(s: RStr<'_>) -> RResult { + deserialize_json::(s).map(DynTrait::from_value) } /// Defines how a TOCommandBox is deserialized from json. #[sabi_extern_fn] -pub fn deserialize_command( - s:RStr<'_> -) -> RResult, RBoxError>{ +pub fn deserialize_command(s: RStr<'_>) -> RResult, RBoxError> { deserialize_json::(s) .map(RBox::new) .map(DynTrait::from_ptr) @@ -230,17 +207,15 @@ pub fn deserialize_command( /// Defines how a TOCommandBox is deserialized from json. #[sabi_extern_fn] -pub fn deserialize_command_borrowing( - s:RStr<'_> -) -> RResult, RBoxError>{ +pub fn deserialize_command_borrowing(s: RStr<'_>) -> RResult, RBoxError> { deserialize_json::(s) .map(RBox::new) - .map(|x|DynTrait::from_borrowing_ptr(x,TOCommand)) + .map(|x| DynTrait::from_borrowing_ptr(x, TOCommand)) } /// Defines how a TOReturnValueArc is deserialized from json. #[sabi_extern_fn] -pub fn deserialize_return_value(s:RStr<'_>) -> RResult{ +pub fn deserialize_return_value(s: RStr<'_>) -> RResult { deserialize_json::(s) .map(RArc::new) .map(DynTrait::from_ptr) @@ -248,29 +223,26 @@ pub fn deserialize_return_value(s:RStr<'_>) -> RResult,TOState>`. #[sabi_extern_fn] pub fn new() -> TOStateBox { - let this=TextOperationState{ - processed_bytes:0, - }; + let this = TextOperationState { processed_bytes: 0 }; DynTrait::from_value(this) } - - /// Reverses order of the lines in `text`. #[sabi_extern_fn] -pub fn reverse_lines<'a>(this: &mut TOStateBox, text: RStr<'a>)-> RString { - let this = this.downcast_as_mut_impltype::().unwrap(); +pub fn reverse_lines<'a>(this: &mut TOStateBox, text: RStr<'a>) -> RString { + let this = this + .downcast_as_mut_impltype::() + .unwrap(); - this.processed_bytes+=text.len() as u64; + this.processed_bytes += text.len() as u64; - let mut lines=text.lines().collect::>(); + let mut lines = text.lines().collect::>(); lines.reverse(); - let mut buffer=RString::with_capacity(text.len()); + let mut buffer = RString::with_capacity(text.len()); for line in lines { buffer.push_str(line); buffer.push('\n'); @@ -278,37 +250,41 @@ pub fn reverse_lines<'a>(this: &mut TOStateBox, text: RStr<'a>)-> RString { buffer } - /// Removes the words in `param.words` from `param.string`, /// as well as the whitespace that comes after it. #[sabi_extern_fn] // How is a `&mut ()` not ffi-safe????? #[allow(improper_ctypes_definitions)] -pub fn remove_words(this: &mut TOStateBox, param: RemoveWords<'_,'_>) -> RString{ - let this = this.downcast_as_mut_impltype::().unwrap(); - - this.processed_bytes+=param.string.len() as u64; - - let set=param.words.map(RCow::into).collect::>>(); - let mut buffer=String::with_capacity(10); - - let haystack=&*param.string; - let mut prev_was_deleted=false; - for kv in haystack.split_while(|c|c.is_alphabetic()) { - let s=kv.str; - let cs=Cow::from(s); - let is_a_word=kv.key; - let is_deleted= (!is_a_word&&prev_was_deleted) || (is_a_word && set.contains(&cs)); +pub fn remove_words(this: &mut TOStateBox, param: RemoveWords<'_, '_>) -> RString { + let this = this + .downcast_as_mut_impltype::() + .unwrap(); + + this.processed_bytes += param.string.len() as u64; + + let set = param + .words + .map(RCow::into) + .collect::>>(); + let mut buffer = String::with_capacity(10); + + let haystack = &*param.string; + let mut prev_was_deleted = false; + for kv in haystack.split_while(|c| c.is_alphabetic()) { + let s = kv.str; + let cs = Cow::from(s); + let is_a_word = kv.key; + let is_deleted = (!is_a_word && prev_was_deleted) || (is_a_word && set.contains(&cs)); if !is_deleted { buffer.push_str(s); } - prev_was_deleted=is_deleted; + prev_was_deleted = is_deleted; } buffer.into() } -/// Returns the amount of text (in bytes) +/// Returns the amount of text (in bytes) /// that was processed in functions taking `&mut TOStateBox`. #[sabi_extern_fn] pub fn get_processed_bytes(this: &TOStateBox) -> u64 { @@ -316,67 +292,65 @@ pub fn get_processed_bytes(this: &TOStateBox) -> u64 { this.processed_bytes } - - -fn run_command_inner(this:&mut TOStateBox,command:Command)->ReturnValue{ +fn run_command_inner(this: &mut TOStateBox, command: Command) -> ReturnValue { match command { - Command::ReverseLines(s)=>{ - reverse_lines(this,s.as_rstr()) - .piped(ReturnValue::ReverseLines) + Command::ReverseLines(s) => { + reverse_lines(this, s.as_rstr()).piped(ReturnValue::ReverseLines) } - Command::RemoveWords{string,words,_marker:_}=>{ - let iter=&mut words.iter().map(|s| RCow::Borrowed(s.as_rstr()) ); - - remove_words(this,RemoveWords{ - string:string.as_rstr(), - words:DynTrait::from_borrowing_ptr(iter,CowStrIter), - }) + Command::RemoveWords { + string, + words, + _marker: _, + } => { + let iter = &mut words.iter().map(|s| RCow::Borrowed(s.as_rstr())); + + remove_words( + this, + RemoveWords { + string: string.as_rstr(), + words: DynTrait::from_borrowing_ptr(iter, CowStrIter), + }, + ) .piped(ReturnValue::RemoveWords) } - Command::GetProcessedBytes=>{ - get_processed_bytes(this) - .piped(ReturnValue::GetProcessedBytes) - } - Command::Batch(list)=>{ - list.into_iter() - .map(|cmd| run_command_inner(this,cmd) ) - .collect::>() - .piped(ReturnValue::Batch) + Command::GetProcessedBytes => { + get_processed_bytes(this).piped(ReturnValue::GetProcessedBytes) } + Command::Batch(list) => list + .into_iter() + .map(|cmd| run_command_inner(this, cmd)) + .collect::>() + .piped(ReturnValue::Batch), } } - /// An interpreter for text operation commands // How is a `*mut ()` not ffi-safe????? #[allow(improper_ctypes_definitions)] #[sabi_extern_fn] -pub fn run_command( - this:&mut TOStateBox, - command:TOCommandBox<'static> -)->TOReturnValueArc{ - let command = command.downcast_into_impltype::>().unwrap() +pub fn run_command(this: &mut TOStateBox, command: TOCommandBox<'static>) -> TOReturnValueArc { + let command = command + .downcast_into_impltype::>() + .unwrap() .piped(RBox::into_inner); - - run_command_inner(this,command) + + run_command_inner(this, command) .piped(RArc::new) .piped(DynTrait::from_ptr) } - ///////////////////////////////////////////////////////////////////////////// - #[cfg(test)] -mod tests{ +mod tests { use super::*; use abi_stable::library::RootModule; use serde_json::value::RawValue; - fn setup(){ - let _=TextOpsMod_Ref::load_module_with(|| Ok::<_,()>(instantiate_root_module()) ); + fn setup() { + let _ = TextOpsMod_Ref::load_module_with(|| Ok::<_, ()>(instantiate_root_module())); } #[test] @@ -392,69 +366,63 @@ mod tests{ fn test_remove_words() { let mut state = new(); { - let words = ["burrito", "like","a"]; - let mut iter=words.iter().cloned().map(RCow::from); + let words = ["burrito", "like", "a"]; + let mut iter = words.iter().cloned().map(RCow::from); let param = RemoveWords { string: "Monads are like a burrito wrapper.".into(), - words: DynTrait::from_borrowing_ptr(&mut iter,CowStrIter), + words: DynTrait::from_borrowing_ptr(&mut iter, CowStrIter), }; assert_eq!(&*remove_words(&mut state, param), "Monads are wrapper."); } { - let words = ["largest","is"]; - let mut iter=words.iter().cloned().map(RCow::from); + let words = ["largest", "is"]; + let mut iter = words.iter().cloned().map(RCow::from); let param = RemoveWords { string: "The largest planet is jupiter.".into(), - words: DynTrait::from_borrowing_ptr(&mut iter,CowStrIter), + words: DynTrait::from_borrowing_ptr(&mut iter, CowStrIter), }; assert_eq!(&*remove_words(&mut state, param), "The planet jupiter."); } } #[test] - fn deserializing(){ + fn deserializing() { setup(); - - let json=r#" + + let json = r#" { "processed_bytes":101 } "#; - let rvref=serde_json::from_str::<&RawValue>(json).unwrap(); - let value0=TOStateBox::deserialize_from_proxy(rvref.into()).unwrap(); + let rvref = serde_json::from_str::<&RawValue>(json).unwrap(); + let value0 = TOStateBox::deserialize_from_proxy(rvref.into()).unwrap(); - let value1=serde_json::from_str::(&json).unwrap(); - - assert_eq!(value0,value1); + let value1 = serde_json::from_str::(&json).unwrap(); + assert_eq!(value0, value1); } - #[test] - fn serializing(){ + fn serializing() { setup(); - let this=TextOperationState { + let this = TextOperationState { processed_bytes: 1337, - }.piped(DynTrait::from_value); + } + .piped(DynTrait::from_value); - let serialized_0= this.serialize_into_proxy() + let serialized_0 = this + .serialize_into_proxy() .unwrap() .get() .split_whitespace() .collect::(); - let expected_0=r#"{"processed_bytes":1337}"#; + let expected_0 = r#"{"processed_bytes":1337}"#; - assert_eq!(serialized_0,expected_0); + assert_eq!(serialized_0, expected_0); - assert_eq!( - serde_json::to_string(&this).unwrap(), - expected_0, - ); + assert_eq!(serde_json::to_string(&this).unwrap(), expected_0,); } - } - - diff --git a/examples/0_modules_and_interface_types/interface/src/lib.rs b/examples/0_modules_and_interface_types/interface/src/lib.rs index 966dbcad..264e83c5 100644 --- a/examples/0_modules_and_interface_types/interface/src/lib.rs +++ b/examples/0_modules_and_interface_types/interface/src/lib.rs @@ -10,274 +10,253 @@ and all the modules inside of the library. */ - use abi_stable::{ - StableAbi, - external_types::{RawValueRef,RawValueBox}, - package_version_strings, declare_root_module_statics, + erased_types::{DeserializeDyn, IteratorItem, SerializeProxyType}, + external_types::{RawValueBox, RawValueRef}, library::RootModule, - erased_types::{DeserializeDyn,SerializeProxyType,IteratorItem}, - DynTrait, - sabi_types::{VersionStrings, RMut}, - std_types::{RBox, RStr, RString,RArc,RCow,RBoxError,RResult}, + package_version_strings, + sabi_types::{RMut, VersionStrings}, + std_types::{RArc, RBox, RBoxError, RCow, RResult, RStr, RString}, + DynTrait, StableAbi, }; - - - /// The root module of the `text_operations` dynamic library. /// With all the functions/modules related to processing text. /// /// To load this module, /// call ::load_from_directory(some_directory_path) #[repr(C)] -#[derive(StableAbi)] -#[sabi(kind(Prefix(prefix_ref="TextOpsMod_Ref")))] +#[derive(StableAbi)] +#[sabi(kind(Prefix(prefix_ref = "TextOpsMod_Ref")))] #[sabi(missing_field(panic))] pub struct TextOpsMod { /// Constructs TOStateBox,state that is passed to other functions in this module. pub new: extern "C" fn() -> TOStateBox, -/** -The `deserializers` submodule. + /** + The `deserializers` submodule. -The `#[sabi(last_prefix_field)]` attribute here means that this is the last field in this struct -that was defined in the first compatible version of the library -(0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), -requiring new fields to always be added below preexisting ones. + The `#[sabi(last_prefix_field)]` attribute here means that this is the last field in this struct + that was defined in the first compatible version of the library + (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), + requiring new fields to always be added below preexisting ones. -The `#[sabi(last_prefix_field)]` attribute would stay on this field until the library -bumps its "major" version, -at which point it would be moved to the last field at the time. + The `#[sabi(last_prefix_field)]` attribute would stay on this field until the library + bumps its "major" version, + at which point it would be moved to the last field at the time. -*/ - #[sabi(last_prefix_field)] + */ + #[sabi(last_prefix_field)] pub deserializers: DeserializerMod_Ref, /// Reverses the order of the lines. - pub reverse_lines: extern "C" fn(&mut TOStateBox,RStr<'_>) -> RString, - + pub reverse_lines: extern "C" fn(&mut TOStateBox, RStr<'_>) -> RString, + /// Removes the `param.words` words from the `param.string` string. - pub remove_words: - extern "C" fn(&mut TOStateBox,param:RemoveWords<'_,'_>) -> RString, - + pub remove_words: extern "C" fn(&mut TOStateBox, param: RemoveWords<'_, '_>) -> RString, + /// Gets the amount (in bytes) of text that was processed pub get_processed_bytes: extern "C" fn(&TOStateBox) -> u64, - - pub run_command: - extern "C" fn(&mut TOStateBox,command:TOCommandBox<'static>)->TOReturnValueArc, -} + pub run_command: + extern "C" fn(&mut TOStateBox, command: TOCommandBox<'static>) -> TOReturnValueArc, +} impl RootModule for TextOpsMod_Ref { - declare_root_module_statics!{TextOpsMod_Ref} + declare_root_module_statics! {TextOpsMod_Ref} const BASE_NAME: &'static str = "text_operations"; const NAME: &'static str = "text_operations"; const VERSION_STRINGS: VersionStrings = package_version_strings!(); } - /// A module for all deserialization functions. #[repr(C)] -#[derive(StableAbi)] -#[sabi(kind(Prefix(prefix_ref="DeserializerMod_Ref")))] +#[derive(StableAbi)] +#[sabi(kind(Prefix(prefix_ref = "DeserializerMod_Ref")))] #[sabi(missing_field(panic))] pub struct DeserializerMod { pub something: std::marker::PhantomData<()>, /** -The implementation for how TOStateBox is going to be deserialized. + The implementation for how TOStateBox is going to be deserialized. -The `#[sabi(last_prefix_field)]` attribute here means that this is the last field in this struct -that was defined in the first compatible version of the library -(0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), -requiring new fields to always be added below preexisting ones. + The `#[sabi(last_prefix_field)]` attribute here means that this is the last field in this struct + that was defined in the first compatible version of the library + (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), + requiring new fields to always be added below preexisting ones. -The `#[sabi(last_prefix_field)]` attribute would stay on this field until the library -bumps its "major" version, -at which point it would be moved to the last field at the time. + The `#[sabi(last_prefix_field)]` attribute would stay on this field until the library + bumps its "major" version, + at which point it would be moved to the last field at the time. -*/ + */ #[sabi(last_prefix_field)] pub deserialize_state: extern "C" fn(RStr<'_>) -> RResult, /// The implementation for how TOCommandBox is going to be deserialized. - pub deserialize_command: + pub deserialize_command: for<'a> extern "C" fn(RStr<'a>) -> RResult, RBoxError>, - + /// The implementation for how TOCommandBox is going to be deserialized, /// borrowing from the input string. - pub deserialize_command_borrowing: + pub deserialize_command_borrowing: for<'borr> extern "C" fn(RStr<'borr>) -> RResult, RBoxError>, - + /// The implementation for how TOReturnValueArc is going to be deserialized. pub deserialize_return_value: extern "C" fn(RStr<'_>) -> RResult, } - - - - /////////////////////////////////////////////// /** -An `InterfaceType` describing which traits are required +An `InterfaceType` describing which traits are required when constructing `TOStateBox`(Serialize,Deserialize,and PartialEq) and are then usable afterwards. */ #[repr(C)] #[derive(StableAbi)] -#[sabi(impl_InterfaceType(Serialize,Deserialize,Debug,PartialEq))] +#[sabi(impl_InterfaceType(Serialize, Deserialize, Debug, PartialEq))] pub struct TOState; /// The state passed to most functions in the TextOpsMod_Ref module. -pub type TOStateBox = DynTrait<'static,RBox<()>,TOState>; +pub type TOStateBox = DynTrait<'static, RBox<()>, TOState>; - -/// First ::serialize_impl returns +/// First ::serialize_impl returns /// a RawValueBox containing the serialized data, /// then the returned RawValueBox is serialized. -impl<'a> SerializeProxyType<'a> for TOState{ - type Proxy=RawValueBox; +impl<'a> SerializeProxyType<'a> for TOState { + type Proxy = RawValueBox; } - /** Describes how a `TOStateBox` is deserialized. */ -impl<'borr> DeserializeDyn<'borr,TOStateBox> for TOState { +impl<'borr> DeserializeDyn<'borr, TOStateBox> for TOState { /// The intermediate type that is deserialized, /// and then converted to `TOStateBox` with `DeserializeDyn::deserialize_dyn`. type Proxy = RawValueRef<'borr>; fn deserialize_dyn(s: RawValueRef<'borr>) -> Result { - TextOpsMod_Ref::get_module().unwrap() + TextOpsMod_Ref::get_module() + .unwrap() .deserializers() .deserialize_state()(s.get_rstr()) - .into_result() + .into_result() } } - /////////////////////////////////////////////////////////////////////////////// /** -An `InterfaceType` describing which traits are required +An `InterfaceType` describing which traits are required when constructing `TOCommandBox`(Send,Sync,Debug,Serialize,etc) and are then usable afterwards. */ #[repr(C)] #[derive(StableAbi)] -#[sabi(impl_InterfaceType(Send,Sync,Debug,Serialize,Deserialize,PartialEq,Iterator))] +#[sabi(impl_InterfaceType(Send, Sync, Debug, Serialize, Deserialize, PartialEq, Iterator))] pub struct TOCommand; /// A de/serializable opaque command enum,used in the TextOpsMod_Ref::run_command function. -pub type TOCommandBox<'borr> = DynTrait<'borr,RBox<()>,TOCommand>; +pub type TOCommandBox<'borr> = DynTrait<'borr, RBox<()>, TOCommand>; -/// This specifies the type Item type that `DynTrait<_,TOCommand>` +/// This specifies the type Item type that `DynTrait<_,TOCommand>` /// yields when iterating. -impl<'a> IteratorItem<'a> for TOCommand{ - type Item=&'a mut RString; +impl<'a> IteratorItem<'a> for TOCommand { + type Item = &'a mut RString; } - -/// First ::serialize_impl returns +/// First ::serialize_impl returns /// a RawValueBox containing the serialized data, /// then the returned RawValueBox is serialized. -impl<'a> SerializeProxyType<'a> for TOCommand{ - type Proxy=RawValueBox; +impl<'a> SerializeProxyType<'a> for TOCommand { + type Proxy = RawValueBox; } /// Describes how TOCommandBox is deserialized -impl<'borr> DeserializeDyn<'borr,TOCommandBox<'static>> for TOCommand { +impl<'borr> DeserializeDyn<'borr, TOCommandBox<'static>> for TOCommand { /// The intermediate type that is deserialized, /// and then converted to `TOCommandBox` with `DeserializeDyn::deserialize_dyn - type Proxy = RawValueRef<'borr> ; + type Proxy = RawValueRef<'borr>; fn deserialize_dyn(s: RawValueRef<'borr>) -> Result, RBoxError> { - TextOpsMod_Ref::get_module().unwrap() + TextOpsMod_Ref::get_module() + .unwrap() .deserializers() .deserialize_command()(s.get_rstr()) - .into_result() + .into_result() } } - /////////////////////////////////////////////////////////////////////////////// - /** -An `InterfaceType` describing which traits are required +An `InterfaceType` describing which traits are required when constructing `TOReturnValueArc`(Send,Sync,Debug,Serialize,Deserialize,and PartialEq) and are then usable afterwards. */ #[repr(C)] #[derive(StableAbi)] -#[sabi(impl_InterfaceType(Sync,Send,Debug,Serialize,Deserialize,PartialEq))] +#[sabi(impl_InterfaceType(Sync, Send, Debug, Serialize, Deserialize, PartialEq))] pub struct TOReturnValue; /// A de/serializable opaque command enum,returned by the TextOpsMod_Ref::run_command function. -pub type TOReturnValueArc = DynTrait<'static,RArc<()>,TOReturnValue>; - +pub type TOReturnValueArc = DynTrait<'static, RArc<()>, TOReturnValue>; -/// First ::serialize_impl returns +/// First ::serialize_impl returns /// a RawValueBox containing the serialized data, /// then the returned RawValueBox is serialized. -impl<'a> SerializeProxyType<'a> for TOReturnValue{ - type Proxy=RawValueBox; +impl<'a> SerializeProxyType<'a> for TOReturnValue { + type Proxy = RawValueBox; } /// Describes how TOReturnValueArc is deserialized -impl<'borr> DeserializeDyn<'borr,TOReturnValueArc> for TOReturnValue { +impl<'borr> DeserializeDyn<'borr, TOReturnValueArc> for TOReturnValue { /// The intermediate type that is deserialized, /// and then converted to `TOReturnValueArc` with `DeserializeDyn::deserialize_dyn type Proxy = RawValueRef<'borr>; fn deserialize_dyn(s: RawValueRef<'borr>) -> Result { - TextOpsMod_Ref::get_module().unwrap() + TextOpsMod_Ref::get_module() + .unwrap() .deserializers() .deserialize_return_value()(s.get_rstr()) - .into_result() + .into_result() } } - /////////////////////////////////////////////////////////////////////////////// - /** -An `InterfaceType` describing which traits are required +An `InterfaceType` describing which traits are required when constructing `DynTrait<_,CowStrIter>`(Send,Sync,and Iterator) and are then usable afterwards. */ #[repr(C)] #[derive(StableAbi)] -#[sabi(impl_InterfaceType(Sync,Send,Iterator))] +#[sabi(impl_InterfaceType(Sync, Send, Iterator))] pub struct CowStrIter; -/// This specifies the type Item type that `DynTrait<_,CowStrIter>` +/// This specifies the type Item type that `DynTrait<_,CowStrIter>` /// yields when iterating. -impl<'a> IteratorItem<'a> for CowStrIter{ - type Item=RCow<'a,str>; +impl<'a> IteratorItem<'a> for CowStrIter { + type Item = RCow<'a, str>; } - - /// The parameters for the `TextOpsMod_Ref.remove_words` function. #[repr(C)] -#[derive(StableAbi)] -pub struct RemoveWords<'a,'b>{ +#[derive(StableAbi)] +pub struct RemoveWords<'a, 'b> { /// The string we're processing. - pub string:RStr<'a>, + pub string: RStr<'a>, /// The words that will be removed from self.string. /// /// An iterator over `RCow<'a,str>`, /// constructed from a `&'b mut impl Iterator>` /// with `DynTrait::from_borrowing_ptr(iter,CowStrIter)`. - pub words:DynTrait<'a, RMut<'b, ()>,CowStrIter>, + pub words: DynTrait<'a, RMut<'b, ()>, CowStrIter>, } - /////////////////////////////////////////////////////////////////////////////// diff --git a/examples/0_modules_and_interface_types/user/src/main.rs b/examples/0_modules_and_interface_types/user/src/main.rs index bd796092..c6241104 100644 --- a/examples/0_modules_and_interface_types/user/src/main.rs +++ b/examples/0_modules_and_interface_types/user/src/main.rs @@ -1,39 +1,38 @@ use std::{ fs, + io::{self, BufRead, Read, Write}, path::PathBuf, - io::{self,BufRead,Write,Read}, }; - use core_extensions::SelfOps; use structopt::StructOpt; use abi_stable::{ - std_types::{RString,RCow}, - DynTrait, library::{development_utils::compute_library_path, RootModule}, + std_types::{RCow, RString}, + DynTrait, }; -use example_0_interface::{CowStrIter,TextOpsMod_Ref,RemoveWords,TOStateBox}; - +use example_0_interface::{CowStrIter, RemoveWords, TOStateBox, TextOpsMod_Ref}; mod tests; /// Processes stdin,outputting the transformed line to stdout. -fn process_stdin(mut f:F)->io::Result<()> -where F:FnMut(&str)->RString +fn process_stdin(mut f: F) -> io::Result<()> +where + F: FnMut(&str) -> RString, { - let mut line_buffer=String::new(); + let mut line_buffer = String::new(); let stdin = io::stdin(); let mut stdin = stdin.lock(); - + let stdout = io::stdout(); let mut stdout = stdout.lock(); - while stdin.read_line(&mut line_buffer)?!=0 { - let returned=f(&line_buffer); + while stdin.read_line(&mut line_buffer)? != 0 { + let returned = f(&line_buffer); line_buffer.clear(); stdout.write_all(returned.as_bytes())?; writeln!(stdout)?; @@ -42,159 +41,151 @@ where F:FnMut(&str)->RString Ok(()) } - - #[derive(StructOpt)] -#[structopt(author="_")] +#[structopt(author = "_")] enum Command { #[structopt(name = "reverse-line-order")] - #[structopt(author="_")] -/** - -Reverse the order of all lines from stdin into stdout once stdin disconnects. - -Example: - -Running this(on linux,don't know how it would work on windows or mac): -``` -echo -e "A\nB\nC\nD" | cargo run -- reverse-line-order -``` - -Outputs this: -``` -D -C -B -A -``` - -*/ - ReverseLineOrder , - -/** - -Copies the stdin into stdout,removing the words passed as command line arguments. - -Example: - -Running this -``` -echo "This is an example phrase,try replacing this with some other sentence." | \ -cargo run -- remove-words is an try this with -``` -Outputs this: -``` -This example phrase,replacing some other sentence. -``` - -*/ + #[structopt(author = "_")] + /** + + Reverse the order of all lines from stdin into stdout once stdin disconnects. + + Example: + + Running this(on linux,don't know how it would work on windows or mac): + ``` + echo -e "A\nB\nC\nD" | cargo run -- reverse-line-order + ``` + + Outputs this: + ``` + D + C + B + A + ``` + + */ + ReverseLineOrder, + + /** + + Copies the stdin into stdout,removing the words passed as command line arguments. + + Example: + + Running this + ``` + echo "This is an example phrase,try replacing this with some other sentence." | \ + cargo run -- remove-words is an try this with + ``` + Outputs this: + ``` + This example phrase,replacing some other sentence. + ``` + + */ #[structopt(name = "remove-words")] - #[structopt(author="_")] - RemoveWords{ - words:Vec - }, + #[structopt(author = "_")] + RemoveWords { words: Vec }, #[structopt(name = "run-tests")] - #[structopt(author="_")] + #[structopt(author = "_")] /** -Runs some tests that require a dynamic library. -This is how some integration tests are done,may be replaced with a -dedicated test suite eventually. - */ + Runs some tests that require a dynamic library. + This is how some integration tests are done,may be replaced with a + dedicated test suite eventually. + */ RunTests, /** -Runs some json encoded commands,outputting the json encoded return value to stdout. -The command can come from either from stdin or from a file -For some examples of json commands please look in the `data/` directory. + Runs some json encoded commands,outputting the json encoded return value to stdout. + The command can come from either from stdin or from a file + For some examples of json commands please look in the `data/` directory. + + Examples: -Examples: - - `cargo run -- json-command data/0_reverse_lines.json` - - `cargo run -- json-command data/1_remove_words.json` + `cargo run -- json-command data/0_reverse_lines.json` - `cargo run -- json-command data/2_get_processed_bytes.json` + `cargo run -- json-command data/1_remove_words.json` -*/ + `cargo run -- json-command data/2_get_processed_bytes.json` + + */ #[structopt(name = "json-command")] - #[structopt(author="_")] - Json{ + #[structopt(author = "_")] + Json { /// The file to load the json command from. - file:Option + file: Option, }, /// Does nothing,used to check the startup duration. #[structopt(name = "nothing")] - #[structopt(author="_")] + #[structopt(author = "_")] Nothing, } - - -fn main()-> io::Result<()> { +fn main() -> io::Result<()> { let target: &std::path::Path = "../../../target/".as_ref(); - let library_path=compute_library_path::(target).unwrap(); + let library_path = compute_library_path::(target).unwrap(); - let mods=TextOpsMod_Ref::load_from_directory(&library_path) - .unwrap_or_else(|e| panic!("{}", e) ); - - let opts = Command::clap() - .get_matches() - .piped_ref(Command::from_clap); + let mods = + TextOpsMod_Ref::load_from_directory(&library_path).unwrap_or_else(|e| panic!("{}", e)); - let mut state=mods.new()(); + let opts = Command::clap().get_matches().piped_ref(Command::from_clap); + + let mut state = mods.new()(); match opts { - Command::ReverseLineOrder=>{ - let mut buffer=String::new(); + Command::ReverseLineOrder => { + let mut buffer = String::new(); io::stdin().read_to_string(&mut buffer)?; - let reversed= - mods.reverse_lines()(&mut state,buffer.as_str().into()); + let reversed = mods.reverse_lines()(&mut state, buffer.as_str().into()); io::stdout().write_all(reversed.as_bytes())?; } - Command::RemoveWords{words}=>{ - process_stdin(|line|{ - let mut words=words.iter().map(RCow::from); - let params=RemoveWords{ - string:line.into(), - words:DynTrait::from_borrowing_ptr(&mut words,CowStrIter), + Command::RemoveWords { words } => { + process_stdin(|line| { + let mut words = words.iter().map(RCow::from); + let params = RemoveWords { + string: line.into(), + words: DynTrait::from_borrowing_ptr(&mut words, CowStrIter), }; - mods.remove_words()(&mut state,params) + mods.remove_words()(&mut state, params) })?; } - Command::RunTests=>{ + Command::RunTests => { tests::run_dynamic_library_tests(mods); } - Command::Json{file}=>{ - fn run_command(mods:TextOpsMod_Ref,state:&mut TOStateBox,s:&str)->RString{ - let command=serde_json::from_str(s) - .unwrap_or_else(|e| panic!("\n{}\n",e) ); - - let ret=mods.run_command()(state,command); + Command::Json { file } => { + fn run_command(mods: TextOpsMod_Ref, state: &mut TOStateBox, s: &str) -> RString { + let command = serde_json::from_str(s).unwrap_or_else(|e| panic!("\n{}\n", e)); + + let ret = mods.run_command()(state, command); serde_json::to_string(&ret) - .unwrap_or_else(|e| panic!("\n{}\n",e) ) + .unwrap_or_else(|e| panic!("\n{}\n", e)) .into() } - match file.as_ref().map(|f| (f,fs::read_to_string(f)) ) { - Some((_,Ok(file)))=>{ - println!("{}",run_command(mods,&mut state,&*file)); + match file.as_ref().map(|f| (f, fs::read_to_string(f))) { + Some((_, Ok(file))) => { + println!("{}", run_command(mods, &mut state, &*file)); } - Some((path,Err(e)))=>{ - println!("Could not load file at:\n\t{}\nBecause:\n\t{}",path.display(),e); + Some((path, Err(e))) => { + println!( + "Could not load file at:\n\t{}\nBecause:\n\t{}", + path.display(), + e + ); } - None=>{ - process_stdin(|line| run_command(mods,&mut state,line) )?; + None => { + process_stdin(|line| run_command(mods, &mut state, line))?; } } } - Command::Nothing=>{} + Command::Nothing => {} } Ok(()) } - - diff --git a/examples/0_modules_and_interface_types/user/src/tests.rs b/examples/0_modules_and_interface_types/user/src/tests.rs index f50baa06..c4007178 100644 --- a/examples/0_modules_and_interface_types/user/src/tests.rs +++ b/examples/0_modules_and_interface_types/user/src/tests.rs @@ -1,16 +1,10 @@ -use abi_stable::{ - std_types::RCow, - DynTrait, -}; - -use example_0_interface::{ - CowStrIter, -}; +use abi_stable::{std_types::RCow, DynTrait}; +use example_0_interface::CowStrIter; use super::*; -/// This tests that a type coming from a dynamic library +/// This tests that a type coming from a dynamic library /// cannot be converted back to its std-library equivalent /// while reusing the heap allocation. /// @@ -19,48 +13,51 @@ use super::*; /// /// There is no way that I am aware to check at compile-time what allocator /// the type is using,so this is the best I can do while staying safe. -pub fn run_dynamic_library_tests(mods:TextOpsMod_Ref){ +pub fn run_dynamic_library_tests(mods: TextOpsMod_Ref) { test_reverse_lines(mods); test_remove_words(mods); - + println!(); println!(".-------------------------."); println!("| tests succeeded! |"); println!("'-------------------------'"); - } - -fn test_reverse_lines(mods:TextOpsMod_Ref) { - let text_ops=mods; +fn test_reverse_lines(mods: TextOpsMod_Ref) { + let text_ops = mods; let mut state = text_ops.new()(); assert_eq!( - &* text_ops.reverse_lines()(&mut state, "hello\nbig\nworld".into()), + &*text_ops.reverse_lines()(&mut state, "hello\nbig\nworld".into()), "world\nbig\nhello\n" ); } - -fn test_remove_words(mods:TextOpsMod_Ref) { - let text_ops=mods; +fn test_remove_words(mods: TextOpsMod_Ref) { + let text_ops = mods; let mut state = text_ops.new()(); { - let words = &mut vec!["burrito", "like","a"].into_iter().map(RCow::from); - + let words = &mut vec!["burrito", "like", "a"].into_iter().map(RCow::from); + let param = RemoveWords { string: "Monads are like a burrito wrapper.".into(), - words: DynTrait::from_borrowing_ptr(words,CowStrIter), + words: DynTrait::from_borrowing_ptr(words, CowStrIter), }; - assert_eq!(&*text_ops.remove_words()(&mut state, param), "Monads are wrapper."); + assert_eq!( + &*text_ops.remove_words()(&mut state, param), + "Monads are wrapper." + ); } { - let words = &mut vec!["largest","is"].into_iter().map(RCow::from); + let words = &mut vec!["largest", "is"].into_iter().map(RCow::from); let param = RemoveWords { string: "The largest planet is jupiter.".into(), - words: DynTrait::from_borrowing_ptr(words,CowStrIter), + words: DynTrait::from_borrowing_ptr(words, CowStrIter), }; - assert_eq!(&*text_ops.remove_words()(&mut state, param), "The planet jupiter."); + assert_eq!( + &*text_ops.remove_words()(&mut state, param), + "The planet jupiter." + ); } } diff --git a/examples/1_trait_objects/application/src/app.rs b/examples/1_trait_objects/application/src/app.rs index 25f9414f..7b73509a 100644 --- a/examples/1_trait_objects/application/src/app.rs +++ b/examples/1_trait_objects/application/src/app.rs @@ -1,31 +1,25 @@ use super::*; -use std::time::{Duration,Instant}; +use std::time::{Duration, Instant}; -pub struct TheApplication{ - pub(super) plugins:Vec, - pub(super) state:ApplicationState, +pub struct TheApplication { + pub(super) plugins: Vec, + pub(super) state: ApplicationState, } - -pub struct ApplicationState{ - // This is separate so that I can use the address +pub struct ApplicationState { + // This is separate so that I can use the address // of a PluginType to find its index inside of plugins. - pub(super) plugin_ids:Vec, - pub(super) id_map:HashMap, - pub(super) delayed_commands:VecDeque, - pub(super) responses:VecDeque, - pub(super) sender:RSender, - pub(super) receiver:RReceiver, - pub(super) last_run_at:Instant, + pub(super) plugin_ids: Vec, + pub(super) id_map: HashMap, + pub(super) delayed_commands: VecDeque, + pub(super) responses: VecDeque, + pub(super) sender: RSender, + pub(super) receiver: RReceiver, + pub(super) last_run_at: Instant, } - - -fn print_response( - plugin_id:&PluginId, - response:&str, -){ +fn print_response(plugin_id: &PluginId, response: &str) { println!( "reponse:\n{}\nfrom:\n {:?}\n\n", response.left_pad(4), @@ -33,59 +27,67 @@ fn print_response( ); } -impl TheApplication{ +impl TheApplication { /// Runs a command, - pub fn run_command(&mut self,which_plugin:WhichPlugin,command:RStr<'_>)->Result<(),AppError>{ - let list=self.state.expand_which_plugin(which_plugin)?; + pub fn run_command( + &mut self, + which_plugin: WhichPlugin, + command: RStr<'_>, + ) -> Result<(), AppError> { + let list = self.state.expand_which_plugin(which_plugin)?; for index in list { - let state=Application_TO::from_ptr(&mut self.state,TD_Opaque); - let plugin=&mut self.plugins[index as usize]; + let state = Application_TO::from_ptr(&mut self.state, TD_Opaque); + let plugin = &mut self.plugins[index as usize]; println!("command:\n{}", command.left_pad(4)); - let resp=plugin.json_command(command,state).into_result()?; + let resp = plugin.json_command(command, state).into_result()?; self.state.register_command_run(); - print_response(&self.state.plugin_ids[index],&resp); + print_response(&self.state.plugin_ids[index], &resp); } Ok(()) } - pub fn tick(&mut self)->Result<(),AppError>{ - if let Ok(ac)=self.state.receiver.try_recv() { - self.state.send_command_to_plugin(&ac.from,ac.which_plugin,ac.command).into_result()?; + pub fn tick(&mut self) -> Result<(), AppError> { + if let Ok(ac) = self.state.receiver.try_recv() { + self.state + .send_command_to_plugin(&ac.from, ac.which_plugin, ac.command) + .into_result()?; } - if let Some(dc)=self.state.delayed_commands.pop_front() { - self.run_command_(&dc.from,dc.plugin_index,&dc.command)?; + if let Some(dc) = self.state.delayed_commands.pop_front() { + self.run_command_(&dc.from, dc.plugin_index, &dc.command)?; } - let mut responses=mem::replace(&mut self.state.responses,VecDeque::new()); - for DelayedResponse{to,from,response} in responses.drain(..) { - let response=PluginResponse::owned_response(from,response); - let state=Application_TO::from_ptr(&mut self.state,TD_Opaque); - if let RSome(res)=self.plugins[to] + let mut responses = mem::replace(&mut self.state.responses, VecDeque::new()); + for DelayedResponse { to, from, response } in responses.drain(..) { + let response = PluginResponse::owned_response(from, response); + let state = Application_TO::from_ptr(&mut self.state, TD_Opaque); + if let RSome(res) = self.plugins[to] .handle_response(response, state) .into_result()? { - print_response(&res.plugin_id,&res.response); + print_response(&res.plugin_id, &res.response); } } - self.state.responses=responses; + self.state.responses = responses; Ok(()) } - pub fn is_finished(&self)->bool{ - self.state.last_run_at.elapsed()>=Duration::from_secs(5) + pub fn is_finished(&self) -> bool { + self.state.last_run_at.elapsed() >= Duration::from_secs(5) } - fn run_command_(&mut self,from:&PluginId,to:usize,command:&str)->Result<(),AppError>{ - let state=Application_TO::from_ptr(&mut self.state,TD_Opaque); - let response=self.plugins[to].json_command(command.into(),state).into_result()?; - let to=self.state.index_for_plugin_id(from)?; + fn run_command_(&mut self, from: &PluginId, to: usize, command: &str) -> Result<(), AppError> { + let state = Application_TO::from_ptr(&mut self.state, TD_Opaque); + let response = self.plugins[to] + .json_command(command.into(), state) + .into_result()?; + let to = self.state.index_for_plugin_id(from)?; self.state.register_command_run(); - let response=DelayedResponse{ - from:self.state.plugin_ids[to].clone(), + let response = DelayedResponse { + from: self.state.plugin_ids[to].clone(), to, response, }; @@ -95,115 +97,103 @@ impl TheApplication{ } } +impl ApplicationState { + pub(crate) fn new() -> Self { + let (sender, receiver) = crossbeam_channel::unbounded(); -impl ApplicationState{ - pub(crate) fn new()->Self{ - let (sender,receiver)=crossbeam_channel::unbounded(); - - Self{ - plugin_ids:Vec::new(), - id_map:HashMap::new(), - delayed_commands:VecDeque::new(), - responses:VecDeque::new(), + Self { + plugin_ids: Vec::new(), + id_map: HashMap::new(), + delayed_commands: VecDeque::new(), + responses: VecDeque::new(), sender, receiver, - last_run_at:Instant::now(), + last_run_at: Instant::now(), } } - fn register_command_run(&mut self){ - self.last_run_at=Instant::now(); + fn register_command_run(&mut self) { + self.last_run_at = Instant::now(); } - fn index_for_plugin_id(&self,id:&PluginId)->Result{ - self.id_map.get(&*id.named) - .and_then(|x| x.indices.get(id.instance as usize).cloned() ) - .ok_or_else(|| AppError::InvalidPlugin(WhichPlugin::Id(id.clone())) ) + fn index_for_plugin_id(&self, id: &PluginId) -> Result { + self.id_map + .get(&*id.named) + .and_then(|x| x.indices.get(id.instance as usize).cloned()) + .ok_or_else(|| AppError::InvalidPlugin(WhichPlugin::Id(id.clone()))) } - fn expand_which_plugin(&self,which_plugin:WhichPlugin)->Result{ + fn expand_which_plugin(&self, which_plugin: WhichPlugin) -> Result { match which_plugin { - WhichPlugin::Id(id)=>{ - self.index_for_plugin_id(&id) - .map(|i| PluginIndices::from([i]) ) - }, - WhichPlugin::First{ref named} - |WhichPlugin::Last{ref named} - |WhichPlugin::Every{ref named}=>{ - self.id_map.get(&**named) - .and_then(|x|{ - let list=&x.indices; - match which_plugin { - WhichPlugin::First{..}=>{ - PluginIndices::from([*list.first()?]) - }, - WhichPlugin::Last{..}=>{ - PluginIndices::from([*list.last()?]) - }, - WhichPlugin::Every{..}=>{ - PluginIndices::from(&**list) - }, - _=>unreachable!(), - }.piped(Some) - }) - .ok_or_else(|| AppError::InvalidPlugin(which_plugin.clone()) ) - }, - WhichPlugin::Many(list)=>{ - let mut plugin_indices=PluginIndices::new(); + WhichPlugin::Id(id) => self + .index_for_plugin_id(&id) + .map(|i| PluginIndices::from([i])), + WhichPlugin::First { ref named } + | WhichPlugin::Last { ref named } + | WhichPlugin::Every { ref named } => self + .id_map + .get(&**named) + .and_then(|x| { + let list = &x.indices; + match which_plugin { + WhichPlugin::First { .. } => PluginIndices::from([*list.first()?]), + WhichPlugin::Last { .. } => PluginIndices::from([*list.last()?]), + WhichPlugin::Every { .. } => PluginIndices::from(&**list), + _ => unreachable!(), + } + .piped(Some) + }) + .ok_or_else(|| AppError::InvalidPlugin(which_plugin.clone())), + WhichPlugin::Many(list) => { + let mut plugin_indices = PluginIndices::new(); for elem in list { plugin_indices.extend(self.expand_which_plugin(elem)?); } - Ok(plugin_indices) + Ok(plugin_indices) } } } } - -impl Application for ApplicationState{ +impl Application for ApplicationState { fn send_command_to_plugin( &mut self, - from:&PluginId, - which_plugin:WhichPlugin, - command:RString, - )->RResult<(),AppError>{ + from: &PluginId, + which_plugin: WhichPlugin, + command: RString, + ) -> RResult<(), AppError> { self.expand_which_plugin(which_plugin) - .map(|plugin_indices|{ - let command=Arc::new(command); + .map(|plugin_indices| { + let command = Arc::new(command); for plugin_index in plugin_indices { - let from=from.clone(); - self.delayed_commands.push_back(DelayedCommand{ + let from = from.clone(); + self.delayed_commands.push_back(DelayedCommand { from, plugin_index, - command:command.clone(), + command: command.clone(), }); } - }).into() + }) + .into() } - fn get_plugin_id(&self,which_plugin:WhichPlugin)->RResult,AppError>{ + fn get_plugin_id(&self, which_plugin: WhichPlugin) -> RResult, AppError> { self.expand_which_plugin(which_plugin) - .map(|list|{ + .map(|list| { list.into_iter() - .map(|i| self.plugin_ids[i].clone() ) + .map(|i| self.plugin_ids[i].clone()) .collect::>() }) .into() } - fn sender(&self)->RSender{ + fn sender(&self) -> RSender { self.sender.clone() } - fn loaded_plugins(&self)->RVec{ + fn loaded_plugins(&self) -> RVec { self.plugin_ids.clone().into() } } - - //////////////////////////////////////////////////////////////////////////////// - - - - diff --git a/examples/1_trait_objects/application/src/main.rs b/examples/1_trait_objects/application/src/main.rs index d5818742..902a1e78 100644 --- a/examples/1_trait_objects/application/src/main.rs +++ b/examples/1_trait_objects/application/src/main.rs @@ -1,155 +1,143 @@ use std::{ - collections::{HashMap,VecDeque}, - io, - path::{Path,PathBuf}, - mem, + collections::{HashMap, VecDeque}, + io, mem, + path::{Path, PathBuf}, sync::Arc, }; use abi_stable::{ - external_types::crossbeam_channel::{self,RSender,RReceiver}, - std_types::{RString,RStr,RResult,RVec,ROk,RErr,RSome}, + external_types::crossbeam_channel::{self, RReceiver, RSender}, + library::{lib_header_from_path, LibraryError, LibrarySuffix, RawLibrary}, sabi_trait::prelude::TD_Opaque, - library::{RawLibrary,LibraryError,LibrarySuffix,lib_header_from_path}, + std_types::{RErr, ROk, RResult, RSome, RStr, RString, RVec}, }; #[allow(unused_imports)] -use core_extensions::{SelfOps,SliceExt,StringExt}; +use core_extensions::{SelfOps, SliceExt, StringExt}; use example_1_interface::{ - AsyncCommand, - Application_TO, - Application, - Error as AppError, - PluginId, - PluginMod_Ref, - PluginType, - PluginResponse, - WhichPlugin, + Application, Application_TO, AsyncCommand, Error as AppError, PluginId, PluginMod_Ref, + PluginResponse, PluginType, WhichPlugin, }; -use serde::{Deserialize}; +use serde::Deserialize; use serde_json::value::RawValue; use smallvec::SmallVec; -mod vec_from_map; mod app; +mod vec_from_map; use crate::{ - app::{TheApplication,ApplicationState}, + app::{ApplicationState, TheApplication}, vec_from_map::VecFromMap, }; - /// Returns the path the plugin will be loaded from. -fn compute_plugin_path(base_name:&str)->io::Result{ - let debug_dir ="../../../target/debug/" .as_ref_::().into_::(); - let release_dir="../../../target/release/".as_ref_::().into_::(); - - let debug_path= - RawLibrary::path_in_directory(&debug_dir ,base_name,LibrarySuffix::NoSuffix); - - let release_path= - RawLibrary::path_in_directory(&release_dir,base_name,LibrarySuffix::NoSuffix); - - match (debug_path.exists(),release_path.exists()) { - (false,false)=>debug_path, - (true,false)=>debug_path, - (false,true)=>release_path, - (true,true)=>{ +fn compute_plugin_path(base_name: &str) -> io::Result { + let debug_dir = "../../../target/debug/" + .as_ref_::() + .into_::(); + let release_dir = "../../../target/release/" + .as_ref_::() + .into_::(); + + let debug_path = RawLibrary::path_in_directory(&debug_dir, base_name, LibrarySuffix::NoSuffix); + + let release_path = + RawLibrary::path_in_directory(&release_dir, base_name, LibrarySuffix::NoSuffix); + + match (debug_path.exists(), release_path.exists()) { + (false, false) => debug_path, + (true, false) => debug_path, + (false, true) => release_path, + (true, true) => { if debug_path.metadata()?.modified()? < release_path.metadata()?.modified()? { release_path - }else{ + } else { debug_path } } - }.piped(Ok) + } + .piped(Ok) } /// A description of what plugin to load. -#[derive(Debug,Clone,Deserialize)] -#[serde(untagged)] -pub enum PluginToLoad{ +#[derive(Debug, Clone, Deserialize)] +#[serde(untagged)] +pub enum PluginToLoad { Named(String), - WithInstances{ - #[serde(alias = "name")] - named:String, - #[serde(default="one_u64")] - instances:u64, - #[serde(alias = "renamed")] - rename:Option, - } + WithInstances { + #[serde(alias = "name")] + named: String, + #[serde(default = "one_u64")] + instances: u64, + #[serde(alias = "renamed")] + rename: Option, + }, } -fn one_u64()->u64{ +fn one_u64() -> u64 { 1 } /// The type that the configuration file is deserialized into. -#[derive(Debug,Clone,Deserialize)] -pub struct Config{ - pub plugins:RVec, - pub commands:VecFromMap>, +#[derive(Debug, Clone, Deserialize)] +pub struct Config { + pub plugins: RVec, + pub commands: VecFromMap>, } - /// A description of plugin instances that were instantiated and left to instantiate, /// as well as the root module of the plugin's dynamic library to instantiate the plugins. -pub struct PluginModAndIndices{ - root_module:PluginMod_Ref, - to_be_instantiated:u64, - indices:Vec, +pub struct PluginModAndIndices { + root_module: PluginMod_Ref, + to_be_instantiated: u64, + indices: Vec, } - -pub type PluginIndices=SmallVec<[usize;1]>; +pub type PluginIndices = SmallVec<[usize; 1]>; /// Commands sent to plugins after calling `Application::send_command_to_plugin`. #[derive(Debug)] -pub struct DelayedCommand{ +pub struct DelayedCommand { /// Which plugin sent the command - from:PluginId, + from: PluginId, /// The index in plugins to which the command is sent. - plugin_index:usize, + plugin_index: usize, /// The command for the `plugin_index` plugin. - command:Arc, + command: Arc, } - /// Used to handle the responses to the delayed commands sent to plugins after calling /// `Application::send_command_to_plugin`. #[derive(Debug)] -pub struct DelayedResponse{ +pub struct DelayedResponse { /// The plugin that sends the reponse. - from:PluginId, + from: PluginId, /// The plugin that sent the command for which this is the reponse. - to:usize, + to: usize, /// The response from the `from` plugin to the `to` plugin. - response:RString, + response: RString, } - -fn main()-> io::Result<()> { - - let config_path=match std::env::args_os().nth(1) { - Some(os)=>PathBuf::from(os), - None=>{ - println!( - "Help:You can pass a configuration's path as a command-line argument." - ); +fn main() -> io::Result<()> { + let config_path = match std::env::args_os().nth(1) { + Some(os) => PathBuf::from(os), + None => { + println!("Help:You can pass a configuration's path as a command-line argument."); PathBuf::from("./data/app_config.json") } }; - let file_contents=match std::fs::read_to_string(&*config_path) { - Ok(x)=>x, - Err(e)=>{ + let file_contents = match std::fs::read_to_string(&*config_path) { + Ok(x) => x, + Err(e) => { eprintln!( "Could not load the configuration file at:\n\ \t{}\n\ - Because of this error:\n{}\n", + Because of this error:\n{}\n", config_path.display(), e ); @@ -157,165 +145,166 @@ fn main()-> io::Result<()> { } }; - let config:Config=match serde_json::from_str(&file_contents) { + let config: Config = match serde_json::from_str(&file_contents) { Ok(x) => x, Err(e) => { eprintln!( "Could not parse the configuration file at:\n\ \t{}\n\ Because of this error:\n\ - {}\n", + {}\n", config_path.display(), e ); std::process::exit(1); - }, + } }; - let mut nonexistent_files=Vec::<(String,io::Error)>::new(); - - let mut library_errs=Vec::<(String,LibraryError)>::new(); + let mut nonexistent_files = Vec::<(String, io::Error)>::new(); - let mut loaded_libraries=Vec::::new(); + let mut library_errs = Vec::<(String, LibraryError)>::new(); - let mut plugins=Vec::new(); - let mut state=ApplicationState::new(); + let mut loaded_libraries = Vec::::new(); - for plug in &config.plugins { + let mut plugins = Vec::new(); + let mut state = ApplicationState::new(); - let (named,instances,rename)=match plug { - PluginToLoad::Named(named)=> - ((*named).clone(),1,None), - PluginToLoad::WithInstances{named,instances,rename}=> - ((*named).clone(),*instances,rename.clone()), + for plug in &config.plugins { + let (named, instances, rename) = match plug { + PluginToLoad::Named(named) => ((*named).clone(), 1, None), + PluginToLoad::WithInstances { + named, + instances, + rename, + } => ((*named).clone(), *instances, rename.clone()), }; - let name_key=rename.unwrap_or_else(||named.clone()); + let name_key = rename.unwrap_or_else(|| named.clone()); - if let Some(mod_i)=state.id_map.get_mut(&*name_key) { - mod_i.to_be_instantiated+=instances; + if let Some(mod_i) = state.id_map.get_mut(&*name_key) { + mod_i.to_be_instantiated += instances; continue; } - let library_path:PathBuf=match compute_plugin_path(named.as_ref()) { - Ok(x)=>x, - Err(e)=>{ - nonexistent_files.push((named.clone(),e)); + let library_path: PathBuf = match compute_plugin_path(named.as_ref()) { + Ok(x) => x, + Err(e) => { + nonexistent_files.push((named.clone(), e)); continue; } }; - let res=(||{ - let header=lib_header_from_path(&library_path)?; + let res = (|| { + let header = lib_header_from_path(&library_path)?; header.init_root_module::() })(); - let root_module=match res { - Ok(x)=>x, - Err(e)=>{ - library_errs.push((named.clone(),e)); + let root_module = match res { + Ok(x) => x, + Err(e) => { + library_errs.push((named.clone(), e)); continue; } }; loaded_libraries.push(name_key.clone()); - state.id_map.insert(name_key.into_::(),PluginModAndIndices{ - root_module, - to_be_instantiated:instances, - indices:Vec::with_capacity(instances as usize), - }); + state.id_map.insert( + name_key.into_::(), + PluginModAndIndices { + root_module, + to_be_instantiated: instances, + indices: Vec::with_capacity(instances as usize), + }, + ); } - if !nonexistent_files.is_empty(){ - for (name,e) in nonexistent_files { + if !nonexistent_files.is_empty() { + for (name, e) in nonexistent_files { eprintln!( "Could not load librarr:\n\ \t{}\n\ because of this error:\n\ {}\n\ ", - name,e + name, e ) } std::process::exit(1); } - if !library_errs.is_empty(){ - for (name,e) in library_errs { + if !library_errs.is_empty() { + for (name, e) in library_errs { eprintln!( "Could not load librarr:\n\ \t{}\n\ because of this error:\n\ {}\n\ ", - name,e + name, e ) } std::process::exit(1); } - let mut plugin_new_errs=Vec::<(String,AppError)>::new(); + let mut plugin_new_errs = Vec::<(String, AppError)>::new(); for name in loaded_libraries { - let mod_i=state.id_map.get_mut(&*name).unwrap(); - for _ in 0..mem::replace(&mut mod_i.to_be_instantiated,0) { - let plugin_constructor=mod_i.root_module.new(); - let new_id=PluginId{ - named:name.clone().into(), - instance:mod_i.indices.len() as u64, + let mod_i = state.id_map.get_mut(&*name).unwrap(); + for _ in 0..mem::replace(&mut mod_i.to_be_instantiated, 0) { + let plugin_constructor = mod_i.root_module.new(); + let new_id = PluginId { + named: name.clone().into(), + instance: mod_i.indices.len() as u64, }; - let plugin=match plugin_constructor(state.sender.clone(),new_id.clone()) { - ROk(x)=>x, - RErr(e)=>{ - plugin_new_errs.push((name.clone(),e)); + let plugin = match plugin_constructor(state.sender.clone(), new_id.clone()) { + ROk(x) => x, + RErr(e) => { + plugin_new_errs.push((name.clone(), e)); continue; } }; - let new_index=plugins.len(); + let new_index = plugins.len(); plugins.push(plugin); - + mod_i.indices.push(new_index); state.plugin_ids.push(new_id); } } if !plugin_new_errs.is_empty() { - for (name,e) in plugin_new_errs { + for (name, e) in plugin_new_errs { eprintln!( "Could not instantiate plugin:\n\ \t{}\n\ because of this error:\n\ {}\n\ ", - name,e + name, e ) } std::process::exit(1); } - let mut config_commands=config.commands.vec.into_iter(); + let mut config_commands = config.commands.vec.into_iter(); - let mut app=TheApplication{ - plugins, - state, - }; + let mut app = TheApplication { plugins, state }; while !app.is_finished() { - if let Some((which_plugin,command))=config_commands.next() { - let command=command.get(); - if let Err(e)=app.run_command(which_plugin.clone(),command.into()){ + if let Some((which_plugin, command)) = config_commands.next() { + let command = command.get(); + if let Err(e) = app.run_command(which_plugin.clone(), command.into()) { eprintln!( "Error while running command on:\n{:?}\nError:{}\nCommand:\n{:?}\n", - which_plugin,e,command + which_plugin, e, command ); } } - if let Err(e)=app.tick() { - eprintln!("Error in application loop:\n{}\n",e); + if let Err(e) = app.tick() { + eprintln!("Error in application loop:\n{}\n", e); } } @@ -325,5 +314,3 @@ fn main()-> io::Result<()> { Ok(()) } - - diff --git a/examples/1_trait_objects/application/src/vec_from_map.rs b/examples/1_trait_objects/application/src/vec_from_map.rs index 3fc51aa4..ed85a58a 100644 --- a/examples/1_trait_objects/application/src/vec_from_map.rs +++ b/examples/1_trait_objects/application/src/vec_from_map.rs @@ -1,24 +1,21 @@ -use std::{ - fmt, - marker::PhantomData, -}; - -use serde::de::{Deserialize, Deserializer, Visitor, MapAccess}; +use std::{fmt, marker::PhantomData}; +use serde::de::{Deserialize, Deserializer, MapAccess, Visitor}; /// Used to deserialize a json object to a list of key-value pairs -#[derive(Clone,Debug)] -pub struct VecFromMap{ - pub vec:Vec<(K,V)>, +#[derive(Clone, Debug)] +pub struct VecFromMap { + pub vec: Vec<(K, V)>, } - struct VecFromMapVisitor { - marker: PhantomData<(K, V)> + marker: PhantomData<(K, V)>, } impl VecFromMapVisitor { - const NEW:Self=Self{marker:PhantomData}; + const NEW: Self = Self { + marker: PhantomData, + }; } impl<'de, K, V> Visitor<'de> for VecFromMapVisitor @@ -36,14 +33,14 @@ where where M: MapAccess<'de>, { - let cap=access.size_hint().unwrap_or(0); - let mut vec = Vec::<(K,V)>::with_capacity(cap); + let cap = access.size_hint().unwrap_or(0); + let mut vec = Vec::<(K, V)>::with_capacity(cap); while let Some(pair) = access.next_entry()? { vec.push(pair); } - Ok(VecFromMap{vec}) + Ok(VecFromMap { vec }) } } diff --git a/examples/1_trait_objects/interface/src/commands.rs b/examples/1_trait_objects/interface/src/commands.rs index 49b16fef..146a4cab 100644 --- a/examples/1_trait_objects/interface/src/commands.rs +++ b/examples/1_trait_objects/interface/src/commands.rs @@ -1,72 +1,60 @@ -use crate::{PluginId,WhichPlugin}; +use crate::{PluginId, WhichPlugin}; -use std::{ - fmt, -}; +use std::fmt; use serde::{ - Serialize,Deserialize, - de::{self,Deserializer, DeserializeOwned, IgnoredAny, Visitor, MapAccess, Error as _}, + de::{self, DeserializeOwned, Deserializer, Error as _, IgnoredAny, MapAccess, Visitor}, + Deserialize, Serialize, }; -use abi_stable::{ - StableAbi, - std_types::*, -}; +use abi_stable::{std_types::*, StableAbi}; /// The commands that map to methods in the Plugin trait. // This is intentionally not `#[derive(StableAbi)]`, // since it can be extended in minor versions of the interface. // I has to be serialized to pass it through ffi. -#[derive(Debug,Clone,PartialEq,Eq,Serialize,Deserialize)] -pub enum BasicCommand{ +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum BasicCommand { GetCommands, } - /// These is the (serialized) return value of calling `PluginExt::send_basic_command`. // This is intentionally not `#[derive(StableAbi)]`, // since it can be extended in minor versions of the interface. // I has to be serialized to pass it through ffi. -#[derive(Debug,Clone,PartialEq,Eq,Serialize,Deserialize)] -pub enum BasicRetVal{ +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum BasicRetVal { GetCommands(RVec), } - // This is intentionally not `#[derive(StableAbi)]`, // since it can be extended in minor versions of the interface. // I has to be serialized to pass it through ffi. -#[derive(Debug,Clone,PartialEq,Eq,Serialize,Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(untagged)] -pub enum CommandUnion{ +pub enum CommandUnion { ForPlugin(T), Basic(BasicCommand), } - -#[derive(Debug,Clone,PartialEq,Eq,Serialize,Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(untagged)] -pub enum ReturnValUnion{ +pub enum ReturnValUnion { ForPlugin(T), Basic(BasicRetVal), } - - //////////////////////////////////////////////////////////////////////////////// - /// A partially deserialize command,that only deserialized its variant. -#[derive(Debug,Clone)] -pub struct WhichVariant{ - pub variant:RString, +#[derive(Debug, Clone)] +pub struct WhichVariant { + pub variant: RString, } - struct WhichVariantVisitor; -impl<'de> Visitor<'de> for WhichVariantVisitor{ +impl<'de> Visitor<'de> for WhichVariantVisitor { type Value = WhichVariant; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { @@ -77,29 +65,31 @@ impl<'de> Visitor<'de> for WhichVariantVisitor{ where E: de::Error, { - Ok(WhichVariant{variant:value.to_string().into()}) + Ok(WhichVariant { + variant: value.to_string().into(), + }) } fn visit_map(self, mut access: M) -> Result where M: MapAccess<'de>, { - let (variant,_)=access.next_entry::()? - .ok_or_else(||M::Error::custom("Expected a map with a single entry"))?; - if let Some((second,_))=access.next_entry::()? { - let s=format!( + let (variant, _) = access + .next_entry::()? + .ok_or_else(|| M::Error::custom("Expected a map with a single entry"))?; + if let Some((second, _)) = access.next_entry::()? { + let s = format!( "Expected a map with a single field,\n\ instead found both {{ \"{}\":... , \"{}\": ... }}", - variant, - second, + variant, second, ); return Err(M::Error::custom(s)); } - Ok(WhichVariant{variant}) + Ok(WhichVariant { variant }) } } -impl<'de> Deserialize<'de> for WhichVariant{ +impl<'de> Deserialize<'de> for WhichVariant { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, @@ -108,54 +98,43 @@ impl<'de> Deserialize<'de> for WhichVariant{ } } - - - //////////////////////////////////////////////////////////////////////////////// - /// Denotes this as a command type. -pub trait CommandTrait:Serialize{ - type Returns:DeserializeOwned; +pub trait CommandTrait: Serialize { + type Returns: DeserializeOwned; } -impl CommandTrait for BasicCommand{ - type Returns=BasicRetVal; +impl CommandTrait for BasicCommand { + type Returns = BasicRetVal; } - /// Describes a command. #[repr(C)] -#[derive(Debug,Clone,PartialEq,Eq,Serialize,Deserialize,StableAbi)] -pub struct CommandDescription{ +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, StableAbi)] +pub struct CommandDescription { /// A description of what this command does. - pub name:RCow<'static,str>, + pub name: RCow<'static, str>, /// A description of what this command does, /// optionally with a description of the command format. - pub description:RCow<'static,str>, + pub description: RCow<'static, str>, } - -impl CommandDescription{ - pub fn from_literals( - name:&'static str, - description:&'static str, - )->Self{ - CommandDescription{ - name:name.into(), - description:description.into(), +impl CommandDescription { + pub fn from_literals(name: &'static str, description: &'static str) -> Self { + CommandDescription { + name: name.into(), + description: description.into(), } } } - //////////////////////////////////////////////////////////////////////////////// - #[repr(C)] -#[derive(Debug,Clone,PartialEq,Eq,StableAbi)] -pub struct AsyncCommand{ - pub from:PluginId, - pub which_plugin:WhichPlugin, - pub command:RString, +#[derive(Debug, Clone, PartialEq, Eq, StableAbi)] +pub struct AsyncCommand { + pub from: PluginId, + pub which_plugin: WhichPlugin, + pub command: RString, } diff --git a/examples/1_trait_objects/interface/src/error.rs b/examples/1_trait_objects/interface/src/error.rs index b591fef0..2b5665ab 100644 --- a/examples/1_trait_objects/interface/src/error.rs +++ b/examples/1_trait_objects/interface/src/error.rs @@ -1,31 +1,28 @@ -use crate::{commands::CommandDescription,WhichPlugin,WhichCommandRet}; +use crate::{commands::CommandDescription, WhichCommandRet, WhichPlugin}; use abi_stable::{ + std_types::{RBox, RBoxError, RString, RVec}, StableAbi, - std_types::{ - RBoxError,RBox,RString,RVec, - }, }; use std::{ error::Error as ErrorTrait, - fmt::{self,Display}, + fmt::{self, Display}, }; use core_extensions::strings::StringExt; - #[repr(u8)] -#[derive(Debug,StableAbi)] -pub enum Error{ +#[derive(Debug, StableAbi)] +pub enum Error { /// An error produced by `serde_json::to_string`. - Serialize(RBoxError,WhichCommandRet), + Serialize(RBoxError, WhichCommandRet), /// An error produced by `serde_json::from_string`. - Deserialize(RBoxError,WhichCommandRet), - /// A deserialization error produced when trying to deserialize json + Deserialize(RBoxError, WhichCommandRet), + /// A deserialization error produced when trying to deserialize json /// as a particular command type. UnsupportedCommand(RBox), - /// A deserialization error produced when trying to deserialize json + /// A deserialization error produced when trying to deserialize json /// as a particular return value type. UnsupportedReturnValue(RBox), /// An invalid plugin. @@ -38,46 +35,49 @@ pub enum Error{ /// Represents a command or return value that wasn't supported. #[repr(C)] -#[derive(Debug,StableAbi)] -pub struct Unsupported{ +#[derive(Debug, StableAbi)] +pub struct Unsupported { /// The name of the plugin for which the command/return value wasn't supported. - pub plugin_name:RString, + pub plugin_name: RString, /// The command/return value that wasn't supported. - pub command_name:RString, + pub command_name: RString, /// A custom error. - pub error:RBoxError, + pub error: RBoxError, /// A list of the commands that the plugin supports - pub supported_commands:RVec, + pub supported_commands: RVec, } - -impl Error{ - pub fn unsupported_command(what:Unsupported)->Self{ +impl Error { + pub fn unsupported_command(what: Unsupported) -> Self { Error::UnsupportedCommand(RBox::new(what)) } - pub fn unsupported_return_value(what:Unsupported)->Self{ + pub fn unsupported_return_value(what: Unsupported) -> Self { Error::UnsupportedReturnValue(RBox::new(what)) } } -impl Display for Error{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result { +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Error::Serialize(e,which)=>{ - let which=match which { - WhichCommandRet::Command=>"command", - WhichCommandRet::Return=>"return value", + Error::Serialize(e, which) => { + let which = match which { + WhichCommandRet::Command => "command", + WhichCommandRet::Return => "return value", }; - writeln!(f,"Error happened while serializing the {}:\n{}\n",which,e) + writeln!( + f, + "Error happened while serializing the {}:\n{}\n", + which, e + ) } - Error::Deserialize(e,which)=>{ - let which=match which { - WhichCommandRet::Command=>"command", - WhichCommandRet::Return=>"return value", + Error::Deserialize(e, which) => { + let which = match which { + WhichCommandRet::Command => "command", + WhichCommandRet::Return => "return value", }; - writeln!(f,"Error happened while deserializing {}:\n{}\n",which,e) + writeln!(f, "Error happened while deserializing {}:\n{}\n", which, e) } - Error::UnsupportedCommand(v)=>{ + Error::UnsupportedCommand(v) => { writeln!( f, "Plugin '{}' ooes not support this command:\n\ @@ -85,10 +85,7 @@ impl Display for Error{ Because of this error:\n{}\n\ Supported commands:\ ", - v.plugin_name, - v.command_name, - v.error, - + v.plugin_name, v.command_name, v.error, )?; for supported in &v.supported_commands { @@ -99,33 +96,30 @@ impl Display for Error{ "\nName:\n{}\nDescription:\n{}\n\n", supported.name.left_padder(4), supported.description.left_padder(4), - ).left_padder(4) + ) + .left_padder(4) )?; } Ok(()) } - Error::UnsupportedReturnValue(v)=> - writeln!( - f, - "Unrecognized return value from '{}',named:\n\ + Error::UnsupportedReturnValue(v) => writeln!( + f, + "Unrecognized return value from '{}',named:\n\ \t'{}'\n\ Because of this error:\n{}\n\ ", - v.plugin_name, - v.command_name, - v.error, - ), - Error::InvalidPlugin(wc)=> - writeln!( - f, - "Attempted to access a nonexistent plugin with the WhichPlugin:\n\t{:?}\n", - wc - ), - Error::Custom(e)=>Display::fmt(e,f), - Error::Many(list)=>{ + v.plugin_name, v.command_name, v.error, + ), + Error::InvalidPlugin(wc) => writeln!( + f, + "Attempted to access a nonexistent plugin with the WhichPlugin:\n\t{:?}\n", + wc + ), + Error::Custom(e) => Display::fmt(e, f), + Error::Many(list) => { for e in list { - writeln!(f,"{}",e)?; + writeln!(f, "{}", e)?; } Ok(()) } @@ -133,6 +127,4 @@ impl Display for Error{ } } - -impl ErrorTrait for Error{} - +impl ErrorTrait for Error {} diff --git a/examples/1_trait_objects/interface/src/lib.rs b/examples/1_trait_objects/interface/src/lib.rs index 6cb36a57..68f1ac4f 100644 --- a/examples/1_trait_objects/interface/src/lib.rs +++ b/examples/1_trait_objects/interface/src/lib.rs @@ -11,88 +11,81 @@ and all the modules inside of the library. */ use abi_stable::{ - StableAbi, - sabi_trait, - package_version_strings, declare_root_module_statics, + external_types::crossbeam_channel::RSender, library::RootModule, - sabi_types::{VersionStrings, RMut}, - external_types::{ - crossbeam_channel::RSender, - }, - std_types::{RBox, RCow, RVec, RStr, RString,RResult, ROption, ROk,RSome}, + package_version_strings, sabi_trait, + sabi_types::{RMut, VersionStrings}, + std_types::{RBox, RCow, ROk, ROption, RResult, RSome, RStr, RString, RVec}, + StableAbi, }; -use serde::{Serialize,Deserialize}; +use serde::{Deserialize, Serialize}; mod commands; mod error; -mod which_plugin; -mod vec_from_map; pub mod utils; - +mod vec_from_map; +mod which_plugin; pub use self::{ commands::{ - BasicCommand,BasicRetVal,CommandDescription,CommandTrait,WhichVariant,AsyncCommand, + AsyncCommand, BasicCommand, BasicRetVal, CommandDescription, CommandTrait, WhichVariant, }, - error::{Error,Unsupported}, - which_plugin::WhichPlugin, + error::{Error, Unsupported}, vec_from_map::VecFromMap, + which_plugin::WhichPlugin, }; - /////////////////////////////////////////////////////////////////////////////// - /** The identifier for a plugin. */ #[repr(C)] -#[derive(Debug,Clone,PartialEq,Eq,StableAbi,Serialize,Deserialize)] -pub struct PluginId{ - pub named:RCow<'static,str>, +#[derive(Debug, Clone, PartialEq, Eq, StableAbi, Serialize, Deserialize)] +pub struct PluginId { + pub named: RCow<'static, str>, /// The number of the instance of this Plugin. - pub instance:u64, + pub instance: u64, } - /// Describes whether a boxed error is a command or a return value. #[repr(u8)] -#[derive(Debug,Clone,PartialEq,Eq,StableAbi,Serialize,Deserialize)] -pub enum WhichCommandRet{ +#[derive(Debug, Clone, PartialEq, Eq, StableAbi, Serialize, Deserialize)] +pub enum WhichCommandRet { Command, Return, } - /// The response from having called `ApplicationMut::send_command_to_plugin` ealier. #[repr(C)] -#[derive(Debug,Clone,PartialEq,Eq,StableAbi)] -pub struct PluginResponse<'a>{ +#[derive(Debug, Clone, PartialEq, Eq, StableAbi)] +pub struct PluginResponse<'a> { /// The id of the plugin that is responding. - pub plugin_id:PluginId, + pub plugin_id: PluginId, /// The response from the plugin - pub response:RCow<'a,str>, + pub response: RCow<'a, str>, } - -impl<'a> PluginResponse<'a>{ - pub fn owned_response(plugin_id:PluginId,response:RString)->Self{ - Self{plugin_id,response:response.into()} +impl<'a> PluginResponse<'a> { + pub fn owned_response(plugin_id: PluginId, response: RString) -> Self { + Self { + plugin_id, + response: response.into(), + } } - pub fn borrowed_response(plugin_id:PluginId,response:RStr<'a>)->Self{ - Self{plugin_id,response:response.into()} + pub fn borrowed_response(plugin_id: PluginId, response: RStr<'a>) -> Self { + Self { + plugin_id, + response: response.into(), + } } } - - /////////////////////////////////////////////////////////////////////////////// - -pub type PluginType=Plugin_TO<'static,RBox<()>>; - +pub type PluginType = Plugin_TO<'static, RBox<()>>; /** A plugin which is loaded by the application,and provides some functionality. @@ -102,53 +95,51 @@ A plugin which is loaded by the application,and provides some functionality. #[sabi_trait] //#[sabi(debug_print)] pub trait Plugin { - /// Handles a JSON encoded command. fn json_command( &mut self, command: RStr<'_>, - app:ApplicationMut<'_>, - )->RResult; + app: ApplicationMut<'_>, + ) -> RResult; /// Handles a response from another Plugin, /// from having called `ApplicationMut::send_command_to_plugin` ealier. fn handle_response<'a>( &mut self, - response:PluginResponse<'a>, - _app:ApplicationMut<'_>, - )->RResult>,Error>{ + response: PluginResponse<'a>, + _app: ApplicationMut<'_>, + ) -> RResult>, Error> { ROk(RSome(response)) } /// Gets the PluginId that was passed to this plugin in its constructor. - fn plugin_id(&self)->&PluginId; + fn plugin_id(&self) -> &PluginId; /// Gets a description of all commands from this Plugin. - fn list_commands(&self)->RVec; + fn list_commands(&self) -> RVec; /* -Closes the plugin, + Closes the plugin, -This does not unload the dynamic library of this plugin, -you can instantiate another instance of this plugin with -`PluginMod_Ref::get_module().new()(application_handle)`. + This does not unload the dynamic library of this plugin, + you can instantiate another instance of this plugin with + `PluginMod_Ref::get_module().new()(application_handle)`. -The `#[sabi(last_prefix_field)]` attribute here means that this is the last method -that was defined in the first compatible version of the library -(0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), -requiring new methods to always be added below preexisting ones. + The `#[sabi(last_prefix_field)]` attribute here means that this is the last method + that was defined in the first compatible version of the library + (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), + requiring new methods to always be added below preexisting ones. -The `#[sabi(last_prefix_field)]` attribute would stay on this method until the library -bumps its "major" version, -at which point it would be moved to the last method at the time. - */ + The `#[sabi(last_prefix_field)]` attribute would stay on this method until the library + bumps its "major" version, + at which point it would be moved to the last method at the time. + */ #[sabi(last_prefix_field)] - fn close(self,app:ApplicationMut<'_>); + fn close(self, app: ApplicationMut<'_>); } - /////////////////////////////////////////////////////////////////////////////// /// The root module of a`plugin` dynamic library. @@ -156,48 +147,42 @@ at which point it would be moved to the last method at the time. /// To load this module, /// call ::load_from_directory(some_directory_path) #[repr(C)] -#[derive(StableAbi)] -#[sabi(kind(Prefix(prefix_ref="PluginMod_Ref")))] +#[derive(StableAbi)] +#[sabi(kind(Prefix(prefix_ref = "PluginMod_Ref")))] #[sabi(missing_field(panic))] pub struct PluginMod { -/** -Constructs the plugin. + /** + Constructs the plugin. -The `#[sabi(last_prefix_field)]` attribute here means that this is the last field in this struct -that was defined in the first compatible version of the library -(0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), -requiring new fields to always be added below preexisting ones. + The `#[sabi(last_prefix_field)]` attribute here means that this is the last field in this struct + that was defined in the first compatible version of the library + (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), + requiring new fields to always be added below preexisting ones. -The `#[sabi(last_prefix_field)]` attribute would stay on this field until the library -bumps its "major" version, -at which point it would be moved to the last field at the time. + The `#[sabi(last_prefix_field)]` attribute would stay on this field until the library + bumps its "major" version, + at which point it would be moved to the last field at the time. -*/ + */ #[sabi(last_prefix_field)] - pub new: extern "C" fn(RSender,PluginId) -> RResult, + pub new: extern "C" fn(RSender, PluginId) -> RResult, } - impl RootModule for PluginMod_Ref { - declare_root_module_statics!{PluginMod_Ref} + declare_root_module_statics! {PluginMod_Ref} const BASE_NAME: &'static str = "plugin"; const NAME: &'static str = "plugin"; const VERSION_STRINGS: VersionStrings = package_version_strings!(); } - - /////////////////////////////////////////////////////////////////////////////// - /// A mutable reference to the application implementation. -pub type ApplicationMut<'a>=Application_TO<'a, RMut<'a, ()>>; - +pub type ApplicationMut<'a> = Application_TO<'a, RMut<'a, ()>>; #[sabi_trait] -pub trait Application{ - +pub trait Application { /// Asynchronously Sends a command to the plugin(s) specified by `which_plugin`. /// /// # Errors @@ -205,31 +190,31 @@ pub trait Application{ /// Returns an `Error::InvalidPlugin` if `which_plugin` is invalid. fn send_command_to_plugin( &mut self, - from:&PluginId, - which_plugin:WhichPlugin, - command:RString, - )->RResult<(),Error>; + from: &PluginId, + which_plugin: WhichPlugin, + command: RString, + ) -> RResult<(), Error>; -/** -Gets the `PluginId`s of the plugins specified by `which_plugin`. + /** + Gets the `PluginId`s of the plugins specified by `which_plugin`. -The `#[sabi(last_prefix_field)]` attribute here means that this is the last method -that was defined in the first compatible version of the library -(0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), -requiring new methods to always be added below preexisting ones. + The `#[sabi(last_prefix_field)]` attribute here means that this is the last method + that was defined in the first compatible version of the library + (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), + requiring new methods to always be added below preexisting ones. -The `#[sabi(last_prefix_field)]` attribute would stay on this method until the library -bumps its "major" version, -at which point it would be moved to the last method at the time. + The `#[sabi(last_prefix_field)]` attribute would stay on this method until the library + bumps its "major" version, + at which point it would be moved to the last method at the time. -*/ + */ #[sabi(last_prefix_field)] - fn get_plugin_id(&self,which_plugin:WhichPlugin)->RResult,Error>; + fn get_plugin_id(&self, which_plugin: WhichPlugin) -> RResult, Error>; /// Gets the sender end of a channel to send commands to the application/other plugins. - fn sender(&self)->RSender; + fn sender(&self) -> RSender; /// Gets the PluginId of all loaded plugins - fn loaded_plugins(&self)->RVec; -} \ No newline at end of file + fn loaded_plugins(&self) -> RVec; +} diff --git a/examples/1_trait_objects/interface/src/utils.rs b/examples/1_trait_objects/interface/src/utils.rs index be431cd6..42b04255 100644 --- a/examples/1_trait_objects/interface/src/utils.rs +++ b/examples/1_trait_objects/interface/src/utils.rs @@ -1,24 +1,15 @@ use crate::{ commands::{ - BasicCommand, - CommandUnion, - CommandUnion as CU, - CommandTrait, - ReturnValUnion, - ReturnValUnion as RVU, - WhichVariant, - BasicRetVal, + BasicCommand, BasicRetVal, CommandTrait, CommandUnion, CommandUnion as CU, ReturnValUnion, + ReturnValUnion as RVU, WhichVariant, }, error::Unsupported, - ApplicationMut,WhichCommandRet,Error,Plugin,PluginType, + ApplicationMut, Error, Plugin, PluginType, WhichCommandRet, }; -use abi_stable::{ - std_types::{RStr, RString, RBoxError, RResult}, -}; - -use serde::{Serialize,Deserialize}; +use abi_stable::std_types::{RBoxError, RResult, RStr, RString}; +use serde::{Deserialize, Serialize}; /** Sends a json encoded command to a plugin,and returns the response by encoding it to json. @@ -38,49 +29,48 @@ These are all error that this function returns If the command is not supported by the plugin. */ -pub fn process_command<'de,P,C,R,F>(this:&mut P,command:RStr<'de>,f:F)->RResult -where - P:Plugin, - F:FnOnce(&mut P,C)->Result, - C:Deserialize<'de>, - R:Serialize, +pub fn process_command<'de, P, C, R, F>( + this: &mut P, + command: RStr<'de>, + f: F, +) -> RResult +where + P: Plugin, + F: FnOnce(&mut P, C) -> Result, + C: Deserialize<'de>, + R: Serialize, { - (||->Result{ - let command=command.as_str(); - - let which_variant=serde_json::from_str::(&command) - .map_err(|e| Error::Deserialize(RBoxError::new(e),WhichCommandRet::Command) )?; - - let command=serde_json::from_str::>(command) - .map_err(|e|{ - Error::unsupported_command(Unsupported{ - plugin_name:this.plugin_id().named.clone().into_owned(), - command_name:which_variant.variant, - error:RBoxError::new(e), - supported_commands:this.list_commands(), - }) - })?; - - let ret:ReturnValUnion=match command { - CU::Basic(BasicCommand::GetCommands)=>{ - let commands=this.list_commands(); + (|| -> Result { + let command = command.as_str(); + + let which_variant = serde_json::from_str::(&command) + .map_err(|e| Error::Deserialize(RBoxError::new(e), WhichCommandRet::Command))?; + + let command = serde_json::from_str::>(command).map_err(|e| { + Error::unsupported_command(Unsupported { + plugin_name: this.plugin_id().named.clone().into_owned(), + command_name: which_variant.variant, + error: RBoxError::new(e), + supported_commands: this.list_commands(), + }) + })?; + + let ret: ReturnValUnion = match command { + CU::Basic(BasicCommand::GetCommands) => { + let commands = this.list_commands(); RVU::Basic(BasicRetVal::GetCommands(commands)) } - CU::ForPlugin(cmd)=>{ - RVU::ForPlugin(f(this,cmd)?) - } + CU::ForPlugin(cmd) => RVU::ForPlugin(f(this, cmd)?), }; match serde_json::to_string(&ret) { - Ok(v)=>Ok(v.into()), - Err(e)=>Err(Error::Serialize(RBoxError::new(e),WhichCommandRet::Return)), + Ok(v) => Ok(v.into()), + Err(e) => Err(Error::Serialize(RBoxError::new(e), WhichCommandRet::Return)), } - })().into() + })() + .into() } - - - /** Sends a typed command to a plugin. @@ -105,29 +95,27 @@ These are all error that this function returns */ pub fn send_command( - this:&mut PluginType, - command:&C, - app:ApplicationMut<'_> -)->Result -where - C:CommandTrait, + this: &mut PluginType, + command: &C, + app: ApplicationMut<'_>, +) -> Result +where + C: CommandTrait, { - let cmd=serde_json::to_string(&command) - .map_err(|e| Error::Serialize(RBoxError::new(e),WhichCommandRet::Command) )?; + let cmd = serde_json::to_string(&command) + .map_err(|e| Error::Serialize(RBoxError::new(e), WhichCommandRet::Command))?; - let ret=this.json_command(RStr::from(&*cmd),app).into_result()?; + let ret = this.json_command(RStr::from(&*cmd), app).into_result()?; - let which_variant=serde_json::from_str::(&*ret) - .map_err(|e| Error::Deserialize(RBoxError::new(e),WhichCommandRet::Return) )?; + let which_variant = serde_json::from_str::(&*ret) + .map_err(|e| Error::Deserialize(RBoxError::new(e), WhichCommandRet::Return))?; - serde_json::from_str::(&ret) - .map_err(|e|{ - Error::unsupported_return_value(Unsupported{ - plugin_name:this.plugin_id().named.clone().into_owned(), - command_name:which_variant.variant, - error:RBoxError::new(e), - supported_commands:this.list_commands(), - }) + serde_json::from_str::(&ret).map_err(|e| { + Error::unsupported_return_value(Unsupported { + plugin_name: this.plugin_id().named.clone().into_owned(), + command_name: which_variant.variant, + error: RBoxError::new(e), + supported_commands: this.list_commands(), }) - + }) } diff --git a/examples/1_trait_objects/interface/src/vec_from_map.rs b/examples/1_trait_objects/interface/src/vec_from_map.rs index 94f97013..e01976fa 100644 --- a/examples/1_trait_objects/interface/src/vec_from_map.rs +++ b/examples/1_trait_objects/interface/src/vec_from_map.rs @@ -1,24 +1,21 @@ -use std::{ - fmt, - marker::PhantomData, -}; - -use serde::de::{Deserialize, Deserializer, Visitor, MapAccess}; +use std::{fmt, marker::PhantomData}; +use serde::de::{Deserialize, Deserializer, MapAccess, Visitor}; /// Used to deserialize a list of key-value pairs from a json object. -#[derive(Clone,Debug)] -pub struct VecFromMap{ - pub vec:Vec<(K,V)>, +#[derive(Clone, Debug)] +pub struct VecFromMap { + pub vec: Vec<(K, V)>, } - struct VecFromMapVisitor { - marker: PhantomData<(K, V)> + marker: PhantomData<(K, V)>, } impl VecFromMapVisitor { - const NEW:Self=Self{marker:PhantomData}; + const NEW: Self = Self { + marker: PhantomData, + }; } impl<'de, K, V> Visitor<'de> for VecFromMapVisitor @@ -36,14 +33,14 @@ where where M: MapAccess<'de>, { - let cap=access.size_hint().unwrap_or(0); - let mut vec = Vec::<(K,V)>::with_capacity(cap); + let cap = access.size_hint().unwrap_or(0); + let mut vec = Vec::<(K, V)>::with_capacity(cap); while let Some(pair) = access.next_entry()? { vec.push(pair); } - Ok(VecFromMap{vec}) + Ok(VecFromMap { vec }) } } diff --git a/examples/1_trait_objects/interface/src/which_plugin.rs b/examples/1_trait_objects/interface/src/which_plugin.rs index 4cbdecc3..89dfb3b9 100644 --- a/examples/1_trait_objects/interface/src/which_plugin.rs +++ b/examples/1_trait_objects/interface/src/which_plugin.rs @@ -1,111 +1,110 @@ use crate::PluginId; use std::{ - fmt::{self,Display}, + fmt::{self, Display}, str::FromStr, }; use arrayvec::ArrayVec; use abi_stable::{ + std_types::{cow::BorrowingRCowStr, RCow, RString, RVec}, StableAbi, - std_types::{RCow,RVec,RString,cow::BorrowingRCowStr}, }; -use core_extensions::{StringExt,SelfOps}; - -use serde::{Serialize,Deserialize,Deserializer,Serializer}; +use core_extensions::{SelfOps, StringExt}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; /// A way to choose to which plugins one refers to when sending commands,and other operations. #[repr(u8)] -#[derive(Debug,Clone,PartialEq,Eq,StableAbi)] -pub enum WhichPlugin{ +#[derive(Debug, Clone, PartialEq, Eq, StableAbi)] +pub enum WhichPlugin { Id(PluginId), - First{ - named:RCow<'static,str>, - }, - Last{ - named:RCow<'static,str>, - }, - Every{ - named:RCow<'static,str>, - }, + First { named: RCow<'static, str> }, + Last { named: RCow<'static, str> }, + Every { named: RCow<'static, str> }, Many(RVec), } - -impl WhichPlugin{ +impl WhichPlugin { /// Converts this `WhichPlugin` to its json representation, /// generally used as a key in a json object. - pub fn to_key(&self)->RString{ - let mut buffer=RString::new(); + pub fn to_key(&self) -> RString { + let mut buffer = RString::new(); self.write_key(&mut buffer); buffer } /// Writes the value of this as a key usable in the application config. - pub fn write_key(&self,buf:&mut RString){ + pub fn write_key(&self, buf: &mut RString) { use std::fmt::Write; match self { - WhichPlugin::Id(id)=>write!(buf,"{}:{}",id.named,id.instance).drop_(), - WhichPlugin::First{named}=>write!(buf,"{}:first",named).drop_(), - WhichPlugin::Last{named}=>write!(buf,"{}:last",named).drop_(), - WhichPlugin::Every{named}=>write!(buf,"{}:every",named).drop_(), - WhichPlugin::Many(list)=>{ + WhichPlugin::Id(id) => write!(buf, "{}:{}", id.named, id.instance).drop_(), + WhichPlugin::First { named } => write!(buf, "{}:first", named).drop_(), + WhichPlugin::Last { named } => write!(buf, "{}:last", named).drop_(), + WhichPlugin::Every { named } => write!(buf, "{}:every", named).drop_(), + WhichPlugin::Many(list) => { for elem in list { elem.write_key(buf); buf.push(','); } - }, + } } } } +impl FromStr for WhichPlugin { + type Err = WhichPluginError; -impl FromStr for WhichPlugin{ - type Err=WhichPluginError; - - fn from_str(full_str:&str)->Result{ - let mut comma_sep=full_str.split(',').peekable(); - let first=comma_sep.next().unwrap_or("").piped(|s|Self::parse_single(s,full_str))?; + fn from_str(full_str: &str) -> Result { + let mut comma_sep = full_str.split(',').peekable(); + let first = comma_sep + .next() + .unwrap_or("") + .piped(|s| Self::parse_single(s, full_str))?; if comma_sep.peek().is_some() { - let mut list:RVec=vec![first].into(); - for s in comma_sep.filter(|s| !s.is_empty() ) { - list.push( Self::parse_single(s,full_str)? ); + let mut list: RVec = vec![first].into(); + for s in comma_sep.filter(|s| !s.is_empty()) { + list.push(Self::parse_single(s, full_str)?); } WhichPlugin::Many(list) - }else{ + } else { first - }.piped(Ok) + } + .piped(Ok) } } - -impl WhichPlugin{ - - fn parse_single(s:&str,full_str:&str)->Result{ - let splitted=s.splitn(2,':').map(|s|s.trim()).collect::>(); - let named=splitted.get(0) - .filter(|s| !s.is_empty() ) - .ok_or_else(|| WhichPluginError(full_str.into()) )? +impl WhichPlugin { + fn parse_single(s: &str, full_str: &str) -> Result { + let splitted = s + .splitn(2, ':') + .map(|s| s.trim()) + .collect::>(); + let named = splitted + .get(0) + .filter(|s| !s.is_empty()) + .ok_or_else(|| WhichPluginError(full_str.into()))? .to_string() - .into_::>(); - let selector=splitted.get(1).map_or("",|x|*x); + .into_::>(); + let selector = splitted.get(1).map_or("", |x| *x); match selector { - "first"=>return Ok(WhichPlugin::First{named}), - ""|"last"=>return Ok(WhichPlugin::Last{named}), - "all"|"every"=>return Ok(WhichPlugin::Every{named}), - _=>(), + "first" => return Ok(WhichPlugin::First { named }), + "" | "last" => return Ok(WhichPlugin::Last { named }), + "all" | "every" => return Ok(WhichPlugin::Every { named }), + _ => (), } - let instance=selector.parse::().map_err(|_| WhichPluginError(full_str.into()) )?; - Ok(WhichPlugin::Id(PluginId{named,instance})) + let instance = selector + .parse::() + .map_err(|_| WhichPluginError(full_str.into()))?; + Ok(WhichPlugin::Id(PluginId { named, instance })) } - pub const FMT_MSG:&'static str=r##" + pub const FMT_MSG: &'static str = r##" "plugin name": refers to the last plugin named "plugin name". @@ -135,11 +134,9 @@ Plugin names: "##; - } - -impl<'de> Deserialize<'de> for WhichPlugin{ +impl<'de> Deserialize<'de> for WhichPlugin { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, @@ -152,8 +149,7 @@ impl<'de> Deserialize<'de> for WhichPlugin{ } } - -impl Serialize for WhichPlugin{ +impl Serialize for WhichPlugin { fn serialize(&self, serializer: S) -> Result where S: Serializer, @@ -162,17 +158,14 @@ impl Serialize for WhichPlugin{ } } - /////////////////////////////////////// - #[repr(transparent)] -#[derive(Debug,Clone,StableAbi)] +#[derive(Debug, Clone, StableAbi)] pub struct WhichPluginError(RString); - -impl Display for WhichPluginError{ - fn fmt(&self,f:&mut fmt::Formatter)->fmt::Result{ +impl Display for WhichPluginError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!( f, "Could not parse this as a `WhichPlugin`:\n\t'{}'\nExpected format:\n{}\n", @@ -182,80 +175,90 @@ impl Display for WhichPluginError{ } } - #[cfg(test)] -mod tests{ +mod tests { use super::*; - fn new_str_expected()->Vec<(&'static str,WhichPlugin)>{ + fn new_str_expected() -> Vec<(&'static str, WhichPlugin)> { vec![ ( "plugin name", - WhichPlugin::Last{named:"plugin name".into()} + WhichPlugin::Last { + named: "plugin name".into(), + }, ), ( "plugin name:10", - WhichPlugin::Id(PluginId{ - named:"plugin name".into(), - instance:10, - }) + WhichPlugin::Id(PluginId { + named: "plugin name".into(), + instance: 10, + }), ), ( "plugin name:first", - WhichPlugin::First{named:"plugin name".into()} + WhichPlugin::First { + named: "plugin name".into(), + }, ), ( "plugin name:last", - WhichPlugin::Last{named:"plugin name".into()} + WhichPlugin::Last { + named: "plugin name".into(), + }, ), ( "plugin name:every", - WhichPlugin::Every{named:"plugin name".into()} + WhichPlugin::Every { + named: "plugin name".into(), + }, ), ( "plugin name 1,plugin name 2:first,plugin name 3:every", - WhichPlugin::Many(vec![ - WhichPlugin::Last{named:"plugin name 1".into()}, - WhichPlugin::First{named:"plugin name 2".into()}, - WhichPlugin::Every{named:"plugin name 3".into()}, - ].into()) + WhichPlugin::Many( + vec![ + WhichPlugin::Last { + named: "plugin name 1".into(), + }, + WhichPlugin::First { + named: "plugin name 2".into(), + }, + WhichPlugin::Every { + named: "plugin name 3".into(), + }, + ] + .into(), + ), ), ] } #[test] - fn parses_correctly(){ - let str_expected=new_str_expected(); + fn parses_correctly() { + let str_expected = new_str_expected(); - for (str_,expected) in str_expected { - let parsed=str_.parse::().unwrap(); - assert_eq!(parsed,expected); + for (str_, expected) in str_expected { + let parsed = str_.parse::().unwrap(); + assert_eq!(parsed, expected); - assert_eq!( - parsed.to_key().parse::().unwrap(), - expected, - ); + assert_eq!(parsed.to_key().parse::().unwrap(), expected,); } } - #[test] - fn serde_(){ - let str_expected=new_str_expected(); - - for (_,elem) in str_expected { - let str_=serde_json::to_string(&elem).unwrap(); - let other:WhichPlugin=serde_json::from_str(&str_) - .unwrap_or_else(|e| panic!("{}",e) ); - assert_eq!(other,elem); + fn serde_() { + let str_expected = new_str_expected(); + + for (_, elem) in str_expected { + let str_ = serde_json::to_string(&elem).unwrap(); + let other: WhichPlugin = + serde_json::from_str(&str_).unwrap_or_else(|e| panic!("{}", e)); + assert_eq!(other, elem); } - } - #[test] - fn parses_incorrectly(){ - let list=vec![ + fn parses_incorrectly() { + let list = vec![ // An empty plugin name is invalid "", ":", @@ -269,4 +272,4 @@ mod tests{ str_.parse::().unwrap_err(); } } -} \ No newline at end of file +} diff --git a/examples/1_trait_objects/plugin_0/src/lib.rs b/examples/1_trait_objects/plugin_0/src/lib.rs index 5c8c7eec..f4e3ac21 100644 --- a/examples/1_trait_objects/plugin_0/src/lib.rs +++ b/examples/1_trait_objects/plugin_0/src/lib.rs @@ -1,104 +1,80 @@ /*! This is an `implementation crate`, -It exports the root module(a struct of function pointers) required by the +It exports the root module(a struct of function pointers) required by the `example_0_interface`(the `interface crate`). */ -use std::{ - collections::HashSet, -}; +use std::collections::HashSet; use abi_stable::{ export_root_module, - sabi_extern_fn, external_types::crossbeam_channel::RSender, prefix_type::PrefixTypeTrait, + sabi_extern_fn, sabi_trait::prelude::TD_Opaque, - std_types::{RStr,RVec, RString,RResult,ROk}, + std_types::{ROk, RResult, RStr, RString, RVec}, }; use example_1_interface::{ - AsyncCommand, - ApplicationMut, - CommandDescription, - Error as AppError, - Plugin,PluginType,PluginId,PluginMod,PluginMod_Ref, - Plugin_TO, - utils::process_command, + utils::process_command, ApplicationMut, AsyncCommand, CommandDescription, Error as AppError, + Plugin, PluginId, PluginMod, PluginMod_Ref, PluginType, Plugin_TO, }; -use core_extensions::{SelfOps,StringExt}; +use core_extensions::{SelfOps, StringExt}; -use serde::{Serialize,Deserialize}; +use serde::{Deserialize, Serialize}; /////////////////////////////////////////////////////////////////////////////////// - /// Exports the root module of this library. /// /// This code isn't run until the layout of the type it returns is checked. #[export_root_module] -fn instantiate_root_module()->PluginMod_Ref{ - PluginMod { - new, - }.leak_into_prefix() +fn instantiate_root_module() -> PluginMod_Ref { + PluginMod { new }.leak_into_prefix() } - ////////////////////////////////////////////////////////////////////////////////////// - /// Instantiates the plugin. #[sabi_extern_fn] -pub fn new(_sender:RSender,plugin_id:PluginId) -> RResult { - let this=TextMunging{ - plugin_id, - }; - ROk(Plugin_TO::from_value(this,TD_Opaque)) +pub fn new(_sender: RSender, plugin_id: PluginId) -> RResult { + let this = TextMunging { plugin_id }; + ROk(Plugin_TO::from_value(this, TD_Opaque)) } - ////////////////////////////////////////////////////////////////////////////////////// - - -#[derive(Debug,Serialize,Deserialize)] -pub enum ProcessTextCmd{ +#[derive(Debug, Serialize, Deserialize)] +pub enum ProcessTextCmd { Rot13(String), - CapitalizeWords{ - text:String, - words:HashSet + CapitalizeWords { + text: String, + words: HashSet, }, } -#[derive(Debug,Serialize,Deserialize)] -pub enum ReturnValue{ +#[derive(Debug, Serialize, Deserialize)] +pub enum ReturnValue { Rot13(String), CapitalizeWords(String), } - - - - ////////////////////////////////////////////////////////////////////////////////////// - fn run_command_inner( - _this:&mut TextMunging, - command:ProcessTextCmd, - _app:ApplicationMut<'_>, -)->Result{ + _this: &mut TextMunging, + command: ProcessTextCmd, + _app: ApplicationMut<'_>, +) -> Result { match command { - ProcessTextCmd::Rot13(text)=>{ - pub fn rot13(this:char)-> char{ - match this{ - v@'a'..='z'=> - ((((v as u8 - b'a')+13)%26)+b'a')as char, - v@'A'..='Z'=> - ((((v as u8 - b'A')+13)%26)+b'A')as char, - v=>v + ProcessTextCmd::Rot13(text) => { + pub fn rot13(this: char) -> char { + match this { + v @ 'a'..='z' => ((((v as u8 - b'a') + 13) % 26) + b'a') as char, + v @ 'A'..='Z' => ((((v as u8 - b'A') + 13) % 26) + b'A') as char, + v => v, } } text.chars() @@ -106,51 +82,50 @@ fn run_command_inner( .collect::() .piped(ReturnValue::Rot13) } - ProcessTextCmd::CapitalizeWords{text,words}=>{ - let mut buffer=String::with_capacity(10); + ProcessTextCmd::CapitalizeWords { text, words } => { + let mut buffer = String::with_capacity(10); - for kv in text.split_while(|c|c.is_alphabetic()) { - let str_=kv.str; - let is_a_word=kv.key; + for kv in text.split_while(|c| c.is_alphabetic()) { + let str_ = kv.str; + let is_a_word = kv.key; if is_a_word && words.contains(str_) { buffer.extend(str_.chars().flat_map(char::to_uppercase)); - }else{ + } else { buffer.push_str(str_); } } ReturnValue::CapitalizeWords(buffer) } - }.piped(Ok) + } + .piped(Ok) } ////////////////////////////////////////////////////////////////////////////////////// - -struct TextMunging{ - plugin_id:PluginId, +struct TextMunging { + plugin_id: PluginId, } - impl Plugin for TextMunging { fn json_command( &mut self, command: RStr<'_>, - app:ApplicationMut<'_>, - )->RResult{ - process_command(self,command,|this,command:ProcessTextCmd|{ - run_command_inner(this,command,app) + app: ApplicationMut<'_>, + ) -> RResult { + process_command(self, command, |this, command: ProcessTextCmd| { + run_command_inner(this, command, app) }) } - fn plugin_id(&self)->&PluginId{ + fn plugin_id(&self) -> &PluginId { &self.plugin_id } - fn list_commands(&self)->RVec{ + fn list_commands(&self) -> RVec { vec![ CommandDescription::from_literals( "Rot13", - "Uses the rot13 algorithm to hide spoilers in plain text." + "Uses the rot13 algorithm to hide spoilers in plain text.", ), CommandDescription::from_literals( "CapitalizeWords", @@ -159,9 +134,9 @@ impl Plugin for TextMunging { Command parans:\n\ {\"text\":\"text here\",words:[\"word0\",\"word1\"]}", ), - ].into() + ] + .into() } - fn close(self,_app:ApplicationMut<'_>){} + fn close(self, _app: ApplicationMut<'_>) {} } - diff --git a/examples/1_trait_objects/plugin_1/src/lib.rs b/examples/1_trait_objects/plugin_1/src/lib.rs index 7f48bf8c..350d9d56 100644 --- a/examples/1_trait_objects/plugin_1/src/lib.rs +++ b/examples/1_trait_objects/plugin_1/src/lib.rs @@ -1,152 +1,127 @@ /*! This is an `implementation crate`, -It exports the root module(a struct of function pointers) required by the +It exports the root module(a struct of function pointers) required by the `example_0_interface`(the `interface crate`). */ use abi_stable::{ export_root_module, - sabi_extern_fn, external_types::crossbeam_channel::RSender, prefix_type::PrefixTypeTrait, + sabi_extern_fn, sabi_trait::prelude::TD_Opaque, - std_types::{RStr,RVec, RString,RResult,ROk}, + std_types::{ROk, RResult, RStr, RString, RVec}, }; use example_1_interface::{ - AsyncCommand, - ApplicationMut, - CommandDescription, - Error as AppError, - Plugin,PluginType,PluginId,PluginMod,PluginMod_Ref, - Plugin_TO, - utils::process_command, - WhichPlugin, + utils::process_command, ApplicationMut, AsyncCommand, CommandDescription, Error as AppError, + Plugin, PluginId, PluginMod, PluginMod_Ref, PluginType, Plugin_TO, WhichPlugin, }; - use core_extensions::SelfOps; -use serde::{Serialize,Deserialize}; +use serde::{Deserialize, Serialize}; use serde_json::value::Value; /////////////////////////////////////////////////////////////////////////////////// - /// Exports the root module of this library. /// /// This code isn't run until the layout of the type it returns is checked. #[export_root_module] -fn instantiate_root_module()->PluginMod_Ref{ - PluginMod { - new, - }.leak_into_prefix() +fn instantiate_root_module() -> PluginMod_Ref { + PluginMod { new }.leak_into_prefix() } - ////////////////////////////////////////////////////////////////////////////////////// - #[sabi_extern_fn] -pub fn new(_sender:RSender,plugin_id:PluginId) -> RResult { - let this=CommandUtils{ - plugin_id, - }; - ROk(Plugin_TO::from_value(this,TD_Opaque)) +pub fn new(_sender: RSender, plugin_id: PluginId) -> RResult { + let this = CommandUtils { plugin_id }; + ROk(Plugin_TO::from_value(this, TD_Opaque)) } - ////////////////////////////////////////////////////////////////////////////////////// - - -#[derive(Debug,Serialize,Deserialize)] -pub enum UtilCmd{ - Repeat{ - how_much:usize, - plugin:WhichPlugin, - command:Value, +#[derive(Debug, Serialize, Deserialize)] +pub enum UtilCmd { + Repeat { + how_much: usize, + plugin: WhichPlugin, + command: Value, }, - Batch{ - plugin:WhichPlugin, - commands:Vec, + Batch { + plugin: WhichPlugin, + commands: Vec, }, } -#[derive(Debug,Serialize,Deserialize)] -pub enum ReturnValue{ +#[derive(Debug, Serialize, Deserialize)] +pub enum ReturnValue { Repeat, Batch, } - - - - ////////////////////////////////////////////////////////////////////////////////////// - fn run_command_inner( - this:&mut CommandUtils, - command:UtilCmd, - mut app:ApplicationMut<'_>, -)->Result{ + this: &mut CommandUtils, + command: UtilCmd, + mut app: ApplicationMut<'_>, +) -> Result { match command { - UtilCmd::Repeat{how_much,plugin,command}=>{ - let s=serde_json::to_string(&command).unwrap(); + UtilCmd::Repeat { + how_much, + plugin, + command, + } => { + let s = serde_json::to_string(&command).unwrap(); for _ in 0..how_much { - app.send_command_to_plugin( - this.plugin_id(), - plugin.clone(), - s.clone().into(), - ).into_result()?; + app.send_command_to_plugin(this.plugin_id(), plugin.clone(), s.clone().into()) + .into_result()?; } ReturnValue::Repeat } - UtilCmd::Batch{plugin,commands}=>{ + UtilCmd::Batch { plugin, commands } => { for command in commands { - let s=serde_json::to_string(&command).unwrap(); - app.send_command_to_plugin( - this.plugin_id(), - plugin.clone(), - s.into(), - ).into_result()?; + let s = serde_json::to_string(&command).unwrap(); + app.send_command_to_plugin(this.plugin_id(), plugin.clone(), s.into()) + .into_result()?; } ReturnValue::Batch } - }.piped(Ok) + } + .piped(Ok) } ////////////////////////////////////////////////////////////////////////////////////// - -struct CommandUtils{ - plugin_id:PluginId, +struct CommandUtils { + plugin_id: PluginId, } - impl Plugin for CommandUtils { fn json_command( &mut self, command: RStr<'_>, - app:ApplicationMut<'_>, - )->RResult{ - process_command(self,command,|this,command|{ - run_command_inner(this,command,app) + app: ApplicationMut<'_>, + ) -> RResult { + process_command(self, command, |this, command| { + run_command_inner(this, command, app) }) } - fn plugin_id(&self)->&PluginId{ + fn plugin_id(&self) -> &PluginId { &self.plugin_id } - fn list_commands(&self)->RVec{ + fn list_commands(&self) -> RVec { vec![ CommandDescription::from_literals( "Repeat", -"\ + "\ Sends a command to a plugin N times. Command params: @@ -155,11 +130,11 @@ Command params: \"plugin\":\"plugin:last\", \"command\":{ ... some command ... } } -" +", ), CommandDescription::from_literals( "Batch", -"\ + "\ Sends a sequence of commands to a plugin. Command params: @@ -172,9 +147,9 @@ Command params: ] }", ), - ].into() + ] + .into() } - fn close(self,_app:ApplicationMut<'_>){} + fn close(self, _app: ApplicationMut<'_>) {} } - diff --git a/examples/2_nonexhaustive/implementation/src/lib.rs b/examples/2_nonexhaustive/implementation/src/lib.rs index 58279172..46b1f697 100644 --- a/examples/2_nonexhaustive/implementation/src/lib.rs +++ b/examples/2_nonexhaustive/implementation/src/lib.rs @@ -1,203 +1,197 @@ -use std::{ - collections::HashMap, - mem, -}; +use std::{collections::HashMap, mem}; use abi_stable::{ + export_root_module, external_types::RawValueBox, - nonexhaustive_enum::{NonExhaustiveFor,NonExhaustive}, + nonexhaustive_enum::{NonExhaustive, NonExhaustiveFor}, prefix_type::PrefixTypeTrait, + rtry, sabi_extern_fn, sabi_trait::prelude::TD_Opaque, - std_types::{RBox,RBoxError,RResult,RStr,RString,ROk,RErr,RVec}, - export_root_module, - sabi_extern_fn, + std_types::{RBox, RBoxError, RErr, ROk, RResult, RStr, RString, RVec}, traits::IntoReprC, - rtry, }; use core_extensions::SelfOps; use example_2_interface::{ - Cents,Command,Command_NE,Error,ItemId,ReturnVal,ReturnVal_NE,Shop,Shop_TO,ShopMod_Ref,ShopMod, - ParamCreateItem,RetRenameItem, + Cents, Command, Command_NE, Error, ItemId, ParamCreateItem, RetRenameItem, ReturnVal, + ReturnVal_NE, Shop, ShopMod, ShopMod_Ref, Shop_TO, }; - #[export_root_module] -fn instantiate_root_module()->ShopMod_Ref{ +fn instantiate_root_module() -> ShopMod_Ref { ShopMod { new, deserialize_command, deserialize_ret_val, serialize_command, serialize_ret_val, - }.leak_into_prefix() + } + .leak_into_prefix() } - #[sabi_extern_fn] -pub fn new()->Shop_TO<'static,RBox<()>>{ +pub fn new() -> Shop_TO<'static, RBox<()>> { Shop_TO::from_value( - ShopState{ - items_map:HashMap::default(), - items:Vec::new(), + ShopState { + items_map: HashMap::default(), + items: Vec::new(), }, - TD_Opaque + TD_Opaque, ) } - - -#[derive(Debug,Clone)] -struct ShopState{ - items_map:HashMap, - items:Vec +#[derive(Debug, Clone)] +struct ShopState { + items_map: HashMap, + items: Vec, } -#[derive(Debug,Clone)] -struct Item{ - name:RString, - id:ItemId, - price:Cents, - count:u32, +#[derive(Debug, Clone)] +struct Item { + name: RString, + id: ItemId, + price: Cents, + count: u32, } - - -impl Shop for ShopState{ - fn run_command( - &mut self, - cmd:Command_NE, - )->RResult>{ +impl Shop for ShopState { + fn run_command(&mut self, cmd: Command_NE) -> RResult> { use std::collections::hash_map::Entry; match cmd.into_enum() { - Ok(Command::CreateItem(inner_cmd))=>{ - let ParamCreateItem{name,initial_count:count,price}= - RBox::into_inner(inner_cmd); + Ok(Command::CreateItem(inner_cmd)) => { + let ParamCreateItem { + name, + initial_count: count, + price, + } = RBox::into_inner(inner_cmd); match self.items_map.entry(name.clone()) { - Entry::Occupied(entry)=>{ - let id=ItemId{id:*entry.get()}; - return RErr(NonExhaustive::new(Error::ItemAlreadyExists{id,name})) + Entry::Occupied(entry) => { + let id = ItemId { id: *entry.get() }; + return RErr(NonExhaustive::new(Error::ItemAlreadyExists { id, name })); } - Entry::Vacant(entry)=>{ - let id=ItemId{id:self.items.len()}; + Entry::Vacant(entry) => { + let id = ItemId { + id: self.items.len(), + }; entry.insert(self.items.len()); - self.items.push(Item{name,id,price,count}); - ReturnVal::CreateItem{count,id} + self.items.push(Item { + name, + id, + price, + count, + }); + ReturnVal::CreateItem { count, id } } } } - Ok(Command::DeleteItem{id})=>{ + Ok(Command::DeleteItem { id }) => { if id.id < self.items.len() { self.items.remove(id.id); - ReturnVal::DeleteItem{id} - }else{ - return RErr(NonExhaustive::new(Error::ItemIdNotFound{id})); + ReturnVal::DeleteItem { id } + } else { + return RErr(NonExhaustive::new(Error::ItemIdNotFound { id })); } } - Ok(Command::AddItem{id,count})=>{ - match self.items.get_mut(id.id) { - Some(item) => { - item.count+=count; - ReturnVal::AddItem{remaining:item.count,id} - } - None => { - return RErr(NonExhaustive::new(Error::ItemIdNotFound{id})); + Ok(Command::AddItem { id, count }) => match self.items.get_mut(id.id) { + Some(item) => { + item.count += count; + ReturnVal::AddItem { + remaining: item.count, + id, } } - } - Ok(Command::RemoveItem{id,count})=>{ - match self.items.get_mut(id.id) { - Some(item) => { - let prev_count=item.count; - item.count=item.count.saturating_sub(count); - ReturnVal::RemoveItem{ - removed:prev_count-item.count, - remaining:item.count, - id - } - } - None => { - return RErr(NonExhaustive::new(Error::ItemIdNotFound{id})); - } + None => { + return RErr(NonExhaustive::new(Error::ItemIdNotFound { id })); } - } - Ok(Command::RenameItem{id,new_name})=>{ - match self.items.get_mut(id.id) { - Some(item) => { - let old_name=mem::replace(&mut item.name,new_name.clone()); - self.items_map.remove(&old_name); - self.items_map.insert(new_name.clone(),id.id); - RetRenameItem{id,old_name,new_name} - .piped(RBox::new) - .piped(ReturnVal::RenameItem) + }, + Ok(Command::RemoveItem { id, count }) => match self.items.get_mut(id.id) { + Some(item) => { + let prev_count = item.count; + item.count = item.count.saturating_sub(count); + ReturnVal::RemoveItem { + removed: prev_count - item.count, + remaining: item.count, + id, } - None => { - return RErr(NonExhaustive::new(Error::ItemIdNotFound{id})); + } + None => { + return RErr(NonExhaustive::new(Error::ItemIdNotFound { id })); + } + }, + Ok(Command::RenameItem { id, new_name }) => match self.items.get_mut(id.id) { + Some(item) => { + let old_name = mem::replace(&mut item.name, new_name.clone()); + self.items_map.remove(&old_name); + self.items_map.insert(new_name.clone(), id.id); + RetRenameItem { + id, + old_name, + new_name, } + .piped(RBox::new) + .piped(ReturnVal::RenameItem) } - } - Ok(Command::Many{list})=>{ - let mut ret=RVec::with_capacity(list.len()); + None => { + return RErr(NonExhaustive::new(Error::ItemIdNotFound { id })); + } + }, + Ok(Command::Many { list }) => { + let mut ret = RVec::with_capacity(list.len()); for elem in list { - let ret_cmd=rtry!(self.run_command(elem)); + let ret_cmd = rtry!(self.run_command(elem)); ret.push(ret_cmd); } - ReturnVal::Many{list:ret} + ReturnVal::Many { list: ret } } - Ok(x)=>{ - return - Error::InvalidCommand{ - cmd:RBox::new(NonExhaustive::new(x)) - }.piped(NonExhaustive::new) - .piped(RErr); + Ok(x) => { + return Error::InvalidCommand { + cmd: RBox::new(NonExhaustive::new(x)), + } + .piped(NonExhaustive::new) + .piped(RErr); } - Err(e)=>{ - return - Error::InvalidCommand{ - cmd:RBox::new(e.into_inner()) - }.piped(NonExhaustive::new) - .piped(RErr); + Err(e) => { + return Error::InvalidCommand { + cmd: RBox::new(e.into_inner()), + } + .piped(NonExhaustive::new) + .piped(RErr); } - }.piped(NonExhaustive::new) - .piped(ROk) + } + .piped(NonExhaustive::new) + .piped(ROk) } } - - #[sabi_extern_fn] -fn deserialize_command(s:RStr<'_>)->RResult{ - deserialize_json::(s) - .map(NonExhaustiveFor::new) +fn deserialize_command(s: RStr<'_>) -> RResult { + deserialize_json::(s).map(NonExhaustiveFor::new) } #[sabi_extern_fn] -fn deserialize_ret_val(s:RStr<'_>)->RResult{ - deserialize_json::(s) - .map(NonExhaustiveFor::new) +fn deserialize_ret_val(s: RStr<'_>) -> RResult { + deserialize_json::(s).map(NonExhaustiveFor::new) } - #[sabi_extern_fn] -fn serialize_command(s:&Command_NE)->RResult{ - s.as_enum().into_c() +fn serialize_command(s: &Command_NE) -> RResult { + s.as_enum() + .into_c() .map_err(RBoxError::from) .and_then(serialize_json) } #[sabi_extern_fn] -fn serialize_ret_val(s:&ReturnVal_NE)->RResult{ - s.as_enum().into_c() +fn serialize_ret_val(s: &ReturnVal_NE) -> RResult { + s.as_enum() + .into_c() .map_err(RBoxError::from) .and_then(serialize_json) } - - - fn deserialize_json<'a, T>(s: RStr<'a>) -> RResult where T: serde::Deserialize<'a>, @@ -213,32 +207,30 @@ where T: serde::Serialize, { match serde_json::to_string::(&value) { - Ok(v)=>unsafe{ ROk(RawValueBox::from_string_unchecked(v)) } - Err(e)=>RErr(RBoxError::new(e)), + Ok(v) => unsafe { ROk(RawValueBox::from_string_unchecked(v)) }, + Err(e) => RErr(RBoxError::new(e)), } } - - #[cfg(test)] -mod tests{ +mod tests { use super::*; use abi_stable::library::RootModule; - fn remove_spaces(s:&str)->String{ - s.chars().filter(|x| !x.is_whitespace() ).collect() + fn remove_spaces(s: &str) -> String { + s.chars().filter(|x| !x.is_whitespace()).collect() } - fn setup(){ - let _=ShopMod_Ref::load_module_with(|| Ok::<_,()>(instantiate_root_module()) ); + fn setup() { + let _ = ShopMod_Ref::load_module_with(|| Ok::<_, ()>(instantiate_root_module())); } #[test] - fn serde_roundtrip_command(){ + fn serde_roundtrip_command() { setup(); - let json_a=r##"{ + let json_a = r##"{ "Many":{"list":[ {"CreateItem":{ "name":"Box of Void", @@ -256,17 +248,15 @@ mod tests{ ]} }"##; - let list=vec![ - json_a, - ]; + let list = vec![json_a]; for json0 in list.into_iter().map(remove_spaces) { - let obj0=serde_json::from_str::(&json0).unwrap(); - - let mut json1=serde_json::to_string(&obj0).unwrap(); - json1.retain(|x| !x.is_whitespace() ); + let obj0 = serde_json::from_str::(&json0).unwrap(); + + let mut json1 = serde_json::to_string(&obj0).unwrap(); + json1.retain(|x| !x.is_whitespace()); - let obj1=serde_json::from_str::(&json1).unwrap(); + let obj1 = serde_json::from_str::(&json1).unwrap(); assert_eq!(json0, json1); assert_eq!(obj0, obj1); @@ -274,10 +264,10 @@ mod tests{ } #[test] - fn serde_roundtrip_return_val(){ + fn serde_roundtrip_return_val() { setup(); - let json_a=r##"{ + let json_a = r##"{ "Many":{"list":[ {"CreateItem":{ "count":100, @@ -295,20 +285,18 @@ mod tests{ ]} }"##; - let list=vec![ - json_a, - ]; + let list = vec![json_a]; for json0 in list.into_iter().map(remove_spaces) { - let obj0=serde_json::from_str::(&json0).unwrap(); - - let mut json1=serde_json::to_string(&obj0).unwrap(); - json1.retain(|x| !x.is_whitespace() ); + let obj0 = serde_json::from_str::(&json0).unwrap(); - let obj1=serde_json::from_str::(&json1).unwrap(); + let mut json1 = serde_json::to_string(&obj0).unwrap(); + json1.retain(|x| !x.is_whitespace()); + + let obj1 = serde_json::from_str::(&json1).unwrap(); assert_eq!(json0, json1); assert_eq!(obj0, obj1); } } -} \ No newline at end of file +} diff --git a/examples/2_nonexhaustive/interface/src/lib.rs b/examples/2_nonexhaustive/interface/src/lib.rs index c09eaadb..f75b06f9 100644 --- a/examples/2_nonexhaustive/interface/src/lib.rs +++ b/examples/2_nonexhaustive/interface/src/lib.rs @@ -1,35 +1,32 @@ use abi_stable::{ - external_types::{RawValueRef,RawValueBox}, - nonexhaustive_enum::{NonExhaustiveFor,DeserializeEnum,SerializeEnum}, + declare_root_module_statics, + external_types::{RawValueBox, RawValueRef}, library::RootModule, - sabi_types::{VersionStrings}, - std_types::{RBox,RString,RResult,RStr,RBoxError,RVec}, - sabi_trait, + nonexhaustive_enum::{DeserializeEnum, NonExhaustiveFor, SerializeEnum}, + package_version_strings, sabi_trait, + sabi_types::VersionStrings, + std_types::{RBox, RBoxError, RResult, RStr, RString, RVec}, StableAbi, - package_version_strings, - declare_root_module_statics, }; -use serde::{Deserialize,Serialize}; - +use serde::{Deserialize, Serialize}; /// Represents United States cents. #[repr(transparent)] -#[derive(StableAbi,Debug,Clone,Copy,PartialEq,Deserialize,Serialize)] -pub struct Cents{ - pub cents:u64, +#[derive(StableAbi, Debug, Clone, Copy, PartialEq, Deserialize, Serialize)] +pub struct Cents { + pub cents: u64, } /// The unique identifier of an item that is/was in the catalogue, /// which are never reused for a different item. #[repr(transparent)] -#[derive(StableAbi,Debug,Clone,Copy,PartialEq,Deserialize,Serialize)] -pub struct ItemId{ +#[derive(StableAbi, Debug, Clone, Copy, PartialEq, Deserialize, Serialize)] +pub struct ItemId { #[doc(hidden)] - pub id:usize, + pub id: usize, } - /////////////////////////////////////////////////////////////////////////////// /** @@ -39,52 +36,51 @@ Every variant of this enum corresponds to a variant of `ReturnVal`. */ #[non_exhaustive] #[repr(u8)] -#[derive(StableAbi,Debug,Clone,PartialEq,Deserialize,Serialize)] +#[derive(StableAbi, Debug, Clone, PartialEq, Deserialize, Serialize)] #[sabi(kind(WithNonExhaustive( - size="[usize;8]", - traits(Send,Sync,Debug,Clone,PartialEq,Serialize,Deserialize), - assert_nonexhaustive="Command", + size = "[usize;8]", + traits(Send, Sync, Debug, Clone, PartialEq, Serialize, Deserialize), + assert_nonexhaustive = "Command", )))] -pub enum Command{ +pub enum Command { /** -`#[sabi(with_boxed_constructor)]` tells the `StableAbi` derive macro to -generate the `fn CreateItem_NE(ParamCreateItem)->ReturnVal_NE` associated function. - */ + `#[sabi(with_boxed_constructor)]` tells the `StableAbi` derive macro to + generate the `fn CreateItem_NE(ParamCreateItem)->ReturnVal_NE` associated function. + */ #[sabi(with_boxed_constructor)] CreateItem(RBox), - DeleteItem{ - id:ItemId, + DeleteItem { + id: ItemId, }, - AddItem{ - id:ItemId, - count:u32, + AddItem { + id: ItemId, + count: u32, }, - RemoveItem{ - id:ItemId, - count:u32, + RemoveItem { + id: ItemId, + count: u32, }, /// This variant was added in the 1.1 version of the library. - #[cfg(feature="v1_1")] - RenameItem{ - id:ItemId, - new_name:RString, + #[cfg(feature = "v1_1")] + RenameItem { + id: ItemId, + new_name: RString, }, /** -This variant was added in the 1.1 version of the library. + This variant was added in the 1.1 version of the library. -`#[sabi(with_constructor)]` tells the `StableAbi` derive macro to -generate the `fn Many_NE(RVec)->Command_NE` associated function. - */ - #[cfg(feature="v1_1")] + `#[sabi(with_constructor)]` tells the `StableAbi` derive macro to + generate the `fn Many_NE(RVec)->Command_NE` associated function. + */ + #[cfg(feature = "v1_1")] #[sabi(with_constructor)] - Many{ - list:RVec + Many { + list: RVec, }, } - /* //This was generated by the StableAbi derive macro on Command. pub type Command_NE= @@ -96,11 +92,11 @@ pub type Command_NE= */ #[repr(C)] -#[derive(StableAbi,Debug,Clone,PartialEq,Deserialize,Serialize)] -pub struct ParamCreateItem{ - pub name:RString, - pub initial_count:u32, - pub price:Cents, +#[derive(StableAbi, Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct ParamCreateItem { + pub name: RString, + pub initial_count: u32, + pub price: Cents, } /** @@ -113,9 +109,9 @@ because `trait()` was passed as a parameter to `#[sabi(kind(WithNonExhaustive( . impl SerializeEnum for Command_Interface { /// The intermediate type the enum is converted into with `SerializeEnum::serialize_enum`, /// and then serialized. - type Proxy=RawValueBox; + type Proxy = RawValueBox; - fn serialize_enum(this:&Command_NE) -> Result{ + fn serialize_enum(this: &Command_NE) -> Result { ShopMod_Ref::get_module().unwrap().serialize_command()(this).into_result() } } @@ -123,66 +119,60 @@ impl SerializeEnum for Command_Interface { /** This specifies how `Command_NE` is deserialized. */ -impl<'a> DeserializeEnum<'a,Command_NE> for Command_Interface{ +impl<'a> DeserializeEnum<'a, Command_NE> for Command_Interface { /// The intermediate type that is deserialized, /// and then converted to the enum with `DeserializeEnum::deserialize_enum`. - type Proxy=RawValueRef<'a>; + type Proxy = RawValueRef<'a>; - fn deserialize_enum(s: RawValueRef<'a>) -> Result{ + fn deserialize_enum(s: RawValueRef<'a>) -> Result { ShopMod_Ref::get_module().unwrap().deserialize_command()(s.get_rstr()).into_result() } } - #[test] -#[cfg(feature="v1_1")] -fn examples_of_constructing_a_command(){ +#[cfg(feature = "v1_1")] +fn examples_of_constructing_a_command() { use abi_stable::nonexhaustive_enum::NonExhaustive; - let id=ItemId{id:0}; - + let id = ItemId { id: 0 }; // Constructing a Command::CreateItem wrapped in NonExhaustive // using the constructor generated by using #[sabi(with_boxed_constructor)] on the variant. assert_eq!( - Command::CreateItem_NE(ParamCreateItem{ - name:"foo".into(), - initial_count:1, - price:Cents{cents:1}, - }), + Command::CreateItem_NE(ParamCreateItem { + name: "foo".into(), + initial_count: 1, + price: Cents { cents: 1 }, + }), { - let x=ParamCreateItem{ - name:"foo".into(), - initial_count:1, - price:Cents{cents:1}, + let x = ParamCreateItem { + name: "foo".into(), + initial_count: 1, + price: Cents { cents: 1 }, }; - let x=RBox::new(x); - let x=Command::CreateItem(x); + let x = RBox::new(x); + let x = Command::CreateItem(x); NonExhaustive::new(x) } ); - - // Constructing a Command::RemoveItem wrapped in NonExhaustive - // without using the constructors generated using + + // Constructing a Command::RemoveItem wrapped in NonExhaustive + // without using the constructors generated using // either #[sabi(with_constructor)] or #[sabi(with_boxed_constructor)], // since neither attribute was applied to the enum or the variant. { - let x=Command::RemoveItem{id,count:1}; - let _=NonExhaustive::new(x); + let x = Command::RemoveItem { id, count: 1 }; + let _ = NonExhaustive::new(x); } // Constructing a Command::Many wrapped in NonExhaustive // using the constructor genereated by using #[sabi(with_constructor)] on the variant - assert_eq!( - Command::Many_NE(RVec::new()), - { - let x=Command::Many{list:RVec::new()}; - NonExhaustive::new(x) - } - ); + assert_eq!(Command::Many_NE(RVec::new()), { + let x = Command::Many { list: RVec::new() }; + NonExhaustive::new(x) + }); } - /////////////////////////////////////////////////////////////////////////////// /** @@ -192,49 +182,49 @@ Every variant of this enum corresponds to a variant of `Command`. */ #[non_exhaustive] #[repr(u8)] -#[derive(StableAbi,Debug,Clone,PartialEq,Deserialize,Serialize)] +#[derive(StableAbi, Debug, Clone, PartialEq, Deserialize, Serialize)] #[sabi(kind(WithNonExhaustive( - size="[usize;6]", - interface="Command_Interface", - assert_nonexhaustive="ReturnVal", + size = "[usize;6]", + interface = "Command_Interface", + assert_nonexhaustive = "ReturnVal", )))] -pub enum ReturnVal{ - CreateItem{ - count:u32, - id:ItemId, +pub enum ReturnVal { + CreateItem { + count: u32, + id: ItemId, }, - DeleteItem{ - id:ItemId, + DeleteItem { + id: ItemId, }, - AddItem{ - remaining:u32, - id:ItemId, + AddItem { + remaining: u32, + id: ItemId, }, - RemoveItem{ - removed:u32, - remaining:u32, - id:ItemId, + RemoveItem { + removed: u32, + remaining: u32, + id: ItemId, }, /** -This variant was added in the 1.1 version of the library. + This variant was added in the 1.1 version of the library. -`#[sabi(with_boxed_constructor)]` tells the `StableAbi` derive macro to -generate the `fn RenameItem_NE(RetRenameItem)->ReturnVal_NE` associated function. - */ - #[cfg(feature="v1_1")] + `#[sabi(with_boxed_constructor)]` tells the `StableAbi` derive macro to + generate the `fn RenameItem_NE(RetRenameItem)->ReturnVal_NE` associated function. + */ + #[cfg(feature = "v1_1")] #[sabi(with_boxed_constructor)] RenameItem(RBox), /** -This variant was added in the 1.1 version of the library. + This variant was added in the 1.1 version of the library. -`#[sabi(with_constructor)]` tells the `StableAbi` derive macro to -generate the `fn Many_NE(RVec)->ReturnVal_NE` associated function. - */ - #[cfg(feature="v1_1")] + `#[sabi(with_constructor)]` tells the `StableAbi` derive macro to + generate the `fn Many_NE(RVec)->ReturnVal_NE` associated function. + */ + #[cfg(feature = "v1_1")] #[sabi(with_constructor)] - Many{ - list:RVec + Many { + list: RVec, }, } @@ -252,28 +242,28 @@ pub type ReturnVal_NE= A command to rename an item in the shop, which must be wrapped in `ReturnVal::RenameItem_NE` to pass to `Shop::run_command`. */ -#[cfg(feature="v1_1")] +#[cfg(feature = "v1_1")] #[repr(C)] -#[derive(StableAbi,Debug,Clone,PartialEq,Serialize,Deserialize)] -pub struct RetRenameItem{ - pub id:ItemId, - pub new_name:RString, - pub old_name:RString, +#[derive(StableAbi, Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct RetRenameItem { + pub id: ItemId, + pub new_name: RString, + pub old_name: RString, } /** This specifies how `ReturnVal_NE` is serialized. This is implemented on Command_Interface, -because `interface="Command_Interface"` was passed as a parameter to +because `interface="Command_Interface"` was passed as a parameter to `#[sabi(kind(WithNonExhaustive( ... )))]`. */ impl SerializeEnum for Command_Interface { /// The intermediate type the enum is converted into with `SerializeEnum::serialize_enum`, /// and then serialized. - type Proxy=RawValueBox; + type Proxy = RawValueBox; - fn serialize_enum(this:&ReturnVal_NE) -> Result{ + fn serialize_enum(this: &ReturnVal_NE) -> Result { ShopMod_Ref::get_module().unwrap().serialize_ret_val()(this).into_result() } } @@ -281,89 +271,82 @@ impl SerializeEnum for Command_Interface { /** This specifies how `ReturnVal_NE` is deserialized. */ -impl<'a> DeserializeEnum<'a,ReturnVal_NE> for Command_Interface{ +impl<'a> DeserializeEnum<'a, ReturnVal_NE> for Command_Interface { /// The intermediate type that is deserialized, /// and then converted to the enum with `DeserializeEnum::deserialize_enum`. - type Proxy=RawValueRef<'a>; + type Proxy = RawValueRef<'a>; - fn deserialize_enum(s: RawValueRef<'a>) -> Result{ + fn deserialize_enum(s: RawValueRef<'a>) -> Result { ShopMod_Ref::get_module().unwrap().deserialize_ret_val()(s.get_rstr()).into_result() } } - - - #[test] -#[cfg(feature="v1_1")] -fn examples_of_constructing_a_returnval(){ +#[cfg(feature = "v1_1")] +fn examples_of_constructing_a_returnval() { use abi_stable::nonexhaustive_enum::NonExhaustive; - let id=ItemId{id:0}; + let id = ItemId { id: 0 }; - // Constructing a ReturnVal::RemoveItem wrapped in NonExhaustive - // without using the constructors generated using + // Constructing a ReturnVal::RemoveItem wrapped in NonExhaustive + // without using the constructors generated using // either #[sabi(with_constructor)] or #[sabi(with_boxed_constructor)], // since neither attribute was applied to the enum or the variant. { - let x=ReturnVal::RemoveItem{removed:0,remaining:0,id}; - let _=NonExhaustive::new(x); + let x = ReturnVal::RemoveItem { + removed: 0, + remaining: 0, + id, + }; + let _ = NonExhaustive::new(x); } // Constructing a ReturnVal::RenameItem wrapped in NonExhaustive // using the constructor generated by using #[sabi(with_boxed_constructor)] on the variant assert_eq!( - ReturnVal::RenameItem_NE(RetRenameItem{ + ReturnVal::RenameItem_NE(RetRenameItem { id, - new_name:"foo".into(), - old_name:"bar".into(), - }), + new_name: "foo".into(), + old_name: "bar".into(), + }), { - let x=RetRenameItem{ + let x = RetRenameItem { id, - new_name:"foo".into(), - old_name:"bar".into(), + new_name: "foo".into(), + old_name: "bar".into(), }; - let x=RBox::new(x); - let x=ReturnVal::RenameItem(x); + let x = RBox::new(x); + let x = ReturnVal::RenameItem(x); NonExhaustive::new(x) } ); - + // Constructing a ReturnVal::Many wrapped in NonExhaustive // using the constructor genereated by using #[sabi(with_constructor)] on the variant - assert_eq!( - ReturnVal::Many_NE(RVec::new()), - { - let x=ReturnVal::Many{list:RVec::new()}; - NonExhaustive::new(x) - } - ); + assert_eq!(ReturnVal::Many_NE(RVec::new()), { + let x = ReturnVal::Many { list: RVec::new() }; + NonExhaustive::new(x) + }); } - /////////////////////////////////////////////////////////////////////////////// - #[non_exhaustive] #[repr(u8)] -#[derive(StableAbi,Debug,Clone,PartialEq)] -#[sabi(kind(WithNonExhaustive( - size="[usize;6]", - traits(Send,Sync,Debug,Clone,PartialEq), -)))] +#[derive(StableAbi, Debug, Clone, PartialEq)] +#[sabi(kind(WithNonExhaustive(size = "[usize;6]", traits(Send, Sync, Debug, Clone, PartialEq),)))] #[sabi(with_constructor)] -pub enum Error{ - ItemAlreadyExists{ - id:ItemId, - name:RString, +pub enum Error { + ItemAlreadyExists { + id: ItemId, + name: RString, }, - ItemIdNotFound{ - id:ItemId, + ItemIdNotFound { + id: ItemId, }, #[sabi(with_boxed_constructor)] - InvalidCommand{ - cmd:RBox, + InvalidCommand { + cmd: RBox, }, } @@ -372,42 +355,34 @@ pub enum Error{ // InvalidCommand overrides it with `#[sabi(with_boxed_constructor)]`, // which generates constructor functions for variants which wrap a pointer. #[test] -#[cfg(feature="v1_1")] -fn examples_of_constructing_an_error(){ +#[cfg(feature = "v1_1")] +fn examples_of_constructing_an_error() { use abi_stable::nonexhaustive_enum::NonExhaustive; - let id=ItemId{id:0}; + let id = ItemId { id: 0 }; - assert_eq!( - Error::ItemAlreadyExists_NE(id,"hello".into()), - { - let x=Error::ItemAlreadyExists{id,name:"hello".into()}; - NonExhaustive::new(x) - } - ); - - assert_eq!( - Error::ItemIdNotFound_NE(id), - { - let x=Error::ItemIdNotFound{id}; - NonExhaustive::new(x) - } - ); - - assert_eq!( - Error::InvalidCommand_NE(Command::__NonExhaustive_NE()), - { - let x=Command::__NonExhaustive; - let x=NonExhaustive::new(x); - let x=RBox::new(x); - let x=Error::InvalidCommand{cmd:x}; - NonExhaustive::new(x) - } - ); + assert_eq!(Error::ItemAlreadyExists_NE(id, "hello".into()), { + let x = Error::ItemAlreadyExists { + id, + name: "hello".into(), + }; + NonExhaustive::new(x) + }); + + assert_eq!(Error::ItemIdNotFound_NE(id), { + let x = Error::ItemIdNotFound { id }; + NonExhaustive::new(x) + }); + + assert_eq!(Error::InvalidCommand_NE(Command::__NonExhaustive_NE()), { + let x = Command::__NonExhaustive; + let x = NonExhaustive::new(x); + let x = RBox::new(x); + let x = Error::InvalidCommand { cmd: x }; + NonExhaustive::new(x) + }); } - - /** The root module of the `shop` dynamic library. @@ -415,76 +390,68 @@ To load this module, call ::load_from_directory(some_directory_path) */ #[repr(C)] -#[derive(StableAbi)] -#[sabi(kind(Prefix(prefix_ref="ShopMod_Ref")))] +#[derive(StableAbi)] +#[sabi(kind(Prefix(prefix_ref = "ShopMod_Ref")))] #[sabi(missing_field(panic))] pub struct ShopMod { /// Constructs the `Shop_TO` trait object. - pub new:extern "C" fn()->Shop_TO<'static,RBox<()>>, + pub new: extern "C" fn() -> Shop_TO<'static, RBox<()>>, /// Deserializes a `Command_NE`. - pub deserialize_command:extern "C" fn(s:RStr<'_>)->RResult, + pub deserialize_command: extern "C" fn(s: RStr<'_>) -> RResult, /// Deserializes a `ReturnVal_NE`. - pub deserialize_ret_val:extern "C" fn(s:RStr<'_>)->RResult, + pub deserialize_ret_val: extern "C" fn(s: RStr<'_>) -> RResult, /// Serializes a `Command_NE`. - pub serialize_command:extern "C" fn(&Command_NE)->RResult, + pub serialize_command: extern "C" fn(&Command_NE) -> RResult, -/** -Serializes a `ReturnVal_NE`. + /** + Serializes a `ReturnVal_NE`. -The `#[sabi(last_prefix_field)]` attribute here means that this is the last field in this struct -that was defined in the first compatible version of the library -(0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), -requiring new fields to always be added below preexisting ones. + The `#[sabi(last_prefix_field)]` attribute here means that this is the last field in this struct + that was defined in the first compatible version of the library + (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), + requiring new fields to always be added below preexisting ones. -The `#[sabi(last_prefix_field)]` attribute would stay on this field until the library -bumps its "major" version, -at which point it would be moved to the last field at the time. + The `#[sabi(last_prefix_field)]` attribute would stay on this field until the library + bumps its "major" version, + at which point it would be moved to the last field at the time. -*/ + */ #[sabi(last_prefix_field)] - pub serialize_ret_val:extern "C" fn(&ReturnVal_NE)->RResult, + pub serialize_ret_val: extern "C" fn(&ReturnVal_NE) -> RResult, } - impl RootModule for ShopMod_Ref { - declare_root_module_statics!{ShopMod_Ref} + declare_root_module_statics! {ShopMod_Ref} const BASE_NAME: &'static str = "shop"; const NAME: &'static str = "shop"; const VERSION_STRINGS: VersionStrings = package_version_strings!(); } - /** This represents a shop manager, which can be sent a growing list of commands with each version. */ #[sabi_trait] -pub trait Shop{ -/** -Runs the `cmd` command. +pub trait Shop { + /** + Runs the `cmd` command. -The `#[sabi(last_prefix_field)]` attribute here means that this is the last method -that was defined in the first compatible version of the library -(0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), -requiring new methods to always be added below preexisting ones. + The `#[sabi(last_prefix_field)]` attribute here means that this is the last method + that was defined in the first compatible version of the library + (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), + requiring new methods to always be added below preexisting ones. -The `#[sabi(last_prefix_field)]` attribute would stay on this method until the library -bumps its "major" version, -at which point it would be moved to the last method at the time. + The `#[sabi(last_prefix_field)]` attribute would stay on this method until the library + bumps its "major" version, + at which point it would be moved to the last method at the time. -*/ + */ #[sabi(last_prefix_field)] - fn run_command( - &mut self, - cmd:Command_NE, - ) -> RResult>; + fn run_command(&mut self, cmd: Command_NE) -> RResult>; } - - - diff --git a/examples/2_nonexhaustive/user/src/main.rs b/examples/2_nonexhaustive/user/src/main.rs index 91a39979..b9730b61 100644 --- a/examples/2_nonexhaustive/user/src/main.rs +++ b/examples/2_nonexhaustive/user/src/main.rs @@ -1,37 +1,33 @@ use std::path::PathBuf; use abi_stable::{ - std_types::{ROk,RErr}, library::{development_utils::compute_library_path, RootModule}, + std_types::{RErr, ROk}, }; -use example_2_interface::{ShopMod_Ref,Command_NE}; +use example_2_interface::{Command_NE, ShopMod_Ref}; - -fn main(){ +fn main() { let target: &std::path::Path = "../../../target/".as_ref(); - let library_path=compute_library_path::(target).unwrap(); + let library_path = compute_library_path::(target).unwrap(); - let mods=ShopMod_Ref::load_from_directory(&library_path) - .unwrap_or_else(|e| panic!("{}", e) ); + let mods = ShopMod_Ref::load_from_directory(&library_path).unwrap_or_else(|e| panic!("{}", e)); - let config_path=match std::env::args_os().nth(1) { - Some(os)=>PathBuf::from(os), - None=>{ - println!( - "Help:You can pass a configuration's path as a command-line argument." - ); + let config_path = match std::env::args_os().nth(1) { + Some(os) => PathBuf::from(os), + None => { + println!("Help:You can pass a configuration's path as a command-line argument."); PathBuf::from("./data/app_config.json") } }; - let file=match std::fs::read_to_string(&*config_path) { - Ok(x)=>x, - Err(e)=>{ + let file = match std::fs::read_to_string(&*config_path) { + Ok(x) => x, + Err(e) => { eprintln!( "Could not load the configuration file at:\n\ \t{}\n\ - Because of this error:\n{}\n", + Because of this error:\n{}\n", config_path.display(), e ); @@ -39,32 +35,30 @@ fn main(){ } }; - let command=match serde_json::from_str::(&file) { + let command = match serde_json::from_str::(&file) { Ok(x) => x, Err(e) => { eprintln!( "Could not parse the configuration file at:\n\ \t{}\n\ Because of this error:\n\ - {}\n", + {}\n", config_path.display(), e ); std::process::exit(1); - }, + } }; - let mut shop_trait_object=mods.new()(); + let mut shop_trait_object = mods.new()(); match shop_trait_object.run_command(command) { - ROk(ret_val)=>{ + ROk(ret_val) => { println!("Return value of running command:\n{:#?}\n", ret_val); } - RErr(e)=>{ - eprintln!("Error from running command:\n{:?}\n",e); + RErr(e) => { + eprintln!("Error from running command:\n{:?}\n", e); std::process::exit(1); } } } - - diff --git a/playground/src/main.rs b/playground/src/main.rs index 522e0602..7e4d4418 100644 --- a/playground/src/main.rs +++ b/playground/src/main.rs @@ -1,12 +1,10 @@ #[allow(unused_imports)] use abi_stable::{ - std_types::{RVec,RBox}, + std_types::{RBox, RVec}, StableAbi, }; #[allow(unused_imports)] use core_extensions::SelfOps; -fn main() { - -} +fn main() {} diff --git a/testing/0/impl_0/src/lib.rs b/testing/0/impl_0/src/lib.rs index 5bf01167..3b9e2009 100644 --- a/testing/0/impl_0/src/lib.rs +++ b/testing/0/impl_0/src/lib.rs @@ -3,47 +3,41 @@ This crate is where extra tests which don't belong in examples go. */ -use testing_interface_0::{ - TestingMod,TestingMod_Ref,ForTests,PrefixTypeMod0, -}; +use testing_interface_0::{ForTests, PrefixTypeMod0, TestingMod, TestingMod_Ref}; use abi_stable::{ - export_root_module, - extern_fn_panic_handling, + export_root_module, extern_fn_panic_handling, prefix_type::PrefixTypeTrait, - traits::{IntoReprC}, - std_types::{RStr,RBox,RVec,RArc, RString}, + std_types::{RArc, RBox, RStr, RString, RVec}, + traits::IntoReprC, }; #[allow(unused_imports)] -use core_extensions::{SelfOps}; +use core_extensions::SelfOps; /////////////////////////////////////////////////////////////////////////////////// - /// Exports the root module of this library. /// /// LibHeader is used to check that the layout of `TextOpsMod` in this dynamic library /// is compatible with the layout of it in the binary that loads this library. #[export_root_module] pub fn get_library() -> TestingMod_Ref { - TestingMod{ + TestingMod { greeter, for_tests, - prefix_types_tests:PrefixTypeMod0{ - field_a:123, - }.leak_into_prefix(), - }.leak_into_prefix() + prefix_types_tests: PrefixTypeMod0 { field_a: 123 }.leak_into_prefix(), + } + .leak_into_prefix() } - -pub extern "C" fn greeter(name:RStr<'_>){ - extern_fn_panic_handling!{ +pub extern "C" fn greeter(name: RStr<'_>) { + extern_fn_panic_handling! { println!("Hello, {}!", name); } } -pub extern "C" fn for_tests()->ForTests{ - extern_fn_panic_handling!{ +pub extern "C" fn for_tests() -> ForTests { + extern_fn_panic_handling! { let arc=RArc::new(RString::from("hello")); ::std::mem::forget(arc.clone()); let box_=RBox::new(10); @@ -55,10 +49,10 @@ pub extern "C" fn for_tests()->ForTests{ box_address:(&*box_) as *const _ as usize, box_, - + vec_address:vec_.as_ptr() as usize, vec_, - + string_address:string.as_ptr() as usize, string, } diff --git a/testing/0/interface_0/src/lib.rs b/testing/0/interface_0/src/lib.rs index 726b89e8..37b35d1a 100644 --- a/testing/0/interface_0/src/lib.rs +++ b/testing/0/interface_0/src/lib.rs @@ -12,34 +12,30 @@ and then all the modules inside of the library. */ - use abi_stable::{ - StableAbi, - package_version_strings, library::RootModule, + package_version_strings, sabi_types::VersionStrings, - std_types::{RBox, RStr, RString,RVec,RArc}, + std_types::{RArc, RBox, RStr, RString, RVec}, + StableAbi, }; - - impl RootModule for TestingMod_Ref { - abi_stable::declare_root_module_statics!{TestingMod_Ref} + abi_stable::declare_root_module_statics! {TestingMod_Ref} const BASE_NAME: &'static str = "testing"; const NAME: &'static str = "testing"; const VERSION_STRINGS: VersionStrings = package_version_strings!(); } - #[repr(C)] -#[derive(StableAbi)] -#[sabi(kind(Prefix(prefix_ref="TestingMod_Ref")))] +#[derive(StableAbi)] +#[sabi(kind(Prefix(prefix_ref = "TestingMod_Ref")))] #[sabi(missing_field(panic))] pub struct TestingMod { #[sabi(last_prefix_field)] - pub greeter:extern "C" fn(RStr<'_>), - pub for_tests:extern "C" fn()->ForTests, + pub greeter: extern "C" fn(RStr<'_>), + pub for_tests: extern "C" fn() -> ForTests, /// An module used in prefix-type tests. pub prefix_types_tests: PrefixTypeMod0_Ref, @@ -49,21 +45,20 @@ pub struct TestingMod { /// This type is used in tests between the interface and user crates. #[repr(C)] -#[derive(StableAbi)] -pub struct ForTests{ - pub arc:RArc, - pub arc_address:usize, - - pub box_:RBox, - pub box_address:usize, - - pub vec_:RVec>, - pub vec_address:usize, - - pub string:RString, - pub string_address:usize, -} +#[derive(StableAbi)] +pub struct ForTests { + pub arc: RArc, + pub arc_address: usize, + + pub box_: RBox, + pub box_address: usize, + pub vec_: RVec>, + pub vec_address: usize, + + pub string: RString, + pub string_address: usize, +} // Macro used to make sure that PrefixTypeMod0_Ref and PrefixTypeMod1_Ref // are changed in lockstep. @@ -72,12 +67,12 @@ macro_rules! declare_PrefixTypeMod { $(#[$attr:meta])* struct $struct_ident:ident; prefix_ref=$prefix:literal ; - + $(extra_fields=[ $($extra_fields:tt)* ])? ) => ( $(#[$attr])* #[repr(C)] - #[derive(StableAbi)] + #[derive(StableAbi)] #[sabi(kind(Prefix(prefix_ref=$prefix)))] #[sabi(missing_field(option))] pub struct $struct_ident { @@ -88,15 +83,14 @@ macro_rules! declare_PrefixTypeMod { ) } - -declare_PrefixTypeMod!{ +declare_PrefixTypeMod! { struct PrefixTypeMod0; prefix_ref="PrefixTypeMod0_Ref"; } -declare_PrefixTypeMod!{ +declare_PrefixTypeMod! { /** - This is unsafely converted from PrefixTypeMod0_Ref in tests to check that + This is unsafely converted from PrefixTypeMod0_Ref in tests to check that `prefix.field_a()==some_integer`, `prefix.field_b()==None`, `prefix.field_c()==None`. @@ -106,7 +100,7 @@ declare_PrefixTypeMod!{ */ struct PrefixTypeMod1; prefix_ref="PrefixTypeMod1_Ref"; - + extra_fields=[ pub field_b:u32, pub field_c:u32, @@ -114,4 +108,3 @@ declare_PrefixTypeMod!{ pub field_d:u32, ] } - diff --git a/testing/0/user_0/src/main.rs b/testing/0/user_0/src/main.rs index 71442264..4ebec9ab 100644 --- a/testing/0/user_0/src/main.rs +++ b/testing/0/user_0/src/main.rs @@ -1,33 +1,27 @@ -use std::{ - io, - sync::Arc, -}; - +use std::{io, sync::Arc}; use core_extensions::SelfOps; use abi_stable::{ - std_types::{RString,RVec,RArc,RBox}, library::{development_utils::compute_library_path, RootModule}, + std_types::{RArc, RBox, RString, RVec}, }; -use testing_interface_0::{TestingMod_Ref, PrefixTypeMod1_Ref}; +use testing_interface_0::{PrefixTypeMod1_Ref, TestingMod_Ref}; - -fn main()-> io::Result<()> { +fn main() -> io::Result<()> { let target: &std::path::Path = "../../../target/".as_ref(); - let library_path=compute_library_path::(target)?; + let library_path = compute_library_path::(target)?; + + let mods = + TestingMod_Ref::load_from_directory(&library_path).unwrap_or_else(|e| panic!("{}", e)); - let mods=TestingMod_Ref::load_from_directory(&library_path) - .unwrap_or_else(|e| panic!("{}", e) ); - run_dynamic_library_tests(mods); Ok(()) } - -/// This tests that a type coming from a dynamic library +/// This tests that a type coming from a dynamic library /// cannot be converted back to its std-library equivalent /// while reusing the heap allocation. /// @@ -36,58 +30,45 @@ fn main()-> io::Result<()> { /// /// There is no way that I am aware to check at compile-time what allocator /// the type is using,so this is the best I can do while staying safe. -pub fn run_dynamic_library_tests(mods: TestingMod_Ref){ +pub fn run_dynamic_library_tests(mods: TestingMod_Ref) { { - let hw=mods.prefix_types_tests(); - let hw=unsafe{ + let hw = mods.prefix_types_tests(); + let hw = unsafe { // This only works because I know that both structs have the same alignment, // if either struct alignment changed that conversion would be unsound. PrefixTypeMod1_Ref(hw.0.cast()) }; - assert_eq!(hw.field_a(),123); - assert_eq!(hw.field_b(),None); - assert_eq!(hw.field_c(),None); - let res=::std::panic::catch_unwind(||{ - let _=hw.field_d(); + assert_eq!(hw.field_a(), 123); + assert_eq!(hw.field_b(), None); + assert_eq!(hw.field_c(), None); + let res = ::std::panic::catch_unwind(|| { + let _ = hw.field_d(); }); - assert!(res.is_err(),"value:{:#?}",res); + assert!(res.is_err(), "value:{:#?}", res); } - let val=mods.for_tests()(); + let val = mods.for_tests()(); { - let arc_std=val.arc.piped(RArc::into_arc); - assert_eq!(Arc::strong_count(&arc_std),1); - assert_ne!( - (&*arc_std) as *const _ as usize, - val.arc_address - ); + let arc_std = val.arc.piped(RArc::into_arc); + assert_eq!(Arc::strong_count(&arc_std), 1); + assert_ne!((&*arc_std) as *const _ as usize, val.arc_address); } { - let box_std=val.box_.piped(RBox::into_box); - assert_ne!( - (&*box_std) as *const _ as usize, - val.box_address - ); + let box_std = val.box_.piped(RBox::into_box); + assert_ne!((&*box_std) as *const _ as usize, val.box_address); } { - let vec_std=val.vec_.piped(RVec::into_vec); - assert_ne!( - vec_std.as_ptr() as usize, - val.vec_address - ); + let vec_std = val.vec_.piped(RVec::into_vec); + assert_ne!(vec_std.as_ptr() as usize, val.vec_address); } { - let string_std=val.string.piped(RString::into_string); - assert_ne!( - string_std.as_ptr() as usize, - val.string_address - ); + let string_std = val.string.piped(RString::into_string); + assert_ne!(string_std.as_ptr() as usize, val.string_address); } - + println!(); println!(".-------------------------."); println!("| tests succeeded! |"); println!("'-------------------------'"); } - diff --git a/testing/1 - loading errors/impl_1/src/lib.rs b/testing/1 - loading errors/impl_1/src/lib.rs index f360f8c8..819fda4a 100644 --- a/testing/1 - loading errors/impl_1/src/lib.rs +++ b/testing/1 - loading errors/impl_1/src/lib.rs @@ -3,17 +3,12 @@ This crate is where extra tests which don't belong in examples go. */ -use testing_interface_1::{ReturnWhat, TestingMod,TestingMod_Ref, get_env_vars}; +use testing_interface_1::{get_env_vars, ReturnWhat, TestingMod, TestingMod_Ref}; -use abi_stable::{ - export_root_module, - prefix_type::PrefixTypeTrait, - std_types::RBoxError, -}; +use abi_stable::{export_root_module, prefix_type::PrefixTypeTrait, std_types::RBoxError}; /////////////////////////////////////////////////////////////////////////////////// - /// Exports the root module of this library. /// /// LibHeader is used to check that the layout of `TextOpsMod` in this dynamic library @@ -23,21 +18,14 @@ pub fn get_library() -> Result { let envars = get_env_vars(); match envars.return_what { - ReturnWhat::Ok=>{ - let ret = TestingMod{ - a: 5, - b: 8, - c: 13, - }.leak_into_prefix(); + ReturnWhat::Ok => { + let ret = TestingMod { a: 5, b: 8, c: 13 }.leak_into_prefix(); Ok(ret) } - ReturnWhat::Error=>{ - Err(RBoxError::from_fmt("What the ....?")) - } - ReturnWhat::Panic=>{ + ReturnWhat::Error => Err(RBoxError::from_fmt("What the ....?")), + ReturnWhat::Panic => { panic!() } } } - diff --git a/testing/1 - loading errors/interface_1/src/lib.rs b/testing/1 - loading errors/interface_1/src/lib.rs index dee9e856..0ede6eed 100644 --- a/testing/1 - loading errors/interface_1/src/lib.rs +++ b/testing/1 - loading errors/interface_1/src/lib.rs @@ -6,28 +6,21 @@ where all publically available modules(structs of function pointers) and types a These crate test a few of the errors that are returned when loading dynamic libraries */ - use abi_stable::{ - StableAbi, - package_version_strings, - library::RootModule, - sabi_types::VersionStrings, + library::RootModule, package_version_strings, sabi_types::VersionStrings, StableAbi, }; - - impl RootModule for TestingMod_Ref { - abi_stable::declare_root_module_statics!{TestingMod_Ref} + abi_stable::declare_root_module_statics! {TestingMod_Ref} const BASE_NAME: &'static str = "testing_1_loading_errors"; const NAME: &'static str = "testing_1_loading_errors"; const VERSION_STRINGS: VersionStrings = package_version_strings!(); } - #[repr(C)] -#[derive(StableAbi)] -#[sabi(kind(Prefix(prefix_ref="TestingMod_Ref")))] +#[derive(StableAbi)] +#[sabi(kind(Prefix(prefix_ref = "TestingMod_Ref")))] #[sabi(missing_field(panic))] pub struct TestingMod { #[sabi(last_prefix_field)] @@ -36,69 +29,62 @@ pub struct TestingMod { pub c: u32, } - //////////////////////////////////////////////////////////////////////////////// /// This type is used to test that errors from types with an incompatble ABI can be printed. -/// -/// The reason that needs to be printed is because the +/// +/// The reason that needs to be printed is because the #[repr(C)] -#[derive(StableAbi)] -#[sabi(kind(Prefix(prefix_ref="WithIncompatibleLayout_Ref")))] +#[derive(StableAbi)] +#[sabi(kind(Prefix(prefix_ref = "WithIncompatibleLayout_Ref")))] pub struct WithIncompatibleLayout { #[sabi(last_prefix_field)] pub __foo: u64, } impl RootModule for WithIncompatibleLayout_Ref { - abi_stable::declare_root_module_statics!{WithIncompatibleLayout_Ref} + abi_stable::declare_root_module_statics! {WithIncompatibleLayout_Ref} const BASE_NAME: &'static str = "testing_1_loading_errors"; const NAME: &'static str = "testing_1_loading_errors"; const VERSION_STRINGS: VersionStrings = package_version_strings!(); } - //////////////////////////////////////////////////////////////////////////////// /// This type is used to test that errors from types with an incompatble ABI can be printed. -/// -/// The reason that needs to be printed is because the +/// +/// The reason that needs to be printed is because the #[repr(C)] -#[derive(StableAbi)] -#[sabi(kind(Prefix(prefix_ref="NonAbiStableLib_Ref")))] +#[derive(StableAbi)] +#[sabi(kind(Prefix(prefix_ref = "NonAbiStableLib_Ref")))] pub struct NonAbiStableLib { #[sabi(last_prefix_field)] pub __foo: u64, } impl RootModule for NonAbiStableLib_Ref { - abi_stable::declare_root_module_statics!{NonAbiStableLib_Ref} + abi_stable::declare_root_module_statics! {NonAbiStableLib_Ref} const BASE_NAME: &'static str = "non_abi_stable_lib"; const NAME: &'static str = "non_abi_stable_lib"; const VERSION_STRINGS: VersionStrings = package_version_strings!(); } - - - - //////////////////////////////////////////////////////////////////////////////// - /// Parameters for the program passed through environment variables. /// /// The reason that env vars are used instead of command line arguments is because /// both the dynamic library and the executable can see the env vars. #[derive(Debug)] -pub struct EnvVars{ +pub struct EnvVars { /// Whether the dynamic library returns an error. pub return_what: ReturnWhat, } #[derive(Debug)] -pub enum ReturnWhat{ +pub enum ReturnWhat { Ok, Error, Panic, @@ -109,8 +95,8 @@ pub struct ParseReturnWhatError(String); impl std::str::FromStr for ReturnWhat { type Err = ParseReturnWhatError; - - fn from_str(str: &str)->Result { + + fn from_str(str: &str) -> Result { let trimmed = str.trim(); if trimmed.starts_with("ok") { Ok(ReturnWhat::Ok) @@ -124,10 +110,9 @@ impl std::str::FromStr for ReturnWhat { } } - /// Returns the parameters passed through environment variables pub fn get_env_vars() -> EnvVars { - EnvVars{ + EnvVars { return_what: std::env::var("RETURN").unwrap().parse().unwrap(), } } diff --git a/testing/1 - loading errors/non_abi_stable_lib/src/lib.rs b/testing/1 - loading errors/non_abi_stable_lib/src/lib.rs index c642b1f3..61693b42 100644 --- a/testing/1 - loading errors/non_abi_stable_lib/src/lib.rs +++ b/testing/1 - loading errors/non_abi_stable_lib/src/lib.rs @@ -1 +1 @@ -//! This crate is an example non-abi_stable dynamic library \ No newline at end of file +//! This crate is an example non-abi_stable dynamic library diff --git a/testing/1 - loading errors/user_1/src/main.rs b/testing/1 - loading errors/user_1/src/main.rs index d65badcb..51fe2f5c 100644 --- a/testing/1 - loading errors/user_1/src/main.rs +++ b/testing/1 - loading errors/user_1/src/main.rs @@ -1,13 +1,11 @@ #![allow(clippy::print_literal)] use abi_stable::library::{ - development_utils::compute_library_path, - LibraryError, RootModule, RootModuleError, + development_utils::compute_library_path, LibraryError, RootModule, RootModuleError, }; use testing_interface_1::{ - NonAbiStableLib_Ref, ReturnWhat, TestingMod_Ref, WithIncompatibleLayout_Ref, - get_env_vars, + get_env_vars, NonAbiStableLib_Ref, ReturnWhat, TestingMod_Ref, WithIncompatibleLayout_Ref, }; use std::fmt; @@ -18,32 +16,32 @@ fn main() { let envars = get_env_vars(); println!("app: {:?}", envars); - + { let err = WithIncompatibleLayout_Ref::load_from_directory("foo/bar/bar".as_ref()) .err() .unwrap(); assert!( - core_extensions::matches!(err, LibraryError::OpenError{..}), + core_extensions::matches!(err, LibraryError::OpenError { .. }), "{:?}", err, ); } { - let library_path= - compute_library_path::(target).unwrap(); - let err = NonAbiStableLib_Ref::load_from_directory(&library_path).err().unwrap(); + let library_path = compute_library_path::(target).unwrap(); + let err = NonAbiStableLib_Ref::load_from_directory(&library_path) + .err() + .unwrap(); assert!( - core_extensions::matches!(err, LibraryError::GetSymbolError{..}), + core_extensions::matches!(err, LibraryError::GetSymbolError { .. }), "{:?}", err, ); } { - let library_path= - compute_library_path::(target).unwrap(); + let library_path = compute_library_path::(target).unwrap(); let err = WithIncompatibleLayout_Ref::load_from_directory(&library_path) .err() @@ -59,32 +57,32 @@ fn main() { let formatted = format!("{0} {0:?}", err); println!( "sum of bytes in the error: {}", - formatted.bytes().map(|x| x as u64 ).sum::() + formatted.bytes().map(|x| x as u64).sum::() ); - } - { - let library_path=compute_library_path::(target).unwrap(); - let res=TestingMod_Ref::load_from_directory(&library_path); + { + let library_path = compute_library_path::(target).unwrap(); + let res = TestingMod_Ref::load_from_directory(&library_path); match envars.return_what { - ReturnWhat::Ok=>{ + ReturnWhat::Ok => { let module = res.unwrap(); assert_eq!(module.a(), 5); assert_eq!(module.b(), 8); assert_eq!(module.c(), 13); } - ReturnWhat::Error|ReturnWhat::Panic=>{ + ReturnWhat::Error | ReturnWhat::Panic => { let err = res.err().expect("Expected the library to return an error"); - if let LibraryError::RootModule{err: rm_err, ..} = &err { - + if let LibraryError::RootModule { err: rm_err, .. } = &err { assert!( core_extensions::matches!( (&envars.return_what, rm_err), - |(ReturnWhat::Error, RootModuleError::Returned{..}) - |(ReturnWhat::Panic, RootModuleError::Unwound{..}) + |(ReturnWhat::Error, RootModuleError::Returned { .. })| ( + ReturnWhat::Panic, + RootModuleError::Unwound { .. } + ) ), "return_what: {:?}\nerror: {:?}", envars.return_what, @@ -103,15 +101,13 @@ fn main() { } println!( "\n{S}{S}\n\nFinished successfully\n\n{S}{S}\n", - S="----------------------------------------", + S = "----------------------------------------", ); } } fn print_error_sum(line: u32, e: E) { let formatted = format!("{0} {0:?}", e); - let sum = formatted.bytes() - .map(|x| x as u64 ) - .sum::(); + let sum = formatted.bytes().map(|x| x as u64).sum::(); println!("{}: sum of bytes in the error: {}", line, sum); } diff --git a/testing/version_compatibility/impl_0/src/lib.rs b/testing/version_compatibility/impl_0/src/lib.rs index 05e84a4e..b9f4a242 100644 --- a/testing/version_compatibility/impl_0/src/lib.rs +++ b/testing/version_compatibility/impl_0/src/lib.rs @@ -3,20 +3,17 @@ This crate is where extra tests which don't belong in examples go. */ -use version_compatibility_interface::{RootMod_Ref, RootMod}; +use version_compatibility_interface::{RootMod, RootMod_Ref}; -use abi_stable::{ - export_root_module, - marker_type::NonOwningPhantom, - prefix_type::PrefixTypeTrait, -}; +use abi_stable::{export_root_module, marker_type::NonOwningPhantom, prefix_type::PrefixTypeTrait}; /////////////////////////////////////////////////////////////////////////////////// #[export_root_module] pub fn get_library() -> RootMod_Ref { - RootMod{ + RootMod { _marker: NonOwningPhantom::DEFAULT, - abi_stable_version:abi_stable::ABI_STABLE_VERSION, - }.leak_into_prefix() -} \ No newline at end of file + abi_stable_version: abi_stable::ABI_STABLE_VERSION, + } + .leak_into_prefix() +} diff --git a/testing/version_compatibility/interface/src/lib.rs b/testing/version_compatibility/interface/src/lib.rs index 19a59ca7..7caaa7cf 100644 --- a/testing/version_compatibility/interface/src/lib.rs +++ b/testing/version_compatibility/interface/src/lib.rs @@ -1,27 +1,18 @@ - -#[cfg(feature="new")] +#[cfg(feature = "new")] extern crate new_abi_stable as abi_stable; -#[cfg(not(feature="new"))] +#[cfg(not(feature = "new"))] extern crate old_abi_stable as abi_stable; -use abi_stable::{ - marker_type::NonOwningPhantom, - sabi_types::VersionStrings, - library::RootModule, -}; +use abi_stable::{library::RootModule, marker_type::NonOwningPhantom, sabi_types::VersionStrings}; +mod many_types { + use std::{marker::PhantomData, sync::atomic}; -mod many_types{ - use std::{ - marker::PhantomData, - sync::atomic, - }; - use abi_stable::{ external_types::{ - crossbeam_channel::{RReceiver,RSender}, - RMutex,RRwLock,ROnce + crossbeam_channel::{RReceiver, RSender}, + RMutex, ROnce, RRwLock, }, marker_type, prefix_type::PrefixRef, @@ -59,10 +50,10 @@ mod many_types{ std::num::NonZeroU16, std::ptr::NonNull<()>, std::ptr::NonNull, - RHashMap, - RHashMap, - RHashMap, - RHashMap, + RHashMap, + RHashMap, + RHashMap, + RHashMap, RVec<()>, RVec, RSlice<'static, ()>, @@ -106,25 +97,24 @@ mod many_types{ marker_type::UnsafeIgnoredType, marker_type::NonOwningPhantom, marker_type::NonOwningPhantom, - ); + ); } pub use many_types::ManyTypes; #[repr(C)] #[derive(abi_stable::StableAbi)] -#[sabi(kind(Prefix(prefix_ref="RootMod_Ref")))] +#[sabi(kind(Prefix(prefix_ref = "RootMod_Ref")))] #[sabi(missing_field(panic))] -pub struct RootMod{ - pub abi_stable_version:VersionStrings, - pub _marker:NonOwningPhantom, +pub struct RootMod { + pub abi_stable_version: VersionStrings, + pub _marker: NonOwningPhantom, } impl RootModule for RootMod_Ref { - abi_stable::declare_root_module_statics!{RootMod_Ref} + abi_stable::declare_root_module_statics! {RootMod_Ref} const BASE_NAME: &'static str = "version_compatibility_impl"; const NAME: &'static str = "version_compatibility_impl"; const VERSION_STRINGS: VersionStrings = abi_stable::package_version_strings!(); } - diff --git a/testing/version_compatibility/user_0/src/main.rs b/testing/version_compatibility/user_0/src/main.rs index 0d965011..97270628 100644 --- a/testing/version_compatibility/user_0/src/main.rs +++ b/testing/version_compatibility/user_0/src/main.rs @@ -1,74 +1,79 @@ use std::{ - path::{Path,PathBuf}, io, + path::{Path, PathBuf}, }; -use abi_stable::{ - library::{AbiHeader,RootModule,LibraryError,abi_header_from_path}, -}; +use abi_stable::library::{abi_header_from_path, AbiHeader, LibraryError, RootModule}; use core_extensions::SelfOps; use version_compatibility_interface::RootMod_Ref; - - /// Returns the path the library will be loaded from. -fn compute_library_dir()->io::Result{ - let debug_dir ="../../../target/debug/" .as_ref_::().into_::(); - let release_dir="../../../target/release/".as_ref_::().into_::(); - - let debug_path =RootMod_Ref::get_library_path(&debug_dir); - let release_path=RootMod_Ref::get_library_path(&release_dir); - - match (debug_path.exists(),release_path.exists()) { - (false,false)=>debug_dir, - (true,false)=>debug_dir, - (false,true)=>release_dir, - (true,true)=>{ +fn compute_library_dir() -> io::Result { + let debug_dir = "../../../target/debug/" + .as_ref_::() + .into_::(); + let release_dir = "../../../target/release/" + .as_ref_::() + .into_::(); + + let debug_path = RootMod_Ref::get_library_path(&debug_dir); + let release_path = RootMod_Ref::get_library_path(&release_dir); + + match (debug_path.exists(), release_path.exists()) { + (false, false) => debug_dir, + (true, false) => debug_dir, + (false, true) => release_dir, + (true, true) => { if debug_path.metadata()?.modified()? < release_path.metadata()?.modified()? { release_dir - }else{ + } else { debug_dir } } - }.piped(Ok) + } + .piped(Ok) } +fn main() -> io::Result<()> { + let library_dir = compute_library_dir().unwrap(); -fn main()-> io::Result<()> { - let library_dir=compute_library_dir().unwrap(); - - (||->Result<(),LibraryError>{ - let header=abi_header_from_path(&RootMod_Ref::get_library_path(&library_dir))?; + (|| -> Result<(), LibraryError> { + let header = abi_header_from_path(&RootMod_Ref::get_library_path(&library_dir))?; println!("header: {:?}", header); println!(); println!("Executable's AbiHeader {:?}", AbiHeader::VALUE); println!(); - println!("Executable's abi_stable version {:?}", abi_stable::ABI_STABLE_VERSION); + println!( + "Executable's abi_stable version {:?}", + abi_stable::ABI_STABLE_VERSION + ); println!(); if header.is_valid() { - let lib_header=header.upgrade()?; + let lib_header = header.upgrade()?; - unsafe{ - let root=lib_header.init_root_module_with_unchecked_layout::()?; + unsafe { + let root = lib_header.init_root_module_with_unchecked_layout::()?; println!("Loaded abi_stable version {:?}", root.abi_stable_version()); println!(); } - lib_header.check_layout::()?; - println!("\ + println!( + "\ The types in abi_stable on crates.io are compatible with those on \ the \"local\" repository\ - "); + " + ); } else { println!("The abi_stable on crates.io isn't semver compatible with this one"); } Ok(()) - })().unwrap_or_else(|e| panic!("{}", e) ); + })() + .unwrap_or_else(|e| panic!("{}", e)); Ok(()) -} \ No newline at end of file +} diff --git a/tools/sabi_extract/src/main.rs b/tools/sabi_extract/src/main.rs index 2186d630..18e39cfa 100644 --- a/tools/sabi_extract/src/main.rs +++ b/tools/sabi_extract/src/main.rs @@ -1,63 +1,53 @@ -use std::{ - fs, - path::PathBuf, -}; - +use std::{fs, path::PathBuf}; use abi_stable::{ + library::lib_header_from_path, //abi_stability::check_layout_compatibility, reflection::export_module::MRItem, - library::lib_header_from_path, }; use core_extensions::SelfOps; use structopt::StructOpt; - /////////////////////////////////////////////////////////////////////////////// - #[derive(StructOpt)] -#[structopt(author="_")] +#[structopt(author = "_")] enum Command { - -/** -Extracts the module structure of an abi_stable library, -with the typenames of each function parameter/return type. -*/ + /** + Extracts the module structure of an abi_stable library, + with the typenames of each function parameter/return type. + */ #[structopt(name = "mods")] - #[structopt(author="_")] + #[structopt(author = "_")] Modules { /// The path to the library. - library_path:PathBuf, - + library_path: PathBuf, + /// Which file to output the module structure to. - #[structopt(short = "o",long="out-file")] + #[structopt(short = "o", long = "out-file")] #[structopt(parse(from_os_str))] - output_file:Option, - + output_file: Option, + /// Whether to output the module structure to stdout. - #[structopt(short = "s",)] - output_stdout:bool, + #[structopt(short = "s")] + output_stdout: bool, /// Whether to outputed json is compact - #[structopt(long = "--compact",)] - compact_json:bool + #[structopt(long = "--compact")] + compact_json: bool, }, } - - - fn main() { + let lib_header = abi_stable::LIB_HEADER; + let minor_s = lib_header.abi_minor.to_string(); - let lib_header=abi_stable::LIB_HEADER; - let minor_s=lib_header.abi_minor.to_string(); - - let short_about= + let short_about = "A program to extract a variety of information from an abi_stable dynamic library."; - let long_about=format!(" + let long_about = format!( + " {short_about} This program uses the {major}.{minor} version of abi_stable. @@ -65,23 +55,32 @@ This program uses the {major}.{minor} version of abi_stable. The loaded dynamic library must use a {major}.{dep_minor}.* \ version of abi_stable to be loaded successfully. ", - short_about=short_about, - major=lib_header.abi_major, - minor=lib_header.abi_minor, - dep_minor=if lib_header.abi_major!=0 { "*" }else{ &*minor_s }, -); - - let opts = Command::clap() + short_about = short_about, + major = lib_header.abi_major, + minor = lib_header.abi_minor, + dep_minor = if lib_header.abi_major != 0 { + "*" + } else { + &*minor_s + }, + ); + + let opts = Command::clap() .about(short_about) .about(&*long_about) .get_matches() .piped_ref(Command::from_clap); match opts { - Command::Modules{library_path,output_file,output_stdout,compact_json}=>{ - let lib_header=lib_header_from_path(library_path.as_ref()).unwrap(); - - let layout=lib_header.layout().unwrap_or_else(||{ + Command::Modules { + library_path, + output_file, + output_stdout, + compact_json, + } => { + let lib_header = lib_header_from_path(library_path.as_ref()).unwrap(); + + let layout = lib_header.layout().unwrap_or_else(|| { println!( "The dynamic library does not support reflection:\n {}", library_path.display(), @@ -89,28 +88,26 @@ version of abi_stable to be loaded successfully. std::process::exit(1); }); - let root_mod=MRItem::from_type_layout(layout); + let root_mod = MRItem::from_type_layout(layout); - let json=&if compact_json { + let json = &if compact_json { serde_json::to_string(&root_mod).unwrap() - }else{ + } else { serde_json::to_string_pretty(&root_mod).unwrap() }; - - if let Some(output_file)=&output_file { - if let Err(e)=fs::write(output_file,json) { + + if let Some(output_file) = &output_file { + if let Err(e) = fs::write(output_file, json) { panic!( - "Error writing to file:\n{}\nError:\n{}\n", + "Error writing to file:\n{}\nError:\n{}\n", output_file.display(), e, ); } } if output_file.is_none() || output_stdout { - println!("{}", json ); + println!("{}", json); } } } - - } From a3ac5c4de3b6142467d43d3d642e787154bb45d2 Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Mon, 4 Oct 2021 01:24:40 -0300 Subject: [PATCH 03/32] Added test(?) of RootModule::{initialize, load_from_file} Clarified when RootModule::initialize runs. Clarified that `mangled_root_module_loader_name` does not return a nul-terminated string. Added script to run cargo fmt, then commit. --- abi_stable/src/library/root_mod_trait.rs | 3 +++ abi_stable_shared/src/lib.rs | 3 +++ commit.sh | 20 +++++++++++++++++++ .../impl/src/lib.rs | 19 ++++++++++++++++-- .../interface/src/lib.rs | 10 +++++++++- .../user/src/main.rs | 9 +++++++++ examples/2_nonexhaustive/user/src/main.rs | 9 +++++++-- 7 files changed, 68 insertions(+), 5 deletions(-) create mode 100755 commit.sh diff --git a/abi_stable/src/library/root_mod_trait.rs b/abi_stable/src/library/root_mod_trait.rs index 1e64fc35..adec5ed7 100644 --- a/abi_stable/src/library/root_mod_trait.rs +++ b/abi_stable/src/library/root_mod_trait.rs @@ -225,6 +225,9 @@ pub trait RootModule: Sized + StableAbi + PrefixRefTrait + 'static { /// Defines behavior that happens once the module is loaded. /// + /// This is ran in the `RootModule::load*` associated functions + /// after the root module has succesfully been loaded. + /// /// The default implementation does nothing. fn initialization(self) -> Result { Ok(self) diff --git a/abi_stable_shared/src/lib.rs b/abi_stable_shared/src/lib.rs index b446b9ad..459b9acc 100644 --- a/abi_stable_shared/src/lib.rs +++ b/abi_stable_shared/src/lib.rs @@ -75,6 +75,9 @@ where } /// Gets the name of the static that contains the LibHeader of an abi_stable library. +/// +/// This does not have a trailing `'\0'`, +/// you need to append it to pass the name to C APIs. pub fn mangled_root_module_loader_name() -> String { mangle_ident("lib_header", "root module loader") } diff --git a/commit.sh b/commit.sh new file mode 100755 index 00000000..dc7ed9c9 --- /dev/null +++ b/commit.sh @@ -0,0 +1,20 @@ +#!/bin/sh + +# +# You can use this script to format and commit the code all at once +# +# + +cargo fmt + +if [ $? -eq 0 ] +then + echo "ran cargo fmt!!!!" +else + exit 1 +fi + + +git update-index --again + +git commit \ No newline at end of file diff --git a/examples/0_modules_and_interface_types/impl/src/lib.rs b/examples/0_modules_and_interface_types/impl/src/lib.rs index ba3726dd..8b3be34c 100644 --- a/examples/0_modules_and_interface_types/impl/src/lib.rs +++ b/examples/0_modules_and_interface_types/impl/src/lib.rs @@ -5,7 +5,12 @@ It exports the root module(a struct of function pointers) required by the */ -use std::{borrow::Cow, collections::HashSet, marker::PhantomData}; +use std::{ + borrow::Cow, + collections::HashSet, + marker::PhantomData, + sync::atomic::{AtomicU64, Ordering}, +}; use example_0_interface::{ CowStrIter, DeserializerMod, DeserializerMod_Ref, RemoveWords, TOCommand, TOCommandBox, @@ -55,6 +60,7 @@ fn instantiate_root_module() -> TextOpsMod_Ref { reverse_lines, remove_words, get_processed_bytes, + set_initial_processed_bytes, run_command, } .leak_into_prefix() @@ -223,11 +229,15 @@ pub fn deserialize_return_value(s: RStr<'_>) -> RResult,TOState>`. #[sabi_extern_fn] pub fn new() -> TOStateBox { - let this = TextOperationState { processed_bytes: 0 }; + let this = TextOperationState { + processed_bytes: INITIAL_PROCESSED_BYTES.load(Ordering::SeqCst), + }; DynTrait::from_value(this) } @@ -292,6 +302,11 @@ pub fn get_processed_bytes(this: &TOStateBox) -> u64 { this.processed_bytes } +#[sabi_extern_fn] +pub fn set_initial_processed_bytes(n: u64) { + INITIAL_PROCESSED_BYTES.store(n, Ordering::SeqCst); +} + fn run_command_inner(this: &mut TOStateBox, command: Command) -> ReturnValue { match command { Command::ReverseLines(s) => { diff --git a/examples/0_modules_and_interface_types/interface/src/lib.rs b/examples/0_modules_and_interface_types/interface/src/lib.rs index 264e83c5..8b2ccaf7 100644 --- a/examples/0_modules_and_interface_types/interface/src/lib.rs +++ b/examples/0_modules_and_interface_types/interface/src/lib.rs @@ -14,7 +14,7 @@ use abi_stable::{ declare_root_module_statics, erased_types::{DeserializeDyn, IteratorItem, SerializeProxyType}, external_types::{RawValueBox, RawValueRef}, - library::RootModule, + library::{LibraryError, RootModule}, package_version_strings, sabi_types::{RMut, VersionStrings}, std_types::{RArc, RBox, RBoxError, RCow, RResult, RStr, RString}, @@ -61,6 +61,9 @@ pub struct TextOpsMod { pub run_command: extern "C" fn(&mut TOStateBox, command: TOCommandBox<'static>) -> TOReturnValueArc, + + /// Sets the initial amount (in bytes) of text that was processed + pub set_initial_processed_bytes: extern "C" fn(u64), } impl RootModule for TextOpsMod_Ref { @@ -68,6 +71,11 @@ impl RootModule for TextOpsMod_Ref { const BASE_NAME: &'static str = "text_operations"; const NAME: &'static str = "text_operations"; const VERSION_STRINGS: VersionStrings = package_version_strings!(); + + fn initialization(self) -> Result { + self.set_initial_processed_bytes()(10); + Ok(self) + } } /// A module for all deserialization functions. diff --git a/examples/0_modules_and_interface_types/user/src/main.rs b/examples/0_modules_and_interface_types/user/src/main.rs index c6241104..3fc36995 100644 --- a/examples/0_modules_and_interface_types/user/src/main.rs +++ b/examples/0_modules_and_interface_types/user/src/main.rs @@ -137,6 +137,15 @@ fn main() -> io::Result<()> { let mut state = mods.new()(); + // Ensuring that `RootModule::initialization` is actually ran + { + assert_eq!(mods.get_processed_bytes()(&state), 10); + + mods.set_initial_processed_bytes()(4000); + let mut state = mods.new()(); + assert_eq!(mods.get_processed_bytes()(&state), 4000); + } + match opts { Command::ReverseLineOrder => { let mut buffer = String::new(); diff --git a/examples/2_nonexhaustive/user/src/main.rs b/examples/2_nonexhaustive/user/src/main.rs index b9730b61..41819605 100644 --- a/examples/2_nonexhaustive/user/src/main.rs +++ b/examples/2_nonexhaustive/user/src/main.rs @@ -9,9 +9,14 @@ use example_2_interface::{Command_NE, ShopMod_Ref}; fn main() { let target: &std::path::Path = "../../../target/".as_ref(); - let library_path = compute_library_path::(target).unwrap(); + let library_dir = compute_library_path::(target).unwrap(); - let mods = ShopMod_Ref::load_from_directory(&library_path).unwrap_or_else(|e| panic!("{}", e)); + // The typical way you'd load the root module + // let mods = ShopMod_Ref::load_from_directory(&library_dir).unwrap_or_else(|e| panic!("{}", e)); + + // Another way to load the root module + let library_file = ShopMod_Ref::get_library_path(&library_dir); + let mods = ShopMod_Ref::load_from_file(&library_file).unwrap_or_else(|e| panic!("{}", e)); let config_path = match std::env::args_os().nth(1) { Some(os) => PathBuf::from(os), From b19fe1765ea22ae6e56e52afe167ba39129ea1d1 Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Mon, 4 Oct 2021 17:21:56 -0300 Subject: [PATCH 04/32] Deprecated `abi_stable::library::mangled_root_module_loader_name` Replaced the function (and uses of it) with these new constants: - ROOT_MODULE_LOADER_NAME - ROOT_MODULE_LOADER_NAME_WITH_NUL - ROOT_MODULE_LOADER_NAME_NULSTR Added test for these constants. Added docs to `AbiHeaderRef` Rewrote NulStr docs, added `as_ptr` accesor method. --- abi_stable/src/library.rs | 43 +++++++++++++++++-- abi_stable/src/library/lib_header.rs | 15 ++++--- abi_stable/src/library/library_tests.rs | 15 +++++++ abi_stable/src/library/root_mod_trait.rs | 4 +- .../export_root_module.rs | 2 +- abi_stable/src/sabi_types/nul_str.rs | 22 +++++++++- abi_stable_derive/src/constants.rs | 1 - abi_stable_derive/src/lib.rs | 14 +++++- 8 files changed, 100 insertions(+), 16 deletions(-) create mode 100644 abi_stable/src/library/library_tests.rs delete mode 100644 abi_stable_derive/src/constants.rs diff --git a/abi_stable/src/library.rs b/abi_stable/src/library.rs index cd3440ee..84d8670b 100644 --- a/abi_stable/src/library.rs +++ b/abi_stable/src/library.rs @@ -15,14 +15,12 @@ use core_extensions::SelfOps; use libloading::{Library as LibLoadingLibrary, Symbol as LLSymbol}; -pub use abi_stable_shared::mangled_root_module_loader_name; - use crate::{ abi_stability::stable_abi_trait::StableAbi, globals::{self, Globals}, marker_type::ErasedPrefix, prefix_type::{PrefixRef, PrefixRefTrait}, - sabi_types::{LateStaticRef, VersionNumber, VersionStrings}, + sabi_types::{LateStaticRef, NulStr, VersionNumber, VersionStrings}, std_types::{RResult, RStr}, type_layout::TypeLayout, }; @@ -31,6 +29,7 @@ pub mod c_abi_testing; pub mod development_utils; mod errors; mod lib_header; +mod library_tests; mod raw_library; mod root_mod_trait; @@ -214,6 +213,44 @@ macro_rules! declare_root_module_statics { ////////////////////////////////////////////////////////////////////// +#[deprecated( + since = "0.10.3", + note = "Use the ROOT_MODULE_LOADER_NAME constant instead" +)] +/// Gets the name of the static that contains the LibHeader of an abi_stable library. +pub fn mangled_root_module_loader_name() -> String { + abi_stable_shared::mangled_root_module_loader_name() +} + +abi_stable_derive::__const_mangled_root_module_loader_name! {} + +/// The name of the `static` that contains the [`AbiHeader`] of an abi_stable library. +/// +/// You can get a handle to that [`AbiHeader`] using +/// [abi_header_from_path](fn.abi_header_from_path.html) or +/// [abi_header_from_raw_library](fn.abi_header_from_raw_library.html). +/// +/// If you need a nul-terminated string, +/// you can use [`ROOT_MODULE_LOADER_NAME_WITH_NUL`] instead. +/// +/// [`LibHeader`]: ./struct.LibHeader.html +/// [`ROOT_MODULE_LOADER_NAME_WITH_NUL`]: ./constant.ROOT_MODULE_LOADER_NAME_WITH_NUL.html +pub const ROOT_MODULE_LOADER_NAME: &str = PRIV_MANGLED_ROOT_MODULE_LOADER_NAME; + +/// A nul-terminated equivalent of [`ROOT_MODULE_LOADER_NAME`]. +/// +/// [`ROOT_MODULE_LOADER_NAME`]: ./constant.ROOT_MODULE_LOADER_NAME.html +pub const ROOT_MODULE_LOADER_NAME_WITH_NUL: &str = PRIV_MANGLED_ROOT_MODULE_LOADER_NAME_NUL; + +/// A [`NulStr`] equivalent of [`ROOT_MODULE_LOADER_NAME`]. +/// +/// [`ROOT_MODULE_LOADER_NAME`]: ./constant.ROOT_MODULE_LOADER_NAME.html +/// [`NulStr`]: ../sabi_types/struct.NulStr.html +pub const ROOT_MODULE_LOADER_NAME_NULSTR: NulStr<'_> = + unsafe { NulStr::from_str(PRIV_MANGLED_ROOT_MODULE_LOADER_NAME_NUL) }; + +////////////////////////////////////////////////////////////////////// + #[doc(hidden)] pub fn __call_root_module_loader(function: fn() -> T) -> RootModuleResult where diff --git a/abi_stable/src/library/lib_header.rs b/abi_stable/src/library/lib_header.rs index a5fadb8b..514381fa 100644 --- a/abi_stable/src/library/lib_header.rs +++ b/abi_stable/src/library/lib_header.rs @@ -303,6 +303,12 @@ const INIT_GLOBALS_WITH: InitGlobalsWith = InitGlobalsWith(crate::globals::initi ////////////////////////////////////////////////////////////////////// +/// A handle to the [`AbiHeader`] of a library. +/// +/// This can be dereferenced into the `AbiHeader`, +/// and [fallibly upgraded](#method.upgrade) into a `&'static LibHeader`. +/// +/// [`AbiHeader`]: ./struct.AbiHeader.html #[repr(transparent)] #[derive(Debug, StableAbi, Copy, Clone)] pub struct AbiHeaderRef(pub(super) RRef<'static, AbiHeader>); @@ -315,11 +321,10 @@ impl std::ops::Deref for AbiHeaderRef { } } -/** -Represents the abi_stable version used by a compiled dynamic library, -which if incompatible would produce a `LibraryError::InvalidAbiHeader` - -*/ +/// Represents the abi_stable version used by a compiled dynamic library, +/// which if incompatible would produce a [`LibraryError::InvalidAbiHeader`] +/// +/// [`LibraryError::InvalidAbiHeader`]: ./enum.LibraryError.html#variant.InvalidAbiHeader #[repr(C)] #[derive(Debug, StableAbi, Copy, Clone)] pub struct AbiHeader { diff --git a/abi_stable/src/library/library_tests.rs b/abi_stable/src/library/library_tests.rs new file mode 100644 index 00000000..f3a5817d --- /dev/null +++ b/abi_stable/src/library/library_tests.rs @@ -0,0 +1,15 @@ +use crate::library::{ + ROOT_MODULE_LOADER_NAME, ROOT_MODULE_LOADER_NAME_NULSTR, ROOT_MODULE_LOADER_NAME_WITH_NUL, +}; +use abi_stable_shared::mangled_root_module_loader_name; + +#[test] +fn root_module_loader_name_test() { + let name = mangled_root_module_loader_name(); + let with_nul = format!("{}\0", name); + + assert_eq!(ROOT_MODULE_LOADER_NAME, name); + assert_eq!(ROOT_MODULE_LOADER_NAME_WITH_NUL, with_nul); + assert_eq!(ROOT_MODULE_LOADER_NAME_NULSTR.to_str(), name); + assert_eq!(ROOT_MODULE_LOADER_NAME_NULSTR.to_str_with_nul(), with_nul); +} diff --git a/abi_stable/src/library/root_mod_trait.rs b/abi_stable/src/library/root_mod_trait.rs index adec5ed7..71a8a0db 100644 --- a/abi_stable/src/library/root_mod_trait.rs +++ b/abi_stable/src/library/root_mod_trait.rs @@ -291,9 +291,7 @@ pub unsafe fn abi_header_from_raw_library( raw_library: &RawLibrary, ) -> Result { unsafe { - let mut mangled = mangled_root_module_loader_name(); - mangled.push('\0'); - + let mangled = ROOT_MODULE_LOADER_NAME_WITH_NUL; let header: AbiHeaderRef = *raw_library.get::(mangled.as_bytes())?; Ok(header) diff --git a/abi_stable/src/proc_macro_reexports/export_root_module.rs b/abi_stable/src/proc_macro_reexports/export_root_module.rs index 774d5112..50124a3d 100644 --- a/abi_stable/src/proc_macro_reexports/export_root_module.rs +++ b/abi_stable/src/proc_macro_reexports/export_root_module.rs @@ -71,7 +71,7 @@ with these things: - The constructor function of the root module. The name used for root modules is the one returned by -`abi_stable::library::mangled_root_module_loader_name`. +`abi_stable::library::ROOT_MODULE_LOADER_NAME`. Because there can't be multiple root modules for a library, that function returns a constant. diff --git a/abi_stable/src/sabi_types/nul_str.rs b/abi_stable/src/sabi_types/nul_str.rs index 49214d7e..0a68cfb4 100644 --- a/abi_stable/src/sabi_types/nul_str.rs +++ b/abi_stable/src/sabi_types/nul_str.rs @@ -10,7 +10,20 @@ use std::{ ptr::NonNull, }; -/// A utf8 null-terminated string slice. +/// A utf8 nul-terminated immutable borrowed string. +/// +/// For the purpose of passing `NulStr`s to C, +/// this has the same ABI as a `std::ptr::NonNull`, +/// and an `Option>` has the same ABI as `*const u8`. +/// +/// # Safety +/// +/// `NulStr` has these safety requirement: +/// - the string must be valid to read for the `'a` lifetime +/// - the string must be utf8 encoded +/// - the string must be nul terminated and not contain interior nul bytes +/// - the string must not be mutated while this is alive +/// (the same semantics as `&` references) #[repr(transparent)] #[derive(Copy, Clone, StableAbi)] pub struct NulStr<'a> { @@ -46,7 +59,7 @@ impl<'a> NulStr<'a> { /// /// # Safety /// - /// The pointer must point to a utf8 and nul terminated (a 0 byte) sequence of bytes. + /// [The same as the type-level safety docs](#safety) pub const unsafe fn from_ptr(ptr: *const u8) -> Self { Self { ptr: NonNull::new_unchecked(ptr as *mut u8), @@ -54,6 +67,11 @@ impl<'a> NulStr<'a> { } } + /// Gets a pointer to the start of this nul-terminated string. + pub const fn as_ptr(self) -> *const std::os::raw::c_char { + self.ptr.as_ptr() as _ + } + /// Converts this `NulStr<'a>` to a `&'a str`,including the nul byte. /// /// # Performance diff --git a/abi_stable_derive/src/constants.rs b/abi_stable_derive/src/constants.rs deleted file mode 100644 index 8b137891..00000000 --- a/abi_stable_derive/src/constants.rs +++ /dev/null @@ -1 +0,0 @@ - diff --git a/abi_stable_derive/src/lib.rs b/abi_stable_derive/src/lib.rs index 48dc1944..f8069edf 100644 --- a/abi_stable_derive/src/lib.rs +++ b/abi_stable_derive/src/lib.rs @@ -98,6 +98,19 @@ pub fn get_root_module_static(_: TokenStream1) -> TokenStream1 { quote!( crate::#export_name ).into() } +#[doc(hidden)] +#[proc_macro] +pub fn __const_mangled_root_module_loader_name(_: TokenStream1) -> TokenStream1 { + let name = abi_stable_shared::mangled_root_module_loader_name(); + let name_nulled = format!("{}\0", name); + + quote!( + const PRIV_MANGLED_ROOT_MODULE_LOADER_NAME: &str = #name; + const PRIV_MANGLED_ROOT_MODULE_LOADER_NAME_NUL: &str = #name_nulled; + ) + .into() +} + /////////////////////////////////////////////////////////////////////////////// #[macro_use] @@ -108,7 +121,6 @@ mod attribute_parsing; mod common_tokens; mod composite_collections; mod concat_and_ranges; -mod constants; mod export_root_module_impl; mod fn_pointer_extractor; mod get_static_equivalent; From c9be292ac742ef8297f2bf85a600b0fe7f3a2abe Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Tue, 5 Oct 2021 00:17:22 -0300 Subject: [PATCH 05/32] Deprecated `nul_str` macro, superceded by the new `nulstr` and `nulstr_trunc` macros. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Made NulStr::from_str safe by panicking when the string isn't nul-terminated, documenting the lossy behavior on interior nuls. Added `NulStr::try_from_str` const fn for fallibly converting a whole string into a `NulStr` Added `ǸulStrError` for `NulStr::try_from_str`. Added "rust_1_46" feature, updated CI to use it. Added `const_fn_if_1_46` macro to make functions `const`, conditional on the `rust_1_46` feature. --- .github/workflows/rust.yml | 6 +- abi_stable/Cargo.toml | 6 +- .../src/abi_stability/stable_abi_trait.rs | 20 ++-- abi_stable/src/derive_macro_reexports.rs | 4 + abi_stable/src/macros.rs | 33 +----- abi_stable/src/macros/internal.rs | 26 ++++ abi_stable/src/macros/nul_str_macros.rs | 90 ++++++++++++++ abi_stable/src/sabi_types.rs | 2 +- abi_stable/src/sabi_types/nul_str.rs | 112 ++++++++++++++++-- abi_stable/src/type_layout/tl_other.rs | 4 +- 10 files changed, 248 insertions(+), 55 deletions(-) create mode 100644 abi_stable/src/macros/nul_str_macros.rs diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 119b476d..a8c407de 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -16,6 +16,10 @@ jobs: os: [ubuntu-latest, windows-latest, macOS-latest] steps: + - name: enable-rust-stable + if: matrix.rust == 'stable' || matrix.rust == 'beta' || matrix.rust == 'nightly' + run: echo "rustv=rust_1_51" >> $GITHUB_ENV + - uses: actions/checkout@v2 - name: ci-all-versions run: | @@ -79,7 +83,7 @@ jobs: cargo test cd "${{github.workspace}}/abi_stable" - cargo test --features "testing" + cargo test --features "${{ env.rustv }} testing" cd "${{github.workspace}}/examples/0_modules_and_interface_types/impl/" cargo test diff --git a/abi_stable/Cargo.toml b/abi_stable/Cargo.toml index dda27276..ebc41627 100644 --- a/abi_stable/Cargo.toml +++ b/abi_stable/Cargo.toml @@ -26,9 +26,11 @@ default = ["channels","serde_json"] rust_1_42=[] -rust_1_51=["rust_1_42", "const_params"] +rust_1_46=["rust_1_42"] -const_params=["rust_1_42"] +rust_1_51=["rust_1_46", "const_params"] + +const_params=["rust_1_46"] # Enables the `#![feature(min_const_generics)]` attribute in nightly_const_params=["const_params"] diff --git a/abi_stable/src/abi_stability/stable_abi_trait.rs b/abi_stable/src/abi_stability/stable_abi_trait.rs index 037cd073..ee2de9b8 100644 --- a/abi_stable/src/abi_stability/stable_abi_trait.rs +++ b/abi_stable/src/abi_stability/stable_abi_trait.rs @@ -201,7 +201,7 @@ where const MONO_TYPE_LAYOUT: &MonoTypeLayout = &MonoTypeLayout::new( *mono_shared_vars, rstr!("PhantomData"), - ItemInfo::std_type_in(nul_str!("std::marker")), + ItemInfo::std_type_in(nulstr_trunc!("std::marker")), MonoTLData::EMPTY, tl_genparams!(;0;), ReprAttr::C, @@ -260,7 +260,7 @@ macro_rules! phantomdata_tuples { const MONO_TYPE_LAYOUT:&MonoTypeLayout=&MonoTypeLayout::new( *mono_shared_vars, rstr!("PhantomData"), - ItemInfo::std_type_in(nul_str!("std::marker")), + ItemInfo::std_type_in(nulstr_trunc!("std::marker")), MonoTLData::EMPTY, tl_genparams!(;0..COUNT;), ReprAttr::C, @@ -639,7 +639,7 @@ where const MONO_TYPE_LAYOUT: &MonoTypeLayout = &MonoTypeLayout::new( *mono_shared_vars, rstr!("NonNull"), - ItemInfo::std_type_in(nul_str!("std::ptr")), + ItemInfo::std_type_in(nulstr_trunc!("std::ptr")), { const S: &[CompTLField] = &[CompTLField::std_field(field0, LifetimeRange::EMPTY, 1)]; @@ -687,7 +687,7 @@ where const MONO_TYPE_LAYOUT: &MonoTypeLayout = &MonoTypeLayout::new( *mono_shared_vars, rstr!("AtomicPtr"), - ItemInfo::std_type_in(nul_str!("std::sync::atomic")), + ItemInfo::std_type_in(nulstr_trunc!("std::sync::atomic")), { const S: &[CompTLField] = &[CompTLField::std_field(field0, LifetimeRange::EMPTY, 1)]; @@ -969,7 +969,7 @@ where const MONO_TYPE_LAYOUT: &MonoTypeLayout = &MonoTypeLayout::new( *mono_shared_vars, rstr!("Option"), - ItemInfo::std_type_in(nul_str!("std::option")), + ItemInfo::std_type_in(nulstr_trunc!("std::option")), MonoTLData::Enum(MonoTLEnum::new(variant_names, rslice![1, 0], { const S: &[CompTLField] = &[CompTLField::std_field(field0, LifetimeRange::EMPTY, 0)]; @@ -1082,7 +1082,7 @@ macro_rules! impl_for_concrete { const MONO_TYPE_LAYOUT:&MonoTypeLayout=&MonoTypeLayout::new( *mono_shared_vars, rstr!($this_name), - ItemInfo::std_type_in(nul_str!($in_mod)), + ItemInfo::std_type_in(nulstr_trunc!($in_mod)), { const S: &[CompTLField] = &[ CompTLField::std_field(field0,LifetimeRange::EMPTY,0), @@ -1189,7 +1189,7 @@ mod rust_1_36_impls { const MONO_TYPE_LAYOUT: &MonoTypeLayout = &MonoTypeLayout::new( *mono_shared_vars, rstr!("MaybeUninit"), - ItemInfo::std_type_in(nul_str!("std::mem")), + ItemInfo::std_type_in(nulstr_trunc!("std::mem")), { const S: &[CompTLField] = &[CompTLField::std_field(field0, LifetimeRange::EMPTY, 0)]; @@ -1253,7 +1253,7 @@ macro_rules! impl_sabi_for_newtype { const MONO_TYPE_LAYOUT:&MonoTypeLayout=&MonoTypeLayout::new( *mono_shared_vars, rstr!($type_name), - ItemInfo::std_type_in(nul_str!($mod_path)), + ItemInfo::std_type_in(nulstr_trunc!($mod_path)), { const S: &[CompTLField] = &[ CompTLField::std_field(field0,LifetimeRange::EMPTY,0), @@ -1341,7 +1341,7 @@ macro_rules! impl_stableabi_for_unit_struct { } impl_stableabi_for_unit_struct! { - PhantomPinned,"PhantomPinned",ItemInfo::std_type_in(nul_str!("std::marker")) + PhantomPinned,"PhantomPinned",ItemInfo::std_type_in(nulstr_trunc!("std::marker")) } ///////////// @@ -1356,7 +1356,7 @@ unsafe impl StableAbi for core_extensions::Void { const MONO_TYPE_LAYOUT: &MonoTypeLayout = &MonoTypeLayout::new( *mono_shared_vars, rstr!("Void"), - ItemInfo::package_and_mod("core_extensions;0.0.0", nul_str!("core_extensions")), + ItemInfo::package_and_mod("core_extensions;0.0.0", nulstr_trunc!("core_extensions")), MonoTLData::Enum(MonoTLEnum::new( StartLen::EMPTY, RSlice::EMPTY, diff --git a/abi_stable/src/derive_macro_reexports.rs b/abi_stable/src/derive_macro_reexports.rs index 45be9ffa..bfdc8a7b 100644 --- a/abi_stable/src/derive_macro_reexports.rs +++ b/abi_stable/src/derive_macro_reexports.rs @@ -50,6 +50,10 @@ pub use std::{ ptr::NonNull, }; +pub use str; + +pub use std::concat; + pub use repr_offset::offset_calc::next_field_offset; pub use core_extensions::{ diff --git a/abi_stable/src/macros.rs b/abi_stable/src/macros.rs index b4752501..d19de101 100644 --- a/abi_stable/src/macros.rs +++ b/abi_stable/src/macros.rs @@ -1,6 +1,9 @@ #[macro_use] mod internal; +#[macro_use] +mod nul_str_macros; + /** Use this when constructing a [`MonoTypeLayout`] when manually implementing StableAbi. @@ -117,7 +120,7 @@ macro_rules! tl_genparams { $crate::type_layout::StartLenConverter( ($($const_p)?) ).to_start_len(); CompGenericParams::new( - $crate::nul_str!($(stringify!($lt),",",)*), + $crate::nulstr_trunc!($crate::pmr::concat!($(stringify!($lt),",",)*)), $crate::tl_genparams!(count; $($lt),* ), ty_param_range, const_param_range, @@ -479,7 +482,7 @@ macro_rules! make_item_info { $crate::type_layout::ItemInfo::new( concat!(env!("CARGO_PKG_NAME"), ";", env!("CARGO_PKG_VERSION")), line!(), - $crate::type_layout::ModPath::inside($crate::nul_str!(module_path!())), + $crate::type_layout::ModPath::inside($crate::nulstr_trunc!(module_path!())), ) }; } @@ -718,32 +721,6 @@ macro_rules! rstr { }}; } -/** -Constructs a [`NulStr`] from a string literal. - -[`NulStr`]: ./sabi_types/struct.NulStr.html - -# Example - -``` -use abi_stable::{ - sabi_types::NulStr, - nul_str, -}; - -assert_eq!( nul_str!("Huh?").to_str_with_nul(), "Huh?\0" ); -assert_eq!( nul_str!("Hello!").to_str_with_nul(), "Hello!\0" ); - - -``` -*/ -#[macro_export] -macro_rules! nul_str { - ( $($str:expr),* $(,)* ) => {unsafe{ - $crate::sabi_types::NulStr::from_str(concat!($($str,)* "\0")) - }} -} - /** Constructs a RStr with the concatenation of the passed in strings, and variables with the range for the individual strings. diff --git a/abi_stable/src/macros/internal.rs b/abi_stable/src/macros/internal.rs index bbb8a0a4..072aa733 100644 --- a/abi_stable/src/macros/internal.rs +++ b/abi_stable/src/macros/internal.rs @@ -119,3 +119,29 @@ macro_rules! zst_assert { [(std::mem::align_of::>() != 1) as usize]; }}; } + +///////////////////////////////////////////////////////////////////////////////7 + +#[cfg(feature = "rust_1_46")] +macro_rules! const_fn_if_1_46 { + ( + $(#[$attr:meta])* + $vis:vis $(unsafe $(@$unsafe:tt@)?)? fn $($rem:tt)* + ) => { + $(#[$attr])* + $vis const $(unsafe $(@$unsafe@)?)? fn $($rem)* + }; +} + +#[cfg(not(feature = "rust_1_46"))] +macro_rules! const_fn_if_1_46 { + ( + $(#[$attr:meta])* + $vis:vis $(unsafe $(@$unsafe:tt@)?)? fn $($rem:tt)* + ) => { + $(#[$attr])* + $vis $(unsafe $(@$unsafe@)?)? fn $($rem)* + }; +} + +///////////////////////////////////////////////////////////////////////////////7 diff --git a/abi_stable/src/macros/nul_str_macros.rs b/abi_stable/src/macros/nul_str_macros.rs new file mode 100644 index 00000000..8096525c --- /dev/null +++ b/abi_stable/src/macros/nul_str_macros.rs @@ -0,0 +1,90 @@ +/// Constructs a [`NulStr`] from a string literal. +/// +/// # Correctness +/// +/// This truncates the passed in string if it contains nul bytes, +/// which means that silent truncation can happen with arbitrary inputs, +/// rather than compile-time errors. +/// +/// [`NulStr`]: ./sabi_types/struct.NulStr.html +/// +#[deprecated( + since = "0.10.3", + note = "Use either `nulstr` or `nulstr_trunc` instead" +)] +#[macro_export] +macro_rules! nul_str { + ( $($str:expr),* $(,)* ) => ({ + const __STR_NHPMWYD3NJA: $crate::sabi_types::NulStr<'_> = + $crate::sabi_types::NulStr::from_str(concat!($($str,)* "\0")); + __STR_NHPMWYD3NJA + }) +} + +/// Constructs a [`NulStr`] from a string literal. +/// +/// # Correctness +/// +/// This truncates the passed in string if it contains nul bytes, +/// which means that silent truncation can happen with arbitrary inputs, +/// rather than compile-time errors. +/// +/// # Example +/// +/// ```rust +/// use abi_stable::nulstr_trunc; +/// +/// assert_eq!( nulstr_trunc!("Huh?").to_str_with_nul(), "Huh?\0" ); +/// +/// assert_eq!( nulstr_trunc!("Hello!").to_str_with_nul(), "Hello!\0" ); +/// +/// assert_eq!( nulstr_trunc!("Hello\0, world!").to_str_with_nul(), "Hello\0" ); +/// +/// ``` +/// +/// [`NulStr`]: ./sabi_types/struct.NulStr.html +#[macro_export] +macro_rules! nulstr_trunc { + ($str:expr $(,)*) => { + $crate::sabi_types::NulStr::from_str($crate::pmr::concat!($str, "\0")) + }; +} + +/// Constructs a [`NulStr`] from a string literal. +/// +/// # Error +/// +/// This causes a compile-time error if the input string contains nul byte(s). +/// +/// # Example +/// +/// ```rust +/// use abi_stable::nulstr; +/// +/// assert_eq!( nulstr!("Huh?").to_str_with_nul(), "Huh?\0" ); +/// assert_eq!( nulstr!("Hello!").to_str_with_nul(), "Hello!\0" ); +/// ``` +/// +/// Nul bytes in the middle of the string cause compilation errors: +/// ```compile_fail +/// use abi_stable::nulstr; +/// +/// assert_eq!( nulstr!("Hello\0, world!").to_str_with_nul(), "Hello\0" ); +/// ``` +/// +/// [`NulStr`]: ./sabi_types/struct.NulStr.html +#[macro_export] +#[cfg(feature = "rust_1_46")] +#[cfg_attr(feature = "docsrs", doc(cfg(feature = "rust_1_46")))] +macro_rules! nulstr { + ($str:expr $(,)*) => {{ + const __STR_NHPMWYD3NJA: &$crate::pmr::str = $crate::pmr::concat!($str, "\0"); + + { + use $crate::sabi_types::NulStr; + const _CHECK: NulStr<'_> = NulStr::__try_from_str_unwrapping(__STR_NHPMWYD3NJA); + + _CHECK + } + }}; +} diff --git a/abi_stable/src/sabi_types.rs b/abi_stable/src/sabi_types.rs index 1fec9d4b..7959bdd6 100644 --- a/abi_stable/src/sabi_types.rs +++ b/abi_stable/src/sabi_types.rs @@ -20,7 +20,7 @@ pub use self::{ late_static_ref::LateStaticRef, maybe_cmp::MaybeCmp, move_ptr::MovePtr, - nul_str::NulStr, + nul_str::{NulStr, NulStrError}, rmut::RMut, rref::RRef, rsmallbox::RSmallBox, diff --git a/abi_stable/src/sabi_types/nul_str.rs b/abi_stable/src/sabi_types/nul_str.rs index 0a68cfb4..fe34b450 100644 --- a/abi_stable/src/sabi_types/nul_str.rs +++ b/abi_stable/src/sabi_types/nul_str.rs @@ -36,22 +36,92 @@ unsafe impl Send for NulStr<'_> {} impl NulStr<'static> { /// An empty string. - pub const EMPTY: Self = NulStr { - ptr: ref_as_nonnull(&0), - _marker: PhantomData, - }; + pub const EMPTY: Self = NulStr::from_str("\0"); } impl<'a> NulStr<'a> { - /// Constructs an NulStr from a slice. + /// Constructs an `NulStr` from a string slice. /// - /// # Safety + /// # Correctness /// - /// `str` must be nul terminated(a 0 byte). - pub const unsafe fn from_str(str: &'a str) -> Self { - Self { - ptr: NonNull::new_unchecked(str.as_ptr() as *mut u8), - _marker: PhantomData, + /// If the string contains interior nuls, + /// the first nul will be considered the string terminator. + /// + /// # Panics + /// + /// This panics when the string does not end with `'\0'`. + pub const fn from_str(str: &'a str) -> Self { + let this = unsafe { + Self { + ptr: NonNull::new_unchecked(str.as_ptr() as *mut u8), + _marker: PhantomData, + } + }; + + let last_byte = str.as_bytes()[str.len() - 1] as usize; + [this /* expected a nul terminator */][last_byte] + } + + const_fn_if_1_46! { + /// Constructs an NulStr from a string slice. + /// + /// # Cosntness + /// + /// This is a `const fn` if the `"rust_1_46"` feature is enabled, + /// otherwise it is a non-`const` function. + /// + /// # Errors + /// + /// This returns a `NulStrError::NoNulTerminator` when the string does not end + /// with `'\0'`. + /// + /// This returns a `NulStrError::InnerNul` when the string contains a + /// `'\0'` before the `'\0'` terminator. + /// + /// # Example + /// + /// ```rust + /// use abi_stable::sabi_types::{NulStr, NulStrError}; + /// + /// assert_eq!(NulStr::try_from_str("hello\0").unwrap().to_str(), "hello"); + /// + /// assert_eq!( + /// NulStr::try_from_str("hello\0world\0"), + /// Err(NulStrError::InnerNul{pos: 5}), + /// ); + /// + /// ``` + pub fn try_from_str(string: &'a str) -> Result { + let mut i = 0; + let mut bytes = string.as_bytes(); + let len = string.len(); + + bytes = match bytes { + [rem @ .., 0] => rem, + _ => return Err(NulStrError::NoNulTerminator), + }; + + while let [b, ref rem @ ..] = *bytes { + if b == 0 { + return Err(NulStrError::InnerNul {pos : i}); + } + i += 1; + bytes = rem; + } + + unsafe{ + Ok(NulStr::from_str(string)) + } + } + } + + #[doc(hidden)] + #[cfg(feature = "rust_1_46")] + pub const fn __try_from_str_unwrapping(s: &'a str) -> Self { + match Self::try_from_str(s) { + Ok(x) => x, + Err(NulStrError::InnerNul { pos }) => [/* encountered nul byte at `pos` */][pos], + Err(_) => [/* unreachable */][s.len()], } } @@ -138,3 +208,23 @@ impl Debug for NulStr<'_> { Debug::fmt(self.to_str(), f) } } + +#[derive(Debug, PartialEq, Clone)] +#[non_exhaustive] +pub enum NulStrError { + InnerNul { pos: usize }, + NoNulTerminator, +} + +impl Display for NulStrError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Self::InnerNul { pos } => { + write!(f, "there is an internal nul at the {} byte offset", pos) + } + Self::NoNulTerminator => f.write_str("there is no nul terminator in the string"), + } + } +} + +impl std::error::Error for NulStrError {} diff --git a/abi_stable/src/type_layout/tl_other.rs b/abi_stable/src/type_layout/tl_other.rs index eb413f24..0040c468 100644 --- a/abi_stable/src/type_layout/tl_other.rs +++ b/abi_stable/src/type_layout/tl_other.rs @@ -45,10 +45,10 @@ pub struct ModPath(NulStr<'static>); impl ModPath { /// An item without a path - pub const NO_PATH: Self = ModPath(nul_str!("")); + pub const NO_PATH: Self = ModPath(nulstr_trunc!("")); /// An item in the prelude. - pub const PRELUDE: Self = ModPath(nul_str!("")); + pub const PRELUDE: Self = ModPath(nulstr_trunc!("")); /// Constructs a ModPath from a string with a module path. pub const fn inside(path: NulStr<'static>) -> Self { From c1e0f9fc1f77e7ba907bc62ff56f8e986db4022f Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Tue, 5 Oct 2021 05:13:31 -0300 Subject: [PATCH 06/32] Added tests for NulStr. Added PartialEq impls for comparing `str` and `NulStr` in both directions. Made the `nulstr_trunc` macro evaluate the constructor call at compile-time Simplified the nulstr macro --- abi_stable/src/macros/nul_str_macros.rs | 18 ++-- abi_stable/src/sabi_types/nul_str.rs | 33 ++++++- abi_stable/src/sabi_types/nul_str/tests.rs | 108 +++++++++++++++++++++ 3 files changed, 146 insertions(+), 13 deletions(-) create mode 100644 abi_stable/src/sabi_types/nul_str/tests.rs diff --git a/abi_stable/src/macros/nul_str_macros.rs b/abi_stable/src/macros/nul_str_macros.rs index 8096525c..76d5f486 100644 --- a/abi_stable/src/macros/nul_str_macros.rs +++ b/abi_stable/src/macros/nul_str_macros.rs @@ -45,9 +45,11 @@ macro_rules! nul_str { /// [`NulStr`]: ./sabi_types/struct.NulStr.html #[macro_export] macro_rules! nulstr_trunc { - ($str:expr $(,)*) => { - $crate::sabi_types::NulStr::from_str($crate::pmr::concat!($str, "\0")) - }; + ($str:expr $(,)*) => {{ + const __STR_NHPMWYD3NJA: $crate::sabi_types::NulStr<'_> = + $crate::sabi_types::NulStr::from_str($crate::pmr::concat!($str, "\0")); + __STR_NHPMWYD3NJA + }}; } /// Constructs a [`NulStr`] from a string literal. @@ -78,13 +80,9 @@ macro_rules! nulstr_trunc { #[cfg_attr(feature = "docsrs", doc(cfg(feature = "rust_1_46")))] macro_rules! nulstr { ($str:expr $(,)*) => {{ - const __STR_NHPMWYD3NJA: &$crate::pmr::str = $crate::pmr::concat!($str, "\0"); - - { - use $crate::sabi_types::NulStr; - const _CHECK: NulStr<'_> = NulStr::__try_from_str_unwrapping(__STR_NHPMWYD3NJA); + const __STR_NHPMWYD3NJA: $crate::sabi_types::NulStr<'_> = + $crate::sabi_types::NulStr::__try_from_str_unwrapping($crate::pmr::concat!($str, "\0")); - _CHECK - } + __STR_NHPMWYD3NJA }}; } diff --git a/abi_stable/src/sabi_types/nul_str.rs b/abi_stable/src/sabi_types/nul_str.rs index fe34b450..a318c7cd 100644 --- a/abi_stable/src/sabi_types/nul_str.rs +++ b/abi_stable/src/sabi_types/nul_str.rs @@ -1,6 +1,9 @@ //! A nul-terminated string,which is just a pointer to the string data, //! it doesn't know the length of the string. +#[cfg(test)] +mod tests; + use crate::{std_types::RStr, utils::ref_as_nonnull}; use std::{ @@ -121,7 +124,7 @@ impl<'a> NulStr<'a> { match Self::try_from_str(s) { Ok(x) => x, Err(NulStrError::InnerNul { pos }) => [/* encountered nul byte at `pos` */][pos], - Err(_) => [/* unreachable */][s.len()], + Err(NulStrError::NoNulTerminator) => [/* there no nul-terminator */][s.len()], } } @@ -138,8 +141,8 @@ impl<'a> NulStr<'a> { } /// Gets a pointer to the start of this nul-terminated string. - pub const fn as_ptr(self) -> *const std::os::raw::c_char { - self.ptr.as_ptr() as _ + pub const fn as_ptr(self) -> *const u8 { + self.ptr.as_ptr() } /// Converts this `NulStr<'a>` to a `&'a str`,including the nul byte. @@ -189,6 +192,30 @@ impl<'a> NulStr<'a> { } } +impl<'a> PartialEq> for &str { + fn eq(&self, other: &NulStr<'a>) -> bool { + self.as_ptr() == other.as_ptr() || *self == other.to_str() + } +} + +impl<'a> PartialEq<&str> for NulStr<'a> { + fn eq(&self, other: &&str) -> bool { + self.as_ptr() == other.as_ptr() || self.to_str() == *other + } +} + +impl<'a> PartialEq> for str { + fn eq(&self, other: &NulStr<'a>) -> bool { + self.as_ptr() == other.as_ptr() || self == other.to_str() + } +} + +impl<'a> PartialEq for NulStr<'a> { + fn eq(&self, other: &str) -> bool { + self.as_ptr() == other.as_ptr() || self.to_str() == other + } +} + impl<'a> PartialEq for NulStr<'a> { fn eq(&self, other: &Self) -> bool { self.ptr == other.ptr || self.to_str() == other.to_str() diff --git a/abi_stable/src/sabi_types/nul_str/tests.rs b/abi_stable/src/sabi_types/nul_str/tests.rs new file mode 100644 index 00000000..2793cde6 --- /dev/null +++ b/abi_stable/src/sabi_types/nul_str/tests.rs @@ -0,0 +1,108 @@ +use crate::sabi_types::{NulStr, NulStrError}; + +use abi_stable_shared::{file_span, test_utils::must_panic}; + +fn from_str_with_constructor(func: fn(&str) -> NulStr<'_>) { + let pairs = [("fob\0", "fob"), ("fo\0", "fo"), ("f\0", "f"), ("\0", "")]; + for (strwn, str) in pairs.iter().copied() { + dbg!(strwn); + let this = func(strwn); + assert_eq!(this.as_ptr(), strwn.as_ptr()); + assert_eq!(this.to_str(), str); + assert_eq!(this.to_rstr(), str); + assert_eq!(this.to_str_with_nul(), strwn); + assert_eq!(this.to_rstr_with_nul(), strwn); + } + + for &strwn in &["foo\0", "foo\0bar\0"] { + dbg!(strwn); + let this = func(strwn); + assert_eq!(this.as_ptr(), strwn.as_ptr()); + assert_eq!(this.to_str(), "foo"); + assert_eq!(this.to_rstr(), "foo"); + assert_eq!(this.to_str_with_nul(), "foo\0"); + assert_eq!(this.to_rstr_with_nul(), "foo\0"); + } +} + +#[test] +fn nulstr_from_str_tests() { + must_panic(file_span!(), || NulStr::from_str("foo\0bar")).unwrap(); + must_panic(file_span!(), || NulStr::from_str("foo")).unwrap(); + must_panic(file_span!(), || NulStr::from_str("")).unwrap(); + + from_str_with_constructor(|s| NulStr::from_str(s)); + from_str_with_constructor(|s| unsafe { NulStr::from_ptr(s.as_ptr()) }); +} + +#[test] +fn nulstr_try_from_str_tests() { + let pairs = [("foobar\0", "foobar"), ("f\0", "f"), ("\0", "")]; + for (strwn, str) in pairs.iter().copied() { + let nuls = [ + NulStr::try_from_str(strwn).unwrap(), + NulStr::__try_from_str_unwrapping(strwn), + ]; + for &nul in &nuls { + assert_eq!(nul.to_str(), str); + assert_eq!(nul.to_str_with_nul(), strwn); + } + } + + let err_pairs = vec![ + ("foo\0bar\0", NulStrError::InnerNul { pos: 3 }), + ("fo\0\0", NulStrError::InnerNul { pos: 2 }), + ("f\0\0", NulStrError::InnerNul { pos: 1 }), + ("\0\0", NulStrError::InnerNul { pos: 0 }), + ("foobar", NulStrError::NoNulTerminator), + ("", NulStrError::NoNulTerminator), + ]; + + for (strwn, err) in err_pairs { + dbg!(strwn); + assert_eq!(NulStr::try_from_str(strwn), Err(err)); + + must_panic(file_span!(), || NulStr::__try_from_str_unwrapping(strwn)).unwrap(); + } +} + +#[test] +fn nulstr_eq_test() { + let strings = [ + "\0", "f\0", "fo\0", "foc\0", "foca\0", "focal\0", "foo\0", "fooo\0", "foooo\0", "bar\0", + "barr\0", "barrr\0", "baz\0", "bazz\0", "bazzz\0", + ] + .iter() + .map(|&x| (x, NulStr::from_str(x))) + .collect::)>>(); + + for &(leftwn, left) in &strings { + assert_eq!(left, left); + + { + let x = leftwn.trim_end_matches('\0'); + + assert_eq!(left, x); + assert_eq!(left, *x); + assert_eq!(x, left); + assert_eq!(*x, left); + assert_eq!(left.to_str_with_nul(), leftwn); + } + + // making sure that NulStr doesn't just do pointer equality + let left_copywn = leftwn.to_string(); + let left_copy = NulStr::from_str(&left_copywn); + assert_eq!(left, left_copy); + assert_eq!(left_copy, left); + + for &(_, right) in &strings { + assert_eq!( + left == right, + left.to_str() == right.to_str(), + "\n left: {:?}\nright: {:?}\n", + left, + right, + ); + } + } +} From 36145f35e7f5c3c4bef1acc8058b20c128f16a70 Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Tue, 5 Oct 2021 17:23:14 -0300 Subject: [PATCH 07/32] Added doc examples to NulStr Changed safety requirements of NulStr to not require no internal nul bytes. --- abi_stable/src/sabi_types/nul_str.rs | 146 ++++++++++++++++++++++++++- 1 file changed, 144 insertions(+), 2 deletions(-) diff --git a/abi_stable/src/sabi_types/nul_str.rs b/abi_stable/src/sabi_types/nul_str.rs index a318c7cd..4616f483 100644 --- a/abi_stable/src/sabi_types/nul_str.rs +++ b/abi_stable/src/sabi_types/nul_str.rs @@ -24,9 +24,45 @@ use std::{ /// `NulStr` has these safety requirement: /// - the string must be valid to read for the `'a` lifetime /// - the string must be utf8 encoded -/// - the string must be nul terminated and not contain interior nul bytes +/// - the string must be nul terminated /// - the string must not be mutated while this is alive /// (the same semantics as `&` references) +/// +/// # Example +/// +/// ### Passing to extern function +/// +/// You can pass `NulStr` to C functions expecting a nul-terminated string. +/// +/// ```rust +/// use abi_stable::sabi_types::NulStr; +/// +/// extern "C" { +/// // the signature in the C side is `uint64_t add_digits(const char*)` +/// fn add_digits(_: NulStr<'_>) -> u64; +/// } +/// # #[export_name = "add_digits"] +/// # pub extern "C" fn add_digits___(str: NulStr<'_>) -> u64 { +/// # str.to_str().bytes() +/// # .filter_map(|x|{ +/// # match x { +/// # b'0'..=b'9' => Some(u64::from(x - b'0')), +/// # _ => None, +/// # } +/// # }) +/// # .sum() +/// # } +/// +/// # fn main() { +/// const FOO: NulStr<'_> = NulStr::from_str("1.2.3\0"); +/// const BAR: NulStr<'_> = NulStr::from_str("12|34\0"); +/// const QUX: NulStr<'_> = NulStr::from_str("123_abcd_45\0"); +/// +/// assert_eq!(unsafe{ add_digits(FOO) }, 6); +/// assert_eq!(unsafe{ add_digits(BAR) }, 10); +/// assert_eq!(unsafe{ add_digits(QUX) }, 15); +/// # } +/// ``` #[repr(transparent)] #[derive(Copy, Clone, StableAbi)] pub struct NulStr<'a> { @@ -53,6 +89,26 @@ impl<'a> NulStr<'a> { /// # Panics /// /// This panics when the string does not end with `'\0'`. + /// + /// # Example + /// + /// ```rust + /// use abi_stable::sabi_types::NulStr; + /// + /// const FOO: NulStr<'_> = NulStr::from_str("foo\0"); + /// // `NulStr`s can be compared with `str`s + /// assert_eq!(FOO, "foo"); + /// + /// const BAR: NulStr<'_> = NulStr::from_str("bar\0"); + /// assert_eq!(BAR, "bar"); + /// + /// const HEWWO: NulStr<'_> = NulStr::from_str("Hello, world!\0"); + /// assert_eq!(HEWWO, "Hello, world!"); + /// + /// const TRUNCATED: NulStr<'_> = NulStr::from_str("baz\0world!\0"); + /// assert_eq!(TRUNCATED, "baz"); + /// + /// ``` pub const fn from_str(str: &'a str) -> Self { let this = unsafe { Self { @@ -86,7 +142,8 @@ impl<'a> NulStr<'a> { /// ```rust /// use abi_stable::sabi_types::{NulStr, NulStrError}; /// - /// assert_eq!(NulStr::try_from_str("hello\0").unwrap().to_str(), "hello"); + /// // `NulStr`s can be compared with `str`s + /// assert_eq!(NulStr::try_from_str("hello\0").unwrap(), "hello"); /// /// assert_eq!( /// NulStr::try_from_str("hello\0world\0"), @@ -133,6 +190,30 @@ impl<'a> NulStr<'a> { /// # Safety /// /// [The same as the type-level safety docs](#safety) + /// + /// # Correctness + /// + /// If the string contains interior nuls, + /// the first nul will be considered the string terminator. + /// + /// # Example + /// + /// ```rust + /// use abi_stable::sabi_types::NulStr; + /// + /// const FOO: NulStr<'_> = unsafe{ NulStr::from_ptr("foo\0".as_ptr()) }; + /// assert_eq!(FOO, "foo"); + /// + /// const BAR: NulStr<'_> = unsafe{ NulStr::from_ptr("bar\0".as_ptr()) }; + /// assert_eq!(BAR, "bar"); + /// + /// const HEWWO: NulStr<'_> = unsafe{ NulStr::from_ptr("Hello, world!\0".as_ptr()) }; + /// assert_eq!(HEWWO, "Hello, world!"); + /// + /// const TRUNCATED: NulStr<'_> = unsafe{ NulStr::from_ptr("baz\0world!\0".as_ptr()) }; + /// assert_eq!(TRUNCATED, "baz"); + /// + /// ``` pub const unsafe fn from_ptr(ptr: *const u8) -> Self { Self { ptr: NonNull::new_unchecked(ptr as *mut u8), @@ -141,6 +222,17 @@ impl<'a> NulStr<'a> { } /// Gets a pointer to the start of this nul-terminated string. + /// + /// # Example + /// + /// ```rust + /// use abi_stable::sabi_types::NulStr; + /// + /// let foo_str = "foo\0"; + /// let foo = NulStr::from_str(foo_str); + /// assert_eq!(foo.as_ptr(), foo_str.as_ptr()); + /// + /// ``` pub const fn as_ptr(self) -> *const u8 { self.ptr.as_ptr() } @@ -151,6 +243,18 @@ impl<'a> NulStr<'a> { /// /// This conversion requires traversing through the entire string to /// find the nul byte. + /// + /// # Example + /// + /// ```rust + /// use abi_stable::sabi_types::NulStr; + /// + /// const FOO: NulStr<'_> = NulStr::from_str("foo bar\0"); + /// let foo: &str = FOO.to_str_with_nul(); + /// assert_eq!(&foo[..3], "foo"); + /// assert_eq!(&foo[4..], "bar\0"); + /// + /// ``` pub fn to_str_with_nul(&self) -> &'a str { unsafe { let bytes = std::ffi::CStr::from_ptr(self.ptr.as_ptr() as *const _).to_bytes_with_nul(); @@ -164,6 +268,19 @@ impl<'a> NulStr<'a> { /// /// This conversion requires traversing through the entire string to /// find the nul byte. + /// + /// # Example + /// + /// ```rust + /// use abi_stable::sabi_types::NulStr; + /// use abi_stable::std_types::RStr; + /// + /// const BAZ: NulStr<'_> = NulStr::from_str("baz qux\0"); + /// let baz: RStr<'_> = BAZ.to_rstr_with_nul(); + /// assert_eq!(&baz[..3], "baz"); + /// assert_eq!(&baz[4..], "qux\0"); + /// + /// ``` pub fn to_rstr_with_nul(&self) -> RStr<'a> { self.to_str_with_nul().into() } @@ -174,6 +291,18 @@ impl<'a> NulStr<'a> { /// /// This conversion requires traversing through the entire string to /// find the nul byte. + /// + /// # Example + /// + /// ```rust + /// use abi_stable::sabi_types::NulStr; + /// + /// const FOO: NulStr<'_> = NulStr::from_str("foo bar\0"); + /// let foo: &str = FOO.to_str(); + /// assert_eq!(&foo[..3], "foo"); + /// assert_eq!(&foo[4..], "bar"); + /// + /// ``` pub fn to_str(self) -> &'a str { unsafe { let bytes = std::ffi::CStr::from_ptr(self.ptr.as_ptr() as *const _).to_bytes(); @@ -187,6 +316,19 @@ impl<'a> NulStr<'a> { /// /// This conversion requires traversing through the entire string to /// find the nul byte. + /// + /// # Example + /// + /// ```rust + /// use abi_stable::sabi_types::NulStr; + /// use abi_stable::std_types::RStr; + /// + /// const BAZ: NulStr<'_> = NulStr::from_str("baz qux\0"); + /// let baz: RStr<'_> = BAZ.to_rstr(); + /// assert_eq!(&baz[..3], "baz"); + /// assert_eq!(&baz[4..], "qux"); + /// + /// ``` pub fn to_rstr(self) -> RStr<'a> { self.to_str().into() } From 1926de6f389c1911c2f56b950ad11b5fc267c8d9 Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Wed, 6 Oct 2021 00:12:03 -0300 Subject: [PATCH 08/32] Added Default, PartialOrd, and Ord impls for NulStr. --- abi_stable/src/sabi_types/nul_str.rs | 36 ++++++++++++++++++++-- abi_stable/src/sabi_types/nul_str/tests.rs | 18 ++++++++++- 2 files changed, 50 insertions(+), 4 deletions(-) diff --git a/abi_stable/src/sabi_types/nul_str.rs b/abi_stable/src/sabi_types/nul_str.rs index 4616f483..d006010b 100644 --- a/abi_stable/src/sabi_types/nul_str.rs +++ b/abi_stable/src/sabi_types/nul_str.rs @@ -7,7 +7,7 @@ mod tests; use crate::{std_types::RStr, utils::ref_as_nonnull}; use std::{ - cmp::{Eq, PartialEq}, + cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}, fmt::{self, Debug, Display}, marker::PhantomData, ptr::NonNull, @@ -131,10 +131,10 @@ impl<'a> NulStr<'a> { /// /// # Errors /// - /// This returns a `NulStrError::NoNulTerminator` when the string does not end + /// This returns a [`NulStrError::NoNulTerminator`] when the string does not end /// with `'\0'`. /// - /// This returns a `NulStrError::InnerNul` when the string contains a + /// This returns a [`NulStrError::InnerNul`] when the string contains a /// `'\0'` before the `'\0'` terminator. /// /// # Example @@ -151,6 +151,9 @@ impl<'a> NulStr<'a> { /// ); /// /// ``` + /// + /// [`NulStrError::InnerNul`]: enum.NulStrError.html#variant.InnerNul + /// [`NulStrError::NoNulTerminator`]: enum.NulStrError.html#variant.NoNulTerminator pub fn try_from_str(string: &'a str) -> Result { let mut i = 0; let mut bytes = string.as_bytes(); @@ -366,6 +369,28 @@ impl<'a> PartialEq for NulStr<'a> { impl<'a> Eq for NulStr<'a> {} +impl<'a> PartialOrd for NulStr<'a> { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl<'a> Ord for NulStr<'a> { + fn cmp(&self, other: &Self) -> Ordering { + if self.ptr == other.ptr { + Ordering::Equal + } else { + self.to_str().cmp(other.to_str()) + } + } +} + +impl Default for NulStr<'_> { + fn default() -> Self { + NulStr::EMPTY + } +} + impl Display for NulStr<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Display::fmt(self.to_str(), f) @@ -378,10 +403,15 @@ impl Debug for NulStr<'_> { } } +/// Error from trying to convert a `&str` to a [`NulStr`] +/// +/// [`NulStr`]: ./struct.NulStr.html #[derive(Debug, PartialEq, Clone)] #[non_exhaustive] pub enum NulStrError { + /// When the string has a `'\0'` before the end. InnerNul { pos: usize }, + /// When the string doesn't end with `'\0'` NoNulTerminator, } diff --git a/abi_stable/src/sabi_types/nul_str/tests.rs b/abi_stable/src/sabi_types/nul_str/tests.rs index 2793cde6..038e97a2 100644 --- a/abi_stable/src/sabi_types/nul_str/tests.rs +++ b/abi_stable/src/sabi_types/nul_str/tests.rs @@ -2,6 +2,8 @@ use crate::sabi_types::{NulStr, NulStrError}; use abi_stable_shared::{file_span, test_utils::must_panic}; +use std::cmp::{Ord, Ordering, PartialOrd}; + fn from_str_with_constructor(func: fn(&str) -> NulStr<'_>) { let pairs = [("fob\0", "fob"), ("fo\0", "fo"), ("f\0", "f"), ("\0", "")]; for (strwn, str) in pairs.iter().copied() { @@ -67,7 +69,7 @@ fn nulstr_try_from_str_tests() { } #[test] -fn nulstr_eq_test() { +fn nulstr_cmp_test() { let strings = [ "\0", "f\0", "fo\0", "foc\0", "foca\0", "focal\0", "foo\0", "fooo\0", "foooo\0", "bar\0", "barr\0", "barrr\0", "baz\0", "bazz\0", "bazzz\0", @@ -79,6 +81,9 @@ fn nulstr_eq_test() { for &(leftwn, left) in &strings { assert_eq!(left, left); + assert_eq!(left.cmp(&left), Ordering::Equal); + assert_eq!(left.partial_cmp(&left), Some(Ordering::Equal)); + { let x = leftwn.trim_end_matches('\0'); @@ -95,6 +100,11 @@ fn nulstr_eq_test() { assert_eq!(left, left_copy); assert_eq!(left_copy, left); + assert_eq!(left.cmp(&left_copy), Ordering::Equal); + assert_eq!(left_copy.cmp(&left), Ordering::Equal); + assert_eq!(left.partial_cmp(&left_copy), Some(Ordering::Equal)); + assert_eq!(left_copy.partial_cmp(&left), Some(Ordering::Equal)); + for &(_, right) in &strings { assert_eq!( left == right, @@ -103,6 +113,12 @@ fn nulstr_eq_test() { left, right, ); + + assert_eq!(left.cmp(&right), left.to_str().cmp(right.to_str())); + assert_eq!( + left.partial_cmp(&right), + left.to_str().partial_cmp(right.to_str()) + ); } } } From b1847231ed3d5972d2779f92bfa55f944a436702 Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Wed, 6 Oct 2021 03:57:42 -0300 Subject: [PATCH 09/32] Changed root module loading. Changed root module loading so that the library is leaked after type checking, but before the root module loader is called. Beforehand it was only leaked if the root module loader runs successfully. Added documentation in `abi_stable::library` what happens to load the root module. Added `LibHeader::ensure_layout` method. Improved docs for: - `ROOT_MODULE_LOADER_NAME` constant - `#[export_root_module]` attribute. --- abi_stable/src/library.rs | 57 ++++++++++++++----- abi_stable/src/library/errors.rs | 2 +- abi_stable/src/library/lib_header.rs | 28 ++++++++- abi_stable/src/library/root_mod_trait.rs | 39 +++++++++---- abi_stable/src/macros/nul_str_macros.rs | 3 +- .../export_root_module.rs | 34 ++++++----- 6 files changed, 117 insertions(+), 46 deletions(-) diff --git a/abi_stable/src/library.rs b/abi_stable/src/library.rs index 84d8670b..cab99173 100644 --- a/abi_stable/src/library.rs +++ b/abi_stable/src/library.rs @@ -1,7 +1,30 @@ -/*! -Traits and types related to loading an abi_stable dynamic library, -as well as functions/modules within. -*/ +//! Traits and types related to loading an abi_stable dynamic library, +//! as well as functions/modules within. +//! +//! # Loading the root module +//! +//! When you use the [`RootModule`]`::load_from*` associated functions, +//! the root module of a library is loaded in this order: +//! 1. A [`RawLibrary`] is loaded +//! 2. An [`AbiHeaderRef`] handle to the static that contains the root module is obtained. +//! 3. The [`AbiHeaderRef`] checks that the abi_stable version used by that library is +//! compatible with the loader's, upgrading to a [`&'static LibHeader`] on success. +//! 4. The [`LibHeader`] checks that the layout of the types in the root module +//! (and everything it references) are compatible with the loader's +//! 5. The library is leaked so that the root module loader can +//! do anything incompatible with library unloading. +//! 6. The [root module](./trait.RootModule.html) +//! is loaded using the function from the loaded library +//! that was annotated with [`#[export_root_module]`](../attr.export_root_module.html). +//! 7. [`RootModule::initialize`] is called on the root module. +//! +//! All steps (except for step 5) can return errors. +//! +//! [`RawLibrary`]: ./struct.RawLibrary.html +//! [`AbiHeaderRef`]: ./struct.AbiHeaderRef.html +//! [`RootModule`]: ./trait.RootModule.html +//! [`RootModule::initialize`]: ./trait.RootModule.html#method.initialization +//! [`&'static LibHeader`]: ./struct.LibHeader.html use std::{ convert::Infallible, @@ -105,9 +128,13 @@ pub struct RootModuleStatics { } impl RootModuleStatics { + /// + /// # Safety + /// + /// This must only be called from the `abi_stable::declare_root_module_statics` macro. #[doc(hidden)] #[inline] - pub const fn _private_new() -> Self { + pub const unsafe fn __private_new() -> Self { Self { root_mod: LateStaticRef::new(), raw_lib: LateStaticRef::new(), @@ -203,8 +230,9 @@ macro_rules! declare_root_module_statics { ( $this:ty ) => ( #[inline] fn root_module_statics()->&'static $crate::library::RootModuleStatics<$this>{ - static _ROOT_MOD_STATICS:$crate::library::RootModuleStatics<$this>= - $crate::library::RootModuleStatics::_private_new(); + static _ROOT_MOD_STATICS:$crate::library::RootModuleStatics<$this>= unsafe{ + $crate::library::RootModuleStatics::__private_new() + }; &_ROOT_MOD_STATICS } @@ -224,17 +252,18 @@ pub fn mangled_root_module_loader_name() -> String { abi_stable_derive::__const_mangled_root_module_loader_name! {} -/// The name of the `static` that contains the [`AbiHeader`] of an abi_stable library. +/// The name of the `static` that contains the [`LibHeader`] of an abi_stable library. /// -/// You can get a handle to that [`AbiHeader`] using -/// [abi_header_from_path](fn.abi_header_from_path.html) or -/// [abi_header_from_raw_library](fn.abi_header_from_raw_library.html). -/// -/// If you need a nul-terminated string, -/// you can use [`ROOT_MODULE_LOADER_NAME_WITH_NUL`] instead. +/// There's also these alternatives to this constant: +/// - [`ROOT_MODULE_LOADER_NAME_WITH_NUL`]: this constant concatenated with `"\0"` +/// - [`ROOT_MODULE_LOADER_NAME_NULSTR`]: a [`NulStr`] equivalent of this constant /// /// [`LibHeader`]: ./struct.LibHeader.html +/// [`AbiHeaderRef`]: ./struct.AbiHeaderRef.html +/// [`AbiHeaderRef::upgrade`]: ./struct.AbiHeaderRef.html#method.upgrade /// [`ROOT_MODULE_LOADER_NAME_WITH_NUL`]: ./constant.ROOT_MODULE_LOADER_NAME_WITH_NUL.html +/// [`ROOT_MODULE_LOADER_NAME_NULSTR`]: ./constant.ROOT_MODULE_LOADER_NAME_NULSTR.html +/// [`NulStr`]: ../sabi_types/struct.NulStr.html pub const ROOT_MODULE_LOADER_NAME: &str = PRIV_MANGLED_ROOT_MODULE_LOADER_NAME; /// A nul-terminated equivalent of [`ROOT_MODULE_LOADER_NAME`]. diff --git a/abi_stable/src/library/errors.rs b/abi_stable/src/library/errors.rs index d3d4c274..12c091ec 100644 --- a/abi_stable/src/library/errors.rs +++ b/abi_stable/src/library/errors.rs @@ -193,7 +193,7 @@ impl ::std::error::Error for RootModuleError {} ////////////////////////////////////////////////////////////////////// /// For converting the return value of a `#[export_root_module]` function -/// to a `Result<(), RootModuleError>`. +/// to a `Result<_, RootModuleError>`. pub trait IntoRootModuleResult { /// The module that is loaded in the success case. type Module: RootModule; diff --git a/abi_stable/src/library/lib_header.rs b/abi_stable/src/library/lib_header.rs index 514381fa..c866575e 100644 --- a/abi_stable/src/library/lib_header.rs +++ b/abi_stable/src/library/lib_header.rs @@ -191,8 +191,7 @@ impl LibHeader { .map_err(RootModuleError::into_library_error::) } - /// Gets the root module,first - /// checking that the layout of the `M` from the dynamic library is + /// Checks that the layout of the `M` root module from the dynamic library is /// compatible with the expected layout. /// /// # Errors @@ -205,7 +204,7 @@ impl LibHeader { /// - `LibraryError::RootModule` : /// If the root module initializer returned an error or panicked. /// - pub fn check_layout(&self) -> Result + pub fn ensure_layout(&self) -> Result<(), LibraryError> where M: RootModule, { @@ -231,6 +230,29 @@ impl LibHeader { atomic::compiler_fence(atomic::Ordering::SeqCst); + Ok(()) + } + + /// Gets the root module,first + /// checking that the layout of the `M` from the dynamic library is + /// compatible with the expected layout. + /// + /// # Errors + /// + /// This returns these errors: + /// + /// - `LibraryError::AbiInstability`: + /// If the layout of the root module is not the expected one. + /// + /// - `LibraryError::RootModule` : + /// If the root module initializer returned an error or panicked. + /// + pub fn check_layout(&self) -> Result + where + M: RootModule, + { + self.ensure_layout::()?; + unsafe { self.unchecked_layout() .map_err(RootModuleError::into_library_error::) diff --git a/abi_stable/src/library/root_mod_trait.rs b/abi_stable/src/library/root_mod_trait.rs index 71a8a0db..afc967ca 100644 --- a/abi_stable/src/library/root_mod_trait.rs +++ b/abi_stable/src/library/root_mod_trait.rs @@ -143,7 +143,8 @@ pub trait RootModule: Sized + StableAbi + PrefixRefTrait + 'static { # Warning If this function is called within a dynamic library, - it must be called at or after the function that exports its root module is called. + it must be called either within the root module loader function or + after that function has been called. **DO NOT** call this in the static initializer of a dynamic library, since this library relies on setting up its global state before @@ -179,17 +180,31 @@ pub trait RootModule: Sized + StableAbi + PrefixRefTrait + 'static { fn load_from(where_: LibraryPath<'_>) -> Result { let statics = Self::root_module_statics(); statics.root_mod.try_init(|| { - let raw_library = load_raw_library::(where_)?; - let items = unsafe { lib_header_from_raw_library(&raw_library)? }; - - let root_mod = items.init_root_module::()?.initialization()?; - - // Important,If I don't leak the library after sucessfully loading the root module - // it would cause any use of the module to be a use after free. - let raw_lib = leak_value(raw_library); - statics.raw_lib.init(|| raw_lib); - - Ok(root_mod) + let mut items_ = None; + statics.raw_lib.try_init(|| -> Result<_, LibraryError> { + let raw_library = load_raw_library::(where_)?; + let items = unsafe { lib_header_from_raw_library(&raw_library)? }; + + items.ensure_layout::()?; + items_ = Some(items); + + // if the library isn't leaked + // it would cause any use of the module to be a use after free. + // + // By leaking the library after type checking, + // but before calling the root module loader, + // this allows the root module loader to do anything that'd prevent + // sound library unloading. + // Nothing that can be done about static initializers that prevent + // library unloading though <_<. + Ok(leak_value(raw_library)) + })?; + + items_ + .as_ref() + .unwrap() + .init_root_module_with_unchecked_layout::()? + .initialization() }) } diff --git a/abi_stable/src/macros/nul_str_macros.rs b/abi_stable/src/macros/nul_str_macros.rs index 76d5f486..d9dfcd85 100644 --- a/abi_stable/src/macros/nul_str_macros.rs +++ b/abi_stable/src/macros/nul_str_macros.rs @@ -21,7 +21,8 @@ macro_rules! nul_str { }) } -/// Constructs a [`NulStr`] from a string literal. +/// Constructs a [`NulStr`] from a string literal, +/// truncating the string on internal nul bytes. /// /// # Correctness /// diff --git a/abi_stable/src/proc_macro_reexports/export_root_module.rs b/abi_stable/src/proc_macro_reexports/export_root_module.rs index 50124a3d..fe5b7ad4 100644 --- a/abi_stable/src/proc_macro_reexports/export_root_module.rs +++ b/abi_stable/src/proc_macro_reexports/export_root_module.rs @@ -1,9 +1,6 @@ /** This attribute is used for functions which export a module in an `implementation crate`. -When applied it creates a mangled function which calls the annotated function, -as well as check its type signature. - This is applied to functions like this: ```rust @@ -53,28 +50,30 @@ The return type of the annotated function can be one of: - `RResult`, where `M` is any type that implements `abi_stable::library::RootModule` -All those types are supported through the `abi_stable::library::IntoRootModuleResult` trait, +All those types are supported through the [`IntoRootModuleResult`] trait, which you can implement if you want to return some other type. # Generated code Exporting the root module creates a -`static THE_NAME_USED_FOR_ALL_ROOT_MODULES:LibHeader= ... ;` +`static THE_NAME_USED_FOR_ALL_ROOT_MODULES: `[`LibHeader`]` = ... ;` with these things: -- The abi_stable version number used by the dynamic library. +- The version of `abi_stable` used. + +- A `#[no_mangle]` function that wraps the annotated root-module constructor function, +converting the return value to [`RootModuleResult`](./library/type.RootModuleResult.html). -- A constant describing the layout of the exported root module,and every type it references. +- The type layout of the root module, +for checking that the types are compatible with whatever loads that library. -- A lazily initialized reference to the root module. +- The version number of the library. -- The constructor function of the root module. +- A [`LateStaticRef`] of the root module. -The name used for root modules is the one returned by -`abi_stable::library::ROOT_MODULE_LOADER_NAME`. -Because there can't be multiple root modules for a library, -that function returns a constant. +The name used for generated static is the value of +[`abi_stable::library::ROOT_MODULE_LOADER_NAME`](./library/constant.ROOT_MODULE_LOADER_NAME.html). # Remove type layout constant @@ -86,8 +85,8 @@ it could be Undefined Behavior. This attribute is useful if one wants to minimize the size of the dynamic library when doing a public release. -It is strongly encouraged that this attribute is used conditionally, -disabling it in Continuous Integration so that the +This attribute should not be used unconditionally, +it should be disabled in Continuous Integration so that the binary compatibility of a dynamic library is checked at some point before releasing it. # More examples @@ -95,6 +94,11 @@ binary compatibility of a dynamic library is checked at some point before releas For a more detailed example look in the README in the repository for this crate. + +[`IntoRootModuleResult`]: ./library/trait.IntoRootModuleResult.html +[`LateStaticRef`]: ./sabi_types/struct.LateStaticRef.html +[`LibHeader`]: ./library/struct.LibHeader.html + */ #[doc(inline)] pub use abi_stable_derive::export_root_module; \ No newline at end of file From c261a4d5e039f1f6468ff22c3c46784317d3509f Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Wed, 6 Oct 2021 16:54:58 -0300 Subject: [PATCH 10/32] Improved docs for a bunch of items. This improves doc formatting, clarity, and add links to mentioned items. --- .../src/abi_stability/stable_abi_trait.rs | 82 ++--- abi_stable/src/derive_macro_reexports.rs | 4 +- abi_stable/src/docs/sabi_trait_inherent.rs | 8 +- abi_stable/src/erased_types/dyn_trait.rs | 66 ++-- abi_stable/src/erased_types/traits.rs | 242 +++++++-------- abi_stable/src/library/root_mod_trait.rs | 13 +- abi_stable/src/macros.rs | 289 +++++++++--------- .../proc_macro_reexports/sabi_extern_fn.rs | 22 +- .../sabi_trait_attribute.rs | 173 ++++++----- 9 files changed, 457 insertions(+), 442 deletions(-) diff --git a/abi_stable/src/abi_stability/stable_abi_trait.rs b/abi_stable/src/abi_stability/stable_abi_trait.rs index ee2de9b8..1b2f36b5 100644 --- a/abi_stable/src/abi_stability/stable_abi_trait.rs +++ b/abi_stable/src/abi_stability/stable_abi_trait.rs @@ -27,48 +27,48 @@ use crate::{ /////////////////////// -/** -Represents a type whose layout is stable. - -This trait can be derived using `#[derive(StableAbi)]`. - -# Safety - -The layout specified in `LAYOUT` must be correct, -otherwise type checking when loading a dynamic library would be unsound, -and passing this into a dynamic library would be equivalent to transmuting it. - -# Caveats - -This trait cannot be directly implemented for functions that take lifetime parameters, -because of that,`#[derive(StableAbi)]` detects the presence of `extern fn` types -in type definitions. - -*/ +/// Represents a type whose layout is stable. +/// +/// This trait can be derived using +/// [`#[derive(StableAbi)]`](./derive.StableAbi.html). +/// +/// # Safety +/// +/// The layout specified in `LAYOUT` must be correct, +/// otherwise type checking when loading a dynamic library would be unsound, +/// and passing this into a dynamic library would be equivalent to transmuting it. +/// +/// # Caveats +/// +/// This trait cannot be directly implemented for functions that take lifetime parameters, +/// because of that, [`#[derive(StableAbi)]`](./derive.StableAbi.html) +/// detects the presence of `extern fn` types in type definitions. pub unsafe trait StableAbi: GetStaticEquivalent_ { - /** - Whether this type has a single invalid bit-pattern. - - Possible values:True/False - - Some standard library types have a single value that is invalid for them eg:0,null. - these types are the only ones which can be stored in a `Option<_>` that implements StableAbi. - - An alternative for types where `IsNonZeroType=False`,you can use `ROption`. - - Non-exhaustive list of std types that are NonZero: - - - `&T` (any T). - - - `&mut T` (any T). - - - `extern "C" fn()`. - - - `std::ptr::NonNull` - - - `std::num::NonZero*` - - */ + /// Whether this type has a single invalid bit-pattern. + /// + /// Possible values: [`True`]/[`False`] + /// + /// Some standard library types have a single value that is invalid for them eg:0,null. + /// these types are the only ones which can be stored in a `Option<_>` that implements StableAbi. + /// + /// For an alternative to `Option` for types where + /// `IsNonZeroType = False`, you can use [`ROption`]. + /// + /// Non-exhaustive list of std types that are NonZero: + /// + /// - `&T` (any T). + /// + /// - `&mut T` (any T). + /// + /// - `extern "C" fn()`. + /// + /// - `std::ptr::NonNull` + /// + /// - `std::num::NonZero*` + /// + /// [`True`]: ./reexports/struct.True.html + /// [`False`]: ./reexports/struct.False.html + /// [`ROption`]: ./std_types/enum.ROption.html type IsNonZeroType: Boolean; /// The layout of the type provided by implementors. diff --git a/abi_stable/src/derive_macro_reexports.rs b/abi_stable/src/derive_macro_reexports.rs index bfdc8a7b..20dc0096 100644 --- a/abi_stable/src/derive_macro_reexports.rs +++ b/abi_stable/src/derive_macro_reexports.rs @@ -27,7 +27,7 @@ pub use crate::{ reflection::ModReflMode, sabi_trait::vtable::{RObjectVtable, RObjectVtable_Ref}, sabi_types::{Constructor, MovePtr, RMut, RRef, VersionStrings}, - std_types::{utypeid::new_utypeid, RNone, RSlice, RSome}, + std_types::{utypeid::new_utypeid, RErr, RNone, ROk, RSlice, RSome}, type_layout::{ CompTLFields, CompTLFunction, DiscriminantRepr, FieldAccessor, GenericTLData, GenericTLEnum, GenericTLPrefixType, IsExhaustive, LifetimeIndex, MakeTLNonExhaustive, @@ -43,7 +43,7 @@ pub use crate::{ }; pub use std::{ - convert::identity, + convert::{identity, From}, fmt::{Debug, Formatter, Result as FmtResult}, mem::ManuallyDrop, option::Option, diff --git a/abi_stable/src/docs/sabi_trait_inherent.rs b/abi_stable/src/docs/sabi_trait_inherent.rs index cc8901c4..2e0b901c 100644 --- a/abi_stable/src/docs/sabi_trait_inherent.rs +++ b/abi_stable/src/docs/sabi_trait_inherent.rs @@ -245,15 +245,15 @@ let mut object: Action_TO<'static, RBox<()>> = Action_TO::from_value(700, TD_CanDowncast); -object = try_unerase::<_, u32>(object).unwrap_err(); +object = try_downcast::<_, u32>(object).unwrap_err(); -object = try_unerase::<_, String>(object).unwrap_err(); +object = try_downcast::<_, String>(object).unwrap_err(); -assert_eq!(*try_unerase::<_, usize>(object).unwrap(), 700); +assert_eq!(*try_downcast::<_, usize>(object).unwrap(), 700); -fn try_unerase( +fn try_downcast( object: Action_TO<'static, P>, ) -> Result> where diff --git a/abi_stable/src/erased_types/dyn_trait.rs b/abi_stable/src/erased_types/dyn_trait.rs index 7666de5a..7c10086d 100644 --- a/abi_stable/src/erased_types/dyn_trait.rs +++ b/abi_stable/src/erased_types/dyn_trait.rs @@ -84,10 +84,10 @@ mod priv_ { /// Can be constructed from a pointer of a value.Requires a `'static` value. /// /// - [`from_borrowing_value`](#method.from_borrowing_value): - /// Can be constructed from the value directly.Cannot unerase the DynTrait afterwards. + /// Can be constructed from the value directly.Cannot downcast the DynTrait afterwards. /// /// - [`from_borrowing_ptr`](#method.from_borrowing_ptr) - /// Can be constructed from a pointer of a value.Cannot unerase the DynTrait afterwards. + /// Can be constructed from a pointer of a value.Cannot downcast the DynTrait afterwards. /// /// DynTrait uses the impls of the value in methods, /// which means that the pointer itself does not have to implement those traits, @@ -214,7 +214,7 @@ mod priv_ { /// /// To be able to serialize and deserialize a DynTrait, /// the interface it uses must implement [`SerializeProxyType`] and [`DeserializeDyn`], - /// and the implementation type must implement `SerializeImplType`. + /// and the implementation type must implement [`SerializeImplType`]. /// /// For a more realistic example you can look at the /// "examples/0_modules_and_interface_types" crates in the repository for this crate. @@ -288,7 +288,7 @@ mod priv_ { /// #[sabi(missing_field(panic))] /// pub struct Module{ /// #[sabi(last_prefix_field)] - /// pub deserialize_foo:extern "C" fn(s:RStr<'_>)->RResult, + /// pub deserialize_foo: extern "C" fn(s: RStr<'_>) -> RResult, /// } /// /// // This is how ffi-safe pointers to non-generic prefix types are constructed @@ -312,7 +312,7 @@ mod priv_ { /// /// #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] /// pub struct Foo{ - /// name:String, + /// name: String, /// } /// /// impl ImplType for Foo { @@ -336,7 +336,7 @@ mod priv_ { /// } /// /// #[sabi_extern_fn] - /// pub fn deserialize_foo(s:RStr<'_>)->RResult{ + /// pub fn deserialize_foo(s: RStr<'_>) -> RResult{ /// match serde_json::from_str::(s.into()) { /// Ok(x) => ROk(DynTrait::from_value(x)), /// Err(e) => RErr(RBoxError::new(e)), @@ -482,20 +482,22 @@ mod priv_ { /// # Making pointers compatible with DynTrait /// /// To make pointers compatible with DynTrait, they must imlement the - /// `abi_stable::pointer_trait::{GetPointerKind, AsPtr, AsMutPtr, CanTransmuteElement}` + /// `abi_stable::pointer_trait::{` + /// [`GetPointerKind`]`, `[`AsPtr`]`, `[`AsMutPtr`]`, `[`CanTransmuteElement`]`}` /// traits as shown in the example. /// - /// `GetPointerKind` should generally be implemented with `type Kind = PK_SmartPointer`. + /// [`GetPointerKind`] should generally be implemented with + /// `type Kind = `[`PK_SmartPointer`]. /// The exception is in the case that it is a `#[repr(transparent)]` /// wrapper around a [`RRef`]/[`RMut`]/`*const T`/`*mut T`/[`NonNull`], - /// in which case it should implement `GetPointerKind` + /// in which case it should implement [`GetPointerKind`]`` /// (when it has shared reference semantics) - /// or `GetPointerKind` + /// or [`GetPointerKind`]`` /// (when it has mutable reference semantics). /// /// ### Example /// - /// This is an example of a newtype wrapping an `RBox`, + /// This is an example of a newtype wrapping an [`RBox`], /// demonstrating that the pointer type doesn't have to implement /// the traits in the [`InterfaceType`], it's the value it points to. /// @@ -556,11 +558,11 @@ mod priv_ { /// #[repr(transparent)] /// #[derive(Default, Clone, StableAbi)] /// pub struct NewtypeBox{ - /// box_:RBox, + /// box_: RBox, /// } /// /// impl NewtypeBox{ - /// pub fn new(value:T)->Self{ + /// pub fn new(value: T) -> Self{ /// Self{ /// box_: RBox::new(value) /// } @@ -606,13 +608,23 @@ mod priv_ { /// [`NonNull`]: https://doc.rust-lang.org/std/ptr/struct.NonNull.html /// [`SerializeProxyType`]: ./erased_types/trait.SerializeProxyType.html /// [`DeserializeDyn`]: ./erased_types/trait.DeserializeDyn.html + /// [`AsMutPtr`]: ./pointer_trait/trait.AsMutPtr.html + /// [`CanTransmuteElement`]: ./pointer_trait/trait.CanTransmuteElement.html + /// [`GetPointerKind`]: ./pointer_trait/trait.GetPointerKind.html + /// [`RRef`]: ./sabi_types/struct.RRef.html + /// [`RMut`]: ./sabi_types/struct.RMut.html + /// [`RBox`]: ./std_types/struct.RBox.html + /// [`PK_Reference`]: ./pointer_trait/struct.PK_Reference.html + /// [`PK_MutReference`]: ./pointer_trait/struct.PK_MutReference.html + /// [`PK_SmartPointer`]: ./pointer_trait/struct.PK_SmartPointer.html + /// [`SerializeImplType`]: ./erased_types/trait.SerializeImplType.html /// #[repr(C)] #[derive(StableAbi)] #[sabi( // debug_print, bound ="I: InterfaceBound", - bound ="VTable_Ref<'borr, P, I>:StableAbi", + bound ="VTable_Ref<'borr, P, I>: StableAbi", extra_checks ="::EXTRA_CHECKS", )] pub struct DynTrait<'borr, P, I, EV = ()> @@ -627,9 +639,9 @@ mod priv_ { } impl DynTrait<'static, RRef<'static, ()>, ()> { - /// Constructs the `DynTrait<_>` from a `T:ImplType`. + /// Constructs the `DynTrait<_>` from a `T: ImplType`. /// - /// Use this whenever possible instead of `from_any_value`, + /// Use this whenever possible instead of [`from_any_value`](#method.from_any_value), /// because it produces better error messages when unerasing the `DynTrait<_>` /// /// # Example @@ -677,9 +689,9 @@ mod priv_ { DynTrait::from_ptr(object) } - /// Constructs the `DynTrait<_>` from a pointer to a `T:ImplType`. + /// Constructs the `DynTrait<_>` from a pointer to a `T: ImplType`. /// - /// Use this whenever possible instead of `from_any_ptr`, + /// Use this whenever possible instead of [`from_any_ptr`](#method.from_any_ptr), /// because it produces better error messages when unerasing the `DynTrait<_>` /// /// # Example @@ -864,7 +876,7 @@ mod priv_ { /// Constructs the `DynTrait<_>` from a value with a `'borr` borrow. /// - /// Cannot unerase the DynTrait afterwards. + /// Cannot downcast the DynTrait afterwards. /// /// # Example /// @@ -885,7 +897,7 @@ mod priv_ { /// /// /// // `DynTrait`s constructed using the `from_borrowing_*` constructors - /// // can't be unerased. + /// // can't be downcasted. /// assert_eq!(to.downcast_as::().ok(), None); /// /// ``` @@ -905,7 +917,7 @@ mod priv_ { /// Constructs the `DynTrait<_>` from a pointer to the erased type /// with a `'borr` borrow. /// - /// Cannot unerase the DynTrait afterwards. + /// Cannot downcast the DynTrait afterwards. /// /// # Example /// @@ -1057,10 +1069,10 @@ mod priv_ { /// `can_it_downcast` can be either: /// /// - [`TD_CanDowncast`]: - /// Which allows the trait object to be unerased, requires that the value implements any. + /// Which allows the trait object to be downcasted, requires that the value implements any. /// /// - [`TD_Opaque`]: - /// Which does not allow the trait object to be unerased. + /// Which does not allow the trait object to be downcasted. /// ///
/// @@ -2109,7 +2121,7 @@ mod priv_ { /// Constructs a DynTrait with a `P`, using the same vtable. /// /// `P` must come from a function in the vtable, - /// or come from a copy of `P:Copy+GetPointerKind`, + /// or come from a copy of `P: Copy+GetPointerKind`, /// to ensure that it is compatible with the functions in it. pub(super) fn from_new_ptr(&self, object: P, extra_value: EV) -> Self { Self { @@ -2862,8 +2874,8 @@ pub type GetVWInterface<'borr, This> = >::Interface ////////////////////////////////////////////////////////////////// -/// Error for `DynTrait<_>` being unerased into the wrong type -/// with one of the `*unerased*` methods. +/// Error for `DynTrait<_>` being downcasted into the wrong type +/// with one of the `*downcasted*` methods. #[derive(Copy, Clone)] pub struct UneraseError { dyn_trait: T, @@ -2883,7 +2895,7 @@ impl UneraseError { } } - /// Extracts the DynTrait, to handle the failure to unerase it. + /// Extracts the DynTrait, to handle the failure to downcast it. #[must_use] pub fn into_inner(self) -> T { self.dyn_trait diff --git a/abi_stable/src/erased_types/traits.rs b/abi_stable/src/erased_types/traits.rs index 31a244fd..9753fc33 100644 --- a/abi_stable/src/erased_types/traits.rs +++ b/abi_stable/src/erased_types/traits.rs @@ -17,23 +17,26 @@ use crate::type_level::{ trait_marker, }; -/** -An `implementation type`, -with an associated `interface type` which describes the traits that -must be implemented when constructing a `DynTrait` from `Self`, -using the `DynTrait::from_value` and `DynTrait::from_ptr` constructors, -so as to pass an opaque type across ffi. - -To initialize `INFO` you can use the `impl_get_type_info` macro. - -# Uniqueness - -Users of this trait can't enforce that they are the only ones with the same interface, -therefore they should handle the `Err(..)`s returned -from the `DynTrait::*_unerased` functions whenever -they convert back and forth between `Self` and `Self::Interface`. - -*/ +/// An `implementation type`, +/// with an associated `interface type` which describes the traits that +/// must be implemented when constructing a [`DynTrait`] from `Self`, +/// using the [`DynTrait::from_value`] and [`DynTrait::from_ptr`] constructors, +/// so as to pass an opaque type across ffi. +/// +/// To initialize `INFO` you can use the [`impl_get_type_info`] macro. +/// +/// # Uniqueness +/// +/// Users of this trait can't enforce that they are the only ones with the same interface, +/// therefore they should handle the `Err(..)`s returned +/// from the `DynTrait::*downcast*` functions whenever +/// they convert back and forth between `Self` and [`Self::Interface`](#associatedtype.Interface). +/// +/// +/// [`DynTrait`]: ./struct.DynTrait.html +/// [`DynTrait::from_value`]: ./struct.DynTrait.html#method.from_value +/// [`DynTrait::from_ptr`]: ./struct.DynTrait.html#method.from_ptr +/// [`impl_get_type_info`]: ./macro.impl_get_type_info.html pub trait ImplType: Sized { /// Describes the traits that must be implemented when constructing a /// `DynTrait` from `Self`. @@ -73,107 +76,108 @@ macro_rules! declare_InterfaceType { } declare_InterfaceType! { - - -/** -Defines the usable/required traits when creating a -`DynTrait, ThisInterfaceType>`. - -This trait can only be implemented using the -`#[derive(StableAbi)]` and the `impl_InterfaceType` macro, -giving a default value to each associated type, -so that adding associated types is not a breaking change. - -The value of every associated type can be. - -- `Implemented<_>`,the trait would be required by, and be usable in `DynTrait`. - -- `Unimplemented<_>`,the trait would not be required by, and not be usable in `DynTrait`. - -# Example - -``` - -use abi_stable::{ - StableAbi, - erased_types::InterfaceType, - type_level::bools::*, -}; - -#[repr(C)] -#[derive(StableAbi)] -#[sabi(impl_InterfaceType(Clone,Debug))] -pub struct FooInterface; - -/* -The `#[sabi(impl_InterfaceType(Clone,Debug))]` helper attribute -(as part of #[derive(StableAbi)]) above is roughly equivalent to this impl: - -impl InterfaceType for FooInterface { - type Clone= Implemented; - - type Debug= Implemented; - - ///////////////////////////////////// - //// defaulted associated types - ///////////////////////////////////// - - // Changing this to require/unrequire in minor versions,is an abi breaking change. - // type Send= Unimplemented; - - // Changing this to require/unrequire in minor versions,is an abi breaking change. - // type Sync= Unimplemented; - - // type Iterator= Unimplemented; - - // type DoubleEndedIterator= Unimplemented; - - // type Default= Unimplemented; - - // type Display= Unimplemented; - - // type Serialize= Unimplemented; - - // type Eq= Unimplemented; - - // type PartialEq= Unimplemented; - - // type Ord= Unimplemented; - - // type PartialOrd= Unimplemented; - - // type Hash= Unimplemented; - - // type Deserialize= Unimplemented; - - // type FmtWrite= Unimplemented; - - // type IoWrite= Unimplemented; - - // type IoSeek= Unimplemented; - - // type IoRead= Unimplemented; - - // type IoBufRead= Unimplemented; - - // type Error= Unimplemented; -} -*/ - -# fn main(){} - - -``` - - -*/ - - + /// Defines the usable/required traits when creating a + /// [`DynTrait, ThisInterfaceType>`](./struct.DynTrait.html). + /// + /// This trait can only be implemented using the + /// [`#[derive(StableAbi)]`](./derive.StableAbi.html) + /// derive with the + /// [`#[sabi(impl_InterfaceType(...))]`](./derive.StableAbi.html#sabiimpl_interfacetype) + /// helper attribute, + /// giving a default value to each associated type, + /// so that adding associated types is not a breaking change. + /// + /// The value of every associated type can be. + /// + /// - [`Implemented<_>`](./type_level/impl_enum/struct.Implemented.html): + /// the trait would be required by, and be usable in `DynTrait`. + /// + /// - [`Unimplemented<_>`](./type_level/impl_enum/struct.Unimplemented.html): + /// the trait would not be required by, and not be usable in `DynTrait`. + /// + /// # Example + /// + /// ``` + /// + /// use abi_stable::{ + /// StableAbi, + /// erased_types::InterfaceType, + /// type_level::bools::*, + /// }; + /// + /// #[repr(C)] + /// #[derive(StableAbi)] + /// #[sabi(impl_InterfaceType(Clone, Debug))] + /// pub struct FooInterface; + /// + /// /* + /// The `#[sabi(impl_InterfaceType(Clone, Debug))]` helper attribute + /// (as part of #[derive(StableAbi)]) above is roughly equivalent to this impl: + /// + /// impl InterfaceType for FooInterface { + /// type Clone = Implemented; + /// + /// type Debug = Implemented; + /// + /// ///////////////////////////////////// + /// //// defaulted associated types + /// ///////////////////////////////////// + /// + /// // Changing this to require/unrequire in minor versions, is an abi breaking change. + /// // type Send = Unimplemented; + /// + /// // Changing this to require/unrequire in minor versions, is an abi breaking change. + /// // type Sync = Unimplemented; + /// + /// // type Iterator = Unimplemented; + /// + /// // type DoubleEndedIterator = Unimplemented; + /// + /// // type Default = Unimplemented; + /// + /// // type Display = Unimplemented; + /// + /// // type Serialize = Unimplemented; + /// + /// // type Eq = Unimplemented; + /// + /// // type PartialEq = Unimplemented; + /// + /// // type Ord = Unimplemented; + /// + /// // type PartialOrd = Unimplemented; + /// + /// // type Hash = Unimplemented; + /// + /// // type Deserialize = Unimplemented; + /// + /// // type FmtWrite = Unimplemented; + /// + /// // type IoWrite = Unimplemented; + /// + /// // type IoSeek = Unimplemented; + /// + /// // type IoRead = Unimplemented; + /// + /// // type IoBufRead = Unimplemented; + /// + /// // type Error = Unimplemented; + /// } + /// */ + /// + /// # fn main(){} + /// + /// + /// ``` + /// + /// + /// + /// assoc_types[ - /// Changing this to require/unrequire in minor versions,is an abi breaking change. + /// Changing this to require/unrequire in minor versions, is an abi breaking change. type Send; - /// Changing this to require/unrequire in minor versions,is an abi breaking change. + /// Changing this to require/unrequire in minor versions, is an abi breaking change. type Sync; type Clone; @@ -283,7 +287,7 @@ where /////////////////////////////////////// /** -Describes how `D` is deserialized,using a proxy to do so. +Describes how `D` is deserialized, using a proxy to do so. Generally this delegates to a library function, so that the implementation can be delegated @@ -399,7 +403,7 @@ pub mod interface_for { { type Interface = Interface; - /// The `&'static TypeInfo` constant,used when unerasing `DynTrait`s into a type. + /// The `&'static TypeInfo` constant, used when unerasing `DynTrait`s into a type. const INFO: &'static TypeInfo = &TypeInfo { size: std::mem::size_of::(), alignment: std::mem::align_of::(), @@ -417,7 +421,7 @@ pub mod interface_for { crate::impl_InterfaceType! { impl crate::erased_types::InterfaceType for () { - type Send=True; - type Sync=True; + type Send= True; + type Sync= True; } } diff --git a/abi_stable/src/library/root_mod_trait.rs b/abi_stable/src/library/root_mod_trait.rs index afc967ca..44ff5c90 100644 --- a/abi_stable/src/library/root_mod_trait.rs +++ b/abi_stable/src/library/root_mod_trait.rs @@ -200,11 +200,14 @@ pub trait RootModule: Sized + StableAbi + PrefixRefTrait + 'static { Ok(leak_value(raw_library)) })?; - items_ - .as_ref() - .unwrap() - .init_root_module_with_unchecked_layout::()? - .initialization() + // safety: the layout was checked in the closure above, + unsafe { + items_ + .as_ref() + .unwrap() + .init_root_module_with_unchecked_layout::()? + .initialization() + } }) } diff --git a/abi_stable/src/macros.rs b/abi_stable/src/macros.rs index d19de101..98af424a 100644 --- a/abi_stable/src/macros.rs +++ b/abi_stable/src/macros.rs @@ -130,46 +130,42 @@ macro_rules! tl_genparams { /////////////////////////////////////////////////////////////////////// -/** -Equivalent to `?` for [`RResult`]. - -# Example - -Defining an extern function that returns a result. - -``` -use abi_stable::{ - std_types::{RResult,ROk,RErr,RBoxError,RStr,Tuple3}, - traits::IntoReprC, - rtry, - sabi_extern_fn, -}; - - -#[sabi_extern_fn] -fn parse_tuple(s:RStr<'_>)->RResult,RBoxError>{ - let mut iter=s.split(',').map(|x|x.trim()); - ROk(Tuple3( - rtry!( iter.next().unwrap_or("").parse().map_err(RBoxError::new).into_c() ), - rtry!( iter.next().unwrap_or("").parse().map_err(RBoxError::new).into_c() ), - rtry!( iter.next().unwrap_or("").parse().map_err(RBoxError::new).into_c() ), - )) -} - - - -``` - -[`RResult`]: ./std_types/enum.RResult.html - -*/ +/// Equivalent to `?` for [`RResult`]. +/// +/// # Example +/// +/// Defining an extern function that returns a result. +/// +/// ``` +/// use abi_stable::{ +/// std_types::{RResult, ROk, RErr, RBoxError, RStr, Tuple3}, +/// traits::IntoReprC, +/// rtry, +/// sabi_extern_fn, +/// }; +/// +/// +/// #[sabi_extern_fn] +/// fn parse_tuple(s: RStr<'_>) -> RResult, RBoxError>{ +/// let mut iter = s.split(',').map(|x| x.trim()); +/// ROk(Tuple3( +/// rtry!( iter.next().unwrap_or("").parse().map_err(RBoxError::new).into_c() ), +/// rtry!( iter.next().unwrap_or("").parse().map_err(RBoxError::new).into_c() ), +/// rtry!( iter.next().unwrap_or("").parse().map_err(RBoxError::new).into_c() ), +/// )) +/// } +/// +/// +/// +/// ``` +/// +/// [`RResult`]: ./std_types/enum.RResult.html #[macro_export] macro_rules! rtry { ($expr:expr) => {{ - use $crate::std_types::{RErr, ROk}; match $expr.into() { - ROk(x) => x, - RErr(x) => return RErr(From::from(x)), + $crate::pmr::ROk(x) => x, + $crate::pmr::RErr(x) => return $crate::pmr::RErr($crate::pmr::From::from(x)), } }}; } @@ -180,10 +176,9 @@ macro_rules! rtry { #[macro_export] macro_rules! rtry_opt { ($expr:expr) => {{ - use $crate::std_types::option::{RNone, RSome}; match $expr.into() { - RSome(x) => x, - RNone => return RNone, + $crate::pmr::RSome(x) => x, + $crate::pmr::RNone => return $crate::pmr::RNone, } }}; } @@ -202,85 +197,84 @@ macro_rules! check_unerased { /////////////////////////////////////////////////////////////////////// -/** -Use this to make sure that you handle panics inside `extern fn` correctly. - -This macro causes an abort if a panic reaches this point. - -It does not prevent functions inside from using `::std::panic::catch_unwind` to catch the panic. - -# Early returns - -This macro by default wraps the passed code in a closure so that any -early returns that happen inside don't interfere with the macro generated code. - -If you don't have an early return (a `return`/`continue`/`break`) -in the code passed to this macro you can use -`extern_fn_panic_handling!{no_early_return; }`, -which *might* be cheaper(this has not been tested yet). - -# Example - -``` -use std::fmt; - -use abi_stable::{ - extern_fn_panic_handling, - std_types::RString, -}; - - -pub extern "C" fn print_debug(this: &T,buf: &mut RString) -where - T: fmt::Debug, -{ - extern_fn_panic_handling! { - use std::fmt::Write; - - println!("{:?}",this); - } -} -``` - -# Example, no_early_return - - -``` -use std::fmt; - -use abi_stable::{ - extern_fn_panic_handling, - std_types::RString, -}; - - -pub extern "C" fn print_debug(this: &T,buf: &mut RString) -where - T: fmt::Debug, -{ - extern_fn_panic_handling!{no_early_return; - use std::fmt::Write; - - println!("{:?}",this); - } -} - -``` - - -*/ +/// Use this to make sure that you handle panics inside `extern fn` correctly. +/// +/// This macro causes an abort if a panic reaches this point. +/// +/// It does not prevent functions inside from using `::std::panic::catch_unwind` +/// to catch the panic. +/// +/// # Early returns +/// +/// This macro by default wraps the passed code in a closure so that any +/// early returns that happen inside don't interfere with the macro generated code. +/// +/// If you don't have an early return (a `return`/`continue`/`break`) +/// in the code passed to this macro you can use +/// `extern_fn_panic_handling!{no_early_return; }`, +/// which *might* be cheaper(this has not been tested yet). +/// +/// # Example +/// +/// ``` +/// use std::fmt; +/// +/// use abi_stable::{ +/// extern_fn_panic_handling, +/// std_types::RString, +/// }; +/// +/// +/// pub extern "C" fn print_debug(this: &T,buf: &mut RString) +/// where +/// T: fmt::Debug, +/// { +/// extern_fn_panic_handling! { +/// use std::fmt::Write; +/// +/// println!("{:?}",this); +/// } +/// } +/// ``` +/// +/// # Example, no_early_return +/// +/// +/// ``` +/// use std::fmt; +/// +/// use abi_stable::{ +/// extern_fn_panic_handling, +/// std_types::RString, +/// }; +/// +/// +/// pub extern "C" fn print_debug(this: &T,buf: &mut RString) +/// where +/// T: fmt::Debug, +/// { +/// extern_fn_panic_handling!{no_early_return; +/// use std::fmt::Write; +/// +/// println!("{:?}",this); +/// } +/// } +/// +/// ``` +/// +/// #[macro_export] macro_rules! extern_fn_panic_handling { (no_early_return; $($fn_contents:tt)* ) => ({ - let aborter_guard={ + let aborter_guard = { use $crate::utils::{AbortBomb,PanicInfo}; #[allow(dead_code)] - const BOMB:AbortBomb=AbortBomb{ - fuse:&PanicInfo{file:file!(),line:line!()} + const BOMB:AbortBomb = AbortBomb{ + fuse: &PanicInfo{file:file!(),line:line!()} }; BOMB }; - let res={ + let res = { $($fn_contents)* }; @@ -291,7 +285,7 @@ macro_rules! extern_fn_panic_handling { ( $($fn_contents:tt)* ) => ( $crate::extern_fn_panic_handling!{ no_early_return; - let a=$crate::marker_type::NotCopyNotClone; + let a = $crate::marker_type::NotCopyNotClone; (move||{ drop(a); $($fn_contents)* @@ -302,45 +296,40 @@ macro_rules! extern_fn_panic_handling { /////////////////////////////////////////////////////////////////////// -/** - -Constructs the [`TypeInfo`] for some type. - -It's necessary for the type to be `'static` because -[`TypeInfo`] stores a private function that returns the [`UTypeId`] of that type. - -# Example - -``` -use abi_stable::{ - impl_get_type_info, - erased_types::{TypeInfo,ImplType}, -}; - -#[derive(Default, Clone, Debug)] -struct Foo { - l: u32, - r: u32, - name: T, -} - -impl ImplType for Foo -where T:'static+Send+Sync -{ - type Interface=(); - - // You have to write the full type (eg: impl_get_type_info!{ Bar<'a,T,U> } ) , - // never write Self. - const INFO:&'static TypeInfo=impl_get_type_info! { Foo }; -} - - -``` - -[`TypeInfo`]: ./erased_types/struct.TypeInfo.html -[`UTypeId`]: ./std_types/struct.UTypeId.html - -*/ +/// Constructs the [`TypeInfo`] for some type. +/// +/// It's necessary for the type to be `'static` because +/// [`TypeInfo`] stores a private function that returns the [`UTypeId`] of that type. +/// +/// # Example +/// +/// ``` +/// use abi_stable::{ +/// impl_get_type_info, +/// erased_types::{TypeInfo,ImplType}, +/// }; +/// +/// #[derive(Default, Clone, Debug)] +/// struct Foo { +/// l: u32, +/// r: u32, +/// name: T, +/// } +/// +/// impl ImplType for Foo +/// where T: 'static + Send + Sync +/// { +/// type Interface = (); +/// +/// const INFO: &'static TypeInfo = impl_get_type_info! { Foo }; +/// } +/// +/// +/// ``` +/// +/// [`TypeInfo`]: ./erased_types/struct.TypeInfo.html +/// [`UTypeId`]: ./std_types/struct.UTypeId.html +/// #[macro_export] macro_rules! impl_get_type_info { ($type:ty) => {{ diff --git a/abi_stable/src/proc_macro_reexports/sabi_extern_fn.rs b/abi_stable/src/proc_macro_reexports/sabi_extern_fn.rs index 797dc49f..c7f0de29 100644 --- a/abi_stable/src/proc_macro_reexports/sabi_extern_fn.rs +++ b/abi_stable/src/proc_macro_reexports/sabi_extern_fn.rs @@ -1,17 +1,17 @@ /** The `sabi_extern_fn` attribute macro allows defining `extern "C"` function that -aborting on unwind instead of causing undefined behavior. +abort on unwind instead of causing undefined behavior. This macro is syntactic sugar to transform this: ```ignore - fn function_name( )-> { + fn function_name( ) -> { } ``` into this: ```ignore - extern "C" fn function_name( )-> { + extern "C" fn function_name( ) -> { ::abi_stable::extern_fn_panic_handling!{ } @@ -26,10 +26,10 @@ catch panics and handle them appropriately. ### Basic examples ```rust -use abi_stable::{sabi_extern_fn,std_types::RArc,traits::IntoReprC}; +use abi_stable::{sabi_extern_fn, std_types::RArc, traits::IntoReprC}; #[sabi_extern_fn] -pub(crate) fn hello()->RArc{ +pub(crate) fn hello() -> RArc{ RArc::new(100) } @@ -41,12 +41,12 @@ assert_eq!(hello(), RArc::new(100)); ```rust use abi_stable::{ sabi_extern_fn, - std_types::{RVec,RStr}, + std_types::{RVec, RStr}, traits::IntoReprC, }; #[sabi_extern_fn] -fn collect_into_lines(text:&str)->RVec>{ +fn collect_into_lines(text:&str) -> RVec>{ text.lines() .filter(|x| !x.is_empty() ) .map(RStr::from) @@ -68,22 +68,22 @@ You can use `#[sabi_extern_fn(no_early_return)]` to potentially improve the runtime performance of the annotated function (this has not been tested). This variant of the attribute removes an intermediate closure that is -used to intercept early returns (`?`,`return`,and some macros), +used to intercept early returns (`?`,`return, and some macros), If this version of the attribute is used on a function which does have an -early return,it will (incorrectly) abort the process. +early return, it will (incorrectly) abort the process when it attempts to return early. ### Example ```rust use abi_stable::{ sabi_extern_fn, - std_types::{RVec,RStr}, + std_types::{RVec, RStr}, traits::IntoReprC, }; #[sabi_extern_fn(no_early_return)] -pub(crate) fn hello()->RVec>{ +pub(crate) fn hello() -> RVec>{ vec![ "hello".into(), "world".into(), diff --git a/abi_stable/src/proc_macro_reexports/sabi_trait_attribute.rs b/abi_stable/src/proc_macro_reexports/sabi_trait_attribute.rs index 586851a6..cc0e7911 100644 --- a/abi_stable/src/proc_macro_reexports/sabi_trait_attribute.rs +++ b/abi_stable/src/proc_macro_reexports/sabi_trait_attribute.rs @@ -2,14 +2,14 @@ This attribute generates an ffi-safe trait object on the trait it's applied to. -All items outside the list of generated items comes from `abi_stable::sabi_trait`. +All items outside the list of generated items comes from [`abi_stable::sabi_trait`]. # Supertraits. -By default these are the supertraits that `#[sabi_trait]` traits can have: +By default these are the supertraits that `#[sabi_trait]` traits can have: -- lifetimes:It can be a lifetime declared by the trait,or `'static`. +- lifetimes: It can be a lifetime declared by the trait, or `'static`. - `Debug` @@ -25,8 +25,8 @@ it uses the default implementation, - `Sync` To be able to have more supertraits you must use the `#[sabi(use_dyntrait)]` helper attribute, -which changes the underlying implementation from `RObject<_>` to `DynTrait<_>`, -allowing these supertraits: +which changes the underlying implementation from [`RObject`] to [`DynTrait`], +allowing these supertraits: - `Iterator`: requires the Item type to be specified. @@ -70,12 +70,12 @@ and that would be Undefined Behavior in many situations. # Extensibility `#[sabi_trait]` trait objects are (ABI-wise) safe to extend in minor versions, -so long as methods are always added at the end,preferably as default methods. +so long as methods are always added at the end, preferably as default methods. A library will not load (through safe means) if methods are added anywhere but the end. Accidentally calling newer methods on trait objects from older versions of a -library will cause a panic at runtime,unless it has a default implementation +library will cause a panic at runtime, unless it has a default implementation (within the trait definition that `#[sabi_trait]` can see). Panics can only happen if one loads multiple versions of a library, @@ -91,16 +91,16 @@ where `Trait` is the name of the annotated trait. This is the module inside of which all the items are generated. -These are the items reexported from the module: +These are the items reexported from the module: -- [`Trait`](#trait):The trait itself. +- [`Trait`](#trait): The trait itself. -- [`Trait_TO`](#trait_to):The trait object for the trait. +- [`Trait_TO`](#trait_to): The trait object for the trait. -- [`Trait_MV`](#trait_mv): +- [`Trait_MV`](#trait_mv): A helper type used to construct the vtable for the trait object in constants. -- [`Trait_CTO`](#trait_cto): +- [`Trait_CTO`](#trait_cto): A type alias for the trait object which is constructible in constants. @@ -118,7 +118,7 @@ only requiring the wrapped pointer to implement the trait in the individual meth
This only implements `Trait` if all the methods are callable, -when the wrapped pointer type implements traits for these methods: +when the wrapped pointer type implements traits for these methods: - `&self` method: requires `AsPtr`. - `&mut self` method: requires `AsMutPtr`. @@ -126,18 +126,18 @@ when the wrapped pointer type implements traits for these methods:
-Trait_TO has these generic parameters(in order): +Trait_TO has these generic parameters(in order): -- `'trait_lifetime_n`: The lifetime parameters of the trait,if any. +- `'trait_lifetime_n`: The lifetime parameters of the trait, if any. -- `'lt`: +- `'lt`: This is the lifetime of the type that the trait object was constructed with. If the trait requires `'static`(in the list of supertraits), then it doesn't have this lifetime parameter. - `Pointer`: An pointer whose referent has been erased, - most commonly `RBox<()>`/`RArc<()>`/`&()`/`&mut ()`. + most commonly [`RBox<()>`]/[`RArc<()>`]/[`RRef<'_, ()>`]/[`RMut<'_, ()>`]. - `trait_type_param_n`: The type parameters of the trait. @@ -146,13 +146,13 @@ then it doesn't have this lifetime parameter. - `trait_assoc_type_n`: The associated types of the trait. -A trait defined like this:`trait Foo<'a, T, U>{ type Hello; type World; }`, -has this trait object:`Foo_TO<'a, 'lt, Pointer, T, U, Hello, World>`. +A trait defined like this: `trait Foo<'a, T, U>{ type Hello; type World; }`, +has this trait object: `Foo_TO<'a, 'lt, Pointer, T, U, Hello, World>`.
One can access the underlying implementation of the trait object through the `obj` field, -allowing one to call these methods(a nonexhaustive list): +allowing one to call these methods(a nonexhaustive list): - downcast_into_impltype(only DynTrait) @@ -174,17 +174,17 @@ you can use the `Trait_TO::from_sabi` associated function. A type alias for the type of the trait objct that is constructible in constants, with the `from_const` constructor function. -Constructed with `Trait_CTO::from_const(&value,Trait_MV::VTABLE)`. +Constructed with `Trait_CTO::from_const(&value, Trait_MV::VTABLE)`. -Trait_CTO has these generic parameters(in order): +Trait_CTO has these generic parameters(in order): -- `'trait_lifetime_n`: The lifetime parameters of the trait,if any. +- `'trait_lifetime_n`: The lifetime parameters of the trait, if any. -- `'lt`:this is the lifetime of the type that the trait object was construct with. +- `'lt`: this is the lifetime of the type that the trait object was construct with. If the trait requires `'static`(in the list of supertraits), then it doesn't have this lifetime parameter. -- `'_ref`:this is the lifetime of the reference that this was constructed with. +- `'_ref`: this is the lifetime of the reference that this was constructed with. - `trait_type_param_n`: The type parameters of the trait. @@ -204,11 +204,11 @@ A helper type used to construct the vtable of the trait object. The trait is defined similarly to how it is before being transformed by the `#[sabi_trait]` attribute. -These are the differences: +These are the differences: -- If there is a by-value method,a `Self:Sized` constraint will be added automatically. +- If there is a by-value method, a `Self: Sized` constraint will be added automatically. -- Lifetime supertraits are stripped,because they disallow the trait object to be +- Lifetime supertraits are stripped, because they disallow the trait object to be constructed with a reference of a smaller lifetime. ### Trait_Bounds @@ -226,7 +226,7 @@ that are valid for `#[derive(StableAbi)]`. # Trait attributes. -These are attributes for the generated trait,applied on the trait(not on methods). +These are attributes for the generated trait, applied on the trait(not on methods). ### `#[sabi(no_trait_impl)]` @@ -242,7 +242,7 @@ Stops using default implementation of methods (from the trait declaration) as the fallback implementation of the method when it's not in the vtable, because the trait object comes from a previous version of the library. -By using this attribute,defaulted methods will behave the same as +By using this attribute, defaulted methods will behave the same as non-defaulted methods when they don't exist in the vtable. ### `#[sabi(debug_print_trait)]` @@ -255,7 +255,7 @@ Note that this does not expand the output of the ### `#[sabi(use_dyntrait)]` Changes how the trait object is implemented to use `DynTrait` instead of `RObject`, -this allows using more traits,with the (potential) cost of having more overhead. +this allows using more traits, with the (potential) cost of having more overhead. # Associated types @@ -267,7 +267,7 @@ that come after those of the trait. # Object safety -Trait objects generated using this attribute have similar restrictions to built-in trait objects: +Trait objects generated using this attribute have similar restrictions to built-in trait objects: - `Self` can only be used to access associated types (using the `Self::AssocType` syntax). @@ -278,7 +278,7 @@ Trait objects generated using this attribute have similar restrictions to built- # Questions and Answers -**Question:** Why does Calling from_ptr/from_value give me a expected a `'static` value error? +**Question: ** Why does Calling from_ptr/from_value give me a expected a `'static` value error? Answer: There are 3 possible reasons @@ -288,7 +288,7 @@ Answer: There are 3 possible reasons (`Eq`/`PartialEq`/`Ord`/`PartialOrd`) as supertraits. This requires the type to be `'static` because comparing trait objects requires -constructing a `std::any::TypeId`,which itself requires `'static` to be constructed. +constructing a `std::any::TypeId`, which itself requires `'static` to be constructed. - 3: Because you passed `TD_CanDowncast` to the constructor function, which requires constructing a `std::any::TypeId` @@ -304,7 +304,7 @@ use abi_stable::{ StableAbi, sabi_trait, sabi_trait::prelude::*, - std_types::{RBox,RArc,RString,RStr,ROption,RNone}, + std_types::{RBox, RArc, RString, RStr, ROption, RNone}, }; use std::{ @@ -313,14 +313,14 @@ use std::{ }; #[sabi_trait] -pub trait Dictionary:Debug+Clone{ +pub trait Dictionary: Debug + Clone { type Value; - fn get(&self,key:RStr<'_>)->Option<&Self::Value>; + fn get(&self, key: RStr<'_>) -> Option<&Self::Value>; /// The `#[sabi(last_prefix_field)]` attribute here means that this is the last method /// that was defined in the first compatible version of the library - /// (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), + /// (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 , etc), /// requiring new methods to always be added below preexisting ones. /// /// The `#[sabi(last_prefix_field)]` attribute would stay on this method until the library @@ -328,10 +328,10 @@ pub trait Dictionary:Debug+Clone{ /// at which point it would be moved to the last method at the time. /// #[sabi(last_prefix_field)] - fn insert(&mut self,key:RString,value:Self::Value)->ROption; + fn insert(&mut self, key: RString, value: Self::Value) -> ROption; /// You can add defaulted methods in minor versions(it's not a breaking change). - fn contains(&self,key:RStr<'_>)->bool{ + fn contains(&self, key: RStr<'_>) -> bool { self.get(key).is_some() } } @@ -340,69 +340,69 @@ pub trait Dictionary:Debug+Clone{ # fn main() { { - impl Dictionary for HashMap + impl Dictionary for HashMap where - V:Debug+Clone + V: Debug + Clone { - type Value=V; - fn get(&self,key:RStr<'_>)->Option<&V>{ + type Value = V; + fn get(&self, key: RStr<'_>) -> Option<&V>{ self.get(key.as_str()) } - fn insert(&mut self,key:RString,value:V)->ROption{ - self.insert(key,value) + fn insert(&mut self, key: RString, value: V) -> ROption{ + self.insert(key, value) .into() } } - let mut map=HashMap::::new(); - map.insert("hello".into(),100); - map.insert("world".into(),10); + let mut map = HashMap::::new(); + map.insert("hello".into(), 100); + map.insert("world".into(), 10); { // This type annotation is for the reader // // You can unerase trait objects constructed with `TD_CanDowncast` - // (as opposed to `TD_Opaque`,which can't be unerased). - let mut object:Dictionary_TO<'_,RBox<()>,u32>= - Dictionary_TO::from_value(map.clone(),TD_CanDowncast); + // (as opposed to `TD_Opaque`, which can't be unerased). + let mut object: Dictionary_TO<'_, RBox<()>, u32>= + Dictionary_TO::from_value(map.clone(), TD_CanDowncast); - assert_eq!(Dictionary::get(&object,"hello".into()),Some(&100)); - assert_eq!(object.get("hello".into()),Some(&100)); // Inherent method call + assert_eq!(Dictionary::get(&object,"hello".into()), Some(&100)); + assert_eq!(object.get("hello".into()), Some(&100)); // Inherent method call - assert_eq!(Dictionary::get(&object,"world".into()),Some(&10)); - assert_eq!(object.get("world".into()),Some(&10)); // Inherent method call + assert_eq!(Dictionary::get(&object,"world".into()), Some(&10)); + assert_eq!(object.get("world".into()), Some(&10)); // Inherent method call - object.insert("what".into(),99); // Inherent method call + object.insert("what".into(), 99); // Inherent method call // You can only unerase a trait object if it was constructed with `TD_CanDowncast` // and it's being unerased into a type that implements `std::any::Any`. - let map:RBox>=object.obj.downcast_into().unwrap(); + let map: RBox>=object.obj.downcast_into().unwrap(); assert_eq!(map.get("hello".into()), Some(&100)); assert_eq!(map.get("world".into()), Some(&10)); assert_eq!(map.get("what".into()), Some(&99)); } { - let arc=RArc::new(map.clone()); + let arc = RArc::new(map.clone()); // This type annotation is for the reader // // You can unerase trait objects constructed with `TD_CanDowncast` - // (as opposed to `TD_Opaque`,which can't be unerased). - let object:Dictionary_TO<'_,RArc<()>,u32>= - Dictionary_TO::from_ptr(arc,TD_CanDowncast); + // (as opposed to `TD_Opaque`, which can't be unerased). + let object: Dictionary_TO<'_, RArc<()>, u32>= + Dictionary_TO::from_ptr(arc, TD_CanDowncast); - assert_eq!(object.get("world".into()),Some(&10)); + assert_eq!(object.get("world".into()), Some(&10)); // Can't call these methods on `Dictionary_TO,..>` // because `RArc<_>` doesn't implement AsMutPtr. // - // assert_eq!(Dictionary::get(&object,"hello"),Some(&100)); + // assert_eq!(Dictionary::get(&object,"hello"), Some(&100)); // - // object.insert("what".into(),99); - // Dictionary::insert(&mut object,"what".into(),99); + // object.insert("what".into(), 99); + // Dictionary::insert(&mut object,"what".into(), 99); - let map:RArc>=object.obj.downcast_into().unwrap(); + let map: RArc>=object.obj.downcast_into().unwrap(); assert_eq!(map.get("hello".into()), Some(&100)); assert_eq!(map.get("world".into()), Some(&10)); } @@ -411,24 +411,24 @@ pub trait Dictionary:Debug+Clone{ { impl Dictionary for (){ - type Value=RString; - fn get(&self,_:RStr<'_>)->Option<&RString>{ + type Value = RString; + fn get(&self, _: RStr<'_>) -> Option<&RString>{ None } - fn insert(&mut self,_:RString,_:RString)->ROption{ + fn insert(&mut self, _: RString, _: RString) -> ROption{ RNone } } // This type annotation is for the reader - let object:Dictionary_TO<'_,RBox<()>,RString>= - Dictionary_TO::from_value( () ,TD_Opaque); + let object: Dictionary_TO<'_, RBox<()>, RString>= + Dictionary_TO::from_value( () , TD_Opaque); - assert_eq!(object.get("hello".into()),None); - assert_eq!(object.get("world".into()),None); + assert_eq!(object.get("hello".into()), None); + assert_eq!(object.get("world".into()), None); // Cannot unerase trait objects created with `TD_Opaque`. - assert_eq!(object.obj.downcast_into::<()>().ok(),None); + assert_eq!(object.obj.downcast_into::<()>().ok(), None); } # } @@ -449,27 +449,27 @@ use abi_stable::{ }; #[sabi_trait] -pub trait StaticSet:Sync+Send+Debug+Clone{ +pub trait StaticSet: Sync + Send + Debug + Clone { type Element; /// Whether the set contains the key. - fn contains(&self,key:&Self::Element)->bool; + fn contains(&self, key: &Self::Element) -> bool; } -impl<'a,T> StaticSet for &'a [T] +impl<'a, T> StaticSet for &'a [T] where - T:std::fmt::Debug+Sync+Send+std::cmp::PartialEq + T: std::fmt::Debug + Sync + Send + std::cmp::PartialEq { - type Element=T; + type Element = T; - fn contains(&self,key:&Self::Element)->bool{ + fn contains(&self, key: &Self::Element) -> bool { (**self).contains(key) } } -const CARDS:&'static [char]=&['A','2','3','4','5','6','7','8','9','J','Q','K']; +const CARDS: &'static [char] = &['A','2','3','4','5','6','7','8','9','J','Q','K']; -static IS_CARD:StaticSet_CTO<'static,'static,char>= +static IS_CARD: StaticSet_CTO<'static,'static, char>= StaticSet_CTO::from_const( &CARDS, TD_Opaque, @@ -494,6 +494,13 @@ assert!( ! IS_CARD.contains(&'B') ); +[`abi_stable::sabi_trait`]: ./sabi_trait/index.html +[`RObject`]: ./sabi_trait/struct.RObject.html +[`DynTrait`]: ./struct.DynTrait.html +[`RBox<()>`]: ./std_types/struct.RBox.html +[`RArc<()>`]: ./std_types/struct.RArc.html +[`RRef<'_, ()>`]: ./sabi_types/struct.RRef.html +[`RMut<'_, ()>`]: ./sabi_types/struct.RMut.html */ #[doc(inline)] From 6d91bab6c73c197dbbe3e115d567195a1f8a6e59 Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Sat, 9 Oct 2021 17:19:44 -0300 Subject: [PATCH 11/32] Rewrote `staticref` macro, improved other docs. Rewrote `staticref` macro to support more cases of static promotion, by using two associated constants, needed `paste` to generate the identifier of the helper constant. Rewrote docs of: - `tag` macro - `GetPointerKind` trait - `PointerKindVariant` trait - `PK_*` structs Added safety docs to `ImmutableRef` trait Rewrote `tl_genparams` macro. Enabled the "macro_utils" feature of `core_extensions` Fixed non-compiling nul_str tests due to version compatibility. Added `paste` as a (private-ish) dependency --- abi_stable/Cargo.toml | 2 + abi_stable/src/derive_macro_reexports.rs | 3 + abi_stable/src/erased_types/traits.rs | 3 +- abi_stable/src/macros.rs | 325 +++++++++------------ abi_stable/src/pointer_trait.rs | 92 ++++-- abi_stable/src/sabi_types/nul_str/tests.rs | 2 + 6 files changed, 217 insertions(+), 210 deletions(-) diff --git a/abi_stable/Cargo.toml b/abi_stable/Cargo.toml index ebc41627..20e8f73c 100644 --- a/abi_stable/Cargo.toml +++ b/abi_stable/Cargo.toml @@ -65,12 +65,14 @@ lock_api = "0.4.4" generational-arena = "0.2.8" crossbeam-channel = { version = "0.5.1", optional = true } serde_json = { version = "1.0.66", features = ["raw_value"], optional = true } +paste = "1.0" [dependencies.core_extensions] default_features=false features=[ "std", "iterators", + "macro_utils", "self_ops", "type_asserts", "type_identity", "type_level_bool", "void", diff --git a/abi_stable/src/derive_macro_reexports.rs b/abi_stable/src/derive_macro_reexports.rs index 20dc0096..cd22d54c 100644 --- a/abi_stable/src/derive_macro_reexports.rs +++ b/abi_stable/src/derive_macro_reexports.rs @@ -57,10 +57,13 @@ pub use std::concat; pub use repr_offset::offset_calc::next_field_offset; pub use core_extensions::{ + count_tts, type_asserts::AssertEq, type_level_bool::{False, True}, }; +pub use ::paste::paste; + pub mod renamed { pub use super::{ CompTLFields as __CompTLFields, CompTLFunction as __CompTLFunction, diff --git a/abi_stable/src/erased_types/traits.rs b/abi_stable/src/erased_types/traits.rs index 9753fc33..6aa56ae3 100644 --- a/abi_stable/src/erased_types/traits.rs +++ b/abi_stable/src/erased_types/traits.rs @@ -18,7 +18,8 @@ use crate::type_level::{ }; /// An `implementation type`, -/// with an associated `interface type` which describes the traits that +/// with [an associated `InterfaceType`](#associatedtype.Interface) +/// which describes the traits that /// must be implemented when constructing a [`DynTrait`] from `Self`, /// using the [`DynTrait::from_value`] and [`DynTrait::from_ptr`] constructors, /// so as to pass an opaque type across ffi. diff --git a/abi_stable/src/macros.rs b/abi_stable/src/macros.rs index 98af424a..636ef1b2 100644 --- a/abi_stable/src/macros.rs +++ b/abi_stable/src/macros.rs @@ -4,124 +4,75 @@ mod internal; #[macro_use] mod nul_str_macros; -/** -Use this when constructing a [`MonoTypeLayout`] when manually implementing StableAbi. - -This stores indices and ranges for the type and/or const parameter taken -from the [`SharedVars`] stored in the same [`TypeLayout`] where this is stored. - -# Syntax - -`tl_genparams!( (),* ; ; )` - -`` is one of: - --` `: No generic parameters of that kind. - --`i`: - Takes the ith type or const parameter(indexed separately). - --`i..j`: - Takes from i to j (exclusive) type or const parameter(indexed separately). - --`i..=j`: - Takes from i to j (inclusive) type or const parameter(indexed separately). - --`x:StartLen`: - Takes from x.start() to x.end() (exclusive) type or const parameter(indexed separately). - - - -# Examples - -### No generic parameters: - -``` -use abi_stable::{ - type_layout::CompGenericParams, - tl_genparams, -}; - -const PARAMS:CompGenericParams=tl_genparams!(;;); - -``` - -### One lifetime,one type parameter,one const parameter - -``` -use abi_stable::{ - type_layout::CompGenericParams, - tl_genparams, -}; - -const PARAMS:CompGenericParams=tl_genparams!('a;0;0); - -``` - -### One lifetime,two type parameters,no const parameters - -``` -use abi_stable::{ - type_layout::CompGenericParams, - tl_genparams, -}; - -const PARAMS:CompGenericParams=tl_genparams!('a;0..=1;); - -``` - -### Four lifetimes,no type parameters,three const parameters - -``` -use abi_stable::{ - type_layout::CompGenericParams, - tl_genparams, -}; - -const PARAMS:CompGenericParams=tl_genparams!('a,'b,'c,'d;;0..3); - -``` - -### No lifetimes,two type parameters,no const parameters - -``` -use abi_stable::{ - type_layout::{CompGenericParams,StartLen}, - tl_genparams, -}; - -const PARAMS:CompGenericParams=tl_genparams!(;StartLen::new(0,2);); - -``` - -[`MonoTypeLayout`]: ./type_layout/struct.MonoTypeLayout.html -[`TypeLayout`]: ./type_layout/struct.TypeLayout.html -[`SharedVars`]: ./type_layout/struct.SharedVars.html - -*/ +/// Can be used to construct [`CompGenericParams`], +/// when manually implementing [`StableAbi`]. +/// +/// This stores indices and ranges for the type and/or const parameters taken +/// from the [`SharedVars`] stored in the same [`TypeLayout`] where this is stored. +/// +/// # Syntax +/// +/// `tl_genparams!( (),* ; ; )` +/// +/// `` is a range of indices into a slice: +/// +/// -` `: No elements. +/// +/// -`i`: Uses the `i`th element. +/// +/// -`i..j`: Uses the elements from i up to j (exclusive). +/// +/// -`i..=j`: Uses the elements from i up to j (inclusive). +/// +/// -`x: StartLen`: Uses the elements from `x.start()` up to `x.end()` (exclusive). +/// +/// For type parameters, this conceptually references the elements from +/// the slice returned by [`SharedVars::type_layouts`]. +/// +/// For const parameters, this conceptually references the elements from +/// the slice returned by [`SharedVars::constants`]. +/// +/// +/// # Example +/// +/// ```rust +/// use abi_stable::{ +/// type_layout::CompGenericParams, +/// tl_genparams, +/// }; +/// +/// const NO_ARGUMENTS: CompGenericParams = tl_genparams!(;;); +/// +/// const THREE_TYPE_ARGUMENTS: CompGenericParams = tl_genparams!(; 0..=2;); +/// +/// const ALL_ARGUMENTS: CompGenericParams = tl_genparams!('a,'b,'c,'d; 0; 0..3); +/// +/// ``` +/// +/// +/// +/// [`MonoTypeLayout`]: ./type_layout/struct.MonoTypeLayout.html +/// [`TypeLayout`]: ./type_layout/struct.TypeLayout.html +/// [`SharedVars`]: ./type_layout/struct.SharedVars.html +/// [`SharedVars::type_layouts`]: ./type_layout/struct.SharedVars.html#method.type_layouts +/// [`SharedVars::constants`]: ./type_layout/struct.SharedVars.html#method.constants +/// [`StableAbi`]: ./trait.StableAbi.html +/// [`CompGenericParams`]: ./type_layout/struct.CompGenericParams.html +/// #[macro_export] macro_rules! tl_genparams { - (count; ) => ( 0 ); - (count; $v0:lifetime) => ( 1 ); - (count; $v0:lifetime,$v1:lifetime $(,$rem:lifetime)*) => ( - 2 + $crate::tl_genparams!(count; $($rem),* ) - ); ( $($lt:lifetime),* $(,)? ; $($ty:expr)? ; $($const_p:expr)? ) => ({ - #[allow(unused_imports)] - use $crate::{ - type_layout::CompGenericParams, - }; - #[allow(unused_parens)] - let ty_param_range=$crate::type_layout::StartLenConverter( ($($ty)?) ).to_start_len(); + let ty_param_range = + $crate::type_layout::StartLenConverter( ($($ty)?) ).to_start_len(); #[allow(unused_parens)] let const_param_range= $crate::type_layout::StartLenConverter( ($($const_p)?) ).to_start_len(); - CompGenericParams::new( + $crate::type_layout::CompGenericParams::new( $crate::nulstr_trunc!($crate::pmr::concat!($(stringify!($lt),",",)*)), - $crate::tl_genparams!(count; $($lt),* ), + $crate::pmr::count_tts!(($($lt)*)) as u8, ty_param_range, const_param_range, ) @@ -356,57 +307,51 @@ macro_rules! impl_get_type_info { /////////////////////////////////////////////////////////////////////////////////////////// -/** -Constructs a [`Tag`], -a dynamically typed value for users to check extra properties about their types -when doing runtime type checking. - -Note that this macro is not recursive, -you need to invoke it every time you construct an array/map/set inside of the macro. - -For more examples look in the [tagging module](./type_layout/tagging/index.html) - -# Example - -Using tags to store the traits the type requires, -so that if this changes it can be reported as an error. - -This will cause an error if the binary and dynamic library disagree about the values inside -the "required traits" map entry . - -In real code this should be written in a -way that keeps the tags and the type bounds in sync. - - -*/ -#[cfg_attr(not(feature = "no_fn_promotion"), doc = "```rust")] -#[cfg_attr(feature = "no_fn_promotion", doc = "```ignore")] -/** -use abi_stable::{ - tag, - type_layout::Tag, - StableAbi, -}; - -const TAGS:Tag=tag!{{ - "required traits"=>tag![[ "Copy" ]], -}}; - - -#[repr(C)] -#[derive(StableAbi)] -#[sabi(bound="T:Copy")] -#[sabi(tag="TAGS")] -struct Value{ - value:T, -} - - -``` - -[`Tag`]: ./type_layout/tagging/struct.Tag.html - -*/ +/// Constructs a [`Tag`](./type_layout/tagging/struct.Tag.html), +/// a dynamically typed value for users to check extra properties about their types +/// when doing runtime type checking. +/// +/// Note that this macro is not recursive, +/// you need to invoke it every time you construct an array/map/set inside of the macro. +/// +/// For more examples look in the [tagging module](./type_layout/tagging/index.html) +/// +/// # Example +/// +/// Using tags to store the traits the type requires, +/// so that if this changes it can be reported as an error. +/// +/// This will cause an error if the binary and dynamic library disagree about the values inside +/// the "required traits" map entry . +/// +/// In real code this should be written in a +/// way that keeps the tags and the type bounds in sync. +/// +/// ```rust +/// use abi_stable::{ +/// tag, +/// type_layout::Tag, +/// StableAbi, +/// }; +/// +/// const TAGS: Tag = tag!{{ +/// "required traits" => tag![["Copy"]], +/// }}; +/// +/// +/// #[repr(C)] +/// #[derive(StableAbi)] +/// #[sabi(bound = "T: Copy")] +/// #[sabi(tag = "TAGS")] +/// struct Value{ +/// value: T, +/// } +/// +/// +/// ``` +/// +/// [`Tag`]: ./type_layout/tagging/struct.Tag.html +/// #[macro_export] macro_rules! tag { ([ $( $elem:expr ),* $(,)? ])=>{{ @@ -804,17 +749,38 @@ macro_rules! make_shared_vars{ /////////////////////////////////////////////////////////////////////////////// -/// Allows declaring a [`StaticRef`] associated `const`ant. +/// Allows declaring a [`StaticRef`] inherent associated `const`ant +/// from possibly non-`'static` references. /// -/// This macro is for declaring inherent associated constant of non-`'static` types. +/// This only works in inherent implementations. /// -/// # Breaking changes +/// This does not work in: /// -/// This macro may be changed to produce compiler-errors when it's used to -/// declare a non-associated `const`, or a constant in a trait implementation. +/// - trait definitions +/// - trait implementations. +/// - modules: to define a non-associated constant. /// /// # Example /// +/// ### Basic +/// +/// ```rust +/// use abi_stable::staticref; +/// +/// struct NONE_REF(T); +/// +/// impl NONE_REF { +/// // Declares a `StaticRef>` that points to a `None`, for any `T`. +/// staticref!(const V: Option = None); +/// } +/// +/// let none_string: &'static Option = NONE_REF::::V.get(); +/// assert_eq!(none_string, &None::); +/// +/// ``` +/// +/// ### More realistic +/// /// This example demonstrates how you can construct a pointer to a vtable, /// constructed at compile-time. /// @@ -943,21 +909,22 @@ macro_rules! staticref{ );* $(;)? )=>{ - $( - $(#[$attr])* - $vis const $name : $crate::sabi_types::StaticRef<$ty> = { - // Generating a random base36 string to avoid name collisions - const fn __sabi_mtuxotq5otc3ntu5mdq4ntgwmzi( - x: &T - ) -> $crate::sabi_types::StaticRef { - unsafe{ - $crate::sabi_types::StaticRef::from_raw(x) - } - } - - __sabi_mtuxotq5otc3ntu5mdq4ntgwmzi( &$crate::pmr::identity::<$ty>($expr) ) - }; - )* + $crate::pmr::paste!{ + $( + #[allow(unused_parens)] + #[doc(hidden)] + const [<$name _NHPMWYD3NJA>] : *const ($ty) = &($expr); + + #[allow(unused_parens)] + $(#[$attr])* + $vis const $name : $crate::sabi_types::StaticRef<($ty)> = unsafe{ + $crate::sabi_types::StaticRef::from_raw( + Self::[<$name _NHPMWYD3NJA>] + ) + }; + )* + } + }; } diff --git a/abi_stable/src/pointer_trait.rs b/abi_stable/src/pointer_trait.rs index ed088e9c..6fe4b791 100644 --- a/abi_stable/src/pointer_trait.rs +++ b/abi_stable/src/pointer_trait.rs @@ -39,31 +39,59 @@ pub enum Deallocate { /// What kind of pointer this is. /// -/// The valid kinds are: -/// -/// - Reference:a `&T`,or a `Copy` wrapper struct containing a `&T` -/// -/// - MutReference:a `&mut T`,or a non-`Drop` wrapper struct containing a `&mut T` +/// # Safety /// -/// - SmartPointer: Any pointer type that's not a reference or a mutable reference. +/// Each associated item describes their requirements for the implementor. /// /// pub unsafe trait GetPointerKind: Sized { /// The kind of the pointer. + /// + /// # Safety for implementor + /// + /// This is what each kind requires to be used as this associated type: + /// + /// - [`PK_Reference`]: `Self` must be a `&T`, + /// or a `Copy` and `#[repr(transparent)]` wrapper around a primitive pointer, + /// with `&T` semantics + /// + /// - [`PK_MutReference`]: `Self` must be a `&mut T`, + /// or a non-`Drop` and `#[repr(transparent)]` wrapper around a + /// primitive pointer, with `&mut T` semantics. + /// + /// - [`PK_SmartPointer`]: Any pointer type that's neither of the two other kinds. + /// + /// + /// [`PK_Reference`]: ./struct.PK_Reference.html + /// [`PK_MutReference`]: ./struct.PK_MutReference.html + /// [`PK_SmartPointer`]: ./struct.PK_SmartPointer.html type Kind: PointerKindVariant; - /// What this pointer points to, - /// if the type implements `std::ops::Deref` it must be the same as - /// `::Target`. + /// What this pointer points to. /// /// This is here so that pointers don't *have to* implement `Deref`. + /// + /// # Safety for implementor + /// + /// If the type implements `std::ops::Deref` this must be the same as + /// `::Target`. + /// type PtrTarget; - /// The kind of the pointer. + /// The value-level version of the [`Kind`](#associatedtype.Kind) associated type. + /// + /// # Safety for implementor + /// + /// This must not be overriden. const KIND: PointerKind = ::VALUE; } -/// A type-level equivalent of a PointerKind variant. +/// For restricting types to the type-level equivalents of [`PointerKind`] variants. +/// +/// This trait is sealed, cannot be implemented outside this module, +/// and won't be implemented for any more types. +/// +/// [`PointerKind`]: ./enum.PointerKind.html pub trait PointerKindVariant: Sealed { /// The value of the PointerKind variant Self is equivalent to. const VALUE: PointerKind; @@ -78,23 +106,29 @@ mod sealed { #[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash, StableAbi)] #[repr(u8)] pub enum PointerKind { - /// a `&T`,or a `Copy` wrapper struct containing a `&T` + /// A `&T`-like pointer Reference, - /// a `&mut T`,or a non-`Drop` wrapper struct containing a `&mut T` + /// a `&mut T`-like pointer MutReference, - /// Any pointer type that's not a reference or a mutable reference. + /// Any pointer type that's neither of the other variants SmartPointer, } -/// The type-level equivalent of `PointerKind::Reference`. +/// The type-level equivalent of [`PointerKind::Reference`]. +/// +/// [`PointerKind::Reference`]: ./enum.PointerKind.html#variant.Reference #[allow(non_camel_case_types)] pub struct PK_Reference; -/// The type-level equivalent of `PointerKind::MutReference`. +/// The type-level equivalent of [`PointerKind::MutReference`]. +/// +/// [`PointerKind::MutReference`]: ./enum.PointerKind.html#variant.MutReference #[allow(non_camel_case_types)] pub struct PK_MutReference; -/// The type-level equivalent of `PointerKind::SmartPointer`. +/// The type-level equivalent of [`PointerKind::SmartPointer`]. +/// +/// [`PointerKind::SmartPointer`]: ./enum.PointerKind.html#variant.SmartPointer #[allow(non_camel_case_types)] pub struct PK_SmartPointer; @@ -733,12 +767,13 @@ impl Drop for DropAllocationMutGuard<'_, T> { /// /// # Safety /// -/// Implementors must only contain a non-null pointer [(*1)](#clarification1). -/// Meaning that they must be `#[repr(transparent)]` wrappers around -/// `&`/`NonNull`/`impl ImmutableRef`. +/// Implementors must be `#[repr(transparent)]` wrappers around +/// `&`/`NonNull`/`impl ImmutableRef`, +/// with any amount of 1-aligned zero-sized fields. /// -/// (*1) -/// They can also contain any amount of zero-sized fields with an alignement of 1. +/// It must be valid to transmute a `NonNull` pointer obtained +/// from [`Self::to_nonnull`](#method.to_nonnull) back into `Self`, +/// producing a pointer just as usable as the original. // // # Implementation notes // @@ -767,13 +802,8 @@ pub unsafe trait ImmutableRef: Copy { /// /// # Safety /// - /// `from` must be one of these: - /// - /// - A pointer from a call to `ImmutableRef::to_nonnull` or - /// `ImmutableRef::to_raw_ptr` on an instance of `Self`, - /// with the same lifetime. - /// - /// - Valid to transmute to Self. + /// `from` must be a pointer from a call to `ImmutableRef::to_nonnull` or + /// `ImmutableRef::to_raw_ptr` on an instance of `Self`. #[inline(always)] unsafe fn from_nonnull(from: NonNull) -> Self { unsafe { Transmuter { from }.to } @@ -819,7 +849,9 @@ unsafe impl<'a, T> ImmutableRef for &'a T { /// A marker type that can be used as a proof that the `T` type parameter of /// `ImmutableRefTarget` -/// implements `ImmutableRef`. +/// implements [`ImmutableRef`]``. +/// +/// [`ImmutableRef`]: ./trait.ImmutableRef.html pub struct ImmutableRefTarget(NonOwningPhantom<(T, U)>); impl Copy for ImmutableRefTarget {} diff --git a/abi_stable/src/sabi_types/nul_str/tests.rs b/abi_stable/src/sabi_types/nul_str/tests.rs index 038e97a2..8d9088de 100644 --- a/abi_stable/src/sabi_types/nul_str/tests.rs +++ b/abi_stable/src/sabi_types/nul_str/tests.rs @@ -43,6 +43,7 @@ fn nulstr_try_from_str_tests() { for (strwn, str) in pairs.iter().copied() { let nuls = [ NulStr::try_from_str(strwn).unwrap(), + #[cfg(feature = "rust_1_46")] NulStr::__try_from_str_unwrapping(strwn), ]; for &nul in &nuls { @@ -64,6 +65,7 @@ fn nulstr_try_from_str_tests() { dbg!(strwn); assert_eq!(NulStr::try_from_str(strwn), Err(err)); + #[cfg(feature = "rust_1_46")] must_panic(file_span!(), || NulStr::__try_from_str_unwrapping(strwn)).unwrap(); } } From 8c34124e662266ad8d55a35eb6c17c39fb093a8b Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Sun, 10 Oct 2021 02:32:35 -0300 Subject: [PATCH 12/32] Improved more docs. Fixed `StaticRef::as_prefix` doc example, it didn't actually use the method before. Added `for_examples::PhantModule` struct --- abi_stable/src/derive_macro_reexports.rs | 2 +- abi_stable/src/for_examples.rs | 18 + abi_stable/src/macros.rs | 340 ++++++++---------- abi_stable/src/prefix_type.rs | 28 +- .../get_static_equivalent.rs | 28 +- .../proc_macro_reexports/sabi_extern_fn.rs | 4 +- .../sabi_trait_attribute.rs | 4 +- .../proc_macro_reexports/stable_abi_derive.rs | 190 +++++----- 8 files changed, 307 insertions(+), 307 deletions(-) diff --git a/abi_stable/src/derive_macro_reexports.rs b/abi_stable/src/derive_macro_reexports.rs index cd22d54c..0fbcb04b 100644 --- a/abi_stable/src/derive_macro_reexports.rs +++ b/abi_stable/src/derive_macro_reexports.rs @@ -27,7 +27,7 @@ pub use crate::{ reflection::ModReflMode, sabi_trait::vtable::{RObjectVtable, RObjectVtable_Ref}, sabi_types::{Constructor, MovePtr, RMut, RRef, VersionStrings}, - std_types::{utypeid::new_utypeid, RErr, RNone, ROk, RSlice, RSome}, + std_types::{utypeid::new_utypeid, RErr, RNone, ROk, ROption, RResult, RSlice, RSome}, type_layout::{ CompTLFields, CompTLFunction, DiscriminantRepr, FieldAccessor, GenericTLData, GenericTLEnum, GenericTLPrefixType, IsExhaustive, LifetimeIndex, MakeTLNonExhaustive, diff --git a/abi_stable/src/for_examples.rs b/abi_stable/src/for_examples.rs index 577508e6..0d184ac8 100644 --- a/abi_stable/src/for_examples.rs +++ b/abi_stable/src/for_examples.rs @@ -31,6 +31,24 @@ impl RootModule for Module_Ref { const VERSION_STRINGS: VersionStrings = crate::package_version_strings!(); } +/// This type is used in prefix type examples. +#[repr(C)] +#[derive(StableAbi)] +#[sabi(kind(Prefix(prefix_ref = "PhantModule_Ref", prefix_fields = "PhantModule_Prefix")))] +pub struct PhantModule { + pub first: ROption, + // The `#[sabi(last_prefix_field)]` attribute here means that this is + // the last field in this struct that was defined in the + // first compatible version of the library, + // requiring new fields to always be added after it. + // Moving this attribute is a breaking change, it can only be done in a + // major version bump.. + #[sabi(last_prefix_field)] + pub second: RStr<'static>, + pub third: usize, + pub phantom: std::marker::PhantomData, +} + /// For demonstrating ffi-safe non-exhaustive enums. #[repr(u8)] // #[derive(Debug,Clone,PartialEq)] diff --git a/abi_stable/src/macros.rs b/abi_stable/src/macros.rs index 636ef1b2..70bc4510 100644 --- a/abi_stable/src/macros.rs +++ b/abi_stable/src/macros.rs @@ -83,29 +83,32 @@ macro_rules! tl_genparams { /// Equivalent to `?` for [`RResult`]. /// +/// Accepts both `Result` and `RResult` arguments. +/// /// # Example /// /// Defining an extern function that returns a result. /// /// ``` /// use abi_stable::{ -/// std_types::{RResult, ROk, RErr, RBoxError, RStr, Tuple3}, -/// traits::IntoReprC, +/// std_types::{RResult, ROk, RBoxError, RStr, Tuple3}, /// rtry, /// sabi_extern_fn, /// }; /// /// /// #[sabi_extern_fn] -/// fn parse_tuple(s: RStr<'_>) -> RResult, RBoxError>{ +/// fn parse_tuple(s: RStr<'_>) -> RResult, RBoxError> { /// let mut iter = s.split(',').map(|x| x.trim()); /// ROk(Tuple3( -/// rtry!( iter.next().unwrap_or("").parse().map_err(RBoxError::new).into_c() ), -/// rtry!( iter.next().unwrap_or("").parse().map_err(RBoxError::new).into_c() ), -/// rtry!( iter.next().unwrap_or("").parse().map_err(RBoxError::new).into_c() ), +/// rtry!(iter.next().unwrap_or("").parse().map_err(RBoxError::new)), +/// rtry!(iter.next().unwrap_or("").parse().map_err(RBoxError::new)), +/// rtry!(iter.next().unwrap_or("").parse().map_err(RBoxError::new)), /// )) /// } /// +/// assert_eq!(parse_tuple("3, 5, 8".into()).unwrap(), Tuple3(3, 5, 8)); +/// parse_tuple("".into()).unwrap_err(); /// /// /// ``` @@ -114,7 +117,7 @@ macro_rules! tl_genparams { #[macro_export] macro_rules! rtry { ($expr:expr) => {{ - match $expr.into() { + match $crate::pmr::RResult::from($expr) { $crate::pmr::ROk(x) => x, $crate::pmr::RErr(x) => return $crate::pmr::RErr($crate::pmr::From::from(x)), } @@ -123,11 +126,34 @@ macro_rules! rtry { /// Equivalent to `?` for [`ROption`]. /// +/// Accepts both `Option` and `ROption` arguments. +/// +/// # Example +/// +/// ```rust +/// use abi_stable::{ +/// std_types::{ROption, RSome, RNone}, +/// rtry_opt, +/// sabi_extern_fn, +/// }; +/// +/// +/// #[sabi_extern_fn] +/// fn funct(arg: ROption) -> ROption { +/// let value = rtry_opt!(Some(3)); +/// RSome(value + rtry_opt!(arg)) +/// } +/// +/// assert_eq!(funct(RSome(5)), RSome(8)); +/// assert_eq!(funct(RNone), RNone::); +/// +/// ``` +/// /// [`ROption`]: ./std_types/enum.ROption.html #[macro_export] macro_rules! rtry_opt { ($expr:expr) => {{ - match $expr.into() { + match $crate::pmr::ROption::from($expr) { $crate::pmr::RSome(x) => x, $crate::pmr::RNone => return $crate::pmr::RNone, } @@ -160,7 +186,7 @@ macro_rules! check_unerased { /// This macro by default wraps the passed code in a closure so that any /// early returns that happen inside don't interfere with the macro generated code. /// -/// If you don't have an early return (a `return`/`continue`/`break`) +/// If you don't have an early return (a `return`/`continue`/`break`/`?`/etc.) /// in the code passed to this macro you can use /// `extern_fn_panic_handling!{no_early_return; }`, /// which *might* be cheaper(this has not been tested yet). @@ -176,14 +202,14 @@ macro_rules! check_unerased { /// }; /// /// -/// pub extern "C" fn print_debug(this: &T,buf: &mut RString) +/// pub extern "C" fn print_debug(this: &T, buf: &mut RString) /// where /// T: fmt::Debug, /// { /// extern_fn_panic_handling! { /// use std::fmt::Write; /// -/// println!("{:?}",this); +/// println!("{:?}", this); /// } /// } /// ``` @@ -200,14 +226,14 @@ macro_rules! check_unerased { /// }; /// /// -/// pub extern "C" fn print_debug(this: &T,buf: &mut RString) +/// pub extern "C" fn print_debug(this: &T, buf: &mut RString) /// where /// T: fmt::Debug, /// { /// extern_fn_panic_handling!{no_early_return; /// use std::fmt::Write; /// -/// println!("{:?}",this); +/// println!("{:?}", this); /// } /// } /// @@ -423,29 +449,28 @@ macro_rules! make_item_info { /////////////////////////////////////////////////////////////////////////////// -/** -Constructs an [`RVec`] using the same syntax that the `std::vec` macro uses. - -# Example - -``` - -use abi_stable::{ - rvec, - std_types::RVec, -}; - -assert_eq!(RVec::::new(), rvec![]); -assert_eq!(RVec::from(vec![0]), rvec![0]); -assert_eq!(RVec::from(vec![0,3]), rvec![0,3]); -assert_eq!(RVec::from(vec![0,3,6]), rvec![0,3,6]); -assert_eq!(RVec::from(vec![1;10]), rvec![1;10]); - -``` - -[`RVec`]: ./std_types/struct.RVec.html - -*/ +/// Constructs an [`RVec`] using the same syntax that the [`std::vec`] macro uses. +/// +/// # Example +/// +/// ``` +/// +/// use abi_stable::{ +/// rvec, +/// std_types::RVec, +/// }; +/// +/// assert_eq!(RVec::::new(), rvec![]); +/// assert_eq!(RVec::from(vec![0]), rvec![0]); +/// assert_eq!(RVec::from(vec![0, 3]), rvec![0, 3]); +/// assert_eq!(RVec::from(vec![0, 3, 6]), rvec![0, 3, 6]); +/// assert_eq!(RVec::from(vec![1; 10]), rvec![1; 10]); +/// +/// ``` +/// +/// [`RVec`]: ./std_types/struct.RVec.html +/// +/// [`std::vec`]: https://doc.rust-lang.org/std/macro.vec.html #[macro_export] macro_rules! rvec { ( $( $anything:tt )* ) => ( @@ -455,32 +480,29 @@ macro_rules! rvec { /////////////////////////////////////////////////////////////////////////////// -/** -Use this macro to construct a `abi_stable::std_types::Tuple*` -with the values passed to the macro. - -# Example - -``` -use abi_stable::{ - rtuple, - std_types::{Tuple1,Tuple2,Tuple3,Tuple4}, -}; - -assert_eq!(rtuple!(), ()); - -assert_eq!(rtuple!(3), Tuple1(3)); - -assert_eq!(rtuple!(3,5), Tuple2(3,5)); - -assert_eq!(rtuple!(3,5,8), Tuple3(3,5,8)); - -assert_eq!(rtuple!(3,5,8,9), Tuple4(3,5,8,9)); - -``` - -*/ - +/// Use this macro to construct a `abi_stable::std_types::Tuple*` +/// with the values passed to the macro. +/// +/// # Example +/// +/// ``` +/// use abi_stable::{ +/// rtuple, +/// std_types::{Tuple1, Tuple2, Tuple3, Tuple4}, +/// }; +/// +/// assert_eq!(rtuple!(), ()); +/// +/// assert_eq!(rtuple!(3), Tuple1(3)); +/// +/// assert_eq!(rtuple!(3, 5), Tuple2(3, 5)); +/// +/// assert_eq!(rtuple!(3, 5, 8), Tuple3(3, 5, 8)); +/// +/// assert_eq!(rtuple!(3, 5, 8, 9), Tuple4(3, 5, 8, 9)); +/// +/// ``` +/// #[macro_export] macro_rules! rtuple { () => { @@ -500,31 +522,27 @@ macro_rules! rtuple { }; } -/** -Use this macro to get the type of a `Tuple*` with the types passed to the macro. - -# Example - -``` -use abi_stable::{ - RTuple, - std_types::{Tuple1,Tuple2,Tuple3,Tuple4}, -}; - -let tuple0:RTuple!()=(); - -let tuple1:RTuple!(i32)=Tuple1(3); - -let tuple2:RTuple!(i32,i32,)=Tuple2(3,5); - -let tuple3:RTuple!(i32,i32,u32,)=Tuple3(3,5,8); - -let tuple4:RTuple!(i32,i32,u32,u32)=Tuple4(3,5,8,9); - - -``` - -*/ +/// Use this macro to get the type of a `Tuple*` with the types passed to the macro. +/// +/// # Example +/// +/// ``` +/// use abi_stable::{ +/// std_types::{Tuple1, Tuple2, Tuple3, Tuple4}, +/// RTuple, +/// }; +/// +/// let tuple0: RTuple!() = (); +/// +/// let tuple1: RTuple!(i32) = Tuple1(3); +/// +/// let tuple2: RTuple!(i32, i32) = Tuple2(3, 5); +/// +/// let tuple3: RTuple!(i32, i32, u32) = Tuple3(3, 5, 8); +/// +/// let tuple4: RTuple!(i32, i32, u32, u32) = Tuple4(3, 5, 8, 9); +/// ``` +/// #[macro_export] macro_rules! RTuple { () => ( @@ -546,52 +564,34 @@ macro_rules! RTuple { /////////////////////////////////////////////////////////////////////////////// -/** -A macro to construct [`RSlice`] constants. - -# Examples - -``` -use abi_stable::{ - std_types::RSlice, - rslice, -}; - -const RSLICE_0:RSlice<'static,u8>=rslice![]; -const RSLICE_1:RSlice<'static,u8>=rslice![1]; -const RSLICE_2:RSlice<'static,u8>=rslice![1,2]; -const RSLICE_3:RSlice<'static,u8>=rslice![1,2,3]; -const RSLICE_4:RSlice<'static,u8>=rslice![1,2,3,5]; -const RSLICE_5:RSlice<'static,u8>=rslice![1,2,3,5,8]; -const RSLICE_6:RSlice<'static,u8>=rslice![1,2,3,5,8,13]; - -assert_eq!( RSLICE_0.as_slice(), <&[u8]>::default() ); -assert_eq!( RSLICE_0.len(), 0 ); - -assert_eq!( RSLICE_1.as_slice(), &[1] ); -assert_eq!( RSLICE_1.len(), 1 ); - -assert_eq!( RSLICE_2.as_slice(), &[1,2] ); -assert_eq!( RSLICE_2.len(), 2 ); - -assert_eq!( RSLICE_3.as_slice(), &[1,2,3] ); -assert_eq!( RSLICE_3.len(), 3 ); - -assert_eq!( RSLICE_4.as_slice(), &[1,2,3,5] ); -assert_eq!( RSLICE_4.len(), 4 ); - -assert_eq!( RSLICE_5.as_slice(), &[1,2,3,5,8] ); -assert_eq!( RSLICE_5.len(), 5 ); - -assert_eq!( RSLICE_6.as_slice(), &[1,2,3,5,8,13] ); -assert_eq!( RSLICE_6.len(), 6 ); - - -``` - -[`RSlice`]: ./std_types/struct.RSlice.html - -*/ +/// A macro to construct [`RSlice`]s. +/// +/// When this macro doesn't work(due to lifetime issues), +/// you'll have to separately create a slice, +/// then pass it to the [`RSlice::from_slice`] const function. +/// +/// # Examples +/// +/// ``` +/// use abi_stable::{ +/// std_types::RSlice, +/// rslice, +/// }; +/// +/// +/// const EMPTY: RSlice<'_, u8> = rslice![]; +/// // `RSlice<'_, T>`s can be compared with `&[T]`s +/// assert_eq!(EMPTY, <&[u8]>::default()); +/// +/// const FOO: RSlice<'_,u8> = rslice![1, 2, 3, 5, 8, 13]; +/// assert_eq!(FOO[..], [1, 2, 3, 5, 8, 13]); +/// +/// ``` +/// +/// [`RSlice`]: ./std_types/struct.RSlice.html +/// +/// [`RSlice::from_slice`]: ./std_types/struct.RSlice.html#method.from_slice +/// #[macro_export] macro_rules! rslice { ( $( $elem:expr ),* $(,)* ) => { @@ -601,51 +601,29 @@ macro_rules! rslice { /////////////////////////////////////////////////////////////////////////////// -/** -A macro to construct [`RStr`] constants. - -# Examples - -``` -use abi_stable::{ - std_types::RStr, - rstr, -}; - -const RSTR_0:RStr<'static>=rstr!(""); -const RSTR_1:RStr<'static>=rstr!("1"); -const RSTR_2:RStr<'static>=rstr!("12"); -const RSTR_3:RStr<'static>=rstr!("123"); -const RSTR_4:RStr<'static>=rstr!("1235"); -const RSTR_5:RStr<'static>=rstr!("12358"); -const RSTR_6:RStr<'static>=rstr!("1235813"); - -assert_eq!( RSTR_0.as_str(), "" ); -assert_eq!( RSTR_0.len(), 0 ); - -assert_eq!( RSTR_1.as_str(), "1" ); -assert_eq!( RSTR_1.len(), 1 ); - -assert_eq!( RSTR_2.as_str(), "12" ); -assert_eq!( RSTR_2.len(), 2 ); - -assert_eq!( RSTR_3.as_str(), "123" ); -assert_eq!( RSTR_3.len(), 3 ); - -assert_eq!( RSTR_4.as_str(), "1235" ); -assert_eq!( RSTR_4.len(), 4 ); - -assert_eq!( RSTR_5.as_str(), "12358" ); -assert_eq!( RSTR_5.len(), 5 ); - -assert_eq!( RSTR_6.as_str(), "1235813" ); -assert_eq!( RSTR_6.len(), 7 ); - -``` - -[`RStr`]: ./std_types/struct.RStr.html - -*/ +/// Constructs [`RStr`] constants from `&'static str` constants. +/// +/// # Examples +/// +/// ``` +/// use abi_stable::{ +/// std_types::RStr, +/// rstr, +/// }; +/// +/// +/// const FOO: RStr<'_> = rstr!(""); +/// // `RStr<'_>`s can be compared with `&str`s +/// assert_eq!(FOO, ""); +/// +/// const BAR_STR: &str = "1235813"; +/// // constructing `RStr<'_>` from a `&str` non-literal constant +/// const BAR: RStr<'_> = rstr!(BAR_STR); +/// assert_eq!(BAR, "1235813"); +/// ``` +/// +/// [`RStr`]: ./std_types/struct.RStr.html +/// #[macro_export] macro_rules! rstr { ( $str:expr ) => {{ @@ -655,10 +633,8 @@ macro_rules! rstr { }}; } -/** -Constructs a RStr with the concatenation of the passed in strings, -and variables with the range for the individual strings. -*/ +/// Constructs a RStr with the concatenation of the passed in strings, +/// and variables with the range for the individual strings. macro_rules! multi_str { ( $( #[$mod_attr:meta] )* diff --git a/abi_stable/src/prefix_type.rs b/abi_stable/src/prefix_type.rs index 0d3929ea..e9f58fee 100644 --- a/abi_stable/src/prefix_type.rs +++ b/abi_stable/src/prefix_type.rs @@ -296,23 +296,29 @@ impl StaticRef> { /// /// ```rust /// use abi_stable::{ - /// for_examples::{Module, Module_Ref}, + /// for_examples::{PhantModule, PhantModule_Ref}, /// prefix_type::{PrefixRef, PrefixTypeTrait, WithMetadata}, /// std_types::{RNone, RStr}, /// staticref, /// }; /// - /// // The `staticref` invocation here declares a `StaticRef>` constant. - /// const WITH_META: &WithMetadata = &WithMetadata::new( - /// PrefixTypeTrait::METADATA, - /// Module { - /// first: RNone, - /// second: RStr::from_str("hello"), - /// third: 100, - /// }, - /// ); + /// struct Foo(T); /// - /// const MOD: Module_Ref = Module_Ref(WITH_META.static_as_prefix()); + /// impl Foo { + /// // The `staticref` invocation here declares a + /// // `StaticRef>>` constant. + /// staticref!(const WITH_META: WithMetadata> = WithMetadata::new( + /// PrefixTypeTrait::METADATA, + /// PhantModule { + /// first: RNone, + /// second: RStr::from_str("hello"), + /// third: 100, + /// phantom: std::marker::PhantomData, + /// }, + /// )); + /// } + /// + /// const MOD: PhantModule_Ref<()> = PhantModule_Ref(Foo::WITH_META.as_prefix()); /// /// assert_eq!(MOD.first(), RNone); /// assert_eq!(MOD.second().as_str(), "hello"); diff --git a/abi_stable/src/proc_macro_reexports/get_static_equivalent.rs b/abi_stable/src/proc_macro_reexports/get_static_equivalent.rs index 5917df21..1c80b07f 100644 --- a/abi_stable/src/proc_macro_reexports/get_static_equivalent.rs +++ b/abi_stable/src/proc_macro_reexports/get_static_equivalent.rs @@ -10,20 +10,20 @@ that used the `#[sabi(not_stableabi(TypeParameter))]` helper attribute. These helper attributes are applied on the type declaration. - + ### `#[sabi(impl_InterfaceType(...))]` Implements the `InterfaceType` trait for a type, defining the usable/required traits when creating a -`DynTrait<_,ThisType>`/`NonExhaustive<_,_,ThisType>`. +`DynTrait<_, ThisType>`/`NonExhaustive<_, _, ThisType>`. -Syntax:`#[sabi(impl_InterfaceType(Trait0,Trait1,...,TraitN))]` +Syntax: `#[sabi(impl_InterfaceType(Trait0, Trait1, ..., TraitN))]` If a trait is not specified, it will not be required when constructing DynTrait/NonExhaustive, and won't be usable afterwards. -
+ The list of valid traits is here @@ -52,38 +52,38 @@ use abi_stable::{ #[derive(StableAbi)] #[sabi( not_stableabi(T), - bound="T:WithName", - tag="tag!( ::NAME )", + bound = "T: WithName", + tag = "tag!( ::NAME )", )] struct WithMarker(UnsafeIgnoredType); impl WithMarker{ - const NEW:Self=WithMarker(UnsafeIgnoredType::NEW); + const NEW: Self = WithMarker(UnsafeIgnoredType::NEW); } trait WithName{ - const NAME:&'static str; + const NAME: &'static str; } #[derive(GetStaticEquivalent)] struct Mark; impl WithName for Mark{ - const NAME:&'static str="Mark"; + const NAME: &'static str = "Mark"; } #[derive(GetStaticEquivalent)] struct John; impl WithName for John{ - const NAME:&'static str="John"; + const NAME: &'static str = "John"; } #[derive(GetStaticEquivalent)] struct JessiJames; impl WithName for JessiJames{ - const NAME:&'static str="JessiJames"; + const NAME: &'static str = "JessiJames"; } @@ -133,13 +133,13 @@ use abi_stable::{ #[derive(StableAbi)] #[sabi( not_stableabi(I), - bound="::Item : StableAbi", + bound = "::Item : StableAbi", )] pub struct CollectedIterator where - I:IntoIterator + I: IntoIterator { - vec:RVec, + vec: RVec, } diff --git a/abi_stable/src/proc_macro_reexports/sabi_extern_fn.rs b/abi_stable/src/proc_macro_reexports/sabi_extern_fn.rs index c7f0de29..961b5cc9 100644 --- a/abi_stable/src/proc_macro_reexports/sabi_extern_fn.rs +++ b/abi_stable/src/proc_macro_reexports/sabi_extern_fn.rs @@ -46,7 +46,7 @@ use abi_stable::{ }; #[sabi_extern_fn] -fn collect_into_lines(text:&str) -> RVec>{ +fn collect_into_lines(text: &str) -> RVec>{ text.lines() .filter(|x| !x.is_empty() ) .map(RStr::from) @@ -68,7 +68,7 @@ You can use `#[sabi_extern_fn(no_early_return)]` to potentially improve the runtime performance of the annotated function (this has not been tested). This variant of the attribute removes an intermediate closure that is -used to intercept early returns (`?`,`return, and some macros), +used to intercept early returns (`?`, `return`, etc), If this version of the attribute is used on a function which does have an early return, it will (incorrectly) abort the process when it attempts to return early. diff --git a/abi_stable/src/proc_macro_reexports/sabi_trait_attribute.rs b/abi_stable/src/proc_macro_reexports/sabi_trait_attribute.rs index cc0e7911..02c37365 100644 --- a/abi_stable/src/proc_macro_reexports/sabi_trait_attribute.rs +++ b/abi_stable/src/proc_macro_reexports/sabi_trait_attribute.rs @@ -376,7 +376,7 @@ pub trait Dictionary: Debug + Clone { // You can only unerase a trait object if it was constructed with `TD_CanDowncast` // and it's being unerased into a type that implements `std::any::Any`. - let map: RBox>=object.obj.downcast_into().unwrap(); + let map: RBox> = object.obj.downcast_into().unwrap(); assert_eq!(map.get("hello".into()), Some(&100)); assert_eq!(map.get("world".into()), Some(&10)); @@ -402,7 +402,7 @@ pub trait Dictionary: Debug + Clone { // Dictionary::insert(&mut object,"what".into(), 99); - let map: RArc>=object.obj.downcast_into().unwrap(); + let map: RArc> = object.obj.downcast_into().unwrap(); assert_eq!(map.get("hello".into()), Some(&100)); assert_eq!(map.get("world".into()), Some(&10)); } diff --git a/abi_stable/src/proc_macro_reexports/stable_abi_derive.rs b/abi_stable/src/proc_macro_reexports/stable_abi_derive.rs index 20bc26a7..fd917a13 100644 --- a/abi_stable/src/proc_macro_reexports/stable_abi_derive.rs +++ b/abi_stable/src/proc_macro_reexports/stable_abi_derive.rs @@ -15,33 +15,33 @@ you must use the full type name and generic arguments. These helper attributes are applied on the type declaration. -### `#[sabi(phantom_field="name:type")]` +### `#[sabi(phantom_field = "name: type")]` Adds a virtual field to the type layout constant, which is checked against the phantom field that was declared in the same order for compatibility. -### `#[sabi(phantom_type_param="type")]` +### `#[sabi(phantom_type_param = "type")]` Adds a virtual type parameter to the type layout constant, which is checked for compatibility. -### `#[sabi(phantom_const_param="constant expression")]` +### `#[sabi(phantom_const_param = "constant expression")]` Adds a virtual const parameter to the type layout constant, which is checked for equality with the vistual const parameter declared in the same order. ### `#[sabi(not_stableabi(TypeParameter))]` -Replaces the implicit `TypeParameter:StableAbi` constraint -with a `TypeParameter:GetStaticEquivalent` constraint. +Replaces the implicit `TypeParameter: StableAbi` constraint +with a `TypeParameter: GetStaticEquivalent` constraint. ### `#[sabi(unsafe_unconstrained(TypeParameter))]` -Removes the implicit `TypeParameter:StableAbi` constraint. +Removes the implicit `TypeParameter: StableAbi` constraint. The type parameter will be ignored when determining whether the type -has already been checked,when loading a dynamic library, +has already been checked, when loading a dynamic library, Don't use this if transmuting this type to have different type parameters, only changing the `#[sabi(unsafe_unconstrained())]` one, @@ -49,23 +49,23 @@ would cause Undefined Behavior. This is only necessary if you are passing `TypeParameter` to `UnsafeIgnoredType` -### `#[sabi(bound="Type:ATrait")]` +### `#[sabi(bound = "Type: ATrait")]` Adds a bound to the `StableAbi` impl. -### `#[sabi(bounds="Type:ATrait,Type2:OtherTrait")]` +### `#[sabi(bounds = "Type: ATrait, Type2: OtherTrait")]` Adds many bounds to the `StableAbi` impl. -### `#[sabi(prefix_bound="Type:ATrait")]` +### `#[sabi(prefix_bound = "Type: ATrait")]` -This is only valid for Prefix types,declared with `#[sabi(kind(Prefix(..)))]`. +This is only valid for Prefix types, declared with `#[sabi(kind(Prefix(..)))]`. Adds a bound to the `PrefixTypeTrait` impl (for the deriving type). -### `#[sabi(prefix_bounds="Type:ATrait,Type2:OtherTrait")]` +### `#[sabi(prefix_bounds = "Type: ATrait, Type2: OtherTrait")]` -This is only valid for Prefix types,declared with `#[sabi(kind(Prefix(..)))]`. +This is only valid for Prefix types, declared with `#[sabi(kind(Prefix(..)))]`. Adds many bound to the `PrefixTypeTrait` impl (for the deriving type). @@ -80,14 +80,14 @@ it won't be checked by the runtime type checker. A type macro is any macro that evaluates to a type. -### `#[sabi(tag=" some_expr ")]` +### `#[sabi(tag = " some_expr ")]` Adds a "tag" associated with the type, a dynamically typed data structure used to encode extra properties about a type. This can only be done once, to add multiple properties you must decide whether you want to use -a map,an array,or a set. +a map, an array, or a set. You can only rely on tags for safety if the specific tags were present since the first compatible version of the library, @@ -100,9 +100,9 @@ or the parents of that one. Sibling means libraries loaded at runtime by the same library/binary (or a parent of that one). -For more information about tags,[look here](./type_layout/tagging/index.html) +For more information about tags, [look here](./type_layout/tagging/index.html) -### `#[sabi(extra_checks="")]` +### `#[sabi(extra_checks = "")]` Adds an `ExtraChecks` trait object associated with the type, which allows encoding and checking extra properties about a type. @@ -114,7 +114,7 @@ For examples of using this attribute ### `#[sabi(debug_print)]` -Prints the generated code,stopping compilation. +Prints the generated code, stopping compilation. ### `#[sabi(kind(Prefix( .. )))]` Declares the struct as being a prefix-type. @@ -127,7 +127,7 @@ that can be extended in semver compatible versions.
Uses "" as the name of the prefix struct.
For more details on prefix-types [look here](./docs/prefix_types/index.html) -- `prefix_fields = "")` (optional: defaults to `_Prefix`): +- `prefix_fields = "")` (optional: defaults to `_Prefix`): Declares a struct with all the field in the deriving type up to(and including) the field with the `#[sabi(last_prefix_field)]` attribute, named "". @@ -144,7 +144,7 @@ For more details on nonexhaustive enums [look here](./docs/sabi_nonexhaustive/in Determines how this type is accessed when treated as a module for reflection. `#[sabi(module_reflection( Module ))]`
-The default reflection mode,treats its the public fields as module items. +The default reflection mode, treats its the public fields as module items. `#[sabi(module_reflection( Opaque ))]`
Treats this as an empty module. @@ -156,70 +156,70 @@ Delegates the treatment of this type as a module to the type it dereferences to. Implements the `InterfaceType` trait for a type, defining the usable/required traits when creating a -`DynTrait<_,ThisType>`/`NonExhaustive<_,_,ThisType>`. +`DynTrait<_, ThisType>`/`NonExhaustive<_, _, ThisType>`. -Syntax:`#[sabi(impl_InterfaceType(Trait0,Trait1,...,TraitN))]` +Syntax: `#[sabi(impl_InterfaceType(Trait0, Trait1, ..., TraitN))]` If a trait is not specified, it will not be required when constructing DynTrait/NonExhaustive, and won't be usable afterwards. - These are the traits you can specify: + These are the traits you can specify: -- Send:Changing this to require/unrequire in minor versions is an abi breaking change. +- `Send`: Changing this to require/unrequire in minor versions is an abi breaking change. -- Sync:Changing this to require/unrequire in minor versions is an abi breaking change. +- `Sync`: Changing this to require/unrequire in minor versions is an abi breaking change. -- Clone +- `Clone` -- Default +- `Default` -- Display +- `Display` -- Debug +- `Debug` -- Eq +- `Eq` -- PartialEq +- `PartialEq` -- Ord +- `Ord` -- PartialOrd +- `PartialOrd` -- Hash +- `Hash` -- Deserialize +- `Deserialize`: corresponds to `serde::Deserialize` -- Serialize +- `Serialize`: corresponds to `serde::Serialize` -- Iterator: +- `Iterator`: this type will also have to implement `abi_stable::erased_types::IteratorItem`. -- DoubleEndedIterator: +- `DoubleEndedIterator`: this type will also have to implement `abi_stable::erased_types::IteratorItem`. -- FmtWrite: corresponds to `std::fmt::Write` . +- `FmtWrite`: corresponds to `std::fmt::Write` . -- IoWrite: corresponds to `std::io::Write` . +- `IoWrite`: corresponds to `std::io::Write` . -- IoSeek: corresponds to `std::io::Seek` . +- `IoSeek`: corresponds to `std::io::Seek` . -- IoRead: corresponds to `std::io::Read` . +- `IoRead`: corresponds to `std::io::Read` . -- IoBufRead: corresponds to `std::io::BufRead` . +- `IoBufRead`: corresponds to `std::io::BufRead` . -- Error +- `Error`: corresponds to `std::error::Error` .
Examples: -- `#[sabi(impl_InterfaceType(Send,Sync))]` +- `#[sabi(impl_InterfaceType(Send, Sync))]` -- `#[sabi(impl_InterfaceType(Send,Sync,Iterator,DoubleEndedIterator))]` +- `#[sabi(impl_InterfaceType(Send, Sync, Iterator, DoubleEndedIterator))]` -- `#[sabi(impl_InterfaceType(Clone,Debug,FmtWrite))]` +- `#[sabi(impl_InterfaceType(Clone, Debug, FmtWrite))]` -- `#[sabi(impl_InterfaceType(Clone,Debug,IoWrite,IoRead))]` +- `#[sabi(impl_InterfaceType(Clone, Debug, IoWrite, IoRead))]` ### `#[sabi(unsafe_opaque_fields]` @@ -243,12 +243,12 @@ which causes Undefined Behavior if the type has a different layout. These helper attributes are applied to fields. -### `#[sabi(rename="ident")]` +### `#[sabi(rename = "ident")]` Renames the field in the generated layout information. Use this when renaming private fields. -### `#[sabi(unsafe_change_type="SomeType")]` +### `#[sabi(unsafe_change_type = "SomeType")]` Changes the type of this field in the generated type layout constant to SomeType. @@ -270,52 +270,52 @@ but doesn't check its layout. This is unsafe because the layout of the type won't be verified when loading the library, which causes Undefined Behavior if the type has a different layout. -### `#[sabi(bound="SomeBound")]` +### `#[sabi(bound = "SomeBound")]` -Adds a `TheFieldType:SomeBound` constraint to the `StableAbi` impl. +Adds a `TheFieldType: SomeBound` constraint to the `StableAbi` impl. Eg: ```ignore -#[sabi(bound="Debug")] -name:RStr<'static>, +#[sabi(bound = "Debug")] +name: RStr<'static>, ``` -adds the `RStr<'static>:Debug` bound to the `StableAbi` impl +adds the `RStr<'static>: Debug` bound to the `StableAbi` impl ### `#[sabi(with_field_indices)]` -This is only valid for Prefix types,declared with `#[sabi(kind(Prefix(..)))]`. +This is only valid for Prefix types, declared with `#[sabi(kind(Prefix(..)))]`. Generates associated constants named `field_index_for_` with the index of each field in the prefix type. Those indices can then be passed to the `abi_stable::prefix_types::panic_on_missing_*` functions to panic on a missing field. -### `#[sabi(accessor_bound="ATrait")]` +### `#[sabi(accessor_bound = "ATrait")]` -This is only valid for Prefix types,declared with `#[sabi(kind(Prefix(..)))]`. +This is only valid for Prefix types, declared with `#[sabi(kind(Prefix(..)))]`. Adds the bound to the field type in the accessor method. ### `#[sabi(last_prefix_field)]` -This is only valid for Prefix types,declared with `#[sabi(kind(Prefix(..)))]`. +This is only valid for Prefix types, declared with `#[sabi(kind(Prefix(..)))]`. Declares that the field it is applied to is the last field in the prefix, where every field up to it is guaranteed to exist. -### `#[sabi(accessible_if=" expression ")]` +### `#[sabi(accessible_if = " expression ")]` -This is only valid for Prefix types,declared with `#[sabi(kind(Prefix(..)))]`. +This is only valid for Prefix types, declared with `#[sabi(kind(Prefix(..)))]`. This attribute turns any field conditional based on the const boolean expression (which must be valid a bool constant). Whether this attribute is aplied to any given prefix field must not change in minor versions. -If `expression` is false,the field won't be accessible, +If `expression` is false, the field won't be accessible, and the type of the field can be anything so long as its size and alignment is compatible. -If `expression` is true,the type of the field must be compatible when checking layout. +If `expression` is true, the type of the field must be compatible when checking layout. If this attribute is apllied to prefix fields, it will only be compatible with other types if they agree on @@ -324,10 +324,10 @@ which accessors are conditional for prefix fields. Prefix fields with this attribute are made private in the generated `_Prefix` struct, without this attribute they keep the visibility. -To do `#[sabi(accessible_if="::CONSTANT")]` you can use the -`#[sabi(prefix_bound="TypeParameter:Trait")]` helper attribute. +To do `#[sabi(accessible_if = "::CONSTANT")]` you can use the +`#[sabi(prefix_bound = "TypeParameter: Trait")]` helper attribute. -### `#[sabi(refl(pub_getter=" function_name "))]` +### `#[sabi(refl(pub_getter = " function_name "))]` Determines the public getter for a field used by reflection. @@ -337,29 +337,29 @@ The function can return either a reference or a value. ### `#[sabi(missing_field( .. ))]` -This is only valid for Prefix types,declared with `#[sabi(kind(Prefix(..)))]`. +This is only valid for Prefix types, declared with `#[sabi(kind(Prefix(..)))]`. -Determines what happens in the accessor method for a field,when the field is missing. +Determines what happens in the accessor method for a field, when the field is missing. The default is that it returns an `Option`, -returning None if the field is absent,Some(field_value) if it's present. +returning None if the field is absent, Some(field_value) if it's present. -If the attribute is on the struct,it's applied to all fields(this is overridable) +If the attribute is on the struct, it's applied to all fields(this is overridable) after the `#[sabi(last_prefix_field)]` attribute. -If the attribute is on a field,it's applied to that field only, +If the attribute is on a field, it's applied to that field only, overriding the setting on the struct. `#[sabi(missing_field(panic))]`
-Panics if the field doesn't exist,with an informative error message. +Panics if the field doesn't exist, with an informative error message. `#[sabi(missing_field(option))]`
-Returns None if the field doesn't exist,Some(fieldvalue) if it does. +Returns None if the field doesn't exist, Some(fieldvalue) if it does. This is the default. -`#[sabi(missing_field(with="somefunction"))]`
+`#[sabi(missing_field(with = "somefunction"))]`
Returns `somefunction()` if the field doesn't exist. -`#[sabi(missing_field(value="some_expression"))]`
+`#[sabi(missing_field(value = "some_expression"))]`
Returns `some_expression` if the field doesn't exist. `#[sabi(missing_field(default))]`
@@ -369,25 +369,25 @@ Returns `Default::default()` if the field doesn't exist. ### `#[sabi(with_constructor)]` -This is only valid for nonexhaustive enums,declared with `#[sabi(kind(WithNonExhaustive(..)))]`. +This is only valid for nonexhaustive enums, declared with `#[sabi(kind(WithNonExhaustive(..)))]`. -Creates constructors for enum variant(s),named the same as the variant(s) with an `_NE` suffix. +Creates constructors for enum variant(s), named the same as the variant(s) with an `_NE` suffix. This attribute can be overriden on variants(when it was also applied to the Container itself). For a variant like this: -`VariantNamed{foo:RString,bar:RBox}` +`VariantNamed{foo: RString, bar: RBox}` it would generate an associated function like this(the exact generated code might differ a bit): ```ignore -fn VariantNamed_NE(foo:RString,bar:RBox)->Enum_NE{ - let x=Enum::VariantNamed{foo,bar}; +fn VariantNamed_NE(foo: RString, bar: RBox)->Enum_NE{ + let x = Enum::VariantNamed{foo, bar}; NonExhaustive::new(x) } ``` ### `#[sabi(with_boxed_constructor)]` -This is only valid for nonexhaustive enums,declared with `#[sabi(kind(WithNonExhaustive(..)))]`. +This is only valid for nonexhaustive enums, declared with `#[sabi(kind(WithNonExhaustive(..)))]`. Creates constructors for enum variant(s) which only contain a pointer, named the same as the variant(s) with an `_NE` suffix. @@ -403,9 +403,9 @@ For a variant like this: it would generate an associated function like this(the exact generated code might differ a bit): ```ignore -fn VariantNamed_NE(value:T)->Enum_NE{ - let x=RBox::new(value); - let x=Enum::VariantNamed(x); +fn VariantNamed_NE(value: T)->Enum_NE{ + let x = RBox::new(value); + let x = Enum::VariantNamed(x); NonExhaustive::new(x) } ``` @@ -414,13 +414,13 @@ fn VariantNamed_NE(value:T)->Enum_NE{ For a variant like this: -`VariantNamed{ptr_:MyPointer}` +`VariantNamed{ptr_: MyPointer}` it would generate an associated function like this(the exact generated code might differ a bit): ```ignore -fn VariantNamed_NE(value:T)->Enum_NE{ - let x=MyPointer::new(value); - let x=Enum::VariantNamed{ptr_:x}; +fn VariantNamed_NE(value: T)->Enum_NE{ + let x = MyPointer::new(value); + let x = Enum::VariantNamed{ptr_: x}; NonExhaustive::new(x) } ``` @@ -431,9 +431,9 @@ For a variant like this: it would generate an associated function like this(the exact generated code might differ a bit): ```ignore -fn VariantNamed_NE(value:::Target)->Enum_NE{ - let x=BoxedStruct::new(value); - let x=Enum::VariantNamed(x); +fn VariantNamed_NE(value: ::Target)->Enum_NE{ + let x = BoxedStruct::new(value); + let x = Enum::VariantNamed(x); NonExhaustive::new(x) } ``` @@ -478,8 +478,8 @@ use abi_stable::StableAbi; #[repr(C)] #[derive(StableAbi)] struct Point2D{ - x:u32, - y:u32, + x: u32, + y: u32, } ``` @@ -493,7 +493,7 @@ use abi_stable::StableAbi; #[repr(transparent)] #[derive(StableAbi)] pub struct Wrapper{ - pub inner:T + pub inner: T } ``` @@ -515,7 +515,7 @@ pub enum Command{ LaunchRockets, EatLaundry, WakeTheDragon{ - using:RString + using: RString } } From 40aea6931938e58a06bacf5ae2c19a2f85579faa Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Sun, 10 Oct 2021 03:48:12 -0300 Subject: [PATCH 13/32] Added spaces in docs for formatting --- abi_stable/src/std_types/string.rs | 216 ++++++++++----------- abi_stable/src/std_types/time.rs | 24 +-- abi_stable/src/std_types/tuple.rs | 12 +- abi_stable/src/std_types/utypeid.rs | 4 +- abi_stable/src/std_types/vec.rs | 290 ++++++++++++++-------------- abi_stable/src/type_level.rs | 4 +- abi_stable/src/utils.rs | 20 +- 7 files changed, 284 insertions(+), 286 deletions(-) diff --git a/abi_stable/src/std_types/string.rs b/abi_stable/src/std_types/string.rs index 5c58c73a..a7979c35 100644 --- a/abi_stable/src/std_types/string.rs +++ b/abi_stable/src/std_types/string.rs @@ -23,7 +23,7 @@ use crate::std_types::{RStr, RVec}; mod iters; #[cfg(test)] -// #[cfg(all(test,not(feature="only_new_tests")))] +// #[cfg(all(test, not(feature = "only_new_tests")))] mod tests; pub use self::iters::{Drain, IntoIter}; @@ -61,16 +61,16 @@ pub struct RString { } impl RString { - /// Creates a new,empty RString. + /// Creates a new, empty RString. /// /// # Example /// /// ``` /// use abi_stable::std_types::RString; /// - /// let str=RString::new(); + /// let str = RString::new(); /// - /// assert_eq!(&str[..],""); + /// assert_eq!(&str[..], ""); /// /// ``` pub const fn new() -> Self { @@ -87,10 +87,10 @@ impl RString { /// ``` /// use abi_stable::std_types::RString; /// - /// let str=RString::with_capacity(10); + /// let str = RString::with_capacity(10); /// - /// assert_eq!(&str[..],""); - /// assert_eq!(str.capacity(),10); + /// assert_eq!(&str[..], ""); + /// assert_eq!(str.capacity(), 10); /// /// ``` pub fn with_capacity(cap: usize) -> Self { @@ -105,14 +105,14 @@ impl RString { /// # Example /// /// ``` - /// use abi_stable::std_types::{RStr,RString}; + /// use abi_stable::std_types::{RStr, RString}; /// - /// let str=RString::from("What is that."); + /// let str = RString::from("What is that."); /// - /// assert_eq!(str.slice(..),RStr::from("What is that.")); - /// assert_eq!(str.slice(..4),RStr::from("What")); - /// assert_eq!(str.slice(4..),RStr::from(" is that.")); - /// assert_eq!(str.slice(4..7),RStr::from(" is")); + /// assert_eq!(str.slice(..), RStr::from("What is that.")); + /// assert_eq!(str.slice(..4), RStr::from("What")); + /// assert_eq!(str.slice(4..), RStr::from(" is that.")); + /// assert_eq!(str.slice(4..7), RStr::from(" is")); /// /// ``` #[inline] @@ -131,8 +131,8 @@ impl RString { /// ``` /// use abi_stable::std_types::RString; /// - /// let str="What is that."; - /// assert_eq!(RString::from(str).as_str(),str); + /// let str = "What is that."; + /// assert_eq!(RString::from(str).as_str(), str); /// /// ``` #[inline] @@ -145,9 +145,9 @@ impl RString { /// # Example /// /// ``` - /// use abi_stable::std_types::{RStr,RString}; + /// use abi_stable::std_types::{RStr, RString}; /// - /// let str="What is that."; + /// let str = "What is that."; /// assert_eq!( /// RString::from(str).as_rstr(), /// RStr::from(str), @@ -166,9 +166,9 @@ impl RString { /// ``` /// use abi_stable::std_types::RString; /// - /// assert_eq!(RString::from("").len(),0); - /// assert_eq!(RString::from("a").len(),1); - /// assert_eq!(RString::from("Regular").len(),7); + /// assert_eq!(RString::from("").len(), 0); + /// assert_eq!(RString::from("a").len(), 1); + /// assert_eq!(RString::from("Regular").len(), 7); /// /// ``` #[inline] @@ -205,15 +205,15 @@ impl RString { /// ``` /// use abi_stable::std_types::RString; /// - /// let mut str=RString::with_capacity(13); + /// let mut str = RString::with_capacity(13); /// - /// assert_eq!(str.capacity(),13); + /// assert_eq!(str.capacity(), 13); /// /// str.push_str("What is that."); - /// assert_eq!(str.capacity(),13); + /// assert_eq!(str.capacity(), 13); /// /// str.push(' '); - /// assert_ne!(str.capacity(),13); + /// assert_ne!(str.capacity(), 13); /// /// ``` #[inline] @@ -232,9 +232,9 @@ impl RString { /// # Examples /// /// ``` - /// use abi_stable::std_types::{RString,RVec}; + /// use abi_stable::std_types::{RString, RVec}; /// - /// let bytes=RVec::from("hello".as_bytes()); + /// let bytes = RVec::from("hello".as_bytes()); /// /// unsafe{ /// assert_eq!( RString::from_utf8_unchecked(bytes).as_str(), "hello" ); @@ -255,10 +255,10 @@ impl RString { /// # Examples /// /// ``` - /// use abi_stable::std_types::{RString,RVec}; + /// use abi_stable::std_types::{RString, RVec}; /// - /// let bytes_ok=RVec::from("hello".as_bytes()); - /// let bytes_err=RVec::from(vec![255]); + /// let bytes_ok = RVec::from("hello".as_bytes()); + /// let bytes_err = RVec::from(vec![255]); /// /// assert_eq!( RString::from_utf8(bytes_ok).unwrap(), RString::from("hello") ); /// assert!( RString::from_utf8(bytes_err).is_err() ); @@ -290,8 +290,8 @@ impl RString { /// ``` /// use abi_stable::std_types::RString; /// - /// let str="What the 😈."; - /// let str_utf16=str.encode_utf16().collect::>(); + /// let str = "What the 😈."; + /// let str_utf16 = str.encode_utf16().collect::>(); /// /// assert_eq!( /// RString::from_utf16(&str_utf16).unwrap(), @@ -307,12 +307,12 @@ impl RString { /// # Example /// /// ``` - /// use abi_stable::std_types::{RString,RVec}; + /// use abi_stable::std_types::{RString, RVec}; /// - /// let bytes=RVec::from("hello".as_bytes()); - /// let str=RString::from("hello"); + /// let bytes = RVec::from("hello".as_bytes()); + /// let str = RString::from("hello"); /// - /// assert_eq!(str.into_bytes(),bytes); + /// assert_eq!(str.into_bytes(), bytes); /// /// ``` pub fn into_bytes(self) -> RVec { @@ -331,10 +331,10 @@ impl RString { /// ``` /// use abi_stable::std_types::RString; /// - /// let std_str=String::from("hello"); - /// let str=RString::from("hello"); + /// let std_str = String::from("hello"); + /// let str = RString::from("hello"); /// - /// assert_eq!(str.into_string(),std_str); + /// assert_eq!(str.into_string(), std_str); /// /// ``` pub fn into_string(self) -> String { @@ -363,7 +363,7 @@ impl RString { /// ``` /// use abi_stable::std_types::RString; /// - /// let mut str=RString::new(); + /// let mut str = RString::new(); /// /// str.reserve(10); /// assert!(str.capacity()>=10); @@ -380,10 +380,10 @@ impl RString { /// ``` /// use abi_stable::std_types::RString; /// - /// let mut str=RString::with_capacity(100); + /// let mut str = RString::with_capacity(100); /// str.push_str("nope"); /// str.shrink_to_fit(); - /// assert_eq!(str.capacity(),4); + /// assert_eq!(str.capacity(), 4); /// /// ``` pub fn shrink_to_fit(&mut self) { @@ -399,10 +399,10 @@ impl RString { /// ``` /// use abi_stable::std_types::RString; /// - /// let mut str=RString::new(); + /// let mut str = RString::new(); /// /// str.reserve_exact(10); - /// assert_eq!(str.capacity(),10); + /// assert_eq!(str.capacity(), 10); /// /// ``` pub fn reserve_exact(&mut self, additional: usize) { @@ -416,13 +416,13 @@ impl RString { /// ``` /// use abi_stable::std_types::RString; /// - /// let mut str=RString::new(); + /// let mut str = RString::new(); /// /// str.push('O'); /// str.push('O'); /// str.push('P'); /// - /// assert_eq!(str.as_str(),"OOP"); + /// assert_eq!(str.as_str(), "OOP"); /// /// ``` pub fn push(&mut self, ch: char) { @@ -439,12 +439,12 @@ impl RString { /// ``` /// use abi_stable::std_types::RString; /// - /// let mut str=RString::new(); + /// let mut str = RString::new(); /// /// str.push_str("green "); /// str.push_str("frog"); /// - /// assert_eq!(str.as_str(),"green frog"); + /// assert_eq!(str.as_str(), "green frog"); /// /// ``` pub fn push_str(&mut self, str: &str) { @@ -458,18 +458,18 @@ impl RString { /// # Example /// /// ``` - /// use abi_stable::std_types::{RString,RVec}; + /// use abi_stable::std_types::{RString, RVec}; /// - /// let mut str=RString::from("yep"); + /// let mut str = RString::from("yep"); /// - /// assert_eq!(str.pop(),Some('p')); - /// assert_eq!(str.pop(),Some('e')); - /// assert_eq!(str.pop(),Some('y')); - /// assert_eq!(str.pop(),None); + /// assert_eq!(str.pop(), Some('p')); + /// assert_eq!(str.pop(), Some('e')); + /// assert_eq!(str.pop(), Some('y')); + /// assert_eq!(str.pop(), None); /// /// ``` pub fn pop(&mut self) -> Option { - // literal copy-paste of std,so if this is wrong std is wrong. + // literal copy-paste of std, so if this is wrong std is wrong. let ch = self.chars().rev().next()?; let newlen = self.len() - ch.len_utf8(); @@ -488,19 +488,19 @@ impl RString { /// # Example /// /// ``` - /// use abi_stable::std_types::{RString,RVec}; + /// use abi_stable::std_types::{RString, RVec}; /// - /// let mut str=RString::from("Galileo"); + /// let mut str = RString::from("Galileo"); /// - /// assert_eq!(str.remove(3),'i'); - /// assert_eq!(str.as_str(),"Galleo"); + /// assert_eq!(str.remove(3), 'i'); + /// assert_eq!(str.as_str(), "Galleo"); /// - /// assert_eq!(str.remove(4),'e'); - /// assert_eq!(str.as_str(),"Gallo"); + /// assert_eq!(str.remove(4), 'e'); + /// assert_eq!(str.as_str(), "Gallo"); /// /// ``` pub fn remove(&mut self, idx: usize) -> char { - // literal copy-paste of std,so if this is wrong std is wrong. + // literal copy-paste of std, so if this is wrong std is wrong. let ch = match self[idx..].chars().next() { Some(ch) => ch, @@ -526,18 +526,18 @@ impl RString { /// # Example /// /// ``` - /// use abi_stable::std_types::{RString,RVec}; + /// use abi_stable::std_types::{RString, RVec}; /// - /// let mut str=RString::from("Cap"); + /// let mut str = RString::from("Cap"); /// - /// str.insert(1,'r'); - /// assert_eq!(str.as_str(),"Crap"); + /// str.insert(1, 'r'); + /// assert_eq!(str.as_str(), "Crap"); /// - /// str.insert(4,'p'); - /// assert_eq!(str.as_str(),"Crapp"); + /// str.insert(4, 'p'); + /// assert_eq!(str.as_str(), "Crapp"); /// - /// str.insert(5,'y'); - /// assert_eq!(str.as_str(),"Crappy"); + /// str.insert(5, 'y'); + /// assert_eq!(str.as_str(), "Crappy"); /// /// ``` pub fn insert(&mut self, idx: usize, ch: char) { @@ -556,22 +556,22 @@ impl RString { /// # Example /// /// ``` - /// use abi_stable::std_types::{RString,RVec}; + /// use abi_stable::std_types::{RString, RVec}; /// - /// let mut str=RString::from("rust"); + /// let mut str = RString::from("rust"); /// - /// str.insert_str(0,"T"); - /// assert_eq!(str.as_str(),"Trust"); + /// str.insert_str(0, "T"); + /// assert_eq!(str.as_str(), "Trust"); /// - /// str.insert_str(5," the source"); - /// assert_eq!(str.as_str(),"Trust the source"); + /// str.insert_str(5, " the source"); + /// assert_eq!(str.as_str(), "Trust the source"); /// - /// str.insert_str(5," the types in"); - /// assert_eq!(str.as_str(),"Trust the types in the source"); + /// str.insert_str(5, " the types in"); + /// assert_eq!(str.as_str(), "Trust the types in the source"); /// /// ``` pub fn insert_str(&mut self, idx: usize, string: &str) { - // literal copy-paste of std,so if this is wrong std is wrong. + // literal copy-paste of std, so if this is wrong std is wrong. assert!(self.is_char_boundary(idx)); @@ -599,22 +599,22 @@ impl RString { /// # Example /// /// ``` - /// use abi_stable::std_types::{RString,RVec}; + /// use abi_stable::std_types::{RString, RVec}; /// /// { - /// let mut str=RString::from("There were 10 people."); + /// let mut str = RString::from("There were 10 people."); /// str.retain(|c| !c.is_numeric() ); - /// assert_eq!(str.as_str(),"There were people."); + /// assert_eq!(str.as_str(), "There were people."); /// } /// { - /// let mut str=RString::from("There were 10 people."); + /// let mut str = RString::from("There were 10 people."); /// str.retain(|c| !c.is_whitespace() ); - /// assert_eq!(str.as_str(),"Therewere10people."); + /// assert_eq!(str.as_str(), "Therewere10people."); /// } /// { - /// let mut str=RString::from("There were 10 people."); + /// let mut str = RString::from("There were 10 people."); /// str.retain(|c| c.is_numeric() ); - /// assert_eq!(str.as_str(),"10"); + /// assert_eq!(str.as_str(), "10"); /// } /// /// ``` @@ -661,20 +661,20 @@ impl RString { } } - /// Turns this into an empty RString,keeping the same allocated buffer. + /// Turns this into an empty RString, keeping the same allocated buffer. /// /// # Example /// /// ``` - /// use abi_stable::std_types::{RString,RVec}; + /// use abi_stable::std_types::{RString, RVec}; /// - /// let mut str=RString::from("Nurse"); + /// let mut str = RString::from("Nurse"); /// - /// assert_eq!(str.as_str(),"Nurse"); + /// assert_eq!(str.as_str(), "Nurse"); /// /// str.clear(); /// - /// assert_eq!(str.as_str(),""); + /// assert_eq!(str.as_str(), ""); /// /// ``` pub fn clear(&mut self) { @@ -804,9 +804,9 @@ impl fmt::Write for RString { } shared_impls! { - mod=string_impls - new_type=RString[][], - original_type=str, + mod = string_impls + new_type = RString[][], + original_type = str, } impl<'de> Deserialize<'de> for RString { @@ -844,39 +844,39 @@ impl RString { ``` use abi_stable::std_types::RString; - let orig="Not a single way"; + let orig = "Not a single way"; { - let mut str=RString::from(orig); + let mut str = RString::from(orig); assert_eq!( str.drain(..).collect::(), orig, ); - assert_eq!(str.as_str(),""); + assert_eq!(str.as_str(), ""); } { - let mut str=RString::from(orig); + let mut str = RString::from(orig); assert_eq!( str.drain(..4).collect::(), "Not ", ); - assert_eq!(str.as_str(),"a single way"); + assert_eq!(str.as_str(), "a single way"); } { - let mut str=RString::from(orig); + let mut str = RString::from(orig); assert_eq!( str.drain(4..).collect::(), "a single way", ); - assert_eq!(str.as_str(),"Not "); + assert_eq!(str.as_str(), "Not "); } { - let mut str=RString::from(orig); + let mut str = RString::from(orig); assert_eq!( str.drain(4..13).collect::(), "a single ", ); - assert_eq!(str.as_str(),"Not way"); + assert_eq!(str.as_str(), "Not way"); } ``` @@ -945,9 +945,9 @@ impl<'a> FromIterator<&'a char> for RString { /// ``` /// use abi_stable::std_types::RString; /// -/// let err=RString::from_utf8(vec![0,0,0,255]).unwrap_err(); +/// let err = RString::from_utf8(vec![0, 0, 0, 255]).unwrap_err(); /// -/// assert_eq!( err.as_bytes() , &[0,0,0,255] ) +/// assert_eq!( err.as_bytes() , &[0, 0, 0, 255] ) /// /// ``` #[derive(Debug)] @@ -962,11 +962,11 @@ impl FromUtf8Error { /// # Example /// /// ``` - /// use abi_stable::std_types::{RString,RVec}; + /// use abi_stable::std_types::{RString, RVec}; /// /// let bytes:RVec= vec![72, 111, 95, 95, 95, 95, 95, 99, 107, 255].into(); /// - /// let err=RString::from_utf8(bytes.clone()).unwrap_err(); + /// let err = RString::from_utf8(bytes.clone()).unwrap_err(); /// /// assert_eq!( err.into_bytes(), bytes ); /// @@ -983,7 +983,7 @@ impl FromUtf8Error { /// /// let bytes= vec![99, 114, 121, 115, 116, 97, 108, 255]; /// - /// let err=RString::from_utf8(bytes.clone()).unwrap_err(); + /// let err = RString::from_utf8(bytes.clone()).unwrap_err(); /// /// assert_eq!( err.as_bytes(), &bytes[..] ); /// @@ -999,7 +999,7 @@ impl FromUtf8Error { /// ``` /// use abi_stable::std_types::RString; /// - /// let err=RString::from_utf8( vec![0, 0, 255] ).unwrap_err(); + /// let err = RString::from_utf8( vec![0, 0, 255] ).unwrap_err(); /// /// assert_eq!( err.error().valid_up_to(), 2 ); /// diff --git a/abi_stable/src/std_types/time.rs b/abi_stable/src/std_types/time.rs index 814d60d3..1d3886a7 100644 --- a/abi_stable/src/std_types/time.rs +++ b/abi_stable/src/std_types/time.rs @@ -11,7 +11,7 @@ use std::time::Duration; /// ``` /// use abi_stable::std_types::RDuration; /// -/// let dur=RDuration::from_millis(31416); +/// let dur = RDuration::from_millis(31416); /// assert_eq!( dur.as_secs(), 31 ); /// assert_eq!( dur.as_nanos(), 31_416_000_000 ); /// @@ -33,7 +33,7 @@ impl RDuration { /// ``` /// use abi_stable::std_types::RDuration; /// - /// let dur=RDuration::new(1,456_000_000); + /// let dur = RDuration::new(1, 456_000_000); /// assert_eq!( dur.as_millis(), 1_456 ); /// assert_eq!( dur.as_micros(), 1_456_000 ); /// @@ -52,7 +52,7 @@ impl RDuration { /// ``` /// use abi_stable::std_types::RDuration; /// - /// let dur=RDuration::from_secs(14); + /// let dur = RDuration::from_secs(14); /// assert_eq!( dur.as_millis(), 14_000 ); /// assert_eq!( dur.as_micros(), 14_000_000 ); /// @@ -71,7 +71,7 @@ impl RDuration { /// ``` /// use abi_stable::std_types::RDuration; /// - /// let dur=RDuration::from_millis(628); + /// let dur = RDuration::from_millis(628); /// assert_eq!( dur.as_micros(), 628_000 ); /// assert_eq!( dur.as_nanos(), 628_000_000 ); /// @@ -90,7 +90,7 @@ impl RDuration { /// ``` /// use abi_stable::std_types::RDuration; /// - /// let dur=RDuration::from_micros(1024); + /// let dur = RDuration::from_micros(1024); /// assert_eq!( dur.as_millis(), 1 ); /// assert_eq!( dur.as_nanos(), 1024_000 ); /// @@ -110,7 +110,7 @@ impl RDuration { /// ``` /// use abi_stable::std_types::RDuration; /// - /// let dur=RDuration::from_nanos(128_256_512); + /// let dur = RDuration::from_nanos(128_256_512); /// assert_eq!( dur.as_millis(), 128 ); /// assert_eq!( dur.as_micros(), 128_256 ); /// @@ -131,7 +131,7 @@ impl RDuration { /// ``` /// use abi_stable::std_types::RDuration; /// - /// let dur=RDuration::from_nanos(64_128_256_512); + /// let dur = RDuration::from_nanos(64_128_256_512); /// assert_eq!( dur.subsec_nanos(), 128_256_512 ); /// /// ``` @@ -146,7 +146,7 @@ impl RDuration { /// ``` /// use abi_stable::std_types::RDuration; /// - /// let dur=RDuration::from_nanos(64_128_256_512); + /// let dur = RDuration::from_nanos(64_128_256_512); /// assert_eq!( dur.seconds(), 64 ); /// /// ``` @@ -161,7 +161,7 @@ impl RDuration { /// ``` /// use abi_stable::std_types::RDuration; /// - /// let dur=RDuration::from_nanos(64_128_256_512); + /// let dur = RDuration::from_nanos(64_128_256_512); /// assert_eq!( dur.as_secs(), 64 ); /// /// ``` @@ -176,7 +176,7 @@ impl RDuration { /// ``` /// use abi_stable::std_types::RDuration; /// - /// let dur=RDuration::from_nanos(64_128_256_512); + /// let dur = RDuration::from_nanos(64_128_256_512); /// assert_eq!( dur.as_millis(), 64_128 ); /// /// ``` @@ -191,7 +191,7 @@ impl RDuration { /// ``` /// use abi_stable::std_types::RDuration; /// - /// let dur=RDuration::from_nanos(64_128_256_512); + /// let dur = RDuration::from_nanos(64_128_256_512); /// assert_eq!( dur.as_micros(), 64_128_256 ); /// /// ``` @@ -206,7 +206,7 @@ impl RDuration { /// ``` /// use abi_stable::std_types::RDuration; /// - /// let dur=RDuration::from_micros(256); + /// let dur = RDuration::from_micros(256); /// assert_eq!( dur.as_nanos(), 256_000 ); /// /// ``` diff --git a/abi_stable/src/std_types/tuple.rs b/abi_stable/src/std_types/tuple.rs index 8f28a7df..dfc3c225 100644 --- a/abi_stable/src/std_types/tuple.rs +++ b/abi_stable/src/std_types/tuple.rs @@ -13,7 +13,7 @@ macro_rules! declare_tuple { $tconstr:ident[$( $tparam:ident ),* $(,)? ] ) => ( $(#[$meta])* - #[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash,StableAbi)] + #[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash, StableAbi)] #[repr(C)] pub struct $tconstr< $($tparam,)* > ( $(pub $tparam,)* @@ -22,7 +22,7 @@ macro_rules! declare_tuple { impl_into_rust_repr! { impl[ $($tparam,)* ] Into<( $($tparam,)* )> for $tconstr< $($tparam,)* > { fn(this){ - let $tconstr($($tparam,)*)=this; + let $tconstr($($tparam,)*) = this; ($($tparam,)*) } } @@ -31,7 +31,7 @@ macro_rules! declare_tuple { impl_from_rust_repr! { impl[ $($tparam,)* ] From<( $($tparam,)* )> for $tconstr< $($tparam,)* > { fn(this){ - let ($($tparam,)*)=this; + let ($($tparam,)*) = this; $tconstr ( $($tparam),* ) } } @@ -83,7 +83,7 @@ declare_tuple! { /// ``` /// use abi_stable::std_types::*; /// - /// assert_eq!( Tuple2(1,2).into_tuple(), (1,2) ); + /// assert_eq!( Tuple2(1, 2).into_tuple(), (1, 2) ); /// /// ``` ] @@ -107,7 +107,7 @@ declare_tuple! { /// ``` /// use abi_stable::std_types::*; /// - /// assert_eq!( Tuple3(1,2,3).into_tuple(), (1,2,3) ); + /// assert_eq!( Tuple3(1, 2, 3).into_tuple(), (1, 2, 3) ); /// /// ``` ] @@ -132,7 +132,7 @@ declare_tuple! { /// ``` /// use abi_stable::std_types::*; /// - /// assert_eq!( Tuple4(1,2,3,4).into_tuple(), (1,2,3,4) ); + /// assert_eq!( Tuple4(1, 2, 3, 4).into_tuple(), (1, 2, 3, 4) ); /// /// ``` ] diff --git a/abi_stable/src/std_types/utypeid.rs b/abi_stable/src/std_types/utypeid.rs index f7d41d5f..41b7ec60 100644 --- a/abi_stable/src/std_types/utypeid.rs +++ b/abi_stable/src/std_types/utypeid.rs @@ -23,7 +23,7 @@ use crate::{sabi_types::MaybeCmp, EXECUTABLE_IDENTITY}; /// use abi_stable::std_types::utypeid::new_utypeid; /// use std::collections::HashMap; /// -/// let hashmap_id=new_utypeid::< HashMap >(); +/// let hashmap_id=new_utypeid::< HashMap >(); /// let vec_id=new_utypeid::< Vec >(); /// let u32_id=new_utypeid::< u32 >(); /// @@ -94,7 +94,7 @@ impl UTypeId { /// use abi_stable::std_types::UTypeId; /// use std::collections::HashMap; /// - /// let id=UTypeId::new::< HashMap >(); + /// let id=UTypeId::new::< HashMap >(); /// # drop(id); /// ``` #[inline(always)] diff --git a/abi_stable/src/std_types/vec.rs b/abi_stable/src/std_types/vec.rs index bc7b20a8..4c51f4ce 100644 --- a/abi_stable/src/std_types/vec.rs +++ b/abi_stable/src/std_types/vec.rs @@ -27,7 +27,7 @@ use crate::{ }; #[cfg(test)] -// #[cfg(all(test,not(feature="only_new_tests")))] +// #[cfg(all(test, not(feature = "only_new_tests")))] mod tests; mod iters; @@ -49,7 +49,7 @@ mod private { ``` use abi_stable::{ - std_types::{RSlice,RVec}, + std_types::{RSlice, RVec}, StableAbi, sabi_extern_fn, }; @@ -57,15 +57,15 @@ mod private { #[repr(C)] #[derive(StableAbi)] pub struct Partitioned{ - pub even:RVec, - pub odd :RVec, + pub even: RVec, + pub odd : RVec, } #[sabi_extern_fn] - pub fn partition_evenness(numbers:RSlice<'_,u32>)->Partitioned{ - let (even,odd)=numbers.iter().cloned().partition(|n| *n % 2 == 0); + pub fn partition_evenness(numbers: RSlice<'_, u32>)->Partitioned{ + let (even, odd) = numbers.iter().cloned().partition(|n| *n % 2 == 0); - Partitioned{even,odd} + Partitioned{even, odd} } ``` @@ -83,7 +83,7 @@ mod private { } impl RVec { - /// Creates a new,empty `RVec`. + /// Creates a new, empty `RVec`. /// /// This function does not allocate. /// @@ -92,7 +92,7 @@ mod private { /// ``` /// use abi_stable::std_types::RVec; /// - /// let list=RVec::::new(); + /// let list = RVec::::new(); /// /// ``` pub const fn new() -> Self { @@ -103,7 +103,7 @@ mod private { // unsafety: // While this implementation is correct, // it would be better to do `RVec::from_vec(Vec::new())` - // when it's possible to call `Vec::{as_mut_ptr,capacity,len}` in const contexts. + // when it's possible to call `Vec::{as_mut_ptr, capacity, len}` in const contexts. RVec { vtable: VTableGetter::::LIB_VTABLE, buffer: std::mem::align_of::() as *mut T, @@ -141,12 +141,12 @@ mod private { /// ``` /// use abi_stable::std_types::RVec; /// - /// let mut list=RVec::new(); + /// let mut list = RVec::new(); /// - /// assert_eq!(list.capacity(),0); + /// assert_eq!(list.capacity(), 0); /// /// list.push(0); - /// assert_ne!(list.capacity(),0); + /// assert_ne!(list.capacity(), 0); /// /// ``` #[inline(always)] @@ -187,7 +187,7 @@ mod private { impl_from_rust_repr! { impl[T] From> for RVec{ fn(this){ - let mut this=ManuallyDrop::new(this); + let mut this = ManuallyDrop::new(this); RVec { vtable: VTableGetter::::LIB_VTABLE, buffer: this.as_mut_ptr(), @@ -203,7 +203,7 @@ mod private { pub use self::private::RVec; impl RVec { - /// Creates a new,empty `RVec`,with a capacity of `cap`. + /// Creates a new, empty `RVec`, with a capacity of `cap`. /// /// This function does not allocate if `cap == 0`. /// @@ -212,36 +212,36 @@ impl RVec { /// ``` /// use abi_stable::std_types::RVec; /// - /// let mut list=RVec::::with_capacity(7); + /// let mut list = RVec::::with_capacity(7); /// - /// assert_eq!(list.len(),0); - /// assert_eq!(list.capacity(),7); + /// assert_eq!(list.len(), 0); + /// assert_eq!(list.capacity(), 7); /// /// list.extend( std::iter::repeat(11).take(7) ); - /// assert_eq!(list.len(),7); - /// assert_eq!(list.capacity(),7); + /// assert_eq!(list.len(), 7); + /// assert_eq!(list.capacity(), 7); /// /// list.push(17); - /// assert_ne!(list.capacity(),7); + /// assert_ne!(list.capacity(), 7); /// ``` pub fn with_capacity(cap: usize) -> Self { Vec::with_capacity(cap).into() } - /// Creates an `RSlice<'a,T>` with access to the `range` range of + /// Creates an `RSlice<'a, T>` with access to the `range` range of /// elements of the `RVec`. /// /// # Example /// /// ``` - /// use abi_stable::std_types::{RSlice,RVec}; + /// use abi_stable::std_types::{RSlice, RVec}; /// - /// let list=RVec::from(vec![0,1,2,3,4,5,6,7,8]); + /// let list = RVec::from(vec![0, 1, 2, 3, 4, 5, 6, 7, 8]); /// - /// assert_eq!( list.slice(..), RSlice::from_slice(&[0,1,2,3,4,5,6,7,8]) ); - /// assert_eq!( list.slice(..4), RSlice::from_slice(&[0,1,2,3]) ); - /// assert_eq!( list.slice(4..), RSlice::from_slice(&[4,5,6,7,8]) ); - /// assert_eq!( list.slice(4..7), RSlice::from_slice(&[4,5,6]) ); + /// assert_eq!( list.slice(..), RSlice::from_slice(&[0, 1, 2, 3, 4, 5, 6, 7, 8]) ); + /// assert_eq!( list.slice(..4), RSlice::from_slice(&[0, 1, 2, 3]) ); + /// assert_eq!( list.slice(4..), RSlice::from_slice(&[4, 5, 6, 7, 8]) ); + /// assert_eq!( list.slice(4..7), RSlice::from_slice(&[4, 5, 6]) ); /// /// ``` #[inline] @@ -253,20 +253,20 @@ impl RVec { (&self[range]).into() } - /// Creates an `RSliceMut<'a,T>` with access to the `range` range of + /// Creates an `RSliceMut<'a, T>` with access to the `range` range of /// elements of the `RVec`. /// /// # Example /// /// ``` - /// use abi_stable::std_types::{RSliceMut,RVec}; + /// use abi_stable::std_types::{RSliceMut, RVec}; /// - /// let mut list=RVec::from(vec![0,1,2,3,4,5,6,7,8]); + /// let mut list = RVec::from(vec![0, 1, 2, 3, 4, 5, 6, 7, 8]); /// - /// assert_eq!( list.slice_mut(..), RSliceMut::from_mut_slice(&mut [0,1,2,3,4,5,6,7,8]) ); - /// assert_eq!( list.slice_mut(..4), RSliceMut::from_mut_slice(&mut [0,1,2,3]) ); - /// assert_eq!( list.slice_mut(4..), RSliceMut::from_mut_slice(&mut [4,5,6,7,8]) ); - /// assert_eq!( list.slice_mut(4..7), RSliceMut::from_mut_slice(&mut [4,5,6]) ); + /// assert_eq!( list.slice_mut(..), RSliceMut::from_mut_slice(&mut [0, 1, 2, 3, 4, 5, 6, 7, 8]) ); + /// assert_eq!( list.slice_mut(..4), RSliceMut::from_mut_slice(&mut [0, 1, 2, 3]) ); + /// assert_eq!( list.slice_mut(4..), RSliceMut::from_mut_slice(&mut [4, 5, 6, 7, 8]) ); + /// assert_eq!( list.slice_mut(4..7), RSliceMut::from_mut_slice(&mut [4, 5, 6]) ); /// /// ``` #[inline] @@ -285,8 +285,8 @@ impl RVec { /// ``` /// use abi_stable::std_types::RVec; /// - /// let list=RVec::from(vec![0,1,2,3]); - /// assert_eq!(list.as_slice(), &[0,1,2,3]); + /// let list = RVec::from(vec![0, 1, 2, 3]); + /// assert_eq!(list.as_slice(), &[0, 1, 2, 3]); /// /// ``` pub fn as_slice(&self) -> &[T] { @@ -300,8 +300,8 @@ impl RVec { /// ``` /// use abi_stable::std_types::RVec; /// - /// let mut list=RVec::from(vec![0,1,2,3]); - /// assert_eq!(list.as_mut_slice(), &mut [0,1,2,3]); + /// let mut list = RVec::from(vec![0, 1, 2, 3]); + /// assert_eq!(list.as_mut_slice(), &mut [0, 1, 2, 3]); /// /// ``` pub fn as_mut_slice(&mut self) -> &mut [T] { @@ -309,30 +309,30 @@ impl RVec { unsafe { ::std::slice::from_raw_parts_mut(self.buffer_mut(), len) } } - /// Creates an `RSlice<'_,T>` with access to all the elements of the `RVec`. + /// Creates an `RSlice<'_, T>` with access to all the elements of the `RVec`. /// /// # Example /// /// ``` - /// use abi_stable::std_types::{RSlice,RVec}; + /// use abi_stable::std_types::{RSlice, RVec}; /// - /// let list=RVec::from(vec![0,1,2,3]); - /// assert_eq!(list.as_rslice(), RSlice::from_slice(&[0,1,2,3])); + /// let list = RVec::from(vec![0, 1, 2, 3]); + /// assert_eq!(list.as_rslice(), RSlice::from_slice(&[0, 1, 2, 3])); /// /// ``` pub const fn as_rslice(&self) -> RSlice<'_, T> { unsafe { RSlice::from_raw_parts(self.as_ptr(), self.len()) } } - /// Creates an `RSliceMut<'_,T>` with access to all the elements of the `RVec`. + /// Creates an `RSliceMut<'_, T>` with access to all the elements of the `RVec`. /// /// # Example /// /// ``` - /// use abi_stable::std_types::{RSliceMut,RVec}; + /// use abi_stable::std_types::{RSliceMut, RVec}; /// - /// let mut list=RVec::from(vec![0,1,2,3]); - /// assert_eq!(list.as_mut_rslice(), RSliceMut::from_mut_slice(&mut [0,1,2,3])); + /// let mut list = RVec::from(vec![0, 1, 2, 3]); + /// assert_eq!(list.as_mut_rslice(), RSliceMut::from_mut_slice(&mut [0, 1, 2, 3])); /// /// ``` pub fn as_mut_rslice(&mut self) -> RSliceMut<'_, T> { @@ -346,15 +346,15 @@ impl RVec { /// ``` /// use abi_stable::std_types::RVec; /// - /// let mut list=RVec::::new(); + /// let mut list = RVec::::new(); /// - /// assert_eq!(list.len(),0); + /// assert_eq!(list.len(), 0); /// /// list.push(0xDEAFBEEF); - /// assert_eq!(list.len(),1); + /// assert_eq!(list.len(), 1); /// /// list.push(0xCAFE); - /// assert_eq!(list.len(),2); + /// assert_eq!(list.len(), 2); /// /// ``` #[inline(always)] @@ -375,12 +375,12 @@ impl RVec { /// ``` /// use abi_stable::std_types::RVec; /// - /// let mut list=RVec::::new(); + /// let mut list = RVec::::new(); /// /// list.reserve_exact(10); /// /// unsafe{ - /// let start=list.as_mut_ptr(); + /// let start = list.as_mut_ptr(); /// for i in 0..10 { /// start.add(i as usize).write(i); /// } @@ -401,15 +401,15 @@ impl RVec { /// ``` /// use abi_stable::std_types::RVec; /// - /// let mut list=RVec::::with_capacity(7); + /// let mut list = RVec::::with_capacity(7); /// /// list.extend( std::iter::repeat(11).take(4) ); - /// assert_eq!(list.len(),4); - /// assert_eq!(list.capacity(),7); + /// assert_eq!(list.len(), 4); + /// assert_eq!(list.capacity(), 7); /// /// list.shrink_to_fit(); - /// assert_eq!(list.len(),4); - /// assert_eq!(list.capacity(),4); + /// assert_eq!(list.len(), 4); + /// assert_eq!(list.capacity(), 4); /// ``` pub fn shrink_to_fit(&mut self) { let vtable = self.vtable(); @@ -423,15 +423,15 @@ impl RVec { /// ``` /// use abi_stable::std_types::RVec; /// - /// let mut list=RVec::::new(); + /// let mut list = RVec::::new(); /// - /// assert_eq!(list.is_empty(),true); + /// assert_eq!(list.is_empty(), true); /// /// list.push(0x1337); - /// assert_eq!(list.is_empty(),false); + /// assert_eq!(list.is_empty(), false); /// /// list.push(0xC001); - /// assert_eq!(list.is_empty(),false); + /// assert_eq!(list.is_empty(), false); /// /// ``` #[inline(always)] @@ -451,13 +451,13 @@ impl RVec { /// ``` /// use abi_stable::std_types::RVec; /// - /// let mut list=RVec::::new(); + /// let mut list = RVec::::new(); /// /// list.push(0); /// list.push(1); /// list.push(2); /// - /// assert_eq!(list.into_vec(), vec![0,1,2]); + /// assert_eq!(list.into_vec(), vec![0, 1, 2]); /// /// ``` pub fn into_vec(self) -> Vec { @@ -482,18 +482,18 @@ impl RVec { } } - /// Creates a `Vec`,copying all the elements of this `RVec`. + /// Creates a `Vec`, copying all the elements of this `RVec`. /// /// # Example /// /// ``` /// use abi_stable::std_types::RVec; /// - /// let mut list=RVec::::new(); + /// let mut list = RVec::::new(); /// /// list.extend( (4..=7).rev() ); /// - /// assert_eq!(list.to_vec(), vec![7,6,5,4] ); + /// assert_eq!(list.to_vec(), vec![7, 6, 5, 4] ); /// /// ``` pub fn to_vec(&self) -> Vec @@ -506,17 +506,17 @@ impl RVec { /// Clones a `&[T]` into a new `RVec`. /// /// This function was defined to aid type inference, - /// because eg:`&[0,1]` is a `&[i32;2]` not a `&[i32]`. + /// because eg: `&[0, 1]` is a `&[i32;2]` not a `&[i32]`. /// /// # Example /// /// ``` /// use abi_stable::std_types::RVec; /// - /// let slic=&[99,88,77,66]; - /// let list=RVec::::from_slice(slic); + /// let slic = &[99, 88, 77, 66]; + /// let list = RVec::::from_slice(slic); /// - /// assert_eq!(list.as_slice(),slic); + /// assert_eq!(list.as_slice(), slic); /// ``` #[inline] pub fn from_slice(slic: &[T]) -> RVec @@ -537,19 +537,19 @@ impl RVec { /// ``` /// use abi_stable::std_types::RVec; /// - /// let mut list=RVec::from(vec![0,1,2,3]); + /// let mut list = RVec::from(vec![0, 1, 2, 3]); /// - /// list.insert(2,22); - /// assert_eq!(list.as_slice(),&[0,1,22,2,3]); + /// list.insert(2, 22); + /// assert_eq!(list.as_slice(), &[0, 1, 22, 2, 3]); /// - /// list.insert(5,55); - /// assert_eq!(list.as_slice(),&[0,1,22,2,3,55]); + /// list.insert(5, 55); + /// assert_eq!(list.as_slice(), &[0, 1, 22, 2, 3, 55]); /// /// ``` pub fn insert(&mut self, index: usize, value: T) { assert!( index <= self.length, - "index out of bounds,index={} len={} ", + "index out of bounds, index={} len={} ", index, self.length ); @@ -579,13 +579,13 @@ impl RVec { /// ``` /// use abi_stable::std_types::RVec; /// - /// let mut list=RVec::from(vec![0,1,2,3]); + /// let mut list = RVec::from(vec![0, 1, 2, 3]); /// - /// assert_eq!(list.try_remove(4),None); - /// assert_eq!(list.try_remove(3),Some(3)); - /// assert_eq!(list.try_remove(1),Some(1)); + /// assert_eq!(list.try_remove(4), None); + /// assert_eq!(list.try_remove(3), Some(3)); + /// assert_eq!(list.try_remove(1), Some(1)); /// - /// assert_eq!(list.as_slice(), &[0,2]); + /// assert_eq!(list.as_slice(), &[0, 2]); /// ``` pub fn try_remove(&mut self, index: usize) -> Option { if self.length <= index { @@ -614,12 +614,12 @@ impl RVec { /// /// ``` /// use abi_stable::{ - /// std_types::{RStr,RVec}, + /// std_types::{RStr, RVec}, /// traits::IntoReprC, /// }; /// /// // This type annotation is purely for the reader. - /// let mut list:RVec>= + /// let mut list: RVec>= /// vec!["foo".into_c(), "bar".into(), "baz".into()].into_c(); /// /// assert_eq!( list.remove(2), "baz".into_c() ); @@ -631,11 +631,11 @@ impl RVec { pub fn remove(&mut self, index: usize) -> T { match self.try_remove(index) { Some(x) => x, - None => panic!("index out of bounds,index={} len={} ", index, self.length), + None => panic!("index out of bounds, index={} len={} ", index, self.length), } } - /// Swaps the element at `index` position with the last element,and then removes it. + /// Swaps the element at `index` position with the last element, and then removes it. /// /// # Panic /// @@ -645,12 +645,12 @@ impl RVec { /// /// ``` /// use abi_stable::{ - /// std_types::{RStr,RVec}, + /// std_types::{RStr, RVec}, /// traits::IntoReprC, /// }; /// /// // This type annotation is purely for the reader. - /// let mut list:RVec>= + /// let mut list: RVec>= /// vec!["foo".into_c(), "bar".into(), "baz".into(), "geo".into()].into_c(); /// /// assert_eq!( list.swap_remove(1), "bar".into_c() ); @@ -676,16 +676,16 @@ impl RVec { /// ``` /// use abi_stable::std_types::RVec; /// - /// let mut list=RVec::::new(); + /// let mut list = RVec::::new(); /// /// list.push(11); /// assert_eq!(list.as_slice(), &[11]); /// /// list.push(22); - /// assert_eq!(list.as_slice(), &[11,22]); + /// assert_eq!(list.as_slice(), &[11, 22]); /// /// list.push(55); - /// assert_eq!(list.as_slice(), &[11,22,55]); + /// assert_eq!(list.as_slice(), &[11, 22, 55]); /// /// ``` pub fn push(&mut self, new_val: T) { @@ -704,12 +704,12 @@ impl RVec { /// # Example /// /// ``` - /// use abi_stable::std_types::{RSlice,RVec}; + /// use abi_stable::std_types::{RSlice, RVec}; /// - /// let mut list=RVec::::from_slice(&[11,22,55]); + /// let mut list = RVec::::from_slice(&[11, 22, 55]); /// /// assert_eq!(list.pop(), Some(55)); - /// assert_eq!(list.as_slice(), &[11,22]); + /// assert_eq!(list.as_slice(), &[11, 22]); /// /// assert_eq!(list.pop(), Some(22)); /// assert_eq!(list.as_slice(), &[11]); @@ -734,17 +734,17 @@ impl RVec { /// Truncates the `RVec` to `to` length. /// Does nothing if `self.len() <= to`. /// - /// Note:this has no effect on the capacity of the `RVec`. + /// Note: this has no effect on the capacity of the `RVec`. /// /// # Example /// /// ``` - /// use abi_stable::std_types::{RSlice,RVec}; + /// use abi_stable::std_types::{RSlice, RVec}; /// - /// let mut list=RVec::::from_slice(&[11,22,55,66,77]); + /// let mut list = RVec::::from_slice(&[11, 22, 55, 66, 77]); /// /// list.truncate(3); - /// assert_eq!(list.as_slice(), &[11,22,55] ); + /// assert_eq!(list.as_slice(), &[11, 22, 55] ); /// /// list.truncate(0); /// assert_eq!(list.as_rslice(), RSlice::::EMPTY ); @@ -759,16 +759,16 @@ impl RVec { /// Removes all the elements from collection. /// - /// Note:this has no effect on the capacity of the `RVec`. + /// Note: this has no effect on the capacity of the `RVec`. /// /// # Example /// /// ``` - /// use abi_stable::std_types::{RSlice,RVec}; + /// use abi_stable::std_types::{RSlice, RVec}; /// - /// let mut list=RVec::::from_slice(&[11,22,55]); + /// let mut list = RVec::::from_slice(&[11, 22, 55]); /// - /// assert_eq!( list.as_slice(), &[11,22,55] ); + /// assert_eq!( list.as_slice(), &[11, 22, 55] ); /// /// list.clear(); /// assert_eq!( list.as_rslice(), RSlice::::EMPTY ); @@ -790,14 +790,14 @@ impl RVec { /// use abi_stable::std_types::RVec; /// /// { - /// let mut list=(0..=10).collect::>(); - /// list.retain(|x| *x%3 ==0 ); - /// assert_eq!(list.as_slice(), &[0,3,6,9]); + /// let mut list = (0..=10).collect::>(); + /// list.retain(|x| *x%3 == 0 ); + /// assert_eq!(list.as_slice(), &[0, 3, 6, 9]); /// } /// { - /// let mut list=(0..=10).collect::>(); - /// list.retain(|x| *x%5 ==0 ); - /// assert_eq!(list.as_slice(), &[0,5,10]); + /// let mut list = (0..=10).collect::>(); + /// list.retain(|x| *x%5 == 0 ); + /// assert_eq!(list.as_slice(), &[0, 5, 10]); /// } /// /// ``` @@ -839,14 +839,14 @@ impl RVec { /// ``` /// use abi_stable::std_types::RVec; /// - /// let mut list=RVec::::new(); + /// let mut list = RVec::::new(); /// /// list.reserve(10); - /// assert!( list.capacity()>=10 ); + /// assert!( list.capacity() >= 10 ); /// - /// let cap=list.capacity(); + /// let cap = list.capacity(); /// list.extend(0..10); - /// assert_eq!( list.capacity(),cap ); + /// assert_eq!( list.capacity(), cap ); /// /// ``` pub fn reserve(&mut self, additional: usize) { @@ -862,14 +862,14 @@ impl RVec { /// ``` /// use abi_stable::std_types::RVec; /// - /// let mut list=RVec::::new(); + /// let mut list = RVec::::new(); /// /// list.reserve_exact(17); - /// assert_eq!( list.capacity(),17 ); + /// assert_eq!( list.capacity(), 17 ); /// - /// let cap=list.capacity(); + /// let cap = list.capacity(); /// list.extend(0..17); - /// assert_eq!( list.capacity(),cap ); + /// assert_eq!( list.capacity(), cap ); /// /// ``` pub fn reserve_exact(&mut self, additional: usize) { @@ -903,16 +903,16 @@ where /// ``` /// use abi_stable::std_types::RVec; /// - /// let mut list=RVec::::new(); + /// let mut list = RVec::::new(); /// - /// list.resize(5,88); - /// assert_eq!( list.as_slice(), &[88,88,88,88,88] ); + /// list.resize(5, 88); + /// assert_eq!( list.as_slice(), &[88, 88, 88, 88, 88] ); /// - /// list.resize(3,0); - /// assert_eq!( list.as_slice(), &[88,88,88] ); + /// list.resize(3, 0); + /// assert_eq!( list.as_slice(), &[88, 88, 88] ); /// - /// list.resize(6,123); - /// assert_eq!( list.as_slice(), &[88,88,88,123,123,123] ); + /// list.resize(6, 123); + /// assert_eq!( list.as_slice(), &[88, 88, 88, 123, 123, 123] ); /// /// ``` pub fn resize(&mut self, new_len: usize, value: T) { @@ -946,12 +946,12 @@ where /// ``` /// use abi_stable::std_types::RVec; /// - /// let mut list=RVec::::new(); + /// let mut list = RVec::::new(); /// - /// list.extend_from_slice(&[99,88]); - /// list.extend_from_slice(&[77,66]); + /// list.extend_from_slice(&[99, 88]); + /// list.extend_from_slice(&[77, 66]); /// - /// assert_eq!( list.as_slice(), &[99,88,77,66] ); + /// assert_eq!( list.as_slice(), &[99, 88, 77, 66] ); /// ``` pub fn extend_from_slice(&mut self, slic_: &[T]) { self.reserve(slic_.len()); @@ -971,11 +971,11 @@ where /// /// ``` /// use abi_stable::{ - /// std_types::{RStr,RVec}, + /// std_types::{RStr, RVec}, /// traits::IntoReprC, /// }; /// - /// let mut list=RVec::>::new(); + /// let mut list = RVec::>::new(); /// /// list.extend_from_slice(&["foo".into_c(), "bar".into()]); /// list.extend_from_slice(&["baz".into_c(), "goo".into()]); @@ -1075,9 +1075,9 @@ slice_like_impl_cmp_traits! { } shared_impls! { - mod=buffer_impls - new_type=RVec[][T], - original_type=Vec, + mod = buffer_impls + new_type = RVec[][T], + original_type = Vec, } impl_into_rust_repr! { @@ -1162,26 +1162,26 @@ impl RVec { # Example ``` - use abi_stable::std_types::{RSlice,RVec}; + use abi_stable::std_types::{RSlice, RVec}; { - let mut list=RVec::from(vec![0,1,2,3,4,5]); - assert_eq!( list.drain(2..4).collect::>(), vec![2,3] ); - assert_eq!( list.as_slice(), &[0,1,4,5] ); + let mut list = RVec::from(vec![0, 1, 2, 3, 4, 5]); + assert_eq!( list.drain(2..4).collect::>(), vec![2, 3] ); + assert_eq!( list.as_slice(), &[0, 1, 4, 5] ); } { - let mut list=RVec::from(vec![0,1,2,3,4,5]); - assert_eq!( list.drain(2..).collect::>(), vec![2,3,4,5] ); - assert_eq!( list.as_slice(), &[0,1] ); + let mut list = RVec::from(vec![0, 1, 2, 3, 4, 5]); + assert_eq!( list.drain(2..).collect::>(), vec![2, 3, 4, 5] ); + assert_eq!( list.as_slice(), &[0, 1] ); } { - let mut list=RVec::from(vec![0,1,2,3,4,5]); - assert_eq!( list.drain(..2).collect::>(), vec![0,1] ); - assert_eq!( list.as_slice(), &[2,3,4,5] ); + let mut list = RVec::from(vec![0, 1, 2, 3, 4, 5]); + assert_eq!( list.drain(..2).collect::>(), vec![0, 1] ); + assert_eq!( list.as_slice(), &[2, 3, 4, 5] ); } { - let mut list=RVec::from(vec![0,1,2,3,4,5]); - assert_eq!( list.drain(..).collect::>(), vec![0,1,2,3,4,5] ); + let mut list = RVec::from(vec![0, 1, 2, 3, 4, 5]); + assert_eq!( list.drain(..).collect::>(), vec![0, 1, 2, 3, 4, 5] ); assert_eq!( list.as_rslice(), RSlice::::EMPTY ); } @@ -1334,7 +1334,7 @@ impl<'a, T: 'a> VTableGetter<'a, T> { WithMetadata::new( PrefixTypeTrait::METADATA, VecVTable { - type_id:Constructor( new_utypeid::> ), + type_id: Constructor( new_utypeid::> ), ..Self::DEFAULT_VTABLE } ) diff --git a/abi_stable/src/type_level.rs b/abi_stable/src/type_level.rs index 03623492..3c96314c 100644 --- a/abi_stable/src/type_level.rs +++ b/abi_stable/src/type_level.rs @@ -1,6 +1,4 @@ -/*! -Types used to represent values at compile-time,eg:True/False. -*/ +//! Types used to represent values at compile-time, eg: True/False. /** Type-level booleans. diff --git a/abi_stable/src/utils.rs b/abi_stable/src/utils.rs index 92c7bdcb..882f1d19 100644 --- a/abi_stable/src/utils.rs +++ b/abi_stable/src/utils.rs @@ -18,7 +18,7 @@ use crate::{ ////////////////////////////////////// -/// Information about a panic,used in `ffi_panic_message`. +/// Information about a panic, used in `ffi_panic_message`. #[derive(Debug, Copy, Clone)] pub struct PanicInfo { pub file: &'static str, @@ -96,7 +96,7 @@ pub union Transmuter { ////////////////////////////////// -/// Leaks `value` into the heap,and returns a reference to it. +/// Leaks `value` into the heap, and returns a reference to it. /// /// # Warning /// @@ -106,7 +106,7 @@ pub union Transmuter { #[inline] pub fn leak_value<'a, T>(value: T) -> &'a T where - T: 'a, // T:'a is for the docs + T: 'a, // T: 'a is for the docs { let x = Box::new(value); let leaked: &'a T = Box::leak(x); @@ -122,7 +122,7 @@ where /// /// # Safety /// -/// This has the same safety concerns that `std::mem::transmute` has,including that +/// This has the same safety concerns that `std::mem::transmute` has, including that /// `T` has to have an alignment and be compatible with `U`. #[inline] #[allow(clippy::needless_lifetimes)] @@ -135,7 +135,7 @@ pub unsafe fn transmute_reference(ref_: &T) -> &U { /// /// # Safety /// -/// This has the same safety concerns that `std::mem::transmute` has,including that +/// This has the same safety concerns that `std::mem::transmute` has, including that /// `T` has to have an alignment and be compatible with `U`. #[inline] #[allow(clippy::needless_lifetimes)] @@ -201,7 +201,7 @@ pub(crate) trait FmtPadding { } macro_rules! impl_fmt_padding { - ($ty:ty) => { + ($ty: ty) => { impl FmtPadding for $ty { fn display_pad<'a, T>( &'a mut self, @@ -282,12 +282,12 @@ where /// ``` /// use abi_stable::utils; /// -/// let arr=["hello","world","foo","bar","baz"]; +/// let arr = ["hello", "world", "foo", "bar", "baz"]; /// -/// assert_eq!(utils::distance_from(&arr[0],&arr[0]),Some(0)); -/// assert_eq!(utils::distance_from(&arr[0],&arr[4]),Some(4)); +/// assert_eq!(utils::distance_from(&arr[0], &arr[0]), Some(0)); +/// assert_eq!(utils::distance_from(&arr[0], &arr[4]), Some(4)); /// -/// assert_eq!(utils::distance_from(&arr[4],&arr[0]),None); +/// assert_eq!(utils::distance_from(&arr[4], &arr[0]), None); /// /// ``` pub fn distance_from(from: *const T, to: *const T) -> Option { From c0cbfe1bcc3c524f3054eaae2f99a6ac73ac51dd Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Sun, 10 Oct 2021 05:08:35 -0300 Subject: [PATCH 14/32] Added spacing to format std_types doc examples --- abi_stable/src/std_types/arc.rs | 74 +++--- abi_stable/src/std_types/boxed.rs | 60 ++--- abi_stable/src/std_types/cmp_ordering.rs | 20 +- abi_stable/src/std_types/cow.rs | 138 +++++----- abi_stable/src/std_types/cow/tests.rs | 8 +- abi_stable/src/std_types/map.rs | 250 +++++++++--------- abi_stable/src/std_types/map/entry.rs | 164 ++++++------ abi_stable/src/std_types/map/extern_fns.rs | 6 +- .../src/std_types/map/iterator_stuff.rs | 38 +-- abi_stable/src/std_types/map/map_query.rs | 6 +- abi_stable/src/std_types/map/test.rs | 16 +- abi_stable/src/std_types/option.rs | 180 ++++++------- abi_stable/src/std_types/range.rs | 10 +- abi_stable/src/std_types/result.rs | 112 ++++---- abi_stable/src/std_types/slice_mut.rs | 116 ++++---- abi_stable/src/std_types/slices.rs | 183 +++++++------ abi_stable/src/std_types/std_error.rs | 164 ++++++------ abi_stable/src/std_types/std_error/test.rs | 32 +-- abi_stable/src/std_types/std_io.rs | 116 ++++---- abi_stable/src/std_types/str.rs | 54 ++-- abi_stable/src/std_types/string.rs | 10 +- abi_stable/src/std_types/string/iters.rs | 28 +- abi_stable/src/std_types/string/tests.rs | 2 +- abi_stable/src/std_types/tuple.rs | 6 +- abi_stable/src/std_types/utypeid.rs | 8 +- abi_stable/src/std_types/vec.rs | 12 +- abi_stable/src/std_types/vec/iters.rs | 40 +-- abi_stable/src/std_types/vec/tests.rs | 8 +- 28 files changed, 928 insertions(+), 933 deletions(-) diff --git a/abi_stable/src/std_types/arc.rs b/abi_stable/src/std_types/arc.rs index 43f0017a..c239a86f 100644 --- a/abi_stable/src/std_types/arc.rs +++ b/abi_stable/src/std_types/arc.rs @@ -35,22 +35,22 @@ mod private { ``` use abi_stable::{ external_types::RMutex, - std_types::{RArc,RVec}, + std_types::{RArc, RVec}, }; use std::thread; - let arc=RArc::new(RMutex::new(RVec::new())); + let arc = RArc::new(RMutex::new(RVec::new())); { - let arc2=RArc::clone(&arc); - assert!( std::ptr::eq(&*arc,&*arc2) ); + let arc2 = RArc::clone(&arc); + assert!( std::ptr::eq(&*arc, &*arc2) ); } - let mut guards=Vec::new(); + let mut guards = Vec::new(); for i in 0..10_u64 { - let arc=RArc::clone(&arc); + let arc = RArc::clone(&arc); guards.push(thread::spawn(move||{ for j in 0..100_u64{ arc.lock().push(i*100+j); @@ -62,9 +62,9 @@ mod private { guard.join().unwrap(); } - let mut vec=RArc::try_unwrap(arc) + let mut vec = RArc::try_unwrap(arc) .ok() - .expect("All the threads were joined,so this must be the only RArc") + .expect("All the threads were joined, so this must be the only RArc") .into_inner(); vec.sort(); @@ -155,7 +155,7 @@ impl RArc { /// ``` /// use abi_stable::std_types::RArc; /// - /// let arc=RArc::new(100); + /// let arc = RArc::new(100); /// /// ``` pub fn new(this: T) -> Self { @@ -181,7 +181,7 @@ impl RArc { /// use abi_stable::std_types::RArc; /// use std::sync::Arc; /// - /// let arc=RArc::new(100); + /// let arc = RArc::new(100); /// /// assert_eq!( RArc::into_arc(arc), Arc::new(100) ); /// @@ -211,11 +211,11 @@ impl RArc { /// ``` /// use abi_stable::std_types::RArc; /// - /// let arc0=RArc::new(100); + /// let arc0 = RArc::new(100); /// assert_eq!( RArc::try_unwrap(arc0), Ok(100) ); /// - /// let arc1=RArc::new(100); - /// let arc1_clone=RArc::clone(&arc1); + /// let arc1 = RArc::new(100); + /// let arc1_clone = RArc::clone(&arc1); /// assert_eq!( RArc::try_unwrap(arc1), Err(arc1_clone.clone()) ); /// /// ``` @@ -233,12 +233,12 @@ impl RArc { /// ``` /// use abi_stable::std_types::RArc; /// - /// let mut arc0=RArc::new(100); - /// *RArc::get_mut(&mut arc0).unwrap()+=400; + /// let mut arc0 = RArc::new(100); + /// *RArc::get_mut(&mut arc0).unwrap() += 400; /// assert_eq!( *arc0, 500 ); /// - /// let mut arc1=RArc::new(100); - /// let _arc1_clone=RArc::clone(&arc1); + /// let mut arc1 = RArc::new(100); + /// let _arc1_clone = RArc::clone(&arc1); /// assert_eq!( RArc::get_mut(&mut arc1), None ); /// /// ``` @@ -265,13 +265,13 @@ impl RArc { /// ``` /// use abi_stable::std_types::RArc; /// - /// let mut arc0=RArc::new(100); - /// *RArc::make_mut(&mut arc0)+=400; + /// let mut arc0 = RArc::new(100); + /// *RArc::make_mut(&mut arc0) += 400; /// assert_eq!( *arc0, 500 ); /// - /// let mut arc1=RArc::new(100); - /// let arc1_clone=RArc::clone(&arc1); - /// *RArc::make_mut(&mut arc1)+=400; + /// let mut arc1 = RArc::new(100); + /// let arc1_clone = RArc::clone(&arc1); + /// *RArc::make_mut(&mut arc1) += 400; /// assert_eq!( *arc1, 500 ); /// assert_eq!( *arc1_clone, 100 ); /// @@ -289,7 +289,7 @@ impl RArc { None => { let new_arc = RArc::new((**this).clone()); *this = new_arc; - // This is fine,since this is a freshly created arc with a clone of the data. + // This is fine, since this is a freshly created arc with a clone of the data. unsafe { &mut *this.data_mut() } } } @@ -302,10 +302,10 @@ impl RArc { /// ``` /// use abi_stable::std_types::RArc; /// - /// let arc=RArc::new(0); + /// let arc = RArc::new(0); /// assert_eq!( RArc::strong_count(&arc), 1 ); /// - /// let clone=RArc::clone(&arc); + /// let clone = RArc::clone(&arc); /// assert_eq!( RArc::strong_count(&arc), 2 ); /// /// ``` @@ -323,14 +323,14 @@ impl RArc { /// /// use std::sync::Arc; /// - /// let rustarc=Arc::new(0); - /// let arc=RArc::from(rustarc.clone()); + /// let rustarc = Arc::new(0); + /// let arc = RArc::from(rustarc.clone()); /// assert_eq!( RArc::weak_count(&arc), 0 ); /// - /// let weak_0=Arc::downgrade(&rustarc); + /// let weak_0 = Arc::downgrade(&rustarc); /// assert_eq!( RArc::weak_count(&arc), 1 ); /// - /// let weak_1=Arc::downgrade(&rustarc); + /// let weak_1 = Arc::downgrade(&rustarc); /// assert_eq!( RArc::weak_count(&arc), 2 ); /// ``` pub fn weak_count(this: &Self) -> usize { @@ -393,9 +393,9 @@ impl Drop for RArc { } shared_impls! {pointer - mod=arc_impls - new_type=RArc[][T], - original_type=Arc, + mod = arc_impls + new_type = RArc[][T], + original_type = Arc, } unsafe impl Sync for RArc where T: Send + Sync {} @@ -421,8 +421,8 @@ mod vtable_mod { }; staticref! { - const WM_DEFAULT: WithMetadata>= - WithMetadata::new(PrefixTypeTrait::METADATA,Self::DEFAULT_VTABLE) + const WM_DEFAULT: WithMetadata> = + WithMetadata::new(PrefixTypeTrait::METADATA, Self::DEFAULT_VTABLE) } // The VTABLE for this type in this executable/library @@ -430,11 +430,11 @@ mod vtable_mod { { ArcVtable_Ref(Self::WM_DEFAULT.as_prefix()) }; #[cfg(test)] - staticref! {const WM_FOR_TESTING: WithMetadata>= + staticref! {const WM_FOR_TESTING: WithMetadata> = WithMetadata::new( PrefixTypeTrait::METADATA, ArcVtable{ - type_id:Constructor( new_utypeid::> ), + type_id: Constructor( new_utypeid::> ), ..Self::DEFAULT_VTABLE } ) @@ -487,7 +487,7 @@ mod vtable_mod { unsafe extern "C" fn get_mut_arc<'a, T>(this: &'a mut RArc) -> Option<&'a mut T> { let arc = Arc::from_raw(this.data()); let mut arc = ManuallyDrop::new(arc); - // This is fine,since we are only touching the data afterwards, + // This is fine, since we are only touching the data afterwards, // which is guaranteed to have the 'a lifetime. let arc: &'a mut Arc = &mut *(&mut *arc as *mut Arc); Arc::get_mut(arc) diff --git a/abi_stable/src/std_types/boxed.rs b/abi_stable/src/std_types/boxed.rs index 55881e60..195808d7 100644 --- a/abi_stable/src/std_types/boxed.rs +++ b/abi_stable/src/std_types/boxed.rs @@ -48,7 +48,7 @@ mod private { ``` use abi_stable::{ - std_types::{RBox,RString}, + std_types::{RBox, RString}, StableAbi, }; @@ -56,19 +56,19 @@ mod private { #[derive(StableAbi)] enum Command{ SendProduct{ - id:u64, + id: u64, }, GoProtest{ - cause:RString, - place:RString, + cause: RString, + place: RString, }, SendComplaint{ - cause:RString, - website:RString, + cause: RString, + website: RString, }, WithMetadata{ - command:RBox, - metadata:RString, + command: RBox, + metadata: RString, }, } @@ -92,8 +92,8 @@ mod private { /// ``` /// use abi_stable::std_types::RBox; /// - /// let baux=RBox::new(100); - /// assert_eq!(*baux,100); + /// let baux = RBox::new(100); + /// assert_eq!(*baux, 100); /// /// ``` pub fn new(value: T) -> Self { @@ -106,16 +106,16 @@ mod private { RBox::new(value).into_pin() } - /// Converts a `Box` to an `RBox`,reusing its heap allocation. + /// Converts a `Box` to an `RBox`, reusing its heap allocation. /// /// # Example /// /// ``` /// use abi_stable::std_types::RBox; /// - /// let baux=Box::new(200); - /// let baux=RBox::from_box(baux); - /// assert_eq!(*baux,200); + /// let baux = Box::new(200); + /// let baux = RBox::from_box(baux); + /// assert_eq!(*baux, 200); /// /// ``` pub fn from_box(p: Box) -> RBox { @@ -126,7 +126,7 @@ mod private { } } - /// Constructs a `Box` from a `MovePtr<'_,T>`. + /// Constructs a `Box` from a `MovePtr<'_, T>`. /// /// # Example /// @@ -139,10 +139,10 @@ mod private { /// std_types::RBox, /// }; /// - /// let b=RSmallBox::<_,[u8;1]>::new(77u8); - /// let rbox:RBox<_>=b.in_move_ptr(|x| RBox::from_move_ptr(x) ); + /// let b = RSmallBox::<_, [u8;1]>::new(77u8); + /// let rbox: RBox<_> = b.in_move_ptr(|x| RBox::from_move_ptr(x) ); /// - /// assert_eq!(*rbox,77); + /// assert_eq!(*rbox, 77); /// /// ``` pub fn from_move_ptr(p: MovePtr<'_, T>) -> RBox { @@ -213,9 +213,9 @@ impl RBox { /// ``` /// use abi_stable::std_types::RBox; /// - /// let baux:RBox=RBox::new(200); - /// let baux:Box=RBox::into_box(baux); - /// assert_eq!(*baux,200); + /// let baux: RBox = RBox::new(200); + /// let baux: Box = RBox::into_box(baux); + /// assert_eq!(*baux, 200); /// /// ``` pub fn into_box(this: Self) -> Box { @@ -248,9 +248,9 @@ impl RBox { /// ``` /// use abi_stable::std_types::RBox; /// - /// let baux:RBox=RBox::new(200); - /// let baux:u32=RBox::into_inner(baux); - /// assert_eq!(baux,200); + /// let baux: RBox = RBox::new(200); + /// let baux: u32 = RBox::into_inner(baux); + /// assert_eq!(baux, 200); /// /// ``` pub fn into_inner(this: Self) -> T { @@ -365,9 +365,9 @@ where } shared_impls! {pointer - mod=box_impls - new_type=RBox[][T], - original_type=Box, + mod = box_impls + new_type = RBox[][T], + original_type = Box, } unsafe impl Send for RBox {} @@ -647,7 +647,7 @@ impl<'a, T: 'a> VTableGetter<'a, T> { WithMetadata::new( PrefixTypeTrait::METADATA, BoxVtable { - type_id:Constructor( new_utypeid::> ), + type_id: Constructor( new_utypeid::> ), ..Self::DEFAULT_VTABLE }, ) @@ -666,10 +666,10 @@ unsafe extern "C" fn destroy_box( ) { extern_fn_panic_handling! {no_early_return; let ptr = ptr as *mut T; - if let CallReferentDrop::Yes=call_drop { + if let CallReferentDrop::Yes = call_drop { ptr::drop_in_place(ptr); } - if let Deallocate::Yes=dealloc { + if let Deallocate::Yes = dealloc { Box::from_raw(ptr as *mut ManuallyDrop); } } diff --git a/abi_stable/src/std_types/cmp_ordering.rs b/abi_stable/src/std_types/cmp_ordering.rs index c5fd9a94..835a797f 100644 --- a/abi_stable/src/std_types/cmp_ordering.rs +++ b/abi_stable/src/std_types/cmp_ordering.rs @@ -9,21 +9,21 @@ Ffi-safe equivalent of `std::cmp::Ordering`. # Example -This defines an extern function,which compares a slice to another. +This defines an extern function, which compares a slice to another. ``` use abi_stable::{ - std_types::{RCmpOrdering,RSlice}, + std_types::{RCmpOrdering, RSlice}, sabi_extern_fn, }; use std::cmp::Ord; #[sabi_extern_fn] -pub fn compare_slices(l:RSlice<'_,T>, r:RSlice<'_,T>)->RCmpOrdering +pub fn compare_slices(l: RSlice<'_, T>, r: RSlice<'_, T>) -> RCmpOrdering where - T:Ord + T: Ord { l.cmp(&r) .into() @@ -65,9 +65,9 @@ impl_from_rust_repr! { impl From for RCmpOrdering { fn(this){ match this { - Ordering::Less=>RCmpOrdering::Less, - Ordering::Equal=>RCmpOrdering::Equal, - Ordering::Greater=>RCmpOrdering::Greater, + Ordering::Less => RCmpOrdering::Less, + Ordering::Equal => RCmpOrdering::Equal, + Ordering::Greater => RCmpOrdering::Greater, } } } @@ -77,9 +77,9 @@ impl_into_rust_repr! { impl Into for RCmpOrdering { fn(this){ match this { - RCmpOrdering::Less=>Ordering::Less, - RCmpOrdering::Equal=>Ordering::Equal, - RCmpOrdering::Greater=>Ordering::Greater, + RCmpOrdering::Less => Ordering::Less, + RCmpOrdering::Equal => Ordering::Equal, + RCmpOrdering::Greater => Ordering::Greater, } } } diff --git a/abi_stable/src/std_types/cow.rs b/abi_stable/src/std_types/cow.rs index d9bff46e..2c778db9 100644 --- a/abi_stable/src/std_types/cow.rs +++ b/abi_stable/src/std_types/cow.rs @@ -1,5 +1,5 @@ /*! -Contains the ffi-safe equivalent of `std::borrow::Cow`,and related items. +Contains the ffi-safe equivalent of `std::borrow::Cow`, and related items. */ use std::{ @@ -170,37 +170,37 @@ Ffi-safe equivalent of `std::borrow::Cow`. The most common examples of this type are: -- `RCow<'_,str>`: contains an `RStr<'_>` or an `RString`. +- `RCow<'_, str>`: contains an `RStr<'_>` or an `RString`. -- `RCow<'_,[T]>`: contains an `RSlice<'_,T>` or an `RVec`. +- `RCow<'_, [T]>`: contains an `RSlice<'_, T>` or an `RVec`. -- `RCow<'_,T>`: contains a `&T` or a `T`. +- `RCow<'_, T>`: contains a `&T` or a `T`. # Example -### Using a `RCow<'a,str>`. +### Using a `RCow<'a, str>`. This implements a solution to the well known fizzbuzz problem. ``` use abi_stable::std_types::RCow; -fn fizzbuzz(n:u32)->RCow<'static,str>{ - match (n%3,n%5) { - (0,0)=>RCow::from("FizzBuzz"), - (0,_)=>RCow::from("Fizz"), - (_,0)=>RCow::from("Buzz"), - (_,_)=>RCow::from(n.to_string()), +fn fizzbuzz(n: u32) -> RCow<'static, str>{ + match (n%3, n%5) { + (0, 0) => RCow::from("FizzBuzz"), + (0, _) => RCow::from("Fizz"), + (_, 0) => RCow::from("Buzz"), + (_, _) => RCow::from(n.to_string()), } } -for n in 1..=100{ - println!("{}",fizzbuzz(n)); +for n in 1 ..= 100{ + println!("{}", fizzbuzz(n)); } ``` -Note:this example allocates when the number is neither a multiple of 5 or 3. +Note: this example allocates when the number is neither a multiple of 5 or 3. */ @@ -235,15 +235,15 @@ where /// ``` /// use abi_stable::std_types::RCow; /// - /// let mut cow:RCow<'_,str>=RCow::from("Hello"); + /// let mut cow: RCow<'_, str> = RCow::from("Hello"); /// - /// assert_eq!(&*cow,"Hello"); + /// assert_eq!(&*cow, "Hello"); /// assert!(cow.is_borrowed()); /// /// cow.to_mut().push_str(", world!"); /// /// assert!(cow.is_owned()); - /// assert_eq!(cow,RCow::from("Hello, world!")); + /// assert_eq!(cow, RCow::from("Hello, world!")); /// /// ``` pub fn to_mut(&mut self) -> &mut B::ROwned { @@ -264,14 +264,14 @@ where /// ``` /// use abi_stable::std_types::RCow; /// - /// let mut cow:RCow<'_,str>=RCow::from("Hello"); + /// let mut cow: RCow<'_, str> = RCow::from("Hello"); /// - /// assert_eq!(&*cow,"Hello"); + /// assert_eq!(&*cow, "Hello"); /// - /// let mut buff=cow.into_owned(); + /// let mut buff = cow.into_owned(); /// buff.push_str(", world!"); /// - /// assert_eq!(&*buff,"Hello, world!"); + /// assert_eq!(&*buff, "Hello, world!"); /// /// ``` pub fn into_owned(self) -> B::ROwned { @@ -286,14 +286,14 @@ where /// # Examples /// /// ``` - /// use abi_stable::std_types::{RCow,RSlice}; + /// use abi_stable::std_types::{RCow, RSlice}; /// { - /// let cow:RCow<'_,[u8]>=RCow::from(&[0,1,2,3][..]); - /// assert_eq!( cow.borrowed(), RSlice::from_slice(&[0,1,2,3]) ); + /// let cow: RCow<'_, [u8]> = RCow::from(&[0, 1, 2, 3][..]); + /// assert_eq!( cow.borrowed(), RSlice::from_slice(&[0, 1, 2, 3]) ); /// } /// { - /// let cow:RCow<'_,[u8]>=RCow::from(vec![0,1,2,3]); - /// assert_eq!( cow.borrowed(), RSlice::from_slice(&[0,1,2,3]) ); + /// let cow: RCow<'_, [u8]> = RCow::from(vec![0, 1, 2, 3]); + /// assert_eq!( cow.borrowed(), RSlice::from_slice(&[0, 1, 2, 3]) ); /// } /// ``` pub fn borrowed<'b: 'a>(&'b self) -> >::RBorrowed { @@ -311,11 +311,11 @@ where /// use abi_stable::std_types::RCow; /// /// { - /// let cow:RCow<'_,[u8]>=RCow::from(&[0,1,2,3][..]); + /// let cow: RCow<'_, [u8]> = RCow::from(&[0, 1, 2, 3][..]); /// assert!( cow.is_borrowed() ); /// } /// { - /// let cow:RCow<'_,[u8]>=RCow::from(vec![0,1,2,3]); + /// let cow: RCow<'_, [u8]> = RCow::from(vec![0, 1, 2, 3]); /// assert!( !cow.is_borrowed() ); /// } /// @@ -331,10 +331,10 @@ where /// ``` /// use abi_stable::std_types::RCow; /// - /// let cow:RCow<'_,[u8]>=RCow::from(&[0,1,2,3][..]); + /// let cow: RCow<'_, [u8]> = RCow::from(&[0, 1, 2, 3][..]); /// assert!( !cow.is_owned() ); /// - /// let cow:RCow<'_,[u8]>=RCow::from(vec![0,1,2,3]); + /// let cow: RCow<'_, [u8]> = RCow::from(vec![0, 1, 2, 3]); /// assert!( cow.is_owned() ); /// /// ``` @@ -456,23 +456,23 @@ deref_coerced_impl_cmp_traits! { } shared_impls! { - mod=slice_impls - new_type=RCow['a][] + mod = slice_impls + new_type = RCow['a][] extra[B] constrained[B] - where [ B:BorrowOwned<'a>+?Sized ], - original_type=void, + where [ B: BorrowOwned<'a>+?Sized ], + original_type = void, } impl_into_rust_repr! { - impl['a,B] Into> for RCow<'a,B> + impl['a, B] Into> for RCow<'a, B> where[ B: BorrowOwned<'a>+?Sized, ]{ fn(this){ match this{ - RCow::Borrowed(x)=>x.piped(B::into_cow_borrow).piped(Cow::Borrowed), - RCow::Owned(x)=>x.piped(B::into_cow_owned).piped(Cow::Owned), + RCow::Borrowed(x) => x.piped(B::into_cow_borrow).piped(Cow::Borrowed), + RCow::Owned(x) => x.piped(B::into_cow_owned).piped(Cow::Owned), } } } @@ -481,14 +481,14 @@ impl_into_rust_repr! { //////////////////////////////////////////////////////////// impl_from_rust_repr! { - impl['a,B] From> for RCow<'a,B> + impl['a, B] From> for RCow<'a, B> where [ B: BorrowOwned<'a>+?Sized , ]{ fn(this){ match this{ - Cow::Borrowed(x)=>x.piped(B::from_cow_borrow).piped(RCow::Borrowed), - Cow::Owned(x)=>x.piped(B::from_cow_owned).piped(RCow::Owned), + Cow::Borrowed(x) => x.piped(B::from_cow_borrow).piped(RCow::Borrowed), + Cow::Owned(x) => x.piped(B::from_cow_owned).piped(RCow::Owned), } } } @@ -550,7 +550,7 @@ impl<'a, T> RCow<'a, [T]> where T: Clone, { - /// For converting a `&'a [T]` to an `RCow<'a,[T]>`, + /// For converting a `&'a [T]` to an `RCow<'a, [T]>`, /// most useful when converting from `&'a [T;N]` because it coerces the array to a slice. #[inline] pub fn from_slice(this: &'a [T]) -> Self { @@ -603,12 +603,12 @@ where //////////////////////////////////////////////////////////// /** -Deserializes an `RCow<'a,[u8]>` that borrows the slice from the deserializer +Deserializes an `RCow<'a, [u8]>` that borrows the slice from the deserializer whenever possible. # Example -Defining a type containing an `RCow<'a,[u8]>` which borrows from the deserializer. +Defining a type containing an `RCow<'a, [u8]>` which borrows from the deserializer. ``` use abi_stable::std_types::cow::{ @@ -616,23 +616,23 @@ use abi_stable::std_types::cow::{ RCow, }; -use serde::{Deserialize,Serialize}; +use serde::{Deserialize, Serialize}; -#[derive(Debug,Deserialize,Serialize,PartialEq)] +#[derive(Debug, Deserialize, Serialize, PartialEq)] pub struct TheSlice<'a>{ - #[serde(borrow,deserialize_with="deserialize_borrowed_bytes")] - slice:RCow<'a,[u8]>, + #[serde(borrow, deserialize_with = "deserialize_borrowed_bytes")] + slice: RCow<'a, [u8]>, } -let the_slice=TheSlice{ slice:RCow::from(vec![0,1,2,3,4,5]) }; +let the_slice = TheSlice{ slice: RCow::from(vec![0, 1, 2, 3, 4, 5]) }; -let vec=bincode::serialize(&the_slice).unwrap(); +let vec = bincode::serialize(&the_slice).unwrap(); -let deserialized_slice=bincode::deserialize(&vec).unwrap(); +let deserialized_slice = bincode::deserialize(&vec).unwrap(); -assert_eq!(the_slice,deserialized_slice); +assert_eq!(the_slice, deserialized_slice); assert!( deserialized_slice.slice.is_borrowed() ); @@ -657,13 +657,13 @@ where } /** -Deserializes an `RCow<'a,str>` that borrows the string from the deserializer +Deserializes an `RCow<'a, str>` that borrows the string from the deserializer whenever possible. # Example -Defining a type containing an `RCow<'a,str>` which borrows from the deserializer. +Defining a type containing an `RCow<'a, str>` which borrows from the deserializer. ``` use abi_stable::std_types::cow::{ @@ -671,23 +671,23 @@ use abi_stable::std_types::cow::{ RCow, }; -use serde::{Deserialize,Serialize}; +use serde::{Deserialize, Serialize}; -#[derive(Debug,Deserialize,Serialize,PartialEq)] +#[derive(Debug, Deserialize, Serialize, PartialEq)] pub struct TheSlice<'a>{ - #[serde(borrow,deserialize_with="deserialize_borrowed_str")] - slice:RCow<'a,str>, + #[serde(borrow, deserialize_with = "deserialize_borrowed_str")] + slice: RCow<'a, str>, } -let the_slice=TheSlice{ slice:RCow::from("That's a lot of fish.") }; +let the_slice = TheSlice{ slice: RCow::from("That's a lot of fish.") }; -let string=serde_json::to_string(&the_slice).unwrap(); +let string = serde_json::to_string(&the_slice).unwrap(); -let deserialized_slice=serde_json::from_str::>(&string).unwrap(); +let deserialized_slice = serde_json::from_str::>(&string).unwrap(); -assert_eq!(the_slice,deserialized_slice); +assert_eq!(the_slice, deserialized_slice); assert!( deserialized_slice.slice.is_borrowed() ); @@ -755,7 +755,7 @@ where } /** -A helper type,to deserialize an `RCow<'a,[u8]>` which borrows from the deserializer. +A helper type, to deserialize an `RCow<'a, [u8]>` which borrows from the deserializer. # Example @@ -766,11 +766,11 @@ use abi_stable::std_types::cow::{ }; -let the_slice:Vec=vec![0,1,2,3,4,5]; +let the_slice: Vec = vec![0, 1, 2, 3, 4, 5]; -let vec=bincode::serialize(&the_slice).unwrap(); +let vec = bincode::serialize(&the_slice).unwrap(); -let deserialized_slice=bincode::deserialize::>(&vec).unwrap(); +let deserialized_slice = bincode::deserialize::>(&vec).unwrap(); assert_eq!( &*deserialized_slice.cow, &*the_slice ); @@ -790,11 +790,11 @@ pub struct BorrowingRCowU8Slice<'a> { } /** -A helper type,to deserialize a `RCow<'a,str>` which borrows from the deserializer. +A helper type, to deserialize a `RCow<'a, str>` which borrows from the deserializer. # Example -Defining a type containing an `RCow<'a,str>` borrowing from the deserializer, +Defining a type containing an `RCow<'a, str>` borrowing from the deserializer, serializing it, and then deserializing it. ``` @@ -804,9 +804,9 @@ use abi_stable::std_types::cow::{ }; -let json=r##""W____ of S____""##; +let json = r##""W____ of S____""##; -let deserialized_slice=serde_json::from_str::>(json).unwrap(); +let deserialized_slice = serde_json::from_str::>(json).unwrap(); assert_eq!( &*deserialized_slice.cow, json.trim_matches('"') ); diff --git a/abi_stable/src/std_types/cow/tests.rs b/abi_stable/src/std_types/cow/tests.rs index 50f72167..fd3139f9 100644 --- a/abi_stable/src/std_types/cow/tests.rs +++ b/abi_stable/src/std_types/cow/tests.rs @@ -4,8 +4,8 @@ use super::*; fn from_into_cow() { macro_rules! from_tests { ( - $from:ident, - Cow<$cow_param:ty> + $from: ident, + Cow<$cow_param: ty> ) => {{ { let borrowed_rcow = $from.into_c().piped(RCow::<$cow_param>::Borrowed); @@ -130,14 +130,14 @@ fn deserialize() { } { // Owned list - let json = r##" [0,1,2,3] "##; + let json = r##" [0, 1, 2, 3] "##; let what: RCow<'_, [u8]> = serde_json::from_str(json).unwrap(); assert_eq!(what.as_owned(), Some(&vec![0, 1, 2, 3].into_c()),); } { - // Borrowed list,using bincode. + // Borrowed list, using bincode. let list = [0u8, 1, 2, 3]; let serialized = bincode::serialize(&list[..]).unwrap(); diff --git a/abi_stable/src/std_types/map.rs b/abi_stable/src/std_types/map.rs index 022f92f9..14e4a80d 100644 --- a/abi_stable/src/std_types/map.rs +++ b/abi_stable/src/std_types/map.rs @@ -1,5 +1,5 @@ /*! -Contains the ffi-safe equivalent of `std::collections::HashMap`,and related items. +Contains the ffi-safe equivalent of `std::collections::HashMap`, and related items. */ use std::{ @@ -47,10 +47,10 @@ pub use self::{ /** -An ffi-safe hashmap,which wraps `std::collections::HashMap`, +An ffi-safe hashmap, which wraps `std::collections::HashMap`, only requiring the `K: Eq + Hash` bounds when constructing it. -Most of the API in `HashMap` is implemented here,including the Entry API. +Most of the API in `HashMap` is implemented here, including the Entry API. # Example @@ -58,13 +58,13 @@ Most of the API in `HashMap` is implemented here,including the Entry API. This example demonstrates how one can use the RHashMap as a dictionary. ``` -use abi_stable::std_types::{RHashMap,Tuple2,RString,RSome}; +use abi_stable::std_types::{RHashMap, Tuple2, RString, RSome}; -let mut map=RHashMap::new(); +let mut map = RHashMap::new(); -map.insert("dictionary","A book/document containing definitions of words"); -map.insert("bibliophile","Someone who loves books."); -map.insert("pictograph","A picture representating of a word."); +map.insert("dictionary", "A book/document containing definitions of words"); +map.insert("bibliophile", "Someone who loves books."); +map.insert("pictograph", "A picture representating of a word."); assert_eq!( map["dictionary"], @@ -81,14 +81,14 @@ assert_eq!( Some(&"A picture representating of a word."), ); -for Tuple2(k,v) in map { - assert!( k=="dictionary" || k=="pictograph" ); +for Tuple2(k, v) in map { + assert!( k == "dictionary" || k == "pictograph" ); assert!( - v=="A book/document containing definitions of words" || - v=="A picture representating of a word.", - "{}=>{}", - k,v + v == "A book/document containing definitions of words" || + v == "A picture representating of a word.", + "{} => {}", + k, v ); } @@ -148,12 +148,12 @@ impl RHashMap { /// # Example /// /// ``` - /// use abi_stable::std_types::{RHashMap,RString}; + /// use abi_stable::std_types::{RHashMap, RString}; /// - /// let mut map=RHashMap::::new(); + /// let mut map = RHashMap::::new(); /// assert!(map.is_empty()); - /// map.insert("Hello".into(),10); - /// assert_eq!(map.is_empty(),false); + /// map.insert("Hello".into(), 10); + /// assert_eq!(map.is_empty(), false); /// /// ``` #[inline] @@ -169,10 +169,10 @@ impl RHashMap { /// # Example /// /// ``` - /// use abi_stable::std_types::{RHashMap,RString}; + /// use abi_stable::std_types::{RHashMap, RString}; /// - /// let mut map=RHashMap::::with_capacity(10); - /// assert!(map.capacity()>=10); + /// let mut map = RHashMap::::with_capacity(10); + /// assert!(map.capacity() >= 10); /// /// ``` #[inline] @@ -192,14 +192,14 @@ impl RHashMap { /// # Example /// /// ``` - /// use abi_stable::std_types::{RHashMap,RString}; + /// use abi_stable::std_types::{RHashMap, RString}; /// use std::collections::hash_map::RandomState; /// /// let s = RandomState::new(); - /// let mut map=RHashMap::::with_hasher(s); + /// let mut map = RHashMap::::with_hasher(s); /// assert!(map.is_empty()); - /// map.insert("Hello".into(),10); - /// assert_eq!(map.is_empty(),false); + /// map.insert("Hello".into(), 10); + /// assert_eq!(map.is_empty(), false); /// /// ``` #[inline] @@ -216,12 +216,12 @@ impl RHashMap { /// # Example /// /// ``` - /// use abi_stable::std_types::{RHashMap,RString}; + /// use abi_stable::std_types::{RHashMap, RString}; /// use std::collections::hash_map::RandomState; /// /// let s = RandomState::new(); - /// let mut map=RHashMap::::with_capacity_and_hasher(10,s); - /// assert!(map.capacity()>=10); + /// let mut map = RHashMap::::with_capacity_and_hasher(10, s); + /// assert!(map.capacity() >= 10); /// /// ``` pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> RHashMap @@ -250,12 +250,12 @@ impl RHashMap { /// # Example /// /// ``` - /// use abi_stable::std_types::{RHashMap,RString}; + /// use abi_stable::std_types::{RHashMap, RString}; /// - /// let mut map=RHashMap::::new(); - /// assert_eq!(map.contains_key("boo"),false); - /// map.insert("boo".into(),0); - /// assert_eq!(map.contains_key("boo"),true); + /// let mut map = RHashMap::::new(); + /// assert_eq!(map.contains_key("boo"), false); + /// map.insert("boo".into(), 0); + /// assert_eq!(map.contains_key("boo"), true); /// /// ``` pub fn contains_key(&self, query: &Q) -> bool @@ -273,11 +273,11 @@ impl RHashMap { /// # Example /// /// ``` - /// use abi_stable::std_types::{RHashMap,RString}; + /// use abi_stable::std_types::{RHashMap, RString}; /// - /// let mut map=RHashMap::::new(); + /// let mut map = RHashMap::::new(); /// assert_eq!(map.get("boo"), None); - /// map.insert("boo".into(),0); + /// map.insert("boo".into(), 0); /// assert_eq!(map.get("boo"), Some(&0)); /// /// ``` @@ -297,11 +297,11 @@ impl RHashMap { /// # Example /// /// ``` - /// use abi_stable::std_types::{RHashMap,RString}; + /// use abi_stable::std_types::{RHashMap, RString}; /// - /// let mut map=RHashMap::::new(); + /// let mut map = RHashMap::::new(); /// assert_eq!(map.get_mut("boo"), None); - /// map.insert("boo".into(),0); + /// map.insert("boo".into(), 0); /// assert_eq!(map.get_mut("boo"), Some(&mut 0)); /// /// ``` @@ -319,9 +319,9 @@ impl RHashMap { /// # Example /// /// ``` - /// use abi_stable::std_types::{RHashMap,RSome,RNone}; + /// use abi_stable::std_types::{RHashMap, RSome, RNone}; /// - /// let mut map=vec![(0,1),(3,4)].into_iter().collect::>(); + /// let mut map = vec![(0, 1), (3, 4)].into_iter().collect::>(); /// /// assert_eq!(map.remove(&0), RSome(1)); /// assert_eq!(map.remove(&0), RNone); @@ -343,14 +343,14 @@ impl RHashMap { /// # Example /// /// ``` - /// use abi_stable::std_types::{RHashMap,RSome,RNone,Tuple2}; + /// use abi_stable::std_types::{RHashMap, RSome, RNone, Tuple2}; /// - /// let mut map=vec![(0,1),(3,4)].into_iter().collect::>(); + /// let mut map = vec![(0, 1), (3, 4)].into_iter().collect::>(); /// - /// assert_eq!(map.remove_entry(&0), RSome(Tuple2(0,1))); + /// assert_eq!(map.remove_entry(&0), RSome(Tuple2(0, 1))); /// assert_eq!(map.remove_entry(&0), RNone); /// - /// assert_eq!(map.remove_entry(&3), RSome(Tuple2(3,4))); + /// assert_eq!(map.remove_entry(&3), RSome(Tuple2(3, 4))); /// assert_eq!(map.remove_entry(&3), RNone); /// /// ``` @@ -372,10 +372,10 @@ impl RHashMap { /// ``` /// use abi_stable::std_types::RHashMap; /// - /// let mut map=RHashMap::::new(); - /// assert_eq!(map.contains_key(&11),false); - /// map.insert(11,0); - /// assert_eq!(map.contains_key(&11),true); + /// let mut map = RHashMap::::new(); + /// assert_eq!(map.contains_key(&11), false); + /// map.insert(11, 0); + /// assert_eq!(map.contains_key(&11), true); /// /// ``` pub fn contains_key_p(&self, key: &K) -> bool { @@ -391,9 +391,9 @@ impl RHashMap { /// ``` /// use abi_stable::std_types::RHashMap; /// - /// let mut map=RHashMap::::new(); + /// let mut map = RHashMap::::new(); /// assert_eq!(map.get(&12), None); - /// map.insert(12,0); + /// map.insert(12, 0); /// assert_eq!(map.get(&12), Some(&0)); /// /// ``` @@ -411,9 +411,9 @@ impl RHashMap { /// ``` /// use abi_stable::std_types::RHashMap; /// - /// let mut map=RHashMap::::new(); + /// let mut map = RHashMap::::new(); /// assert_eq!(map.get_mut(&12), None); - /// map.insert(12,0); + /// map.insert(12, 0); /// assert_eq!(map.get_mut(&12), Some(&mut 0)); /// /// ``` @@ -427,9 +427,9 @@ impl RHashMap { /// # Example /// /// ``` - /// use abi_stable::std_types::{RHashMap,RSome,RNone}; + /// use abi_stable::std_types::{RHashMap, RSome, RNone}; /// - /// let mut map=vec![(0,1),(3,4)].into_iter().collect::>(); + /// let mut map = vec![(0, 1), (3, 4)].into_iter().collect::>(); /// /// assert_eq!(map.remove_p(&0), RSome(1)); /// assert_eq!(map.remove_p(&0), RNone); @@ -447,14 +447,14 @@ impl RHashMap { /// # Example /// /// ``` - /// use abi_stable::std_types::{RHashMap,RSome,RNone,Tuple2}; + /// use abi_stable::std_types::{RHashMap, RSome, RNone, Tuple2}; /// - /// let mut map=vec![(0,1),(3,4)].into_iter().collect::>(); + /// let mut map = vec![(0, 1), (3, 4)].into_iter().collect::>(); /// - /// assert_eq!(map.remove_entry_p(&0), RSome(Tuple2(0,1))); + /// assert_eq!(map.remove_entry_p(&0), RSome(Tuple2(0, 1))); /// assert_eq!(map.remove_entry_p(&0), RNone); /// - /// assert_eq!(map.remove_entry_p(&3), RSome(Tuple2(3,4))); + /// assert_eq!(map.remove_entry_p(&3), RSome(Tuple2(3, 4))); /// assert_eq!(map.remove_entry_p(&3), RNone); /// /// ``` @@ -474,24 +474,24 @@ impl RHashMap { /// ``` /// use abi_stable::std_types::RHashMap; /// - /// let mut map=vec![(0,1),(3,4)].into_iter().collect::>(); + /// let mut map = vec![(0, 1), (3, 4)].into_iter().collect::>(); /// - /// assert_eq!(map.index_p(&0),&1); - /// assert_eq!(map.index_p(&3),&4); + /// assert_eq!(map.index_p(&0), &1); + /// assert_eq!(map.index_p(&3), &4); /// /// ``` /// /// ```should_panic /// use abi_stable::std_types::RHashMap; /// - /// let mut map=RHashMap::::new(); + /// let mut map = RHashMap::::new(); /// - /// assert_eq!(map.index_p(&0),&1); + /// assert_eq!(map.index_p(&0), &1); /// /// ``` pub fn index_p(&self, key: &K) -> &V { self.get_p(key) - .expect("no entry in RHashMap<_,_> found for key") + .expect("no entry in RHashMap<_, _> found for key") } /// Returns a mutable reference to the value associated with the key. @@ -505,42 +505,42 @@ impl RHashMap { /// ``` /// use abi_stable::std_types::RHashMap; /// - /// let mut map=vec![(0,1),(3,4)].into_iter().collect::>(); + /// let mut map = vec![(0, 1), (3, 4)].into_iter().collect::>(); /// - /// assert_eq!(map.index_mut_p(&0),&mut 1); - /// assert_eq!(map.index_mut_p(&3),&mut 4); + /// assert_eq!(map.index_mut_p(&0), &mut 1); + /// assert_eq!(map.index_mut_p(&3), &mut 4); /// /// ``` /// /// ```should_panic /// use abi_stable::std_types::RHashMap; /// - /// let mut map=RHashMap::::new(); + /// let mut map = RHashMap::::new(); /// - /// assert_eq!(map.index_mut_p(&0),&mut 1); + /// assert_eq!(map.index_mut_p(&0), &mut 1); /// /// ``` pub fn index_mut_p(&mut self, key: &K) -> &mut V { self.get_mut_p(key) - .expect("no entry in RHashMap<_,_> found for key") + .expect("no entry in RHashMap<_, _> found for key") } ////////////////////////////////// - /// Inserts a value into the map,associating it with a key,returning the previous value. + /// Inserts a value into the map, associating it with a key, returning the previous value. /// /// # Example /// /// ``` /// use abi_stable::std_types::RHashMap; /// - /// let mut map=RHashMap::::new(); + /// let mut map = RHashMap::::new(); /// - /// map.insert(0,1); - /// map.insert(2,3); + /// map.insert(0, 1); + /// map.insert(2, 3); /// - /// assert_eq!(map[&0],1); - /// assert_eq!(map[&2],3); + /// assert_eq!(map[&0], 1); + /// assert_eq!(map[&2], 3); /// /// ``` pub fn insert(&mut self, key: K, value: V) -> ROption { @@ -555,7 +555,7 @@ impl RHashMap { /// ``` /// use abi_stable::std_types::RHashMap; /// - /// let mut map=RHashMap::::new(); + /// let mut map = RHashMap::::new(); /// map.reserve(10); /// /// ``` @@ -572,15 +572,15 @@ impl RHashMap { /// ``` /// use abi_stable::std_types::RHashMap; /// - /// let mut map=vec![(0,1),(3,4)].into_iter().collect::>(); + /// let mut map = vec![(0, 1), (3, 4)].into_iter().collect::>(); /// - /// assert_eq!(map.contains_key(&0),true); - /// assert_eq!(map.contains_key(&3),true); + /// assert_eq!(map.contains_key(&0), true); + /// assert_eq!(map.contains_key(&3), true); /// /// map.clear(); /// - /// assert_eq!(map.contains_key(&0),false); - /// assert_eq!(map.contains_key(&3),false); + /// assert_eq!(map.contains_key(&0), false); + /// assert_eq!(map.contains_key(&3), false); /// /// ``` pub fn clear(&mut self) { @@ -595,13 +595,13 @@ impl RHashMap { /// ``` /// use abi_stable::std_types::RHashMap; /// - /// let mut map=RHashMap::::new(); + /// let mut map = RHashMap::::new(); /// - /// assert_eq!(map.len(),0); - /// map.insert(0,1); - /// assert_eq!(map.len(),1); - /// map.insert(2,3); - /// assert_eq!(map.len(),2); + /// assert_eq!(map.len(), 0); + /// map.insert(0, 1); + /// assert_eq!(map.len(), 1); + /// map.insert(2, 3); + /// assert_eq!(map.len(), 2); /// /// ``` pub fn len(&self) -> usize { @@ -609,18 +609,18 @@ impl RHashMap { vtable.len()(self.map.as_rref()) } - /// Returns the capacity of the map,the amount of elements it can store without reallocating. + /// Returns the capacity of the map, the amount of elements it can store without reallocating. /// - /// Note that this is a lower bound,since hash maps don't necessarily have an exact capacity. + /// Note that this is a lower bound, since hash maps don't necessarily have an exact capacity. /// /// # Example /// /// ``` /// use abi_stable::std_types::RHashMap; /// - /// let mut map=RHashMap::::with_capacity(4); + /// let mut map = RHashMap::::with_capacity(4); /// - /// assert!(map.capacity()>=4); + /// assert!(map.capacity() >= 4); /// /// ``` pub fn capacity(&self) -> usize { @@ -635,18 +635,18 @@ impl RHashMap { /// ``` /// use abi_stable::std_types::RHashMap; /// - /// let mut map=RHashMap::::new(); + /// let mut map = RHashMap::::new(); /// - /// assert_eq!(map.is_empty(),true); - /// map.insert(0,1); - /// assert_eq!(map.is_empty(),false); + /// assert_eq!(map.is_empty(), true); + /// map.insert(0, 1); + /// assert_eq!(map.is_empty(), false); /// /// ``` pub fn is_empty(&self) -> bool { self.len() == 0 } - /// Iterates over the entries in the map,with references to the values in the map. + /// Iterates over the entries in the map, with references to the values in the map. /// /// This returns a type that implements /// `Iterator > + !Send + !Sync + Clone` @@ -654,16 +654,16 @@ impl RHashMap { /// # Example /// /// ``` - /// use abi_stable::std_types::{RHashMap,Tuple2}; + /// use abi_stable::std_types::{RHashMap, Tuple2}; /// - /// let mut map=RHashMap::::new(); + /// let mut map = RHashMap::::new(); /// - /// map.insert(0,1); - /// map.insert(3,4); + /// map.insert(0, 1); + /// map.insert(3, 4); /// - /// let mut list=map.iter().collect::>(); + /// let mut list = map.iter().collect::>(); /// list.sort(); - /// assert_eq!( list, vec![Tuple2(&0,&1),Tuple2(&3,&4)] ); + /// assert_eq!( list, vec![Tuple2(&0, &1), Tuple2(&3, &4)] ); /// /// ``` pub fn iter(&self) -> Iter<'_, K, V> { @@ -672,7 +672,7 @@ impl RHashMap { vtable.iter()(self.map.as_rref()) } - /// Iterates over the entries in the map,with mutable references to the values in the map. + /// Iterates over the entries in the map, with mutable references to the values in the map. /// /// This returns a type that implements /// `Iterator > + !Send + !Sync` @@ -680,16 +680,16 @@ impl RHashMap { /// # Example /// /// ``` - /// use abi_stable::std_types::{RHashMap,Tuple2}; + /// use abi_stable::std_types::{RHashMap, Tuple2}; /// - /// let mut map=RHashMap::::new(); + /// let mut map = RHashMap::::new(); /// - /// map.insert(0,1); - /// map.insert(3,4); + /// map.insert(0, 1); + /// map.insert(3, 4); /// - /// let mut list=map.iter_mut().collect::>(); + /// let mut list = map.iter_mut().collect::>(); /// list.sort(); - /// assert_eq!( list, vec![Tuple2(&0,&mut 1),Tuple2(&3,&mut 4)] ); + /// assert_eq!( list, vec![Tuple2(&0, &mut 1), Tuple2(&3, &mut 4)] ); /// /// ``` pub fn iter_mut(&mut self) -> IterMut<'_, K, V> { @@ -698,23 +698,23 @@ impl RHashMap { vtable.iter_mut()(self.map.as_rmut()) } - /// Clears the map,returning an iterator over all the entries that were removed. + /// Clears the map, returning an iterator over all the entries that were removed. /// /// This returns a type that implements `Iterator > + !Send + !Sync` /// /// # Example /// /// ``` - /// use abi_stable::std_types::{RHashMap,Tuple2}; + /// use abi_stable::std_types::{RHashMap, Tuple2}; /// - /// let mut map=RHashMap::::new(); + /// let mut map = RHashMap::::new(); /// - /// map.insert(0,1); - /// map.insert(3,4); + /// map.insert(0, 1); + /// map.insert(3, 4); /// - /// let mut list=map.drain().collect::>(); + /// let mut list = map.drain().collect::>(); /// list.sort(); - /// assert_eq!( list, vec![Tuple2(0,1),Tuple2(3,4)] ); + /// assert_eq!( list, vec![Tuple2(0, 1), Tuple2(3, 4)] ); /// /// assert!(map.is_empty()); /// @@ -734,14 +734,14 @@ impl RHashMap { ``` use abi_stable::std_types::RHashMap; - let mut map=RHashMap::::new(); + let mut map = RHashMap::::new(); // Inserting an entry that wasn't there before. { - let mut entry=map.entry(0); - assert_eq!(entry.get(),None); - assert_eq!(entry.or_insert(3),&mut 3); - assert_eq!(map.get(&0),Some(&3)); + let mut entry = map.entry(0); + assert_eq!(entry.get(), None); + assert_eq!(entry.or_insert(3), &mut 3); + assert_eq!(map.get(&0), Some(&3)); } @@ -927,7 +927,7 @@ where fn index(&self, query: &Q) -> &V { self.get(query) - .expect("no entry in RHashMap<_,_> found for key") + .expect("no entry in RHashMap<_, _> found for key") } } @@ -938,7 +938,7 @@ where { fn index_mut(&mut self, query: &Q) -> &mut V { self.get_mut(query) - .expect("no entry in RHashMap<_,_> found for key") + .expect("no entry in RHashMap<_, _> found for key") } } diff --git a/abi_stable/src/std_types/map/entry.rs b/abi_stable/src/std_types/map/entry.rs index 055bca46..44201a23 100644 --- a/abi_stable/src/std_types/map/entry.rs +++ b/abi_stable/src/std_types/map/entry.rs @@ -21,7 +21,7 @@ pub(super) enum BoxedREntry<'a, K, V> { /// A handle into an entry in a map, which is either vacant or occupied. #[derive(StableAbi)] #[repr(C)] -#[sabi(bound = "K:'a", bound = "V:'a")] +#[sabi(bound = "K: 'a", bound = "V: 'a")] pub enum REntry<'a, K, V> { Occupied(ROccupiedEntry<'a, K, V>), Vacant(RVacantEntry<'a, K, V>), @@ -87,10 +87,10 @@ impl<'a, K, V> REntry<'a, K, V> { /// ``` /// use abi_stable::std_types::RHashMap; /// - /// let mut map:RHashMap=vec![(1,100)].into_iter().collect(); + /// let mut map: RHashMap = vec![(1, 100)].into_iter().collect(); /// - /// assert_eq!(map.entry(0).get(),None); - /// assert_eq!(map.entry(1).get(),Some(&100)); + /// assert_eq!(map.entry(0).get(), None); + /// assert_eq!(map.entry(1).get(), Some(&100)); /// /// ``` pub fn get(&self) -> Option<&V> { @@ -107,10 +107,10 @@ impl<'a, K, V> REntry<'a, K, V> { /// ``` /// use abi_stable::std_types::RHashMap; /// - /// let mut map:RHashMap=vec![(1,100)].into_iter().collect(); + /// let mut map: RHashMap = vec![(1, 100)].into_iter().collect(); /// - /// assert_eq!(map.entry(0).get_mut(),None); - /// assert_eq!(map.entry(1).get_mut(),Some(&mut 100)); + /// assert_eq!(map.entry(0).get_mut(), None); + /// assert_eq!(map.entry(1).get_mut(), Some(&mut 100)); /// /// ``` pub fn get_mut(&mut self) -> Option<&mut V> { @@ -128,11 +128,11 @@ impl<'a, K, V> REntry<'a, K, V> { /// ``` /// use abi_stable::std_types::RHashMap; /// - /// let mut map=RHashMap::::new(); + /// let mut map = RHashMap::::new(); /// - /// assert_eq!(map.entry(0).or_insert(100),&mut 100); + /// assert_eq!(map.entry(0).or_insert(100), &mut 100); /// - /// assert_eq!(map.entry(0).or_insert(400),&mut 100); + /// assert_eq!(map.entry(0).or_insert(400), &mut 100); /// /// ``` pub fn or_insert(self, default: V) -> &'a mut V { @@ -148,9 +148,9 @@ impl<'a, K, V> REntry<'a, K, V> { /// # Example /// /// ``` - /// use abi_stable::std_types::{RHashMap,RString}; + /// use abi_stable::std_types::{RHashMap, RString}; /// - /// let mut map=RHashMap::::new(); + /// let mut map = RHashMap::::new(); /// /// assert_eq!( /// map.entry(0).or_insert_with(|| "foo".into() ), @@ -178,10 +178,10 @@ impl<'a, K, V> REntry<'a, K, V> { /// # Example /// /// ``` - /// use abi_stable::std_types::{RHashMap,RString}; + /// use abi_stable::std_types::{RHashMap, RString}; /// - /// let mut map=RHashMap::::new(); - /// map.insert("foo".into(),"bar".into()); + /// let mut map = RHashMap::::new(); + /// map.insert("foo".into(), "bar".into()); /// /// assert_eq!( /// map.entry("foo".into()).key(), @@ -202,10 +202,10 @@ impl<'a, K, V> REntry<'a, K, V> { /// # Example /// /// ``` - /// use abi_stable::std_types::{RHashMap,RString}; + /// use abi_stable::std_types::{RHashMap, RString}; /// - /// let mut map=RHashMap::::new(); - /// map.insert("foo".into(),"bar".into()); + /// let mut map = RHashMap::::new(); + /// map.insert("foo".into(), "bar".into()); /// /// assert_eq!( /// map.entry("foo".into()) @@ -235,12 +235,12 @@ impl<'a, K, V> REntry<'a, K, V> { /// ``` /// use abi_stable::std_types::RHashMap; /// - /// let mut map=RHashMap::::new(); + /// let mut map = RHashMap::::new(); /// - /// assert_eq!(map.entry(0).or_insert(100),&mut 100); - /// assert_eq!(map.entry(0).or_default(),&mut 100); + /// assert_eq!(map.entry(0).or_insert(100), &mut 100); + /// assert_eq!(map.entry(0).or_default(), &mut 100); /// - /// assert_eq!(map.entry(1).or_default(),&mut 0); + /// assert_eq!(map.entry(1).or_default(), &mut 0); /// /// ``` pub fn or_default(self) -> &'a mut V @@ -272,7 +272,7 @@ where /// A handle into an occupied entry in a map. #[derive(StableAbi)] #[repr(C)] -#[sabi(bound = "K:'a", bound = "V:'a")] +#[sabi(bound = "K: 'a", bound = "V: 'a")] pub struct ROccupiedEntry<'a, K, V> { entry: RMut<'a, ErasedOccupiedEntry>, vtable: OccupiedVTable_Ref, @@ -282,7 +282,7 @@ pub struct ROccupiedEntry<'a, K, V> { /// A handle into a vacant entry in a map. #[derive(StableAbi)] #[repr(C)] -#[sabi(bound = "K:'a", bound = "V:'a")] +#[sabi(bound = "K: 'a", bound = "V: 'a")] pub struct RVacantEntry<'a, K, V> { entry: RMut<'a, ErasedVacantEntry>, vtable: VacantVTable_Ref, @@ -318,17 +318,17 @@ impl<'a, K, V> ROccupiedEntry<'a, K, V> { /// # Example /// /// ``` - /// use abi_stable::std_types::map::{REntry,RHashMap}; + /// use abi_stable::std_types::map::{REntry, RHashMap}; /// - /// let mut map=RHashMap::::new(); + /// let mut map = RHashMap::::new(); /// - /// map.insert(0,100); + /// map.insert(0, 100); /// /// match map.entry(0) { - /// REntry::Occupied(entry)=>{ - /// assert_eq!(entry.key(),&0); + /// REntry::Occupied(entry) => { + /// assert_eq!(entry.key(), &0); /// } - /// REntry::Vacant(_)=>unreachable!(), + /// REntry::Vacant(_) => unreachable!(), /// }; /// /// @@ -344,17 +344,17 @@ impl<'a, K, V> ROccupiedEntry<'a, K, V> { /// # Example /// /// ``` - /// use abi_stable::std_types::map::{REntry,RHashMap}; + /// use abi_stable::std_types::map::{REntry, RHashMap}; /// - /// let mut map=RHashMap::::new(); + /// let mut map = RHashMap::::new(); /// - /// map.insert(6,15); + /// map.insert(6, 15); /// /// match map.entry(6) { - /// REntry::Occupied(entry)=>{ - /// assert_eq!(entry.get(),&15); + /// REntry::Occupied(entry) => { + /// assert_eq!(entry.get(), &15); /// } - /// REntry::Vacant(_)=>unreachable!(), + /// REntry::Vacant(_) => unreachable!(), /// }; /// /// @@ -366,22 +366,22 @@ impl<'a, K, V> ROccupiedEntry<'a, K, V> { } /// Gets a mutable reference to the value in the entry. - /// To borrow with the lifetime of the map,use `ROccupiedEntry::into_mut`. + /// To borrow with the lifetime of the map, use `ROccupiedEntry::into_mut`. /// /// # Example /// /// ``` - /// use abi_stable::std_types::map::{REntry,RHashMap}; + /// use abi_stable::std_types::map::{REntry, RHashMap}; /// - /// let mut map=RHashMap::::new(); + /// let mut map = RHashMap::::new(); /// - /// map.insert(6,15); + /// map.insert(6, 15); /// /// match map.entry(6) { - /// REntry::Occupied(mut entry)=>{ - /// assert_eq!(entry.get_mut(),&mut 15); + /// REntry::Occupied(mut entry) => { + /// assert_eq!(entry.get_mut(), &mut 15); /// } - /// REntry::Vacant(_)=>unreachable!(), + /// REntry::Vacant(_) => unreachable!(), /// }; /// /// @@ -399,17 +399,17 @@ impl<'a, K, V> ROccupiedEntry<'a, K, V> { /// # Example /// /// ``` - /// use abi_stable::std_types::map::{REntry,RHashMap}; + /// use abi_stable::std_types::map::{REntry, RHashMap}; /// - /// let mut map=RHashMap::::new(); + /// let mut map = RHashMap::::new(); /// - /// map.insert("baz".into(),0xDEAD); + /// map.insert("baz".into(), 0xDEAD); /// /// match map.entry("baz".into()) { - /// REntry::Occupied(entry)=>{ - /// assert_eq!(entry.into_mut(),&mut 0xDEAD); + /// REntry::Occupied(entry) => { + /// assert_eq!(entry.into_mut(), &mut 0xDEAD); /// } - /// REntry::Vacant(_)=>unreachable!(), + /// REntry::Vacant(_) => unreachable!(), /// }; /// /// @@ -420,22 +420,22 @@ impl<'a, K, V> ROccupiedEntry<'a, K, V> { vtable.fn_into_mut_elem()(self) } - /// Replaces the current value of the entry with `value`,returning the previous value. + /// Replaces the current value of the entry with `value`, returning the previous value. /// /// # Example /// /// ``` - /// use abi_stable::std_types::map::{REntry,RHashMap}; + /// use abi_stable::std_types::map::{REntry, RHashMap}; /// - /// let mut map=RHashMap::::new(); + /// let mut map = RHashMap::::new(); /// - /// map.insert("baz".into(),0xD00D); + /// map.insert("baz".into(), 0xD00D); /// /// match map.entry("baz".into()) { - /// REntry::Occupied(mut entry)=>{ - /// assert_eq!(entry.insert(0xDEAD),0xD00D); + /// REntry::Occupied(mut entry) => { + /// assert_eq!(entry.insert(0xDEAD), 0xD00D); /// } - /// REntry::Vacant(_)=>{ + /// REntry::Vacant(_) => { /// unreachable!(); /// } /// } @@ -449,22 +449,22 @@ impl<'a, K, V> ROccupiedEntry<'a, K, V> { vtable.insert_elem()(self.entry.reborrow(), value) } - /// Removes the entry from the map,returns the value. + /// Removes the entry from the map, returns the value. /// /// # Example /// /// ``` - /// use abi_stable::std_types::map::{REntry,RHashMap}; + /// use abi_stable::std_types::map::{REntry, RHashMap}; /// - /// let mut map=RHashMap::::new(); + /// let mut map = RHashMap::::new(); /// - /// map.insert("baz".into(),0xDEAD); + /// map.insert("baz".into(), 0xDEAD); /// /// match map.entry("baz".into()) { - /// REntry::Occupied(entry)=>{ - /// assert_eq!(entry.remove(),0xDEAD); + /// REntry::Occupied(entry) => { + /// assert_eq!(entry.remove(), 0xDEAD); /// } - /// REntry::Vacant(_)=>{ + /// REntry::Vacant(_) => { /// unreachable!(); /// } /// } @@ -534,16 +534,16 @@ impl<'a, K, V> RVacantEntry<'a, K, V> { /// # Example /// /// ``` - /// use abi_stable::std_types::map::{REntry,RHashMap}; + /// use abi_stable::std_types::map::{REntry, RHashMap}; /// - /// let mut map=RHashMap::::new(); + /// let mut map = RHashMap::::new(); /// /// match map.entry(1337) { - /// REntry::Occupied(_)=>{ + /// REntry::Occupied(_) => { /// unreachable!(); /// } - /// REntry::Vacant(entry)=>{ - /// assert_eq!(entry.key(),&1337); + /// REntry::Vacant(entry) => { + /// assert_eq!(entry.key(), &1337); /// } /// } /// @@ -561,16 +561,16 @@ impl<'a, K, V> RVacantEntry<'a, K, V> { /// # Example /// /// ``` - /// use abi_stable::std_types::map::{REntry,RHashMap}; + /// use abi_stable::std_types::map::{REntry, RHashMap}; /// - /// let mut map=RHashMap::::new(); + /// let mut map = RHashMap::::new(); /// /// match map.entry("lol".into()) { - /// REntry::Occupied(_)=>{ + /// REntry::Occupied(_) => { /// unreachable!(); /// } - /// REntry::Vacant(entry)=>{ - /// assert_eq!(entry.into_key(),"lol".to_string()); + /// REntry::Vacant(entry) => { + /// assert_eq!(entry.into_key(), "lol".to_string()); /// } /// } /// @@ -583,21 +583,21 @@ impl<'a, K, V> RVacantEntry<'a, K, V> { vtable.fn_into_key()(self) } - /// Sets the value of the entry,returning a mutable reference to it. + /// Sets the value of the entry, returning a mutable reference to it. /// /// # Example /// /// ``` - /// use abi_stable::std_types::map::{REntry,RHashMap}; + /// use abi_stable::std_types::map::{REntry, RHashMap}; /// - /// let mut map=RHashMap::::new(); + /// let mut map = RHashMap::::new(); /// /// match map.entry("lol".into()) { - /// REntry::Occupied(_)=>{ + /// REntry::Occupied(_) => { /// unreachable!(); /// } - /// REntry::Vacant(entry)=>{ - /// assert_eq!(entry.insert(67),&mut 67); + /// REntry::Vacant(entry) => { + /// assert_eq!(entry.insert(67), &mut 67); /// } /// } /// @@ -649,7 +649,7 @@ impl OccupiedVTable { const VTABLE_REF: OccupiedVTable_Ref = OccupiedVTable_Ref(Self::WM_VTABLE.as_prefix()); staticref! { - const WM_VTABLE: WithMetadata> = + const WM_VTABLE: WithMetadata> = WithMetadata::new(PrefixTypeTrait::METADATA, Self::VTABLE) } @@ -750,7 +750,7 @@ impl VacantVTable { const VTABLE_REF: VacantVTable_Ref = VacantVTable_Ref(Self::WM_VTABLE.as_prefix()); staticref! { - const WM_VTABLE: WithMetadata> = + const WM_VTABLE: WithMetadata> = WithMetadata::new(PrefixTypeTrait::METADATA, Self::VTABLE) } @@ -765,7 +765,7 @@ impl VacantVTable { impl ErasedVacantEntry { unsafe extern "C" fn drop_entry(this: RMut<'_, Self>) { extern_fn_panic_handling! { - Self::run_downcast_as_mut(this,|this|{ + Self::run_downcast_as_mut(this, |this|{ ManuallyDrop::drop(this); }) } diff --git a/abi_stable/src/std_types/map/extern_fns.rs b/abi_stable/src/std_types/map/extern_fns.rs index 61216cab..054b8e90 100644 --- a/abi_stable/src/std_types/map/extern_fns.rs +++ b/abi_stable/src/std_types/map/extern_fns.rs @@ -16,7 +16,7 @@ where F: FnOnce(&'a BoxedHashMap<'a, K, V, S>) -> R, { extern_fn_panic_handling! { - let map = unsafe{ this.transmute_into_ref::>() }; + let map = unsafe{ this.transmute_into_ref::>() }; f(map) } } @@ -26,7 +26,7 @@ where F: FnOnce(&'a mut BoxedHashMap<'a, K, V, S>) -> R, { extern_fn_panic_handling! { - let map = unsafe{ this.transmute_into_mut::>() }; + let map = unsafe{ this.transmute_into_mut::>() }; f(map) } } @@ -38,7 +38,7 @@ where V: 'a, { extern_fn_panic_handling! { - let map = unsafe{ this.transmute_element::>() }; + let map = unsafe{ this.transmute_element::>() }; f( map ) } } diff --git a/abi_stable/src/std_types/map/iterator_stuff.rs b/abi_stable/src/std_types/map/iterator_stuff.rs index 8eff31a5..377918b6 100644 --- a/abi_stable/src/std_types/map/iterator_stuff.rs +++ b/abi_stable/src/std_types/map/iterator_stuff.rs @@ -7,50 +7,50 @@ use crate::{ macro_rules! declare_iter_interface { ( - $k:ident=>$v:ident; - $(#[$attr:meta])* - interface=$interface:ident; - type Item=$item:ty; + $k: ident => $v: ident; + $(#[$attr: meta])* + interface = $interface: ident; + type Item = $item: ty; ) => ( #[repr(C)] #[derive(StableAbi)] $(#[$attr])* - pub struct $interface<$k,$v>(PhantomData<($k,$v)>); + pub struct $interface<$k, $v>(PhantomData<($k, $v)>); - impl<$k,$v> $interface<$k,$v>{ + impl<$k, $v> $interface<$k, $v>{ /// Constructs this type. - pub const NEW:Self=Self(PhantomData); + pub const NEW: Self = Self(PhantomData); } - impl<'a,$k:'a,$v:'a> IteratorItem<'a> for $interface<$k,$v>{ - type Item=$item; + impl<'a, $k: 'a, $v: 'a> IteratorItem<'a> for $interface<$k, $v>{ + type Item = $item; } ) } declare_iter_interface! { - K=>V; + K => V; /// The `InterfaceType` of the `Iter` iterator for `RHashMap`. - #[sabi(impl_InterfaceType(Iterator,Clone))] - interface=RefIterInterface; - type Item=Tuple2<&'a K,&'a V>; + #[sabi(impl_InterfaceType(Iterator, Clone))] + interface = RefIterInterface; + type Item = Tuple2<&'a K, &'a V>; } declare_iter_interface! { - K=>V; + K => V; /// The `InterfaceType` of the `IterMut` iterator for `RHashMap`. #[sabi(impl_InterfaceType(Iterator))] - interface=MutIterInterface; - type Item=Tuple2<&'a K,&'a mut V>; + interface = MutIterInterface; + type Item = Tuple2<&'a K, &'a mut V>; } declare_iter_interface! { - K=>V; + K => V; /// The `InterfaceType` of the `Drain` iterator for `RHashMap`. #[sabi(impl_InterfaceType(Iterator))] - interface=ValIterInterface; - type Item=Tuple2; + interface = ValIterInterface; + type Item = Tuple2; } diff --git a/abi_stable/src/std_types/map/map_query.rs b/abi_stable/src/std_types/map/map_query.rs index dafbf1ea..2b9edac8 100644 --- a/abi_stable/src/std_types/map/map_query.rs +++ b/abi_stable/src/std_types/map/map_query.rs @@ -26,8 +26,8 @@ impl<'a, K> MapQuery<'a, K> { } // #[inline] - // pub(super) unsafe fn to_static(self)->MapQuery<'static,K>{ - // mem::transmute::,MapQuery<'static,K>>(self) + // pub(super) unsafe fn to_static(self) -> MapQuery<'static, K>{ + // mem::transmute::, MapQuery<'static, K>>(self) // } #[inline] @@ -65,7 +65,7 @@ where { extern_fn_panic_handling! { let query = unsafe{ query.transmute_into_ref::<&Q>() }; - key.borrow()==*query + key.borrow() == *query } } diff --git a/abi_stable/src/std_types/map/test.rs b/abi_stable/src/std_types/map/test.rs index 26e282ce..e394d37a 100644 --- a/abi_stable/src/std_types/map/test.rs +++ b/abi_stable/src/std_types/map/test.rs @@ -71,7 +71,7 @@ fn test_eq() { #[test] fn clone() { macro_rules! clone_test { - ( $hasher:ty ) => {{ + ( $hasher: ty ) => {{ let map = new_map::(); let clone_ = map.clone(); @@ -90,7 +90,7 @@ fn clone() { } macro_rules! insert_test { - ( $hasher:ty ) => {{ + ( $hasher: ty ) => {{ let mut map = RHashMap::::default(); map.insert("what".into(), 10); map.insert("the".into(), 5); @@ -106,7 +106,7 @@ fn insert() { } macro_rules! remove_test { - ( $hasher:ty ) => {{ + ( $hasher: ty ) => {{ let mut map = RHashMap::::default(); map.insert("what".into(), 10); map.insert("the".into(), 5); @@ -176,7 +176,7 @@ where } macro_rules! get_test { - ( $hasher:ty ) => {{ + ( $hasher: ty ) => {{ let mut map = RHashMap::::default(); map.insert("what".into(), 10); map.insert("the".into(), 5); @@ -410,10 +410,10 @@ fn test_serde() { let json = r##" { - "90":"40", - "10":"20", - "88":"30", - "77":"22" + "90": "40", + "10": "20", + "88": "30", + "77": "22" } "##; diff --git a/abi_stable/src/std_types/option.rs b/abi_stable/src/std_types/option.rs index 2cddd4f2..ed3df444 100644 --- a/abi_stable/src/std_types/option.rs +++ b/abi_stable/src/std_types/option.rs @@ -10,7 +10,7 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer}; /// Ffi-safe equivalent of the `std::option::Option` type. /// -/// `Option` is also ffi-safe for NonNull/NonZero types,and references. +/// `Option` is also ffi-safe for NonNull/NonZero types, and references. /// #[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)] #[repr(u8)] @@ -31,8 +31,8 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10) .as_ref(),RSome(&10)); - /// assert_eq!(RNone::.as_ref(),RNone ); + /// assert_eq!(RSome(10) .as_ref(), RSome(&10)); + /// assert_eq!(RNone::.as_ref(), RNone ); /// /// ``` #[inline] @@ -50,8 +50,8 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10) .as_mut(),RSome(&mut 10)); - /// assert_eq!(RNone::.as_mut(),RNone ); + /// assert_eq!(RSome(10) .as_mut(), RSome(&mut 10)); + /// assert_eq!(RNone::.as_mut(), RNone ); /// /// ``` #[inline] @@ -69,8 +69,8 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10) .is_rsome(),true); - /// assert_eq!(RNone::.is_rsome(),false); + /// assert_eq!(RSome(10) .is_rsome(), true); + /// assert_eq!(RNone::.is_rsome(), false); /// /// ``` #[inline] @@ -85,8 +85,8 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10) .is_rnone(),false); - /// assert_eq!(RNone::.is_rnone(),true); + /// assert_eq!(RSome(10) .is_rnone(), false); + /// assert_eq!(RNone::.is_rnone(), true); /// /// ``` #[inline] @@ -101,8 +101,8 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10) .is_some(),true); - /// assert_eq!(RNone::.is_some(),false); + /// assert_eq!(RSome(10) .is_some(), true); + /// assert_eq!(RNone::.is_some(), false); /// /// ``` #[inline] @@ -117,8 +117,8 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10) .is_none(),false); - /// assert_eq!(RNone::.is_none(),true); + /// assert_eq!(RSome(10) .is_none(), false); + /// assert_eq!(RNone::.is_none(), true); /// /// ``` #[inline] @@ -133,8 +133,8 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10) .into_option(),Some(10)); - /// assert_eq!(RNone::.into_option(),None ); + /// assert_eq!(RSome(10) .into_option(), Some(10)); + /// assert_eq!(RNone::.into_option(), None ); /// /// ``` #[inline] @@ -161,7 +161,7 @@ impl ROption { /// ```should_panic /// # use abi_stable::std_types::*; /// - /// let _=RNone::<()>.expect("Oh noooo!"); + /// let _ = RNone::<()>.expect("Oh noooo!"); /// ``` #[inline] pub fn expect(self, msg: &str) -> T { @@ -186,22 +186,22 @@ impl ROption { /// ```should_panic /// # use abi_stable::std_types::*; /// - /// let _=RNone::<()>.unwrap(); + /// let _ = RNone::<()>.unwrap(); /// ``` #[inline] pub fn unwrap(self) -> T { self.into_option().unwrap() } - /// Returns the value in the `ROption`,or `def` if `self` is `RNone`. + /// Returns the value in the `ROption`, or `def` if `self` is `RNone`. /// /// # Example /// /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10) .unwrap_or(99),10); - /// assert_eq!(RNone::.unwrap_or(99),99); + /// assert_eq!(RSome(10) .unwrap_or(99), 10); + /// assert_eq!(RNone::.unwrap_or(99), 99); /// /// ``` #[inline] @@ -212,15 +212,15 @@ impl ROption { } } - /// Returns the value in the `ROption`,or `T::default()` if `self` is `RNone`. + /// Returns the value in the `ROption`, or `T::default()` if `self` is `RNone`. /// /// # Example /// /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10) .unwrap_or_default(),10); - /// assert_eq!(RNone::.unwrap_or_default(),0); + /// assert_eq!(RSome(10) .unwrap_or_default(), 10); + /// assert_eq!(RNone::.unwrap_or_default(), 0); /// /// ``` #[inline] @@ -242,8 +242,8 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10) .unwrap_or_else(|| 77 ),10); - /// assert_eq!(RNone::.unwrap_or_else(|| 77 ),77); + /// assert_eq!(RSome(10) .unwrap_or_else(|| 77 ), 10); + /// assert_eq!(RNone::.unwrap_or_else(|| 77 ), 77); /// /// ``` #[inline] @@ -265,8 +265,8 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10) .map(|x| x*2 ),RSome(20)); - /// assert_eq!(RNone::.map(|x| x*2 ),RNone); + /// assert_eq!(RSome(10) .map(|x| x*2 ), RSome(20)); + /// assert_eq!(RNone::.map(|x| x*2 ), RNone); /// /// ``` #[inline] @@ -288,8 +288,8 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10) .map_or(77,|x| x*2 ),20); - /// assert_eq!(RNone::.map_or(77,|x| x*2 ),77); + /// assert_eq!(RSome(10) .map_or(77, |x| x*2 ), 20); + /// assert_eq!(RNone::.map_or(77, |x| x*2 ), 77); /// /// ``` #[inline] @@ -311,8 +311,8 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10) .map_or_else(||77,|x| x*2 ),20); - /// assert_eq!(RNone::.map_or_else(||77,|x| x*2 ),77); + /// assert_eq!(RSome(10) .map_or_else(||77, |x| x*2 ), 20); + /// assert_eq!(RNone::.map_or_else(||77, |x| x*2 ), 77); /// /// ``` #[inline] @@ -327,17 +327,17 @@ impl ROption { } } - /// Returns `self` if `predicate(&self)` is true,otherwise returns `RNone`. + /// Returns `self` if `predicate(&self)` is true, otherwise returns `RNone`. /// /// # Example /// /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10).filter(|x| (x%2)==0 ),RSome(10)); - /// assert_eq!(RSome(10).filter(|x| (x%2)==1 ),RNone ); - /// assert_eq!(RNone::.filter(|_| true ),RNone ); - /// assert_eq!(RNone::.filter(|_| false ),RNone ); + /// assert_eq!(RSome(10).filter(|x| (x%2) == 0 ), RSome(10)); + /// assert_eq!(RSome(10).filter(|x| (x%2) == 1 ), RNone ); + /// assert_eq!(RNone::.filter(|_| true ), RNone ); + /// assert_eq!(RNone::.filter(|_| false ), RNone ); /// /// ``` pub fn filter

(self, predicate: P) -> Self @@ -352,17 +352,17 @@ impl ROption { RNone } - /// Returns `self` if it is `RNone`,otherwise returns `optb`. + /// Returns `self` if it is `RNone`, otherwise returns `optb`. /// /// # Example /// /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10).and(RSome(20)),RSome(20)); - /// assert_eq!(RSome(10).and(RNone ),RNone); - /// assert_eq!(RNone::.and(RSome(20)),RNone); - /// assert_eq!(RNone::.and(RNone ),RNone); + /// assert_eq!(RSome(10).and(RSome(20)), RSome(20)); + /// assert_eq!(RSome(10).and(RNone ), RNone); + /// assert_eq!(RNone::.and(RSome(20)), RNone); + /// assert_eq!(RNone::.and(RNone ), RNone); /// /// ``` #[inline] @@ -381,10 +381,10 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10).and_then(|x|RSome(x * 2)),RSome(20)); - /// assert_eq!(RSome(10).and_then(|_|RNone::),RNone); - /// assert_eq!(RNone::.and_then(|x|RSome(x * 2)),RNone); - /// assert_eq!(RNone::.and_then(|_|RNone::),RNone); + /// assert_eq!(RSome(10).and_then(|x|RSome(x * 2)), RSome(20)); + /// assert_eq!(RSome(10).and_then(|_|RNone::), RNone); + /// assert_eq!(RNone::.and_then(|x|RSome(x * 2)), RNone); + /// assert_eq!(RNone::.and_then(|_|RNone::), RNone); /// /// ``` #[inline] @@ -405,10 +405,10 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10).or(RSome(20)),RSome(10)); - /// assert_eq!(RSome(10).or(RNone ),RSome(10)); - /// assert_eq!(RNone::.or(RSome(20)),RSome(20)); - /// assert_eq!(RNone::.or(RNone ),RNone); + /// assert_eq!(RSome(10).or(RSome(20)), RSome(10)); + /// assert_eq!(RSome(10).or(RNone ), RSome(10)); + /// assert_eq!(RNone::.or(RSome(20)), RSome(20)); + /// assert_eq!(RNone::.or(RNone ), RNone); /// /// ``` #[inline] @@ -427,10 +427,10 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10).or_else(|| RSome(20) ),RSome(10)); - /// assert_eq!(RSome(10).or_else(|| RNone ),RSome(10)); - /// assert_eq!(RNone::.or_else(|| RSome(20) ),RSome(20)); - /// assert_eq!(RNone::.or_else(|| RNone ),RNone); + /// assert_eq!(RSome(10).or_else(|| RSome(20) ), RSome(10)); + /// assert_eq!(RSome(10).or_else(|| RNone ), RSome(10)); + /// assert_eq!(RNone::.or_else(|| RSome(20) ), RSome(20)); + /// assert_eq!(RNone::.or_else(|| RNone ), RNone); /// /// ``` #[inline] @@ -452,10 +452,10 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10).xor(RSome(20)),RNone ); - /// assert_eq!(RSome(10).xor(RNone ),RSome(10)); - /// assert_eq!(RNone::.xor(RSome(20)),RSome(20)); - /// assert_eq!(RNone::.xor(RNone ),RNone ); + /// assert_eq!(RSome(10).xor(RSome(20)), RNone ); + /// assert_eq!(RSome(10).xor(RNone ), RSome(10)); + /// assert_eq!(RNone::.xor(RSome(20)), RSome(20)); + /// assert_eq!(RNone::.xor(RNone ), RNone ); /// /// ``` #[inline] @@ -475,9 +475,9 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10).get_or_insert(40),&mut 10); - /// assert_eq!(RSome(20).get_or_insert(55),&mut 20); - /// assert_eq!(RNone::.get_or_insert(77),&mut 77); + /// assert_eq!(RSome(10).get_or_insert(40), &mut 10); + /// assert_eq!(RSome(20).get_or_insert(55), &mut 20); + /// assert_eq!(RNone::.get_or_insert(77), &mut 77); /// /// ``` #[inline] @@ -500,9 +500,9 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10).get_or_insert_with(||40),&mut 10); - /// assert_eq!(RSome(20).get_or_insert_with(||55),&mut 20); - /// assert_eq!(RNone::.get_or_insert_with(||77),&mut 77); + /// assert_eq!(RSome(10).get_or_insert_with(||40), &mut 10); + /// assert_eq!(RSome(20).get_or_insert_with(||55), &mut 20); + /// assert_eq!(RNone::.get_or_insert_with(||77), &mut 77); /// /// ``` #[inline] @@ -520,24 +520,24 @@ impl ROption { } } - /// Takes the value of `self`,replacing it with `RNone` + /// Takes the value of `self`, replacing it with `RNone` /// /// # Example /// /// ``` /// # use abi_stable::std_types::*; /// - /// let mut opt0=RSome(10); - /// assert_eq!(opt0.take(),RSome(10)); - /// assert_eq!(opt0,RNone); + /// let mut opt0 = RSome(10); + /// assert_eq!(opt0.take(), RSome(10)); + /// assert_eq!(opt0, RNone); /// - /// let mut opt1=RSome(20); - /// assert_eq!(opt1.take(),RSome(20)); - /// assert_eq!(opt1,RNone); + /// let mut opt1 = RSome(20); + /// assert_eq!(opt1.take(), RSome(20)); + /// assert_eq!(opt1, RNone); /// - /// let mut opt2=RNone::; - /// assert_eq!(opt2.take(),RNone); - /// assert_eq!(opt2,RNone); + /// let mut opt2 = RNone::; + /// assert_eq!(opt2.take(), RNone); + /// assert_eq!(opt2, RNone); /// /// ``` #[inline] @@ -552,17 +552,17 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// let mut opt0=RSome(10); - /// assert_eq!(opt0.replace(55),RSome(10)); - /// assert_eq!(opt0,RSome(55)); + /// let mut opt0 = RSome(10); + /// assert_eq!(opt0.replace(55), RSome(10)); + /// assert_eq!(opt0, RSome(55)); /// - /// let mut opt1=RSome(20); - /// assert_eq!(opt1.replace(88),RSome(20)); - /// assert_eq!(opt1,RSome(88)); + /// let mut opt1 = RSome(20); + /// assert_eq!(opt1.replace(88), RSome(20)); + /// assert_eq!(opt1, RSome(88)); /// - /// let mut opt2=RNone::; - /// assert_eq!(opt2.replace(33),RNone); - /// assert_eq!(opt2,RSome(33)); + /// let mut opt2 = RNone::; + /// assert_eq!(opt2.replace(33), RNone); + /// assert_eq!(opt2, RSome(33)); /// /// ``` #[inline] @@ -579,8 +579,8 @@ impl ROption<&T> { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(&vec![()]).cloned(),RSome(vec![()])); - /// assert_eq!(RNone::<&Vec<()>>.cloned(),RNone ); + /// assert_eq!(RSome(&vec![()]).cloned(), RSome(vec![()])); + /// assert_eq!(RNone::<&Vec<()>>.cloned(), RNone ); /// /// ``` #[inline] @@ -601,8 +601,8 @@ impl ROption<&T> { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(&7).copied(),RSome(7)); - /// assert_eq!(RNone::<&u32>.copied(),RNone); + /// assert_eq!(RSome(&7).copied(), RSome(7)); + /// assert_eq!(RNone::<&u32>.copied(), RNone); /// /// ``` #[inline] @@ -625,8 +625,8 @@ impl ROption<&mut T> { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(&mut vec![()]).cloned(),RSome(vec![()])); - /// assert_eq!(RNone::<&mut Vec<()>>.cloned(),RNone ); + /// assert_eq!(RSome(&mut vec![()]).cloned(), RSome(vec![()])); + /// assert_eq!(RNone::<&mut Vec<()>>.cloned(), RNone ); /// /// ``` #[inline] @@ -647,8 +647,8 @@ impl ROption<&mut T> { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(&mut 7).copied(),RSome(7)); - /// assert_eq!(RNone::<&mut u32>.copied(),RNone ); + /// assert_eq!(RSome(&mut 7).copied(), RSome(7)); + /// assert_eq!(RNone::<&mut u32>.copied(), RNone ); /// /// ``` #[inline] diff --git a/abi_stable/src/std_types/range.rs b/abi_stable/src/std_types/range.rs index ba410b22..2078c10d 100644 --- a/abi_stable/src/std_types/range.rs +++ b/abi_stable/src/std_types/range.rs @@ -7,7 +7,7 @@ use std::ops::{Range, RangeFrom, RangeInclusive, RangeTo, RangeToInclusive}; //////////////////////////////////////////////////////////////// macro_rules! impl_into_iterator { - ( $from:ident,$to:ident ) => { + ( $from: ident, $to: ident ) => { impl IntoIterator for $from where $to: Iterator, @@ -65,7 +65,7 @@ impl_into_rust_repr! { } } -impl_into_iterator! { RRange,Range } +impl_into_iterator! { RRange, Range } //////////////////////////////////////////////////////////////// @@ -95,7 +95,7 @@ impl_into_rust_repr! { } } -impl_into_iterator! { RRangeInclusive,RangeInclusive } +impl_into_iterator! { RRangeInclusive, RangeInclusive } //////////////////////////////////////////////////////////////// @@ -123,7 +123,7 @@ impl_into_rust_repr! { } } -impl_into_iterator! { RRangeFrom,RangeFrom } +impl_into_iterator! { RRangeFrom, RangeFrom } //////////////////////////////////////////////////////////////// @@ -172,7 +172,7 @@ impl_from_rust_repr! { impl_into_rust_repr! { impl[T] Into> for RRangeToInclusive { fn(this){ - ..=this.end + ..= this.end } } } diff --git a/abi_stable/src/std_types/result.rs b/abi_stable/src/std_types/result.rs index 604d98a9..68f6e431 100644 --- a/abi_stable/src/std_types/result.rs +++ b/abi_stable/src/std_types/result.rs @@ -8,7 +8,7 @@ use core_extensions::matches; use crate::std_types::{RNone, ROption, RSome}; -/// Ffi-safe equivalent of `Result`. +/// Ffi-safe equivalent of `Result`. #[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash, Deserialize, Serialize)] #[repr(u8)] #[derive(StableAbi)] @@ -22,15 +22,15 @@ pub enum RResult { pub use self::RResult::*; impl RResult { - /// Converts from `RResult` to `RResult<&T,&E>`. + /// Converts from `RResult` to `RResult<&T, &E>`. /// /// # Example /// /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(ROk::(10).as_ref(),ROk(&10)); - /// assert_eq!(RErr::(5).as_ref(),RErr(&5)); + /// assert_eq!(ROk::(10).as_ref(), ROk(&10)); + /// assert_eq!(RErr::(5).as_ref(), RErr(&5)); /// /// ``` #[inline] @@ -41,15 +41,15 @@ impl RResult { } } - /// Converts from `RResult` to `RResult<&mut T,&mut E>`. + /// Converts from `RResult` to `RResult<&mut T, &mut E>`. /// /// # Example /// /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(ROk::(10).as_mut(),ROk(&mut 10)); - /// assert_eq!(RErr::(5).as_mut(),RErr(&mut 5)); + /// assert_eq!(ROk::(10).as_mut(), ROk(&mut 10)); + /// assert_eq!(RErr::(5).as_mut(), RErr(&mut 5)); /// /// ``` #[inline] @@ -67,8 +67,8 @@ impl RResult { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(ROk::(10).is_rok(),true); - /// assert_eq!(RErr::(5).is_rok(),false); + /// assert_eq!(ROk::(10).is_rok(), true); + /// assert_eq!(RErr::(5).is_rok(), false); /// /// ``` #[inline] @@ -83,8 +83,8 @@ impl RResult { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(ROk::(10).is_ok(),true); - /// assert_eq!(RErr::(5).is_ok(),false); + /// assert_eq!(ROk::(10).is_ok(), true); + /// assert_eq!(RErr::(5).is_ok(), false); /// /// ``` #[inline] @@ -99,8 +99,8 @@ impl RResult { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(ROk::(10).is_rerr(),false); - /// assert_eq!(RErr::(5).is_rerr(),true); + /// assert_eq!(ROk::(10).is_rerr(), false); + /// assert_eq!(RErr::(5).is_rerr(), true); /// /// ``` #[inline] @@ -115,8 +115,8 @@ impl RResult { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(ROk::(10).is_err(),false); - /// assert_eq!(RErr::(5).is_err(),true); + /// assert_eq!(ROk::(10).is_err(), false); + /// assert_eq!(RErr::(5).is_err(), true); /// /// ``` #[inline] @@ -124,15 +124,15 @@ impl RResult { matches! {self, RErr{..}} } - /// Converts from `RResult` to `Result`. + /// Converts from `RResult` to `Result`. /// /// # Example /// /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(ROk::(10).into_result(),Ok (10)); - /// assert_eq!(RErr::(5).into_result(),Err(5)); + /// assert_eq!(ROk::(10).into_result(), Ok (10)); + /// assert_eq!(RErr::(5).into_result(), Err(5)); /// /// ``` #[inline] @@ -140,7 +140,7 @@ impl RResult { self.into() } - /// Converts the `RResult` to a `RResult` by transforming the value in + /// Converts the `RResult` to a `RResult` by transforming the value in /// `ROk` using the `op` closure. /// /// # Example @@ -148,8 +148,8 @@ impl RResult { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(ROk::(10).map(|x| x*3 ),ROk(30)); - /// assert_eq!(RErr::(5).map(|x| x/2 ),RErr(5)); + /// assert_eq!(ROk::(10).map(|x| x*3 ), ROk(30)); + /// assert_eq!(RErr::(5).map(|x| x/2 ), RErr(5)); /// /// ``` #[inline] @@ -163,7 +163,7 @@ impl RResult { } } - /// Converts the `RResult` to a `RResult` by + /// Converts the `RResult` to a `RResult` by /// transforming the value in `RErr` using the `op` closure. /// /// # Example @@ -171,8 +171,8 @@ impl RResult { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(ROk::(10).map_err(|x| x*3 ),ROk(10)); - /// assert_eq!(RErr::(5).map_err(|x| x/2 ),RErr(2)); + /// assert_eq!(ROk::(10).map_err(|x| x*3 ), ROk(10)); + /// assert_eq!(RErr::(5).map_err(|x| x/2 ), RErr(2)); /// /// ``` #[inline] @@ -186,7 +186,7 @@ impl RResult { } } - /// Converts the `RResult` to a `U` by + /// Converts the `RResult` to a `U` by /// transforming the value in `ROk` using the `with_ok` closure, /// otherwise transforming the value in RErr using the `with_err` closure, /// @@ -195,8 +195,8 @@ impl RResult { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(ROk::(10).map_or_else(|_|77 ,|x| x*3 ),30); - /// assert_eq!(RErr::(5).map_or_else(|e|e*4,|x| x/2 ),20); + /// assert_eq!(ROk::(10).map_or_else(|_|77 , |x| x*3 ), 30); + /// assert_eq!(RErr::(5).map_or_else(|e|e*4, |x| x/2 ), 20); /// /// ``` #[inline] @@ -217,19 +217,19 @@ impl RResult { /// # use abi_stable::std_types::*; /// /// assert_eq!( - /// ROk::(10).and_then(|x| ROk ::(x*3) ), + /// ROk::(10).and_then(|x| ROk ::(x*3) ), /// ROk (30), /// ); /// assert_eq!( - /// ROk::(10).and_then(|x| RErr::(x*3)), + /// ROk::(10).and_then(|x| RErr::(x*3)), /// RErr(30), /// ); /// assert_eq!( - /// RErr::(5).and_then(|x| ROk ::(x/2) ), + /// RErr::(5).and_then(|x| ROk ::(x/2) ), /// RErr(5), /// ); /// assert_eq!( - /// RErr::(5).and_then(|x| RErr::(x/2) ), + /// RErr::(5).and_then(|x| RErr::(x/2) ), /// RErr(5), /// ); /// @@ -253,10 +253,10 @@ impl RResult { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(ROk::(10).or_else(|e| ROk ::(e*3) ) ,ROk(10)); - /// assert_eq!(ROk::(10).or_else(|e| RErr::(e*3)) ,ROk(10)); - /// assert_eq!(RErr::(5).or_else(|e| ROk ::(e/2) ),ROk (2)); - /// assert_eq!(RErr::(5).or_else(|e| RErr::(e/2) ),RErr(2)); + /// assert_eq!(ROk::(10).or_else(|e| ROk ::(e*3) ) , ROk(10)); + /// assert_eq!(ROk::(10).or_else(|e| RErr::(e*3)) , ROk(10)); + /// assert_eq!(RErr::(5).or_else(|e| ROk ::(e/2) ), ROk (2)); + /// assert_eq!(RErr::(5).or_else(|e| RErr::(e/2) ), RErr(2)); /// /// ``` #[inline] @@ -282,7 +282,7 @@ impl RResult { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!( ROk::<_,()>(500).unwrap(), 500 ); + /// assert_eq!( ROk::<_, ()>(500).unwrap(), 500 ); /// /// ``` /// @@ -290,7 +290,7 @@ impl RResult { /// ```should_panic /// # use abi_stable::std_types::*; /// - /// let _=RErr::<(),_>("Oh noooo!").unwrap(); + /// let _ = RErr::<(), _>("Oh noooo!").unwrap(); /// ``` pub fn unwrap(self) -> T where @@ -312,7 +312,7 @@ impl RResult { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!( ROk::<_,()>(500).expect("Are you OK?"), 500 ); + /// assert_eq!( ROk::<_, ()>(500).expect("Are you OK?"), 500 ); /// /// ``` /// @@ -320,7 +320,7 @@ impl RResult { /// ```should_panic /// # use abi_stable::std_types::*; /// - /// let _=RErr::<(),_>(()).expect("This can't be!"); + /// let _ = RErr::<(), _>(()).expect("This can't be!"); /// ``` pub fn expect(self, message: &str) -> T where @@ -341,7 +341,7 @@ impl RResult { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!( RErr::<(),u32>(0xB007).unwrap_err(), 0xB007 ); + /// assert_eq!( RErr::<(), u32>(0xB007).unwrap_err(), 0xB007 ); /// /// ``` /// @@ -349,7 +349,7 @@ impl RResult { /// ```should_panic /// # use abi_stable::std_types::*; /// - /// let _=ROk::<(),()>(()).unwrap_err(); + /// let _ = ROk::<(), ()>(()).unwrap_err(); /// ``` pub fn unwrap_err(self) -> E where @@ -371,7 +371,7 @@ impl RResult { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!( RErr::<(),u32>(0xB001).expect_err("Murphy's law"), 0xB001 ); + /// assert_eq!( RErr::<(), u32>(0xB001).expect_err("Murphy's law"), 0xB001 ); /// /// ``` /// @@ -379,7 +379,7 @@ impl RResult { /// ```should_panic /// # use abi_stable::std_types::*; /// - /// let _=ROk::<(),()>(()).expect_err("Everything is Ok"); + /// let _ = ROk::<(), ()>(()).expect_err("Everything is Ok"); /// ``` pub fn expect_err(self, message: &str) -> E where @@ -388,15 +388,15 @@ impl RResult { self.into_result().expect_err(message) } - /// Returns the value in `ROk`,or `def` if `self` is `RErr`. + /// Returns the value in `ROk`, or `def` if `self` is `RErr`. /// /// # Example /// /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(ROk::(10).unwrap_or(0xEEEE),10); - /// assert_eq!(RErr::(5).unwrap_or(0b101010),0b101010); + /// assert_eq!(ROk::(10).unwrap_or(0xEEEE), 10); + /// assert_eq!(RErr::(5).unwrap_or(0b101010), 0b101010); /// /// ``` #[inline] @@ -415,8 +415,8 @@ impl RResult { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(ROk::(10).unwrap_or_else(|e| e*3 ),10); - /// assert_eq!(RErr::(5).unwrap_or_else(|e| e/2 ),2); + /// assert_eq!(ROk::(10).unwrap_or_else(|e| e*3 ), 10); + /// assert_eq!(RErr::(5).unwrap_or_else(|e| e/2 ), 2); /// /// ``` #[inline] @@ -438,8 +438,8 @@ impl RResult { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(ROk::(10).unwrap_or_default(),10); - /// assert_eq!(RErr::(5).unwrap_or_default(),0); + /// assert_eq!(ROk::(10).unwrap_or_default(), 10); + /// assert_eq!(RErr::(5).unwrap_or_default(), 0); /// /// ``` #[inline] @@ -454,15 +454,15 @@ impl RResult { } /// Converts from `RResult` to `ROption`, - /// `ROk` maps to `RSome`,`RErr` maps to `RNone`. + /// `ROk` maps to `RSome`, `RErr` maps to `RNone`. /// /// # Example /// /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(ROk::(10).ok(),RSome(10)); - /// assert_eq!(RErr::(5).ok(),RNone); + /// assert_eq!(ROk::(10).ok(), RSome(10)); + /// assert_eq!(RErr::(5).ok(), RNone); /// /// ``` #[inline] @@ -474,15 +474,15 @@ impl RResult { } /// Converts from `RResult` to `ROption`, - /// `ROk` maps to `RNone`,`RErr` maps to `RSome`. + /// `ROk` maps to `RNone`, `RErr` maps to `RSome`. /// /// # Example /// /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(ROk::(10).err(),RNone); - /// assert_eq!(RErr::(5).err(),RSome(5)); + /// assert_eq!(ROk::(10).err(), RNone); + /// assert_eq!(RErr::(5).err(), RSome(5)); /// /// ``` #[inline] diff --git a/abi_stable/src/std_types/slice_mut.rs b/abi_stable/src/std_types/slice_mut.rs index 893d82c2..7c211c4c 100644 --- a/abi_stable/src/std_types/slice_mut.rs +++ b/abi_stable/src/std_types/slice_mut.rs @@ -28,14 +28,14 @@ mod privacy { # Lifetime problems - Because `RSliceMut` dereferences into a mutable slice,you can call slice methods on it. + Because `RSliceMut` dereferences into a mutable slice, you can call slice methods on it. If you call a slice method that returns a borrow into the slice, - it will have the lifetime of the `let slice: RSliceMut<'a,[T]>` variable instead of the `'a` + it will have the lifetime of the `let slice: RSliceMut<'a, [T]>` variable instead of the `'a` lifetime that it's parameterized over. To get a slice with the same lifetime as an `RSliceMut`, - one must use one of the `RSliceMut::{into_slice,into_mut_slice}` methods. + one must use one of the `RSliceMut::{into_slice, into_mut_slice}` methods. Example of what would not work: @@ -43,11 +43,11 @@ mod privacy { ```compile_fail use abi_stable::std_types::RSliceMut; - fn into_slice<'a,T>(slic:RSliceMut<'a,T>)->&'a [T] { + fn into_slice<'a, T>(slic: RSliceMut<'a, T>) -> &'a [T] { &*slic } - fn into_mut_slice<'a,T>(slic:RSliceMut<'a,T>)->&'a mut [T] { + fn into_mut_slice<'a, T>(slic: RSliceMut<'a, T>) -> &'a mut [T] { &mut *slic } ``` @@ -57,11 +57,11 @@ mod privacy { ``` use abi_stable::std_types::RSliceMut; - fn into_slice<'a,T>(slic:RSliceMut<'a,T>)->&'a [T] { + fn into_slice<'a, T>(slic: RSliceMut<'a, T>) -> &'a [T] { slic.into_slice() } - fn into_mut_slice<'a,T>(slic:RSliceMut<'a,T>)->&'a mut [T] { + fn into_mut_slice<'a, T>(slic: RSliceMut<'a, T>) -> &'a mut [T] { slic.into_mut_slice() } ``` @@ -79,12 +79,12 @@ mod privacy { }; #[sabi_extern_fn] - pub fn find_first_mut<'a,T>(slice_:RSliceMut<'a,T>,element:&T)->Option<&'a mut T> + pub fn find_first_mut<'a, T>(slice_: RSliceMut<'a, T>, element: &T) -> Option<&'a mut T> where - T:std::cmp::PartialEq + T: std::cmp::PartialEq { slice_.iter() - .position(|x| x==element ) + .position(|x| x == element ) .map(|i| &mut slice_.into_mut_slice()[i] ) } @@ -94,7 +94,7 @@ mod privacy { */ #[repr(C)] #[derive(StableAbi)] - #[sabi(bound = "T:'a")] + #[sabi(bound = "T: 'a")] pub struct RSliceMut<'a, T> { data: *mut T, length: usize, @@ -104,7 +104,7 @@ mod privacy { /// Used as a workaround to make `from_raw_parts_mut` a const fn. #[repr(C)] #[derive(StableAbi)] - #[sabi(bound = "T:'a")] + #[sabi(bound = "T: 'a")] struct MutWorkaround<'a, T>(&'a mut T); impl_from_rust_repr! { @@ -149,7 +149,7 @@ mod privacy { /// /// assert_eq!(RSliceMut::::from_mut_slice(&mut[]).len(), 0); /// assert_eq!(RSliceMut::from_mut_slice(&mut[0]).len(), 1); - /// assert_eq!(RSliceMut::from_mut_slice(&mut[0,1]).len(), 2); + /// assert_eq!(RSliceMut::from_mut_slice(&mut[0, 1]).len(), 2); /// /// /// ``` @@ -167,7 +167,7 @@ mod privacy { /// /// assert_eq!(RSliceMut::::from_mut_slice(&mut []).is_empty(), true); /// assert_eq!(RSliceMut::from_mut_slice(&mut [0]).is_empty(), false); - /// assert_eq!(RSliceMut::from_mut_slice(&mut [0,1]).is_empty(), false); + /// assert_eq!(RSliceMut::from_mut_slice(&mut [0, 1]).is_empty(), false); /// /// ``` #[inline] @@ -175,7 +175,7 @@ mod privacy { self.length == 0 } - /// Constructs an `RSliceMut<'a,T>` from a pointer to the first element, + /// Constructs an `RSliceMut<'a, T>` from a pointer to the first element, /// and a length. /// /// # Safety @@ -188,7 +188,7 @@ mod privacy { /// /// - `ptr_` is aligned to `T`. /// - /// - the data `ptr_` points to must be valid for the lifetime of this `RSlice<'a,T>` + /// - the data `ptr_` points to must be valid for the lifetime of this `RSlice<'a, T>` /// /// # Examples /// @@ -198,8 +198,8 @@ mod privacy { /// ``` /// use abi_stable::std_types::RSliceMut; /// - /// fn convert(slice_:&mut [T])->RSliceMut<'_,T>{ - /// let len=slice_.len(); + /// fn convert(slice_: &mut [T]) -> RSliceMut<'_, T>{ + /// let len = slice_.len(); /// unsafe{ /// RSliceMut::from_raw_parts_mut( slice_.as_mut_ptr(), len ) /// } @@ -224,9 +224,9 @@ impl<'a, T> RSliceMut<'a, T> { // Self::EMPTY // } - /// Converts a mutable reference to `T` to a single element `RSliceMut<'a,T>`. + /// Converts a mutable reference to `T` to a single element `RSliceMut<'a, T>`. /// - /// Note:this function does not copy anything. + /// Note: this function does not copy anything. /// /// # Example /// @@ -243,18 +243,18 @@ impl<'a, T> RSliceMut<'a, T> { unsafe { Self::from_raw_parts_mut(ref_, 1) } } - /// Converts a `&'a mut [T]` to a `RSliceMut<'a,T>`. + /// Converts a `&'a mut [T]` to a `RSliceMut<'a, T>`. /// /// # Example /// /// ``` /// use abi_stable::std_types::RSliceMut; /// - /// let empty:&mut [u8]=&mut []; + /// let empty: &mut [u8] = &mut []; /// /// assert_eq!(RSliceMut::::from_mut_slice(&mut[]).as_mut_slice(), empty); /// assert_eq!(RSliceMut::from_mut_slice(&mut[0]).as_mut_slice() , &mut [0][..]); - /// assert_eq!(RSliceMut::from_mut_slice(&mut[0,1]).as_mut_slice() , &mut [0,1][..]); + /// assert_eq!(RSliceMut::from_mut_slice(&mut[0, 1]).as_mut_slice() , &mut [0, 1][..]); /// /// ``` #[inline] @@ -262,7 +262,7 @@ impl<'a, T> RSliceMut<'a, T> { slic.into() } - /// Creates an `RSlice<'b,T>` with access to the `range` range of elements. + /// Creates an `RSlice<'b, T>` with access to the `range` range of elements. /// /// This is an inherent method instead of an implementation of the /// `std::ops::Index` trait because it does not return a reference. @@ -270,15 +270,15 @@ impl<'a, T> RSliceMut<'a, T> { /// # Example /// /// ``` - /// use abi_stable::std_types::{RSliceMut,RSlice}; + /// use abi_stable::std_types::{RSliceMut, RSlice}; /// - /// let slic=&mut[0,1,2,3]; - /// let slic=RSliceMut::from_mut_slice(slic); + /// let slic = &mut[0, 1, 2, 3]; + /// let slic = RSliceMut::from_mut_slice(slic); /// - /// assert_eq!(slic.slice(..),RSlice::from_slice(&[0,1,2,3])); - /// assert_eq!(slic.slice(..2),RSlice::from_slice(&[0,1])); - /// assert_eq!(slic.slice(2..),RSlice::from_slice(&[2,3])); - /// assert_eq!(slic.slice(1..3),RSlice::from_slice(&[1,2])); + /// assert_eq!(slic.slice(..), RSlice::from_slice(&[0, 1, 2, 3])); + /// assert_eq!(slic.slice(..2), RSlice::from_slice(&[0, 1])); + /// assert_eq!(slic.slice(2..), RSlice::from_slice(&[2, 3])); + /// assert_eq!(slic.slice(1..3), RSlice::from_slice(&[1, 2])); /// /// ``` #[allow(clippy::needless_lifetimes)] @@ -289,7 +289,7 @@ impl<'a, T> RSliceMut<'a, T> { self.as_slice().index(i).into() } - /// Creates an `RSliceMut<'a,T>` with access to the `range` range of elements. + /// Creates an `RSliceMut<'a, T>` with access to the `range` range of elements. /// /// This is an inherent method instead of an implementation of the /// `std::ops::IndexMut` trait because it does not return a reference. @@ -299,13 +299,13 @@ impl<'a, T> RSliceMut<'a, T> { /// ``` /// use abi_stable::std_types::RSliceMut; /// - /// let slic=&mut[0,1,2,3]; - /// let mut slic=RSliceMut::from_mut_slice(slic); + /// let slic = &mut[0, 1, 2, 3]; + /// let mut slic = RSliceMut::from_mut_slice(slic); /// - /// assert_eq!(slic.slice_mut(..),RSliceMut::from_mut_slice(&mut[0,1,2,3])); - /// assert_eq!(slic.slice_mut(..2),RSliceMut::from_mut_slice(&mut[0,1])); - /// assert_eq!(slic.slice_mut(2..),RSliceMut::from_mut_slice(&mut[2,3])); - /// assert_eq!(slic.slice_mut(1..3),RSliceMut::from_mut_slice(&mut[1,2])); + /// assert_eq!(slic.slice_mut(..), RSliceMut::from_mut_slice(&mut[0, 1, 2, 3])); + /// assert_eq!(slic.slice_mut(..2), RSliceMut::from_mut_slice(&mut[0, 1])); + /// assert_eq!(slic.slice_mut(2..), RSliceMut::from_mut_slice(&mut[2, 3])); + /// assert_eq!(slic.slice_mut(1..3), RSliceMut::from_mut_slice(&mut[1, 2])); /// /// ``` #[allow(clippy::needless_lifetimes)] @@ -321,15 +321,15 @@ impl<'a, T> RSliceMut<'a, T> { /// # Example /// /// ``` - /// use abi_stable::std_types::{RSliceMut,RVec}; + /// use abi_stable::std_types::{RSliceMut, RVec}; /// - /// let slic=&mut[0,1,2,3]; - /// let slic=RSliceMut::from_mut_slice(slic); + /// let slic = &mut[0, 1, 2, 3]; + /// let slic = RSliceMut::from_mut_slice(slic); /// - /// assert_eq!(slic.slice(..).to_rvec(),RVec::from_slice(&[0,1,2,3])); - /// assert_eq!(slic.slice(..2).to_rvec(),RVec::from_slice(&[0,1])); - /// assert_eq!(slic.slice(2..).to_rvec(),RVec::from_slice(&[2,3])); - /// assert_eq!(slic.slice(1..3).to_rvec(),RVec::from_slice(&[1,2])); + /// assert_eq!(slic.slice(..).to_rvec(), RVec::from_slice(&[0, 1, 2, 3])); + /// assert_eq!(slic.slice(..2).to_rvec(), RVec::from_slice(&[0, 1])); + /// assert_eq!(slic.slice(2..).to_rvec(), RVec::from_slice(&[2, 3])); + /// assert_eq!(slic.slice(1..3).to_rvec(), RVec::from_slice(&[1, 2])); /// /// ``` pub fn to_rvec(&self) -> RVec @@ -354,7 +354,7 @@ impl<'a, T> RSliceMut<'a, T> { /// ``` /// use abi_stable::std_types::RSliceMut; /// - /// assert_eq!(RSliceMut::from_mut_slice(&mut[0,1,2,3]).as_slice(), &[0,1,2,3]); + /// assert_eq!(RSliceMut::from_mut_slice(&mut[0, 1, 2, 3]).as_slice(), &[0, 1, 2, 3]); /// /// ``` pub fn as_slice(&self) -> &[T] { @@ -371,7 +371,7 @@ impl<'a, T> RSliceMut<'a, T> { /// ``` /// use abi_stable::std_types::RSliceMut; /// - /// assert_eq!(RSliceMut::from_mut_slice(&mut[0,1,2,3]).into_slice(), &[0,1,2,3]); + /// assert_eq!(RSliceMut::from_mut_slice(&mut[0, 1, 2, 3]).into_slice(), &[0, 1, 2, 3]); /// /// ``` pub fn into_slice(self) -> &'a [T] { @@ -383,11 +383,11 @@ impl<'a, T> RSliceMut<'a, T> { /// # Example /// /// ``` - /// use abi_stable::std_types::{RSliceMut,RSlice}; + /// use abi_stable::std_types::{RSliceMut, RSlice}; /// /// assert_eq!( - /// RSliceMut::from_mut_slice(&mut[0,1,2,3]).as_rslice(), - /// RSlice::from_slice(&[0,1,2,3]), + /// RSliceMut::from_mut_slice(&mut[0, 1, 2, 3]).as_rslice(), + /// RSlice::from_slice(&[0, 1, 2, 3]), /// ); /// /// ``` @@ -403,11 +403,11 @@ impl<'a, T> RSliceMut<'a, T> { /// # Example /// /// ``` - /// use abi_stable::std_types::{RSliceMut,RSlice}; + /// use abi_stable::std_types::{RSliceMut, RSlice}; /// /// assert_eq!( - /// RSliceMut::from_mut_slice(&mut[0,1,2,3]).into_rslice(), - /// RSlice::from_slice(&[0,1,2,3]), + /// RSliceMut::from_mut_slice(&mut[0, 1, 2, 3]).into_rslice(), + /// RSlice::from_slice(&[0, 1, 2, 3]), /// ); /// /// ``` @@ -422,7 +422,7 @@ impl<'a, T> RSliceMut<'a, T> { /// ``` /// use abi_stable::std_types::RSliceMut; /// - /// assert_eq!(RSliceMut::from_mut_slice(&mut[0,1,2,3]).as_mut_slice(), &mut [0,1,2,3]); + /// assert_eq!(RSliceMut::from_mut_slice(&mut[0, 1, 2, 3]).as_mut_slice(), &mut [0, 1, 2, 3]); /// /// ``` pub fn as_mut_slice(&mut self) -> &mut [T] { @@ -439,7 +439,7 @@ impl<'a, T> RSliceMut<'a, T> { /// ``` /// use abi_stable::std_types::RSliceMut; /// - /// assert_eq!(RSliceMut::from_mut_slice(&mut[0,1,2,3]).into_mut_slice(), &mut [0,1,2,3]); + /// assert_eq!(RSliceMut::from_mut_slice(&mut[0, 1, 2, 3]).into_mut_slice(), &mut [0, 1, 2, 3]); /// /// ``` pub fn into_mut_slice(mut self) -> &'a mut [T] { @@ -589,9 +589,9 @@ impl<'a> Write for RSliceMut<'a, u8> { type SliceMut<'a, T> = &'a mut [T]; shared_impls! { - mod=slice_impls - new_type=RSliceMut['a][T], - original_type=SliceMut, + mod = slice_impls + new_type = RSliceMut['a][T], + original_type = SliceMut, } //////////////////////////////////////////////////////////////////////////////// diff --git a/abi_stable/src/std_types/slices.rs b/abi_stable/src/std_types/slices.rs index 145e5e9d..1dc36e06 100644 --- a/abi_stable/src/std_types/slices.rs +++ b/abi_stable/src/std_types/slices.rs @@ -19,76 +19,71 @@ use crate::std_types::RVec; mod private { use super::*; - /** - Ffi-safe equivalent of `&'a [T]` - - As of the writing this documentation the abi stability of `&[T]` is - not yet guaranteed. - - # Lifetime problems - - Because `RSlice` dereferences into a slice,you can call slice methods on it. - - If you call a slice method that returns a borrow into the slice, - it will have the lifetime of the `let slice: RSlice<'a,[T]>` variable instead of the `'a` - lifetime that it's parameterized over. - - To get a slice with the same lifetime as an `RSlice`, - one must use the `RSlice::as_slice` method. - - - Example of what would not work: - - ```compile_fail - use abi_stable::std_types::RSlice; - - fn into_slice<'a,T>(slic:RSlice<'a,T>)->&'a [T] { - &*slic - } - ``` - - Example of what would work: - - ``` - use abi_stable::std_types::RSlice; - - fn into_slice<'a,T>(slic:RSlice<'a,T>)->&'a [T] { - slic.as_slice() - } - ``` - - - - # Example - - Defining an extern fn that returns a reference to - the first element that compares equal to a parameter. - - ``` - use abi_stable::{ - std_types::RSlice, - sabi_extern_fn, - }; - - #[sabi_extern_fn] - pub fn find_first_mut<'a,T>(slice_:RSlice<'a,T>,element:&T)->Option<&'a T> - where - T:std::cmp::PartialEq - { - slice_.iter() - .position(|x| x==element ) - .map(|i| &slice_.as_slice()[i] ) - } - - - ``` - - - - */ + /// Ffi-safe equivalent of `&'a [T]` + /// + /// As of the writing this documentation the abi stability of `&[T]` is + /// not yet guaranteed. + /// + /// # Lifetime problems + /// + /// Because `RSlice` dereferences into a slice, you can call slice methods on it. + /// + /// If you call a slice method that returns a borrow into the slice, + /// it will have the lifetime of the `let slice: RSlice<'a, [T]>` variable instead of the `'a` + /// lifetime that it's parameterized over. + /// + /// To get a slice with the same lifetime as an `RSlice`, + /// one must use the `RSlice::as_slice` method. + /// + /// + /// Example of what would not work: + /// + /// ```compile_fail + /// use abi_stable::std_types::RSlice; + /// + /// fn into_slice<'a, T>(slic: RSlice<'a, T>) -> &'a [T] { + /// &*slic + /// } + /// ``` + /// + /// Example of what would work: + /// + /// ``` + /// use abi_stable::std_types::RSlice; + /// + /// fn into_slice<'a, T>(slic: RSlice<'a, T>) -> &'a [T] { + /// slic.as_slice() + /// } + /// ``` + /// + /// + /// + /// # Example + /// + /// Defining an extern fn that returns a reference to + /// the first element that compares equal to a parameter. + /// + /// ``` + /// use abi_stable::{ + /// std_types::RSlice, + /// sabi_extern_fn, + /// }; + /// + /// #[sabi_extern_fn] + /// pub fn find_first_mut<'a, T>(slice_: RSlice<'a, T>, element: &T) -> Option<&'a T> + /// where + /// T: std::cmp::PartialEq + /// { + /// slice_.iter() + /// .position(|x| x == element ) + /// .map(|i| &slice_.as_slice()[i] ) + /// } + /// + /// + /// ``` #[repr(C)] #[derive(StableAbi)] - #[sabi(bound = "T:'a")] + #[sabi(bound = "T: 'a")] //#[sabi(debug_print)] pub struct RSlice<'a, T> { data: *const T, @@ -117,7 +112,7 @@ mod private { _marker: PhantomData, }; - /// Constructs an `RSlice<'a,T>` from a pointer to the first element, + /// Constructs an `RSlice<'a, T>` from a pointer to the first element, /// and a length. /// /// # Safety @@ -140,7 +135,7 @@ mod private { /// ``` /// use abi_stable::std_types::RSlice; /// - /// fn convert(slice_:&[T])->RSlice<'_,T>{ + /// fn convert(slice_: &[T]) -> RSlice<'_, T>{ /// unsafe{ /// RSlice::from_raw_parts( slice_.as_ptr(), slice_.len() ) /// } @@ -173,7 +168,7 @@ mod private { /// ``` /// use abi_stable::std_types::RSlice; /// - /// assert_eq!(RSlice::from_slice(&[0,1,2,3]).as_slice(), &[0,1,2,3]); + /// assert_eq!(RSlice::from_slice(&[0, 1, 2, 3]).as_slice(), &[0, 1, 2, 3]); /// /// ``` pub fn as_slice(&self) -> &'a [T] { @@ -194,7 +189,7 @@ mod private { /// /// assert_eq!(RSlice::::from_slice(&[]).len(), 0); /// assert_eq!(RSlice::from_slice(&[0]).len(), 1); - /// assert_eq!(RSlice::from_slice(&[0,1]).len(), 2); + /// assert_eq!(RSlice::from_slice(&[0, 1]).len(), 2); /// /// ``` #[inline] @@ -211,7 +206,7 @@ mod private { /// /// assert_eq!(RSlice::::from_slice(&[]).is_empty(), true); /// assert_eq!(RSlice::from_slice(&[0]).is_empty(), false); - /// assert_eq!(RSlice::from_slice(&[0,1]).is_empty(), false); + /// assert_eq!(RSlice::from_slice(&[0, 1]).is_empty(), false); /// /// ``` #[inline] @@ -229,9 +224,9 @@ impl<'a, T> RSlice<'a, T> { Self::EMPTY } - /// Converts a reference to `T` to a single element `RSlice<'a,T>`. + /// Converts a reference to `T` to a single element `RSlice<'a, T>`. /// - /// Note:this function does not copy anything. + /// Note: this function does not copy anything. /// /// # Example /// @@ -248,18 +243,18 @@ impl<'a, T> RSlice<'a, T> { unsafe { Self::from_raw_parts(ref_, 1) } } - /// Converts a `&[T]` to an `RSlice<'_,T>`. + /// Converts a `&[T]` to an `RSlice<'_, T>`. /// /// # Example /// /// ``` /// use abi_stable::std_types::RSlice; /// - /// let empty:&[u8]=&[]; + /// let empty: &[u8] = &[]; /// /// assert_eq!(RSlice::::from_slice(&[]).as_slice(), empty); /// assert_eq!(RSlice::from_slice(&[0]).as_slice() , &[0][..]); - /// assert_eq!(RSlice::from_slice(&[0,1]).as_slice() , &[0,1][..]); + /// assert_eq!(RSlice::from_slice(&[0, 1]).as_slice() , &[0, 1][..]); /// /// ``` #[inline] @@ -267,7 +262,7 @@ impl<'a, T> RSlice<'a, T> { unsafe { RSlice::from_raw_parts(slic.as_ptr(), slic.len()) } } - /// Creates an `RSlice<'a,T>` with access to the `range` range of elements. + /// Creates an `RSlice<'a, T>` with access to the `range` range of elements. /// /// This is an inherent method instead of an implementation of the /// `std::ops::Index` trait because it does not return a reference. @@ -277,12 +272,12 @@ impl<'a, T> RSlice<'a, T> { /// ``` /// use abi_stable::std_types::RSlice; /// - /// let slic=RSlice::from_slice(&[0,1,2,3]); + /// let slic = RSlice::from_slice(&[0, 1, 2, 3]); /// - /// assert_eq!(slic.slice(..),RSlice::from_slice(&[0,1,2,3])); - /// assert_eq!(slic.slice(..2),RSlice::from_slice(&[0,1])); - /// assert_eq!(slic.slice(2..),RSlice::from_slice(&[2,3])); - /// assert_eq!(slic.slice(1..3),RSlice::from_slice(&[1,2])); + /// assert_eq!(slic.slice(..), RSlice::from_slice(&[0, 1, 2, 3])); + /// assert_eq!(slic.slice(..2), RSlice::from_slice(&[0, 1])); + /// assert_eq!(slic.slice(2..), RSlice::from_slice(&[2, 3])); + /// assert_eq!(slic.slice(1..3), RSlice::from_slice(&[1, 2])); /// /// ``` pub fn slice(&self, i: I) -> RSlice<'a, T> @@ -297,14 +292,14 @@ impl<'a, T> RSlice<'a, T> { /// # Example /// /// ``` - /// use abi_stable::std_types::{RSlice,RVec}; + /// use abi_stable::std_types::{RSlice, RVec}; /// - /// let slic=RSlice::from_slice(&[0,1,2,3]); + /// let slic = RSlice::from_slice(&[0, 1, 2, 3]); /// - /// assert_eq!( slic.slice(..).to_rvec(), RVec::from_slice(&[0,1,2,3]) ); - /// assert_eq!( slic.slice(..2).to_rvec(), RVec::from_slice(&[0,1]) ); - /// assert_eq!( slic.slice(2..).to_rvec(), RVec::from_slice(&[2,3]) ); - /// assert_eq!( slic.slice(1..3).to_rvec(), RVec::from_slice(&[1,2]) ); + /// assert_eq!( slic.slice(..).to_rvec(), RVec::from_slice(&[0, 1, 2, 3]) ); + /// assert_eq!( slic.slice(..2).to_rvec(), RVec::from_slice(&[0, 1]) ); + /// assert_eq!( slic.slice(2..).to_rvec(), RVec::from_slice(&[2, 3]) ); + /// assert_eq!( slic.slice(1..3).to_rvec(), RVec::from_slice(&[1, 2]) ); /// /// ``` pub fn to_rvec(&self) -> RVec @@ -314,7 +309,7 @@ impl<'a, T> RSlice<'a, T> { self.to_vec().into() } - /// Transmutes n `RSlice<'a,T>` to a `RSlice<'a,U>` + /// Transmutes n `RSlice<'a, T>` to a `RSlice<'a, U>` /// /// # Safety /// @@ -482,9 +477,9 @@ impl<'a> BufRead for RSlice<'a, u8> { type Slice<'a, T> = &'a [T]; shared_impls! { - mod=slice_impls - new_type=RSlice['a][T], - original_type=Slice, + mod = slice_impls + new_type = RSlice['a][T], + original_type = Slice, } //////////////////////////////////////////////////////////////////////////////// diff --git a/abi_stable/src/std_types/std_error.rs b/abi_stable/src/std_types/std_error.rs index 80256edf..be68b42a 100644 --- a/abi_stable/src/std_types/std_error.rs +++ b/abi_stable/src/std_types/std_error.rs @@ -25,7 +25,7 @@ use crate::{ }; #[cfg(test)] -// #[cfg(all(test,not(feature="only_new_tests")))] +// #[cfg(all(test, not(feature = "only_new_tests")))] mod test; /** @@ -35,33 +35,33 @@ whose `Send + Sync`ness is determined by the `M` type parameter. # Examples ### Converting from and into `Box` - + ``` use std::{ convert::TryFrom, error::Error as ErrorTrait, }; -use abi_stable::std_types::{RBox,RBoxError,UnsyncRBoxError,SendRBoxError}; +use abi_stable::std_types::{RBox, RBoxError, UnsyncRBoxError, SendRBoxError}; { - let from:Box= "hello,error".into(); - let rbox=UnsyncRBoxError::from_box(from); - let _:Box= rbox.into_box(); + let from: Box = "hello, error".into(); + let rbox = UnsyncRBoxError::from_box(from); + let _: Box = rbox.into_box(); } { let arr_err=<[();0]>::try_from(&[()][..]).unwrap_err(); - let from:Box= Box::new(arr_err); - let rbox=SendRBoxError::from_box(from); - let _:Box= rbox.into_box(); + let from: Box = Box::new(arr_err); + let rbox = SendRBoxError::from_box(from); + let _: Box = rbox.into_box(); } { let arr_err=<[();0]>::try_from(&[()][..]).unwrap_err(); - let from:Box= Box::new(arr_err); - let rbox=RBoxError::from_box(from); - let _:Box= rbox.into_box(); + let from: Box = Box::new(arr_err); + let rbox = RBoxError::from_box(from); + let _: Box = rbox.into_box(); } ``` @@ -69,24 +69,24 @@ use abi_stable::std_types::{RBox,RBoxError,UnsyncRBoxError,SendRBoxError}; ### Downcasting by value ``` -use std::num::{ParseFloatError,ParseIntError}; +use std::num::{ParseFloatError, ParseIntError}; -use abi_stable::std_types::{RBox,RBoxError}; +use abi_stable::std_types::{RBox, RBoxError}; -// Constructing a `RBoxError` from a `Box`,then downcasting to a `ParseIntError`. +// Constructing a `RBoxError` from a `Box`, then downcasting to a `ParseIntError`. { - let parse_err="".parse::().unwrap_err(); - let dyn_err:Box= + let parse_err = "".parse::().unwrap_err(); + let dyn_err: Box = Box::new(parse_err.clone()); - let err=RBoxError::from_box(dyn_err); + let err = RBoxError::from_box(dyn_err); assert_eq!( err.downcast::().unwrap(), RBox::new(parse_err) ); } -// Constructing a `RBoxError` from a `ParseFloatError`,then downcasting back to it. +// Constructing a `RBoxError` from a `ParseFloatError`, then downcasting back to it. { - let parse_err="".parse::().unwrap_err(); - let err=RBoxError::new(parse_err.clone()); + let parse_err = "".parse::().unwrap_err(); + let err = RBoxError::new(parse_err.clone()); assert_eq!( err.downcast::().unwrap(), RBox::new(parse_err) ); } @@ -94,8 +94,8 @@ use abi_stable::std_types::{RBox,RBoxError}; // Constructing a `RBoxError` from a `ParseFloatError`, // then attempting to downcasting it to a `ParseIntError`. { - let parse_err="".parse::().unwrap_err(); - let err=RBoxError::new(parse_err); + let parse_err = "".parse::().unwrap_err(); + let err = RBoxError::new(parse_err); assert!( err.downcast::().is_err() ); } @@ -111,23 +111,23 @@ use std::{ str::Utf8Error, }; -use abi_stable::std_types::{RBox,UnsyncRBoxError}; +use abi_stable::std_types::{RBox, UnsyncRBoxError}; // Constructing a `UnsyncRBoxError` from a `Box`, // then downcasting to a `TryFromIntError`. { - let int_err=u32::try_from(-1_i32).unwrap_err(); - let dyn_err:Box= + let int_err = u32::try_from(-1_i32).unwrap_err(); + let dyn_err: Box = Box::new(int_err.clone()); - let err=UnsyncRBoxError::from_box(dyn_err); + let err = UnsyncRBoxError::from_box(dyn_err); assert_eq!( err.downcast_ref::().unwrap(), &int_err ); } -// Constructing a `UnsyncRBoxError` from a `Utf8Error`,then downcasting back to it. +// Constructing a `UnsyncRBoxError` from a `Utf8Error`, then downcasting back to it. { - let utf8_err=std::str::from_utf8(&[255]).unwrap_err(); - let err=UnsyncRBoxError::new(utf8_err.clone()); + let utf8_err = std::str::from_utf8(&[255]).unwrap_err(); + let err = UnsyncRBoxError::new(utf8_err.clone()); assert_eq!( err.downcast_ref::().unwrap(), &utf8_err ); } @@ -135,8 +135,8 @@ use abi_stable::std_types::{RBox,UnsyncRBoxError}; // Constructing a `UnsyncRBoxError` from a `Utf8Error`, // then attempting to downcasting it to a `TryFromIntError`. { - let utf8_err=std::str::from_utf8(&[255]).unwrap_err(); - let err=UnsyncRBoxError::new(utf8_err); + let utf8_err = std::str::from_utf8(&[255]).unwrap_err(); + let err = UnsyncRBoxError::new(utf8_err); assert!( err.downcast_ref::().is_none() ); } @@ -147,36 +147,36 @@ use abi_stable::std_types::{RBox,UnsyncRBoxError}; ### Downcasting by mutable reference ``` -use std::string::{FromUtf8Error,FromUtf16Error}; +use std::string::{FromUtf8Error, FromUtf16Error}; -use abi_stable::std_types::{RBox,SendRBoxError}; +use abi_stable::std_types::{RBox, SendRBoxError}; // Constructing a `SendRBoxError` from a `Box`, // then downcasting to a `FromUtf8Error`. { - let str_err=|| String::from_utf8(vec![255]).unwrap_err() ; - let dyn_err:Box= + let str_err = || String::from_utf8(vec![255]).unwrap_err() ; + let dyn_err: Box = Box::new(str_err()); - let mut err=SendRBoxError::from_box(dyn_err); + let mut err = SendRBoxError::from_box(dyn_err); - assert!( err.downcast_ref::().is_some() ,"part A"); + assert!( err.downcast_ref::().is_some() , "part A"); } -// Constructing a `SendRBoxError` from a `FromUtf8Error`,then downcasting back to it. +// Constructing a `SendRBoxError` from a `FromUtf8Error`, then downcasting back to it. { - let str_err=|| String::from_utf8(vec![255]).unwrap_err() ; - let mut err=SendRBoxError::new(str_err()); + let str_err = || String::from_utf8(vec![255]).unwrap_err() ; + let mut err = SendRBoxError::new(str_err()); - assert!( err.downcast_ref::().is_some() ,"part B"); + assert!( err.downcast_ref::().is_some() , "part B"); } // Constructing a `SendRBoxError` from a `FromUtf16Error`, // then attempting to downcasting it to a `FromUtf8Error`. { - let str_err=|| String::from_utf16(&[0xD834]).unwrap_err() ; - let mut err=SendRBoxError::new(str_err()); + let str_err = || String::from_utf16(&[0xD834]).unwrap_err() ; + let mut err = SendRBoxError::new(str_err()); - assert!( err.downcast_ref::().is_none() ,"part C"); + assert!( err.downcast_ref::().is_none() , "part C"); } ``` @@ -209,9 +209,9 @@ impl RBoxError_ { /// ``` /// use abi_stable::std_types::RBoxError; /// - /// let str_err=String::from_utf8(vec![255]).unwrap_err(); + /// let str_err = String::from_utf8(vec![255]).unwrap_err(); /// - /// let err=RBoxError::new(str_err); + /// let err = RBoxError::new(str_err); /// ``` pub fn new(value: T) -> Self where @@ -229,9 +229,9 @@ impl RBoxError_ { /// ``` /// use abi_stable::std_types::SendRBoxError; /// - /// let str_err=String::from_utf16(&[0xD834]).unwrap_err() ; + /// let str_err = String::from_utf16(&[0xD834]).unwrap_err() ; /// - /// let err=SendRBoxError::new(str_err); + /// let err = SendRBoxError::new(str_err); /// ``` pub fn new(value: T) -> Self where @@ -249,9 +249,9 @@ impl RBoxError_ { /// ``` /// use abi_stable::std_types::UnsyncRBoxError; /// - /// let str_err=std::str::from_utf8(&[255]).unwrap_err() ; + /// let str_err = std::str::from_utf8(&[255]).unwrap_err() ; /// - /// let err=UnsyncRBoxError::new(str_err); + /// let err = UnsyncRBoxError::new(str_err); /// ``` pub fn new(value: T) -> Self where @@ -270,15 +270,15 @@ impl RBoxError_ { /// ``` /// use abi_stable::std_types::RBoxError; /// - /// let int_error="".parse::().unwrap_err(); + /// let int_error = "".parse::().unwrap_err(); /// - /// let display_fmt=int_error.to_string(); - /// let debug_fmt=format!("{:#?}",int_error); + /// let display_fmt = int_error.to_string(); + /// let debug_fmt = format!("{:#?}", int_error); /// - /// let err=RBoxError::from_fmt(&int_error); + /// let err = RBoxError::from_fmt(&int_error); /// - /// assert_eq!(display_fmt,err.to_string()); - /// assert_eq!(debug_fmt,format!("{:?}",err)); + /// assert_eq!(display_fmt, err.to_string()); + /// assert_eq!(debug_fmt, format!("{:?}", err)); /// ``` pub fn from_fmt(value: &T) -> Self where @@ -299,13 +299,13 @@ impl RBoxError_ { /// ``` /// use abi_stable::std_types::RBoxError; /// - /// let int_error="".parse::().unwrap_err(); + /// let int_error = "".parse::().unwrap_err(); /// - /// let debug_fmt=format!("{:#?}",int_error); - /// let err=RBoxError::from_debug(&int_error); + /// let debug_fmt = format!("{:#?}", int_error); + /// let err = RBoxError::from_debug(&int_error); /// - /// assert_eq!(debug_fmt,format!("{}",err)); - /// assert_eq!(debug_fmt,format!("{:#?}",err)); + /// assert_eq!(debug_fmt, format!("{}", err)); + /// assert_eq!(debug_fmt, format!("{:#?}", err)); /// ``` pub fn from_debug(value: &T) -> Self where @@ -388,14 +388,14 @@ impl RBoxError_ { /// # Example /// /// ``` - /// use abi_stable::std_types::{RBoxError,UnsyncRBoxError}; + /// use abi_stable::std_types::{RBoxError, UnsyncRBoxError}; /// use std::convert::TryFrom; /// - /// let int_err=u32::try_from(-1_i32).unwrap_err(); + /// let int_err = u32::try_from(-1_i32).unwrap_err(); /// - /// let err:RBoxError=RBoxError::new(int_err); + /// let err: RBoxError = RBoxError::new(int_err); /// - /// let unsync_err:&UnsyncRBoxError=err.as_unsync(); + /// let unsync_err: &UnsyncRBoxError = err.as_unsync(); /// /// ``` pub fn as_unsync(&self) -> &UnsyncRBoxError { @@ -407,14 +407,14 @@ impl RBoxError_ { /// # Example /// /// ``` - /// use abi_stable::std_types::{RBoxError,UnsyncRBoxError}; + /// use abi_stable::std_types::{RBoxError, UnsyncRBoxError}; /// use std::convert::TryFrom; /// - /// let int_err=u64::try_from(-1338_i32).unwrap_err(); + /// let int_err = u64::try_from(-1338_i32).unwrap_err(); /// - /// let err:RBoxError=RBoxError::new(int_err); + /// let err: RBoxError = RBoxError::new(int_err); /// - /// let unsync_err:UnsyncRBoxError=err.into_unsync(); + /// let unsync_err: UnsyncRBoxError = err.into_unsync(); /// /// ``` pub fn into_unsync(self) -> UnsyncRBoxError { @@ -428,15 +428,15 @@ impl RBoxError_ { /// # Example /// /// ``` - /// use abi_stable::std_types::{RBoxError,SendRBoxError}; + /// use abi_stable::std_types::{RBoxError, SendRBoxError}; /// use std::convert::TryFrom; /// - /// let slice:&mut [u32]=&mut []; + /// let slice: &mut [u32] = &mut []; /// let arr_err=<&mut [u32;10]>::try_from(slice).unwrap_err(); /// - /// let err:RBoxError=RBoxError::new(arr_err); + /// let err: RBoxError = RBoxError::new(arr_err); /// - /// let unsync_err:&SendRBoxError=err.as_send(); + /// let unsync_err: &SendRBoxError = err.as_send(); /// /// ``` pub fn as_send(&self) -> &SendRBoxError { @@ -448,15 +448,15 @@ impl RBoxError_ { /// # Example /// /// ``` - /// use abi_stable::std_types::{RBoxError,SendRBoxError}; + /// use abi_stable::std_types::{RBoxError, SendRBoxError}; /// use std::convert::TryFrom; /// - /// let slice:&[u32]=&[]; + /// let slice: &[u32] = &[]; /// let arr_err=<&[u32;10]>::try_from(slice).unwrap_err(); /// - /// let err:RBoxError=RBoxError::new(arr_err); + /// let err: RBoxError = RBoxError::new(arr_err); /// - /// let unsync_err:SendRBoxError=err.into_send(); + /// let unsync_err: SendRBoxError = err.into_send(); /// /// ``` pub fn into_send(self) -> SendRBoxError { @@ -482,9 +482,9 @@ impl Debug for RBoxError_ { macro_rules! from_impls { ( - $first_docs:expr, - $boxdyn:ty, - $marker:ty, + $first_docs: expr, + $boxdyn: ty, + $marker: ty, ) => { impl From<$boxdyn> for RBoxError_<$marker> { #[doc = $first_docs] @@ -800,7 +800,7 @@ unsafe extern "C" fn as_debug_display( this: RRef<'_, ErasedObject>, ) -> ROption> { extern_fn_panic_handling! { - let this=unsafe{ this.transmute_into_ref::() }; + let this = unsafe{ this.transmute_into_ref::() }; ROption::RSome(DebugDisplayRef{ debug: this.debug.as_str().into(), display: this.display.as_str().into(), diff --git a/abi_stable/src/std_types/std_error/test.rs b/abi_stable/src/std_types/std_error/test.rs index 8e4d238e..24d2d054 100644 --- a/abi_stable/src/std_types/std_error/test.rs +++ b/abi_stable/src/std_types/std_error/test.rs @@ -70,8 +70,8 @@ fn downcast() { macro_rules! downcast_ { ( - method=$method:ident, - conv=$conv:expr + method = $method: ident, + conv = $conv: expr ) => {{ let res0 = RBoxError::new(err.clone()) .$method::() @@ -88,9 +88,9 @@ fn downcast() { }}; } - downcast_! {method=downcast ,conv=|x| x.ok() } - downcast_! {method=downcast_ref,conv=::std::convert::identity} - downcast_! {method=downcast_mut,conv=::std::convert::identity} + downcast_! {method = downcast , conv = |x| x.ok() } + downcast_! {method = downcast_ref, conv=::std::convert::identity} + downcast_! {method = downcast_mut, conv=::std::convert::identity} } #[test] @@ -99,34 +99,34 @@ fn casts_among_rboxerrors() { macro_rules! casts_among_rboxerrors_ { ( - err_ty=$err:ty; - methods=[$($method:ident),* $(,)*]; + err_ty = $err: ty; + methods = [$($method: ident),* $(,)*]; ) => ({ $( let e0=<$err>::new(err.clone()); - let addr=e0.heap_address(); - let e1=e0.$method(); + let addr = e0.heap_address(); + let e1 = e0.$method(); assert_eq!(addr, e1.heap_address()); - check_formatting_equivalence(&err,&e1); + check_formatting_equivalence(&err, &e1); )* }) } casts_among_rboxerrors_! { - err_ty=UnsyncRBoxError; - methods=[into_unsync,as_unsync]; + err_ty = UnsyncRBoxError; + methods = [into_unsync, as_unsync]; } casts_among_rboxerrors_! { - err_ty=SendRBoxError; - methods=[into_unsync,as_unsync]; + err_ty = SendRBoxError; + methods = [into_unsync, as_unsync]; } casts_among_rboxerrors_! { - err_ty=RBoxError; - methods=[into_unsync,as_unsync,as_send,into_send]; + err_ty = RBoxError; + methods = [into_unsync, as_unsync, as_send, into_send]; } } diff --git a/abi_stable/src/std_types/std_io.rs b/abi_stable/src/std_types/std_io.rs index 25b34b8b..4573c34d 100644 --- a/abi_stable/src/std_types/std_io.rs +++ b/abi_stable/src/std_types/std_io.rs @@ -1,5 +1,5 @@ /*! -Ffi-safe equivalents of `std::io::{ErrorKind,Error,SeekFrom}`. +Ffi-safe equivalents of `std::io::{ErrorKind, Error, SeekFrom}`. */ use std::{ @@ -32,10 +32,10 @@ pub struct RIoErrorKind { macro_rules! impl_error_kind { ( $( - $variant:ident,discriminant=$value:expr , message=$as_str_msg:expr ; + $variant: ident, discriminant = $value: expr , message = $as_str_msg: expr ; )* ) => ( - /// Every (visible) variant of RIoErrorKind,equivalent to that of `std::io::ErrorKind`. + /// Every (visible) variant of RIoErrorKind, equivalent to that of `std::io::ErrorKind`. #[allow(non_upper_case_globals)] impl RIoErrorKind { $( @@ -63,7 +63,7 @@ macro_rules! impl_error_kind { $( ErrorKind::$variant=> RIoErrorKind::$variant, )* - _=>RIoErrorKind::Other, + _ => RIoErrorKind::Other, } } } @@ -76,7 +76,7 @@ macro_rules! impl_error_kind { $( RIoErrorKind::$variant=> ErrorKind::$variant, )* - _=>ErrorKind::Other, + _ => ErrorKind::Other, } } } @@ -96,23 +96,23 @@ macro_rules! impl_error_kind { } impl_error_kind! { - NotFound, discriminant = 1 , message="entity not found" ; - PermissionDenied, discriminant = 2 , message="permission denied" ; - ConnectionRefused, discriminant = 3 , message="connection refused" ; - ConnectionReset, discriminant = 4 , message="connection reset" ; - ConnectionAborted, discriminant = 5 , message="connection aborted" ; - NotConnected, discriminant = 6 , message="not connected" ; - AddrInUse, discriminant = 7 , message="address in use" ; - AddrNotAvailable, discriminant = 8 , message="address not available" ; - BrokenPipe, discriminant = 9 , message="broken pipe" ; - AlreadyExists, discriminant = 10 , message="entity already exists" ; - WouldBlock, discriminant = 11 , message="operation would block" ; - InvalidInput, discriminant = 12 , message="invalid input parameter" ; - InvalidData, discriminant = 13 , message="invalid data" ; - TimedOut, discriminant = 14 , message="timed out" ; - WriteZero, discriminant = 15 , message="write zero" ; - Interrupted, discriminant = 16 , message="operation interrupted" ; - UnexpectedEof, discriminant = 17 , message="unexpected end of file" ; + NotFound, discriminant = 1 , message = "entity not found" ; + PermissionDenied, discriminant = 2 , message = "permission denied" ; + ConnectionRefused, discriminant = 3 , message = "connection refused" ; + ConnectionReset, discriminant = 4 , message = "connection reset" ; + ConnectionAborted, discriminant = 5 , message = "connection aborted" ; + NotConnected, discriminant = 6 , message = "not connected" ; + AddrInUse, discriminant = 7 , message = "address in use" ; + AddrNotAvailable, discriminant = 8 , message = "address not available" ; + BrokenPipe, discriminant = 9 , message = "broken pipe" ; + AlreadyExists, discriminant = 10 , message = "entity already exists" ; + WouldBlock, discriminant = 11 , message = "operation would block" ; + InvalidInput, discriminant = 12 , message = "invalid input parameter" ; + InvalidData, discriminant = 13 , message = "invalid data" ; + TimedOut, discriminant = 14 , message = "timed out" ; + WriteZero, discriminant = 15 , message = "write zero" ; + Interrupted, discriminant = 16 , message = "operation interrupted" ; + UnexpectedEof, discriminant = 17 , message = "unexpected end of file" ; } /////////////////////////////////////////////////////////////////////////// @@ -133,9 +133,9 @@ impl_from_rust_repr! { impl From for RSeekFrom { fn(this){ match this { - SeekFrom::Start(x) =>RSeekFrom::Start(x), - SeekFrom::End(x) =>RSeekFrom::End(x), - SeekFrom::Current(x)=>RSeekFrom::Current(x), + SeekFrom::Start(x) => RSeekFrom::Start(x), + SeekFrom::End(x) => RSeekFrom::End(x), + SeekFrom::Current(x) => RSeekFrom::Current(x), } } } @@ -145,9 +145,9 @@ impl_into_rust_repr! { impl Into for RSeekFrom { fn(this){ match this { - RSeekFrom::Start(x) =>SeekFrom::Start(x), - RSeekFrom::End(x) =>SeekFrom::End(x), - RSeekFrom::Current(x)=>SeekFrom::Current(x), + RSeekFrom::Start(x) => SeekFrom::Start(x), + RSeekFrom::End(x) => SeekFrom::End(x), + RSeekFrom::Current(x) => SeekFrom::Current(x), } } } @@ -165,7 +165,7 @@ Defining an extern function to write a slice into a writer twice. ``` use abi_stable::{ erased_types::interfaces::IoWriteInterface, - std_types::{RIoError,RResult,ROk}, + std_types::{RIoError, RResult, ROk}, traits::IntoReprC, DynTrait, RMut, sabi_extern_fn, @@ -176,9 +176,9 @@ use std::io::Write; #[sabi_extern_fn] pub fn write_slice_twice( - mut write: DynTrait,IoWriteInterface>, + mut write: DynTrait, IoWriteInterface>, slice: &[u8], -)->RResult<(),RIoError>{ +) -> RResult<(), RIoError>{ rtry!( write.write_all(slice).into_c() ); rtry!( write.write_all(slice).into_c() ); ROk(()) @@ -200,8 +200,8 @@ impl_from_rust_repr! { impl From for RIoError { fn(this){ RIoError{ - kind:this.kind().into(), - error:this.into_inner().map(RBoxError::from_box).into_c() + kind: this.kind().into(), + error: this.into_inner().map(RBoxError::from_box).into_c() } } } @@ -210,10 +210,10 @@ impl_from_rust_repr! { impl_into_rust_repr! { impl Into for RIoError { fn(this){ - let kind=this.kind().into_::(); + let kind = this.kind().into_::(); match this.into_inner() { - Some(e)=>ioError::new(kind,RBoxError::into_box(e)), - None=>ioError::from(kind), + Some(e) => ioError::new(kind, RBoxError::into_box(e)), + None => ioError::from(kind), } } } @@ -243,7 +243,7 @@ impl RIoError { /// use abi_stable::std_types::RIoError; /// use std::io::ErrorKind; /// - /// let err=RIoError::new( ErrorKind::Other, "".parse::().unwrap_err()); + /// let err = RIoError::new( ErrorKind::Other, "".parse::().unwrap_err()); /// ``` pub fn new(kind: ErrorKind, error: E) -> Self where @@ -264,9 +264,9 @@ impl RIoError { /// use abi_stable::std_types::RIoError; /// use std::io::ErrorKind; /// - /// let str_err="Timeout receiving the response from server."; + /// let str_err = "Timeout receiving the response from server."; /// - /// let err=RIoError::new_( ErrorKind::TimedOut, str_err); + /// let err = RIoError::new_( ErrorKind::TimedOut, str_err); /// ``` #[inline] pub fn new_(kind: ErrorKind, error: E) -> Self @@ -284,7 +284,7 @@ impl RIoError { /// use abi_stable::std_types::RIoError; /// use std::io::ErrorKind; /// - /// let err=RIoError::from_kind( ErrorKind::AlreadyExists ); + /// let err = RIoError::from_kind( ErrorKind::AlreadyExists ); /// ``` pub fn from_kind(kind: ErrorKind) -> Self { Self { @@ -302,9 +302,9 @@ impl RIoError { /// use abi_stable::std_types::RIoError; /// use std::io::ErrorKind; /// - /// let str_err="Could not create file \"memes.txt\" because it already exists."; + /// let str_err = "Could not create file \"memes.txt\" because it already exists."; /// - /// let err=RIoError::with_box( ErrorKind::AlreadyExists, str_err.into()); + /// let err = RIoError::with_box( ErrorKind::AlreadyExists, str_err.into()); /// ``` pub fn with_box(kind: ErrorKind, error: Box) -> Self { RIoError { @@ -321,11 +321,11 @@ impl RIoError { /// use abi_stable::std_types::RIoError; /// use std::io::ErrorKind; /// - /// type DynErr=Box; + /// type DynErr = Box; /// - /// let str_err:DynErr="IP address `256.256.256.256` is already in use.".into(); + /// let str_err: DynErr = "IP address `256.256.256.256` is already in use.".into(); /// - /// let err=RIoError::with_rboxerror( ErrorKind::AddrInUse, str_err.into() ); + /// let err = RIoError::with_rboxerror( ErrorKind::AddrInUse, str_err.into() ); /// ``` pub fn with_rboxerror(kind: ErrorKind, error: RBoxError) -> Self { RIoError { @@ -339,10 +339,10 @@ impl RIoError { /// # Example /// /// ``` - /// use abi_stable::std_types::{RIoError,RIoErrorKind}; + /// use abi_stable::std_types::{RIoError, RIoErrorKind}; /// use std::io::ErrorKind; /// - /// let err=RIoError::from_kind( ErrorKind::AlreadyExists ); + /// let err = RIoError::from_kind( ErrorKind::AlreadyExists ); /// /// assert_eq!(err.kind(), RIoErrorKind::AlreadyExists); /// ``` @@ -356,16 +356,16 @@ impl RIoError { /// # Example /// /// ``` - /// use abi_stable::std_types::{RIoError,RIoErrorKind,RBoxError}; + /// use abi_stable::std_types::{RIoError, RIoErrorKind, RBoxError}; /// use std::io::ErrorKind; /// /// { - /// let err=RIoError::from_kind( ErrorKind::AlreadyExists ); + /// let err = RIoError::from_kind( ErrorKind::AlreadyExists ); /// assert_eq!(err.get_ref().map(|_|()), None); /// } /// { - /// let msg="Cannot access directory at \"/home/Steve/memes/\"."; - /// let err=RIoError::new_( ErrorKind::PermissionDenied, msg ); + /// let msg = "Cannot access directory at \"/home/Steve/memes/\"."; + /// let err = RIoError::new_( ErrorKind::PermissionDenied, msg ); /// /// assert!(err.get_ref().is_some()); /// } @@ -381,16 +381,16 @@ impl RIoError { /// # Example /// /// ``` - /// use abi_stable::std_types::{RIoError,RIoErrorKind,RBoxError}; + /// use abi_stable::std_types::{RIoError, RIoErrorKind, RBoxError}; /// use std::io::ErrorKind; /// /// { - /// let mut err=RIoError::from_kind( ErrorKind::AlreadyExists ); + /// let mut err = RIoError::from_kind( ErrorKind::AlreadyExists ); /// assert_eq!(err.get_mut().map(|_|()), None); /// } /// { - /// let mut msg="Cannot access directory at \"/home/Patrick/373.15K takes/\"."; - /// let mut err=RIoError::new_( ErrorKind::PermissionDenied, msg ); + /// let mut msg = "Cannot access directory at \"/home/Patrick/373.15K takes/\"."; + /// let mut err = RIoError::new_( ErrorKind::PermissionDenied, msg ); /// assert!(err.get_mut().is_some()); /// } /// @@ -409,12 +409,12 @@ impl RIoError { /// use std::io::ErrorKind; /// /// { - /// let err=RIoError::from_kind( ErrorKind::AlreadyExists ); + /// let err = RIoError::from_kind( ErrorKind::AlreadyExists ); /// assert_eq!(err.into_inner().map(|_|()), None); /// } /// { - /// let mut msg="Cannot access directory at \"/home/wo_boat/blog/\"."; - /// let err=RIoError::new_( ErrorKind::PermissionDenied, msg ); + /// let mut msg = "Cannot access directory at \"/home/wo_boat/blog/\"."; + /// let err = RIoError::new_( ErrorKind::PermissionDenied, msg ); /// assert!(err.into_inner().is_some()); /// } /// diff --git a/abi_stable/src/std_types/str.rs b/abi_stable/src/std_types/str.rs index 6922f168..04f160c6 100644 --- a/abi_stable/src/std_types/str.rs +++ b/abi_stable/src/std_types/str.rs @@ -31,10 +31,10 @@ use abi_stable::{ #[sabi_extern_fn] -fn first_word(phrase:RStr<'_>)->RStr<'_>{ +fn first_word(phrase: RStr<'_>) -> RStr<'_>{ match phrase.as_str().split_whitespace().next() { - Some(x)=>x.into(), - None=>"".into() + Some(x) => x.into(), + None => "".into() } } @@ -62,9 +62,9 @@ impl<'a> RStr<'a> { /// ``` /// use abi_stable::std_types::RStr; /// - /// const STR:RStr<'static>=RStr::empty(); + /// const STR: RStr<'static> = RStr::empty(); /// - /// assert_eq!(STR,RStr::from("")); + /// assert_eq!(STR, RStr::from("")); /// /// ``` #[inline] @@ -81,7 +81,7 @@ impl<'a> RStr<'a> { /// /// - `ptr_` points to valid memory, /// - /// - `ptr_ .. ptr+len` range is accessible memory,and is valid utf-8. + /// - `ptr_ .. ptr+len` range is accessible memory, and is valid utf-8. /// /// - The data that `ptr_` points to must be valid for the lifetime of this `RStr<'a>` /// @@ -93,7 +93,7 @@ impl<'a> RStr<'a> { /// ``` /// use abi_stable::std_types::RStr; /// - /// fn convert(slice_:&str)->RStr<'_>{ + /// fn convert(slice_: &str) -> RStr<'_>{ /// unsafe{ /// RStr::from_raw_parts( slice_.as_ptr(), slice_.len() ) /// } @@ -133,12 +133,12 @@ impl<'a> RStr<'a> { /// ``` /// use abi_stable::std_types::RStr; /// - /// let str=RStr::from("What is that."); + /// let str = RStr::from("What is that."); /// - /// assert_eq!(str.slice(..),str); - /// assert_eq!(str.slice(..4),RStr::from("What")); - /// assert_eq!(str.slice(4..),RStr::from(" is that.")); - /// assert_eq!(str.slice(4..7),RStr::from(" is")); + /// assert_eq!(str.slice(..), str); + /// assert_eq!(str.slice(..4), RStr::from("What")); + /// assert_eq!(str.slice(4..), RStr::from(" is that.")); + /// assert_eq!(str.slice(4..7), RStr::from(" is")); /// /// ``` pub fn slice(&self, i: I) -> RStr<'a> @@ -153,12 +153,12 @@ impl<'a> RStr<'a> { /// # Example /// /// ``` - /// use abi_stable::std_types::{RSlice,RStr}; + /// use abi_stable::std_types::{RSlice, RStr}; /// - /// let str=RStr::from("What is that."); - /// let bytes=RSlice::from("What is that.".as_bytes()); + /// let str = RStr::from("What is that."); + /// let bytes = RSlice::from("What is that.".as_bytes()); /// - /// assert_eq!(str.as_rslice(),bytes); + /// assert_eq!(str.as_rslice(), bytes); /// /// ``` #[inline] @@ -173,8 +173,8 @@ impl<'a> RStr<'a> { /// ``` /// use abi_stable::std_types::RStr; /// - /// let str="What is that."; - /// assert_eq!(RStr::from(str).as_str(),str); + /// let str = "What is that."; + /// assert_eq!(RStr::from(str).as_str(), str); /// /// ``` #[inline] @@ -194,9 +194,9 @@ impl<'a> RStr<'a> { /// ``` /// use abi_stable::std_types::RStr; /// - /// assert_eq!(RStr::from("").len(),0); - /// assert_eq!(RStr::from("a").len(),1); - /// assert_eq!(RStr::from("What").len(),4); + /// assert_eq!(RStr::from("").len(), 0); + /// assert_eq!(RStr::from("a").len(), 1); + /// assert_eq!(RStr::from("What").len(), 4); /// /// ``` #[inline] @@ -211,9 +211,9 @@ impl<'a> RStr<'a> { /// ``` /// use abi_stable::std_types::RStr; /// - /// assert_eq!(RStr::from("").is_empty(),true); - /// assert_eq!(RStr::from("a").is_empty(),false); - /// assert_eq!(RStr::from("What").is_empty(),false); + /// assert_eq!(RStr::from("").is_empty(), true); + /// assert_eq!(RStr::from("a").is_empty(), false); + /// assert_eq!(RStr::from("What").is_empty(), false); /// /// ``` pub const fn is_empty(&self) -> bool { @@ -339,9 +339,9 @@ impl<'a> Serialize for RStr<'a> { type Str<'a> = &'a str; shared_impls! { - mod=slice_impls - new_type=RStr['a][], - original_type=Str, + mod = slice_impls + new_type = RStr['a][], + original_type = Str, } //////////////////////////////////////////////////// diff --git a/abi_stable/src/std_types/string.rs b/abi_stable/src/std_types/string.rs index a7979c35..afd8f585 100644 --- a/abi_stable/src/std_types/string.rs +++ b/abi_stable/src/std_types/string.rs @@ -43,10 +43,10 @@ use abi_stable::{ #[sabi_extern_fn] -fn first_word(phrase:RString)->RString{ +fn first_word(phrase: RString) -> RString{ match phrase.split_whitespace().next_back() { - Some(x)=>x.into(), - None=>RString::new(), + Some(x) => x.into(), + None => RString::new(), } } @@ -366,7 +366,7 @@ impl RString { /// let mut str = RString::new(); /// /// str.reserve(10); - /// assert!(str.capacity()>=10); + /// assert!(str.capacity() >= 10); /// /// ``` pub fn reserve(&mut self, additional: usize) { @@ -964,7 +964,7 @@ impl FromUtf8Error { /// ``` /// use abi_stable::std_types::{RString, RVec}; /// - /// let bytes:RVec= vec![72, 111, 95, 95, 95, 95, 95, 99, 107, 255].into(); + /// let bytes: RVec = vec![72, 111, 95, 95, 95, 95, 95, 99, 107, 255].into(); /// /// let err = RString::from_utf8(bytes.clone()).unwrap_err(); /// diff --git a/abi_stable/src/std_types/string/iters.rs b/abi_stable/src/std_types/string/iters.rs index aebcc1d0..831a2e23 100644 --- a/abi_stable/src/std_types/string/iters.rs +++ b/abi_stable/src/std_types/string/iters.rs @@ -21,15 +21,15 @@ impl IntoIter { /// ``` /// use abi_stable::std_types::RString; /// - /// let mut iter=RString::from("abcd").into_iter(); + /// let mut iter = RString::from("abcd").into_iter(); /// - /// assert_eq!(iter.as_str(),"abcd"); + /// assert_eq!(iter.as_str(), "abcd"); /// - /// assert_eq!(iter.next(),Some('a')); - /// assert_eq!(iter.as_str(),"bcd"); + /// assert_eq!(iter.next(), Some('a')); + /// assert_eq!(iter.as_str(), "bcd"); /// - /// assert_eq!(iter.next_back(),Some('d')); - /// assert_eq!(iter.as_str(),"bc"); + /// assert_eq!(iter.next_back(), Some('d')); + /// assert_eq!(iter.as_str(), "bc"); /// /// ``` pub fn as_str(&self) -> &str { @@ -87,20 +87,20 @@ impl<'a> Drain<'a> { /// ``` /// use abi_stable::std_types::RString; /// - /// let mut string=RString::from("abcdefg"); - /// let mut iter=string.drain(2..6); + /// let mut string = RString::from("abcdefg"); + /// let mut iter = string.drain(2..6); /// - /// assert_eq!(iter.as_str(),"cdef"); + /// assert_eq!(iter.as_str(), "cdef"); /// - /// assert_eq!(iter.next(),Some('c')); - /// assert_eq!(iter.as_str(),"def"); + /// assert_eq!(iter.next(), Some('c')); + /// assert_eq!(iter.as_str(), "def"); /// - /// assert_eq!(iter.next_back(),Some('f')); - /// assert_eq!(iter.as_str(),"de"); + /// assert_eq!(iter.next_back(), Some('f')); + /// assert_eq!(iter.as_str(), "de"); /// /// drop(iter); /// - /// assert_eq!(string.as_str(),"abg") + /// assert_eq!(string.as_str(), "abg") /// /// ``` pub fn as_str(&self) -> &str { diff --git a/abi_stable/src/std_types/string/tests.rs b/abi_stable/src/std_types/string/tests.rs index 31d6cdb5..27786278 100644 --- a/abi_stable/src/std_types/string/tests.rs +++ b/abi_stable/src/std_types/string/tests.rs @@ -11,7 +11,7 @@ static TEST_STR: &str = "hello_world.cáscara.ñ.🎊🍕👏😊😀😄😉 #[test] fn from_to_string() { - let orig = "hello,world!"; + let orig = "hello, world!"; let orig_owned = orig.to_string(); let orig_cap = orig_owned.capacity(); diff --git a/abi_stable/src/std_types/tuple.rs b/abi_stable/src/std_types/tuple.rs index dfc3c225..0dbde415 100644 --- a/abi_stable/src/std_types/tuple.rs +++ b/abi_stable/src/std_types/tuple.rs @@ -6,11 +6,11 @@ Contains ffi-safe equivalents of tuples up to 4 elements. macro_rules! declare_tuple { ( - struct_attrs[ $(#[$meta:meta])* ] + struct_attrs[ $(#[$meta: meta])* ] - into_tuple_attrs[ $(#[$into_tuple_attrs:meta])* ] + into_tuple_attrs[ $(#[$into_tuple_attrs: meta])* ] - $tconstr:ident[$( $tparam:ident ),* $(,)? ] + $tconstr: ident[$( $tparam: ident ),* $(,)? ] ) => ( $(#[$meta])* #[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash, StableAbi)] diff --git a/abi_stable/src/std_types/utypeid.rs b/abi_stable/src/std_types/utypeid.rs index 41b7ec60..fee1a593 100644 --- a/abi_stable/src/std_types/utypeid.rs +++ b/abi_stable/src/std_types/utypeid.rs @@ -23,9 +23,9 @@ use crate::{sabi_types::MaybeCmp, EXECUTABLE_IDENTITY}; /// use abi_stable::std_types::utypeid::new_utypeid; /// use std::collections::HashMap; /// -/// let hashmap_id=new_utypeid::< HashMap >(); -/// let vec_id=new_utypeid::< Vec >(); -/// let u32_id=new_utypeid::< u32 >(); +/// let hashmap_id = new_utypeid::< HashMap >(); +/// let vec_id = new_utypeid::< Vec >(); +/// let u32_id = new_utypeid::< u32 >(); /// /// assert_eq!( hashmap_id, hashmap_id ); /// assert_eq!( vec_id, vec_id ); @@ -94,7 +94,7 @@ impl UTypeId { /// use abi_stable::std_types::UTypeId; /// use std::collections::HashMap; /// - /// let id=UTypeId::new::< HashMap >(); + /// let id = UTypeId::new::< HashMap >(); /// # drop(id); /// ``` #[inline(always)] diff --git a/abi_stable/src/std_types/vec.rs b/abi_stable/src/std_types/vec.rs index 4c51f4ce..2d15f585 100644 --- a/abi_stable/src/std_types/vec.rs +++ b/abi_stable/src/std_types/vec.rs @@ -62,7 +62,7 @@ mod private { } #[sabi_extern_fn] - pub fn partition_evenness(numbers: RSlice<'_, u32>)->Partitioned{ + pub fn partition_evenness(numbers: RSlice<'_, u32>) -> Partitioned{ let (even, odd) = numbers.iter().cloned().partition(|n| *n % 2 == 0); Partitioned{even, odd} @@ -491,7 +491,7 @@ impl RVec { /// /// let mut list = RVec::::new(); /// - /// list.extend( (4..=7).rev() ); + /// list.extend( (4 ..= 7).rev() ); /// /// assert_eq!(list.to_vec(), vec![7, 6, 5, 4] ); /// @@ -619,7 +619,7 @@ impl RVec { /// }; /// /// // This type annotation is purely for the reader. - /// let mut list: RVec>= + /// let mut list: RVec> = /// vec!["foo".into_c(), "bar".into(), "baz".into()].into_c(); /// /// assert_eq!( list.remove(2), "baz".into_c() ); @@ -650,7 +650,7 @@ impl RVec { /// }; /// /// // This type annotation is purely for the reader. - /// let mut list: RVec>= + /// let mut list: RVec> = /// vec!["foo".into_c(), "bar".into(), "baz".into(), "geo".into()].into_c(); /// /// assert_eq!( list.swap_remove(1), "bar".into_c() ); @@ -790,12 +790,12 @@ impl RVec { /// use abi_stable::std_types::RVec; /// /// { - /// let mut list = (0..=10).collect::>(); + /// let mut list = (0 ..= 10).collect::>(); /// list.retain(|x| *x%3 == 0 ); /// assert_eq!(list.as_slice(), &[0, 3, 6, 9]); /// } /// { - /// let mut list = (0..=10).collect::>(); + /// let mut list = (0 ..= 10).collect::>(); /// list.retain(|x| *x%5 == 0 ); /// assert_eq!(list.as_slice(), &[0, 5, 10]); /// } diff --git a/abi_stable/src/std_types/vec/iters.rs b/abi_stable/src/std_types/vec/iters.rs index bbde9b17..4e7a76e8 100644 --- a/abi_stable/src/std_types/vec/iters.rs +++ b/abi_stable/src/std_types/vec/iters.rs @@ -106,15 +106,15 @@ impl IntoIter { /// ``` /// use abi_stable::std_types::RVec; /// - /// let mut iter=RVec::from(vec![0,1,2,3]).into_iter(); + /// let mut iter = RVec::from(vec![0, 1, 2, 3]).into_iter(); /// - /// assert_eq!( iter.as_slice(), &[0,1,2,3] ); + /// assert_eq!( iter.as_slice(), &[0, 1, 2, 3] ); /// /// assert_eq!( iter.next(), Some(0) ); - /// assert_eq!( iter.as_slice(), &[1,2,3] ); + /// assert_eq!( iter.as_slice(), &[1, 2, 3] ); /// /// assert_eq!( iter.next_back(), Some(3) ); - /// assert_eq!( iter.as_slice(), &[1,2] ); + /// assert_eq!( iter.as_slice(), &[1, 2] ); /// /// ``` pub fn as_slice(&self) -> &[T] { @@ -128,15 +128,15 @@ impl IntoIter { /// ``` /// use abi_stable::std_types::RVec; /// - /// let mut iter=RVec::from(vec![0,1,2,3]).into_iter(); + /// let mut iter = RVec::from(vec![0, 1, 2, 3]).into_iter(); /// - /// assert_eq!( iter.as_mut_slice(), &mut [0,1,2,3] ); + /// assert_eq!( iter.as_mut_slice(), &mut [0, 1, 2, 3] ); /// /// assert_eq!( iter.next(), Some(0) ); - /// assert_eq!( iter.as_mut_slice(), &mut [1,2,3] ); + /// assert_eq!( iter.as_mut_slice(), &mut [1, 2, 3] ); /// /// assert_eq!( iter.next_back(), Some(3) ); - /// assert_eq!( iter.as_mut_slice(), &mut [1,2] ); + /// assert_eq!( iter.as_mut_slice(), &mut [1, 2] ); /// /// ``` pub fn as_mut_slice(&mut self) -> &mut [T] { @@ -191,20 +191,20 @@ impl<'a, T> Drain<'a, T> { /// ``` /// use abi_stable::std_types::RVec; /// - /// let mut list=(0..8).collect::>(); - /// let mut iter=list.drain(3..7); + /// let mut list = (0..8).collect::>(); + /// let mut iter = list.drain(3..7); /// - /// assert_eq!( iter.as_slice(), &[3,4,5,6] ); + /// assert_eq!( iter.as_slice(), &[3, 4, 5, 6] ); /// /// assert_eq!( iter.next(), Some(3) ); - /// assert_eq!( iter.as_slice(), &[4,5,6] ); + /// assert_eq!( iter.as_slice(), &[4, 5, 6] ); /// /// assert_eq!( iter.next(), Some(4) ); - /// assert_eq!( iter.as_slice(), &[5,6] ); + /// assert_eq!( iter.as_slice(), &[5, 6] ); /// /// drop(iter); /// - /// assert_eq!(list.as_slice(),&[0,1,2,7]); + /// assert_eq!(list.as_slice(), &[0, 1, 2, 7]); /// /// ``` pub fn as_slice(&self) -> &[T] { @@ -218,20 +218,20 @@ impl<'a, T> Drain<'a, T> { /// ``` /// use abi_stable::std_types::RVec; /// - /// let mut list=(0..8).collect::>(); - /// let mut iter=list.drain(3..7); + /// let mut list = (0..8).collect::>(); + /// let mut iter = list.drain(3..7); /// - /// assert_eq!( iter.as_mut_slice(), &mut [3,4,5,6] ); + /// assert_eq!( iter.as_mut_slice(), &mut [3, 4, 5, 6] ); /// /// assert_eq!( iter.next(), Some(3) ); - /// assert_eq!( iter.as_mut_slice(), &mut [4,5,6] ); + /// assert_eq!( iter.as_mut_slice(), &mut [4, 5, 6] ); /// /// assert_eq!( iter.next(), Some(4) ); - /// assert_eq!( iter.as_mut_slice(), &mut [5,6] ); + /// assert_eq!( iter.as_mut_slice(), &mut [5, 6] ); /// /// drop(iter); /// - /// assert_eq!(list.as_slice(),&[0,1,2,7]); + /// assert_eq!(list.as_slice(), &[0, 1, 2, 7]); /// /// ``` pub fn as_mut_slice(&mut self) -> &mut [T] { diff --git a/abi_stable/src/std_types/vec/tests.rs b/abi_stable/src/std_types/vec/tests.rs index 1e557650..427a201b 100644 --- a/abi_stable/src/std_types/vec/tests.rs +++ b/abi_stable/src/std_types/vec/tests.rs @@ -23,7 +23,7 @@ fn vec_drain() { let pointer = Arc::new(()); macro_rules! assert_eq_drain { - ($range:expr,$after_drain:expr) => { + ($range: expr, $after_drain: expr) => { let range = $range; { let after_drain: Vec = $after_drain; @@ -65,7 +65,7 @@ fn insert_remove() { assert_eq!(&*list, &*original); }; - //vec![b'a',b'b',b'c',b'd',b'e',b'f',b'g',b'h',b'i',b'j'] + //vec![b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h', b'i', b'j'] assert_insert_remove(0, vec![b'b', b'c', b'd']); assert_insert_remove(1, vec![b'a', b'c', b'd']); @@ -370,8 +370,8 @@ fn into_vec() { let list = list.clone().set_vtable_for_testing(); let list_ptr = list.as_ptr() as usize; let list_1 = list.into_vec(); - // No,MIR interpreter, - // I'm not dereferencing a pointer here,I am comparing their adresses. + // No, MIR interpreter, + // I'm not dereferencing a pointer here, I am comparing their adresses. assert_ne!(list_ptr, list_1.as_ptr() as usize); assert_eq!(orig, list_1); } From 5f7c37dba43464df632ab415ec316d3a604a2a5b Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Wed, 27 Oct 2021 00:04:25 -0300 Subject: [PATCH 15/32] Formatted sabi_types and sabi_trait doc examples --- abi_stable/src/sabi_trait/examples.rs | 115 +++---- abi_stable/src/sabi_trait/robject.rs | 276 +++++++-------- abi_stable/src/sabi_types/constructor.rs | 106 +++--- abi_stable/src/sabi_types/ignored_wrapper.rs | 101 +++--- abi_stable/src/sabi_types/late_static_ref.rs | 231 ++++++------- abi_stable/src/sabi_types/maybe_cmp.rs | 34 +- abi_stable/src/sabi_types/move_ptr.rs | 251 ++++++-------- abi_stable/src/sabi_types/nul_str.rs | 16 +- abi_stable/src/sabi_types/rmut.rs | 42 ++- abi_stable/src/sabi_types/rref.rs | 50 ++- abi_stable/src/sabi_types/rsmallbox.rs | 343 +++++++++---------- abi_stable/src/sabi_types/static_ref.rs | 233 ++++++------- abi_stable/src/sabi_types/version.rs | 184 +++++++--- 13 files changed, 936 insertions(+), 1046 deletions(-) diff --git a/abi_stable/src/sabi_trait/examples.rs b/abi_stable/src/sabi_trait/examples.rs index 3d061e9d..9220ad54 100644 --- a/abi_stable/src/sabi_trait/examples.rs +++ b/abi_stable/src/sabi_trait/examples.rs @@ -10,66 +10,61 @@ use crate::{ ////////////////////////////////////// -/** - -``` -use abi_stable::{ - sabi_trait::{prelude::*,examples::*}, - std_types::*, -}; - -let _=RSomething_TO::<_,(),u32>::from_value(RBox::new(10_u32),TD_Opaque); - -``` - -While RSomething_TO can be constructed from an RArc, -no method on the trait can be called because RSomething has mutable and by value methods. - -```compile_fail -use abi_stable::{ - sabi_trait::{prelude::*,examples::*}, - std_types::*, -}; - - -let what=RSomething_TO::from_ptr(RArc::new(100u32),TD_Opaque); -RSomething::into_value(what); - -``` - - -Cannot create RSomething from a !Sync type. -```compile_fail -use abi_stable::{ - marker_type::*, - sabi_trait::{prelude::*,examples::*}, - std_types::*, -}; - -use std::marker::PhantomData; - -let ptr=RBox::new(PhantomData::); -let _=RSomething_TO::<_,(),PhantomData::>::from_value(ptr,TD_Opaque); - -``` - -Cannot create RSomething from a !Send type. -```compile_fail -use abi_stable::{ - marker_type::*, - sabi_trait::{prelude::*,examples::*}, - std_types::*, -}; - -use std::marker::PhantomData; - -let ptr=RBox::new(PhantomData::); -let _=RSomething_TO::<_,(),PhantomData>::from_value(ptr,TD_Opaque); - -``` - - -*/ +/// ``` +/// use abi_stable::{ +/// sabi_trait::{examples::*, prelude::*}, +/// std_types::*, +/// }; +/// +/// let _ = RSomething_TO::<_, (), u32>::from_value(RBox::new(10_u32), TD_Opaque); +/// +/// ``` +/// +/// While RSomething_TO can be constructed from an RArc, +/// no method on the trait can be called because RSomething has mutable and by value methods. +/// +/// ```compile_fail +/// use abi_stable::{ +/// sabi_trait::{examples::*, prelude::*}, +/// std_types::*, +/// }; +/// +/// let what = RSomething_TO::from_ptr(RArc::new(100u32), TD_Opaque); +/// RSomething::into_value(what); +/// +/// ``` +/// +/// +/// Cannot create RSomething from a !Sync type. +/// ```compile_fail +/// use abi_stable::{ +/// marker_type::*, +/// sabi_trait::{examples::*, prelude::*}, +/// std_types::*, +/// }; +/// +/// use std::marker::PhantomData; +/// +/// let ptr = RBox::new(PhantomData::); +/// let _ = RSomething_TO::<_, (), PhantomData>::from_value(ptr, TD_Opaque); +/// +/// ``` +/// +/// Cannot create RSomething from a !Send type. +/// ```compile_fail +/// use abi_stable::{ +/// marker_type::*, +/// sabi_trait::{examples::*, prelude::*}, +/// std_types::*, +/// }; +/// +/// use std::marker::PhantomData; +/// +/// let ptr = RBox::new(PhantomData::); +/// let _ = RSomething_TO::<_, (), PhantomData>::from_value(ptr, TD_Opaque); +/// +/// ``` +/// #[sabi_trait] // #[sabi(debug_print_trait)] pub trait RSomething: Send + Sync + Clone + Debug { diff --git a/abi_stable/src/sabi_trait/robject.rs b/abi_stable/src/sabi_trait/robject.rs index aae4533f..77df2c6a 100644 --- a/abi_stable/src/sabi_trait/robject.rs +++ b/abi_stable/src/sabi_trait/robject.rs @@ -127,45 +127,37 @@ where } } -/** -Clone is implemented for references and smart pointers, -using `GetPointerKind` to decide whether `P` is a smart pointer or a reference. - -RObject does not implement Clone if P==`&mut ()` : - - -```compile_fail -use abi_stable::{ - sabi_trait::{ - doc_examples::ConstExample_TO, - TD_Opaque, - }, - std_types::*, -}; - -let mut object=ConstExample_TO::from_value(10usize, TD_Opaque); -let borrow=object.sabi_reborrow_mut(); -let _=borrow.clone(); -``` - -Here is the same example with `sabi_reborrow` - -``` -use abi_stable::{ - sabi_trait::{ - doc_examples::ConstExample_TO, - TD_Opaque, - }, - std_types::*, -}; - -let mut object=ConstExample_TO::from_value(10usize, TD_Opaque); -let borrow=object.sabi_reborrow(); -let _=borrow.clone(); -``` - - -*/ +/// Clone is implemented for references and smart pointers, +/// using `GetPointerKind` to decide whether `P` is a smart pointer or a reference. +/// +/// RObject does not implement Clone if `P` == `&mut ()` : +/// +/// +/// ```compile_fail +/// use abi_stable::{ +/// sabi_trait::{doc_examples::ConstExample_TO, TD_Opaque}, +/// std_types::*, +/// }; +/// +/// let mut object = ConstExample_TO::from_value(10usize, TD_Opaque); +/// let borrow = object.sabi_reborrow_mut(); +/// let _ = borrow.clone(); +/// ``` +/// +/// Here is the same example with `sabi_reborrow` +/// +/// ``` +/// use abi_stable::{ +/// sabi_trait::{doc_examples::ConstExample_TO, TD_Opaque}, +/// std_types::*, +/// }; +/// +/// let mut object = ConstExample_TO::from_value(10usize, TD_Opaque); +/// let borrow = object.sabi_reborrow(); +/// let _ = borrow.clone(); +/// ``` +/// +/// impl<'lt, P, I, V> Clone for RObject<'lt, P, I, V> where P: AsPtr, @@ -238,28 +230,25 @@ impl<'lt, P, I, V> RObject<'lt, P, I, V> where P: AsPtr, { - /** - - Constructs an RObject from a pointer and an extra vtable. - - This is mostly intended to be called by `#[sabi_trait]` generated trait objects. - - # Safety - - These are the requirements for the caller: - - - `P` must be a pointer to the type that the vtable functions - take as the first parameter. - - - The vtable must not come from a reborrowed `RObject` - (created using `RObject::reborrow` or `RObject::reborrow_mut`). - - - The vtable must be the `SomeVTableName` of a struct declared with - `#[derive(StableAbi)] #[sabi(kind(Prefix(prefix_ref="SomeVTableName")))]`. - - - The vtable must have `RObjectVtable_Ref` as its first declared field - - */ + /// Constructs an RObject from a pointer and an extra vtable. + /// + /// This is mostly intended to be called by `#[sabi_trait]` generated trait objects. + /// + /// # Safety + /// + /// These are the requirements for the caller: + /// + /// - `P` must be a pointer to the type that the vtable functions + /// take as the first parameter. + /// + /// - The vtable must not come from a reborrowed `RObject` + /// (created using `RObject::reborrow` or `RObject::reborrow_mut`). + /// + /// - The vtable must be the `SomeVTableName` of a struct declared with + /// `#[derive(StableAbi)] #[sabi(kind(Prefix(prefix_ref="SomeVTableName")))]`. + /// + /// - The vtable must have `RObjectVtable_Ref` as its first declared field + /// pub unsafe fn with_vtable(ptr: OrigPtr, vtable: PrefixRef) -> RObject<'lt, P, I, V> where OrigPtr: CanTransmuteElement<(), TransmutedPtr = P>, @@ -275,38 +264,29 @@ where } impl<'borr, 'a, I, V> RObject<'borr, RRef<'a, ()>, I, V> { - /** - This function allows constructing an RObject in a constant/static. - - This is mostly intended for `#[sabi_trait] generated trait objects` - - # Safety - - This has the same safety requirements as `RObject::with_vtable` - - # Example - - Because this is intended for `#[sabi_trait]` generated trait objects, - this demonstrates how to construct one in a constant. - - ``` - use abi_stable::sabi_trait::{ - doc_examples::{ConstExample_CTO, ConstExample_MV}, - prelude::TD_Opaque, - }; - - const EXAMPLE0:ConstExample_CTO<'static,'static>= - ConstExample_CTO::from_const( - &0usize, - TD_Opaque, - ConstExample_MV::VTABLE, - ); - - - ``` - - - */ + /// This function allows constructing an RObject in a constant/static. + /// + /// This is mostly intended for `#[sabi_trait] generated trait objects` + /// + /// # Safety + /// + /// This has the same safety requirements as `RObject::with_vtable` + /// + /// # Example + /// + /// Because this is intended for `#[sabi_trait]` generated trait objects, + /// this demonstrates how to construct one in a constant. + /// + /// ``` + /// use abi_stable::sabi_trait::{ + /// doc_examples::{ConstExample_CTO, ConstExample_MV}, + /// prelude::TD_Opaque, + /// }; + /// + /// const EXAMPLE0: ConstExample_CTO<'static, 'static> = + /// ConstExample_CTO::from_const(&0usize, TD_Opaque, ConstExample_MV::VTABLE); + /// + /// ``` pub const unsafe fn with_vtable_const( ptr: &'a T, vtable: VTableTO_RO, Downcasting, V>, @@ -367,15 +347,17 @@ where /// /// ```rust /// use abi_stable::{ - /// sabi_trait::doc_examples::Doer_TO, - /// std_types::RBox, + /// sabi_trait::doc_examples::Doer_TO, std_types::RBox, /// type_level::downcasting::TD_CanDowncast, /// }; /// - /// let to = ||Doer_TO::from_value(5usize, TD_CanDowncast); + /// let to = || Doer_TO::from_value(5usize, TD_CanDowncast); /// /// // `to.obj` is an RObject - /// assert_eq!(to().obj.downcast_into::().ok(), Some(RBox::new(5usize))); + /// assert_eq!( + /// to().obj.downcast_into::().ok(), + /// Some(RBox::new(5usize)) + /// ); /// assert_eq!(to().obj.downcast_into::().ok(), None); /// /// ``` @@ -410,16 +392,14 @@ where /// /// ```rust /// use abi_stable::{ - /// sabi_trait::doc_examples::Doer_TO, - /// std_types::RArc, - /// type_level::downcasting::TD_CanDowncast, - /// RRef, RMut, + /// sabi_trait::doc_examples::Doer_TO, std_types::RArc, + /// type_level::downcasting::TD_CanDowncast, RMut, RRef, /// }; /// /// { /// let to: Doer_TO<'_, RArc<()>> = /// Doer_TO::from_ptr(RArc::new(8usize), TD_CanDowncast); - /// + /// /// // `to.obj` is an RObject /// assert_eq!(to.obj.downcast_as::().ok(), Some(&8usize)); /// assert_eq!(to.obj.downcast_as::().ok(), None); @@ -428,9 +408,8 @@ where /// // `#[sabi_trait]` trait objects constructed from `&` /// // use `RRef<'_, ()>` instead of `&'_ ()` /// // since `&T` can't soundly be transmuted back and forth into `&()` - /// let to: Doer_TO<'_, RRef<'_, ()>> = - /// Doer_TO::from_ptr(&13usize, TD_CanDowncast); - /// + /// let to: Doer_TO<'_, RRef<'_, ()>> = Doer_TO::from_ptr(&13usize, TD_CanDowncast); + /// /// assert_eq!(to.obj.downcast_as::().ok(), Some(&13usize)); /// assert_eq!(to.obj.downcast_as::().ok(), None); /// } @@ -439,9 +418,8 @@ where /// // `#[sabi_trait]` trait objects constructed from `&mut` /// // use `RMut<'_, ()>` instead of `&'_ mut ()` /// // since `&mut T` can't soundly be transmuted back and forth into `&mut ()` - /// let to: Doer_TO<'_, RMut<'_, ()>> = - /// Doer_TO::from_ptr(mmut, TD_CanDowncast); - /// + /// let to: Doer_TO<'_, RMut<'_, ()>> = Doer_TO::from_ptr(mmut, TD_CanDowncast); + /// /// assert_eq!(to.obj.downcast_as::().ok(), Some(&21usize)); /// assert_eq!(to.obj.downcast_as::().ok(), None); /// } @@ -476,16 +454,14 @@ where /// /// ```rust /// use abi_stable::{ - /// sabi_trait::doc_examples::Doer_TO, - /// std_types::RBox, - /// type_level::downcasting::TD_CanDowncast, - /// RRef, RMut, + /// sabi_trait::doc_examples::Doer_TO, std_types::RBox, + /// type_level::downcasting::TD_CanDowncast, RMut, RRef, /// }; /// /// { /// let mut to: Doer_TO<'_, RBox<()>> = /// Doer_TO::from_value(34usize, TD_CanDowncast); - /// + /// /// // `to.obj` is an RObject /// assert_eq!(to.obj.downcast_as_mut::().ok(), Some(&mut 34usize)); /// assert_eq!(to.obj.downcast_as_mut::().ok(), None); @@ -495,9 +471,8 @@ where /// // `#[sabi_trait]` trait objects constructed from `&mut` /// // use `RMut<'_, ()>` instead of `&'_ mut ()` /// // since `&mut T` can't soundly be transmuted back and forth into `&mut ()` - /// let mut to: Doer_TO<'_, RMut<'_, ()>> = - /// Doer_TO::from_ptr(mmut, TD_CanDowncast); - /// + /// let mut to: Doer_TO<'_, RMut<'_, ()>> = Doer_TO::from_ptr(mmut, TD_CanDowncast); + /// /// assert_eq!(to.obj.downcast_as_mut::().ok(), Some(&mut 55usize)); /// assert_eq!(to.obj.downcast_as_mut::().ok(), None); /// } @@ -524,16 +499,18 @@ where /// /// ```rust /// use abi_stable::{ - /// sabi_trait::doc_examples::Doer_TO, - /// std_types::RBox, + /// sabi_trait::doc_examples::Doer_TO, std_types::RBox, /// type_level::downcasting::TD_Opaque, /// }; /// - /// let to = ||Doer_TO::from_value(5usize, TD_Opaque); + /// let to = || Doer_TO::from_value(5usize, TD_Opaque); /// - /// unsafe{ + /// unsafe { /// // `to.obj` is an RObject - /// assert_eq!(to().obj.unchecked_downcast_into::(), RBox::new(5usize)); + /// assert_eq!( + /// to().obj.unchecked_downcast_into::(), + /// RBox::new(5usize) + /// ); /// } /// ``` #[inline] @@ -557,16 +534,13 @@ where /// /// ```rust /// use abi_stable::{ - /// sabi_trait::doc_examples::Doer_TO, - /// std_types::RArc, - /// type_level::downcasting::TD_Opaque, - /// RRef, RMut, + /// sabi_trait::doc_examples::Doer_TO, std_types::RArc, + /// type_level::downcasting::TD_Opaque, RMut, RRef, /// }; /// /// { - /// let to: Doer_TO<'_, RArc<()>> = - /// Doer_TO::from_ptr(RArc::new(8usize), TD_Opaque); - /// + /// let to: Doer_TO<'_, RArc<()>> = Doer_TO::from_ptr(RArc::new(8usize), TD_Opaque); + /// /// unsafe { /// // `to.obj` is an RObject /// assert_eq!(to.obj.unchecked_downcast_as::(), &8usize); @@ -576,9 +550,8 @@ where /// // `#[sabi_trait]` trait objects constructed from `&` /// // use `RRef<'_, ()>` instead of `&'_ ()` /// // since `&T` can't soundly be transmuted back and forth into `&()` - /// let to: Doer_TO<'_, RRef<'_, ()>> = - /// Doer_TO::from_ptr(&13usize, TD_Opaque); - /// + /// let to: Doer_TO<'_, RRef<'_, ()>> = Doer_TO::from_ptr(&13usize, TD_Opaque); + /// /// unsafe { /// assert_eq!(to.obj.unchecked_downcast_as::(), &13usize); /// } @@ -588,9 +561,8 @@ where /// // `#[sabi_trait]` trait objects constructed from `&mut` /// // use `RMut<'_, ()>` instead of `&'_ mut ()` /// // since `&mut T` can't soundly be transmuted back and forth into `&mut ()` - /// let to: Doer_TO<'_, RMut<'_, ()>> = - /// Doer_TO::from_ptr(mmut, TD_Opaque); - /// + /// let to: Doer_TO<'_, RMut<'_, ()>> = Doer_TO::from_ptr(mmut, TD_Opaque); + /// /// unsafe { /// assert_eq!(to.obj.unchecked_downcast_as::(), &21usize); /// } @@ -617,16 +589,13 @@ where /// /// ```rust /// use abi_stable::{ - /// sabi_trait::doc_examples::Doer_TO, - /// std_types::RBox, - /// type_level::downcasting::TD_Opaque, - /// RRef, RMut, + /// sabi_trait::doc_examples::Doer_TO, std_types::RBox, + /// type_level::downcasting::TD_Opaque, RMut, RRef, /// }; /// /// { - /// let mut to: Doer_TO<'_, RBox<()>> = - /// Doer_TO::from_value(34usize, TD_Opaque); - /// + /// let mut to: Doer_TO<'_, RBox<()>> = Doer_TO::from_value(34usize, TD_Opaque); + /// /// unsafe { /// // `to.obj` is an RObject /// assert_eq!(to.obj.unchecked_downcast_as_mut::(), &mut 34usize); @@ -637,9 +606,8 @@ where /// // `#[sabi_trait]` trait objects constructed from `&mut` /// // use `RMut<'_, ()>` instead of `&'_ mut ()` /// // since `&mut T` can't soundly be transmuted back and forth into `&mut ()` - /// let mut to: Doer_TO<'_, RMut<'_, ()>> = - /// Doer_TO::from_ptr(mmut, TD_Opaque); - /// + /// let mut to: Doer_TO<'_, RMut<'_, ()>> = Doer_TO::from_ptr(mmut, TD_Opaque); + /// /// unsafe { /// assert_eq!(to.obj.unchecked_downcast_as_mut::(), &mut 55usize); /// } @@ -688,14 +656,11 @@ where /// /// ```rust /// use abi_stable::{ - /// sabi_trait::doc_examples::Doer_TO, - /// std_types::RBox, - /// type_level::downcasting::TD_Opaque, - /// RRef, RMut, + /// sabi_trait::doc_examples::Doer_TO, std_types::RBox, + /// type_level::downcasting::TD_Opaque, RMut, RRef, /// }; /// - /// let mut to: Doer_TO<'_, RBox<()>> = - /// Doer_TO::from_value(13usize, TD_Opaque); + /// let mut to: Doer_TO<'_, RBox<()>> = Doer_TO::from_value(13usize, TD_Opaque); /// /// // `to.obj` is an RObject /// assert_eq!(debug_string(to.obj.reborrow()), "13"); @@ -705,10 +670,9 @@ where /// assert_eq!(debug_string(to.sabi_reborrow()), "13"); /// assert_eq!(debug_string(to.sabi_reborrow()), "13"); /// - /// /// fn debug_string(to: T) -> String /// where - /// T: std::fmt::Debug + /// T: std::fmt::Debug, /// { /// format!("{:?}", to) /// } @@ -742,21 +706,19 @@ where /// sabi_trait::doc_examples::{Doer, Doer_TO}, /// std_types::RBox, /// type_level::downcasting::TD_Opaque, - /// RRef, RMut, + /// RMut, RRef, /// }; /// - /// let mut to: Doer_TO<'_, RBox<()>> = - /// Doer_TO::from_value(2usize, TD_Opaque); + /// let mut to: Doer_TO<'_, RBox<()>> = Doer_TO::from_value(2usize, TD_Opaque); /// /// // `#[sabi_trait]` trait objects have an equivalent `sabi_reborrow_mut` method, /// // which delegate to this method. /// assert_eq!(increment(to.sabi_reborrow_mut()).value(), 3); /// assert_eq!(increment(to.sabi_reborrow_mut()).value(), 4); /// - /// /// fn increment(mut to: T) -> T /// where - /// T: Doer + /// T: Doer, /// { /// to.add_into(1); /// to diff --git a/abi_stable/src/sabi_types/constructor.rs b/abi_stable/src/sabi_types/constructor.rs index 5acecf95..86fa8934 100644 --- a/abi_stable/src/sabi_types/constructor.rs +++ b/abi_stable/src/sabi_types/constructor.rs @@ -3,61 +3,57 @@ use std::{ fmt::{self, Debug, Display}, }; -/** -Newtype wrapper to pass function pointers to `const fn`. - -A workaround for it not being possible to get a function pointer within a `const fn`, -since it's possible to pass structs that happen to have function pointer fields. - -Every impl of this type delegates the impl to the return value of the wrapped function -(which it calls every time),don't use those impls if the function is likely expensive. - -# Example - -``` -use abi_stable::{ - sabi_types::Constructor, - std_types::{ROption,RNone,RSome}, -}; - - -extern "C" fn returns_100()->ROption{ - RSome(100) -} - -extern "C" fn returns_100b()->ROption{ - RSome(100) -} - -extern "C" fn returns_200()->ROption{ - RSome(200) -} - -extern "C" fn returns_none()->ROption{ - RNone -} - - -const A: Constructor>= Constructor(returns_100); -const B: Constructor>= Constructor(returns_100b); -const C: Constructor>= Constructor(returns_200); -const D: Constructor>= Constructor(returns_none); - -assert_eq!(A,A); -assert_eq!(B,B); -assert_eq!(C,C); -assert_eq!(D,D); - -assert_eq!(A,B); - -assert_ne!(A,C); -assert_ne!(A,D); -assert_ne!(B,C); -assert_ne!(C,D); - - -``` -*/ +/// Newtype wrapper to pass function pointers to `const fn`. +/// +/// A workaround for it not being possible to get a function pointer within a `const fn`, +/// since it's possible to pass structs that happen to have function pointer fields. +/// +/// Every impl of this type delegates the impl to the return value of the wrapped function +/// (which it calls every time),don't use those impls if the function is likely expensive. +/// +/// # Example +/// +/// ``` +/// use abi_stable::{ +/// sabi_types::Constructor, +/// std_types::{RNone, ROption, RSome}, +/// }; +/// +/// extern "C" fn returns_100() -> ROption { +/// RSome(100) +/// } +/// +/// extern "C" fn returns_100b() -> ROption { +/// RSome(100) +/// } +/// +/// extern "C" fn returns_200() -> ROption { +/// RSome(200) +/// } +/// +/// extern "C" fn returns_none() -> ROption { +/// RNone +/// } +/// +/// const A: Constructor> = Constructor(returns_100); +/// const B: Constructor> = Constructor(returns_100b); +/// const C: Constructor> = Constructor(returns_200); +/// const D: Constructor> = Constructor(returns_none); +/// +/// assert_eq!(A, A); +/// assert_eq!(B, B); +/// assert_eq!(C, C); +/// assert_eq!(D, D); +/// +/// assert_eq!(A, B); +/// +/// assert_ne!(A, C); +/// assert_ne!(A, D); +/// assert_ne!(B, C); +/// assert_ne!(C, D); +/// +/// ``` +/// #[repr(transparent)] #[derive(StableAbi)] // #[sabi(debug_print)] diff --git a/abi_stable/src/sabi_types/ignored_wrapper.rs b/abi_stable/src/sabi_types/ignored_wrapper.rs index 9a729aaf..fdc37a29 100644 --- a/abi_stable/src/sabi_types/ignored_wrapper.rs +++ b/abi_stable/src/sabi_types/ignored_wrapper.rs @@ -9,56 +9,55 @@ use std::{ ops::{Deref, DerefMut}, }; -/** -Wrapper type used to ignore its contents in comparisons. - -Use this if you want to derive trait while ignoring the contents of fields in the -`PartialEq`/`Eq`/`PartialOrd`/`Ord`/`Hash` traits. - -It also replaces the hash of T with the hash of `()`. - -# Example - -This example defines a struct with a `CmpIgnored` field. - -``` -use abi_stable::sabi_types::CmpIgnored; - -use std::collections::HashSet; - -#[derive(Debug,Clone,PartialEq,Eq,PartialOrd,Ord,Hash)] -pub struct User{ - name:String, - surname:String, - alt_name:CmpIgnored, -} - - -let a=User{ - name:"J__n".to_string(), - surname:"E____t".to_string(), - alt_name:"Z______l P______d".to_string().into(), -}; - -let b=User{ - name:"J__n".to_string(), - surname:"E____t".to_string(), - alt_name:"H___ of B_____".to_string().into(), -}; - -assert_eq!(a,b); - -let mut map=HashSet::new(); - -map.replace(a.clone()); -assert_eq!( map.replace(b.clone()).unwrap().alt_name.as_str(), "Z______l P______d" ); - -assert_eq!(map.len(),1); -assert_eq!( map.get(&a).unwrap().alt_name.as_str(), "H___ of B_____" ); - -``` - -*/ +/// Wrapper type used to ignore its contents in comparisons. +/// +/// Use this if you want to derive trait while ignoring the contents of fields in the +/// `PartialEq`/`Eq`/`PartialOrd`/`Ord`/`Hash` traits. +/// +/// It also replaces the hash of T with the hash of `()`. +/// +/// # Example +/// +/// This example defines a struct with a `CmpIgnored` field. +/// +/// ``` +/// use abi_stable::sabi_types::CmpIgnored; +/// +/// use std::collections::HashSet; +/// +/// #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +/// pub struct User { +/// name: String, +/// surname: String, +/// alt_name: CmpIgnored, +/// } +/// +/// let a = User { +/// name: "J__n".to_string(), +/// surname: "E____t".to_string(), +/// alt_name: "Z______l P______d".to_string().into(), +/// }; +/// +/// let b = User { +/// name: "J__n".to_string(), +/// surname: "E____t".to_string(), +/// alt_name: "H___ of B_____".to_string().into(), +/// }; +/// +/// assert_eq!(a, b); +/// +/// let mut map = HashSet::new(); +/// +/// map.replace(a.clone()); +/// assert_eq!( +/// map.replace(b.clone()).unwrap().alt_name.as_str(), +/// "Z______l P______d" +/// ); +/// +/// assert_eq!(map.len(), 1); +/// assert_eq!(map.get(&a).unwrap().alt_name.as_str(), "H___ of B_____");/// +/// ``` +/// #[repr(transparent)] #[derive(Default, Copy, Clone, StableAbi)] pub struct CmpIgnored { @@ -73,7 +72,7 @@ impl CmpIgnored { /// ``` /// use abi_stable::sabi_types::CmpIgnored; /// - /// let val=CmpIgnored::new(100); + /// let val = CmpIgnored::new(100); /// /// ``` pub const fn new(value: T) -> Self { diff --git a/abi_stable/src/sabi_types/late_static_ref.rs b/abi_stable/src/sabi_types/late_static_ref.rs index 62f6fa6e..5753e107 100644 --- a/abi_stable/src/sabi_types/late_static_ref.rs +++ b/abi_stable/src/sabi_types/late_static_ref.rs @@ -14,76 +14,68 @@ use crate::{ prefix_type::{PointsToPrefixFields, PrefixRef}, }; -/** -A late-initialized static reference,with fallible initialization. - -As opposed to `Once`, -this allows initialization of its static reference to happen fallibly, -by returning a `Result<_,_>` from the `try_init` function, -or by panicking inside either initialization function. - -On `Err(_)` and panics,one can try initialializing the static reference again. - -# Example - -This lazily loads a configuration file. - -``` - -use abi_stable::{ - sabi_types::LateStaticRef, - std_types::{RBox,RBoxError,RHashMap,RString}, - utils::leak_value, -}; - -use std::{ - fs, - io, - path::Path, -}; - -use serde::Deserialize; - - -#[derive(Deserialize)] -pub struct Config{ - pub user_actions:RHashMap, -} - -#[derive(Deserialize)] -pub enum UserAction{ - Include, - Ignore, - ReplaceWith, -} - - -fn load_config(file_path:&Path)->Result<&'static Config,RBoxError>{ - static CONFIG:LateStaticRef<&Config>=LateStaticRef::new(); - - CONFIG.try_init(||{ - let file=load_file(file_path).map_err(RBoxError::new)?; - let config=serde_json::from_str::(&file).map_err(RBoxError::new)?; - Ok(leak_value(config)) - }) -} - - -# fn load_file(file_path:&Path)->Result{ -# let str=r##" -# { -# "user_actions":{ -# "oolong":"prolonged", -# "genius":"idiot" -# } -# } -# "##.to_string(); -# Ok(str) -# } - -``` - -*/ +/// A late-initialized static reference,with fallible initialization. +/// +/// As opposed to `Once`, +/// this allows initialization of its static reference to happen fallibly, +/// by returning a `Result<_,_>` from the `try_init` function, +/// or by panicking inside either initialization function. +/// +/// On `Err(_)` and panics,one can try initialializing the static reference again. +/// +/// # Example +/// +/// This lazily loads a configuration file. +/// +/// ``` +/// +/// use abi_stable::{ +/// sabi_types::LateStaticRef, +/// std_types::{RBox, RBoxError, RHashMap, RString}, +/// utils::leak_value, +/// }; +/// +/// use std::{fs, io, path::Path}; +/// +/// use serde::Deserialize; +/// +/// #[derive(Deserialize)] +/// pub struct Config { +/// pub user_actions: RHashMap, +/// } +/// +/// #[derive(Deserialize)] +/// pub enum UserAction { +/// Include, +/// Ignore, +/// ReplaceWith, +/// } +/// +/// fn load_config(file_path: &Path) -> Result<&'static Config, RBoxError> { +/// static CONFIG: LateStaticRef<&Config> = LateStaticRef::new(); +/// +/// CONFIG.try_init(|| { +/// let file = load_file(file_path).map_err(RBoxError::new)?; +/// let config = +/// serde_json::from_str::(&file).map_err(RBoxError::new)?; +/// Ok(leak_value(config)) +/// }) +/// } +/// +/// # fn load_file(file_path:&Path)->Result{ +/// # let str=r##" +/// # { +/// # "user_actions":{ +/// # "oolong":"prolonged", +/// # "genius":"idiot" +/// # } +/// # } +/// # "##.to_string(); +/// # Ok(str) +/// # } +/// +/// ``` +/// #[repr(C)] #[derive(StableAbi)] pub struct LateStaticRef { @@ -105,7 +97,7 @@ impl LateStaticRef { /// ``` /// use abi_stable::sabi_types::LateStaticRef; /// - /// static LATE_REF:LateStaticRef<&String>=LateStaticRef::new(); + /// static LATE_REF: LateStaticRef<&String> = LateStaticRef::new(); /// /// ``` pub const fn new() -> Self { @@ -125,8 +117,7 @@ impl LateStaticRef<&'static T> { /// ``` /// use abi_stable::sabi_types::LateStaticRef; /// - /// static LATE_REF:LateStaticRef<&&str>= - /// LateStaticRef::from_ref(&"Hello!"); + /// static LATE_REF: LateStaticRef<&&str> = LateStaticRef::from_ref(&"Hello!"); /// /// ``` pub const fn from_ref(value: &'static T) -> Self { @@ -145,13 +136,13 @@ impl LateStaticRef { /// /// ``` /// use abi_stable::{ - /// StableAbi, /// pointer_trait::ImmutableRef, /// prefix_type::{PrefixRefTrait, PrefixTypeTrait, WithMetadata}, - /// sabi_types::LateStaticRef + /// sabi_types::LateStaticRef, + /// StableAbi, /// }; /// - /// fn main(){ + /// fn main() { /// assert_eq!(LATE_REF.get().unwrap().get_number()(), 100); /// } /// @@ -173,23 +164,17 @@ impl LateStaticRef { /// /// first compatible version of the library. /// /// Moving this attribute is a braeking change. /// #[sabi(last_prefix_field)] - /// pub get_number: extern "C" fn()->u32, - /// + /// pub get_number: extern "C" fn() -> u32, /// } /// /// const MODULE: PersonMod_Ref = { - /// - /// const S: &WithMetadata = &WithMetadata::new( - /// PrefixTypeTrait::METADATA, - /// PersonMod{ - /// get_number, - /// } - /// ); + /// const S: &WithMetadata = + /// &WithMetadata::new(PrefixTypeTrait::METADATA, PersonMod { get_number }); /// /// PersonMod_Ref(S.static_as_prefix()) /// }; /// - /// extern fn get_number()->u32{ + /// extern "C" fn get_number() -> u32 { /// 100 /// } /// ``` @@ -224,10 +209,8 @@ impl LateStaticRef { /// /// ```rust /// use abi_stable::{ + /// pointer_trait::ImmutableRef, sabi_types::LateStaticRef, utils::ref_as_nonnull, /// StableAbi, - /// pointer_trait::ImmutableRef, - /// sabi_types::LateStaticRef, - /// utils::ref_as_nonnull, /// }; /// /// use std::ptr::NonNull; @@ -246,11 +229,8 @@ impl LateStaticRef { /// } /// /// const MODULE: LateStaticRef> = { - /// unsafe{ - /// LateStaticRef::from_custom( - /// ImmutableRef::TARGET, - /// Foo(&100).as_nonnull(), - /// ) + /// unsafe { + /// LateStaticRef::from_custom(ImmutableRef::TARGET, Foo(&100).as_nonnull()) /// } /// }; /// ``` @@ -283,27 +263,22 @@ where /// # Example /// /// ``` - /// use abi_stable::{ - /// sabi_types::LateStaticRef, - /// utils::leak_value, - /// }; + /// use abi_stable::{sabi_types::LateStaticRef, utils::leak_value}; /// - /// static LATE:LateStaticRef<&String>=LateStaticRef::new(); + /// static LATE: LateStaticRef<&String> = LateStaticRef::new(); /// - /// static EARLY:LateStaticRef<&&str>= - /// LateStaticRef::from_ref(&"Hello!"); + /// static EARLY: LateStaticRef<&&str> = LateStaticRef::from_ref(&"Hello!"); /// - /// assert_eq!( LATE.try_init(|| Err("oh no!") ), Err("oh no!") ); + /// assert_eq!(LATE.try_init(|| Err("oh no!")), Err("oh no!")); /// assert_eq!( - /// LATE - /// .try_init(||->Result<&'static String,()>{ - /// Ok( leak_value("Yay".to_string()) ) - /// }) - /// .map(|s| s.as_str() ), + /// LATE.try_init(|| -> Result<&'static String, ()> { + /// Ok(leak_value("Yay".to_string())) + /// }) + /// .map(|s| s.as_str()), /// Ok("Yay"), /// ); /// - /// assert_eq!( EARLY.try_init(|| Err("oh no!") ), Ok(&"Hello!") ); + /// assert_eq!(EARLY.try_init(|| Err("oh no!")), Ok(&"Hello!")); /// /// /// ``` @@ -343,23 +318,19 @@ where /// # Example /// /// ``` - /// use abi_stable::{ - /// sabi_types::LateStaticRef, - /// utils::leak_value, - /// }; + /// use abi_stable::{sabi_types::LateStaticRef, utils::leak_value}; /// - /// static LATE:LateStaticRef<&String>=LateStaticRef::new(); + /// static LATE: LateStaticRef<&String> = LateStaticRef::new(); /// - /// static EARLY:LateStaticRef<&&str>= - /// LateStaticRef::from_ref(&"Hello!"); + /// static EARLY: LateStaticRef<&&str> = LateStaticRef::from_ref(&"Hello!"); /// - /// let _=std::panic::catch_unwind(||{ - /// LATE.init(|| panic!() ); + /// let _ = std::panic::catch_unwind(|| { + /// LATE.init(|| panic!()); /// }); /// - /// assert_eq!( LATE.init(|| leak_value("Yay".to_string()) ), &"Yay" ); + /// assert_eq!(LATE.init(|| leak_value("Yay".to_string())), &"Yay"); /// - /// assert_eq!( EARLY.init(|| panic!() ), &"Hello!" ); + /// assert_eq!(EARLY.init(|| panic!()), &"Hello!"); /// /// ``` #[inline] @@ -376,25 +347,21 @@ where /// # Example /// /// ``` - /// use abi_stable::{ - /// sabi_types::LateStaticRef, - /// utils::leak_value, - /// }; + /// use abi_stable::{sabi_types::LateStaticRef, utils::leak_value}; /// - /// static LATE:LateStaticRef<&String>=LateStaticRef::new(); + /// static LATE: LateStaticRef<&String> = LateStaticRef::new(); /// - /// static EARLY:LateStaticRef<&&str>= - /// LateStaticRef::from_ref(&"Hello!"); + /// static EARLY: LateStaticRef<&&str> = LateStaticRef::from_ref(&"Hello!"); /// - /// let _=std::panic::catch_unwind(||{ - /// LATE.init(|| panic!() ); + /// let _ = std::panic::catch_unwind(|| { + /// LATE.init(|| panic!()); /// }); /// - /// assert_eq!( LATE.get(), None ); - /// LATE.init(|| leak_value("Yay".to_string()) ); - /// assert_eq!( LATE.get().map(|s| s.as_str() ), Some("Yay") ); + /// assert_eq!(LATE.get(), None); + /// LATE.init(|| leak_value("Yay".to_string())); + /// assert_eq!(LATE.get().map(|s| s.as_str()), Some("Yay")); /// - /// assert_eq!( EARLY.get(), Some(&"Hello!") ); + /// assert_eq!(EARLY.get(), Some(&"Hello!")); /// /// ``` pub fn get(&self) -> Option { diff --git a/abi_stable/src/sabi_types/maybe_cmp.rs b/abi_stable/src/sabi_types/maybe_cmp.rs index d3fe313f..cd9394e3 100644 --- a/abi_stable/src/sabi_types/maybe_cmp.rs +++ b/abi_stable/src/sabi_types/maybe_cmp.rs @@ -1,23 +1,21 @@ use std::cmp::{Eq, Ordering, PartialEq, PartialOrd}; -/** -An Option-like type which only compares equal if it contains a value(the `Just` variant). - -# Example - -``` -use abi_stable::sabi_types::MaybeCmp; - -assert_eq!( MaybeCmp::Just(10), MaybeCmp::Just(10) ); - -assert_ne!( MaybeCmp::Just(0), MaybeCmp::Just(10) ); -assert_ne!( MaybeCmp::Just(0), MaybeCmp::Nothing ); -assert_ne!( MaybeCmp::Nothing, MaybeCmp::Just(0) ); -assert_ne!( MaybeCmp::::Nothing, MaybeCmp::Nothing ); - -``` - -*/ +/// An Option-like type which only compares equal if it contains a value(the `Just` variant). +/// +/// # Example +/// +/// ``` +/// use abi_stable::sabi_types::MaybeCmp; +/// +/// assert_eq!(MaybeCmp::Just(10), MaybeCmp::Just(10)); +/// +/// assert_ne!(MaybeCmp::Just(0), MaybeCmp::Just(10)); +/// assert_ne!(MaybeCmp::Just(0), MaybeCmp::Nothing); +/// assert_ne!(MaybeCmp::Nothing, MaybeCmp::Just(0)); +/// assert_ne!(MaybeCmp::::Nothing, MaybeCmp::Nothing); +/// +/// ``` +/// #[allow(clippy::derive_hash_xor_eq)] #[derive(Debug, Copy, Clone, Hash)] #[repr(u8)] diff --git a/abi_stable/src/sabi_types/move_ptr.rs b/abi_stable/src/sabi_types/move_ptr.rs index fa41d89f..311d8353 100644 --- a/abi_stable/src/sabi_types/move_ptr.rs +++ b/abi_stable/src/sabi_types/move_ptr.rs @@ -13,91 +13,82 @@ use std::{ use crate::{sabi_types::RMut, std_types::RBox, traits::IntoInner}; -/** -A move pointer, which allows moving the value from the reference, -consuming it in the process. - -If `MovePtr::into_inner` isn't called, this drops the referenced value when it's dropped - -# Safety - -This is unsafe to construct since the user must ensure that the -original owner of the value never accesses it again. - -# Motivation - -`MovePtr` was created as a way to pass `self` by value to ffi-safe trait object methods, -since one can't simply pass `self` by value(because the type is erased). - -# Examples - -### Using OwnedPointer::in_move_ptr - -This is how one can use MovePtr without `unsafe`. - -This simply moves the contents of an `RBox` into a `Box`. - -``` -use abi_stable::{ - pointer_trait::OwnedPointer, - sabi_types::MovePtr, - std_types::RBox, -}; - - -fn move_rbox_to_box(rbox:RBox)->Box{ - rbox.in_move_ptr(|move_ptr|{ - MovePtr::into_box(move_ptr) - }) -} - -assert_eq!( move_rbox_to_box(RBox::new(99)), Box::new(99) ); - -assert_eq!( move_rbox_to_box(RBox::new(())), Box::new(()) ); - -assert_eq!( - move_rbox_to_box(RBox::new(String::from("SHIT"))), - Box::new(String::from("SHIT")) -); - - -``` - -### Using the (unsafe) `MovePtr::new` - -This is (sort of) how `RBox` implements moving the `T` it owns out of its allocation - -This is basically what `OwnedPointer::{with_move_ptr,in_move_ptr}` do. - -``` -use abi_stable::{ - pointer_trait::{AsMutPtr, OwnedPointer}, - sabi_types::MovePtr, - std_types::RBox, -}; - -use std::mem::ManuallyDrop; - -let rbox = RBox::new(0x100); - -let second_rbox; - -unsafe{ - let mut rbox = ManuallyDrop::new(rbox); - - let move_ptr = unsafe{ MovePtr::from_rmut(rbox.as_rmut()) }; - second_rbox = RBox::from_move_ptr(move_ptr); - - OwnedPointer::drop_allocation(&mut rbox); -} - -assert_eq!(second_rbox, RBox::new(0x100)); - - - -``` - -*/ +/// A move pointer, which allows moving the value from the reference, +/// consuming it in the process. +/// +/// If `MovePtr::into_inner` isn't called, this drops the referenced value when it's dropped +/// +/// # Safety +/// +/// This is unsafe to construct since the user must ensure that the +/// original owner of the value never accesses it again. +/// +/// # Motivation +/// +/// `MovePtr` was created as a way to pass `self` by value to ffi-safe trait object methods, +/// since one can't simply pass `self` by value(because the type is erased). +/// +/// # Examples +/// +/// ### Using OwnedPointer::in_move_ptr +/// +/// This is how one can use MovePtr without `unsafe`. +/// +/// This simply moves the contents of an `RBox` into a `Box`. +/// +/// ``` +/// use abi_stable::{ +/// pointer_trait::OwnedPointer, sabi_types::MovePtr, std_types::RBox, +/// }; +/// +/// fn move_rbox_to_box(rbox: RBox) -> Box { +/// rbox.in_move_ptr(|move_ptr| MovePtr::into_box(move_ptr)) +/// } +/// +/// assert_eq!(move_rbox_to_box(RBox::new(99)), Box::new(99)); +/// +/// assert_eq!(move_rbox_to_box(RBox::new(())), Box::new(())); +/// +/// assert_eq!( +/// move_rbox_to_box(RBox::new(String::from("SHIT"))), +/// Box::new(String::from("SHIT")) +/// ); +/// +/// +/// ``` +/// +/// ### Using the (unsafe) `MovePtr::new` +/// +/// This is (sort of) how `RBox` implements moving the `T` it owns out of its allocation +/// +/// This is basically what `OwnedPointer::{with_move_ptr,in_move_ptr}` do. +/// +/// ``` +/// use abi_stable::{ +/// pointer_trait::{AsMutPtr, OwnedPointer}, +/// sabi_types::MovePtr, +/// std_types::RBox, +/// }; +/// +/// use std::mem::ManuallyDrop; +/// +/// let rbox = RBox::new(0x100); +/// +/// let second_rbox; +/// +/// unsafe { +/// let mut rbox = ManuallyDrop::new(rbox); +/// +/// let move_ptr = unsafe { MovePtr::from_rmut(rbox.as_rmut()) }; +/// second_rbox = RBox::from_move_ptr(move_ptr); +/// +/// OwnedPointer::drop_allocation(&mut rbox); +/// } +/// +/// assert_eq!(second_rbox, RBox::new(0x100)); +/// +/// +/// ``` #[repr(transparent)] #[derive(StableAbi)] #[sabi(bound = "T:'a")] @@ -124,7 +115,7 @@ impl<'a, T> MovePtr<'a, T> { /// /// let mut manual = ManuallyDrop::new(String::from("hello")); /// - /// let moveptr = unsafe{ MovePtr::new(&mut *manual) }; + /// let moveptr = unsafe { MovePtr::new(&mut *manual) }; /// /// drop(moveptr); // moveptr drops the String here. /// ``` @@ -148,19 +139,16 @@ impl<'a, T> MovePtr<'a, T> { /// /// ``` /// use abi_stable::{ - /// sabi_types::MovePtr, - /// std_types::RString, - /// pointer_trait::AsMutPtr, + /// pointer_trait::AsMutPtr, sabi_types::MovePtr, std_types::RString, /// utils::manuallydrop_as_rmut, /// }; /// /// use std::mem::ManuallyDrop; /// - /// /// let mut mdrop = ManuallyDrop::new(RString::from("hello")); /// /// // safety: `mdrop` is never accessed again - /// let moveptr = unsafe{ MovePtr::from_rmut(manuallydrop_as_rmut(&mut mdrop)) }; + /// let moveptr = unsafe { MovePtr::from_rmut(manuallydrop_as_rmut(&mut mdrop)) }; /// assert_eq!(*moveptr, "hello"); /// /// let string: RString = MovePtr::into_inner(moveptr); @@ -191,20 +179,16 @@ impl<'a, T> MovePtr<'a, T> { /// /// ``` /// use abi_stable::{ - /// sabi_types::MovePtr, - /// std_types::RVec, - /// pointer_trait::AsMutPtr, + /// pointer_trait::AsMutPtr, rvec, sabi_types::MovePtr, std_types::RVec, /// utils::manuallydrop_as_raw_mut, - /// rvec, /// }; /// /// use std::mem::ManuallyDrop; /// - /// /// let mut mdrop = ManuallyDrop::new(rvec![3, 5, 8]); /// /// // safety: `mdrop` is never accessed again - /// let moveptr = unsafe{ MovePtr::from_raw(manuallydrop_as_raw_mut(&mut mdrop)) }; + /// let moveptr = unsafe { MovePtr::from_raw(manuallydrop_as_raw_mut(&mut mdrop)) }; /// assert_eq!(moveptr[..], [3, 5, 8]); /// /// let vector: RVec = MovePtr::into_inner(moveptr); @@ -224,16 +208,14 @@ impl<'a, T> MovePtr<'a, T> { /// /// ``` /// use abi_stable::{ - /// pointer_trait::OwnedPointer, - /// sabi_types::MovePtr, - /// std_types::RBox, + /// pointer_trait::OwnedPointer, sabi_types::MovePtr, std_types::RBox, /// }; /// - /// let rbox=RBox::new(String::from("NOPE")); - /// let address_rbox=&*rbox as *const String as usize; + /// let rbox = RBox::new(String::from("NOPE")); + /// let address_rbox = &*rbox as *const String as usize; /// - /// rbox.in_move_ptr(|move_ptr|{ - /// assert_eq!( address_rbox, MovePtr::as_ptr(&move_ptr) as usize ); + /// rbox.in_move_ptr(|move_ptr| { + /// assert_eq!(address_rbox, MovePtr::as_ptr(&move_ptr) as usize); /// }); /// /// ``` @@ -250,16 +232,14 @@ impl<'a, T> MovePtr<'a, T> { /// /// ``` /// use abi_stable::{ - /// pointer_trait::OwnedPointer, - /// sabi_types::MovePtr, - /// std_types::RBox, + /// pointer_trait::OwnedPointer, sabi_types::MovePtr, std_types::RBox, /// }; /// - /// let rbox=RBox::new(String::from("NOPE")); - /// let address_rbox=&*rbox as *const String as usize; + /// let rbox = RBox::new(String::from("NOPE")); + /// let address_rbox = &*rbox as *const String as usize; /// - /// rbox.in_move_ptr(|mut move_ptr|{ - /// assert_eq!( address_rbox, MovePtr::as_mut_ptr(&mut move_ptr) as usize ); + /// rbox.in_move_ptr(|mut move_ptr| { + /// assert_eq!(address_rbox, MovePtr::as_mut_ptr(&mut move_ptr) as usize); /// }); /// /// ``` @@ -276,18 +256,15 @@ impl<'a, T> MovePtr<'a, T> { /// /// ``` /// use abi_stable::{ - /// pointer_trait::OwnedPointer, - /// sabi_types::MovePtr, - /// std_types::RBox, + /// pointer_trait::OwnedPointer, sabi_types::MovePtr, std_types::RBox, /// }; /// - /// let rbox=RBox::new(String::from("NOPE")); + /// let rbox = RBox::new(String::from("NOPE")); /// - /// let string=rbox.in_move_ptr(|move_ptr|unsafe{ - /// MovePtr::into_raw(move_ptr).read() - /// }); + /// let string = + /// rbox.in_move_ptr(|move_ptr| unsafe { MovePtr::into_raw(move_ptr).read() }); /// - /// assert_eq!(string,String::from("NOPE")); + /// assert_eq!(string, String::from("NOPE")); /// /// ``` #[inline] @@ -303,18 +280,14 @@ impl<'a, T> MovePtr<'a, T> { /// /// ``` /// use abi_stable::{ - /// pointer_trait::OwnedPointer, - /// sabi_types::MovePtr, - /// std_types::RBox, + /// pointer_trait::OwnedPointer, sabi_types::MovePtr, std_types::RBox, /// }; /// - /// let rbox=RBox::new(String::from("WHAT!!!")); + /// let rbox = RBox::new(String::from("WHAT!!!")); /// - /// let boxed=rbox.in_move_ptr(|move_ptr|unsafe{ - /// MovePtr::into_box(move_ptr) - /// }); + /// let boxed = rbox.in_move_ptr(|move_ptr| unsafe { MovePtr::into_box(move_ptr) }); /// - /// assert_eq!(boxed,Box::new(String::from("WHAT!!!"))); + /// assert_eq!(boxed, Box::new(String::from("WHAT!!!"))); /// /// ``` #[inline] @@ -340,18 +313,14 @@ impl<'a, T> MovePtr<'a, T> { /// /// ``` /// use abi_stable::{ - /// pointer_trait::OwnedPointer, - /// sabi_types::MovePtr, - /// std_types::RBox, + /// pointer_trait::OwnedPointer, sabi_types::MovePtr, std_types::RBox, /// }; /// - /// let rbox=RBox::new(String::from("WHAT!!!")); + /// let rbox = RBox::new(String::from("WHAT!!!")); /// - /// let boxed=rbox.in_move_ptr(|move_ptr|unsafe{ - /// MovePtr::into_rbox(move_ptr) - /// }); + /// let boxed = rbox.in_move_ptr(|move_ptr| unsafe { MovePtr::into_rbox(move_ptr) }); /// - /// assert_eq!( boxed, RBox::new(String::from("WHAT!!!")) ); + /// assert_eq!(boxed, RBox::new(String::from("WHAT!!!"))); /// /// ``` #[inline] @@ -365,16 +334,14 @@ impl<'a, T> MovePtr<'a, T> { /// /// ``` /// use abi_stable::{ - /// pointer_trait::OwnedPointer, - /// sabi_types::MovePtr, - /// std_types::RBox, + /// pointer_trait::OwnedPointer, sabi_types::MovePtr, std_types::RBox, /// }; /// - /// let rbox=RBox::new(String::from("(The Wi)zard(of)oz")); + /// let rbox = RBox::new(String::from("(The Wi)zard(of)oz")); /// - /// let string=rbox.in_move_ptr(|ptr| MovePtr::into_inner(ptr) ); + /// let string = rbox.in_move_ptr(|ptr| MovePtr::into_inner(ptr)); /// - /// assert_eq!( string, String::from("(The Wi)zard(of)oz") ); + /// assert_eq!(string, String::from("(The Wi)zard(of)oz")); /// /// ``` #[inline] @@ -403,7 +370,7 @@ impl<'a, T> MovePtr<'a, T> { /// /// let rbox = RBox::new(RString::from("hello")); /// - /// let bytes = rbox.in_move_ptr(|ptr| unsafe{ + /// let bytes = rbox.in_move_ptr(|ptr| unsafe { /// MovePtr::into_inner(MovePtr::transmute::>(ptr)) /// }); /// diff --git a/abi_stable/src/sabi_types/nul_str.rs b/abi_stable/src/sabi_types/nul_str.rs index d006010b..487bcc64 100644 --- a/abi_stable/src/sabi_types/nul_str.rs +++ b/abi_stable/src/sabi_types/nul_str.rs @@ -58,9 +58,9 @@ use std::{ /// const BAR: NulStr<'_> = NulStr::from_str("12|34\0"); /// const QUX: NulStr<'_> = NulStr::from_str("123_abcd_45\0"); /// -/// assert_eq!(unsafe{ add_digits(FOO) }, 6); -/// assert_eq!(unsafe{ add_digits(BAR) }, 10); -/// assert_eq!(unsafe{ add_digits(QUX) }, 15); +/// assert_eq!(unsafe { add_digits(FOO) }, 6); +/// assert_eq!(unsafe { add_digits(BAR) }, 10); +/// assert_eq!(unsafe { add_digits(QUX) }, 15); /// # } /// ``` #[repr(transparent)] @@ -147,7 +147,7 @@ impl<'a> NulStr<'a> { /// /// assert_eq!( /// NulStr::try_from_str("hello\0world\0"), - /// Err(NulStrError::InnerNul{pos: 5}), + /// Err(NulStrError::InnerNul { pos: 5 }), /// ); /// /// ``` @@ -204,16 +204,16 @@ impl<'a> NulStr<'a> { /// ```rust /// use abi_stable::sabi_types::NulStr; /// - /// const FOO: NulStr<'_> = unsafe{ NulStr::from_ptr("foo\0".as_ptr()) }; + /// const FOO: NulStr<'_> = unsafe { NulStr::from_ptr("foo\0".as_ptr()) }; /// assert_eq!(FOO, "foo"); /// - /// const BAR: NulStr<'_> = unsafe{ NulStr::from_ptr("bar\0".as_ptr()) }; + /// const BAR: NulStr<'_> = unsafe { NulStr::from_ptr("bar\0".as_ptr()) }; /// assert_eq!(BAR, "bar"); /// - /// const HEWWO: NulStr<'_> = unsafe{ NulStr::from_ptr("Hello, world!\0".as_ptr()) }; + /// const HEWWO: NulStr<'_> = unsafe { NulStr::from_ptr("Hello, world!\0".as_ptr()) }; /// assert_eq!(HEWWO, "Hello, world!"); /// - /// const TRUNCATED: NulStr<'_> = unsafe{ NulStr::from_ptr("baz\0world!\0".as_ptr()) }; + /// const TRUNCATED: NulStr<'_> = unsafe { NulStr::from_ptr("baz\0world!\0".as_ptr()) }; /// assert_eq!(TRUNCATED, "baz"); /// /// ``` diff --git a/abi_stable/src/sabi_types/rmut.rs b/abi_stable/src/sabi_types/rmut.rs index cbf34311..e7f71f9a 100644 --- a/abi_stable/src/sabi_types/rmut.rs +++ b/abi_stable/src/sabi_types/rmut.rs @@ -29,27 +29,26 @@ use crate::{ /// This example demonstrates how a simple `&mut dyn Any`-like type can be implemented. /// /// ```rust -/// use abi_stable::{ -/// marker_type::ErasedObject, -/// std_types::UTypeId, -/// RMut, -/// }; +/// use abi_stable::{marker_type::ErasedObject, std_types::UTypeId, RMut}; /// -/// fn main(){ +/// fn main() { /// let mut value = WithTypeId::new(5u32); /// let mut clone = value.clone(); /// let mut erased = value.erase(); /// /// assert_eq!(WithTypeId::downcast::(erased.reborrow()), None); /// assert_eq!(WithTypeId::downcast::(erased.reborrow()), None); -/// assert_eq!(WithTypeId::downcast::(erased.reborrow()), Some(&mut clone)); +/// assert_eq!( +/// WithTypeId::downcast::(erased.reborrow()), +/// Some(&mut clone) +/// ); /// } /// /// // `#[repr(C))]` with a trailing `T` field is required for soundly transmuting from /// // `RMut<'a, WithTypeId>` to `RMut<'a, WithTypeId>`. /// #[repr(C)] /// #[derive(Debug, PartialEq, Clone)] -/// struct WithTypeId{ +/// struct WithTypeId { /// type_id: UTypeId, /// value: T, /// } @@ -57,27 +56,27 @@ use crate::{ /// impl WithTypeId { /// pub fn new(value: T) -> Self /// where -/// T: 'static +/// T: 'static, /// { -/// Self{ +/// Self { /// type_id: UTypeId::new::(), /// value, /// } /// } /// /// pub fn erase(&mut self) -> RMut<'_, WithTypeId> { -/// unsafe{ RMut::new(self).transmute::>() } +/// unsafe { RMut::new(self).transmute::>() } /// } /// } /// /// impl WithTypeId { /// pub fn downcast(this: RMut<'_, Self>) -> Option<&mut WithTypeId> /// where -/// T: 'static +/// T: 'static, /// { /// if this.get().type_id == UTypeId::new::() { /// // safety: we checked that type parameter was `T` -/// unsafe{ Some(this.transmute_into_mut::>()) } +/// unsafe { Some(this.transmute_into_mut::>()) } /// } else { /// None /// } @@ -181,7 +180,7 @@ impl<'a, T> RMut<'a, T> { /// // `&mut foo` is casted to a pointer to a compatible type (`u32` to `i32`), /// // `rmut` is only used for the lifetime of foo, /// // and is the only active pointer to `foo` while it's used. - /// let mut rmut = unsafe{ RMut::from_raw((&mut foo) as *mut u32 as *mut i32) }; + /// let mut rmut = unsafe { RMut::from_raw((&mut foo) as *mut u32 as *mut i32) }; /// *rmut.get_mut() -= 4; /// /// assert_eq!(*rmut.get(), -1); @@ -401,7 +400,7 @@ impl<'a, T> RMut<'a, T> { /// let mut val = 34; /// let rmut = RMut::new(&mut val); /// - /// unsafe{ + /// unsafe { /// assert_eq!(*rmut.as_ptr(), 34); /// } /// ``` @@ -420,7 +419,7 @@ impl<'a, T> RMut<'a, T> { /// let mut val = 34; /// let mut rmut = RMut::new(&mut val); /// - /// unsafe{ + /// unsafe { /// rmut.as_mut_ptr().write(7); /// /// *rmut.as_mut_ptr() *= 2; @@ -443,7 +442,7 @@ impl<'a, T> RMut<'a, T> { /// let mut val = 89; /// let rmut = RMut::new(&mut val); /// - /// unsafe{ + /// unsafe { /// let ptr = rmut.into_raw(); /// /// ptr.write(27); @@ -479,7 +478,6 @@ impl<'a, T> RMut<'a, T> { /// /// assert_eq!(val, Direction::Down); /// - /// /// #[repr(u8)] /// #[derive(Debug, PartialEq)] /// enum Direction { @@ -515,7 +513,7 @@ impl<'a, T> RMut<'a, T> { /// /// assert_eq!(rmut.get(), &13); /// - /// unsafe{ + /// unsafe { /// *rmut.transmute_into_mut::() = -1; /// } /// @@ -548,7 +546,7 @@ impl<'a, T> RMut<'a, T> { /// let mut val: [u32; 3] = [2, 3, 0]; /// let mut rmut = RMut::new(&mut val); /// - /// unsafe{ + /// unsafe { /// // safety: /// // it's sound to transmute mutable references of arrays into shorter arrays. /// // @@ -584,7 +582,7 @@ impl<'a, T> RMut<'a, T> { /// # Example /// /// ```rust - /// use abi_stable::{RRef, RMut}; + /// use abi_stable::{RMut, RRef}; /// /// let mut val = 77; /// let rmut = RMut::new(&mut val); @@ -607,7 +605,7 @@ impl<'a, T> RMut<'a, T> { /// # Example /// /// ```rust - /// use abi_stable::{RRef, RMut}; + /// use abi_stable::{RMut, RRef}; /// /// let mut val = 0; /// let rmut = RMut::new(&mut val); diff --git a/abi_stable/src/sabi_types/rref.rs b/abi_stable/src/sabi_types/rref.rs index 895428d3..fbe861d3 100644 --- a/abi_stable/src/sabi_types/rref.rs +++ b/abi_stable/src/sabi_types/rref.rs @@ -28,13 +28,9 @@ use crate::{ /// This example demonstrates how a simple `&dyn Any`-like type can be implemented. /// /// ```rust -/// use abi_stable::{ -/// marker_type::ErasedObject, -/// std_types::UTypeId, -/// RRef, -/// }; +/// use abi_stable::{marker_type::ErasedObject, std_types::UTypeId, RRef}; /// -/// fn main(){ +/// fn main() { /// let value = WithTypeId::new(5u32); /// let erased = value.erase(); /// @@ -47,7 +43,7 @@ use crate::{ /// // `RRef<'a, WithTypeId>` to `RRef<'a, WithTypeId>`. /// #[repr(C)] /// #[derive(Debug, PartialEq)] -/// struct WithTypeId{ +/// struct WithTypeId { /// type_id: UTypeId, /// value: T, /// } @@ -55,27 +51,27 @@ use crate::{ /// impl WithTypeId { /// pub fn new(value: T) -> Self /// where -/// T: 'static +/// T: 'static, /// { -/// Self{ +/// Self { /// type_id: UTypeId::new::(), /// value, /// } /// } /// /// pub fn erase(&self) -> RRef<'_, WithTypeId> { -/// unsafe{ RRef::new(self).transmute::>() } +/// unsafe { RRef::new(self).transmute::>() } /// } /// } /// /// impl WithTypeId { /// pub fn downcast(this: RRef<'_, Self>) -> Option<&WithTypeId> /// where -/// T: 'static +/// T: 'static, /// { /// if this.get().type_id == UTypeId::new::() { /// // safety: we checked that type parameter was `T` -/// unsafe{ Some(this.transmute_into_ref::>()) } +/// unsafe { Some(this.transmute_into_ref::>()) } /// } else { /// None /// } @@ -151,13 +147,12 @@ impl<'a, T> RRef<'a, T> { /// ``` /// use abi_stable::sabi_types::RRef; /// - /// struct GetPtr<'a,T>(&'a T); + /// struct GetPtr<'a, T>(&'a T); /// - /// impl<'a,T:'a> GetPtr<'a,T>{ - /// const REF:&'a Option=&None; + /// impl<'a, T: 'a> GetPtr<'a, T> { + /// const REF: &'a Option = &None; /// - /// const STATIC:RRef<'a,Option>= - /// RRef::new(Self::REF); + /// const STATIC: RRef<'a, Option> = RRef::new(Self::REF); /// } /// /// ``` @@ -181,14 +176,12 @@ impl<'a, T> RRef<'a, T> { /// ``` /// use abi_stable::sabi_types::RRef; /// - /// struct GetPtr<'a,T>(&'a T); + /// struct GetPtr<'a, T>(&'a T); /// - /// impl<'a,T:'a> GetPtr<'a,T>{ - /// const PTR:*const Option=&None; + /// impl<'a, T: 'a> GetPtr<'a, T> { + /// const PTR: *const Option = &None; /// - /// const STATIC:RRef<'a,Option>=unsafe{ - /// RRef::from_raw(Self::PTR) - /// }; + /// const STATIC: RRef<'a, Option> = unsafe { RRef::from_raw(Self::PTR) }; /// } /// /// ``` @@ -249,7 +242,7 @@ impl<'a, T> RRef<'a, T> { /// /// let rref = RRef::new(&89); /// - /// unsafe{ + /// unsafe { /// assert_eq!(*rref.as_ptr(), 89); /// } /// ``` @@ -278,7 +271,7 @@ impl<'a, T> RRef<'a, T> { /// let rref = RRef::new(&13u32); /// /// // safety: Wrapping is a `#[repr(transparent)]` wrapper with one `pub` field. - /// let trans = unsafe{ rref.transmute::>() }; + /// let trans = unsafe { rref.transmute::>() }; /// /// assert_eq!(trans, RRef::new(&Wrapping(13u32))); /// @@ -311,12 +304,9 @@ impl<'a, T> RRef<'a, T> { /// # Example /// /// ```rust - /// use abi_stable::{ - /// RRef, - /// std_types::Tuple2, - /// }; + /// use abi_stable::{std_types::Tuple2, RRef}; /// - /// unsafe{ + /// unsafe { /// let reff = RRef::new(&Tuple2(3u32, 5u64)); /// assert_eq!(reff.transmute_into_ref::(), &3u32); /// } diff --git a/abi_stable/src/sabi_types/rsmallbox.rs b/abi_stable/src/sabi_types/rsmallbox.rs index 898119c1..b79a93a4 100644 --- a/abi_stable/src/sabi_types/rsmallbox.rs +++ b/abi_stable/src/sabi_types/rsmallbox.rs @@ -33,139 +33,125 @@ pub use self::private::RSmallBox; mod private { use super::*; - /** - - A box type which stores small values inline as an optimization. - - # Inline storage - - The `Inline` type parameter - is the storage space on the stack (as in inline with the `RSmallBox` struct) - where small values get stored,instead of storing them on the heap. - - It has to have an alignment greater than or equal to the value being stored, - otherwise storing the value on the heap. - - To ensure that the inline storage has enough alignemnt you can use one of the - `AlignTo*` types from the (reexported) alignment submodule, - or from `abi_stable::inline_storage::alignment`. - - # Examples - - ### In a nonexhaustive enum - - Using an RSmallBox to store a generic type in a nonexhaustive enum. - - ``` - use abi_stable::{ - sabi_types::RSmallBox, - std_types::RString, - reexports::SelfOps, - StableAbi, - }; - - #[repr(u8)] - #[derive(StableAbi,Debug,Clone,PartialEq)] - #[sabi(kind(WithNonExhaustive( - // Determines the maximum size of this enum in semver compatible versions. - // This is 7 usize large because: - // - The enum discriminant occupies 1 usize(because the enum is usize aligned). - // - RSmallBox: is 6 usize large - size="[usize;7]", - // Determines the traits that are required when wrapping this enum in NonExhaustive, - // and are then available with it. - traits(Debug,Clone,PartialEq), - )))] - pub enum SomeEnum{ - #[doc(hidden)] - __NonExhaustive, - Foo, - Bar, - // This variant was added in a newer (compatible) version of the library. - Baz(RSmallBox) - } - - impl SomeEnum{ - pub fn is_inline(&self)->bool{ - match self { - SomeEnum::__NonExhaustive=>true, - SomeEnum::Foo=>true, - SomeEnum::Bar=>true, - SomeEnum::Baz(rsbox)=>RSmallBox::is_inline(rsbox), - } - } - - pub fn is_heap_allocated(&self)->bool{ - !self.is_inline() - } - - } - - - #[repr(C)] - #[derive(StableAbi,Debug,Clone,PartialEq)] - pub struct FullName{ - pub name:RString, - pub surname:RString, - } - - # fn main(){ - - let rstring="Oh boy!" - .piped(RString::from) - .piped(RSmallBox::new) - .piped(SomeEnum::Baz); - - let full_name= - FullName{ name:"R__e".into(), surname:"L_____e".into() } - .piped(RSmallBox::new) - .piped(SomeEnum::Baz); - - - assert!( rstring.is_inline() ); - assert!( full_name.is_heap_allocated() ); - - - # } - - ``` - - ### Trying out different `Inline` type parameters - - This example demonstrates how changing the `Inline` type parameter can - change whether an RString is stored inline or on the heap. - - ``` - use abi_stable::{ - inline_storage::alignment::AlignToUsize, - sabi_types::RSmallBox, - std_types::RString, - StableAbi, - }; - - use std::mem; - - type JustRightInlineBox= - RSmallBox()*4 ]>>; - - let string=RString::from("What is that supposed to mean?"); - - let small=RSmallBox::<_,[usize;3]>::new(string.clone()); - let medium=RSmallBox::<_,[usize;4]>::new(string.clone()); - let large=RSmallBox::<_,[usize;16]>::new(string.clone()); - let not_enough_alignment=RSmallBox::<_,[u8;64]>::new(string.clone()); - let just_right=JustRightInlineBox::new(string.clone()); - - - assert!( RSmallBox::is_heap_allocated(&small) ); - assert!( RSmallBox::is_inline(&medium) ); - assert!( RSmallBox::is_inline(&large) ); - assert!( RSmallBox::is_heap_allocated(¬_enough_alignment) ); - assert!( RSmallBox::is_inline(&just_right) ); - - ``` - - */ + /// + /// A box type which stores small values inline as an optimization. + /// + /// # Inline storage + /// + /// The `Inline` type parameter + /// is the storage space on the stack (as in inline with the `RSmallBox` struct) + /// where small values get stored,instead of storing them on the heap. + /// + /// It has to have an alignment greater than or equal to the value being stored, + /// otherwise storing the value on the heap. + /// + /// To ensure that the inline storage has enough alignemnt you can use one of the + /// `AlignTo*` types from the (reexported) alignment submodule, + /// or from `abi_stable::inline_storage::alignment`. + /// + /// # Examples + /// + /// ### In a nonexhaustive enum + /// + /// Using an RSmallBox to store a generic type in a nonexhaustive enum. + /// + /// ``` + /// use abi_stable::{reexports::SelfOps, sabi_types::RSmallBox, std_types::RString, StableAbi}; + /// + /// #[repr(u8)] + /// #[derive(StableAbi, Debug, Clone, PartialEq)] + /// #[sabi(kind(WithNonExhaustive( + /// // Determines the maximum size of this enum in semver compatible versions. + /// // This is 7 usize large because: + /// // - The enum discriminant occupies 1 usize(because the enum is usize aligned). + /// // - RSmallBox: is 6 usize large + /// size="[usize;7]", + /// // Determines the traits that are required when wrapping this enum in NonExhaustive, + /// // and are then available with it. + /// traits(Debug,Clone,PartialEq), + /// )))] + /// pub enum SomeEnum { + /// #[doc(hidden)] + /// __NonExhaustive, + /// Foo, + /// Bar, + /// // This variant was added in a newer (compatible) version of the library. + /// Baz(RSmallBox), + /// } + /// + /// impl SomeEnum { + /// pub fn is_inline(&self) -> bool { + /// match self { + /// SomeEnum::__NonExhaustive => true, + /// SomeEnum::Foo => true, + /// SomeEnum::Bar => true, + /// SomeEnum::Baz(rsbox) => RSmallBox::is_inline(rsbox), + /// } + /// } + /// + /// pub fn is_heap_allocated(&self) -> bool { + /// !self.is_inline() + /// } + /// } + /// + /// #[repr(C)] + /// #[derive(StableAbi, Debug, Clone, PartialEq)] + /// pub struct FullName { + /// pub name: RString, + /// pub surname: RString, + /// } + /// + /// # fn main(){ + /// + /// let rstring = "Oh boy!" + /// .piped(RString::from) + /// .piped(RSmallBox::new) + /// .piped(SomeEnum::Baz); + /// + /// let full_name = FullName { + /// name: "R__e".into(), + /// surname: "L_____e".into(), + /// } + /// .piped(RSmallBox::new) + /// .piped(SomeEnum::Baz); + /// + /// assert!(rstring.is_inline()); + /// assert!(full_name.is_heap_allocated()); + /// + /// # } + /// + /// ``` + /// + /// ### Trying out different `Inline` type parameters + /// + /// This example demonstrates how changing the `Inline` type parameter can + /// change whether an RString is stored inline or on the heap. + /// + /// ``` + /// use abi_stable::{ + /// inline_storage::alignment::AlignToUsize, sabi_types::RSmallBox, std_types::RString, + /// StableAbi, + /// }; + /// + /// use std::mem; + /// + /// type JustRightInlineBox = RSmallBox() * 4]>>; + /// + /// let string = RString::from("What is that supposed to mean?"); + /// + /// let small = RSmallBox::<_, [usize; 3]>::new(string.clone()); + /// let medium = RSmallBox::<_, [usize; 4]>::new(string.clone()); + /// let large = RSmallBox::<_, [usize; 16]>::new(string.clone()); + /// let not_enough_alignment = RSmallBox::<_, [u8; 64]>::new(string.clone()); + /// let just_right = JustRightInlineBox::new(string.clone()); + /// + /// assert!(RSmallBox::is_heap_allocated(&small)); + /// assert!(RSmallBox::is_inline(&medium)); + /// assert!(RSmallBox::is_inline(&large)); + /// assert!(RSmallBox::is_heap_allocated(¬_enough_alignment)); + /// assert!(RSmallBox::is_inline(&just_right)); + /// + /// ``` #[repr(C)] #[derive(StableAbi)] #[sabi(not_stableabi(Inline))] @@ -184,13 +170,9 @@ mod private { /// # Example /// /// ``` - /// use abi_stable::{ - /// sabi_types::RSmallBox, - /// std_types::RString, - /// }; - /// - /// let xbox=RSmallBox::<_,[usize;4]>::new(RString::from("one")); + /// use abi_stable::{sabi_types::RSmallBox, std_types::RString}; /// + /// let xbox = RSmallBox::<_, [usize; 4]>::new(RString::from("one")); /// /// ``` #[inline] @@ -208,17 +190,14 @@ mod private { /// # Example /// /// ``` - /// use abi_stable::{ - /// sabi_types::RSmallBox, - /// std_types::RString, - /// }; + /// use abi_stable::{sabi_types::RSmallBox, std_types::RString}; /// - /// let mut play=RSmallBox::<_,[usize;4]>::new(RString::from("station")); + /// let mut play = RSmallBox::<_, [usize; 4]>::new(RString::from("station")); /// - /// let play_addr=&mut play as *mut RSmallBox<_,_> as usize; - /// let heap_addr=RSmallBox::as_mut_ptr(&mut play) as usize; + /// let play_addr = &mut play as *mut RSmallBox<_, _> as usize; + /// let heap_addr = RSmallBox::as_mut_ptr(&mut play) as usize; /// - /// assert_eq!(play_addr,heap_addr); + /// assert_eq!(play_addr, heap_addr); /// /// ``` #[inline] @@ -235,20 +214,16 @@ mod private { /// # Example /// /// ``` - /// use abi_stable::{ - /// sabi_types::RSmallBox, - /// reexports::SelfOps, - /// std_types::RVec, - /// }; + /// use abi_stable::{reexports::SelfOps, sabi_types::RSmallBox, std_types::RVec}; /// - /// let mut generations=vec![1,2,3,4,5,6,7,8] + /// let mut generations = vec![1, 2, 3, 4, 5, 6, 7, 8] /// .piped(RVec::from) - /// .piped(RSmallBox::<_,[usize;2]>::new); + /// .piped(RSmallBox::<_, [usize; 2]>::new); /// - /// let generations_addr=&generations as *const RSmallBox<_,_> as usize; - /// let heap_addr=RSmallBox::as_ptr(&generations) as usize; + /// let generations_addr = &generations as *const RSmallBox<_, _> as usize; + /// let heap_addr = RSmallBox::as_ptr(&generations) as usize; /// - /// assert_ne!(generations_addr,heap_addr); + /// assert_ne!(generations_addr, heap_addr); /// /// ``` #[inline] @@ -265,17 +240,13 @@ mod private { /// # Example /// /// ``` - /// use abi_stable::{ - /// pointer_trait::OwnedPointer, - /// sabi_types::RSmallBox, - /// std_types::RBox, - /// }; + /// use abi_stable::{pointer_trait::OwnedPointer, sabi_types::RSmallBox, std_types::RBox}; /// - /// let rbox=RBox::new(1000_u64); - /// let rsbox:RSmallBox= - /// rbox.in_move_ptr(|x| RSmallBox::::from_move_ptr(x) ); + /// let rbox = RBox::new(1000_u64); + /// let rsbox: RSmallBox = + /// rbox.in_move_ptr(|x| RSmallBox::::from_move_ptr(x)); /// - /// assert_eq!( *rsbox, 1000_u64 ); + /// assert_eq!(*rsbox, 1000_u64); /// /// ``` pub fn from_move_ptr(from_ptr: MovePtr<'_, T>) -> Self @@ -320,12 +291,12 @@ mod private { /// ``` /// use abi_stable::sabi_types::RSmallBox; /// - /// let old=RSmallBox::::new(599_u64); - /// assert!( ! RSmallBox::is_inline(&old) ); + /// let old = RSmallBox::::new(599_u64); + /// assert!(!RSmallBox::is_inline(&old)); /// - /// let new=RSmallBox::move_::<[u64;1]>(old); - /// assert!( RSmallBox::is_inline(&new) ); - /// assert_eq!(*new,599_u64); + /// let new = RSmallBox::move_::<[u64; 1]>(old); + /// assert!(RSmallBox::is_inline(&new)); + /// assert_eq!(*new, 599_u64); /// /// ``` #[inline] @@ -341,16 +312,13 @@ mod private { /// # Example /// /// ``` - /// use abi_stable::{ - /// sabi_types::RSmallBox, - /// std_types::RString, - /// }; + /// use abi_stable::{sabi_types::RSmallBox, std_types::RString}; /// - /// let heap=RSmallBox::::new(599_u64); - /// assert!( ! RSmallBox::is_inline(&heap) ); + /// let heap = RSmallBox::::new(599_u64); + /// assert!(!RSmallBox::is_inline(&heap)); /// - /// let inline=RSmallBox::::new("hello".into()); - /// assert!( RSmallBox::is_inline(&inline) ); + /// let inline = RSmallBox::::new("hello".into()); + /// assert!(RSmallBox::is_inline(&inline)); /// /// ``` pub fn is_inline(this: &Self) -> bool { @@ -362,16 +330,13 @@ mod private { /// # Example /// /// ``` - /// use abi_stable::{ - /// sabi_types::RSmallBox, - /// std_types::RHashMap, - /// }; + /// use abi_stable::{sabi_types::RSmallBox, std_types::RHashMap}; /// - /// let heap=RSmallBox::<_,[u8;4]>::new(String::new()); - /// assert!( RSmallBox::is_heap_allocated(&heap) ); + /// let heap = RSmallBox::<_, [u8; 4]>::new(String::new()); + /// assert!(RSmallBox::is_heap_allocated(&heap)); /// - /// let inline=RSmallBox::<_,[usize;3]>::new(RHashMap::::new()); - /// assert!( ! RSmallBox::is_heap_allocated(&inline) ); + /// let inline = RSmallBox::<_, [usize; 3]>::new(RHashMap::::new()); + /// assert!(!RSmallBox::is_heap_allocated(&inline)); /// /// ``` pub fn is_heap_allocated(this: &Self) -> bool { @@ -385,8 +350,8 @@ mod private { /// ``` /// use abi_stable::sabi_types::RSmallBox; /// - /// let rbox=RSmallBox::<_,[usize;3]>::new(vec![0,1,2]); - /// assert_eq!( RSmallBox::into_inner(rbox), vec![0,1,2] ); + /// let rbox = RSmallBox::<_, [usize; 3]>::new(vec![0, 1, 2]); + /// assert_eq!(RSmallBox::into_inner(rbox), vec![0, 1, 2]); /// /// ``` #[allow(clippy::redundant_closure)] diff --git a/abi_stable/src/sabi_types/static_ref.rs b/abi_stable/src/sabi_types/static_ref.rs index c06026c3..645c3d4e 100644 --- a/abi_stable/src/sabi_types/static_ref.rs +++ b/abi_stable/src/sabi_types/static_ref.rs @@ -6,101 +6,91 @@ use std::{ ptr::NonNull, }; -/** -A wrapper type for vtable static references, -and other constants that have `non-'static` generic parameters -but are safe to reference for the lifetime of `T`. - -# Purpose - -This type is necessary because Rust doesn't understand that vtables live for `'static`, -even though they have `non-'static` type parameters. - -# Example - -This defines a non-extensible vtable,using a StaticRef as the pointer to the vtable. - -``` -use abi_stable::{ - marker_type::ErasedObject, - prefix_type::{PrefixTypeTrait,WithMetadata}, - sabi_types::StaticRef, - StableAbi, - sabi_extern_fn, - staticref, -}; - -use std::{ - marker::PhantomData, - ops::Deref, -}; - -fn main(){ - let boxed = BoxLike::new("foo".to_string()); - assert_eq!(boxed.as_str(), "foo"); -} - -/// An ffi-safe `Box` -#[repr(C)] -#[derive(StableAbi)] -pub struct BoxLike { - data: *mut T, - - vtable: StaticRef>, - - _marker: PhantomData, -} - -impl BoxLike { - pub fn new(value: T) -> Self { - Self{ - data: Box::into_raw(Box::new(value)), - vtable: VTable::::VTABLE, - _marker: PhantomData, - } - } -} - -impl Drop for BoxLike { - fn drop(&mut self){ - unsafe{ - (self.vtable.drop_)(self.data); - } - } -} - -impl Deref for BoxLike { - type Target = T; - - fn deref(&self) -> &T { - unsafe{ - &*self.data - } - } -} - -#[repr(C)] -#[derive(StableAbi)] -pub struct VTable{ - drop_:unsafe extern "C" fn(*mut T), -} - -impl VTable { - // The `staticref` macro declares a `StaticRef>` constant. - staticref!(const VTABLE: Self = Self{ - drop_: drop_box::, - }); -} - - -#[sabi_extern_fn] -unsafe fn drop_box(object: *mut T){ - drop(Box::from_raw(object)); -} - -``` - -*/ +/// A wrapper type for vtable static references, +/// and other constants that have `non-'static` generic parameters +/// but are safe to reference for the lifetime of `T`. +/// +/// # Purpose +/// +/// This type is necessary because Rust doesn't understand that vtables live for `'static`, +/// even though they have `non-'static` type parameters. +/// +/// # Example +/// +/// This defines a non-extensible vtable,using a StaticRef as the pointer to the vtable. +/// +/// ``` +/// use abi_stable::{ +/// marker_type::ErasedObject, +/// prefix_type::{PrefixTypeTrait, WithMetadata}, +/// sabi_extern_fn, +/// sabi_types::StaticRef, +/// staticref, StableAbi, +/// }; +/// +/// use std::{marker::PhantomData, ops::Deref}; +/// +/// fn main() { +/// let boxed = BoxLike::new("foo".to_string()); +/// assert_eq!(boxed.as_str(), "foo"); +/// } +/// +/// /// An ffi-safe `Box` +/// #[repr(C)] +/// #[derive(StableAbi)] +/// pub struct BoxLike { +/// data: *mut T, +/// +/// vtable: StaticRef>, +/// +/// _marker: PhantomData, +/// } +/// +/// impl BoxLike { +/// pub fn new(value: T) -> Self { +/// Self { +/// data: Box::into_raw(Box::new(value)), +/// vtable: VTable::::VTABLE, +/// _marker: PhantomData, +/// } +/// } +/// } +/// +/// impl Drop for BoxLike { +/// fn drop(&mut self) { +/// unsafe { +/// (self.vtable.drop_)(self.data); +/// } +/// } +/// } +/// +/// impl Deref for BoxLike { +/// type Target = T; +/// +/// fn deref(&self) -> &T { +/// unsafe { &*self.data } +/// } +/// } +/// +/// #[repr(C)] +/// #[derive(StableAbi)] +/// pub struct VTable { +/// drop_: unsafe extern "C" fn(*mut T), +/// } +/// +/// impl VTable { +/// // The `staticref` macro declares a `StaticRef>` constant. +/// staticref!(const VTABLE: Self = Self{ +/// drop_: drop_box::, +/// }); +/// } +/// +/// #[sabi_extern_fn] +/// unsafe fn drop_box(object: *mut T) { +/// drop(Box::from_raw(object)); +/// } +/// +/// ``` #[repr(transparent)] #[derive(StableAbi)] pub struct StaticRef { @@ -148,14 +138,12 @@ impl StaticRef { /// /// struct GetPtr(T); /// - /// impl GetPtr{ - /// const PTR:*const Option=&None; + /// impl GetPtr { + /// const PTR: *const Option = &None; /// - /// const STATIC:StaticRef>=unsafe{ - /// StaticRef::from_raw(Self::PTR) - /// }; + /// const STATIC: StaticRef> = unsafe { StaticRef::from_raw(Self::PTR) }; /// } - /// + /// {} /// ``` pub const unsafe fn from_raw(ref_: *const T) -> Self { Self { @@ -176,12 +164,11 @@ impl StaticRef { /// /// impl GetPtr /// where - /// T:'static + /// T: 'static, /// { - /// const REF:&'static Option=&None; + /// const REF: &'static Option = &None; /// - /// const STATIC:StaticRef>= - /// StaticRef::new(Self::REF); + /// const STATIC: StaticRef> = StaticRef::new(Self::REF); /// } /// /// ``` @@ -208,16 +195,13 @@ impl StaticRef { /// /// struct GetPtr(T); /// - /// impl GetPtr{ - /// const PTR:*const Option=&None; + /// impl GetPtr { + /// const PTR: *const Option = &None; /// - /// const STATIC:StaticRef>=unsafe{ - /// StaticRef::from_raw(Self::PTR) - /// }; + /// const STATIC: StaticRef> = unsafe { StaticRef::from_raw(Self::PTR) }; /// } /// - /// let reference:&'static Option= - /// GetPtr::::STATIC.get(); + /// let reference: &'static Option = GetPtr::::STATIC.get(); /// /// ``` pub fn get<'a>(self) -> &'a T { @@ -234,16 +218,13 @@ impl StaticRef { /// /// struct GetPtr(T); /// - /// impl GetPtr{ - /// const PTR:*const Option=&None; + /// impl GetPtr { + /// const PTR: *const Option = &None; /// - /// const STATIC:StaticRef>=unsafe{ - /// StaticRef::from_raw(Self::PTR) - /// }; + /// const STATIC: StaticRef> = unsafe { StaticRef::from_raw(Self::PTR) }; /// } /// - /// let reference:*const Option= - /// GetPtr::::STATIC.as_ptr(); + /// let reference: *const Option = GetPtr::::STATIC.as_ptr(); /// /// ``` pub const fn as_ptr(self) -> *const T { @@ -264,18 +245,14 @@ impl StaticRef { /// /// struct GetPtr(T); /// - /// impl GetPtr{ - /// const PTR:*const Option=&None; + /// impl GetPtr { + /// const PTR: *const Option = &None; /// - /// const STATIC:StaticRef>=unsafe{ - /// StaticRef::from_raw(Self::PTR) - /// }; + /// const STATIC: StaticRef> = unsafe { StaticRef::from_raw(Self::PTR) }; /// } /// - /// let reference:StaticRef>=unsafe{ - /// GetPtr::<()>::STATIC - /// .transmute::>() - /// }; + /// let reference: StaticRef> = + /// unsafe { GetPtr::<()>::STATIC.transmute::>() }; /// /// ``` pub const unsafe fn transmute(self) -> StaticRef { diff --git a/abi_stable/src/sabi_types/version.rs b/abi_stable/src/sabi_types/version.rs index d6e8376d..596960d9 100644 --- a/abi_stable/src/sabi_types/version.rs +++ b/abi_stable/src/sabi_types/version.rs @@ -35,15 +35,14 @@ use crate::std_types::RStr; /// ``` /// use abi_stable::sabi_types::VersionStrings; /// -/// let v1_0_0=VersionStrings::new("1.0.0").parsed().unwrap(); -/// let v1_0_5=VersionStrings::new("1.0.5").parsed().unwrap(); -/// let v1_1_0=VersionStrings::new("1.1.0").parsed().unwrap(); -/// let v2_0_0=VersionStrings::new("1.0.5").parsed().unwrap(); +/// let v1_0_0 = VersionStrings::new("1.0.0").parsed().unwrap(); +/// let v1_0_5 = VersionStrings::new("1.0.5").parsed().unwrap(); +/// let v1_1_0 = VersionStrings::new("1.1.0").parsed().unwrap(); +/// let v2_0_0 = VersionStrings::new("1.0.5").parsed().unwrap(); /// -/// -/// assert!( v1_0_0.is_compatible(v1_0_5),"'{}' '{}'",v1_0_0,v1_0_5); -/// assert!( v1_0_5.is_compatible(v1_1_0),"'{}' '{}'",v1_0_5,v1_1_0); -/// assert!( !v1_1_0.is_compatible(v2_0_0),"'{}' '{}'",v1_1_0,v2_0_0); +/// assert!(v1_0_0.is_compatible(v1_0_5), "'{}' '{}'", v1_0_0, v1_0_5); +/// assert!(v1_0_5.is_compatible(v1_1_0), "'{}' '{}'", v1_0_5, v1_1_0); +/// assert!(!v1_1_0.is_compatible(v2_0_0), "'{}' '{}'", v1_1_0, v2_0_0); /// /// ``` #[derive(Debug, Copy, Clone, PartialEq, Eq, StableAbi)] @@ -69,15 +68,30 @@ pub struct VersionStrings { /// ``` /// use abi_stable::sabi_types::VersionNumber; /// -/// let v0_1_0=VersionNumber{major:0,minor:1,patch:0}; -/// let v0_1_5=VersionNumber{major:0,minor:1,patch:5}; -/// let v0_1_8=VersionNumber{major:0,minor:1,patch:8}; -/// let v0_2_0=VersionNumber{major:0,minor:2,patch:0}; -/// +/// let v0_1_0 = VersionNumber { +/// major: 0, +/// minor: 1, +/// patch: 0, +/// }; +/// let v0_1_5 = VersionNumber { +/// major: 0, +/// minor: 1, +/// patch: 5, +/// }; +/// let v0_1_8 = VersionNumber { +/// major: 0, +/// minor: 1, +/// patch: 8, +/// }; +/// let v0_2_0 = VersionNumber { +/// major: 0, +/// minor: 2, +/// patch: 0, +/// }; /// -/// assert!( v0_1_0.is_compatible(v0_1_5),"'{}' '{}'",v0_1_0,v0_1_5); -/// assert!( v0_1_5.is_compatible(v0_1_8),"'{}' '{}'",v0_1_5,v0_1_8); -/// assert!( !v0_1_8.is_compatible(v0_2_0),"'{}' '{}'",v0_1_8,v0_2_0); +/// assert!(v0_1_0.is_compatible(v0_1_5), "'{}' '{}'", v0_1_0, v0_1_5); +/// assert!(v0_1_5.is_compatible(v0_1_8), "'{}' '{}'", v0_1_5, v0_1_8); +/// assert!(!v0_1_8.is_compatible(v0_2_0), "'{}' '{}'", v0_1_8, v0_2_0); /// /// ``` #[derive(Debug, Copy, Clone, PartialEq, Eq, StableAbi)] @@ -100,7 +114,7 @@ impl VersionStrings { /// ``` /// use abi_stable::sabi_types::VersionStrings; /// - /// static VERSION:VersionStrings=VersionStrings::new("0.1.2"); + /// static VERSION: VersionStrings = VersionStrings::new("0.1.2"); /// /// ``` pub const fn new(version: &'static str) -> Self { @@ -118,14 +132,21 @@ impl VersionStrings { /// # Example /// /// ``` - /// use abi_stable::sabi_types::{VersionNumber,VersionStrings}; + /// use abi_stable::sabi_types::{VersionNumber, VersionStrings}; /// - /// static VERSION:VersionStrings=VersionStrings::new("0.1.2"); + /// static VERSION: VersionStrings = VersionStrings::new("0.1.2"); /// - /// assert_eq!( VERSION.parsed(), Ok(VersionNumber{major:0,minor:1,patch:2}) ); + /// assert_eq!( + /// VERSION.parsed(), + /// Ok(VersionNumber { + /// major: 0, + /// minor: 1, + /// patch: 2 + /// }) + /// ); /// - /// let err_version=VersionStrings::new("0.a.2.b"); - /// assert!( err_version.parsed().is_err() ); + /// let err_version = VersionStrings::new("0.a.2.b"); + /// assert!(err_version.parsed().is_err()); /// /// ``` pub fn parsed(self) -> Result { @@ -143,14 +164,21 @@ impl VersionNumber { /// # Example /// /// ``` - /// use abi_stable::sabi_types::{VersionNumber,VersionStrings}; + /// use abi_stable::sabi_types::{VersionNumber, VersionStrings}; /// - /// static VERSION:VersionStrings=VersionStrings::new("10.5.20"); + /// static VERSION: VersionStrings = VersionStrings::new("10.5.20"); /// - /// assert_eq!( VersionNumber::new(VERSION), Ok(VersionNumber{major:10,minor:5,patch:20}) ); + /// assert_eq!( + /// VersionNumber::new(VERSION), + /// Ok(VersionNumber { + /// major: 10, + /// minor: 5, + /// patch: 20 + /// }) + /// ); /// - /// let err_version=VersionStrings::new("not a version number"); - /// assert!( VersionNumber::new(err_version).is_err() ); + /// let err_version = VersionStrings::new("not a version number"); + /// assert!(VersionNumber::new(err_version).is_err()); /// /// ``` pub fn new(vn: VersionStrings) -> Result { @@ -197,14 +225,30 @@ impl VersionNumber { /// ``` /// use abi_stable::sabi_types::VersionNumber; /// - /// let v0_1_0=VersionNumber{major:0,minor:1,patch:0}; - /// let v0_1_5=VersionNumber{major:0,minor:1,patch:5}; - /// let v0_1_8=VersionNumber{major:0,minor:1,patch:8}; - /// let v0_2_0=VersionNumber{major:0,minor:2,patch:0}; - /// - /// assert!( v0_1_0.is_compatible(v0_1_5),"'{}' '{}'",v0_1_0,v0_1_5); - /// assert!( v0_1_5.is_compatible(v0_1_8),"'{}' '{}'",v0_1_5,v0_1_8); - /// assert!( !v0_1_8.is_compatible(v0_2_0),"'{}' '{}'",v0_1_8,v0_2_0); + /// let v0_1_0 = VersionNumber { + /// major: 0, + /// minor: 1, + /// patch: 0, + /// }; + /// let v0_1_5 = VersionNumber { + /// major: 0, + /// minor: 1, + /// patch: 5, + /// }; + /// let v0_1_8 = VersionNumber { + /// major: 0, + /// minor: 1, + /// patch: 8, + /// }; + /// let v0_2_0 = VersionNumber { + /// major: 0, + /// minor: 2, + /// patch: 0, + /// }; + /// + /// assert!(v0_1_0.is_compatible(v0_1_5), "'{}' '{}'", v0_1_0, v0_1_5); + /// assert!(v0_1_5.is_compatible(v0_1_8), "'{}' '{}'", v0_1_5, v0_1_8); + /// assert!(!v0_1_8.is_compatible(v0_2_0), "'{}' '{}'", v0_1_8, v0_2_0); /// /// ``` pub fn is_compatible(self, library_implementor: VersionNumber) -> bool { @@ -232,27 +276,59 @@ impl VersionNumber { /// ``` /// use abi_stable::sabi_types::VersionNumber; /// - /// let v0_1_0=VersionNumber{major:0,minor:1,patch:0}; - /// let v0_1_5=VersionNumber{major:0,minor:1,patch:5}; - /// let v0_1_8=VersionNumber{major:0,minor:1,patch:8}; - /// let v0_2_0=VersionNumber{major:0,minor:2,patch:0}; - /// let v0_2_8=VersionNumber{major:0,minor:2,patch:8}; - /// let v1_0_0=VersionNumber{major:1,minor:0,patch:0}; - /// let v1_5_0=VersionNumber{major:1,minor:5,patch:0}; - /// let v2_0_0=VersionNumber{major:2,minor:0,patch:0}; - /// - /// fn is_compat_assert( l:VersionNumber, r:VersionNumber, are_they_compat:bool ){ - /// assert_eq!( l.is_loosely_compatible(r), are_they_compat ); - /// assert_eq!( r.is_loosely_compatible(l), are_they_compat ); + /// let v0_1_0 = VersionNumber { + /// major: 0, + /// minor: 1, + /// patch: 0, + /// }; + /// let v0_1_5 = VersionNumber { + /// major: 0, + /// minor: 1, + /// patch: 5, + /// }; + /// let v0_1_8 = VersionNumber { + /// major: 0, + /// minor: 1, + /// patch: 8, + /// }; + /// let v0_2_0 = VersionNumber { + /// major: 0, + /// minor: 2, + /// patch: 0, + /// }; + /// let v0_2_8 = VersionNumber { + /// major: 0, + /// minor: 2, + /// patch: 8, + /// }; + /// let v1_0_0 = VersionNumber { + /// major: 1, + /// minor: 0, + /// patch: 0, + /// }; + /// let v1_5_0 = VersionNumber { + /// major: 1, + /// minor: 5, + /// patch: 0, + /// }; + /// let v2_0_0 = VersionNumber { + /// major: 2, + /// minor: 0, + /// patch: 0, + /// }; + /// + /// fn is_compat_assert(l: VersionNumber, r: VersionNumber, are_they_compat: bool) { + /// assert_eq!(l.is_loosely_compatible(r), are_they_compat); + /// assert_eq!(r.is_loosely_compatible(l), are_they_compat); /// } /// - /// is_compat_assert( v0_1_0, v0_1_5, true ); - /// is_compat_assert( v0_1_5, v0_1_8, true ); - /// is_compat_assert( v1_0_0, v1_5_0, true ); - /// is_compat_assert( v0_1_8, v0_2_0, false); - /// is_compat_assert( v0_2_8, v1_0_0, false); - /// is_compat_assert( v2_0_0, v1_0_0, false); - /// is_compat_assert( v2_0_0, v1_5_0, false); + /// is_compat_assert(v0_1_0, v0_1_5, true); + /// is_compat_assert(v0_1_5, v0_1_8, true); + /// is_compat_assert(v1_0_0, v1_5_0, true); + /// is_compat_assert(v0_1_8, v0_2_0, false); + /// is_compat_assert(v0_2_8, v1_0_0, false); + /// is_compat_assert(v2_0_0, v1_0_0, false); + /// is_compat_assert(v2_0_0, v1_5_0, false); /// /// ``` pub fn is_loosely_compatible(self, library_implementor: VersionNumber) -> bool { From adabef0d1c99862d8740ab3102de059388e3e26d Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Wed, 27 Oct 2021 01:36:07 -0300 Subject: [PATCH 16/32] Formatted more doc comments. Turned more `/** */`-style doc comments to `///` Did both in submodules of: - external_types - library - macros - nonexhaustive_enum - prefix_type - proc_macro_reexports --- abi_stable/src/erased_types/traits.rs | 6 +- .../src/external_types/crossbeam_channel.rs | 185 +++--- .../src/external_types/parking_lot/mutex.rs | 224 ++++--- .../src/external_types/parking_lot/once.rs | 311 +++++----- .../src/external_types/parking_lot/rw_lock.rs | 395 ++++++------ abi_stable/src/external_types/serde_json.rs | 523 +++++++--------- abi_stable/src/library/lib_header.rs | 174 +++--- abi_stable/src/library/root_mod_trait.rs | 315 +++++----- abi_stable/src/macros/nul_str_macros.rs | 11 +- .../src/nonexhaustive_enum/nonexhaustive.rs | 570 ++++++++---------- abi_stable/src/nonexhaustive_enum/traits.rs | 63 +- abi_stable/src/prefix_type/prefix_ref.rs | 93 +-- .../export_root_module.rs | 10 +- .../get_static_equivalent.rs | 68 +-- .../proc_macro_reexports/sabi_extern_fn.rs | 26 +- .../sabi_trait_attribute.rs | 95 ++- .../proc_macro_reexports/stable_abi_derive.rs | 32 +- 17 files changed, 1439 insertions(+), 1662 deletions(-) diff --git a/abi_stable/src/erased_types/traits.rs b/abi_stable/src/erased_types/traits.rs index 6aa56ae3..ff89325a 100644 --- a/abi_stable/src/erased_types/traits.rs +++ b/abi_stable/src/erased_types/traits.rs @@ -100,11 +100,7 @@ declare_InterfaceType! { /// /// ``` /// - /// use abi_stable::{ - /// StableAbi, - /// erased_types::InterfaceType, - /// type_level::bools::*, - /// }; + /// use abi_stable::{erased_types::InterfaceType, type_level::bools::*, StableAbi}; /// /// #[repr(C)] /// #[derive(StableAbi)] diff --git a/abi_stable/src/external_types/crossbeam_channel.rs b/abi_stable/src/external_types/crossbeam_channel.rs index 7762d3f9..b07ad8b2 100644 --- a/abi_stable/src/external_types/crossbeam_channel.rs +++ b/abi_stable/src/external_types/crossbeam_channel.rs @@ -51,7 +51,7 @@ pub use self::iteration::{RIntoIter, RIter}; #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// -/// let rx=mpmc::never::<()>(); +/// let rx = mpmc::never::<()>(); /// /// assert_eq!(rx.try_recv().ok(), None); /// @@ -74,18 +74,18 @@ pub fn never() -> RReceiver { #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// -/// let (tx,rx)=mpmc::bounded::(3); +/// let (tx, rx) = mpmc::bounded::(3); /// -/// std::thread::spawn(move||{ +/// std::thread::spawn(move || { /// tx.send(10).unwrap(); /// tx.send(11).unwrap(); /// tx.send(12).unwrap(); /// }); /// -/// assert_eq!( rx.recv().unwrap(), 10 ); -/// assert_eq!( rx.recv().unwrap(), 11 ); -/// assert_eq!( rx.recv().unwrap(), 12 ); -/// assert!( rx.try_recv().is_err() ); +/// assert_eq!(rx.recv().unwrap(), 10); +/// assert_eq!(rx.recv().unwrap(), 11); +/// assert_eq!(rx.recv().unwrap(), 12); +/// assert!(rx.try_recv().is_err()); /// /// ``` /// @@ -102,13 +102,13 @@ pub fn bounded(capacity: usize) -> (RSender, RReceiver) { #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// -/// let (tx,rx)=mpmc::unbounded::<&'static str>(); +/// let (tx, rx) = mpmc::unbounded::<&'static str>(); /// -/// let join_guard=std::thread::spawn(move||{ -/// assert_eq!( rx.recv().unwrap(), "foo" ); -/// assert_eq!( rx.recv().unwrap(), "bar" ); -/// assert_eq!( rx.recv().unwrap(), "baz" ); -/// assert!( rx.try_recv().is_err() ); +/// let join_guard = std::thread::spawn(move || { +/// assert_eq!(rx.recv().unwrap(), "foo"); +/// assert_eq!(rx.recv().unwrap(), "bar"); +/// assert_eq!(rx.recv().unwrap(), "baz"); +/// assert!(rx.try_recv().is_err()); /// }); /// /// tx.send("foo").unwrap(); @@ -136,19 +136,19 @@ pub fn unbounded() -> (RSender, RReceiver) { #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// -/// let (tx,rx)=mpmc::bounded::<&'static str>(1024); +/// let (tx, rx) = mpmc::bounded::<&'static str>(1024); /// -/// std::thread::spawn(move||{ -/// for _ in 0..4{ +/// std::thread::spawn(move || { +/// for _ in 0..4 { /// tx.send("Are we there yet.").unwrap(); /// } /// }); /// -/// assert_eq!(rx.recv().unwrap(),"Are we there yet."); -/// assert_eq!(rx.recv().unwrap(),"Are we there yet."); -/// assert_eq!(rx.recv().unwrap(),"Are we there yet."); -/// assert_eq!(rx.recv().unwrap(),"Are we there yet."); -/// assert!( rx.recv().is_err() ); +/// assert_eq!(rx.recv().unwrap(), "Are we there yet."); +/// assert_eq!(rx.recv().unwrap(), "Are we there yet."); +/// assert_eq!(rx.recv().unwrap(), "Are we there yet."); +/// assert_eq!(rx.recv().unwrap(), "Are we there yet."); +/// assert!(rx.recv().is_err()); /// /// /// ``` @@ -178,12 +178,12 @@ impl RSender { #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// - /// let (tx,rx)=mpmc::bounded::(3); + /// let (tx, rx) = mpmc::bounded::(3); /// /// tx.send(1057).unwrap(); /// /// drop(rx); - /// assert!( tx.send(0).is_err() ); + /// assert!(tx.send(0).is_err()); /// /// ``` /// @@ -210,13 +210,13 @@ impl RSender { #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// - /// let (tx,rx)=mpmc::bounded::(1); + /// let (tx, rx) = mpmc::bounded::(1); /// /// tx.try_send(true).unwrap(); - /// assert!( tx.try_send(true).unwrap_err().is_full() ); + /// assert!(tx.try_send(true).unwrap_err().is_full()); /// /// drop(rx); - /// assert!( tx.try_send(false).unwrap_err().is_disconnected() ); + /// assert!(tx.try_send(false).unwrap_err().is_disconnected()); /// /// ``` /// @@ -246,15 +246,15 @@ impl RSender { /// /// use std::time::Duration; /// - /// let (tx,rx)=mpmc::bounded::<()>(1); + /// let (tx, rx) = mpmc::bounded::<()>(1); /// - /// let timeout=Duration::from_millis(1); + /// let timeout = Duration::from_millis(1); /// - /// tx.send_timeout((),timeout).unwrap(); - /// assert!( tx.send_timeout((),timeout).unwrap_err().is_timeout() ); + /// tx.send_timeout((), timeout).unwrap(); + /// assert!(tx.send_timeout((), timeout).unwrap_err().is_timeout()); /// /// drop(rx); - /// assert!( tx.send_timeout((),timeout).unwrap_err().is_disconnected() ); + /// assert!(tx.send_timeout((), timeout).unwrap_err().is_disconnected()); /// /// ``` /// @@ -272,15 +272,15 @@ impl RSender { #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// - /// let (tx,rx)=mpmc::bounded::<()>(1); + /// let (tx, rx) = mpmc::bounded::<()>(1); /// - /// assert!( tx.is_empty() ); + /// assert!(tx.is_empty()); /// /// tx.send(()).unwrap(); - /// assert!( !tx.is_empty() ); + /// assert!(!tx.is_empty()); /// /// rx.recv().unwrap(); - /// assert!( tx.is_empty() ); + /// assert!(tx.is_empty()); /// ``` pub fn is_empty(&self) -> bool { let vtable = self.vtable(); @@ -298,18 +298,18 @@ impl RSender { #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// - /// let (tx,rx)=mpmc::bounded::<()>(2); + /// let (tx, rx) = mpmc::bounded::<()>(2); /// - /// assert!( !tx.is_full() ); + /// assert!(!tx.is_full()); /// /// tx.send(()).unwrap(); - /// assert!( !tx.is_full() ); + /// assert!(!tx.is_full()); /// /// tx.send(()).unwrap(); - /// assert!( tx.is_full() ); + /// assert!(tx.is_full()); /// /// rx.recv().unwrap(); - /// assert!( !tx.is_full() ); + /// assert!(!tx.is_full()); /// ``` pub fn is_full(&self) -> bool { let vtable = self.vtable(); @@ -325,18 +325,18 @@ impl RSender { #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// - /// let (tx,rx)=mpmc::bounded::<()>(2); + /// let (tx, rx) = mpmc::bounded::<()>(2); /// - /// assert_eq!(tx.len(),0); + /// assert_eq!(tx.len(), 0); /// /// tx.send(()).unwrap(); - /// assert_eq!(tx.len(),1); + /// assert_eq!(tx.len(), 1); /// /// tx.send(()).unwrap(); - /// assert_eq!(tx.len(),2); + /// assert_eq!(tx.len(), 2); /// /// rx.recv().unwrap(); - /// assert_eq!(tx.len(),1); + /// assert_eq!(tx.len(), 1); /// /// ``` pub fn len(&self) -> usize { @@ -356,12 +356,12 @@ impl RSender { /// use abi_stable::external_types::crossbeam_channel as mpmc; /// /// { - /// let (tx,rx)=mpmc::bounded::<()>(2); - /// assert_eq!(tx.capacity(),Some(2)); + /// let (tx, rx) = mpmc::bounded::<()>(2); + /// assert_eq!(tx.capacity(), Some(2)); /// } /// { - /// let (tx,rx)=mpmc::unbounded::<()>(); - /// assert_eq!(tx.capacity(),None); + /// let (tx, rx) = mpmc::unbounded::<()>(); + /// assert_eq!(tx.capacity(), None); /// } /// /// ``` @@ -418,24 +418,23 @@ impl_from_rust_repr! { #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// -/// let (tx,rx)=mpmc::unbounded::<&'static str>(); +/// let (tx, rx) = mpmc::unbounded::<&'static str>(); /// -/// let join_guard=std::thread::spawn(move||{ -/// assert_eq!(rx.recv().unwrap(),"PING"); -/// assert_eq!(rx.recv().unwrap(),"PING"); -/// assert_eq!(rx.recv().unwrap(),"PING"); -/// assert_eq!(rx.recv().unwrap(),"PING"); -/// assert!( rx.try_recv().unwrap_err().is_empty() ); +/// let join_guard = std::thread::spawn(move || { +/// assert_eq!(rx.recv().unwrap(), "PING"); +/// assert_eq!(rx.recv().unwrap(), "PING"); +/// assert_eq!(rx.recv().unwrap(), "PING"); +/// assert_eq!(rx.recv().unwrap(), "PING"); +/// assert!(rx.try_recv().unwrap_err().is_empty()); /// }); /// -/// for _ in 0..4{ +/// for _ in 0..4 { /// tx.send("PING").unwrap(); /// } /// /// join_guard.join().unwrap(); /// -/// assert!( tx.send("").is_err() ); -/// +/// assert!(tx.send("").is_err()); /// /// ``` /// @@ -464,13 +463,13 @@ impl RReceiver { #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// - /// let (tx,rx)=mpmc::bounded::<&'static str>(3); + /// let (tx, rx) = mpmc::bounded::<&'static str>(3); /// /// tx.send("J__e H____y").unwrap(); - /// assert_eq!( rx.recv().unwrap(), "J__e H____y" ); + /// assert_eq!(rx.recv().unwrap(), "J__e H____y"); /// /// drop(tx); - /// assert!( rx.recv().is_err() ); + /// assert!(rx.recv().is_err()); /// /// ``` /// @@ -498,15 +497,15 @@ impl RReceiver { #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// - /// let (tx,rx)=mpmc::bounded::<&'static str>(3); + /// let (tx, rx) = mpmc::bounded::<&'static str>(3); /// - /// assert!( rx.try_recv().is_err() ); + /// assert!(rx.try_recv().is_err()); /// /// tx.send("D__e S_____r").unwrap(); - /// assert_eq!( rx.try_recv().unwrap(), "D__e S_____r" ); + /// assert_eq!(rx.try_recv().unwrap(), "D__e S_____r"); /// /// drop(tx); - /// assert!( rx.try_recv().is_err() ); + /// assert!(rx.try_recv().is_err()); /// /// ``` pub fn try_recv(&self) -> Result { @@ -535,17 +534,17 @@ impl RReceiver { /// /// use std::time::Duration; /// - /// let (tx,rx)=mpmc::bounded::<&'static str>(3); + /// let (tx, rx) = mpmc::bounded::<&'static str>(3); /// - /// let timeout=Duration::from_millis(1); + /// let timeout = Duration::from_millis(1); /// - /// assert!( rx.recv_timeout(timeout).unwrap_err().is_timeout() ); + /// assert!(rx.recv_timeout(timeout).unwrap_err().is_timeout()); /// /// tx.send("D__e S_____r").unwrap(); - /// assert_eq!( rx.recv_timeout(timeout).unwrap(), "D__e S_____r" ); + /// assert_eq!(rx.recv_timeout(timeout).unwrap(), "D__e S_____r"); /// /// drop(tx); - /// assert!( rx.recv_timeout(timeout).unwrap_err().is_disconnected() ); + /// assert!(rx.recv_timeout(timeout).unwrap_err().is_disconnected()); /// /// ``` /// @@ -563,15 +562,15 @@ impl RReceiver { #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// - /// let (tx,rx)=mpmc::bounded::<()>(1); + /// let (tx, rx) = mpmc::bounded::<()>(1); /// - /// assert!( rx.is_empty() ); + /// assert!(rx.is_empty()); /// /// tx.send(()).unwrap(); - /// assert!( !rx.is_empty() ); + /// assert!(!rx.is_empty()); /// /// rx.recv().unwrap(); - /// assert!( rx.is_empty() ); + /// assert!(rx.is_empty()); /// ``` pub fn is_empty(&self) -> bool { let vtable = self.vtable(); @@ -589,18 +588,18 @@ impl RReceiver { #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// - /// let (tx,rx)=mpmc::bounded::<()>(2); + /// let (tx, rx) = mpmc::bounded::<()>(2); /// - /// assert!( !rx.is_full() ); + /// assert!(!rx.is_full()); /// /// tx.send(()).unwrap(); - /// assert!( !rx.is_full() ); + /// assert!(!rx.is_full()); /// /// tx.send(()).unwrap(); - /// assert!( rx.is_full() ); + /// assert!(rx.is_full()); /// /// rx.recv().unwrap(); - /// assert!( !rx.is_full() ); + /// assert!(!rx.is_full()); /// ``` pub fn is_full(&self) -> bool { let vtable = self.vtable(); @@ -616,18 +615,18 @@ impl RReceiver { #[cfg_attr(feature = "test_miri_track_raw", doc = "```ignore")] /// use abi_stable::external_types::crossbeam_channel as mpmc; /// - /// let (tx,rx)=mpmc::bounded::<()>(2); + /// let (tx, rx) = mpmc::bounded::<()>(2); /// - /// assert_eq!(rx.len(),0); + /// assert_eq!(rx.len(), 0); /// /// tx.send(()).unwrap(); - /// assert_eq!(rx.len(),1); + /// assert_eq!(rx.len(), 1); /// /// tx.send(()).unwrap(); - /// assert_eq!(rx.len(),2); + /// assert_eq!(rx.len(), 2); /// /// rx.recv().unwrap(); - /// assert_eq!(rx.len(),1); + /// assert_eq!(rx.len(), 1); /// /// ``` pub fn len(&self) -> usize { @@ -647,12 +646,12 @@ impl RReceiver { /// use abi_stable::external_types::crossbeam_channel as mpmc; /// /// { - /// let (tx,rx)=mpmc::bounded::<()>(2); - /// assert_eq!(rx.capacity(),Some(2)); + /// let (tx, rx) = mpmc::bounded::<()>(2); + /// assert_eq!(rx.capacity(), Some(2)); /// } /// { - /// let (tx,rx)=mpmc::unbounded::<()>(); - /// assert_eq!(rx.capacity(),None); + /// let (tx, rx) = mpmc::unbounded::<()>(); + /// assert_eq!(rx.capacity(), None); /// } /// /// ``` @@ -672,16 +671,16 @@ impl RReceiver { /// /// use std::thread; /// - /// let (tx,rx)=mpmc::bounded::(1); + /// let (tx, rx) = mpmc::bounded::(1); /// - /// thread::spawn(move||{ + /// thread::spawn(move || { /// for i in 0..1000 { /// tx.send(i).unwrap(); /// } /// }); /// - /// for (i,n) in rx.iter().enumerate() { - /// assert_eq!(i,n); + /// for (i, n) in rx.iter().enumerate() { + /// assert_eq!(i, n); /// } /// /// ``` diff --git a/abi_stable/src/external_types/parking_lot/mutex.rs b/abi_stable/src/external_types/parking_lot/mutex.rs index 340f5388..26b65694 100644 --- a/abi_stable/src/external_types/parking_lot/mutex.rs +++ b/abi_stable/src/external_types/parking_lot/mutex.rs @@ -35,38 +35,36 @@ fn assert_mutex_size() { let _assert_size: [(); mem::size_of::() - RAW_LOCK_SIZE]; } -/** -A mutual exclusion lock that allows dynamic mutable borrows of shared data. - -# Poisoning - -As opposed to the standard library version of this type, -this mutex type does not use poisoning, -simply unlocking the lock when a panic happens. - -# Example - -``` -use abi_stable::external_types::RMutex; - -static MUTEX:RMutex=RMutex::new(0); - -let guard=std::thread::spawn(||{ - for _ in 0..100 { - *MUTEX.lock()+=1; - } -}); - -for _ in 0..100 { - *MUTEX.lock()+=1; -} - -guard.join().unwrap(); - -assert_eq!(*MUTEX.lock(),200); - -``` -*/ +/// A mutual exclusion lock that allows dynamic mutable borrows of shared data. +/// +/// # Poisoning +/// +/// As opposed to the standard library version of this type, +/// this mutex type does not use poisoning, +/// simply unlocking the lock when a panic happens. +/// +/// # Example +/// +/// ``` +/// use abi_stable::external_types::RMutex; +/// +/// static MUTEX: RMutex = RMutex::new(0); +/// +/// let guard = std::thread::spawn(|| { +/// for _ in 0..100 { +/// *MUTEX.lock() += 1; +/// } +/// }); +/// +/// for _ in 0..100 { +/// *MUTEX.lock() += 1; +/// } +/// +/// guard.join().unwrap(); +/// +/// assert_eq!(*MUTEX.lock(), 200); +/// +/// ``` #[repr(C)] #[derive(StableAbi)] pub struct RMutex { @@ -75,12 +73,10 @@ pub struct RMutex { vtable: VTable_Ref, } -/** -A mutex guard,which allows mutable access to the data inside an `RMutex`. - -When dropped this will unlock the mutex. - -*/ +/// A mutex guard,which allows mutable access to the data inside an `RMutex`. +/// +/// When dropped this will unlock the mutex. +/// #[repr(transparent)] #[derive(StableAbi)] #[sabi(bound = "T:'a")] @@ -100,9 +96,9 @@ impl RMutex { /// ``` /// use abi_stable::external_types::RMutex; /// - /// static MUTEX:RMutex>=RMutex::new(None); + /// static MUTEX: RMutex> = RMutex::new(None); /// - /// let mutex=RMutex::new(0); + /// let mutex = RMutex::new(0); /// /// ``` pub const fn new(value: T) -> Self { @@ -133,9 +129,9 @@ impl RMutex { /// ``` /// use abi_stable::external_types::RMutex; /// - /// let mutex=RMutex::new("hello".to_string()); + /// let mutex = RMutex::new("hello".to_string()); /// - /// assert_eq!(mutex.into_inner().as_str(),"hello"); + /// assert_eq!(mutex.into_inner().as_str(), "hello"); /// /// ``` #[inline] @@ -152,12 +148,11 @@ impl RMutex { /// ``` /// use abi_stable::external_types::RMutex; /// - /// let mut mutex=RMutex::new("Hello".to_string()); + /// let mut mutex = RMutex::new("Hello".to_string()); /// /// mutex.get_mut().push_str(", World!"); /// - /// assert_eq!(mutex.lock().as_str(),"Hello, World!"); - /// + /// assert_eq!(mutex.lock().as_str(), "Hello, World!"); /// /// ``` #[inline] @@ -165,58 +160,54 @@ impl RMutex { unsafe { &mut *self.data.get() } } - /** - Acquires a mutex,blocking the current thread until it can. - - This function returns a guard which releases the mutex when it is dropped. - - Trying to lock the mutex in the same thread that holds the lock will cause a deadlock. - - # Example - - ``` - use abi_stable::external_types::RMutex; - - static MUTEX:RMutex=RMutex::new(0); - - let guard=std::thread::spawn(|| *MUTEX.lock()+=1 ); - - *MUTEX.lock()+=4; - - guard.join().unwrap(); - - assert_eq!(*MUTEX.lock(),5); - - ``` - - */ + /// Acquires a mutex,blocking the current thread until it can. + /// + /// This function returns a guard which releases the mutex when it is dropped. + /// + /// Trying to lock the mutex in the same thread that holds the lock will cause a deadlock. + /// + /// # Example + /// + /// ``` + /// use abi_stable::external_types::RMutex; + /// + /// static MUTEX: RMutex = RMutex::new(0); + /// + /// let guard = std::thread::spawn(|| *MUTEX.lock() += 1); + /// + /// *MUTEX.lock() += 4; + /// + /// guard.join().unwrap(); + /// + /// assert_eq!(*MUTEX.lock(), 5); + /// + /// ``` #[inline] pub fn lock(&self) -> RMutexGuard<'_, T> { self.vtable().lock()(&self.raw_mutex); self.make_guard() } - /** - Attemps to acquire a mutex guard. - - Returns the mutex guard if the mutex can be immediately acquired, - otherwise returns `RNone`. - - # Example - - ``` - use abi_stable::external_types::RMutex; - static MUTEX:RMutex=RMutex::new(0); - - let mut guard=MUTEX.try_lock().unwrap(); - - assert!( MUTEX.try_lock().is_none() ); - - assert_eq!(*guard,0); - - ``` - - */ + /// Attemps to acquire a mutex guard. + /// + /// Returns the mutex guard if the mutex can be immediately acquired, + /// otherwise returns `RNone`. + /// + /// # Example + /// + /// ``` + /// use abi_stable::external_types::RMutex; + /// + /// static MUTEX: RMutex = RMutex::new(0); + /// + /// let mut guard = MUTEX.try_lock().unwrap(); + /// + /// assert!(MUTEX.try_lock().is_none()); + /// + /// assert_eq!(*guard, 0); + /// + /// ``` + /// #[inline] pub fn try_lock(&self) -> ROption> { if self.vtable().try_lock()(&self.raw_mutex) { @@ -226,34 +217,29 @@ impl RMutex { } } - /** - Attempts to acquire a mutex guard for the `timeout` duration. - - Once the timeout is reached,this will return `RNone`, - otherwise it will return the mutex guard. - - - # Example - - ``` - use abi_stable::{ - external_types::RMutex, - std_types::RDuration, - }; - - static MUTEX:RMutex=RMutex::new(0); - - static DUR:RDuration=RDuration::from_millis(4); - - let mut guard=MUTEX.try_lock_for(DUR).unwrap(); - - assert!( MUTEX.try_lock_for(DUR).is_none() ); - - assert_eq!(*guard,0); - - ``` - - */ + /// Attempts to acquire a mutex guard for the `timeout` duration. + /// + /// Once the timeout is reached,this will return `RNone`, + /// otherwise it will return the mutex guard. + /// + /// + /// # Example + /// + /// ``` + /// use abi_stable::{external_types::RMutex, std_types::RDuration}; + /// + /// static MUTEX: RMutex = RMutex::new(0); + /// + /// static DUR: RDuration = RDuration::from_millis(4); + /// + /// let mut guard = MUTEX.try_lock_for(DUR).unwrap(); + /// + /// assert!(MUTEX.try_lock_for(DUR).is_none()); + /// + /// assert_eq!(*guard, 0); + /// + /// ``` + /// #[inline] pub fn try_lock_for(&self, timeout: RDuration) -> ROption> { if self.vtable().try_lock_for()(&self.raw_mutex, timeout) { diff --git a/abi_stable/src/external_types/parking_lot/once.rs b/abi_stable/src/external_types/parking_lot/once.rs index d39f8327..df397559 100644 --- a/abi_stable/src/external_types/parking_lot/once.rs +++ b/abi_stable/src/external_types/parking_lot/once.rs @@ -34,39 +34,36 @@ fn assert_mutex_size() { /////////////////////////////////////////////////////////////////////////////// -/** -A synchronization primitive for running global initialization once. - -# Example - -``` -use abi_stable::external_types::{ROnce,RMutex}; - -static MUTEX:RMutex=RMutex::new(0); - -static ONCE:ROnce=ROnce::new(); - -let guards= - std::iter::repeat_with(||{ - std::thread::spawn(||{ - ONCE.call_once(||{ - *MUTEX.lock()+=1; - }) - }) - }) - .take(20) - .collect::>(); - -for guard in guards{ - guard.join().unwrap(); -} - -assert_eq!(*MUTEX.lock(),1); - -``` - - -*/ +/// A synchronization primitive for running global initialization once. +/// +/// # Example +/// +/// ``` +/// use abi_stable::external_types::{RMutex, ROnce}; +/// +/// static MUTEX: RMutex = RMutex::new(0); +/// +/// static ONCE: ROnce = ROnce::new(); +/// +/// let guards = std::iter::repeat_with(|| { +/// std::thread::spawn(|| { +/// ONCE.call_once(|| { +/// *MUTEX.lock() += 1; +/// }) +/// }) +/// }) +/// .take(20) +/// .collect::>(); +/// +/// for guard in guards { +/// guard.join().unwrap(); +/// } +/// +/// assert_eq!(*MUTEX.lock(), 1); +/// +/// ``` +/// +/// #[repr(C)] #[derive(StableAbi)] pub struct ROnce { @@ -99,7 +96,7 @@ impl ROnce { /// ``` /// use abi_stable::external_types::ROnce; /// - /// static ONCE:ROnce=ROnce::NEW; + /// static ONCE: ROnce = ROnce::NEW; /// /// ``` pub const NEW: Self = ROnce { @@ -111,67 +108,63 @@ impl ROnce { self.vtable } - /** - Gets the running state of this ROnce. - - # Example - - ``` - use abi_stable::external_types::parking_lot::once::{ROnce,ROnceState}; - - use std::panic::AssertUnwindSafe; - - let once=ROnce::new(); - - assert_eq!(once.state(), ROnceState::New ); - - let _=std::panic::catch_unwind(AssertUnwindSafe(||{ - once.call_once(|| panic!() ); - })); - - assert!( once.state().poisoned() ); - - once.call_once_force(|_| () ); - - assert!( once.state().done() ); - - ``` - */ + /// Gets the running state of this ROnce. + /// + /// # Example + /// + /// ``` + /// use abi_stable::external_types::parking_lot::once::{ROnce, ROnceState}; + /// + /// use std::panic::AssertUnwindSafe; + /// + /// let once = ROnce::new(); + /// + /// assert_eq!(once.state(), ROnceState::New); + /// + /// let _ = std::panic::catch_unwind(AssertUnwindSafe(|| { + /// once.call_once(|| panic!()); + /// })); + /// + /// assert!(once.state().poisoned()); + /// + /// once.call_once_force(|_| ()); + /// + /// assert!(once.state().done()); + /// + /// ``` pub fn state(&self) -> ROnceState { unsafe { self.vtable().state()(&self.opaque_once) } } - /** - Runs an initialization function. - - `f` will be run only if this is the first time this method has been called - on this ROnce. - - Once this function returns it is guaranteed that some closure passed - to this method has run to completion. - - # Panics - - Panics in the closure will cause this ROnce to become poisoned, - and any future calls to this method will panic. - - # Example - - ``` - use abi_stable::external_types::ROnce; - - let once=ROnce::new(); - let mut counter=0usize; - - once.call_once(|| counter+=1 ); - once.call_once(|| counter+=1 ); - once.call_once(|| counter+=1 ); - once.call_once(|| counter+=1 ); - - assert_eq!(counter,1); - - ``` - */ + /// Runs an initialization function. + /// + /// `f` will be run only if this is the first time this method has been called + /// on this ROnce. + /// + /// Once this function returns it is guaranteed that some closure passed + /// to this method has run to completion. + /// + /// # Panics + /// + /// Panics in the closure will cause this ROnce to become poisoned, + /// and any future calls to this method will panic. + /// + /// # Example + /// + /// ``` + /// use abi_stable::external_types::ROnce; + /// + /// let once = ROnce::new(); + /// let mut counter = 0usize; + /// + /// once.call_once(|| counter += 1); + /// once.call_once(|| counter += 1); + /// once.call_once(|| counter += 1); + /// once.call_once(|| counter += 1); + /// + /// assert_eq!(counter, 1); + /// + /// ``` pub fn call_once(&self, f: F) where F: FnOnce(), @@ -193,40 +186,37 @@ impl ROnce { } } - /** - Runs an initialization function,even if the ROnce is poisoned. - - This will keep trying to run different closures until one of them doesn't panic. - - The ROnceState parameter describes whether the ROnce is New or Poisoned. - - - # Example - - ``` - use abi_stable::external_types::ROnce; - - use std::panic::{self,AssertUnwindSafe}; - - let once=ROnce::new(); - let mut counter=0usize; - - for i in 0..100 { - let _=panic::catch_unwind(AssertUnwindSafe(||{ - once.call_once_force(|_|{ - if i < 6 { - panic!(); - } - counter=i; - }) - })); - } - - assert_eq!(counter,6); - - ``` - - */ + /// Runs an initialization function,even if the ROnce is poisoned. + /// + /// This will keep trying to run different closures until one of them doesn't panic. + /// + /// The ROnceState parameter describes whether the ROnce is New or Poisoned. + /// + /// + /// # Example + /// + /// ``` + /// use abi_stable::external_types::ROnce; + /// + /// use std::panic::{self, AssertUnwindSafe}; + /// + /// let once = ROnce::new(); + /// let mut counter = 0usize; + /// + /// for i in 0..100 { + /// let _ = panic::catch_unwind(AssertUnwindSafe(|| { + /// once.call_once_force(|_| { + /// if i < 6 { + /// panic!(); + /// } + /// counter = i; + /// }) + /// })); + /// } + /// + /// assert_eq!(counter, 6); + /// + /// ``` pub fn call_once_force(&self, f: F) where F: FnOnce(ROnceState), @@ -284,48 +274,43 @@ pub enum ROnceState { } impl ROnceState { - /** - Whether the ROnce is poisoned,requiring call_once_force to run. - - # Example - - ``` - use abi_stable::external_types::ROnce; - - use std::panic::AssertUnwindSafe; - - let once=ROnce::new(); - - let _=std::panic::catch_unwind(AssertUnwindSafe(||{ - once.call_once(|| panic!() ); - })); - - assert!(once.state().poisoned()); - - ``` - - */ + /// Whether the ROnce is poisoned,requiring call_once_force to run. + /// + /// # Example + /// + /// ``` + /// use abi_stable::external_types::ROnce; + /// + /// use std::panic::AssertUnwindSafe; + /// + /// let once = ROnce::new(); + /// + /// let _ = std::panic::catch_unwind(AssertUnwindSafe(|| { + /// once.call_once(|| panic!()); + /// })); + /// + /// assert!(once.state().poisoned()); + /// + /// ``` + /// pub fn poisoned(&self) -> bool { matches!(self, ROnceState::Poisoned) } - /** - Whether the ROnce has already finished running. - - # Example - - ``` - use abi_stable::external_types::ROnce; - - let once=ROnce::new(); - - once.call_once(|| () ); - - assert!(once.state().done()); - - ``` - - */ + /// Whether the ROnce has already finished running. + /// + /// # Example + /// + /// ``` + /// use abi_stable::external_types::ROnce; + /// + /// let once = ROnce::new(); + /// + /// once.call_once(|| ()); + /// + /// assert!(once.state().done()); + /// + /// ``` pub fn done(&self) -> bool { matches!(self, ROnceState::Done) } diff --git a/abi_stable/src/external_types/parking_lot/rw_lock.rs b/abi_stable/src/external_types/parking_lot/rw_lock.rs index 16e6e8d0..98f92a72 100644 --- a/abi_stable/src/external_types/parking_lot/rw_lock.rs +++ b/abi_stable/src/external_types/parking_lot/rw_lock.rs @@ -35,41 +35,39 @@ fn assert_lock_size() { let _assert_size: [(); mem::size_of::() - RAW_LOCK_SIZE]; } -/** -A read-write lock that allows dynamic mutable/shared borrows of shared data. - -RRwLock allows either multiple shared locks,or a single write lock. - -# Poisoning - -As opposed to the standard library version of this type, -this rwlock type does not use poisoning, -simply unlocking the lock when a panic happens. - -# Example - -``` -use abi_stable::external_types::RRwLock; - -static LOCK:RRwLock=RRwLock::new(0); - -let guard=std::thread::spawn(||{ - for _ in 0..100 { - *LOCK.write()+=1; - } -}); - -for _ in 0..100 { - *LOCK.write()+=1; -} - -guard.join().unwrap(); - -assert_eq!(*LOCK.read(),200); - -``` - -*/ +/// A read-write lock that allows dynamic mutable/shared borrows of shared data. +/// +/// RRwLock allows either multiple shared locks,or a single write lock. +/// +/// # Poisoning +/// +/// As opposed to the standard library version of this type, +/// this rwlock type does not use poisoning, +/// simply unlocking the lock when a panic happens. +/// +/// # Example +/// +/// ``` +/// use abi_stable::external_types::RRwLock; +/// +/// static LOCK: RRwLock = RRwLock::new(0); +/// +/// let guard = std::thread::spawn(|| { +/// for _ in 0..100 { +/// *LOCK.write() += 1; +/// } +/// }); +/// +/// for _ in 0..100 { +/// *LOCK.write() += 1; +/// } +/// +/// guard.join().unwrap(); +/// +/// assert_eq!(*LOCK.read(), 200); +/// +/// ``` +/// #[repr(C)] #[derive(StableAbi)] pub struct RRwLock { @@ -78,13 +76,11 @@ pub struct RRwLock { vtable: VTable_Ref, } -/** -A read guard,which allows shared access to the data inside the `RRwLock`. - -There can be many of these for the same RRwLock at any given time. - -When dropped this will unlock the rwlock. -*/ +/// A read guard,which allows shared access to the data inside the `RRwLock`. +/// +/// There can be many of these for the same RRwLock at any given time. +/// +/// When dropped this will unlock the rwlock. #[repr(transparent)] #[derive(StableAbi)] #[sabi(bound = "T:'a")] @@ -94,13 +90,11 @@ pub struct RReadGuard<'a, T> { _marker: PhantomData<(&'a T, UnsyncUnsend)>, } -/** -A write guard,which allows mutable access to the data inside the `RRwLock`. - -There can be only of these for the same RRwLock at any given time. - -When dropped this will unlock the rwlock. -*/ +/// A write guard,which allows mutable access to the data inside the `RRwLock`. +/// +/// There can be only of these for the same RRwLock at any given time. +/// +/// When dropped this will unlock the rwlock. #[repr(transparent)] #[derive(StableAbi)] #[sabi(bound = "T:'a")] @@ -120,9 +114,9 @@ impl RRwLock { /// ``` /// use abi_stable::external_types::RRwLock; /// - /// static LOCK:RRwLock>=RRwLock::new(None); + /// static LOCK: RRwLock> = RRwLock::new(None); /// - /// let lock=RRwLock::new(0); + /// let lock = RRwLock::new(0); /// /// ``` pub const fn new(value: T) -> Self { @@ -161,9 +155,9 @@ impl RRwLock { /// ``` /// use abi_stable::external_types::RRwLock; /// - /// let lock=RRwLock::new("hello".to_string()); + /// let lock = RRwLock::new("hello".to_string()); /// - /// assert_eq!(lock.into_inner().as_str(),"hello"); + /// assert_eq!(lock.into_inner().as_str(), "hello"); /// /// ``` #[inline] @@ -180,11 +174,11 @@ impl RRwLock { /// ``` /// use abi_stable::external_types::RRwLock; /// - /// let mut lock=RRwLock::new("Hello".to_string()); + /// let mut lock = RRwLock::new("Hello".to_string()); /// /// lock.get_mut().push_str(", World!"); /// - /// assert_eq!(lock.read().as_str(),"Hello, World!"); + /// assert_eq!(lock.read().as_str(), "Hello, World!"); /// /// ``` #[inline] @@ -192,61 +186,58 @@ impl RRwLock { unsafe { &mut *self.data.get() } } - /** - Acquires a lock for reading,blocking the current thread until it can. - - This function returns a read guard,which releases read access when it is dropped. - - Trying to lock the rwlock for reading in the same thread that has write - access to the same rwlock will cause a deadlock. - - # Example - - ``` - use abi_stable::external_types::RRwLock; - - static LOCK:RRwLock=RRwLock::new(0); - - *LOCK.write()+=4; - - let read_guard_a=LOCK.read(); - let read_guard_b=LOCK.read(); - - assert_eq!(*read_guard_a,4); - assert_eq!(*read_guard_b,4); - - ``` - - */ + /// Acquires a lock for reading,blocking the current thread until it can. + /// + /// This function returns a read guard,which releases read access when it is dropped. + /// + /// Trying to lock the rwlock for reading in the same thread that has write + /// access to the same rwlock will cause a deadlock. + /// + /// # Example + /// + /// ``` + /// use abi_stable::external_types::RRwLock; + /// + /// static LOCK: RRwLock = RRwLock::new(0); + /// + /// *LOCK.write() += 4; + /// + /// let read_guard_a = LOCK.read(); + /// let read_guard_b = LOCK.read(); + /// + /// assert_eq!(*read_guard_a, 4); + /// assert_eq!(*read_guard_b, 4); + /// + /// ``` + /// #[inline] pub fn read(&self) -> RReadGuard<'_, T> { self.vtable().lock_shared()(&self.raw_lock); self.read_guard() } - /** - Attemps to acquire a lock for reading,failing if it is locked for writing. - - Returns the read guard if the rwlock can be immediately acquired,otherwise returns RNone. - - # Example - - ``` - use abi_stable::external_types::RRwLock; - - static LOCK:RRwLock=RRwLock::new(0); - - let mut write_guard=LOCK.write(); - assert!(LOCK.try_read().is_none()); - - *write_guard+=4; - drop(write_guard); - - assert_eq!(*LOCK.try_read().unwrap(),4); - - ``` - - */ + /// Attemps to acquire a lock for reading,failing if it is locked for writing. + /// + /// Returns the read guard if the rwlock can be immediately acquired,otherwise returns RNone. + /// + /// # Example + /// + /// ``` + /// use abi_stable::external_types::RRwLock; + /// + /// static LOCK: RRwLock = RRwLock::new(0); + /// + /// let mut write_guard = LOCK.write(); + /// + /// assert!(LOCK.try_read().is_none()); + /// + /// *write_guard += 4; + /// drop(write_guard); + /// + /// assert_eq!(*LOCK.try_read().unwrap(), 4); + /// + /// ``` + /// #[inline] pub fn try_read(&self) -> ROption> { if self.vtable().try_lock_shared()(&self.raw_lock) { @@ -256,37 +247,31 @@ impl RRwLock { } } - /** - Attempts to acquire a lock for reading,for the timeout duration. - - Once the timeout is reached,this will return None, - otherwise it will return the read guard. - - - # Example - - ``` - use abi_stable::{ - external_types::RRwLock, - std_types::RDuration, - }; - - static LOCK:RRwLock=RRwLock::new(0); - - static DUR:RDuration=RDuration::from_millis(1); - - let mut write_guard=LOCK.write(); - - assert!(LOCK.try_read_for(DUR).is_none()); - - *write_guard+=7; - drop(write_guard); - - assert_eq!(*LOCK.try_read_for(DUR).unwrap(),7); - - ``` - - */ + /// Attempts to acquire a lock for reading,for the timeout duration. + /// + /// Once the timeout is reached,this will return None, + /// otherwise it will return the read guard. + /// + /// + /// # Example + /// + /// ``` + /// use abi_stable::{external_types::RRwLock, std_types::RDuration}; + /// + /// static LOCK: RRwLock = RRwLock::new(0); + /// + /// static DUR: RDuration = RDuration::from_millis(1); + /// + /// let mut write_guard = LOCK.write(); + /// + /// assert!(LOCK.try_read_for(DUR).is_none()); + /// + /// *write_guard += 7; + /// drop(write_guard); + /// + /// assert_eq!(*LOCK.try_read_for(DUR).unwrap(), 7); + /// + /// ``` #[inline] pub fn try_read_for(&self, timeout: RDuration) -> ROption> { if self.vtable().try_lock_shared_for()(&self.raw_lock, timeout) { @@ -296,57 +281,54 @@ impl RRwLock { } } - /** - Acquires a lock for writing,blocking the current thread until it can. - - This function returns a write guard,which releases write access when it is dropped. - - Trying to lock the rwlock in the same thread that has read or write - access to the same rwlock will cause a deadlock. - - # Example - - ``` - use abi_stable::external_types::RRwLock; - - let lock=RRwLock::new(0); - - let mut guard=lock.write(); - - *guard+=4; - - assert_eq!(*guard,4); - - ``` - */ + /// Acquires a lock for writing,blocking the current thread until it can. + /// + /// This function returns a write guard,which releases write access when it is dropped. + /// + /// Trying to lock the rwlock in the same thread that has read or write + /// access to the same rwlock will cause a deadlock. + /// + /// # Example + /// + /// ``` + /// use abi_stable::external_types::RRwLock; + /// + /// let lock = RRwLock::new(0); + /// + /// let mut guard = lock.write(); + /// + /// *guard += 4; + /// + /// assert_eq!(*guard, 4); + /// + /// ``` #[inline] pub fn write(&self) -> RWriteGuard<'_, T> { self.vtable().lock_exclusive()(&self.raw_lock); self.write_guard() } - /** - Attemps to acquire a lock for writing. - - Returns the write guard if the rwlock can be immediately acquired,otherwise returns RNone. - - - # Example - - ``` - use abi_stable::external_types::RRwLock; - - let lock=RRwLock::new(0); - - let mut guard=lock.write(); - - assert!( lock.try_write().is_none() ); - - *guard+=4; - - assert_eq!(*guard,4); - ``` - */ + /// Attemps to acquire a lock for writing. + /// + /// Returns the write guard if the rwlock can be immediately acquired,otherwise returns RNone. + /// + /// + /// # Example + /// + /// ``` + /// use abi_stable::external_types::RRwLock; + /// + /// let lock = RRwLock::new(0); + /// + /// let mut guard = lock.write(); + /// + /// assert!(lock.try_write().is_none()); + /// + /// *guard += 4; + /// + /// assert_eq!(*guard, 4); + /// + /// ``` #[inline] pub fn try_write(&self) -> ROption> { if self.vtable().try_lock_exclusive()(&self.raw_lock) { @@ -356,35 +338,30 @@ impl RRwLock { } } - /** - Attempts to acquire a lock for writing,for the timeout duration. - - Once the timeout is reached,this will return None, - otherwise it will return the write guard. - - - # Example - - ``` - use abi_stable::{ - external_types::RRwLock, - std_types::RDuration, - }; - - static DUR:RDuration=RDuration::from_millis(1); - - let lock=RRwLock::new(0); - - let mut write_guard=lock.try_write_for(DUR).unwrap(); - *write_guard+=4; - - assert!( lock.try_write_for(DUR).is_none() ); - - assert_eq!(*write_guard,4); - - ``` - - */ + /// Attempts to acquire a lock for writing,for the timeout duration. + /// + /// Once the timeout is reached,this will return None, + /// otherwise it will return the write guard. + /// + /// + /// # Example + /// + /// ``` + /// use abi_stable::{external_types::RRwLock, std_types::RDuration}; + /// + /// static DUR: RDuration = RDuration::from_millis(1); + /// + /// let lock = RRwLock::new(0); + /// + /// let mut write_guard = lock.try_write_for(DUR).unwrap(); + /// *write_guard += 4; + /// + /// assert!(lock.try_write_for(DUR).is_none()); + /// + /// assert_eq!(*write_guard, 4); + /// + /// ``` + /// #[inline] pub fn try_write_for(&self, timeout: RDuration) -> ROption> { if self.vtable().try_lock_exclusive_for()(&self.raw_lock, timeout) { diff --git a/abi_stable/src/external_types/serde_json.rs b/abi_stable/src/external_types/serde_json.rs index 5b3eb4f9..fca30820 100644 --- a/abi_stable/src/external_types/serde_json.rs +++ b/abi_stable/src/external_types/serde_json.rs @@ -12,79 +12,73 @@ use serde_json::{error::Error as JsonError, value::RawValue}; use crate::std_types::{RStr, RString}; -/** -An ffi-safe equivalent of `&serde_json::value::RawValue` - -# Example - -This defines a function that serializes a struct, -and deserializes the json into another one with `RawValueRef` fields. - -``` -use abi_stable::{ - external_types::RawValueRef, - std_types::{RStr,RResult,ROk,RErr,RString,RBoxError}, - sabi_extern_fn, -}; - -use serde::{Serialize,Deserialize}; - -use std::collections::HashMap; - -const JSON:&'static str=r##"{"hello":"world"}"##; - -let value=RawValueRef::try_from_str(JSON).unwrap(); - -assert_eq!( - serde_json::to_string(&value).unwrap().as_str(), - JSON -); - - -#[derive(Serialize)] -pub struct Pair{ - pub first:Vec, - pub second:HashMap, -} - -#[derive(Debug,Deserialize)] -pub struct PairDeserialize<'a>{ - #[serde(borrow)] - pub first:RawValueRef<'a>, - - #[serde(borrow)] - pub second:RawValueRef<'a>, -} - -#[sabi_extern_fn] -fn deserialize_data_structure<'de>( - input:RStr<'de>, -)->RResult,RBoxError>{ - - match serde_json::from_str::(input.into()) { - Ok(x)=>ROk(x), - Err(x)=>RErr(RBoxError::new(x)), - } -} - -# fn main(){ - -let json= - serde_json::to_string(&Pair{ - first:vec![0,1,2], - second:vec![ (RString::from("hello"),"world".into()) ].into_iter().collect(), - }).unwrap(); - -let pair=deserialize_data_structure(json.as_str().into()).unwrap(); - -assert_eq!(pair.first.get(),"[0,1,2]"); -assert_eq!(pair.second.get(),r##"{"hello":"world"}"##); - - -# } - -``` -*/ +/// An ffi-safe equivalent of `&serde_json::value::RawValue` +/// +/// # Example +/// +/// This defines a function that serializes a struct, +/// and deserializes the json into another one with `RawValueRef` fields. +/// +/// ``` +/// use abi_stable::{ +/// external_types::RawValueRef, +/// sabi_extern_fn, +/// std_types::{RBoxError, RErr, ROk, RResult, RStr, RString}, +/// }; +/// +/// use serde::{Deserialize, Serialize}; +/// +/// use std::collections::HashMap; +/// +/// const JSON: &'static str = r##"{"hello":"world"}"##; +/// +/// let value = RawValueRef::try_from_str(JSON).unwrap(); +/// +/// assert_eq!(serde_json::to_string(&value).unwrap().as_str(), JSON); +/// +/// #[derive(Serialize)] +/// pub struct Pair { +/// pub first: Vec, +/// pub second: HashMap, +/// } +/// +/// #[derive(Debug, Deserialize)] +/// pub struct PairDeserialize<'a> { +/// #[serde(borrow)] +/// pub first: RawValueRef<'a>, +/// +/// #[serde(borrow)] +/// pub second: RawValueRef<'a>, +/// } +/// +/// #[sabi_extern_fn] +/// fn deserialize_data_structure<'de>( +/// input: RStr<'de>, +/// ) -> RResult, RBoxError> { +/// match serde_json::from_str::(input.into()) { +/// Ok(x) => ROk(x), +/// Err(x) => RErr(RBoxError::new(x)), +/// } +/// } +/// +/// # fn main(){ +/// +/// let json = serde_json::to_string(&Pair { +/// first: vec![0, 1, 2], +/// second: vec![(RString::from("hello"), "world".into())] +/// .into_iter() +/// .collect(), +/// }) +/// .unwrap(); +/// +/// let pair = deserialize_data_structure(json.as_str().into()).unwrap(); +/// +/// assert_eq!(pair.first.get(), "[0,1,2]"); +/// assert_eq!(pair.second.get(), r##"{"hello":"world"}"##); +/// +/// # } +/// +/// ``` #[repr(transparent)] #[derive(StableAbi, Copy, Clone)] pub struct RawValueRef<'a> { @@ -92,64 +86,51 @@ pub struct RawValueRef<'a> { } impl<'a> RawValueRef<'a> { - /** - Converts a `&str` to a `RawValueRef<'a>` without checking whether it is valid JSON. - - # Safety - - `input` must be valid JSON and contain no leading or trailing whitespace. - - # Example - - ``` - use abi_stable::external_types::RawValueRef; - - const JSON:&'static str=r##"{"huh":"that is interesting"}"##; - - let value=unsafe{ RawValueRef::from_str_unchecked(JSON) }; - - assert_eq!( - serde_json::to_string(&value).unwrap().as_str(), - JSON - ); - ``` - - */ + /// Converts a `&str` to a `RawValueRef<'a>` without checking whether it is valid JSON. + /// + /// # Safety + /// + /// `input` must be valid JSON and contain no leading or trailing whitespace. + /// + /// # Example + /// + /// ``` + /// use abi_stable::external_types::RawValueRef; + /// + /// const JSON: &'static str = r##"{"huh":"that is interesting"}"##; + /// + /// let value = unsafe { RawValueRef::from_str_unchecked(JSON) }; + /// + /// assert_eq!(serde_json::to_string(&value).unwrap().as_str(), JSON); + /// + /// ``` pub unsafe fn from_str_unchecked(input: &'a str) -> RawValueRef<'a> { Self { ref_: RStr::from(input), } } - /** - Converts a `RStr<'a>` to a `RawValueRef<'a>` without checking whether it is valid JSON. - - # Safety - - `input` must be valid JSON and contain no leading or trailing whitespace. - - - # Example - - ``` - use abi_stable::{ - external_types::RawValueRef, - std_types::RStr, - }; - - const JSON:&'static str=r##"{"huh":"that is interesting"}"##; - - let json_rstr=RStr::from(JSON); - let value=unsafe{ RawValueRef::from_rstr_unchecked(json_rstr) }; - - assert_eq!( - serde_json::to_string(&value).unwrap().as_str(), - JSON - ); - ``` - - - */ + /// Converts a `RStr<'a>` to a `RawValueRef<'a>` without checking whether it is valid JSON. + /// + /// # Safety + /// + /// `input` must be valid JSON and contain no leading or trailing whitespace. + /// + /// + /// # Example + /// + /// ``` + /// use abi_stable::{external_types::RawValueRef, std_types::RStr}; + /// + /// const JSON: &'static str = r##"{"huh":"that is interesting"}"##; + /// + /// let json_rstr = RStr::from(JSON); + /// let value = unsafe { RawValueRef::from_rstr_unchecked(json_rstr) }; + /// + /// assert_eq!(serde_json::to_string(&value).unwrap().as_str(), JSON); + /// ``` + /// + /// pub unsafe fn from_rstr_unchecked(input: RStr<'a>) -> RawValueRef<'a> { Self { ref_: input } } @@ -161,16 +142,13 @@ impl<'a> RawValueRef<'a> { /// # Example /// /// ``` - /// use abi_stable::{ - /// external_types::RawValueRef, - /// std_types::RStr, - /// }; + /// use abi_stable::{external_types::RawValueRef, std_types::RStr}; /// - /// const JSON:&'static str=r##"{"nope":"oof"}"##; + /// const JSON: &'static str = r##"{"nope":"oof"}"##; /// - /// let raw=RawValueRef::try_from_str(JSON).unwrap(); + /// let raw = RawValueRef::try_from_str(JSON).unwrap(); /// - /// assert_eq!( raw.get(), JSON ); + /// assert_eq!(raw.get(), JSON); /// /// ``` #[inline] @@ -185,11 +163,11 @@ impl<'a> RawValueRef<'a> { /// ``` /// use abi_stable::external_types::RawValueRef; /// - /// const JSON:&'static str=r##"{"huh":1007}"##; + /// const JSON: &'static str = r##"{"huh":1007}"##; /// - /// let raw=serde_json::from_str::>(JSON).unwrap(); + /// let raw = serde_json::from_str::>(JSON).unwrap(); /// - /// assert_eq!( raw.get(), JSON ); + /// assert_eq!(raw.get(), JSON); /// /// ``` #[inline] @@ -202,16 +180,13 @@ impl<'a> RawValueRef<'a> { /// # Example /// /// ``` - /// use abi_stable::{ - /// external_types::RawValueRef, - /// std_types::RStr, - /// }; + /// use abi_stable::{external_types::RawValueRef, std_types::RStr}; /// - /// const JSON:&'static str=r##"{"bugs":"life"}"##; + /// const JSON: &'static str = r##"{"bugs":"life"}"##; /// - /// let raw=serde_json::from_str::>(JSON).unwrap(); + /// let raw = serde_json::from_str::>(JSON).unwrap(); /// - /// assert_eq!( raw.get_rstr(), RStr::from(JSON) ); + /// assert_eq!(raw.get_rstr(), RStr::from(JSON)); /// /// ``` #[inline] @@ -267,76 +242,69 @@ impl<'de: 'a, 'a> Deserialize<'de> for RawValueRef<'a> { /////////////////////////////////////////////////////////////////////////////// -/** -An ffi-safe equivalent of `Box` - - -# Example - -This defines a function that serializes a struct, -and deserializes the json into another one with `RawValueBox` fields. - -``` -use abi_stable::{ - external_types::RawValueBox, - std_types::{RStr,RResult,ROk,RErr,RString,RBoxError}, - sabi_extern_fn, -}; - -use serde::{Serialize,Deserialize}; - - -const JSON:&'static str=r##"{"hello":"world"}"##; - -let value=RawValueBox::try_from_string(JSON.to_string()).unwrap(); - -assert_eq!( - serde_json::to_string(&value).unwrap().as_str(), - JSON -); - - -#[derive(Serialize)] -pub struct Pair{ - pub first:u64, - pub second:RString, -} - -#[derive(Debug,Deserialize)] -pub struct PairDeserialize{ - pub first:RawValueBox, - pub second:RawValueBox, -} - - -#[sabi_extern_fn] -fn deserialize_data_structure(input:RStr<'_>)->RResult{ - match serde_json::from_str::(input.into()) { - Ok(x)=>ROk(x), - Err(x)=>RErr(RBoxError::new(x)), - } -} - - -# fn main(){ - -let json= - serde_json::to_string(&Pair{ - first:99, - second:"How many apples?".into(), - }).unwrap(); - -let pair=deserialize_data_structure(json.as_str().into()).unwrap(); - -assert_eq!(pair.first.get(),"99"); -assert_eq!(pair.second.get(),r##""How many apples?"}"##); - - -# } - -``` - -*/ +/// An ffi-safe equivalent of `Box` +/// +/// +/// # Example +/// +/// This defines a function that serializes a struct, +/// and deserializes the json into another one with `RawValueBox` fields. +/// +/// ``` +/// use abi_stable::{ +/// external_types::RawValueBox, +/// sabi_extern_fn, +/// std_types::{RBoxError, RErr, ROk, RResult, RStr, RString}, +/// }; +/// +/// use serde::{Deserialize, Serialize}; +/// +/// const JSON: &'static str = r##"{"hello":"world"}"##; +/// +/// let value = RawValueBox::try_from_string(JSON.to_string()).unwrap(); +/// +/// assert_eq!(serde_json::to_string(&value).unwrap().as_str(), JSON); +/// +/// #[derive(Serialize)] +/// pub struct Pair { +/// pub first: u64, +/// pub second: RString, +/// } +/// +/// #[derive(Debug, Deserialize)] +/// pub struct PairDeserialize { +/// pub first: RawValueBox, +/// pub second: RawValueBox, +/// } +/// +/// #[sabi_extern_fn] +/// fn deserialize_data_structure( +/// input: RStr<'_>, +/// ) -> RResult { +/// match serde_json::from_str::(input.into()) { +/// Ok(x) => ROk(x), +/// Err(x) => RErr(RBoxError::new(x)), +/// } +/// } +/// +/// # fn main(){ +/// +/// let json = serde_json::to_string(&Pair { +/// first: 99, +/// second: "How many apples?".into(), +/// }) +/// .unwrap(); +/// +/// let pair = deserialize_data_structure(json.as_str().into()).unwrap(); +/// +/// assert_eq!(pair.first.get(), "99"); +/// assert_eq!(pair.second.get(), r##""How many apples?"}"##); +/// +/// # } +/// +/// +/// ``` +/// #[repr(transparent)] #[derive(StableAbi, Clone)] pub struct RawValueBox { @@ -344,30 +312,25 @@ pub struct RawValueBox { } impl RawValueBox { - /** - Converts a `String` to an `RawValueBox` without checking whether it is valid JSON. - - # Safety - - `input` must be valid JSON and contain no leading or trailing whitespace. - - - # Example - - ``` - use abi_stable::external_types::RawValueBox; - - const JSON:&'static str=r##"{"huh":"that is interesting"}"##; - - let value=unsafe{ RawValueBox::from_string_unchecked(JSON.to_string()) }; - - assert_eq!( - serde_json::to_string(&value).unwrap().as_str(), - JSON - ); - ``` - - */ + /// Converts a `String` to an `RawValueBox` without checking whether it is valid JSON. + /// + /// # Safety + /// + /// `input` must be valid JSON and contain no leading or trailing whitespace. + /// + /// + /// # Example + /// + /// ``` + /// use abi_stable::external_types::RawValueBox; + /// + /// const JSON: &'static str = r##"{"huh":"that is interesting"}"##; + /// + /// let value = unsafe { RawValueBox::from_string_unchecked(JSON.to_string()) }; + /// + /// assert_eq!(serde_json::to_string(&value).unwrap().as_str(), JSON); + /// ``` + /// #[inline] pub unsafe fn from_string_unchecked(input: String) -> RawValueBox { Self { @@ -375,35 +338,26 @@ impl RawValueBox { } } - /** - Converts an `RString` to an `RawValueBox` without checking whether it is valid JSON. - - # Safety - - `input` must be valid JSON and contain no leading or trailing whitespace. - - - # Example - - ``` - use abi_stable::{ - external_types::RawValueBox, - std_types::RString, - }; - - const JSON:&'static str=r##"{"huh":"that is interesting"}"##; - - let json_rstring=RString::from(JSON); - let value=unsafe{ RawValueBox::from_rstring_unchecked(json_rstring) }; - - assert_eq!( - serde_json::to_string(&value).unwrap().as_str(), - JSON - ); - ``` - - - */ + /// Converts an `RString` to an `RawValueBox` without checking whether it is valid JSON. + /// + /// # Safety + /// + /// `input` must be valid JSON and contain no leading or trailing whitespace. + /// + /// + /// # Example + /// + /// ``` + /// use abi_stable::{external_types::RawValueBox, std_types::RString}; + /// + /// const JSON: &'static str = r##"{"huh":"that is interesting"}"##; + /// + /// let json_rstring = RString::from(JSON); + /// let value = unsafe { RawValueBox::from_rstring_unchecked(json_rstring) }; + /// + /// assert_eq!(serde_json::to_string(&value).unwrap().as_str(), JSON); + /// ``` + /// #[inline] pub unsafe fn from_rstring_unchecked(input: RString) -> RawValueBox { Self { string: input } @@ -416,16 +370,13 @@ impl RawValueBox { /// # Example /// /// ``` - /// use abi_stable::{ - /// external_types::RawValueBox, - /// std_types::RString, - /// }; + /// use abi_stable::{external_types::RawValueBox, std_types::RString}; /// - /// const JSON:&'static str=r##"{"nope":"oof"}"##; + /// const JSON: &'static str = r##"{"nope":"oof"}"##; /// - /// let raw=RawValueBox::try_from_string(JSON.to_string()).unwrap(); + /// let raw = RawValueBox::try_from_string(JSON.to_string()).unwrap(); /// - /// assert_eq!( raw.get(), JSON ); + /// assert_eq!(raw.get(), JSON); /// /// ``` #[inline] @@ -440,11 +391,11 @@ impl RawValueBox { /// ``` /// use abi_stable::external_types::RawValueBox; /// - /// const JSON:&'static str=r##"{"huh":1007}"##; + /// const JSON: &'static str = r##"{"huh":1007}"##; /// - /// let raw=serde_json::from_str::(JSON).unwrap(); + /// let raw = serde_json::from_str::(JSON).unwrap(); /// - /// assert_eq!( raw.get(), JSON ); + /// assert_eq!(raw.get(), JSON); /// /// ``` #[inline] @@ -457,16 +408,13 @@ impl RawValueBox { /// # Example /// /// ``` - /// use abi_stable::{ - /// external_types::RawValueBox, - /// std_types::RStr, - /// }; + /// use abi_stable::{external_types::RawValueBox, std_types::RStr}; /// - /// const JSON:&'static str=r##"{"bugs":"life"}"##; + /// const JSON: &'static str = r##"{"bugs":"life"}"##; /// - /// let raw=serde_json::from_str::(JSON).unwrap(); + /// let raw = serde_json::from_str::(JSON).unwrap(); /// - /// assert_eq!( raw.get_rstr(), RStr::from(JSON) ); + /// assert_eq!(raw.get_rstr(), RStr::from(JSON)); /// /// ``` #[inline] @@ -479,16 +427,13 @@ impl RawValueBox { /// # Example /// /// ``` - /// use abi_stable::external_types::{RawValueBox,RawValueRef}; + /// use abi_stable::external_types::{RawValueBox, RawValueRef}; /// - /// const JSON:&'static str=r##"{"bugs":"life"}"##; + /// const JSON: &'static str = r##"{"bugs":"life"}"##; /// - /// let raw=serde_json::from_str::(JSON).unwrap(); + /// let raw = serde_json::from_str::(JSON).unwrap(); /// - /// assert_eq!( - /// raw.get(), - /// RawValueRef::try_from_str(JSON).unwrap().get() - /// ); + /// assert_eq!(raw.get(), RawValueRef::try_from_str(JSON).unwrap().get()); /// /// ``` #[inline] diff --git a/abi_stable/src/library/lib_header.rs b/abi_stable/src/library/lib_header.rs index c866575e..a25ce3d2 100644 --- a/abi_stable/src/library/lib_header.rs +++ b/abi_stable/src/library/lib_header.rs @@ -101,43 +101,41 @@ impl LibHeader { Ok(()) } - /** - Checks that the library is compatible,returning the root module on success. - - It checks that these are compatible: - - - The version number of the library - - - The layout of the root module. - - # Warning - - If this function is called within a dynamic library, - it must be called at or after the function that exports its root module is called. - - **DO NOT** call this in the static initializer of a dynamic library, - since this library relies on setting up its global state before - calling the root module loader. - - # Errors - - This returns these errors: - - - `LibraryError::ParseVersionError`: - If the version strings in the library can't be parsed as version numbers, - this can only happen if the version strings are manually constructed. - - - `LibraryError::IncompatibleVersionNumber`: - If the version number of the library is incompatible. - - - `LibraryError::AbiInstability`: - If the layout of the root module is not the expected one. - - - `LibraryError::RootModule` : - If the root module initializer returned an error or panicked. - - - */ + /// Checks that the library is compatible, returning the root module on success. + /// + /// It checks that these are compatible: + /// + /// - The version number of the library + /// + /// - The layout of the root module. + /// + /// # Warning + /// + /// If this function is called within a dynamic library, + /// it must be called at or after the function that exports its root module is called. + /// + /// **DO NOT** call this in the static initializer of a dynamic library, + /// since this library relies on setting up its global state before + /// calling the root module loader. + /// + /// # Errors + /// + /// This returns these errors: + /// + /// - `LibraryError::ParseVersionError`: + /// If the version strings in the library can't be parsed as version numbers, + /// this can only happen if the version strings are manually constructed. + /// + /// - `LibraryError::IncompatibleVersionNumber`: + /// If the version number of the library is incompatible. + /// + /// - `LibraryError::AbiInstability`: + /// If the layout of the root module is not the expected one. + /// + /// - `LibraryError::RootModule` : + /// If the root module initializer returned an error or panicked. + /// + /// pub fn init_root_module(&self) -> Result where M: RootModule, @@ -146,42 +144,40 @@ impl LibHeader { self.check_layout::() } - /** - Checks that the version number of the library is compatible, - returning the root module on success. - - This function transmutes the root module type, - without checking that the layout is compatible first. - - # Warning - - If this function is called within a dynamic library, - it must be called at or after the function that exports its root module is called. - - **DO NOT** call this in the static initializer of a dynamic library, - since this library relies on setting up its global state before - calling the root module loader. - - # Safety - - The caller must ensure that `M` has the expected layout. - - # Errors - - This returns these errors: - - - `LibraryError::ParseVersionError`: - If the version strings in the library can't be parsed as version numbers, - this can only happen if the version strings are manually constructed. - - - `LibraryError::IncompatibleVersionNumber`: - If the version number of the library is incompatible. - - - `LibraryError::RootModule` : - If the root module initializer returned an error or panicked. - - - */ + /// Checks that the version number of the library is compatible, + /// returning the root module on success. + /// + /// This function transmutes the root module type, + /// without checking that the layout is compatible first. + /// + /// # Warning + /// + /// If this function is called within a dynamic library, + /// it must be called at or after the function that exports its root module is called. + /// + /// **DO NOT** call this in the static initializer of a dynamic library, + /// since this library relies on setting up its global state before + /// calling the root module loader. + /// + /// # Safety + /// + /// The caller must ensure that `M` has the expected layout. + /// + /// # Errors + /// + /// This returns these errors: + /// + /// - `LibraryError::ParseVersionError`: + /// If the version strings in the library can't be parsed as version numbers, + /// this can only happen if the version strings are manually constructed. + /// + /// - `LibraryError::IncompatibleVersionNumber`: + /// If the version number of the library is incompatible. + /// + /// - `LibraryError::RootModule` : + /// If the root module initializer returned an error or panicked. + /// + /// pub unsafe fn init_root_module_with_unchecked_layout(&self) -> Result where M: RootModule, @@ -259,23 +255,21 @@ impl LibHeader { } } - /** - Gets the root module without checking that the layout of `M` is the expected one. - This is effectively a transmute. - - This is useful if a user keeps a cache of which dynamic libraries - have been checked for layout compatibility. - - # Safety - - The caller must ensure that `M` has the expected layout. - - # Errors - - This function can return a `RootModuleError` - because the root module failed to initialize. - - */ + /// Gets the root module without checking that the layout of `M` is the expected one. + /// This is effectively a transmute. + /// + /// This is useful if a user keeps a cache of which dynamic libraries + /// have been checked for layout compatibility. + /// + /// # Safety + /// + /// The caller must ensure that `M` has the expected layout. + /// + /// # Errors + /// + /// This function can return a `RootModuleError` + /// because the root module failed to initialize. + /// pub unsafe fn unchecked_layout(&self) -> Result where M: PrefixRefTrait, diff --git a/abi_stable/src/library/root_mod_trait.rs b/abi_stable/src/library/root_mod_trait.rs index 44ff5c90..d6889524 100644 --- a/abi_stable/src/library/root_mod_trait.rs +++ b/abi_stable/src/library/root_mod_trait.rs @@ -15,16 +15,12 @@ use crate::{marker_type::NonOwningPhantom, prefix_type::PrefixRefTrait, utils::l /// ### Basic /// /// ```rust -/// use abi_stable::{ -/// library::RootModule, -/// sabi_types::VersionStrings, -/// StableAbi, -/// }; +/// use abi_stable::{library::RootModule, sabi_types::VersionStrings, StableAbi}; /// /// #[repr(C)] /// #[derive(StableAbi)] /// #[sabi(kind(Prefix(prefix_ref = "Module_Ref", prefix_fields = "Module_Prefix")))] -/// pub struct Module{ +/// pub struct Module { /// pub first: u8, /// // The `#[sabi(last_prefix_field)]` attribute here means that this is /// // the last field in this module that was defined in the @@ -34,12 +30,13 @@ use crate::{marker_type::NonOwningPhantom, prefix_type::PrefixRefTrait, utils::l /// pub third: u32, /// } /// impl RootModule for Module_Ref { -/// abi_stable::declare_root_module_statics!{Module_Ref} +/// abi_stable::declare_root_module_statics! {Module_Ref} /// const BASE_NAME: &'static str = "example_root_module"; /// const NAME: &'static str = "example_root_module"; /// const VERSION_STRINGS: VersionStrings = abi_stable::package_version_strings!(); /// } /// + /// # fn main(){} /// ``` pub trait RootModule: Sized + StableAbi + PrefixRefTrait + 'static { @@ -88,23 +85,19 @@ pub trait RootModule: Sized + StableAbi + PrefixRefTrait + 'static { /// fn root_module_statics() -> &'static RootModuleStatics; - /** - Gets the root module,returning None if the module is not yet loaded. - */ + /// Gets the root module,returning None if the module is not yet loaded. #[inline] fn get_module() -> Option { Self::root_module_statics().root_mod.get() } - /** - Gets the RawLibrary of the module, - returning None if the dynamic library failed to load - (it doesn't exist or layout checking failed). - - Note that if the root module is initialized using `Self::load_module_with`, - this will return None even though `Self::get_module` does not. - - */ + /// Gets the RawLibrary of the module, + /// returning None if the dynamic library failed to load + /// (it doesn't exist or layout checking failed). + /// + /// Note that if the root module is initialized using `Self::load_module_with`, + /// this will return None even though `Self::get_module` does not. + /// #[inline] fn get_raw_library() -> Option<&'static RawLibrary> { Self::root_module_statics().raw_lib.get() @@ -116,16 +109,12 @@ pub trait RootModule: Sized + StableAbi + PrefixRefTrait + 'static { RawLibrary::path_in_directory(directory, base_name, LibrarySuffix::NoSuffix) } - /** - - Loads the root module,with a closure which either - returns the root module or an error. - - If the root module was already loaded, - this will return the already loaded root module, - without calling the closure. - - */ + /// Loads the root module,with a closure which either + /// returns the root module or an error. + /// + /// If the root module was already loaded, + /// this will return the already loaded root module, + /// without calling the closure. fn load_module_with(f: F) -> Result where F: FnOnce() -> Result, @@ -133,50 +122,48 @@ pub trait RootModule: Sized + StableAbi + PrefixRefTrait + 'static { Self::root_module_statics().root_mod.try_init(f) } - /** - Loads this module from the path specified by `where_`, - first loading the dynamic library if it wasn't already loaded. - - Once the root module is loaded, - this will return the already loaded root module. - - # Warning - - If this function is called within a dynamic library, - it must be called either within the root module loader function or - after that function has been called. - - **DO NOT** call this in the static initializer of a dynamic library, - since this library relies on setting up its global state before - calling the root module loader. - - # Errors - - This will return these errors: - - - `LibraryError::OpenError`: - If the dynamic library itself could not be loaded. - - - `LibraryError::GetSymbolError`: - If the root module was not exported. - - - `LibraryError::InvalidAbiHeader`: - If the abi_stable version used by the library is not compatible. - - - `LibraryError::ParseVersionError`: - If the version strings in the library can't be parsed as version numbers, - this can only happen if the version strings are manually constructed. - - - `LibraryError::IncompatibleVersionNumber`: - If the version number of the library is incompatible. - - - `LibraryError::AbiInstability`: - If the layout of the root module is not the expected one. - - - `LibraryError::RootModule` : - If the root module initializer returned an error or panicked. - - */ + /// Loads this module from the path specified by `where_`, + /// first loading the dynamic library if it wasn't already loaded. + /// + /// Once the root module is loaded, + /// this will return the already loaded root module. + /// + /// # Warning + /// + /// If this function is called within a dynamic library, + /// it must be called either within the root module loader function or + /// after that function has been called. + /// + /// **DO NOT** call this in the static initializer of a dynamic library, + /// since this library relies on setting up its global state before + /// calling the root module loader. + /// + /// # Errors + /// + /// This will return these errors: + /// + /// - `LibraryError::OpenError`: + /// If the dynamic library itself could not be loaded. + /// + /// - `LibraryError::GetSymbolError`: + /// If the root module was not exported. + /// + /// - `LibraryError::InvalidAbiHeader`: + /// If the abi_stable version used by the library is not compatible. + /// + /// - `LibraryError::ParseVersionError`: + /// If the version strings in the library can't be parsed as version numbers, + /// this can only happen if the version strings are manually constructed. + /// + /// - `LibraryError::IncompatibleVersionNumber`: + /// If the version number of the library is incompatible. + /// + /// - `LibraryError::AbiInstability`: + /// If the layout of the root module is not the expected one. + /// + /// - `LibraryError::RootModule` : + /// If the root module initializer returned an error or panicked. + /// fn load_from(where_: LibraryPath<'_>) -> Result { let statics = Self::root_module_statics(); statics.root_mod.try_init(|| { @@ -211,32 +198,26 @@ pub trait RootModule: Sized + StableAbi + PrefixRefTrait + 'static { }) } - /** - - Loads this module from the directory specified by `where_`, - first loading the dynamic library if it wasn't already loaded. - - Once the root module is loaded, - this will return the already loaded root module. - - Warnings and Errors are detailed in [`load_from`](#method.load_from), - - */ + /// Loads this module from the directory specified by `where_`, + /// first loading the dynamic library if it wasn't already loaded. + /// + /// Once the root module is loaded, + /// this will return the already loaded root module. + /// + /// Warnings and Errors are detailed in [`load_from`](#method.load_from), + /// fn load_from_directory(where_: &Path) -> Result { Self::load_from(LibraryPath::Directory(where_)) } - /** - - Loads this module from the file at `path_`, - first loading the dynamic library if it wasn't already loaded. - - Once the root module is loaded, - this will return the already loaded root module. - - Warnings and Errors are detailed in [`load_from`](#method.load_from), - - */ + /// Loads this module from the file at `path_`, + /// first loading the dynamic library if it wasn't already loaded. + /// + /// Once the root module is loaded, + /// this will return the already loaded root module. + /// + /// Warnings and Errors are detailed in [`load_from`](#method.load_from), + /// fn load_from_file(path_: &Path) -> Result { Self::load_from(LibraryPath::FullPath(path_)) } @@ -264,47 +245,45 @@ where RawLibrary::load_at(&path) } -/** -Gets the LibHeader of a library. - -# Errors - -This will return these errors: - -- `LibraryError::GetSymbolError`: -If the root module was not exported. - -- `LibraryError::InvalidAbiHeader`: -If the abi_stable used by the library is not compatible. - -# Safety - -The LibHeader is implicitly tied to the lifetime of the library, -it will contain dangling `'static` references if the library is dropped before it does. - -*/ +/// Gets the LibHeader of a library. +/// +/// # Errors +/// +/// This will return these errors: +/// +/// - `LibraryError::GetSymbolError`: +/// If the root module was not exported. +/// +/// - `LibraryError::InvalidAbiHeader`: +/// If the abi_stable used by the library is not compatible. +/// +/// # Safety +/// +/// The LibHeader is implicitly tied to the lifetime of the library, +/// it will contain dangling `'static` references if the library is dropped before it does. +/// +/// pub unsafe fn lib_header_from_raw_library( raw_library: &RawLibrary, ) -> Result<&'static LibHeader, LibraryError> { unsafe { abi_header_from_raw_library(raw_library)?.upgrade() } } -/** -Gets the AbiHeaderRef of a library. - -# Errors - -This will return these errors: - -- `LibraryError::GetSymbolError`: -If the root module was not exported. - -# Safety - -The AbiHeaderRef is implicitly tied to the lifetime of the library, -it will contain dangling `'static` references if the library is dropped before it does. - -*/ +/// Gets the AbiHeaderRef of a library. +/// +/// # Errors +/// +/// This will return these errors: +/// +/// - `LibraryError::GetSymbolError`: +/// If the root module was not exported. +/// +/// # Safety +/// +/// The AbiHeaderRef is implicitly tied to the lifetime of the library, +/// it will contain dangling `'static` references if the library is dropped before it does. +/// +/// pub unsafe fn abi_header_from_raw_library( raw_library: &RawLibrary, ) -> Result { @@ -316,27 +295,26 @@ pub unsafe fn abi_header_from_raw_library( } } -/** -Gets the LibHeader of the library at the path. - -This leaks the underlying dynamic library, -if you need to do this without leaking you'll need to use -`lib_header_from_raw_library` instead. - -# Errors - -This will return these errors: - -- `LibraryError::OpenError`: -If the dynamic library itself could not be loaded. - -- `LibraryError::GetSymbolError`: -If the root module was not exported. - -- `LibraryError::InvalidAbiHeader`: -If the abi_stable version used by the library is not compatible. - -*/ +/// Gets the LibHeader of the library at the path. +/// +/// This leaks the underlying dynamic library, +/// if you need to do this without leaking you'll need to use +/// `lib_header_from_raw_library` instead. +/// +/// # Errors +/// +/// This will return these errors: +/// +/// - `LibraryError::OpenError`: +/// If the dynamic library itself could not be loaded. +/// +/// - `LibraryError::GetSymbolError`: +/// If the root module was not exported. +/// +/// - `LibraryError::InvalidAbiHeader`: +/// If the abi_stable version used by the library is not compatible. +/// +/// pub fn lib_header_from_path(path: &Path) -> Result<&'static LibHeader, LibraryError> { let raw_lib = RawLibrary::load_at(path)?; @@ -347,24 +325,23 @@ pub fn lib_header_from_path(path: &Path) -> Result<&'static LibHeader, LibraryEr Ok(library_getter) } -/** -Gets the AbiHeaderRef of the library at the path. - -This leaks the underlying dynamic library, -if you need to do this without leaking you'll need to use -`lib_header_from_raw_library` instead. - -# Errors - -This will return these errors: - -- `LibraryError::OpenError`: -If the dynamic library itself could not be loaded. - -- `LibraryError::GetSymbolError`: -If the root module was not exported. - -*/ +/// Gets the AbiHeaderRef of the library at the path. +/// +/// This leaks the underlying dynamic library, +/// if you need to do this without leaking you'll need to use +/// `lib_header_from_raw_library` instead. +/// +/// # Errors +/// +/// This will return these errors: +/// +/// - `LibraryError::OpenError`: +/// If the dynamic library itself could not be loaded. +/// +/// - `LibraryError::GetSymbolError`: +/// If the root module was not exported. +/// +/// pub fn abi_header_from_path(path: &Path) -> Result { let raw_lib = RawLibrary::load_at(path)?; diff --git a/abi_stable/src/macros/nul_str_macros.rs b/abi_stable/src/macros/nul_str_macros.rs index d9dfcd85..73dfe0a4 100644 --- a/abi_stable/src/macros/nul_str_macros.rs +++ b/abi_stable/src/macros/nul_str_macros.rs @@ -35,11 +35,14 @@ macro_rules! nul_str { /// ```rust /// use abi_stable::nulstr_trunc; /// -/// assert_eq!( nulstr_trunc!("Huh?").to_str_with_nul(), "Huh?\0" ); +/// assert_eq!(nulstr_trunc!("Huh?").to_str_with_nul(), "Huh?\0"); /// -/// assert_eq!( nulstr_trunc!("Hello!").to_str_with_nul(), "Hello!\0" ); +/// assert_eq!(nulstr_trunc!("Hello!").to_str_with_nul(), "Hello!\0"); /// -/// assert_eq!( nulstr_trunc!("Hello\0, world!").to_str_with_nul(), "Hello\0" ); +/// assert_eq!( +/// nulstr_trunc!("Hello\0, world!").to_str_with_nul(), +/// "Hello\0" +/// ); /// /// ``` /// @@ -72,7 +75,7 @@ macro_rules! nulstr_trunc { /// ```compile_fail /// use abi_stable::nulstr; /// -/// assert_eq!( nulstr!("Hello\0, world!").to_str_with_nul(), "Hello\0" ); +/// assert_eq!(nulstr!("Hello\0, world!").to_str_with_nul(), "Hello\0"); /// ``` /// /// [`NulStr`]: ./sabi_types/struct.NulStr.html diff --git a/abi_stable/src/nonexhaustive_enum/nonexhaustive.rs b/abi_stable/src/nonexhaustive_enum/nonexhaustive.rs index 61656ff2..1e4a4b0e 100644 --- a/abi_stable/src/nonexhaustive_enum/nonexhaustive.rs +++ b/abi_stable/src/nonexhaustive_enum/nonexhaustive.rs @@ -35,126 +35,120 @@ use serde::{de, ser, Deserialize, Deserializer, Serialize, Serializer}; #[cfg(all(test, not(feature = "only_new_tests")))] mod tests; -/** - -A generic type for all ffi-safe non-exhaustive enums. - -This type allows adding variants to enums it wraps in ABI compatible versions of a library. - -# Generic parameters - -### `E` - -This is the enum that this was constructed from, -and can be unwrapped back into if it's one of the valid variants in this context. - -### `S` - -The storage type,used to store the enum opaquely. - -This has to be at least the size and alignment of the wrapped enum. - -This is necessary because: - -- The compiler assumes that an enum cannot be a variant outside the ones it sees. - -- To give some flexibility to grow the enum in semver compatible versions of a library. - -### `I` - -The interface of the enum(it implements `InterfaceType`), -determining which traits are required when constructing `NonExhaustive<>` -and which are available afterwards. - -### Example - -Say that we define an error type for a library. - - -Version 1.0. -``` -use abi_stable::{ - StableAbi, - nonexhaustive_enum::{NonExhaustiveFor,NonExhaustive}, - std_types::RString, - sabi_trait, -}; - -#[repr(u8)] -#[derive(StableAbi,Debug,Clone,PartialEq)] -#[sabi(kind(WithNonExhaustive( - size="[usize;8]", - traits(Debug,Clone,PartialEq), -)))] -pub enum Error{ - #[doc(hidden)] - __NonExhaustive, - CouldNotFindItem{ - name:RString, - }, - OutOfStock{ - id:usize, - name:RString, - }, -} - - -fn returns_could_not_find_item(name:RString)->NonExhaustiveFor{ - let e=Error::CouldNotFindItem{name}; - NonExhaustive::new(e) -} - -fn returns_out_of_stock(id:usize,name:RString)->NonExhaustiveFor{ - let e=Error::OutOfStock{id,name}; - NonExhaustive::new(e) -} - -``` - -Then in 1.1 we add another error variant,returned only by new library functions. - -``` -use abi_stable::{ - StableAbi, - nonexhaustive_enum::{NonExhaustiveFor,NonExhaustive}, - std_types::RString, - sabi_trait, -}; - -#[repr(u8)] -#[derive(StableAbi,Debug,Clone,PartialEq)] -#[sabi(kind(WithNonExhaustive( - size="[usize;8]", - traits(Debug,Clone,PartialEq), -)))] -pub enum Error{ - #[doc(hidden)] - __NonExhaustive, - CouldNotFindItem{ - name:RString, - }, - OutOfStock{ - id:usize, - name:RString, - }, - InvalidItemId{ - id:usize, - }, -} - - -fn returns_invalid_item_id()->NonExhaustiveFor{ - NonExhaustive::new(Error::InvalidItemId{id:100}) -} - -``` - -If a library user attempted to unwrap `Error::InvalidItemId` -(using NonExhaustive::as_enum/as_enum_mut/into_enum) -with the 1.0 version of `Error` they would get an `Err(..)` back. - - -*/ +/// A generic type for all ffi-safe non-exhaustive enums. +/// +/// This type allows adding variants to enums it wraps in ABI compatible versions of a library. +/// +/// # Generic parameters +/// +/// ### `E` +/// +/// This is the enum that this was constructed from, +/// and can be unwrapped back into if it's one of the valid variants in this context. +/// +/// ### `S` +/// +/// The storage type,used to store the enum opaquely. +/// +/// This has to be at least the size and alignment of the wrapped enum. +/// +/// This is necessary because: +/// +/// - The compiler assumes that an enum cannot be a variant outside the ones it sees. +/// +/// - To give some flexibility to grow the enum in semver compatible versions of a library. +/// +/// ### `I` +/// +/// The interface of the enum(it implements `InterfaceType`), +/// determining which traits are required when constructing `NonExhaustive<>` +/// and which are available afterwards. +/// +/// ### Example +/// +/// Say that we define an error type for a library. +/// +/// +/// Version 1.0. +/// ``` +/// use abi_stable::{ +/// nonexhaustive_enum::{NonExhaustive, NonExhaustiveFor}, +/// sabi_trait, +/// std_types::RString, +/// StableAbi, +/// }; +/// +/// #[repr(u8)] +/// #[derive(StableAbi, Debug, Clone, PartialEq)] +/// #[sabi(kind(WithNonExhaustive( +/// size = "[usize;8]", +/// traits(Debug, Clone, PartialEq), +/// )))] +/// pub enum Error { +/// #[doc(hidden)] +/// __NonExhaustive, +/// CouldNotFindItem { +/// name: RString, +/// }, +/// OutOfStock { +/// id: usize, +/// name: RString, +/// }, +/// } +/// +/// fn returns_could_not_find_item(name: RString) -> NonExhaustiveFor { +/// let e = Error::CouldNotFindItem { name }; +/// NonExhaustive::new(e) +/// } +/// +/// fn returns_out_of_stock(id: usize, name: RString) -> NonExhaustiveFor { +/// let e = Error::OutOfStock { id, name }; +/// NonExhaustive::new(e) +/// } +/// +/// ``` +/// +/// Then in 1.1 we add another error variant,returned only by new library functions. +/// +/// ``` +/// use abi_stable::{ +/// nonexhaustive_enum::{NonExhaustive, NonExhaustiveFor}, +/// sabi_trait, +/// std_types::RString, +/// StableAbi, +/// }; +/// +/// #[repr(u8)] +/// #[derive(StableAbi, Debug, Clone, PartialEq)] +/// #[sabi(kind(WithNonExhaustive( +/// size = "[usize;8]", +/// traits(Debug, Clone, PartialEq), +/// )))] +/// pub enum Error { +/// #[doc(hidden)] +/// __NonExhaustive, +/// CouldNotFindItem { +/// name: RString, +/// }, +/// OutOfStock { +/// id: usize, +/// name: RString, +/// }, +/// InvalidItemId { +/// id: usize, +/// }, +/// } +/// +/// fn returns_invalid_item_id() -> NonExhaustiveFor { +/// NonExhaustive::new(Error::InvalidItemId { id: 100 }) +/// } +/// +/// ``` +/// +/// If a library user attempted to unwrap `Error::InvalidItemId` +/// (using NonExhaustive::as_enum/as_enum_mut/into_enum) +/// with the 1.0 version of `Error` they would get an `Err(..)` back. +/// #[repr(C)] #[derive(StableAbi)] #[sabi( @@ -188,13 +182,11 @@ pub type NonExhaustiveWI = NonExhaustive::DefaultSto pub type NonExhaustiveWS = NonExhaustive::DefaultInterface>; impl NonExhaustive { - /** - Constructs a `NonExhaustive<>` from `value` using its default interface and storage. - - # Panic - - This panics if the storage has an alignment or size smaller than that of `E`. - */ + /// Constructs a `NonExhaustive<>` from `value` using its default interface and storage. + /// + /// # Panic + /// + /// This panics if the storage has an alignment or size smaller than that of `E`. #[inline] pub fn new(value: E) -> Self where @@ -203,14 +195,12 @@ impl NonExhaustive { NonExhaustive::with_storage_and_interface(value) } - /** - Constructs a `NonExhaustive<>` from `value` using its default storage - and a custom interface. - - # Panic - - This panics if the storage has an alignment or size smaller than that of `E`. - */ + /// Constructs a `NonExhaustive<>` from `value` using its default storage + /// and a custom interface. + /// + /// # Panic + /// + /// This panics if the storage has an alignment or size smaller than that of `E`. #[inline] pub fn with_interface(value: E) -> Self where @@ -219,14 +209,12 @@ impl NonExhaustive { NonExhaustive::with_storage_and_interface(value) } - /** - Constructs a `NonExhaustive<>` from `value` using its default interface - and a custom storage. - - # Panic - - This panics if the storage has an alignment or size smaller than that of `E`. - */ + /// Constructs a `NonExhaustive<>` from `value` using its default interface + /// and a custom storage. + /// + /// # Panic + /// + /// This panics if the storage has an alignment or size smaller than that of `E`. #[inline] pub fn with_storage(value: E) -> Self where @@ -235,13 +223,11 @@ impl NonExhaustive { NonExhaustive::with_storage_and_interface(value) } - /** - Constructs a `NonExhaustive<>` from `value` using both a custom interface and storage. - - # Panic - - This panics if the storage has an alignment or size smaller than that of `E`. - */ + /// Constructs a `NonExhaustive<>` from `value` using both a custom interface and storage. + /// + /// # Panic + /// + /// This panics if the storage has an alignment or size smaller than that of `E`. pub fn with_storage_and_interface(value: E) -> Self where E: GetVTable, @@ -305,33 +291,31 @@ impl NonExhaustive where E: GetEnumInfo, { - /** - Unwraps a reference to this `NonExhaustive<>` into a reference to the original enum. - - # Errors - - This returns an error if the wrapped enum is of a variant that is - not valid in this context. - - # Example - - This shows how some `NonExhaustive` can be unwrapped, and others cannot.
- That enum comes from a newer version of the library than this knows. - - ``` - use abi_stable::nonexhaustive_enum::{ - doc_enums::example_2::{Foo,new_a,new_b,new_c}, - }; - - assert_eq!(new_a() .as_enum().ok(),Some(&Foo::A) ); - assert_eq!(new_b(10).as_enum().ok(),Some(&Foo::B(10))); - assert_eq!(new_b(77).as_enum().ok(),Some(&Foo::B(77))); - assert_eq!(new_c().as_enum().ok() ,None ); - - - ``` - - */ + /// wraps a reference to this `NonExhaustive<>` into a reference to the original enum. + /// + /// # Errors + /// + /// This returns an error if the wrapped enum is of a variant that is + /// not valid in this context. + /// + /// # Example + /// + /// This shows how some `NonExhaustive` can be unwrapped, and others cannot.
+ /// That enum comes from a newer version of the library than this knows. + /// + /// ``` + /// use abi_stable::nonexhaustive_enum::doc_enums::example_2::{ + /// new_a, new_b, new_c, Foo, + /// }; + /// + /// assert_eq!(new_a().as_enum().ok(), Some(&Foo::A)); + /// assert_eq!(new_b(10).as_enum().ok(), Some(&Foo::B(10))); + /// assert_eq!(new_b(77).as_enum().ok(), Some(&Foo::B(77))); + /// assert_eq!(new_c().as_enum().ok(), None); + /// + /// + /// ``` + /// pub fn as_enum(&self) -> Result<&E, UnwrapEnumError<&Self>> { let discriminant = self.get_discriminant(); if E::is_valid_discriminant(discriminant) { @@ -341,46 +325,40 @@ where } } - /** - Unwraps a mutable reference to this `NonExhaustive<>` into a - mutable reference to the original enum. - - # Errors - - This returns an error if the wrapped enum is of a variant that is - not valid in this context. - - # Example - - This shows how some `NonExhaustive` can be unwrapped, and others cannot.
- That enum comes from a newer version of the library than this knows. - - ``` - use abi_stable::nonexhaustive_enum::{ - doc_enums::example_1::{Foo,new_a,new_b,new_c}, - }; - - assert_eq!(new_a() .as_enum_mut().ok(),Some(&mut Foo::A)); - assert_eq!(new_b(10).as_enum_mut().ok(),None); - assert_eq!(new_b(77).as_enum_mut().ok(),None); - assert_eq!(new_c().as_enum_mut().ok() ,None); - - - ``` - - */ + /// Unwraps a mutable reference to this `NonExhaustive<>` into a + /// mutable reference to the original enum. + /// + /// # Errors + /// + /// This returns an error if the wrapped enum is of a variant that is + /// not valid in this context. + /// + /// # Example + /// + /// This shows how some `NonExhaustive` can be unwrapped, and others cannot.
+ /// That enum comes from a newer version of the library than this knows. + /// + /// ``` + /// use abi_stable::nonexhaustive_enum::doc_enums::example_1::{ + /// new_a, new_b, new_c, Foo, + /// }; + /// + /// assert_eq!(new_a().as_enum_mut().ok(), Some(&mut Foo::A)); + /// assert_eq!(new_b(10).as_enum_mut().ok(), None); + /// assert_eq!(new_b(77).as_enum_mut().ok(), None); + /// assert_eq!(new_c().as_enum_mut().ok(), None); + /// + /// ``` pub fn as_enum_mut(&mut self) -> Result<&mut E, UnwrapEnumError<&mut Self>> where E: GetVTable, { let discriminant = self.get_discriminant(); if E::is_valid_discriminant(discriminant) { - /* - Must update the vtable every time as_enum_mut is called, - because if the enum is replaced with a variant with a discriminant - outside the valid range for the functions in the vtable, - it would be undefined behavior to call those functions. - */ + // Must update the vtable every time as_enum_mut is called, + // because if the enum is replaced with a variant with a discriminant + // outside the valid range for the functions in the vtable, + // it would be undefined behavior to call those functions. self.vtable = E::VTABLE_REF; unsafe { Ok(&mut *(&mut self.fill as *mut ScratchSpace as *mut E)) } } else { @@ -388,31 +366,29 @@ where } } - /** - Unwraps this `NonExhaustive<>` into the original enum. - - # Errors - - This returns an error if the wrapped enum is of a variant that is - not valid in this context. - - # Example - - This shows how some `NonExhaustive` can be unwrapped, and others cannot.
- That enum comes from a newer version of the library than this knows. - - ``` - use abi_stable::nonexhaustive_enum::{ - doc_enums::example_2::{Foo,new_a,new_b,new_c}, - }; - - assert_eq!(new_a() .into_enum().ok(),Some(Foo::A)); - assert_eq!(new_b(10).into_enum().ok(),Some(Foo::B(10))); - assert_eq!(new_b(77).into_enum().ok(),Some(Foo::B(77))); - assert_eq!(new_c().into_enum().ok() ,None); - - - */ + /// Unwraps this `NonExhaustive<>` into the original enum. + /// + /// # Errors + /// + /// This returns an error if the wrapped enum is of a variant that is + /// not valid in this context. + /// + /// # Example + /// + /// This shows how some `NonExhaustive` can be unwrapped, and others cannot.
+ /// That enum comes from a newer version of the library than this knows. + /// + /// ``` + /// use abi_stable::nonexhaustive_enum::doc_enums::example_2::{ + /// new_a, new_b, new_c, Foo, + /// }; + /// + /// assert_eq!(new_a().into_enum().ok(), Some(Foo::A)); + /// assert_eq!(new_b(10).into_enum().ok(), Some(Foo::B(10))); + /// assert_eq!(new_b(77).into_enum().ok(), Some(Foo::B(77))); + /// assert_eq!(new_c().into_enum().ok(), None); + /// + /// ``` pub fn into_enum(self) -> Result> { let discriminant = self.get_discriminant(); if E::is_valid_discriminant(discriminant) { @@ -423,20 +399,16 @@ where } } - /** - Returns whether the discriminant of this enum is valid in this context. - - The only way for it to be invalid is if the dynamic library is a - newer version than this knows. - */ + /// Returns whether the discriminant of this enum is valid in this context. + /// + /// The only way for it to be invalid is if the dynamic library is a + /// newer version than this knows. #[inline] pub fn is_valid_discriminant(&self) -> bool { E::is_valid_discriminant(self.get_discriminant()) } - /** - Gets the value of the discriminant of the enum. - */ + /// Gets the value of the discriminant of the enum. #[inline] pub fn get_discriminant(&self) -> E::Discriminant { unsafe { *(&self.fill as *const ScratchSpace as *const E::Discriminant) } @@ -444,76 +416,66 @@ where } impl NonExhaustive { - /** - Transmute this `NonExhaustive` into `NonExhaustive`, - changing the type of the enum it wraps. - - # Safety - - This has the same safety requirements that `std::mem::transmute` has. - - # Panics - - This panics if the storage has an alignment or size smaller than that of `F`. - - */ + /// Transmute this `NonExhaustive` into `NonExhaustive`, + /// changing the type of the enum it wraps. + /// + /// # Safety + /// + /// This has the same safety requirements that `std::mem::transmute` has. + /// + /// # Panics + /// + /// This panics if the storage has an alignment or size smaller than that of `F`. + /// + /// pub unsafe fn transmute_enum(self) -> NonExhaustive { NonExhaustive::::assert_fits_within_storage(); transmute_ignore_size(self) } - /** - Transmute this `&NonExhaustive` into `&NonExhaustive`, - changing the type of the enum it wraps. - - # Safety - - This has the same safety requirements that `std::mem::transmute` has. - - # Panics - - This panics if the storage has an alignment or size smaller than that of `F`. - - */ + /// Transmute this `&NonExhaustive` into `&NonExhaustive`, + /// changing the type of the enum it wraps. + /// + /// # Safety + /// + /// This has the same safety requirements that `std::mem::transmute` has. + /// + /// # Panics + /// + /// This panics if the storage has an alignment or size smaller than that of `F`. pub unsafe fn transmute_enum_ref(&self) -> &NonExhaustive { NonExhaustive::::assert_fits_within_storage(); &*(self as *const Self as *const _) } - /** - Transmute this `&mut NonExhaustive` into `&mut NonExhaustive`, - changing the type of the enum it wraps. - - # Safety - - This has the same safety requirements that `std::mem::transmute` has. - - # Panics - - This panics if the storage has an alignment or size smaller than that of `F`. - - */ + /// Transmute this `&mut NonExhaustive` into `&mut NonExhaustive`, + /// changing the type of the enum it wraps. + /// + /// # Safety + /// + /// This has the same safety requirements that `std::mem::transmute` has. + /// + /// # Panics + /// + /// This panics if the storage has an alignment or size smaller than that of `F`. pub unsafe fn transmute_enum_mut(&mut self) -> &mut NonExhaustive { NonExhaustive::::assert_fits_within_storage(); &mut *(self as *mut Self as *mut _) } - /** - Transmute this pointer to a `NonExhaustive` into - a pointer (of the same kind) to a `NonExhaustive`, - changing the type of the enum it wraps. - - # Safety - - This has the same safety requirements that - `abi_stable::pointer_traits::TransmuteElement::transmute_element` has. - - # Panics - - This panics if the storage has an alignment or size smaller than that of `F`. - - */ - + /// Transmute this pointer to a `NonExhaustive` into + /// a pointer (of the same kind) to a `NonExhaustive`, + /// changing the type of the enum it wraps. + /// + /// # Safety + /// + /// This has the same safety requirements that + /// `abi_stable::pointer_traits::TransmuteElement::transmute_element` has. + /// + /// # Panics + /// + /// This panics if the storage has an alignment or size smaller than that of `F`. + /// pub unsafe fn transmute_enum_ptr(this: P) -> P::TransmutedPtr where P: Deref, @@ -846,11 +808,9 @@ where /////////////////////////////////////////////////////////////////////////////// -/** -An error for a situation where a `NonExhaustive<>` could not be unwrapped into the enum -because the discriminant wasn't valid in this context -(likely because it is from a newer version of the library). -*/ +/// An error for a situation where a `NonExhaustive<>` could not be unwrapped into the enum +/// because the discriminant wasn't valid in this context +/// (likely because it is from a newer version of the library). #[must_use] #[repr(transparent)] #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, StableAbi)] diff --git a/abi_stable/src/nonexhaustive_enum/traits.rs b/abi_stable/src/nonexhaustive_enum/traits.rs index c805ccc6..92010374 100644 --- a/abi_stable/src/nonexhaustive_enum/traits.rs +++ b/abi_stable/src/nonexhaustive_enum/traits.rs @@ -17,27 +17,22 @@ use crate::{ InterfaceType, }; -/** -Gets the type whose type layout is used to represent this enum in `NonExhaustive<>`. - -# Safety - -`Self::NonExhaustive` must describe the layout of this enum, -with the size and alignment of `Storage`. -*/ +/// Gets the type whose type layout is used to represent this enum in `NonExhaustive<>`. +/// +/// # Safety +/// +/// `Self::NonExhaustive` must describe the layout of this enum, +/// with the size and alignment of `Storage`. pub unsafe trait GetNonExhaustive: GetEnumInfo { /// The type whose type layout is used to represent this enum. type NonExhaustive; } -/** -Describes the discriminant of an enum,and its valid values. - -# Safety - -This must be an enum with a `#[repr(C)]` or `#[repr(SomeInteFgerType)]` attribute. - -*/ +/// Describes the discriminant of an enum,and its valid values. +/// +/// # Safety +/// +/// This must be an enum with a `#[repr(C)]` or `#[repr(SomeInteFgerType)]` attribute. pub unsafe trait GetEnumInfo: Sized { /// The type of the discriminant. type Discriminant: ValidDiscriminant; @@ -163,14 +158,12 @@ impl_valid_discriminant! {u8,i8,u16,i16,u32,i32,u64,i64,usize,isize} /////////////////////////////////////////////////////////////////////////////// -/** -Describes how some enum is serialized. - -This is generally implemented by the interface of an enum -(`Enum_Interface` for `Enum`),which also implements [`InterfaceType`]). - -[`InterfaceType`]: ../trait.InterfaceType.html -*/ +/// Describes how some enum is serialized. +/// +/// This is generally implemented by the interface of an enum +/// (`Enum_Interface` for `Enum`),which also implements [`InterfaceType`]). +/// +/// [`InterfaceType`]: ../trait.InterfaceType.html pub trait SerializeEnum { /// The intermediate type the `NE` is converted into,to serialize it. type Proxy; @@ -214,18 +207,16 @@ where /////////////////////////////////////// -/** -Describes how a nonexhaustive enum is deserialized. - -Generally this delegates to a library function, -so that the implementation can be delegated -to the `implementation crate`. - -This is generally implemented by the interface of an enum -(`Enum_Interface` for `Enum`),which also implements [`InterfaceType`]). - -[`InterfaceType`]: ../trait.InterfaceType.html -*/ +/// Describes how a nonexhaustive enum is deserialized. +/// +/// Generally this delegates to a library function, +/// so that the implementation can be delegated +/// to the `implementation crate`. +/// +/// This is generally implemented by the interface of an enum +/// (`Enum_Interface` for `Enum`),which also implements [`InterfaceType`]). +/// +/// [`InterfaceType`]: ../trait.InterfaceType.html pub trait DeserializeEnum<'borr, NE> { /// The intermediate type the `NE` is converted from,to deserialize it. type Proxy; diff --git a/abi_stable/src/prefix_type/prefix_ref.rs b/abi_stable/src/prefix_type/prefix_ref.rs index 038197df..36f5b8c6 100644 --- a/abi_stable/src/prefix_type/prefix_ref.rs +++ b/abi_stable/src/prefix_type/prefix_ref.rs @@ -25,32 +25,29 @@ use std::{ /// /// ```rust /// use abi_stable::{ -/// StableAbi, -/// staticref, /// prefix_type::{PrefixRef, PrefixTypeTrait, WithMetadata}, +/// staticref, StableAbi, /// }; /// -/// fn main(){ +/// fn main() { /// // `Module_Ref`'s constructor can also be called at compile-time /// asserts(Module_Ref(PREFIX_A)); /// asserts(Module_Ref(PREFIX_B)); /// } /// -/// fn asserts(module: Module_Ref){ +/// fn asserts(module: Module_Ref) { /// assert_eq!(module.first(), 5); /// assert_eq!(module.second(), 8); -/// +/// /// // If this Module_Ref had come from a previous version of the library without a /// // `third` field it would return `None`. /// assert_eq!(module.third(), Some(13)); /// } /// -/// -/// /// #[repr(C)] /// #[derive(StableAbi)] /// #[sabi(kind(Prefix(prefix_ref = "Module_Ref", prefix_fields = "Module_Prefix")))] -/// struct Module{ +/// struct Module { /// first: usize, /// // The `#[sabi(last_prefix_field)]` attribute here means that this is /// // the last field in this struct that was defined in the @@ -63,7 +60,7 @@ use std::{ /// third: usize, /// } /// -/// const MOD_VAL: Module = Module{ +/// const MOD_VAL: Module = Module { /// first: 5, /// second: 8, /// third: 13, @@ -93,13 +90,10 @@ use std::{ /// }); /// } /// -/// /// const PREFIX_B: PrefixRef = WithAssoc::MOD_WM.as_prefix(); /// -/// /// ///////////////////////////////////////// /// -/// /// ``` #[repr(transparent)] pub struct PrefixRef

{ @@ -148,23 +142,25 @@ impl

PrefixRef

{ /// use abi_stable::{ /// for_examples::{Module, Module_Prefix, Module_Ref}, /// prefix_type::{PrefixRef, PrefixTypeTrait, WithMetadata}, - /// std_types::*, /// rstr, + /// std_types::*, /// }; /// /// const MOD_WM: &WithMetadata = { - /// &WithMetadata::new(PrefixTypeTrait::METADATA, Module{ - /// first: RSome(3), - /// second: rstr!("hello"), - /// third: 8, - /// }) + /// &WithMetadata::new( + /// PrefixTypeTrait::METADATA, + /// Module { + /// first: RSome(3), + /// second: rstr!("hello"), + /// third: 8, + /// }, + /// ) /// }; /// - /// const PREFIX: PrefixRef = unsafe{ PrefixRef::from_raw(MOD_WM) }; + /// const PREFIX: PrefixRef = unsafe { PrefixRef::from_raw(MOD_WM) }; /// /// const MODULE: Module_Ref = Module_Ref(PREFIX); /// - /// /// assert_eq!(MODULE.first(), RSome(3)); /// /// assert_eq!(MODULE.second().as_str(), "hello"); @@ -191,15 +187,15 @@ impl

PrefixRef

{ /// use abi_stable::{ /// for_examples::{Module, Module_Prefix, Module_Ref}, /// prefix_type::{PrefixRef, PrefixTypeTrait, WithMetadata}, - /// std_types::*, /// rstr, staticref, + /// std_types::*, /// }; /// /// struct Foo {} /// /// impl Foo { /// // This macro declares a `StaticRef` pointing to the assigned `WithMetadata`. - /// staticref!{const MOD_WM: WithMetadata = + /// staticref! {const MOD_WM: WithMetadata = /// WithMetadata::new(PrefixTypeTrait::METADATA, Module{ /// first: RNone, /// second: rstr!("world"), @@ -212,7 +208,6 @@ impl

PrefixRef

{ /// /// const MODULE: Module_Ref = Module_Ref(PREFIX); /// - /// /// assert_eq!(MODULE.first(), RNone); /// /// assert_eq!(MODULE.second().as_str(), "world"); @@ -237,23 +232,25 @@ impl

PrefixRef

{ /// use abi_stable::{ /// for_examples::{Module, Module_Prefix, Module_Ref}, /// prefix_type::{PrefixRef, PrefixTypeTrait, WithMetadata}, - /// std_types::*, /// rstr, + /// std_types::*, /// }; /// /// const MOD_WM: &WithMetadata = { - /// &WithMetadata::new(PrefixTypeTrait::METADATA, Module{ - /// first: RNone, - /// second: rstr!("foo"), - /// third: 21, - /// }) + /// &WithMetadata::new( + /// PrefixTypeTrait::METADATA, + /// Module { + /// first: RNone, + /// second: rstr!("foo"), + /// third: 21, + /// }, + /// ) /// }; /// /// const PREFIX: PrefixRef = PrefixRef::from_ref(MOD_WM); /// /// const MODULE: Module_Ref = Module_Ref(PREFIX); /// - /// /// assert_eq!(MODULE.first(), RNone); /// /// assert_eq!(MODULE.second().as_str(), "foo"); @@ -281,21 +278,24 @@ impl

PrefixRef

{ /// }; /// /// const MOD_WM: &WithMetadata = { - /// &WithMetadata::new(PrefixTypeTrait::METADATA, Module{ - /// first: RNone, - /// second: RStr::empty(), - /// third: 0, - /// }) + /// &WithMetadata::new( + /// PrefixTypeTrait::METADATA, + /// Module { + /// first: RNone, + /// second: RStr::empty(), + /// third: 0, + /// }, + /// ) /// }; /// /// const PREFIX: PrefixRef = PrefixRef::from_ref(MOD_WM); /// /// let accessibility = PREFIX.metadata().field_accessibility(); /// - /// assert!( accessibility.is_accessible(0) ); // The `first` field - /// assert!( accessibility.is_accessible(1) ); // The `second` field - /// assert!( accessibility.is_accessible(2) ); // The `third` field - /// assert!( !accessibility.is_accessible(3) ); // There's no field after `third` + /// assert!(accessibility.is_accessible(0)); // The `first` field + /// assert!(accessibility.is_accessible(1)); // The `second` field + /// assert!(accessibility.is_accessible(2)); // The `third` field + /// assert!(!accessibility.is_accessible(3)); // There's no field after `third` /// /// ``` /// @@ -312,16 +312,19 @@ impl

PrefixRef

{ /// use abi_stable::{ /// for_examples::{Module, Module_Prefix}, /// prefix_type::{PrefixRef, PrefixTypeTrait, WithMetadata}, - /// std_types::*, /// rstr, + /// std_types::*, /// }; /// /// const MOD_WM: &WithMetadata = { - /// &WithMetadata::new(PrefixTypeTrait::METADATA, Module{ - /// first: RNone, - /// second: rstr!("foo"), - /// third: 21, - /// }) + /// &WithMetadata::new( + /// PrefixTypeTrait::METADATA, + /// Module { + /// first: RNone, + /// second: rstr!("foo"), + /// third: 21, + /// }, + /// ) /// }; /// /// const PREFIX_REF: PrefixRef = PrefixRef::from_ref(MOD_WM); diff --git a/abi_stable/src/proc_macro_reexports/export_root_module.rs b/abi_stable/src/proc_macro_reexports/export_root_module.rs index fe5b7ad4..5318bcb2 100644 --- a/abi_stable/src/proc_macro_reexports/export_root_module.rs +++ b/abi_stable/src/proc_macro_reexports/export_root_module.rs @@ -9,12 +9,9 @@ use abi_stable::prefix_type::PrefixTypeTrait; #[abi_stable::export_root_module] pub fn get_hello_world_mod() -> TextOperationsMod_Ref { - TextOperationsMod{ - reverse_string, - }.leak_into_prefix() + TextOperationsMod { reverse_string }.leak_into_prefix() } - # #[repr(C)] # #[derive(abi_stable::StableAbi)] # #[sabi(kind(Prefix(prefix_ref="TextOperationsMod_Ref")))] @@ -25,7 +22,7 @@ pub fn get_hello_world_mod() -> TextOperationsMod_Ref { # } # # extern "C" fn reverse_string() {} -# + # impl abi_stable::library::RootModule for TextOperationsMod_Ref { # abi_stable::declare_root_module_statics!{TextOperationsMod_Ref} # const BASE_NAME: &'static str = "stuff"; @@ -33,9 +30,10 @@ pub fn get_hello_world_mod() -> TextOperationsMod_Ref { # const VERSION_STRINGS: abi_stable::sabi_types::VersionStrings = # abi_stable::package_version_strings!(); # } -# + # fn main(){} + ``` # Return Type diff --git a/abi_stable/src/proc_macro_reexports/get_static_equivalent.rs b/abi_stable/src/proc_macro_reexports/get_static_equivalent.rs index 1c80b07f..8b4a544f 100644 --- a/abi_stable/src/proc_macro_reexports/get_static_equivalent.rs +++ b/abi_stable/src/proc_macro_reexports/get_static_equivalent.rs @@ -41,11 +41,8 @@ and use the value of an associated constant as the identity of the type. use std::marker::PhantomData; use abi_stable::{ - abi_stability::check_layout_compatibility, - marker_type::UnsafeIgnoredType, - StableAbi, - GetStaticEquivalent, - tag, + abi_stability::check_layout_compatibility, marker_type::UnsafeIgnoredType, tag, + GetStaticEquivalent, StableAbi, }; #[repr(C)] @@ -53,65 +50,58 @@ use abi_stable::{ #[sabi( not_stableabi(T), bound = "T: WithName", - tag = "tag!( ::NAME )", + tag = "tag!( ::NAME )" )] struct WithMarker(UnsafeIgnoredType); -impl WithMarker{ +impl WithMarker { const NEW: Self = WithMarker(UnsafeIgnoredType::NEW); } - -trait WithName{ +trait WithName { const NAME: &'static str; } #[derive(GetStaticEquivalent)] struct Mark; -impl WithName for Mark{ +impl WithName for Mark { const NAME: &'static str = "Mark"; } - #[derive(GetStaticEquivalent)] struct John; -impl WithName for John{ +impl WithName for John { const NAME: &'static str = "John"; } - #[derive(GetStaticEquivalent)] struct JessiJames; -impl WithName for JessiJames{ +impl WithName for JessiJames { const NAME: &'static str = "JessiJames"; } - # fn main(){ // This checks that the two types aren't considered compatible. -assert!( - check_layout_compatibility( - as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, - ).is_err() -); +assert!(check_layout_compatibility( + as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, +) +.is_err()); // This checks that the two types aren't considered compatible. -assert!( - check_layout_compatibility( - as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, - ).is_err() -); +assert!(check_layout_compatibility( + as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, +) +.is_err()); // This checks that the two types aren't considered compatible. -assert!( - check_layout_compatibility( - as StableAbi>::LAYOUT, - as StableAbi>::LAYOUT, - ).is_err() -); +assert!(check_layout_compatibility( + as StableAbi>::LAYOUT, + as StableAbi>::LAYOUT, +) +.is_err()); # } @@ -124,20 +114,14 @@ This example demonstrates how one can have a type parameter, and use its associated type as a field. ```rust -use abi_stable::{ - std_types::RVec, - StableAbi, -}; +use abi_stable::{std_types::RVec, StableAbi}; #[repr(C)] #[derive(StableAbi)] -#[sabi( - not_stableabi(I), - bound = "::Item : StableAbi", -)] +#[sabi(not_stableabi(I), bound = "::Item : StableAbi")] pub struct CollectedIterator where - I: IntoIterator + I: IntoIterator, { vec: RVec, } diff --git a/abi_stable/src/proc_macro_reexports/sabi_extern_fn.rs b/abi_stable/src/proc_macro_reexports/sabi_extern_fn.rs index 961b5cc9..7b25b3c8 100644 --- a/abi_stable/src/proc_macro_reexports/sabi_extern_fn.rs +++ b/abi_stable/src/proc_macro_reexports/sabi_extern_fn.rs @@ -29,7 +29,7 @@ catch panics and handle them appropriately. use abi_stable::{sabi_extern_fn, std_types::RArc, traits::IntoReprC}; #[sabi_extern_fn] -pub(crate) fn hello() -> RArc{ +pub(crate) fn hello() -> RArc { RArc::new(100) } @@ -41,25 +41,25 @@ assert_eq!(hello(), RArc::new(100)); ```rust use abi_stable::{ sabi_extern_fn, - std_types::{RVec, RStr}, + std_types::{RStr, RVec}, traits::IntoReprC, }; #[sabi_extern_fn] -fn collect_into_lines(text: &str) -> RVec>{ +fn collect_into_lines(text: &str) -> RVec> { text.lines() - .filter(|x| !x.is_empty() ) + .filter(|x| !x.is_empty()) .map(RStr::from) .collect() } - assert_eq!( collect_into_lines("what\nis\nthat"), - vec![ "what".into_c() , "is".into() , "that".into() ].into_c(), + vec!["what".into_c(), "is".into(), "that".into()].into_c(), ); + ``` # no_early_return @@ -78,22 +78,16 @@ early return, it will (incorrectly) abort the process when it attempts to return ```rust use abi_stable::{ sabi_extern_fn, - std_types::{RVec, RStr}, + std_types::{RStr, RVec}, traits::IntoReprC, }; #[sabi_extern_fn(no_early_return)] -pub(crate) fn hello() -> RVec>{ - vec![ - "hello".into(), - "world".into(), - ].into() +pub(crate) fn hello() -> RVec> { + vec!["hello".into(), "world".into()].into() } -assert_eq!( - hello(), - vec![ "hello".into_c() , "world".into() ].into_c(), -); +assert_eq!(hello(), vec!["hello".into_c(), "world".into()].into_c(),); diff --git a/abi_stable/src/proc_macro_reexports/sabi_trait_attribute.rs b/abi_stable/src/proc_macro_reexports/sabi_trait_attribute.rs index 02c37365..f4875810 100644 --- a/abi_stable/src/proc_macro_reexports/sabi_trait_attribute.rs +++ b/abi_stable/src/proc_macro_reexports/sabi_trait_attribute.rs @@ -301,16 +301,13 @@ which itself requires `'static` to be constructed. ```rust use abi_stable::{ - StableAbi, sabi_trait, sabi_trait::prelude::*, - std_types::{RBox, RArc, RString, RStr, ROption, RNone}, + std_types::{RArc, RBox, RNone, ROption, RStr, RString}, + StableAbi, }; -use std::{ - collections::HashMap, - fmt::Debug, -}; +use std::{collections::HashMap, fmt::Debug}; #[sabi_trait] pub trait Dictionary: Debug + Clone { @@ -318,15 +315,15 @@ pub trait Dictionary: Debug + Clone { fn get(&self, key: RStr<'_>) -> Option<&Self::Value>; - /// The `#[sabi(last_prefix_field)]` attribute here means that this is the last method + /// The `#[sabi(last_prefix_field)]` attribute here means that this is the last method /// that was defined in the first compatible version of the library /// (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 , etc), /// requiring new methods to always be added below preexisting ones. - /// - /// The `#[sabi(last_prefix_field)]` attribute would stay on this method until the library + /// + /// The `#[sabi(last_prefix_field)]` attribute would stay on this method until the library /// bumps its "major" version, /// at which point it would be moved to the last method at the time. - /// + /// #[sabi(last_prefix_field)] fn insert(&mut self, key: RString, value: Self::Value) -> ROption; @@ -336,21 +333,19 @@ pub trait Dictionary: Debug + Clone { } } - # fn main() { { impl Dictionary for HashMap where - V: Debug + Clone + V: Debug + Clone, { type Value = V; - fn get(&self, key: RStr<'_>) -> Option<&V>{ + fn get(&self, key: RStr<'_>) -> Option<&V> { self.get(key.as_str()) } - fn insert(&mut self, key: RString, value: V) -> ROption{ - self.insert(key, value) - .into() + fn insert(&mut self, key: RString, value: V) -> ROption { + self.insert(key, value).into() } } @@ -361,16 +356,16 @@ pub trait Dictionary: Debug + Clone { { // This type annotation is for the reader // - // You can unerase trait objects constructed with `TD_CanDowncast` + // You can unerase trait objects constructed with `TD_CanDowncast` // (as opposed to `TD_Opaque`, which can't be unerased). - let mut object: Dictionary_TO<'_, RBox<()>, u32>= + let mut object: Dictionary_TO<'_, RBox<()>, u32> = Dictionary_TO::from_value(map.clone(), TD_CanDowncast); - assert_eq!(Dictionary::get(&object,"hello".into()), Some(&100)); + assert_eq!(Dictionary::get(&object, "hello".into()), Some(&100)); assert_eq!(object.get("hello".into()), Some(&100)); // Inherent method call - - assert_eq!(Dictionary::get(&object,"world".into()), Some(&10)); - assert_eq!(object.get("world".into()), Some(&10)); // Inherent method call + + assert_eq!(Dictionary::get(&object, "world".into()), Some(&10)); + assert_eq!(object.get("world".into()), Some(&10)); // Inherent method call object.insert("what".into(), 99); // Inherent method call @@ -386,13 +381,13 @@ pub trait Dictionary: Debug + Clone { let arc = RArc::new(map.clone()); // This type annotation is for the reader // - // You can unerase trait objects constructed with `TD_CanDowncast` + // You can unerase trait objects constructed with `TD_CanDowncast` // (as opposed to `TD_Opaque`, which can't be unerased). - let object: Dictionary_TO<'_, RArc<()>, u32>= + let object: Dictionary_TO<'_, RArc<()>, u32> = Dictionary_TO::from_ptr(arc, TD_CanDowncast); assert_eq!(object.get("world".into()), Some(&10)); - + // Can't call these methods on `Dictionary_TO,..>` // because `RArc<_>` doesn't implement AsMutPtr. // @@ -400,29 +395,27 @@ pub trait Dictionary: Debug + Clone { // // object.insert("what".into(), 99); // Dictionary::insert(&mut object,"what".into(), 99); - let map: RArc> = object.obj.downcast_into().unwrap(); assert_eq!(map.get("hello".into()), Some(&100)); assert_eq!(map.get("world".into()), Some(&10)); } - } { - impl Dictionary for (){ + impl Dictionary for () { type Value = RString; - fn get(&self, _: RStr<'_>) -> Option<&RString>{ + fn get(&self, _: RStr<'_>) -> Option<&RString> { None } - fn insert(&mut self, _: RString, _: RString) -> ROption{ + fn insert(&mut self, _: RString, _: RString) -> ROption { RNone } } // This type annotation is for the reader - let object: Dictionary_TO<'_, RBox<()>, RString>= - Dictionary_TO::from_value( () , TD_Opaque); + let object: Dictionary_TO<'_, RBox<()>, RString> = + Dictionary_TO::from_value((), TD_Opaque); assert_eq!(object.get("hello".into()), None); assert_eq!(object.get("world".into()), None); @@ -433,6 +426,7 @@ pub trait Dictionary: Debug + Clone { # } + ``` @@ -442,11 +436,7 @@ This shows how one can construct a `#[sabi_trait]` generated trait object in a c ```rust -use abi_stable::{ - sabi_trait::TD_Opaque, - sabi_trait, - -}; +use abi_stable::{sabi_trait, sabi_trait::TD_Opaque}; #[sabi_trait] pub trait StaticSet: Sync + Send + Debug + Clone { @@ -458,35 +448,32 @@ pub trait StaticSet: Sync + Send + Debug + Clone { impl<'a, T> StaticSet for &'a [T] where - T: std::fmt::Debug + Sync + Send + std::cmp::PartialEq + T: std::fmt::Debug + Sync + Send + std::cmp::PartialEq, { type Element = T; - + fn contains(&self, key: &Self::Element) -> bool { (**self).contains(key) } } -const CARDS: &'static [char] = &['A','2','3','4','5','6','7','8','9','J','Q','K']; +const CARDS: &'static [char] = + &['A', '2', '3', '4', '5', '6', '7', '8', '9', 'J', 'Q', 'K']; -static IS_CARD: StaticSet_CTO<'static,'static, char>= - StaticSet_CTO::from_const( - &CARDS, - TD_Opaque, - StaticSet_MV::VTABLE, - ); +static IS_CARD: StaticSet_CTO<'static, 'static, char> = + StaticSet_CTO::from_const(&CARDS, TD_Opaque, StaticSet_MV::VTABLE); # fn main(){ -assert!( IS_CARD.contains(&'A') ); -assert!( IS_CARD.contains(&'4') ); -assert!( IS_CARD.contains(&'7') ); -assert!( IS_CARD.contains(&'9') ); -assert!( IS_CARD.contains(&'J') ); +assert!(IS_CARD.contains(&'A')); +assert!(IS_CARD.contains(&'4')); +assert!(IS_CARD.contains(&'7')); +assert!(IS_CARD.contains(&'9')); +assert!(IS_CARD.contains(&'J')); -assert!( ! IS_CARD.contains(&'0') ); -assert!( ! IS_CARD.contains(&'1') ); -assert!( ! IS_CARD.contains(&'B') ); +assert!(!IS_CARD.contains(&'0')); +assert!(!IS_CARD.contains(&'1')); +assert!(!IS_CARD.contains(&'B')); # } diff --git a/abi_stable/src/proc_macro_reexports/stable_abi_derive.rs b/abi_stable/src/proc_macro_reexports/stable_abi_derive.rs index fd917a13..7db77f78 100644 --- a/abi_stable/src/proc_macro_reexports/stable_abi_derive.rs +++ b/abi_stable/src/proc_macro_reexports/stable_abi_derive.rs @@ -379,8 +379,8 @@ For a variant like this: `VariantNamed{foo: RString, bar: RBox}` it would generate an associated function like this(the exact generated code might differ a bit): ```ignore -fn VariantNamed_NE(foo: RString, bar: RBox)->Enum_NE{ - let x = Enum::VariantNamed{foo, bar}; +fn VariantNamed_NE(foo: RString, bar: RBox) -> Enum_NE { + let x = Enum::VariantNamed { foo, bar }; NonExhaustive::new(x) } ``` @@ -403,7 +403,7 @@ For a variant like this: it would generate an associated function like this(the exact generated code might differ a bit): ```ignore -fn VariantNamed_NE(value: T)->Enum_NE{ +fn VariantNamed_NE(value: T) -> Enum_NE { let x = RBox::new(value); let x = Enum::VariantNamed(x); NonExhaustive::new(x) @@ -418,9 +418,9 @@ For a variant like this: it would generate an associated function like this(the exact generated code might differ a bit): ```ignore -fn VariantNamed_NE(value: T)->Enum_NE{ +fn VariantNamed_NE(value: T) -> Enum_NE { let x = MyPointer::new(value); - let x = Enum::VariantNamed{ptr_: x}; + let x = Enum::VariantNamed { ptr_: x }; NonExhaustive::new(x) } ``` @@ -431,7 +431,9 @@ For a variant like this: it would generate an associated function like this(the exact generated code might differ a bit): ```ignore -fn VariantNamed_NE(value: ::Target)->Enum_NE{ +fn VariantNamed_NE( + value: ::Target, +) -> Enum_NE { let x = BoxedStruct::new(value); let x = Enum::VariantNamed(x); NonExhaustive::new(x) @@ -477,7 +479,7 @@ use abi_stable::StableAbi; #[repr(C)] #[derive(StableAbi)] -struct Point2D{ +struct Point2D { x: u32, y: u32, } @@ -492,10 +494,11 @@ use abi_stable::StableAbi; #[repr(transparent)] #[derive(StableAbi)] -pub struct Wrapper{ - pub inner: T +pub struct Wrapper { + pub inner: T, } + ``` ### On a `#[repr(u8)]` enum. @@ -504,19 +507,14 @@ This enum cannot add variants in minor versions, for that you have to use [nonexhaustive enums](./docs/sabi_nonexhaustive/index.html). ``` -use abi_stable::{ - StableAbi, - std_types::RString, -}; +use abi_stable::{std_types::RString, StableAbi}; #[repr(u8)] #[derive(StableAbi)] -pub enum Command{ +pub enum Command { LaunchRockets, EatLaundry, - WakeTheDragon{ - using: RString - } + WakeTheDragon { using: RString }, } ``` From 3403c4057acffc37cceb16c690de1fc1358169d7 Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Wed, 27 Oct 2021 02:01:27 -0300 Subject: [PATCH 17/32] Formatted more doc comments. Turned more `/** */`-style doc comments to `///` Did both in submodules of: - abi_stability - erased_types Formatted doc comments in `abi_stalble::docs` --- abi_stable/src/abi_stability/abi_checking.rs | 60 +- abi_stable/src/abi_stability/extra_checks.rs | 1398 ++++++++--------- .../abi_stability/get_static_equivalent.rs | 5 +- .../src/abi_stability/stable_abi_trait.rs | 4 +- abi_stable/src/docs/library_evolution.rs | 26 +- abi_stable/src/docs/prefix_types.rs | 172 +- abi_stable/src/docs/sabi_nonexhaustive.rs | 439 +++--- abi_stable/src/docs/sabi_trait_inherent.rs | 38 +- abi_stable/src/erased_types/dyn_trait.rs | 636 +++----- 9 files changed, 1263 insertions(+), 1515 deletions(-) diff --git a/abi_stable/src/abi_stability/abi_checking.rs b/abi_stable/src/abi_stability/abi_checking.rs index 27366e33..d3836617 100644 --- a/abi_stable/src/abi_stability/abi_checking.rs +++ b/abi_stable/src/abi_stability/abi_checking.rs @@ -1,6 +1,4 @@ -/*! -Functions and types related to the layout checking. -*/ +//! Functions and types related to the layout checking. use std::{cmp::Ordering, fmt, mem}; @@ -1071,16 +1069,14 @@ impl AbiChecker { } } -/** -Checks that the layout of `interface` is compatible with `implementation`. - -# Warning - -This function is not symmetric, -the first parameter must be the expected layout, -and the second must be actual layout. - -*/ +/// Checks that the layout of `interface` is compatible with `implementation`. +/// +/// # Warning +/// +/// This function is not symmetric, +/// the first parameter must be the expected layout, +/// and the second must be actual layout. +/// pub fn check_layout_compatibility( interface: &'static TypeLayout, implementation: &'static TypeLayout, @@ -1142,9 +1138,7 @@ pub fn check_layout_compatibility_with_globals( } } -/** -Checks that the layout of `interface` is compatible with `implementation`, -*/ +/// Checks that the layout of `interface` is compatible with `implementation`, pub(crate) extern "C" fn check_layout_compatibility_for_ffi( interface: &'static TypeLayout, implementation: &'static TypeLayout, @@ -1174,24 +1168,22 @@ pub(crate) extern "C" fn check_layout_compatibility_for_ffi( } } -/** -Checks that the layout of `interface` is compatible with `implementation`, - -If this function is called within a dynamic library, -it must be called during or after the function that exports its root module is called. - -**DO NOT** call this in the static initializer of a dynamic library, -since this library relies on setting up its global state before -calling the root module loader. - -# Warning - -This function is not symmetric, -the first parameter must be the expected layout, -and the second must be actual layout. - - -*/ +/// Checks that the layout of `interface` is compatible with `implementation`, +/// +/// If this function is called within a dynamic library, +/// it must be called during or after the function that exports its root module is called. +/// +/// **DO NOT** call this in the static initializer of a dynamic library, +/// since this library relies on setting up its global state before +/// calling the root module loader. +/// +/// # Warning +/// +/// This function is not symmetric, +/// the first parameter must be the expected layout, +/// and the second must be actual layout. +/// +/// pub extern "C" fn exported_check_layout_compatibility( interface: &'static TypeLayout, implementation: &'static TypeLayout, diff --git a/abi_stable/src/abi_stability/extra_checks.rs b/abi_stable/src/abi_stability/extra_checks.rs index e30ebfa8..99317222 100644 --- a/abi_stable/src/abi_stability/extra_checks.rs +++ b/abi_stable/src/abi_stability/extra_checks.rs @@ -1,637 +1,593 @@ -/*! -Contains items for adding checks to individual types. - -# Implementing and using ExtraChecks - -To add extra checks to a type follow these steps: - -- Create some type and implement ExtraChecks for it, - -- Apply the `#[sabi(extra_checks="const expression that implements ExtraChecks")]` - attribute to a type that uses `#[derive(StableAbi)]`. - -# Combination - -This is how an ExtraChecks can be combined across all -dynamic libraries to ensure some property(which can be relied on for safety). - -This is a very similar process to how abi_stable ensures that -vtables and modules are consistent across dynamic libraries. - -### Failure - -Loading many libraries that contain ExtraChecks trait objects that need -to be combined can fail if the representative version of the trait objects -are incompatible with those of the library, -even if both the library and the binary are otherwise compatible. - -The graphs below uses the `LIBRARY( ExtraChecks trait object )` format, -where the trait object is compatible only if the one in the binary -is a prefix of the string in the library, -and all the libraries have a prefix of the same string. - -This is fine: - -```text -A("ab")<---B("abc") -\__________C("abcd") -``` - -This is not fine - -```text - __________D("abe") -/ -A("ab")<---B("abc") -\__________C("abcd") -``` - -The case that is not fine happens when the `ExtraChecks_TO::combine` method returned an error. - - -### Example - -``` - -use abi_stable::{ - abi_stability::{ - extra_checks::{ - TypeCheckerMut, - ExtraChecks,ExtraChecksStaticRef,ExtraChecksRef,ExtraChecksBox, - ForExtraChecksImplementor,ExtraChecksError, - }, - check_layout_compatibility, - }, - marker_type::UnsafeIgnoredType, - type_layout::TypeLayout, - sabi_trait::prelude::TD_Opaque, - std_types::{RCow,RResult,ROption,RSome,RStr}, - sabi_extern_fn, - GetStaticEquivalent, - StableAbi, -}; - -use std::fmt::{self,Display}; - - -const LAYOUT0:&'static TypeLayout= as StableAbi>::LAYOUT; -const LAYOUT1:&'static TypeLayout= as StableAbi>::LAYOUT; -const LAYOUT1B:&'static TypeLayout= as StableAbi>::LAYOUT; -const LAYOUT2:&'static TypeLayout= as StableAbi>::LAYOUT; - - -fn main(){ - // Compared LAYOUT0 to LAYOUT1B, - // then stored LAYOUT0.extra_checks as the ExtraChecks associated with both layouts. - check_layout_compatibility(LAYOUT0,LAYOUT1B).unwrap(); - - // Compared LAYOUT1 to LAYOUT2, - // then stored LAYOUT2.extra_checks as the ExtraChecks associated with both layouts. - check_layout_compatibility(LAYOUT1,LAYOUT2).unwrap(); - - // Compared LAYOUT0 to LAYOUT2: - // - the comparison succeeded, - // - then both are combined. - // - The combined trait object is attempted to be combined with the - // ExtraChecks in the global map associated to both LAYOUT0 and LAYOUT2, - // which are LAYOUT1B.extra_checks and LAYOUT2.extra_checks respectively. - // - Combining the trait objects with the ones in the global map fails because - // the one from LAYOUT1B is incompatible with the one from LAYOUT2. - check_layout_compatibility(LAYOUT0,LAYOUT2).unwrap_err(); -} - - - -////////////////////////////////////////////////////////////////////////////////// - - - -#[repr(C)] -#[derive(StableAbi)] -#[sabi( - // Replaces the C:StableAbi constraint with `C:GetStaticEquivalent` - // (a supertrait of StableAbi). - not_stableabi(C), - bound="C:GetConstant", - extra_checks="Self::CHECKER" -)] -struct WithConstant{ - // UnsafeIgnoredType is equivalent to PhantomData, - // except that all `UnsafeIgnoredType` are considered the same type by `StableAbi`. - _marker:UnsafeIgnoredType, -} - -impl WithConstant{ - const NEW:Self=Self{ - _marker:UnsafeIgnoredType::NEW, - }; -} - -impl WithConstant -where - C:GetConstant -{ - const CHECKER:ConstChecker= - ConstChecker{ - chars:RStr::from_str(C::CHARS) - }; - -} - - -trait GetConstant{ - const CHARS:&'static str; -} - -use self::constants::*; - -#[allow(non_camel_case_types)] -mod constants{ - use super::*; - - #[derive(GetStaticEquivalent)] - pub struct V1_0; - - impl GetConstant for V1_0{ - const CHARS:&'static str="ab"; - } - - - #[derive(GetStaticEquivalent)] - pub struct V1_1; - - impl GetConstant for V1_1{ - const CHARS:&'static str="abc"; - } - - - #[derive(GetStaticEquivalent)] - pub struct V1_1_Incompatible; - - impl GetConstant for V1_1_Incompatible{ - const CHARS:&'static str="abd"; - } - - - #[derive(GetStaticEquivalent)] - pub struct V1_2; - - impl GetConstant for V1_2{ - const CHARS:&'static str="abcd"; - } -} - - - -///////////////////////////////////////// - -#[repr(C)] -#[derive(Debug,Clone,StableAbi)] -pub struct ConstChecker{ - chars:RStr<'static>, -} - - -impl Display for ConstChecker{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - writeln!( - f, - "ConstChecker: \ - Checks that the associated constant for \ - the other type is compatible with:\n{}\n.\ - ", - self.chars - ) - } -} - - -impl ConstChecker { - fn check_compatible_inner(&self,other:&ConstChecker)->Result<(), UnequalConstError> { - if other.chars.starts_with(&*self.chars) { - Ok(()) - }else{ - Err(UnequalConstError{ - expected:self.chars, - found:other.chars, - }) - } - } -} -unsafe impl ExtraChecks for ConstChecker { - fn type_layout(&self)->&'static TypeLayout{ - ::LAYOUT - } - - fn check_compatibility( - &self, - _layout_containing_self:&'static TypeLayout, - layout_containing_other:&'static TypeLayout, - checker:TypeCheckerMut<'_>, - )->RResult<(), ExtraChecksError> { - Self::downcast_with_layout(layout_containing_other,checker,|other,_|{ - self.check_compatible_inner(other) - }) - } - - fn nested_type_layouts(&self)->RCow<'_,[&'static TypeLayout]>{ - RCow::from_slice(&[]) - } - - fn combine( - &self, - other:ExtraChecksRef<'_>, - checker:TypeCheckerMut<'_> - )->RResult, ExtraChecksError>{ - Self::downcast_with_object(other,checker,|other,_|{ - let (min,max)=min_max_by(self,other,|x|x.chars.len()); - min.check_compatible_inner(max) - .map(|_| RSome( ExtraChecksBox::from_value(max.clone(),TD_Opaque) ) ) - }) - } -} - - - -#[derive(Debug,Clone)] -pub struct UnequalConstError{ - expected:RStr<'static>, - found:RStr<'static>, -} - -impl Display for UnequalConstError{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - writeln!( - f, - "Expected the `GetConstant::CHARS` associated constant to be compatible with:\ - \n {}\ - \nFound:\ - \n {}\ - ", - self.expected, - self.found, - ) - } -} - -impl std::error::Error for UnequalConstError{} - - -pub(crate) fn min_max_by(l:T,r:T,mut f:F)->(T,T) -where - F:FnMut(&T)->K, - K:Ord, -{ - if f(&l) < f(&r) { - (l,r) - }else{ - (r,l) - } -} - - -``` - - -# Examples - -### Alphabetic. - -This defines an ExtraChecks which checks that fields are alphabetically sorted - -``` -use abi_stable::{ - abi_stability::{ - extra_checks::{ - TypeCheckerMut,ExtraChecks,ExtraChecksStaticRef, - ForExtraChecksImplementor,ExtraChecksError, - }, - check_layout_compatibility, - }, - type_layout::TypeLayout, - sabi_trait::prelude::TD_Opaque, - std_types::{RCow,RDuration,RResult,ROption,RStr,RString}, - sabi_extern_fn, - StableAbi, -}; - -use std::fmt::{self,Display}; - -fn main(){ - - let rect_layout=::LAYOUT; - let person_layout=::LAYOUT; - - // This passes because the fields are in order - check_layout_compatibility(rect_layout,rect_layout) - .unwrap_or_else(|e| panic!("{}",e) ); - - // This errors because the struct's fields aren't in order - check_layout_compatibility(person_layout,person_layout) - .unwrap_err(); - -} - - -#[repr(C)] -#[derive(StableAbi)] -#[sabi(extra_checks="InOrderChecker")] -struct Rectangle{ - x:u32, - y:u32, - z:u32, -} - - -#[repr(C)] -#[derive(StableAbi)] -#[sabi(extra_checks="InOrderChecker")] -struct Person{ - name:RString, - surname:RString, - age:RDuration, -} - - -///////////////////////////////////////// - - -#[repr(C)] -#[derive(Debug,Clone,StableAbi)] -pub struct InOrderChecker; - - -impl Display for InOrderChecker{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - f.write_str("InOrderChecker: Checks that field names are sorted alphabetically.") - } -} - - -unsafe impl ExtraChecks for InOrderChecker { - fn type_layout(&self)->&'static TypeLayout{ - ::LAYOUT - } - - fn check_compatibility( - &self, - layout_containing_self:&'static TypeLayout, - layout_containing_other:&'static TypeLayout, - checker:TypeCheckerMut<'_>, - )->RResult<(), ExtraChecksError> { - Self::downcast_with_layout(layout_containing_other,checker,|_,_|{ - let fields=match layout_containing_self.get_fields() { - Some(fields)if !fields.is_empty()=>fields, - _=>return Ok(()), - }; - - let mut prev=fields.iter().next().unwrap(); - for curr in fields { - if prev.name() > curr.name() { - return Err(OutOfOrderError{ - previous_one:prev.name(), - first_one:curr.name(), - }); - } - prev=curr; - } - Ok(()) - }) - } - - fn nested_type_layouts(&self)->RCow<'_,[&'static TypeLayout]>{ - RCow::from_slice(&[]) - } -} - - - -#[derive(Debug,Clone)] -pub struct OutOfOrderError{ - previous_one:&'static str, - - /// The first field that is out of order. - first_one:&'static str, -} - -impl Display for OutOfOrderError{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - writeln!( - f, - "Expected fields to be alphabetically sorted.\n\ - Found field '{}' before '{}'\ - ", - self.previous_one, - self.first_one, - ) - } -} - -impl std::error::Error for OutOfOrderError{} - - -``` - -### Associated Constant. - -This defines an ExtraChecks which checks that an associated constant is -the same for both types. - -``` -use abi_stable::{ - abi_stability::{ - extra_checks::{ - TypeCheckerMut,ExtraChecks,ExtraChecksStaticRef, - ForExtraChecksImplementor,ExtraChecksError, - }, - check_layout_compatibility, - }, - marker_type::UnsafeIgnoredType, - type_layout::TypeLayout, - sabi_trait::prelude::TD_Opaque, - std_types::{RCow,RDuration,RResult,RStr,RString}, - sabi_extern_fn, - GetStaticEquivalent, - StableAbi, -}; - -use std::fmt::{self,Display}; - -fn main(){ - - let const0= as StableAbi>::LAYOUT; - let const_second_0= as StableAbi>::LAYOUT; - let const1= as StableAbi>::LAYOUT; - let const2= as StableAbi>::LAYOUT; - - check_layout_compatibility(const0,const0).unwrap(); - check_layout_compatibility(const_second_0,const_second_0).unwrap(); - check_layout_compatibility(const1,const1).unwrap(); - check_layout_compatibility(const2,const2).unwrap(); - - //////////// - // WithConstant and WithConstant are compatible with each other - // because their `GetConstant::NUMBER` associated constant is the same value. - check_layout_compatibility(const0,const_second_0).unwrap(); - check_layout_compatibility(const_second_0,const0).unwrap(); - - - //////////// - // None of the lines below are compatible because their - // `GetConstant::NUMBER` associated constant isn't the same value. - check_layout_compatibility(const0,const1).unwrap_err(); - check_layout_compatibility(const0,const2).unwrap_err(); - - check_layout_compatibility(const1,const0).unwrap_err(); - check_layout_compatibility(const1,const2).unwrap_err(); - - check_layout_compatibility(const2,const0).unwrap_err(); - check_layout_compatibility(const2,const1).unwrap_err(); - -} - - -#[repr(C)] -#[derive(StableAbi)] -#[sabi( - // Replaces the C:StableAbi constraint with `C:GetStaticEquivalent` - // (a supertrait of StableAbi). - not_stableabi(C), - bound="C:GetConstant", - extra_checks="Self::CHECKER" -)] -struct WithConstant{ - // UnsafeIgnoredType is equivalent to PhantomData, - // except that all `UnsafeIgnoredType` are considered the same type by `StableAbi`. - _marker:UnsafeIgnoredType, -} - -impl WithConstant{ - const NEW:Self=Self{ - _marker:UnsafeIgnoredType::NEW, - }; -} - -impl WithConstant -where - C:GetConstant -{ - const CHECKER:ConstChecker= - ConstChecker{number:C::NUMBER}; -} - - -trait GetConstant{ - const NUMBER:u64; -} - -#[derive(GetStaticEquivalent)] -struct N0; -impl GetConstant for N0{ - const NUMBER:u64=0; -} - -#[derive(GetStaticEquivalent)] -struct SecondN0; -impl GetConstant for SecondN0{ - const NUMBER:u64=0; -} - -#[derive(GetStaticEquivalent)] -struct N1; -impl GetConstant for N1{ - const NUMBER:u64=1; -} - -#[derive(GetStaticEquivalent)] -struct N2; -impl GetConstant for N2{ - const NUMBER:u64=2; -} - - -///////////////////////////////////////// - -#[repr(C)] -#[derive(Debug,Clone,StableAbi)] -pub struct ConstChecker{ - number:u64 -} - - -impl Display for ConstChecker{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - writeln!( - f, - "ConstChecker: \ - Checks that the associated constant for \ - for the other type is {}.\ - ", - self.number - ) - } -} - - -unsafe impl ExtraChecks for ConstChecker { - fn type_layout(&self)->&'static TypeLayout{ - ::LAYOUT - } - - fn check_compatibility( - &self, - layout_containing_self:&'static TypeLayout, - layout_containing_other:&'static TypeLayout, - checker:TypeCheckerMut<'_>, - )->RResult<(), ExtraChecksError> { - Self::downcast_with_layout(layout_containing_other,checker,|other,_|{ - if self.number==other.number { - Ok(()) - }else{ - Err(UnequalConstError{ - expected:self.number, - found:other.number, - }) - } - }) - } - - fn nested_type_layouts(&self)->RCow<'_,[&'static TypeLayout]>{ - RCow::from_slice(&[]) - } -} - - - -#[derive(Debug,Clone)] -pub struct UnequalConstError{ - expected:u64, - found:u64, -} - -impl Display for UnequalConstError{ - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ - writeln!( - f, - "Expected the `GetConstant::NUMBER` associated constant to be:\ - \n {}\ - \nFound:\ - \n {}\ - ", - self.expected, - self.found, - ) - } -} - -impl std::error::Error for UnequalConstError{} - - -``` - - - -*/ +//! Contains items for adding checks to individual types. +//! +//! # Implementing and using ExtraChecks +//! +//! To add extra checks to a type follow these steps: +//! +//! - Create some type and implement ExtraChecks for it, +//! +//! - Apply the `#[sabi(extra_checks="const expression that implements ExtraChecks")]` +//! attribute to a type that uses `#[derive(StableAbi)]`. +//! +//! # Combination +//! +//! This is how an ExtraChecks can be combined across all +//! dynamic libraries to ensure some property(which can be relied on for safety). +//! +//! This is a very similar process to how abi_stable ensures that +//! vtables and modules are consistent across dynamic libraries. +//! +//! ### Failure +//! +//! Loading many libraries that contain ExtraChecks trait objects that need +//! to be combined can fail if the representative version of the trait objects +//! are incompatible with those of the library, +//! even if both the library and the binary are otherwise compatible. +//! +//! The graphs below uses the `LIBRARY( ExtraChecks trait object )` format, +//! where the trait object is compatible only if the one in the binary +//! is a prefix of the string in the library, +//! and all the libraries have a prefix of the same string. +//! +//! This is fine: +//! +//! ```text +//! A("ab")<---B("abc") +//! \__________C("abcd") +//! ``` +//! +//! This is not fine +//! +//! ```text +//! __________D("abe") +//! / +//! A("ab")<---B("abc") +//! \__________C("abcd") +//! ``` +//! +//! The case that is not fine happens when the `ExtraChecks_TO::combine` method returned an error. +//! +//! +//! ### Example +//! +//! ``` +//! +//! use abi_stable::{ +//! abi_stability::{ +//! check_layout_compatibility, +//! extra_checks::{ +//! ExtraChecks, ExtraChecksBox, ExtraChecksError, ExtraChecksRef, +//! ExtraChecksStaticRef, ForExtraChecksImplementor, TypeCheckerMut, +//! }, +//! }, +//! marker_type::UnsafeIgnoredType, +//! sabi_extern_fn, +//! sabi_trait::prelude::TD_Opaque, +//! std_types::{RCow, ROption, RResult, RSome, RStr}, +//! type_layout::TypeLayout, +//! GetStaticEquivalent, StableAbi, +//! }; +//! +//! use std::fmt::{self, Display}; +//! +//! const LAYOUT0: &'static TypeLayout = as StableAbi>::LAYOUT; +//! const LAYOUT1: &'static TypeLayout = as StableAbi>::LAYOUT; +//! const LAYOUT1B: &'static TypeLayout = +//! as StableAbi>::LAYOUT; +//! const LAYOUT2: &'static TypeLayout = as StableAbi>::LAYOUT; +//! +//! fn main() { +//! // Compared LAYOUT0 to LAYOUT1B, +//! // then stored LAYOUT0.extra_checks as the ExtraChecks associated with both layouts. +//! check_layout_compatibility(LAYOUT0, LAYOUT1B).unwrap(); +//! +//! // Compared LAYOUT1 to LAYOUT2, +//! // then stored LAYOUT2.extra_checks as the ExtraChecks associated with both layouts. +//! check_layout_compatibility(LAYOUT1, LAYOUT2).unwrap(); +//! +//! // Compared LAYOUT0 to LAYOUT2: +//! // - the comparison succeeded, +//! // - then both are combined. +//! // - The combined trait object is attempted to be combined with the +//! // ExtraChecks in the global map associated to both LAYOUT0 and LAYOUT2, +//! // which are LAYOUT1B.extra_checks and LAYOUT2.extra_checks respectively. +//! // - Combining the trait objects with the ones in the global map fails because +//! // the one from LAYOUT1B is incompatible with the one from LAYOUT2. +//! check_layout_compatibility(LAYOUT0, LAYOUT2).unwrap_err(); +//! } +//! +//! ////////////////////////////////////////////////////////////////////////////////// +//! +//! #[repr(C)] +//! #[derive(StableAbi)] +//! #[sabi( +//! // Replaces the C:StableAbi constraint with `C:GetStaticEquivalent` +//! // (a supertrait of StableAbi). +//! not_stableabi(C), +//! bound="C:GetConstant", +//! extra_checks="Self::CHECKER" +//! )] +//! struct WithConstant { +//! // UnsafeIgnoredType is equivalent to PhantomData, +//! // except that all `UnsafeIgnoredType` are considered the same type by `StableAbi`. +//! _marker: UnsafeIgnoredType, +//! } +//! +//! impl WithConstant { +//! const NEW: Self = Self { +//! _marker: UnsafeIgnoredType::NEW, +//! }; +//! } +//! +//! impl WithConstant +//! where +//! C: GetConstant, +//! { +//! const CHECKER: ConstChecker = ConstChecker { +//! chars: RStr::from_str(C::CHARS), +//! }; +//! } +//! +//! trait GetConstant { +//! const CHARS: &'static str; +//! } +//! +//! use self::constants::*; +//! +//! #[allow(non_camel_case_types)] +//! mod constants { +//! use super::*; +//! +//! #[derive(GetStaticEquivalent)] +//! pub struct V1_0; +//! +//! impl GetConstant for V1_0 { +//! const CHARS: &'static str = "ab"; +//! } +//! +//! #[derive(GetStaticEquivalent)] +//! pub struct V1_1; +//! +//! impl GetConstant for V1_1 { +//! const CHARS: &'static str = "abc"; +//! } +//! +//! #[derive(GetStaticEquivalent)] +//! pub struct V1_1_Incompatible; +//! +//! impl GetConstant for V1_1_Incompatible { +//! const CHARS: &'static str = "abd"; +//! } +//! +//! #[derive(GetStaticEquivalent)] +//! pub struct V1_2; +//! +//! impl GetConstant for V1_2 { +//! const CHARS: &'static str = "abcd"; +//! } +//! } +//! +//! ///////////////////////////////////////// +//! +//! #[repr(C)] +//! #[derive(Debug, Clone, StableAbi)] +//! pub struct ConstChecker { +//! chars: RStr<'static>, +//! } +//! +//! impl Display for ConstChecker { +//! fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { +//! writeln!( +//! f, +//! "ConstChecker: \ +//! Checks that the associated constant for \ +//! the other type is compatible with:\n{}\n.\ +//! ", +//! self.chars +//! ) +//! } +//! } +//! +//! impl ConstChecker { +//! fn check_compatible_inner( +//! &self, +//! other: &ConstChecker, +//! ) -> Result<(), UnequalConstError> { +//! if other.chars.starts_with(&*self.chars) { +//! Ok(()) +//! } else { +//! Err(UnequalConstError { +//! expected: self.chars, +//! found: other.chars, +//! }) +//! } +//! } +//! } +//! unsafe impl ExtraChecks for ConstChecker { +//! fn type_layout(&self) -> &'static TypeLayout { +//! ::LAYOUT +//! } +//! +//! fn check_compatibility( +//! &self, +//! _layout_containing_self: &'static TypeLayout, +//! layout_containing_other: &'static TypeLayout, +//! checker: TypeCheckerMut<'_>, +//! ) -> RResult<(), ExtraChecksError> { +//! Self::downcast_with_layout(layout_containing_other, checker, |other, _| { +//! self.check_compatible_inner(other) +//! }) +//! } +//! +//! fn nested_type_layouts(&self) -> RCow<'_, [&'static TypeLayout]> { +//! RCow::from_slice(&[]) +//! } +//! +//! fn combine( +//! &self, +//! other: ExtraChecksRef<'_>, +//! checker: TypeCheckerMut<'_>, +//! ) -> RResult, ExtraChecksError> { +//! Self::downcast_with_object(other, checker, |other, _| { +//! let (min, max) = min_max_by(self, other, |x| x.chars.len()); +//! min.check_compatible_inner(max) +//! .map(|_| RSome(ExtraChecksBox::from_value(max.clone(), TD_Opaque))) +//! }) +//! } +//! } +//! +//! #[derive(Debug, Clone)] +//! pub struct UnequalConstError { +//! expected: RStr<'static>, +//! found: RStr<'static>, +//! } +//! +//! impl Display for UnequalConstError { +//! fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { +//! writeln!( +//! f, +//! "Expected the `GetConstant::CHARS` associated constant to be compatible with:\ +//! \n {}\ +//! \nFound:\ +//! \n {}\ +//! ", +//! self.expected, +//! self.found, +//! ) +//! } +//! } +//! +//! impl std::error::Error for UnequalConstError {} +//! +//! pub(crate) fn min_max_by(l: T, r: T, mut f: F) -> (T, T) +//! where +//! F: FnMut(&T) -> K, +//! K: Ord, +//! { +//! if f(&l) < f(&r) { +//! (l, r) +//! } else { +//! (r, l) +//! } +//! } +//! +//! +//! ``` +//! +//! +//! # Examples +//! +//! ### Alphabetic. +//! +//! This defines an ExtraChecks which checks that fields are alphabetically sorted +//! +//! ``` +//! use abi_stable::{ +//! abi_stability::{ +//! check_layout_compatibility, +//! extra_checks::{ +//! ExtraChecks, ExtraChecksError, ExtraChecksStaticRef, +//! ForExtraChecksImplementor, TypeCheckerMut, +//! }, +//! }, +//! sabi_extern_fn, +//! sabi_trait::prelude::TD_Opaque, +//! std_types::{RCow, RDuration, ROption, RResult, RStr, RString}, +//! type_layout::TypeLayout, +//! StableAbi, +//! }; +//! +//! use std::fmt::{self, Display}; +//! +//! fn main() { +//! let rect_layout = ::LAYOUT; +//! let person_layout = ::LAYOUT; +//! +//! // This passes because the fields are in order +//! check_layout_compatibility(rect_layout, rect_layout) +//! .unwrap_or_else(|e| panic!("{}", e)); +//! +//! // This errors because the struct's fields aren't in order +//! check_layout_compatibility(person_layout, person_layout).unwrap_err(); +//! } +//! +//! #[repr(C)] +//! #[derive(StableAbi)] +//! #[sabi(extra_checks = "InOrderChecker")] +//! struct Rectangle { +//! x: u32, +//! y: u32, +//! z: u32, +//! } +//! +//! #[repr(C)] +//! #[derive(StableAbi)] +//! #[sabi(extra_checks = "InOrderChecker")] +//! struct Person { +//! name: RString, +//! surname: RString, +//! age: RDuration, +//! } +//! +//! ///////////////////////////////////////// +//! +//! #[repr(C)] +//! #[derive(Debug, Clone, StableAbi)] +//! pub struct InOrderChecker; +//! +//! impl Display for InOrderChecker { +//! fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { +//! f.write_str( +//! "InOrderChecker: Checks that field names are sorted alphabetically.", +//! ) +//! } +//! } +//! +//! unsafe impl ExtraChecks for InOrderChecker { +//! fn type_layout(&self) -> &'static TypeLayout { +//! ::LAYOUT +//! } +//! +//! fn check_compatibility( +//! &self, +//! layout_containing_self: &'static TypeLayout, +//! layout_containing_other: &'static TypeLayout, +//! checker: TypeCheckerMut<'_>, +//! ) -> RResult<(), ExtraChecksError> { +//! Self::downcast_with_layout(layout_containing_other, checker, |_, _| { +//! let fields = match layout_containing_self.get_fields() { +//! Some(fields) if !fields.is_empty() => fields, +//! _ => return Ok(()), +//! }; +//! +//! let mut prev = fields.iter().next().unwrap(); +//! for curr in fields { +//! if prev.name() > curr.name() { +//! return Err(OutOfOrderError { +//! previous_one: prev.name(), +//! first_one: curr.name(), +//! }); +//! } +//! prev = curr; +//! } +//! Ok(()) +//! }) +//! } +//! +//! fn nested_type_layouts(&self) -> RCow<'_, [&'static TypeLayout]> { +//! RCow::from_slice(&[]) +//! } +//! } +//! +//! #[derive(Debug, Clone)] +//! pub struct OutOfOrderError { +//! previous_one: &'static str, +//! +//! /// The first field that is out of order. +//! first_one: &'static str, +//! } +//! +//! impl Display for OutOfOrderError { +//! fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { +//! writeln!( +//! f, +//! "Expected fields to be alphabetically sorted.\n\ +//! Found field '{}' before '{}'\ +//! ", +//! self.previous_one, self.first_one, +//! ) +//! } +//! } +//! +//! impl std::error::Error for OutOfOrderError {} +//! +//! +//! ``` +//! +//! ### Associated Constant. +//! +//! This defines an ExtraChecks which checks that an associated constant is +//! the same for both types. +//! +//! ``` +//! use abi_stable::{ +//! abi_stability::{ +//! check_layout_compatibility, +//! extra_checks::{ +//! ExtraChecks, ExtraChecksError, ExtraChecksStaticRef, +//! ForExtraChecksImplementor, TypeCheckerMut, +//! }, +//! }, +//! marker_type::UnsafeIgnoredType, +//! sabi_extern_fn, +//! sabi_trait::prelude::TD_Opaque, +//! std_types::{RCow, RDuration, RResult, RStr, RString}, +//! type_layout::TypeLayout, +//! GetStaticEquivalent, StableAbi, +//! }; +//! +//! use std::fmt::{self, Display}; +//! +//! fn main() { +//! let const0 = as StableAbi>::LAYOUT; +//! let const_second_0 = as StableAbi>::LAYOUT; +//! let const1 = as StableAbi>::LAYOUT; +//! let const2 = as StableAbi>::LAYOUT; +//! +//! check_layout_compatibility(const0, const0).unwrap(); +//! check_layout_compatibility(const_second_0, const_second_0).unwrap(); +//! check_layout_compatibility(const1, const1).unwrap(); +//! check_layout_compatibility(const2, const2).unwrap(); +//! +//! //////////// +//! // WithConstant and WithConstant are compatible with each other +//! // because their `GetConstant::NUMBER` associated constant is the same value. +//! check_layout_compatibility(const0, const_second_0).unwrap(); +//! check_layout_compatibility(const_second_0, const0).unwrap(); +//! +//! //////////// +//! // None of the lines below are compatible because their +//! // `GetConstant::NUMBER` associated constant isn't the same value. +//! check_layout_compatibility(const0, const1).unwrap_err(); +//! check_layout_compatibility(const0, const2).unwrap_err(); +//! +//! check_layout_compatibility(const1, const0).unwrap_err(); +//! check_layout_compatibility(const1, const2).unwrap_err(); +//! +//! check_layout_compatibility(const2, const0).unwrap_err(); +//! check_layout_compatibility(const2, const1).unwrap_err(); +//! } +//! +//! #[repr(C)] +//! #[derive(StableAbi)] +//! #[sabi( +//! // Replaces the C:StableAbi constraint with `C:GetStaticEquivalent` +//! // (a supertrait of StableAbi). +//! not_stableabi(C), +//! bound="C:GetConstant", +//! extra_checks="Self::CHECKER" +//! )] +//! struct WithConstant { +//! // UnsafeIgnoredType is equivalent to PhantomData, +//! // except that all `UnsafeIgnoredType` are considered the same type by `StableAbi`. +//! _marker: UnsafeIgnoredType, +//! } +//! +//! impl WithConstant { +//! const NEW: Self = Self { +//! _marker: UnsafeIgnoredType::NEW, +//! }; +//! } +//! +//! impl WithConstant +//! where +//! C: GetConstant, +//! { +//! const CHECKER: ConstChecker = ConstChecker { number: C::NUMBER }; +//! } +//! +//! trait GetConstant { +//! const NUMBER: u64; +//! } +//! +//! #[derive(GetStaticEquivalent)] +//! struct N0; +//! impl GetConstant for N0 { +//! const NUMBER: u64 = 0; +//! } +//! +//! #[derive(GetStaticEquivalent)] +//! struct SecondN0; +//! impl GetConstant for SecondN0 { +//! const NUMBER: u64 = 0; +//! } +//! +//! #[derive(GetStaticEquivalent)] +//! struct N1; +//! impl GetConstant for N1 { +//! const NUMBER: u64 = 1; +//! } +//! +//! #[derive(GetStaticEquivalent)] +//! struct N2; +//! impl GetConstant for N2 { +//! const NUMBER: u64 = 2; +//! } +//! +//! ///////////////////////////////////////// +//! +//! #[repr(C)] +//! #[derive(Debug, Clone, StableAbi)] +//! pub struct ConstChecker { +//! number: u64, +//! } +//! +//! impl Display for ConstChecker { +//! fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { +//! writeln!( +//! f, +//! "ConstChecker: \ +//! Checks that the associated constant for \ +//! for the other type is {}.\ +//! ", +//! self.number +//! ) +//! } +//! } +//! +//! unsafe impl ExtraChecks for ConstChecker { +//! fn type_layout(&self) -> &'static TypeLayout { +//! ::LAYOUT +//! } +//! +//! fn check_compatibility( +//! &self, +//! layout_containing_self: &'static TypeLayout, +//! layout_containing_other: &'static TypeLayout, +//! checker: TypeCheckerMut<'_>, +//! ) -> RResult<(), ExtraChecksError> { +//! Self::downcast_with_layout(layout_containing_other, checker, |other, _| { +//! if self.number == other.number { +//! Ok(()) +//! } else { +//! Err(UnequalConstError { +//! expected: self.number, +//! found: other.number, +//! }) +//! } +//! }) +//! } +//! +//! fn nested_type_layouts(&self) -> RCow<'_, [&'static TypeLayout]> { +//! RCow::from_slice(&[]) +//! } +//! } +//! +//! #[derive(Debug, Clone)] +//! pub struct UnequalConstError { +//! expected: u64, +//! found: u64, +//! } +//! +//! impl Display for UnequalConstError { +//! fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { +//! writeln!( +//! f, +//! "Expected the `GetConstant::NUMBER` associated constant to be:\ +//! \n {}\ +//! \nFound:\ +//! \n {}\ +//! ", +//! self.expected, self.found, +//! ) +//! } +//! } +//! +//! impl std::error::Error for UnequalConstError {} +//! +//! +//! ``` +//! use crate::{ rtry, sabi_trait, @@ -722,27 +678,24 @@ pub unsafe trait ExtraChecks: 'static + Debug + Display + Clone + Send + Sync { /// because `UTypeId`s from different dynamic libraries are incompatible. fn type_layout(&self) -> &'static TypeLayout; - /** - - Checks that `self` is compatible another type which implements ExtraChecks. - - Calling `check_layout_compatibility` from here will immediately return an error, - prefer doing `checker.check_compatibility(...)` instead. - - # Parameters - - `layout_containing_self`: - The TypeLayout that contains this `ExtraChecks` trait object in the extra_checks field. - - `layout_containing_other`: - The TypeLayout that contains the `other` `ExtraChecks` trait object in the extra_checks field, - which `self` is compared to. - - `checker`: - The type checker,which allows this function to check type layouts. - - - */ + /// Checks that `self` is compatible another type which implements ExtraChecks. + /// + /// Calling `check_layout_compatibility` from here will immediately return an error, + /// prefer doing `checker.check_compatibility(...)` instead. + /// + /// # Parameters + /// + /// `layout_containing_self`: + /// The TypeLayout that contains this `ExtraChecks` trait object in the extra_checks field. + /// + /// `layout_containing_other`: + /// The TypeLayout that contains the `other` `ExtraChecks` trait object in the extra_checks field, + /// which `self` is compared to. + /// + /// `checker`: + /// The type checker,which allows this function to check type layouts. + /// + /// fn check_compatibility( &self, layout_containing_self: &'static TypeLayout, @@ -755,40 +708,38 @@ pub unsafe trait ExtraChecks: 'static + Debug + Display + Clone + Send + Sync { /// This is necessary for the Debug implementation of `TypeLayout`. fn nested_type_layouts(&self) -> RCow<'_, [&'static TypeLayout]>; - /** - Combines this ExtraChecks trait object with another one. - - To guarantee that the `extra_checks` - associated with a type (inside `::LAYOUT.extra_cheks` ) - has a single representative value across all dynamic libraries, - you must override this method, - and return `ROk(RSome(_))` by combining `self` and `other` in some way. - - - # Parameters - - `other`: - The other ExtraChecks trait object that this is combined with.. - - `checker`: - The trait object of the type checker,which allows this function to check type layouts. - - - # Return value - - This returns: - - - `ROk(RNone)`: - If `self` doesn't need to be unified across all dynamic libraries, - or the representative version doesn't need to be updated. - - - `ROk(RSome(_))`: - If `self` needs to be unified across all dynamic libraries, - returning the combined `self` and `other`. - - - `RErr(_)`: If there was a problem unifying `self` and `other`. - - */ + /// Combines this ExtraChecks trait object with another one. + /// + /// To guarantee that the `extra_checks` + /// associated with a type (inside `::LAYOUT.extra_cheks` ) + /// has a single representative value across all dynamic libraries, + /// you must override this method, + /// and return `ROk(RSome(_))` by combining `self` and `other` in some way. + /// + /// + /// # Parameters + /// + /// `other`: + /// The other ExtraChecks trait object that this is combined with.. + /// + /// `checker`: + /// The trait object of the type checker,which allows this function to check type layouts. + /// + /// + /// # Return value + /// + /// This returns: + /// + /// - `ROk(RNone)`: + /// If `self` doesn't need to be unified across all dynamic libraries, + /// or the representative version doesn't need to be updated. + /// + /// - `ROk(RSome(_))`: + /// If `self` needs to be unified across all dynamic libraries, + /// returning the combined `self` and `other`. + /// + /// - `RErr(_)`: If there was a problem unifying `self` and `other`. + /// #[sabi(last_prefix_field)] fn combine( &self, @@ -813,26 +764,24 @@ pub type ExtraChecksBox = ExtraChecks_TO>; /// An extension trait for `ExtraChecks` implementors. pub trait ForExtraChecksImplementor: StableAbi + ExtraChecks { - /** - Accesses the `ExtraChecks` field in `layout_containing_other`, downcasted into `Self`. - - If the closure returns an `ExtraChecksError`,it'll be returned unmodified and unwrapped. - - # Returns - - - ROk(_): - If `other` was downcasted to `Self`,and `f` did not return any errors. - - - RErr(ExtraChecksError::NoneExtraChecks): - If`layout_containing_other` does not contain an ExtraChecks trait object. - - - RErr(ExtraChecksError::TypeChecker): - If there is an error while type checking. - - - RErr(ExtraChecksError::ExtraChecks(_)): - If there is an custom error within the function. - - */ + /// Accesses the `ExtraChecks` field in `layout_containing_other`, downcasted into `Self`. + /// + /// If the closure returns an `ExtraChecksError`,it'll be returned unmodified and unwrapped. + /// + /// # Returns + /// + /// - ROk(_): + /// If `other` was downcasted to `Self`,and `f` did not return any errors. + /// + /// - RErr(ExtraChecksError::NoneExtraChecks): + /// If`layout_containing_other` does not contain an ExtraChecks trait object. + /// + /// - RErr(ExtraChecksError::TypeChecker): + /// If there is an error while type checking. + /// + /// - RErr(ExtraChecksError::ExtraChecks(_)): + /// If there is an custom error within the function. + /// fn downcast_with_layout( layout_containing_other: &'static TypeLayout, checker: TypeCheckerMut<'_>, @@ -850,23 +799,20 @@ pub trait ForExtraChecksImplementor: StableAbi + ExtraChecks { Self::downcast_with_object(other, checker, f) } - /** - Allows one to access `other` downcast into `Self`. - - If the closure returns an `ExtraChecksError`,it'll be returned unmodified and unwrapped. - - # Returns - - - ROk(_): - If `other` could be downcasted to `Self`,and `f` did not return any errors. - - - RErr(ExtraChecksError::TypeChecker): - If there is an error while type checking. - - - RErr(ExtraChecksError::ExtraChecks(_)): - If there is an custom error within the function. - - */ + /// Allows one to access `other` downcast into `Self`. + /// + /// If the closure returns an `ExtraChecksError`,it'll be returned unmodified and unwrapped. + /// + /// # Returns + /// + /// - ROk(_): + /// If `other` could be downcasted to `Self`,and `f` did not return any errors. + /// + /// - RErr(ExtraChecksError::TypeChecker): + /// If there is an error while type checking. + /// + /// - RErr(ExtraChecksError::ExtraChecks(_)): + /// If there is an custom error within the function. fn downcast_with_object( other: ExtraChecksRef<'_>, mut checker: TypeCheckerMut<'_>, diff --git a/abi_stable/src/abi_stability/get_static_equivalent.rs b/abi_stable/src/abi_stability/get_static_equivalent.rs index b3eddafc..1cf9ea8d 100644 --- a/abi_stable/src/abi_stability/get_static_equivalent.rs +++ b/abi_stable/src/abi_stability/get_static_equivalent.rs @@ -1,7 +1,4 @@ -/*! -Containst the `GetStaticEquivalent_` trait and related items. - -*/ +//! Contains the `GetStaticEquivalent_` trait and related items. /// A type that stands in for `Self`,used to create a `UTypeId` for doing layout checking. /// diff --git a/abi_stable/src/abi_stability/stable_abi_trait.rs b/abi_stable/src/abi_stability/stable_abi_trait.rs index 1b2f36b5..c3b11039 100644 --- a/abi_stable/src/abi_stability/stable_abi_trait.rs +++ b/abi_stable/src/abi_stability/stable_abi_trait.rs @@ -1,6 +1,4 @@ -/*! -Where the StableAbi trait is declared,as well as related types/traits. -*/ +//! Where the StableAbi trait is declared,as well as related types/traits. use core_extensions::type_level_bool::{Boolean, False, True}; use std::{ diff --git a/abi_stable/src/docs/library_evolution.rs b/abi_stable/src/docs/library_evolution.rs index 97b0594b..2aef4bff 100644 --- a/abi_stable/src/docs/library_evolution.rs +++ b/abi_stable/src/docs/library_evolution.rs @@ -39,24 +39,19 @@ It is not possible to add variants or fields to exhaustive enums. Exhaustive enums being ones that are declared like this: ```rust -use abi_stable::{ - std_types::RString, - StableAbi, -}; +use abi_stable::{std_types::RString, StableAbi}; #[repr(u8)] #[derive(StableAbi)] -enum Exhaustive{ +enum Exhaustive { A, B(RString), C, - D{ - hello:u32, - world:i64, - }, + D { hello: u32, world: i64 }, } # fn main(){} + ``` ### Non-exhaustive enums @@ -82,18 +77,19 @@ Example field-less enum implemented as a struct wrapping an integer: use abi_stable::StableAbi; #[repr(transparent)] -#[derive(StableAbi,Eq,PartialEq)] +#[derive(StableAbi, Eq, PartialEq)] pub struct Direction(u8); -impl Direction{ - pub const LEFT :Self=Direction(0); - pub const RIGHT:Self=Direction(1); - pub const UP :Self=Direction(2); - pub const DOWN :Self=Direction(3); +impl Direction { + pub const LEFT: Self = Direction(0); + pub const RIGHT: Self = Direction(1); + pub const UP: Self = Direction(2); + pub const DOWN: Self = Direction(3); } # fn main(){} + ``` diff --git a/abi_stable/src/docs/prefix_types.rs b/abi_stable/src/docs/prefix_types.rs index 8c110e22..d0533b5b 100644 --- a/abi_stable/src/docs/prefix_types.rs +++ b/abi_stable/src/docs/prefix_types.rs @@ -65,25 +65,26 @@ Declaring a Prefix-type. ``` use abi_stable::{ + std_types::{RDuration, RStr}, StableAbi, - std_types::{RDuration,RStr}, }; #[repr(C)] #[derive(StableAbi)] -#[sabi(kind(Prefix(prefix_ref="Module_Ref")))] +#[sabi(kind(Prefix(prefix_ref = "Module_Ref")))] #[sabi(missing_field(panic))] pub struct Module { - pub lib_name:RStr<'static>, + pub lib_name: RStr<'static>, #[sabi(last_prefix_field)] - pub elapsed:extern "C" fn()->RDuration, + pub elapsed: extern "C" fn() -> RDuration, - pub description:RStr<'static>, + pub description: RStr<'static>, } # fn main(){} + ``` In this example: @@ -110,32 +111,32 @@ For constructing a vtable, you can look at [the next example](#vtable_constructi ``` use abi_stable::{ + extern_fn_panic_handling, prefix_type::{PrefixTypeTrait, WithMetadata}, - std_types::{RDuration,RStr}, - extern_fn_panic_handling, staticref, + staticref, + std_types::{RDuration, RStr}, StableAbi, }; -fn main(){ +fn main() { assert_eq!(MODULE_REF.lib_name().as_str(), "foo"); assert_eq!(MODULE_REF.elapsed()(1000), RDuration::from_secs(1)); assert_eq!(MODULE_REF.description().as_str(), "this is a module field"); - } #[repr(C)] #[derive(StableAbi)] -#[sabi(kind(Prefix(prefix_ref="Module_Ref")))] +#[sabi(kind(Prefix(prefix_ref = "Module_Ref")))] #[sabi(missing_field(panic))] pub struct Module { - pub lib_name:RStr<'static>, + pub lib_name: RStr<'static>, #[sabi(last_prefix_field)] - pub elapsed:extern "C" fn(T)->RDuration, + pub elapsed: extern "C" fn(T) -> RDuration, - pub description:RStr<'static>, + pub description: RStr<'static>, } impl Module { @@ -150,14 +151,14 @@ impl Module { )); } - const MODULE_REF: Module_Ref = Module_Ref(Module::MODULE_VAL.as_prefix()); extern "C" fn elapsed(milliseconds: u64) -> RDuration { - extern_fn_panic_handling!{ + extern_fn_panic_handling! { RDuration::from_millis(milliseconds) } } + ``` @@ -167,13 +168,13 @@ This eaxmple demonstrates how you can construct a vtable. ```rust use abi_stable::{ + extern_fn_panic_handling, marker_type::ErasedObject, prefix_type::{PrefixTypeTrait, WithMetadata}, - extern_fn_panic_handling, staticref, - StableAbi, + staticref, StableAbi, }; -fn main(){ +fn main() { unsafe { let vtable = MakeVTable::::MAKE; assert_eq!( @@ -192,29 +193,28 @@ fn main(){ #[repr(C)] #[derive(StableAbi)] -#[sabi(kind(Prefix(prefix_ref="VTable_Ref")))] +#[sabi(kind(Prefix(prefix_ref = "VTable_Ref")))] #[sabi(missing_field(panic))] pub struct VTable { #[sabi(last_prefix_field)] - pub get_number: unsafe extern "C" fn(*const ErasedObject)->u64, + pub get_number: unsafe extern "C" fn(*const ErasedObject) -> u64, } - // A dummy struct, used purely for its associated constants. struct MakeVTable(T); impl MakeVTable where - T: Copy + Into + T: Copy + Into, { unsafe extern "C" fn get_number(this: *const ErasedObject) -> u64 { - extern_fn_panic_handling!{ + extern_fn_panic_handling! { (*this.cast::()).into() * 4 } } // This macro declares a `StaticRef>` constant. - staticref!{pub const VAL: WithMetadata = WithMetadata::new( + staticref! {pub const VAL: WithMetadata = WithMetadata::new( PrefixTypeTrait::METADATA, VTable{get_number: Self::get_number}, )} @@ -233,17 +233,16 @@ Here is the implementation of a Box-like type,which uses a vtable that is a pref ``` use std::{ - ops::{Deref,DerefMut}, marker::PhantomData, mem::ManuallyDrop, + ops::{Deref, DerefMut}, }; use abi_stable::{ - StableAbi, extern_fn_panic_handling, - staticref, pointer_trait::{CallReferentDrop, TransmuteElement}, prefix_type::{PrefixTypeTrait, WithMetadata}, + staticref, StableAbi, }; /// An ffi-safe `Box` @@ -257,67 +256,57 @@ pub struct BoxLike { _marker: PhantomData, } +impl BoxLike { + pub fn new(value: T) -> Self { + let box_ = Box::new(value); -impl BoxLike{ - pub fn new(value:T)->Self{ - let box_=Box::new(value); - - Self{ - data:Box::into_raw(box_), + Self { + data: Box::into_raw(box_), vtable: BoxVtable::VTABLE, - _marker:PhantomData, + _marker: PhantomData, } } - fn vtable(&self)-> BoxVtable_Ref{ + fn vtable(&self) -> BoxVtable_Ref { self.vtable } /// Extracts the value this owns. - pub fn into_inner(self)->T{ - let this=ManuallyDrop::new(self); - let vtable=this.vtable(); - unsafe{ + pub fn into_inner(self) -> T { + let this = ManuallyDrop::new(self); + let vtable = this.vtable(); + unsafe { // Must copy this before calling `vtable.destructor()` // because otherwise it would be reading from a dangling pointer. - let ret=this.data.read(); - vtable.destructor()(this.data,CallReferentDrop::No); + let ret = this.data.read(); + vtable.destructor()(this.data, CallReferentDrop::No); ret } } } - impl Deref for BoxLike { - type Target=T; + type Target = T; - fn deref(&self)->&T{ - unsafe{ - &(*self.data) - } + fn deref(&self) -> &T { + unsafe { &(*self.data) } } } impl DerefMut for BoxLike { - fn deref_mut(&mut self)->&mut T{ - unsafe{ - &mut (*self.data) - } + fn deref_mut(&mut self) -> &mut T { + unsafe { &mut (*self.data) } } } +impl Drop for BoxLike { + fn drop(&mut self) { + let vtable = self.vtable(); -impl Drop for BoxLike{ - fn drop(&mut self){ - let vtable=self.vtable(); - - unsafe{ - vtable.destructor()(self.data,CallReferentDrop::Yes) - } + unsafe { vtable.destructor()(self.data, CallReferentDrop::Yes) } } } - // `#[sabi(kind(Prefix))]` Declares this type as being a prefix-type, // generating both of these types: // @@ -331,7 +320,6 @@ impl Drop for BoxLike{ #[derive(StableAbi)] #[sabi(kind(Prefix))] pub(crate) struct BoxVtable { - /// The `#[sabi(last_prefix_field)]` attribute here means that this is /// the last field in this struct that was defined in the /// first compatible version of the library @@ -346,10 +334,9 @@ pub(crate) struct BoxVtable { destructor: unsafe extern "C" fn(*mut T, CallReferentDrop), } - // This is how ffi-safe pointers to generic prefix types are constructed // at compile-time. -impl BoxVtable{ +impl BoxVtable { // This macro declares a `StaticRef>>` constant. // // StaticRef represents a reference to data that lives forever, @@ -362,9 +349,8 @@ impl BoxVtable{ }, )); - const VTABLE: BoxVtable_Ref = { - BoxVtable_Ref( Self::VTABLE_VAL.as_prefix() ) - }; + const VTABLE: BoxVtable_Ref = + { BoxVtable_Ref(Self::VTABLE_VAL.as_prefix()) }; } unsafe extern "C" fn destroy_box(v: *mut T, call_drop: CallReferentDrop) { @@ -388,13 +374,12 @@ This declares,initializes,and uses a module. ``` use abi_stable::{ - StableAbi, + prefix_type::{PrefixTypeTrait, WithMetadata}, sabi_extern_fn, std_types::RDuration, - prefix_type::{PrefixTypeTrait, WithMetadata}, + StableAbi, }; - // `#[sabi(kind(Prefix))]` Declares this type as being a prefix-type, // generating both of these types: // @@ -408,7 +393,6 @@ use abi_stable::{ #[derive(StableAbi)] #[sabi(kind(Prefix))] pub struct PersonMod { - /// The `#[sabi(last_prefix_field)]` attribute here means that this is /// the last field in this struct that was defined in the /// first compatible version of the library @@ -420,63 +404,60 @@ pub struct PersonMod { /// at which point it would be moved to the last field at the time. /// #[sabi(last_prefix_field)] - pub customer_for: extern "C" fn(Id)->RDuration, + pub customer_for: extern "C" fn(Id) -> RDuration, // The default behavior for the getter is to return an Option, // if the field exists it returns Some(_), // otherwise it returns None. - pub bike_count: extern "C" fn(Id)->u32, + pub bike_count: extern "C" fn(Id) -> u32, // The getter for this field panics if the field doesn't exist. #[sabi(missing_field(panic))] - pub visits: extern "C" fn(Id)->u32, + pub visits: extern "C" fn(Id) -> u32, // The getter for this field returns `default_score()` if the field doesn't exist. - #[sabi(missing_field(with="default_score"))] - pub score: extern "C" fn(Id)->u32, + #[sabi(missing_field(with = "default_score"))] + pub score: extern "C" fn(Id) -> u32, // The getter for this field returns `Default::default()` if the field doesn't exist. #[sabi(missing_field(default))] - pub visit_length: Option< extern "C" fn(Id)->RDuration >, - + pub visit_length: Option RDuration>, } -fn default_score()-> extern "C" fn(Id)->u32 { - extern "C" fn default(_:Id)->u32{ +fn default_score() -> extern "C" fn(Id) -> u32 { + extern "C" fn default(_: Id) -> u32 { 1000 } default } -type Id=u32; +type Id = u32; -# # static VARS:&[(RDuration,u32)]=&[ # (RDuration::new(1_000,0),10), # (RDuration::new(1_000_000,0),1), # ]; -# + # #[sabi_extern_fn] # fn customer_for(id:Id)->RDuration{ # VARS[id as usize].0 # } -# + # #[sabi_extern_fn] # fn bike_count(id:Id)->u32{ # VARS[id as usize].1 # } -# + # #[sabi_extern_fn] # fn visits(id:Id)->u32{ # VARS[id as usize].1 # } -# + # #[sabi_extern_fn] # fn score(id:Id)->u32{ # VARS[id as usize].1 # } -# /* ... @@ -488,33 +469,28 @@ type Id=u32; const _MODULE_WM_: &WithMetadata = &WithMetadata::new( PrefixTypeTrait::METADATA, - PersonMod{ + PersonMod { customer_for, bike_count, visits, score, - visit_length:None, - } + visit_length: None, + }, ); const MODULE: PersonMod_Ref = PersonMod_Ref(_MODULE_WM_.static_as_prefix()); // Getting the value for every field of `MODULE`. -let customer_for: extern "C" fn(Id)->RDuration = - MODULE.customer_for(); +let customer_for: extern "C" fn(Id) -> RDuration = MODULE.customer_for(); -let bike_count: Optionu32> = - MODULE.bike_count(); +let bike_count: Option u32> = MODULE.bike_count(); -let visits: extern "C" fn(Id)->u32= - MODULE.visits(); +let visits: extern "C" fn(Id) -> u32 = MODULE.visits(); -let score: extern "C" fn(Id)->u32= - MODULE.score(); +let score: extern "C" fn(Id) -> u32 = MODULE.score(); -let visit_length: OptionRDuration> = - MODULE.visit_length(); +let visit_length: Option RDuration> = MODULE.visit_length(); # } diff --git a/abi_stable/src/docs/sabi_nonexhaustive.rs b/abi_stable/src/docs/sabi_nonexhaustive.rs index 863a2d97..181b8626 100644 --- a/abi_stable/src/docs/sabi_nonexhaustive.rs +++ b/abi_stable/src/docs/sabi_nonexhaustive.rs @@ -173,39 +173,38 @@ For a more realistic example you can look at the ``` use abi_stable::{ - StableAbi, - rtry, - sabi_extern_fn, - external_types::{RawValueBox,RawValueRef}, - nonexhaustive_enum::{NonExhaustive,SerializeEnum,DeserializeEnum}, + external_types::{RawValueBox, RawValueRef}, + nonexhaustive_enum::{DeserializeEnum, NonExhaustive, SerializeEnum}, prefix_type::{PrefixTypeTrait, WithMetadata}, - std_types::{RBoxError,RString,RStr,RResult,ROk,RErr}, + rtry, sabi_extern_fn, + std_types::{RBoxError, RErr, ROk, RResult, RStr, RString}, traits::IntoReprC, + StableAbi, }; -use serde::{Deserialize,Serialize}; +use serde::{Deserialize, Serialize}; #[repr(u8)] -#[derive(StableAbi,Debug,Clone,PartialEq,Deserialize,Serialize)] +#[derive(StableAbi, Debug, Clone, PartialEq, Deserialize, Serialize)] #[sabi(kind(WithNonExhaustive( - // Determines the maximum size of this enum in semver compatible versions. - size="[usize;10]", - // Determines the traits that are required when wrapping this enum in NonExhaustive, - // and are then available with it. - traits(Debug,Clone,PartialEq,Serialize,Deserialize), +// Determines the maximum size of this enum in semver compatible versions. +size="[usize;10]", +// Determines the traits that are required when wrapping this enum in NonExhaustive, +// and are then available with it. +traits(Debug,Clone,PartialEq,Serialize,Deserialize), )))] // The `#[sabi(with_constructor)]` helper attribute here generates constructor functions // that look take the fields of the variant as parameters and return a `ValidTag_NE`. #[sabi(with_constructor)] -pub enum ValidTag{ +pub enum ValidTag { #[doc(hidden)] __NonExhaustive, Foo, Bar, - Tag{ - name:RString, - tag:RString, - } + Tag { + name: RString, + tag: RString, + }, } /* @@ -222,30 +221,24 @@ pub type ValidTag_NE= impl SerializeEnum for ValidTag_Interface { /// A type that `ValidTag_NE` is converted into(inside `SerializeEnum::serialize_enum`), /// and then serialized. - type Proxy=RawValueBox; - - fn serialize_enum(this:&ValidTag_NE) -> Result{ - Module::VALUE - .serialize_tag()(this) - .into_result() + type Proxy = RawValueBox; + fn serialize_enum(this: &ValidTag_NE) -> Result { + Module::VALUE.serialize_tag()(this).into_result() } } /// This describes how the enum is deserialized. -impl<'a> DeserializeEnum<'a,ValidTag_NE> for ValidTag_Interface{ +impl<'a> DeserializeEnum<'a, ValidTag_NE> for ValidTag_Interface { /// A type that is deserialized, /// and then converted into `ValidTag_NE` inside `DeserializeEnum::deserialize_enum`. - type Proxy=RawValueRef<'a>; + type Proxy = RawValueRef<'a>; - fn deserialize_enum(s: RawValueRef<'a>) -> Result{ - Module::VALUE - .deserialize_tag()(s.get_rstr()) - .into_result() + fn deserialize_enum(s: RawValueRef<'a>) -> Result { + Module::VALUE.deserialize_tag()(s.get_rstr()).into_result() } } - # fn main(){ assert_eq!( @@ -259,17 +252,18 @@ assert_eq!( ); assert_eq!( - serde_json::from_str::(r#" - {"Tag":{ - "name":"what", - "tag":"the" - }} - "#).unwrap(), - ValidTag::Tag_NE("what".into(),"the".into()) + serde_json::from_str::( + r#" + {"Tag":{ + "name":"what", + "tag":"the" + }} +"# + ) + .unwrap(), + ValidTag::Tag_NE("what".into(), "the".into()) ); - - assert_eq!( &serde_json::to_string(&ValidTag::Foo_NE()).unwrap(), r#""Foo""#, @@ -300,15 +294,17 @@ assert_eq!( #[derive(StableAbi)] #[sabi(kind(Prefix))] #[sabi(missing_field(panic))] -pub struct Module{ - pub serialize_tag:extern "C" fn(&ValidTag_NE)->RResult, +pub struct Module { + pub serialize_tag: + extern "C" fn(&ValidTag_NE) -> RResult, /// `#[sabi(last_prefix_field)]`means that it is the last field in the struct /// that was defined in the first compatible version of the library /// (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), /// requiring new fields to always be added below preexisting ones. #[sabi(last_prefix_field)] - pub deserialize_tag:extern "C" fn(s:RStr<'_>)->RResult, + pub deserialize_tag: + extern "C" fn(s: RStr<'_>) -> RResult, } // This is how you can construct `Module` in a way that allows it to become generic later. @@ -327,7 +323,7 @@ impl Module { }, )); - const VALUE: Module_Ref = Module_Ref( Self::TMP0.as_prefix() ); + const VALUE: Module_Ref = Module_Ref(Self::TMP0.as_prefix()); } ///////////////////////////////////////////////////////////////////////////////////////// @@ -335,28 +331,25 @@ impl Module { ///////////////////////////////////////////////////////////////////////////////////////// #[sabi_extern_fn] -pub fn serialize_tag(enum_:&ValidTag_NE)->RResult{ - let enum_=rtry!( enum_.as_enum().into_c() ); +pub fn serialize_tag(enum_: &ValidTag_NE) -> RResult { + let enum_ = rtry!(enum_.as_enum().into_c()); match serde_json::to_string(&enum_) { - Ok(v)=>{ - RawValueBox::try_from_string(v) - .map_err(RBoxError::new) - .into_c() - } - Err(e)=>RErr(RBoxError::new(e)), + Ok(v) => RawValueBox::try_from_string(v) + .map_err(RBoxError::new) + .into_c(), + Err(e) => RErr(RBoxError::new(e)), } } #[sabi_extern_fn] -pub fn deserialize_tag(s:RStr<'_>)->RResult{ +pub fn deserialize_tag(s: RStr<'_>) -> RResult { match serde_json::from_str::(s.into()) { Ok(x) => ROk(NonExhaustive::new(x)), Err(e) => RErr(RBoxError::new(e)), } } - ``` @@ -370,25 +363,24 @@ because one of the variant contains a generic type. ``` use abi_stable::{ - StableAbi, - nonexhaustive_enum::{NonExhaustiveFor,NonExhaustive}, - std_types::{RBox,RString}, + nonexhaustive_enum::{NonExhaustive, NonExhaustiveFor}, sabi_trait, + std_types::{RBox, RString}, + StableAbi, }; use std::{ cmp::PartialEq, - fmt::{self,Debug,Display}, + fmt::{self, Debug, Display}, }; - #[repr(u8)] -#[derive(StableAbi,Debug,Clone,PartialEq)] +#[derive(StableAbi, Debug, Clone, PartialEq)] #[sabi(kind(WithNonExhaustive( - size="[usize;3]", - traits(Debug,Display,Clone,PartialEq), + size = "[usize;3]", + traits(Debug, Display, Clone, PartialEq), )))] -pub enum Message{ +pub enum Message { #[doc(hidden)] __NonExhaustive, SaysHello, @@ -401,70 +393,64 @@ pub enum Message{ // Available since 1.1 //////////////////////////////////////// #[sabi(with_boxed_constructor)] - SaysThankYou(RBox) - + SaysThankYou(RBox), } - impl Display for Message where - T:Display + T: Display, { - fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Message::__NonExhaustive=>unreachable!(), - Message::SaysHello=>write!(f,"Hello!"), - Message::SaysGoodbye=>write!(f,"Goodbye!"), - Message::Custom(custom)=>Display::fmt(&**custom,f), - Message::SaysThankYou(x)=>writeln!(f,"Thank you,{}!",x.to), + Message::__NonExhaustive => unreachable!(), + Message::SaysHello => write!(f, "Hello!"), + Message::SaysGoodbye => write!(f, "Goodbye!"), + Message::Custom(custom) => Display::fmt(&**custom, f), + Message::SaysThankYou(x) => writeln!(f, "Thank you,{}!", x.to), } } } - // Only available since 1.1 #[repr(C)] -#[derive(StableAbi,Debug,Clone,PartialEq)] -pub struct SaysThankYou{ - to:RString, +#[derive(StableAbi, Debug, Clone, PartialEq)] +pub struct SaysThankYou { + to: RString, } # fn main(){ // Constructing Message::Custom wrapped in a NonExhaustive { - let custom_message:Message_NE= - Message::Custom_NE("Hello".into()); + let custom_message: Message_NE = Message::Custom_NE("Hello".into()); - let custom_message_desugar:Message_NE={ - let x=RBox::new("Hello".into()); - let x=Message::Custom(x); + let custom_message_desugar: Message_NE = { + let x = RBox::new("Hello".into()); + let x = Message::Custom(x); NonExhaustive::new(x) }; - assert_eq!(custom_message,custom_message_desugar); + assert_eq!(custom_message, custom_message_desugar); } - // Constructing Message::SaysThankYou wrapped in a NonExhaustive // This variant is only available since 1.1 { - let says_thank_you:Message_NE= - Message::SaysThankYou_NE(SaysThankYou{ - to:"Hello".into(), - }); - - let says_thank_you_desugar:Message_NE={ - let x=SaysThankYou{to:"Hello".into()}; - let x=Message::SaysThankYou(RBox::new(x)); + let says_thank_you: Message_NE = + Message::SaysThankYou_NE(SaysThankYou { to: "Hello".into() }); + + let says_thank_you_desugar: Message_NE = { + let x = SaysThankYou { to: "Hello".into() }; + let x = Message::SaysThankYou(RBox::new(x)); NonExhaustive::new(x) }; - assert_eq!(says_thank_you,says_thank_you_desugar); + assert_eq!(says_thank_you, says_thank_you_desugar); } # } + ``` @@ -476,107 +462,96 @@ This example shows how one can use RSmallBox to define a generic nonexhausitve e ``` use abi_stable::{ - sabi_types::RSmallBox, - std_types::{RString,RVec}, reexports::SelfOps, + sabi_types::RSmallBox, + std_types::{RString, RVec}, StableAbi, }; #[repr(u8)] -#[derive(StableAbi,Debug,Clone,PartialEq)] +#[derive(StableAbi, Debug, Clone, PartialEq)] #[sabi(kind(WithNonExhaustive( - // Determines the maximum size of this enum in semver compatible versions. - // This is 11 usize large because: - // - The enum discriminant occupies 1 usize(because the enum is usize aligned). - // - RSmallBox: is 10 usize large - size="[usize;11]", - // Determines the traits that are required when wrapping this enum in NonExhaustive, - // and are then available with it. - traits(Debug,Clone,PartialEq), +// Determines the maximum size of this enum in semver compatible versions. +// This is 11 usize large because: +// - The enum discriminant occupies 1 usize(because the enum is usize aligned). +// - RSmallBox: is 10 usize large +size="[usize;11]", +// Determines the traits that are required when wrapping this enum in NonExhaustive, +// and are then available with it. +traits(Debug,Clone,PartialEq), )))] #[sabi(with_constructor)] -pub enum SomeEnum{ +pub enum SomeEnum { #[doc(hidden)] __NonExhaustive, Foo, Bar, - Crash{ - reason:RString, - animal:RString, + Crash { + reason: RString, + animal: RString, }, // This variant was added in a newer (compatible) version of the library. #[sabi(with_boxed_constructor)] - Other(RSmallBox) + Other(RSmallBox), } -impl SomeEnum{ - pub fn is_inline(&self)->bool{ +impl SomeEnum { + pub fn is_inline(&self) -> bool { match self { - SomeEnum::__NonExhaustive=>true, - SomeEnum::Foo=>true, - SomeEnum::Bar=>true, - SomeEnum::Crash{..}=>true, - SomeEnum::Other(rsbox)=>RSmallBox::is_inline(rsbox), + SomeEnum::__NonExhaustive => true, + SomeEnum::Foo => true, + SomeEnum::Bar => true, + SomeEnum::Crash { .. } => true, + SomeEnum::Other(rsbox) => RSmallBox::is_inline(rsbox), } } - pub fn is_heap_allocated(&self)->bool{ + pub fn is_heap_allocated(&self) -> bool { !self.is_inline() } - } - #[repr(C)] -#[derive(StableAbi,Debug,Clone,PartialEq)] -pub struct FullName{ - pub name:RString, - pub surname:RString, +#[derive(StableAbi, Debug, Clone, PartialEq)] +pub struct FullName { + pub name: RString, + pub surname: RString, } - /// A way to represent a frozen `Vec>`. /// /// This example just constructs NestedVec directly, /// realistically it would be constructed in an associated function of NestedVec. #[repr(C)] -#[derive(StableAbi,Debug,Clone,PartialEq)] -pub struct NestedVec{ - indices:RVec, - nested:RVec, - dummy_field:u32, +#[derive(StableAbi, Debug, Clone, PartialEq)] +pub struct NestedVec { + indices: RVec, + nested: RVec, + dummy_field: u32, } - # fn main(){ -let crash=SomeEnum::<()>::Crash_NE("No reason".into(),"Bandi____".into()); +let crash = SomeEnum::<()>::Crash_NE("No reason".into(), "Bandi____".into()); -let other_fullname= - SomeEnum::Other_NE(FullName{ name:"R__e".into(), surname:"L_____e".into() }); +let other_fullname = SomeEnum::Other_NE(FullName { + name: "R__e".into(), + surname: "L_____e".into(), +}); -let other_nestedlist={ - let nestedlist=NestedVec{ - indices:vec![0,2,3,5].into(), +let other_nestedlist = { + let nestedlist = NestedVec { + indices: vec![0, 2, 3, 5].into(), // Each line here is a nested list. - nested:vec![ - false,false, - true, - true,false, - true,true,true, - ].into(), - dummy_field:0, + nested: vec![false, false, true, true, false, true, true, true].into(), + dummy_field: 0, }; SomeEnum::Other_NE(nestedlist) }; - - - -assert!( crash.as_enum().unwrap().is_inline() ); -assert!( other_fullname.as_enum().unwrap().is_inline() ); -assert!( other_nestedlist.as_enum().unwrap().is_heap_allocated() ); - +assert!(crash.as_enum().unwrap().is_inline()); +assert!(other_fullname.as_enum().unwrap().is_inline()); +assert!(other_nestedlist.as_enum().unwrap().is_heap_allocated()); # } @@ -598,183 +573,185 @@ won't be convertible back into `Event`. ``` use abi_stable::{ - StableAbi, - nonexhaustive_enum::{NonExhaustiveFor,NonExhaustive}, - std_types::{RString,RArc}, + nonexhaustive_enum::{NonExhaustive, NonExhaustiveFor}, sabi_trait, + std_types::{RArc, RString}, + StableAbi, }; - #[doc(hidden)] #[repr(C)] -#[derive(StableAbi,Debug,Clone,Copy,PartialEq)] -pub struct ObjectId( - pub usize -); +#[derive(StableAbi, Debug, Clone, Copy, PartialEq)] +pub struct ObjectId(pub usize); #[doc(hidden)] #[repr(C)] -#[derive(StableAbi,Debug,Clone,Copy,PartialEq)] -pub struct GroupId( - pub usize -); - +#[derive(StableAbi, Debug, Clone, Copy, PartialEq)] +pub struct GroupId(pub usize); #[repr(u8)] -#[derive(StableAbi,Debug,Clone,PartialEq)] +#[derive(StableAbi, Debug, Clone, PartialEq)] #[sabi(kind(WithNonExhaustive( - size="[usize;8]", - traits(Debug,Clone,PartialEq), + size = "[usize;8]", + traits(Debug, Clone, PartialEq), )))] #[sabi(with_constructor)] -pub enum Event{ +pub enum Event { #[doc(hidden)] __NonExhaustive, - CreatedInstance{ - object_id:ObjectId, + CreatedInstance { + object_id: ObjectId, }, - RemovedInstance{ - object_id:ObjectId, + RemovedInstance { + object_id: ObjectId, }, ///////////////// // Added in 1.1 ///////////////// - CreatedGroup{ - name:RString, - group_id:GroupId, + CreatedGroup { + name: RString, + group_id: GroupId, }, - RemovedGroup{ - name:RString, - group_id:GroupId, + RemovedGroup { + name: RString, + group_id: GroupId, }, - AssociatedWithGroup{ - object_id:ObjectId, - group_id:GroupId, + AssociatedWithGroup { + object_id: ObjectId, + group_id: GroupId, }, ///////////////// // Added in 1.2 ///////////////// - RemovedAssociationWithGroup{ - object_id:ObjectId, - group_id:GroupId, + RemovedAssociationWithGroup { + object_id: ObjectId, + group_id: GroupId, }, #[sabi(with_boxed_constructor)] - DummyVariant{ - pointer:RArc<()>, + DummyVariant { + pointer: RArc<()>, }, } -let objectid_0=ObjectId(0); -let objectid_1=ObjectId(1); +let objectid_0 = ObjectId(0); +let objectid_1 = ObjectId(1); -let groupid_0=GroupId(0); -let groupid_1=GroupId(0); +let groupid_0 = GroupId(0); +let groupid_1 = GroupId(0); // Constructing a Event::CreatedInstance wrapped in a NonExhaustive { - let from_ne_constructor:Event_NE= - Event::CreatedInstance_NE(objectid_0); - let regular={ - let ev=Event::CreatedInstance{object_id:objectid_0}; + let from_ne_constructor: Event_NE = Event::CreatedInstance_NE(objectid_0); + let regular = { + let ev = Event::CreatedInstance { + object_id: objectid_0, + }; NonExhaustive::new(ev) }; - assert_eq!(from_ne_constructor,regular); + assert_eq!(from_ne_constructor, regular); } // Constructing a Event::RemovedInstance wrapped in a NonExhaustive { - let from_ne_constructor=Event::RemovedInstance_NE(objectid_0); - let regular={ - let ev=Event::RemovedInstance{object_id:objectid_0}; + let from_ne_constructor = Event::RemovedInstance_NE(objectid_0); + let regular = { + let ev = Event::RemovedInstance { + object_id: objectid_0, + }; NonExhaustive::new(ev) }; - assert_eq!(from_ne_constructor,regular); + assert_eq!(from_ne_constructor, regular); } // Constructing a Event::RemovedInstance wrapped in a NonExhaustive { - let from_ne_constructor=Event::RemovedInstance_NE(objectid_0); - let regular={ - let ev=Event::RemovedInstance{object_id:objectid_0}; + let from_ne_constructor = Event::RemovedInstance_NE(objectid_0); + let regular = { + let ev = Event::RemovedInstance { + object_id: objectid_0, + }; NonExhaustive::new(ev) }; - assert_eq!(from_ne_constructor,regular); + assert_eq!(from_ne_constructor, regular); } // Constructing a Event::CreatedGroup wrapped in a NonExhaustive // This is only available from 1.1 { - let from_ne_constructor=Event::CreatedGroup_NE("hello".into(),groupid_0); - let regular={ - let ev=Event::CreatedGroup{name:"hello".into(),group_id:groupid_0}; + let from_ne_constructor = Event::CreatedGroup_NE("hello".into(), groupid_0); + let regular = { + let ev = Event::CreatedGroup { + name: "hello".into(), + group_id: groupid_0, + }; NonExhaustive::new(ev) }; - assert_eq!(from_ne_constructor,regular); + assert_eq!(from_ne_constructor, regular); } // Constructing a Event::RemovedGroup wrapped in a NonExhaustive // This is only available from 1.1 { - let from_ne_constructor=Event::RemovedGroup_NE("hello".into(),groupid_0); - let regular={ - let ev=Event::RemovedGroup{name:"hello".into(),group_id:groupid_0}; + let from_ne_constructor = Event::RemovedGroup_NE("hello".into(), groupid_0); + let regular = { + let ev = Event::RemovedGroup { + name: "hello".into(), + group_id: groupid_0, + }; NonExhaustive::new(ev) }; - assert_eq!(from_ne_constructor,regular); + assert_eq!(from_ne_constructor, regular); } - // Constructing a Event::AssociatedWithGroup wrapped in a NonExhaustive // This is only available from 1.1 { - let from_ne_constructor=Event::AssociatedWithGroup_NE(objectid_0,groupid_0); - let regular={ - let ev=Event::AssociatedWithGroup{ - object_id:objectid_0, - group_id:groupid_0, + let from_ne_constructor = Event::AssociatedWithGroup_NE(objectid_0, groupid_0); + let regular = { + let ev = Event::AssociatedWithGroup { + object_id: objectid_0, + group_id: groupid_0, }; NonExhaustive::new(ev) }; - assert_eq!(from_ne_constructor,regular); + assert_eq!(from_ne_constructor, regular); } - // Constructing a Event::RemovedAssociationWithGroup wrapped in a NonExhaustive // This is only available from 1.2 { - let from_ne_constructor=Event::RemovedAssociationWithGroup_NE(objectid_0,groupid_0); - let regular={ - let ev=Event::RemovedAssociationWithGroup{ - object_id:objectid_0, - group_id:groupid_0, + let from_ne_constructor = + Event::RemovedAssociationWithGroup_NE(objectid_0, groupid_0); + let regular = { + let ev = Event::RemovedAssociationWithGroup { + object_id: objectid_0, + group_id: groupid_0, }; NonExhaustive::new(ev) }; - assert_eq!(from_ne_constructor,regular); + assert_eq!(from_ne_constructor, regular); } // Constructing a Event::DummyVariant wrapped in a NonExhaustive // This is only available from 1.2 { - let from_ne_constructor=Event::DummyVariant_NE(()); - let regular={ - let x=RArc::new(()); - let x=Event::DummyVariant{ - pointer:x - }; + let from_ne_constructor = Event::DummyVariant_NE(()); + let regular = { + let x = RArc::new(()); + let x = Event::DummyVariant { pointer: x }; NonExhaustive::new(x) }; - assert_eq!(from_ne_constructor,regular); + assert_eq!(from_ne_constructor, regular); } ``` diff --git a/abi_stable/src/docs/sabi_trait_inherent.rs b/abi_stable/src/docs/sabi_trait_inherent.rs index 2e0b901c..130a1431 100644 --- a/abi_stable/src/docs/sabi_trait_inherent.rs +++ b/abi_stable/src/docs/sabi_trait_inherent.rs @@ -68,7 +68,7 @@ use abi_stable::{ sabi_trait::doc_examples::Action_TO, std_types::{RArc, RBox}, type_level::downcasting::TD_CanDowncast, - RRef, RMut, + RMut, RRef, }; // From an RBox @@ -148,8 +148,7 @@ Its possible values are [`TD_CanDowncast`] and [`TD_Opaque`]. **Example**: ```rust use abi_stable::{ - sabi_trait::doc_examples::Action_TO, - std_types::RBox, + sabi_trait::doc_examples::Action_TO, std_types::RBox, type_level::downcasting::TD_CanDowncast, }; @@ -194,17 +193,13 @@ You can construct the `vtable_for` parameter with `_MV:VTABLE` **Example:** ```rust use abi_stable::{ - sabi_trait::doc_examples::Action_trait::{Action_CTO, Action_TO, Action_MV}, + sabi_trait::doc_examples::Action_trait::{Action_CTO, Action_MV, Action_TO}, std_types::RBox, type_level::downcasting::TD_CanDowncast, }; const TO: Action_CTO<'_, '_> = - Action_TO::from_const( - &200, - TD_CanDowncast, - Action_MV::VTABLE, - ); + Action_TO::from_const(&200, TD_CanDowncast, Action_MV::VTABLE); assert_eq!(TO.get(), 200); @@ -234,7 +229,7 @@ For [`Action_TO`] specifically, [`RObject`] is the backend. use abi_stable::{ pointer_trait::{CanTransmuteElement, OwnedPointer}, sabi_trait::{ - doc_examples::Action_trait::{Action_Interface, Action_TO, Action_MV}, + doc_examples::Action_trait::{Action_Interface, Action_MV, Action_TO}, RObject, }, std_types::RBox, @@ -244,15 +239,12 @@ use abi_stable::{ let mut object: Action_TO<'static, RBox<()>> = Action_TO::from_value(700, TD_CanDowncast); - object = try_downcast::<_, u32>(object).unwrap_err(); object = try_downcast::<_, String>(object).unwrap_err(); assert_eq!(*try_downcast::<_, usize>(object).unwrap(), 700); - - fn try_downcast( object: Action_TO<'static, P>, ) -> Result> @@ -261,7 +253,8 @@ where // This bound is required to call `downcast_into` on the `obj: RObject<…>` field P: OwnedPointer + CanTransmuteElement, { - object.obj + object + .obj .downcast_into() .map_err(|e| Action_TO::from_sabi(e.into_inner())) } @@ -291,10 +284,8 @@ This method is only available for traits that either: **Example**: ```rust use abi_stable::{ - sabi_trait::doc_examples::Action_TO, - std_types::RBox, - type_level::downcasting::TD_CanDowncast, - RRef, + sabi_trait::doc_examples::Action_TO, std_types::RBox, + type_level::downcasting::TD_CanDowncast, RRef, }; let mut object: Action_TO<'static, RBox<()>> = @@ -309,10 +300,9 @@ assert_eq!(object.add_mut(14), 321); // last use of `object`, so we can move it into the function assert_eq!(to_debug_string(object), "321"); - fn to_debug_string(x: T) -> String where - T: std::fmt::Debug + T: std::fmt::Debug, { format!("{:?}", x) } @@ -320,6 +310,7 @@ where fn get_usize(x: Action_TO<'_, RRef<'_, ()>>) -> usize { x.get() } + ``` ## `sabi_reborrow_mut` method @@ -345,9 +336,7 @@ This method is only available for traits that either: **Example**: ```rust use abi_stable::{ - pointer_trait::AsMutPtr, - sabi_trait::doc_examples::Action_TO, - std_types::RBox, + pointer_trait::AsMutPtr, sabi_trait::doc_examples::Action_TO, std_types::RBox, type_level::downcasting::TD_CanDowncast, }; @@ -361,11 +350,10 @@ assert_eq!(add_mut(object.sabi_reborrow_mut(), 10), 416); // last use of `object`, so we can move it into the function assert_eq!(add_mut(object, 20), 436); - fn add_mut

(mut x: Action_TO<'_, P>, how_much: usize) -> usize where // Needed for calling mutable methods on `Action_TO` - P: AsMutPtr + P: AsMutPtr, { x.add_mut(how_much) } diff --git a/abi_stable/src/erased_types/dyn_trait.rs b/abi_stable/src/erased_types/dyn_trait.rs index 7c10086d..6058dbf0 100644 --- a/abi_stable/src/erased_types/dyn_trait.rs +++ b/abi_stable/src/erased_types/dyn_trait.rs @@ -1,6 +1,4 @@ -/*! -Contains the `DynTrait` type, and related traits/type aliases. -*/ +//! Contains the `DynTrait` type, and related traits/type aliases. use std::{ fmt::{self, Write as fmtWrite}, @@ -221,27 +219,24 @@ mod priv_ { /// /// ``` /// use abi_stable::{ - /// StableAbi, - /// impl_get_type_info, - /// sabi_extern_fn, /// erased_types::{ - /// InterfaceType, DeserializeDyn, SerializeProxyType, ImplType, SerializeImplType, - /// TypeInfo, + /// DeserializeDyn, ImplType, InterfaceType, SerializeImplType, + /// SerializeProxyType, TypeInfo, /// }, - /// external_types::{RawValueRef, RawValueBox}, + /// external_types::{RawValueBox, RawValueRef}, + /// impl_get_type_info, /// prefix_type::{PrefixTypeTrait, WithMetadata}, - /// type_level::bools::*, - /// DynTrait, - /// std_types::{RBox, RStr, RBoxError, RResult, ROk, RErr}, + /// sabi_extern_fn, + /// std_types::{RBox, RBoxError, RErr, ROk, RResult, RStr}, /// traits::IntoReprC, + /// type_level::bools::*, + /// DynTrait, StableAbi, /// }; /// - /// /// ////////////////////////////////// /// //// In interface crate ///// /// ////////////////////////////////// /// - /// /// use serde::{Deserialize, Serialize}; /// /// /// An `InterfaceType` describing which traits are implemented by FooInterfaceBox. @@ -253,65 +248,57 @@ mod priv_ { /// /// The state passed to most functions in the TextOpsMod module. /// pub type FooInterfaceBox = DynTrait<'static, RBox<()>, FooInterface>; /// - /// /// /// First ::serialize_impl returns /// /// a RawValueBox containing the serialized data, /// /// then the returned RawValueBox is serialized. - /// impl<'s> SerializeProxyType<'s> for FooInterface{ + /// impl<'s> SerializeProxyType<'s> for FooInterface { /// type Proxy = RawValueBox; /// } /// - /// /// impl<'borr> DeserializeDyn<'borr, FooInterfaceBox> for FooInterface { /// type Proxy = RawValueRef<'borr>; /// - /// fn deserialize_dyn(s: RawValueRef<'borr>) -> Result { - /// MODULE - /// .deserialize_foo()(s.get_rstr()) - /// .into_result() + /// fn deserialize_dyn( + /// s: RawValueRef<'borr>, + /// ) -> Result { + /// MODULE.deserialize_foo()(s.get_rstr()).into_result() /// } /// } /// - /// /// // `#[sabi(kind(Prefix))]` declares this type as being a prefix-type, /// // generating both of these types:
/// // /// // - Module_Prefix`: /// // A struct with the fields up to (and including) the field with the /// // `#[sabi(last_prefix_field)]` attribute. - /// // + /// // /// // - Module_Ref`: /// // An ffi-safe pointer to a `Module`, with methods to get `Module`'s fields. /// #[repr(C)] /// #[derive(StableAbi)] /// #[sabi(kind(Prefix))] /// #[sabi(missing_field(panic))] - /// pub struct Module{ + /// pub struct Module { /// #[sabi(last_prefix_field)] - /// pub deserialize_foo: extern "C" fn(s: RStr<'_>) -> RResult, + /// pub deserialize_foo: + /// extern "C" fn(s: RStr<'_>) -> RResult, /// } /// /// // This is how ffi-safe pointers to non-generic prefix types are constructed /// // at compile-time. /// const MODULE: Module_Ref = { - /// const S: &WithMetadata = &WithMetadata::new( - /// PrefixTypeTrait::METADATA, - /// Module{ - /// deserialize_foo, - /// } - /// ); + /// const S: &WithMetadata = + /// &WithMetadata::new(PrefixTypeTrait::METADATA, Module { deserialize_foo }); /// /// Module_Ref(S.static_as_prefix()) /// }; /// - /// /// ///////////////////////////////////////////////////////////////////////////////////////// /// //// In implementation crate (the one that gets compiled as a dynamic library) ///// /// ///////////////////////////////////////////////////////////////////////////////////////// /// - /// /// #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] - /// pub struct Foo{ + /// pub struct Foo { /// name: String, /// } /// @@ -326,46 +313,46 @@ mod priv_ { /// /// fn serialize_impl(&'s self) -> Result { /// match serde_json::to_string(self) { - /// Ok(v) =>{ - /// RawValueBox::try_from_string(v) - /// .map_err(RBoxError::new) - /// } - /// Err(e) =>Err(RBoxError::new(e)), + /// Ok(v) => RawValueBox::try_from_string(v).map_err(RBoxError::new), + /// Err(e) => Err(RBoxError::new(e)), /// } /// } /// } /// /// #[sabi_extern_fn] - /// pub fn deserialize_foo(s: RStr<'_>) -> RResult{ + /// pub fn deserialize_foo(s: RStr<'_>) -> RResult { /// match serde_json::from_str::(s.into()) { /// Ok(x) => ROk(DynTrait::from_value(x)), /// Err(e) => RErr(RBoxError::new(e)), /// } /// } /// - /// /// # /* /// #[test] /// fn testing_serialization_deserialization() { /// # */ fn main() { - /// let foo = Foo{name:"nope".into()}; + /// let foo = Foo { + /// name: "nope".into(), + /// }; /// let object = DynTrait::from_value(foo.clone()); - /// + /// /// assert_eq!( - /// serde_json::from_str::(r##" - /// { - /// "name":"nope" - /// } - /// "##).unwrap(), + /// serde_json::from_str::( + /// r##" + /// { + /// "name":"nope" + /// } + /// "## + /// ) + /// .unwrap(), /// object /// ); - /// + /// /// assert_eq!( /// serde_json::to_string(&object).unwrap(), /// r##"{"name":"nope"}"## /// ); - /// - /// } + /// # } /// /// ``` /// @@ -393,9 +380,9 @@ mod priv_ { /// /// ``` /// use abi_stable::{ - /// DynTrait, RRef, RMut, /// erased_types::interfaces::PartialEqInterface, /// std_types::{RArc, RBox}, + /// DynTrait, RMut, RRef, /// }; /// /// { @@ -403,7 +390,7 @@ mod priv_ { /// // since `&T` can't soundly be transmuted back and forth into `&()` /// let left: DynTrait<'static, RRef<'_, ()>, PartialEqInterface> = /// DynTrait::from_any_ptr(&100, PartialEqInterface); - /// + /// /// let mut n100 = 100; /// // `DynTrait`s constructed from `&mut` are `DynTrait<'_, RMut<'_, ()>, _>` /// // since `&mut T` can't soundly be transmuted back and forth into `&mut ()` @@ -429,10 +416,7 @@ mod priv_ { /// This is an example of using the `write!()` macro with DynTrait. /// /// ``` - /// use abi_stable::{ - /// DynTrait, RMut, - /// erased_types::interfaces::FmtWriteInterface, - /// }; + /// use abi_stable::{erased_types::interfaces::FmtWriteInterface, DynTrait, RMut}; /// /// use std::fmt::Write; /// @@ -458,10 +442,7 @@ mod priv_ { /// Using `DynTrait` as an `Iterator` and `DoubleEndedIterator`. /// /// ``` - /// use abi_stable::{ - /// DynTrait, - /// erased_types::interfaces::DEIteratorInterface, - /// }; + /// use abi_stable::{erased_types::interfaces::DEIteratorInterface, DynTrait}; /// /// let mut wrapped = DynTrait::from_any_value(0..=10, DEIteratorInterface::NEW); /// @@ -470,11 +451,7 @@ mod priv_ { /// vec![0, 1, 2, 3, 4] /// ); /// - /// assert_eq!( - /// wrapped.rev().collect::>(), - /// vec![10, 9, 8, 7, 6, 5] - /// ); - /// + /// assert_eq!(wrapped.rev().collect::>(), vec![10, 9, 8, 7, 6, 5]); /// /// ``` /// @@ -505,7 +482,7 @@ mod priv_ { /// /// use abi_stable::DynTrait; /// - /// fn main(){ + /// fn main() { /// let lines = "line0\nline1\nline2"; /// let mut iter = NewtypeBox::new(lines.lines()); /// @@ -523,18 +500,23 @@ mod priv_ { /// /// assert_eq!( /// clone.rev().collect::>(), - /// /// vec!["line2", "line1", "line0"], /// ) - /// /// } /// /// #[repr(C)] /// #[derive(StableAbi)] - /// #[sabi(impl_InterfaceType(Sync, Send, Iterator, DoubleEndedIterator, Clone, Debug))] + /// #[sabi(impl_InterfaceType( + /// Sync, + /// Send, + /// Iterator, + /// DoubleEndedIterator, + /// Clone, + /// Debug + /// ))] /// pub struct IteratorInterface; /// - /// impl<'a> IteratorItem<'a> for IteratorInterface{ + /// impl<'a> IteratorItem<'a> for IteratorInterface { /// type Item = &'a str; /// } /// @@ -543,33 +525,30 @@ mod priv_ { /// use std::ops::{Deref, DerefMut}; /// /// use abi_stable::{ - /// StableAbi, - /// InterfaceType, - /// std_types::RBox, /// erased_types::IteratorItem, /// pointer_trait::{ - /// AsPtr, AsMutPtr, - /// GetPointerKind, PK_SmartPointer, - /// CanTransmuteElement, + /// AsMutPtr, AsPtr, CanTransmuteElement, GetPointerKind, PK_SmartPointer, /// }, + /// std_types::RBox, /// type_level::bools::True, + /// InterfaceType, StableAbi, /// }; /// /// #[repr(transparent)] /// #[derive(Default, Clone, StableAbi)] - /// pub struct NewtypeBox{ + /// pub struct NewtypeBox { /// box_: RBox, /// } /// - /// impl NewtypeBox{ - /// pub fn new(value: T) -> Self{ - /// Self{ - /// box_: RBox::new(value) + /// impl NewtypeBox { + /// pub fn new(value: T) -> Self { + /// Self { + /// box_: RBox::new(value), /// } /// } /// } /// - /// unsafe impl GetPointerKind for NewtypeBox{ + /// unsafe impl GetPointerKind for NewtypeBox { /// // This is a smart pointer because `RBox` is one. /// type Kind = PK_SmartPointer; /// type PtrTarget = T; @@ -597,7 +576,7 @@ mod priv_ { /// /// unsafe fn transmute_element_(self) -> Self::TransmutedPtr { /// let box_: RBox = self.box_.transmute_element_(); - /// NewtypeBox{box_} + /// NewtypeBox { box_ } /// } /// } /// @@ -648,9 +627,7 @@ mod priv_ { /// /// ```rust /// use abi_stable::{ - /// erased_types::TypeInfo, - /// std_types::RBox, - /// DynTrait, ImplType, StableAbi, + /// erased_types::TypeInfo, std_types::RBox, DynTrait, ImplType, StableAbi, /// }; /// /// fn main() { @@ -660,14 +637,13 @@ mod priv_ { /// assert_eq!(format!("{:?}", to), "Foo(10)"); /// } /// - /// /// #[repr(transparent)] /// #[derive(Debug, StableAbi)] /// struct Foo(u32); /// /// impl ImplType for Foo { /// type Interface = FooInterface; - /// + /// /// const INFO: &'static TypeInfo = abi_stable::impl_get_type_info!(Foo); /// } /// @@ -700,8 +676,7 @@ mod priv_ { /// use abi_stable::{ /// erased_types::TypeInfo, /// std_types::{RArc, RBox}, - /// DynTrait, RRef, RMut, - /// ImplType, StableAbi, + /// DynTrait, ImplType, RMut, RRef, StableAbi, /// }; /// /// fn main() { @@ -711,7 +686,7 @@ mod priv_ { /// // since `&T` can't soundly be transmuted back and forth into `&()` /// let rref: DynTrait<'static, RRef<'_, ()>, FooInterface> = /// DynTrait::from_ptr(&Foo(10u32)); - /// + /// /// assert_eq!(format!("{:?}", rref), "Foo(10)"); /// } /// // Constructing a DynTrait from a `&mut T` @@ -721,33 +696,32 @@ mod priv_ { /// // since `&mut T` can't soundly be transmuted back and forth into `&mut ()` /// let rmut: DynTrait<'static, RMut<'_, ()>, FooInterface> = /// DynTrait::from_ptr(mmut); - /// + /// /// assert_eq!(format!("{:?}", rmut), "Foo(20)"); /// } /// // Constructing a DynTrait from a `RBox` /// { /// let boxed: DynTrait<'static, RBox<()>, FooInterface> = /// DynTrait::from_ptr(RBox::new(Foo(30u32))); - /// + /// /// assert_eq!(format!("{:?}", boxed), "Foo(30)"); /// } /// // Constructing a DynTrait from an `RArc` /// { /// let arc: DynTrait<'static, RArc<()>, FooInterface> = /// DynTrait::from_ptr(RArc::new(Foo(30u32))); - /// + /// /// assert_eq!(format!("{:?}", arc), "Foo(30)"); /// } /// } /// - /// /// #[repr(transparent)] /// #[derive(Debug, StableAbi)] /// struct Foo(u32); /// /// impl ImplType for Foo { /// type Interface = FooInterface; - /// + /// /// const INFO: &'static TypeInfo = abi_stable::impl_get_type_info!(Foo); /// } /// @@ -757,7 +731,6 @@ mod priv_ { /// #[sabi(impl_InterfaceType(Sync, Debug))] /// pub struct FooInterface; /// - /// /// ``` pub fn from_ptr(object: P) -> DynTrait<'static, P::TransmutedPtr, T::Interface> where @@ -781,12 +754,9 @@ mod priv_ { /// /// ```rust /// use abi_stable::{ - /// erased_types::interfaces::DebugDisplayInterface, - /// std_types::RBox, - /// DynTrait, + /// erased_types::interfaces::DebugDisplayInterface, std_types::RBox, DynTrait, /// }; /// - /// /// // DebugDisplayInterface is `Debug + Display + Sync + Send` /// let to: DynTrait<'static, RBox<()>, DebugDisplayInterface> = /// DynTrait::from_any_value(3u8, DebugDisplayInterface); @@ -814,7 +784,7 @@ mod priv_ { /// use abi_stable::{ /// erased_types::interfaces::DebugDisplayInterface, /// std_types::{RArc, RBox}, - /// DynTrait, RRef, RMut, + /// DynTrait, RMut, RRef, /// }; /// /// // Constructing a DynTrait from a `&T` @@ -882,12 +852,9 @@ mod priv_ { /// /// ```rust /// use abi_stable::{ - /// erased_types::interfaces::DebugDisplayInterface, - /// std_types::RBox, - /// DynTrait, + /// erased_types::interfaces::DebugDisplayInterface, std_types::RBox, DynTrait, /// }; /// - /// /// // DebugDisplayInterface is `Debug + Display + Sync + Send` /// let to: DynTrait<'static, RBox<()>, DebugDisplayInterface> = /// DynTrait::from_borrowing_value(3u8, DebugDisplayInterface); @@ -895,7 +862,6 @@ mod priv_ { /// assert_eq!(format!("{}", to), "3"); /// assert_eq!(format!("{:?}", to), "3"); /// - /// /// // `DynTrait`s constructed using the `from_borrowing_*` constructors /// // can't be downcasted. /// assert_eq!(to.downcast_as::().ok(), None); @@ -925,7 +891,7 @@ mod priv_ { /// use abi_stable::{ /// erased_types::interfaces::DebugDisplayInterface, /// std_types::{RArc, RBox}, - /// DynTrait, RRef, RMut, + /// DynTrait, RMut, RRef, /// }; /// /// // Constructing a DynTrait from a `&T` @@ -997,14 +963,10 @@ mod priv_ { /// /// ```rust /// use abi_stable::{ - /// erased_types::{ - /// interfaces::DebugDisplayInterface, - /// TD_Opaque, - /// }, + /// erased_types::{interfaces::DebugDisplayInterface, TD_Opaque}, /// DynTrait, RRef, /// }; /// - /// /// // DebugDisplayInterface is `Debug + Display + Sync + Send` /// let to: DynTrait<'static, RRef<()>, DebugDisplayInterface, usize> = /// DynTrait::with_extra_value::<_, TD_Opaque>(&55u8, 100usize); @@ -1093,25 +1055,19 @@ mod priv_ { /// ``` /// use abi_stable::{ /// erased_types::{ - /// interfaces::DebugDisplayInterface, - /// DynTrait, TD_Opaque, VTableDT, + /// interfaces::DebugDisplayInterface, DynTrait, TD_Opaque, VTableDT, /// }, /// sabi_types::RRef, /// }; /// - /// static STRING:&str ="What the heck"; + /// static STRING: &str = "What the heck"; /// - /// static DYN: DynTrait<'static, RRef<'static,()>, DebugDisplayInterface,()> = - /// DynTrait::from_const( - /// &STRING, - /// TD_Opaque, - /// VTableDT::GET, - /// (), - /// ); + /// static DYN: DynTrait<'static, RRef<'static, ()>, DebugDisplayInterface, ()> = + /// DynTrait::from_const(&STRING, TD_Opaque, VTableDT::GET, ()); /// - /// fn main(){ - /// assert_eq!( format!("{}", DYN), format!("{}", STRING) ); - /// assert_eq!( format!("{:?}", DYN), format!("{:?}", STRING) ); + /// fn main() { + /// assert_eq!(format!("{}", DYN), format!("{}", STRING)); + /// assert_eq!(format!("{:?}", DYN), format!("{:?}", STRING)); /// } /// /// ``` @@ -1193,11 +1149,7 @@ mod priv_ { /// # Example /// /// ```rust - /// use abi_stable::{ - /// erased_types::TD_Opaque, - /// DynTrait, RRef, - /// }; - /// + /// use abi_stable::{erased_types::TD_Opaque, DynTrait, RRef}; /// /// let to: DynTrait<'static, RRef<()>, (), char> = /// DynTrait::with_extra_value::<_, TD_Opaque>(&55u8, 'Z'); @@ -1225,15 +1177,11 @@ mod priv_ { /// # Example /// /// ```rust - /// use abi_stable::{ - /// erased_types::TD_Opaque, - /// DynTrait, RRef, - /// }; + /// use abi_stable::{erased_types::TD_Opaque, DynTrait, RRef}; /// /// let reff = &55u8; /// - /// let to: DynTrait<'static, RRef<()>, ()> = - /// DynTrait::from_any_ptr(reff, ()); + /// let to: DynTrait<'static, RRef<()>, ()> = DynTrait::from_any_ptr(reff, ()); /// /// assert_eq!(to.sabi_object_address(), reff as *const _ as usize); /// @@ -1266,17 +1214,12 @@ mod priv_ { /// # Example /// /// ```rust - /// use abi_stable::{ - /// std_types::RBox, - /// DynTrait, - /// }; + /// use abi_stable::{std_types::RBox, DynTrait}; /// + /// let to: DynTrait<'static, RBox<()>, ()> = DynTrait::from_any_value(66u8, ()); /// - /// let to: DynTrait<'static, RBox<()>, ()> = - /// DynTrait::from_any_value(66u8, ()); - /// - /// unsafe{ - /// assert_eq!(to.sabi_erased_ref().transmute_into_ref::() , &66); + /// unsafe { + /// assert_eq!(to.sabi_erased_ref().transmute_into_ref::(), &66); /// } /// ``` pub fn sabi_erased_ref(&self) -> RRef<'_, ErasedObject> @@ -1298,17 +1241,15 @@ mod priv_ { /// # Example /// /// ```rust - /// use abi_stable::{ - /// std_types::RBox, - /// DynTrait, - /// }; + /// use abi_stable::{std_types::RBox, DynTrait}; /// + /// let mut to: DynTrait<'static, RBox<()>, ()> = DynTrait::from_any_value("hello", ()); /// - /// let mut to: DynTrait<'static, RBox<()>, ()> = - /// DynTrait::from_any_value("hello", ()); - /// - /// unsafe{ - /// assert_eq!(to.sabi_erased_mut().transmute_into_mut::<&str>() , &mut "hello"); + /// unsafe { + /// assert_eq!( + /// to.sabi_erased_mut().transmute_into_mut::<&str>(), + /// &mut "hello" + /// ); /// } /// ``` #[inline] @@ -1324,17 +1265,12 @@ mod priv_ { /// # Example /// /// ```rust - /// use abi_stable::{ - /// std_types::RBox, - /// DynTrait, - /// }; + /// use abi_stable::{std_types::RBox, DynTrait}; /// + /// let to: DynTrait<'static, RBox<()>, ()> = DynTrait::from_any_value(66u8, ()); /// - /// let to: DynTrait<'static, RBox<()>, ()> = - /// DynTrait::from_any_value(66u8, ()); - /// - /// unsafe{ - /// assert_eq!(to.sabi_as_rref().transmute_into_ref::() , &66); + /// unsafe { + /// assert_eq!(to.sabi_as_rref().transmute_into_ref::(), &66); /// } /// ``` pub fn sabi_as_rref(&self) -> RRef<'_, ()> @@ -1349,17 +1285,12 @@ mod priv_ { /// # Example /// /// ```rust - /// use abi_stable::{ - /// std_types::RBox, - /// DynTrait, - /// }; - /// + /// use abi_stable::{std_types::RBox, DynTrait}; /// - /// let mut to: DynTrait<'static, RBox<()>, ()> = - /// DynTrait::from_any_value("hello", ()); + /// let mut to: DynTrait<'static, RBox<()>, ()> = DynTrait::from_any_value("hello", ()); /// - /// unsafe{ - /// assert_eq!(to.sabi_as_rmut().transmute_into_mut::<&str>() , &mut "hello"); + /// unsafe { + /// assert_eq!(to.sabi_as_rmut().transmute_into_mut::<&str>(), &mut "hello"); /// } /// ``` pub fn sabi_as_rmut(&mut self) -> RMut<'_, ()> @@ -1386,11 +1317,10 @@ mod priv_ { /// DynTrait, /// }; /// - /// /// let to: DynTrait<'static, RBox<()>, ()> = /// DynTrait::from_any_value(RVec::::from_slice(b"foobarbaz"), ()); /// - /// let string = to.sabi_with_value(|x| unsafe{ + /// let string = to.sabi_with_value(|x| unsafe { /// MovePtr::into_inner(MovePtr::transmute::(x)) /// }); /// @@ -1464,10 +1394,7 @@ mod priv_ { /// to().downcast_into_impltype::>().ok(), /// Some(RBox::new(Foo(b'A'))), /// ); - /// assert_eq!( - /// to().downcast_into_impltype::>().ok(), - /// None, - /// ); + /// assert_eq!(to().downcast_into_impltype::>().ok(), None,); /// } /// { /// fn to() -> DynTrait<'static, RArc<()>, FooInterface> { @@ -1478,10 +1405,7 @@ mod priv_ { /// to().downcast_into_impltype::>().ok(), /// Some(RArc::new(Foo(b'B'))), /// ); - /// assert_eq!( - /// to().downcast_into_impltype::>().ok(), - /// None, - /// ); + /// assert_eq!(to().downcast_into_impltype::>().ok(), None,); /// } /// # } /// @@ -1491,18 +1415,16 @@ mod priv_ { /// /// impl ImplType for Foo { /// type Interface = FooInterface; - /// + /// /// const INFO: &'static TypeInfo = abi_stable::impl_get_type_info!(Foo); /// } /// - /// /// /// An `InterfaceType` describing which traits are implemented by FooInterfaceBox. /// #[repr(C)] /// #[derive(StableAbi)] /// #[sabi(impl_InterfaceType(Sync, Debug))] /// pub struct FooInterface; /// - /// /// ``` pub fn downcast_into_impltype(self) -> Result> where @@ -1537,10 +1459,8 @@ mod priv_ { /// /// ```rust /// use abi_stable::{ - /// erased_types::TypeInfo, - /// std_types::RArc, - /// DynTrait, RRef, RMut, - /// ImplType, StableAbi, + /// erased_types::TypeInfo, std_types::RArc, DynTrait, ImplType, RMut, RRef, + /// StableAbi, /// }; /// /// # fn main(){ @@ -1576,11 +1496,10 @@ mod priv_ { /// /// impl ImplType for Foo { /// type Interface = FooInterface; - /// + /// /// const INFO: &'static TypeInfo = abi_stable::impl_get_type_info!(Foo); /// } /// - /// /// /// An `InterfaceType` describing which traits are implemented by FooInterfaceBox. /// #[repr(C)] /// #[derive(StableAbi)] @@ -1618,10 +1537,7 @@ mod priv_ { /// /// ```rust /// use abi_stable::{ - /// erased_types::TypeInfo, - /// std_types::RBox, - /// DynTrait, RMut, - /// ImplType, StableAbi, + /// erased_types::TypeInfo, std_types::RBox, DynTrait, ImplType, RMut, StableAbi, /// }; /// /// # fn main(){ @@ -1631,14 +1547,20 @@ mod priv_ { /// let mut to: DynTrait<'static, RMut<'_, ()>, FooInterface> = /// DynTrait::from_ptr(&mut val); /// - /// assert_eq!(to.downcast_as_mut_impltype::>().ok(), Some(&mut Foo(7))); + /// assert_eq!( + /// to.downcast_as_mut_impltype::>().ok(), + /// Some(&mut Foo(7)) + /// ); /// assert_eq!(to.downcast_as_mut_impltype::>().ok(), None); /// } /// { /// let mut to: DynTrait<'static, RBox<()>, FooInterface> = /// DynTrait::from_ptr(RBox::new(Foo(1u8))); /// - /// assert_eq!(to.downcast_as_mut_impltype::>().ok(), Some(&mut Foo(1u8))); + /// assert_eq!( + /// to.downcast_as_mut_impltype::>().ok(), + /// Some(&mut Foo(1u8)) + /// ); /// assert_eq!(to.downcast_as_mut_impltype::>().ok(), None); /// } /// @@ -1650,11 +1572,10 @@ mod priv_ { /// /// impl ImplType for Foo { /// type Interface = FooInterface; - /// + /// /// const INFO: &'static TypeInfo = abi_stable::impl_get_type_info!(Foo); /// } /// - /// /// /// An `InterfaceType` describing which traits are implemented by FooInterfaceBox. /// #[repr(C)] /// #[derive(StableAbi)] @@ -1754,14 +1675,10 @@ mod priv_ { /// # Example /// /// ```rust - /// use abi_stable::{ - /// std_types::RArc, - /// DynTrait, RRef, RMut, - /// }; + /// use abi_stable::{std_types::RArc, DynTrait, RMut, RRef}; /// /// { - /// let to: DynTrait<'static, RRef<'_, ()>, ()> = - /// DynTrait::from_any_ptr(&9u8, ()); + /// let to: DynTrait<'static, RRef<'_, ()>, ()> = DynTrait::from_any_ptr(&9u8, ()); /// /// assert_eq!(to.downcast_as::().ok(), Some(&9u8)); /// assert_eq!(to.downcast_as::().ok(), None); @@ -1817,10 +1734,7 @@ mod priv_ { /// # Example /// /// ```rust - /// use abi_stable::{ - /// std_types::RBox, - /// DynTrait, RMut, - /// }; + /// use abi_stable::{std_types::RBox, DynTrait, RMut}; /// /// { /// let mut val = 7u8; @@ -1839,7 +1753,6 @@ mod priv_ { /// assert_eq!(to.downcast_as_mut::().ok(), None); /// } /// - /// /// ``` pub fn downcast_as_mut(&mut self) -> Result<&mut T, UneraseError<&mut Self>> where @@ -1906,14 +1819,10 @@ mod priv_ { /// # Example /// /// ```rust - /// use abi_stable::{ - /// std_types::RArc, - /// DynTrait, RRef, RMut, - /// }; + /// use abi_stable::{std_types::RArc, DynTrait, RMut, RRef}; /// /// unsafe { - /// let to: DynTrait<'static, RRef<'_, ()>, ()> = - /// DynTrait::from_any_ptr(&9u8, ()); + /// let to: DynTrait<'static, RRef<'_, ()>, ()> = DynTrait::from_any_ptr(&9u8, ()); /// /// assert_eq!(to.unchecked_downcast_as::(), &9u8); /// } @@ -1952,10 +1861,7 @@ mod priv_ { /// # Example /// /// ```rust - /// use abi_stable::{ - /// std_types::RBox, - /// DynTrait, RMut, - /// }; + /// use abi_stable::{std_types::RBox, DynTrait, RMut}; /// /// unsafe { /// let mut val = 7u8; @@ -1972,7 +1878,6 @@ mod priv_ { /// assert_eq!(to.unchecked_downcast_as_mut::(), &mut 1u8); /// } /// - /// /// ``` #[inline] pub unsafe fn unchecked_downcast_as_mut(&mut self) -> &mut T @@ -2022,23 +1927,18 @@ mod priv_ { /// use abi_stable::{ /// erased_types::interfaces::DebugDisplayInterface, /// std_types::RBox, - /// type_level::{ - /// impl_enum::Implemented, - /// trait_marker, - /// }, + /// type_level::{impl_enum::Implemented, trait_marker}, /// DynTrait, InterfaceBound, RRef, /// }; /// - /// /// let to: DynTrait<'static, RBox<()>, DebugDisplayInterface> = /// DynTrait::from_any_value(1337_u16, DebugDisplayInterface); /// /// assert_eq!(debug_string(to.reborrow()), "1337"); /// - /// /// fn debug_string(to: DynTrait<'_, RRef<'_, ()>, I>) -> String /// where - /// I: InterfaceBound> + /// I: InterfaceBound>, /// { /// format!("{:?}", to) /// } @@ -2074,12 +1974,9 @@ mod priv_ { /// /// ```rust /// use abi_stable::{ - /// erased_types::interfaces::DEIteratorInterface, - /// std_types::RBox, - /// DynTrait, + /// erased_types::interfaces::DEIteratorInterface, std_types::RBox, DynTrait, /// }; /// - /// /// let mut to = DynTrait::from_any_value(0_u8..=255, DEIteratorInterface::NEW); /// /// assert_eq!(both_ends(to.reborrow_mut()), (Some(0), Some(255))); @@ -2087,7 +1984,6 @@ mod priv_ { /// assert_eq!(both_ends(to.reborrow_mut()), (Some(2), Some(253))); /// assert_eq!(both_ends(to.reborrow_mut()), (Some(3), Some(252))); /// - /// /// fn both_ends(mut to: I) -> (Option, Option) /// where /// I: DoubleEndedIterator, @@ -2171,20 +2067,23 @@ mod priv_ { /// # Example /// /// ```rust - /// use abi_stable::{ - /// DynTrait, - /// erased_types::interfaces::DebugDefEqInterface, - /// }; + /// use abi_stable::{erased_types::interfaces::DebugDefEqInterface, DynTrait}; /// /// { /// let object = DynTrait::from_any_value(true, DebugDefEqInterface); - /// - /// assert_eq!(object.default(), DynTrait::from_any_value(false, DebugDefEqInterface)); + /// + /// assert_eq!( + /// object.default(), + /// DynTrait::from_any_value(false, DebugDefEqInterface) + /// ); /// } /// { /// let object = DynTrait::from_any_value(123u8, DebugDefEqInterface); - /// - /// assert_eq!(object.default(), DynTrait::from_any_value(0u8, DebugDefEqInterface)); + /// + /// assert_eq!( + /// object.default(), + /// DynTrait::from_any_value(0u8, DebugDefEqInterface) + /// ); /// } /// /// ``` @@ -2278,25 +2177,23 @@ where } } -/** -Clone is implemented for references and smart pointers, -using `GetPointerKind` to decide whether `P` is a smart pointer or a reference. - -DynTrait does not implement Clone if P ==`RMut<'_, ()>` : - -```compile_fail -# use abi_stable::{ -# DynTrait, -# erased_types::interfaces::CloneInterface, -# }; - -let mut object = DynTrait::from_any_value((),()); -let borrow = object.reborrow_mut(); -let _ = borrow.clone(); - -``` - -*/ +/// Clone is implemented for references and smart pointers, +/// using `GetPointerKind` to decide whether `P` is a smart pointer or a reference. +/// +/// DynTrait does not implement Clone if P ==`RMut<'_, ()>` : +/// +/// ```compile_fail +/// # use abi_stable::{ +/// # DynTrait, +/// # erased_types::interfaces::CloneInterface, +/// # }; +/// +/// let mut object = DynTrait::from_any_value((),()); +/// let borrow = object.reborrow_mut(); +/// let _ = borrow.clone(); +/// +/// ``` +/// impl<'borr, P, I, EV> Clone for DynTrait<'borr, P, I, EV> where P: AsPtr, @@ -2345,12 +2242,10 @@ where { } -/** -First it serializes a `DynTrait<_>` into a string by using -::serialize_impl, -then it serializes the string. - -*/ +/// First it serializes a `DynTrait<_>` into a string by using +/// ::serialize_impl, +/// then it serializes the string. +/// impl<'borr, P, I, EV> Serialize for DynTrait<'borr, P, I, EV> where P: AsPtr, @@ -2519,48 +2414,44 @@ where I: InterfaceBound>, Item: 'borr, { - /** - Eagerly skips n elements from the iterator. - - This method is faster than using `Iterator::skip`. - - # Example - - ``` - # use abi_stable::{ - # DynTrait, - # erased_types::interfaces::IteratorInterface, - # std_types::RVec, - # traits::IntoReprC, - # }; - - let mut iter = 0..20; - let mut wrapped = DynTrait::from_any_ptr(&mut iter, IteratorInterface::NEW); - - assert_eq!(wrapped.next(), Some(0)); - - wrapped.skip_eager(2); - - assert_eq!(wrapped.next(), Some(3)); - assert_eq!(wrapped.next(), Some(4)); - assert_eq!(wrapped.next(), Some(5)); - - wrapped.skip_eager(2); - - assert_eq!(wrapped.next(), Some(8)); - assert_eq!(wrapped.next(), Some(9)); - - wrapped.skip_eager(9); - - assert_eq!(wrapped.next(), Some(19)); - assert_eq!(wrapped.next(), None ); - - - - ``` - - - */ + /// Eagerly skips n elements from the iterator. + /// + /// This method is faster than using `Iterator::skip`. + /// + /// # Example + /// + /// ``` + /// # use abi_stable::{ + /// # DynTrait, + /// # erased_types::interfaces::IteratorInterface, + /// # std_types::RVec, + /// # traits::IntoReprC, + /// # }; + /// + /// let mut iter = 0..20; + /// let mut wrapped = DynTrait::from_any_ptr(&mut iter, IteratorInterface::NEW); + /// + /// assert_eq!(wrapped.next(), Some(0)); + /// + /// wrapped.skip_eager(2); + /// + /// assert_eq!(wrapped.next(), Some(3)); + /// assert_eq!(wrapped.next(), Some(4)); + /// assert_eq!(wrapped.next(), Some(5)); + /// + /// wrapped.skip_eager(2); + /// + /// assert_eq!(wrapped.next(), Some(8)); + /// assert_eq!(wrapped.next(), Some(9)); + /// + /// wrapped.skip_eager(9); + /// + /// assert_eq!(wrapped.next(), Some(19)); + /// assert_eq!(wrapped.next(), None); + /// + /// + /// ``` + /// pub fn skip_eager(&mut self, n: usize) { unsafe { let vtable = self.sabi_vtable(); @@ -2568,40 +2459,35 @@ where } } - /** - Extends the `RVec` with the `self` Iterator. - - Extends `buffer` with as many elements of the iterator as `taking` specifies: - - - RNone: Yields all elements.Use this with care, since Iterators can be infinite. - - - RSome(n): Yields n elements. - - ### Example - - ``` - # use abi_stable::{ - # DynTrait, - # erased_types::interfaces::IteratorInterface, - # std_types::{RVec, RSome}, - # traits::IntoReprC, - # }; - - let mut wrapped = DynTrait::from_any_value(0.. , IteratorInterface::NEW); - - let mut buffer = vec![ 101, 102, 103 ].into_c(); - wrapped.extending_rvec(&mut buffer, RSome(5)); - assert_eq!( - &buffer[..], - &*vec![101, 102, 103, 0, 1, 2, 3, 4] - ); - - assert_eq!( wrapped.next(), Some(5)); - assert_eq!( wrapped.next(), Some(6)); - assert_eq!( wrapped.next(), Some(7)); - - ``` - */ + /// Extends the `RVec` with the `self` Iterator. + /// + /// Extends `buffer` with as many elements of the iterator as `taking` specifies: + /// + /// - RNone: Yields all elements.Use this with care, since Iterators can be infinite. + /// + /// - RSome(n): Yields n elements. + /// + /// ### Example + /// + /// ``` + /// # use abi_stable::{ + /// # DynTrait, + /// # erased_types::interfaces::IteratorInterface, + /// # std_types::{RVec, RSome}, + /// # traits::IntoReprC, + /// # }; + /// + /// let mut wrapped = DynTrait::from_any_value(0.., IteratorInterface::NEW); + /// + /// let mut buffer = vec![101, 102, 103].into_c(); + /// wrapped.extending_rvec(&mut buffer, RSome(5)); + /// assert_eq!(&buffer[..], &*vec![101, 102, 103, 0, 1, 2, 3, 4]); + /// + /// assert_eq!(wrapped.next(), Some(5)); + /// assert_eq!(wrapped.next(), Some(6)); + /// assert_eq!(wrapped.next(), Some(7)); + /// + /// ``` pub fn extending_rvec(&mut self, buffer: &mut RVec, taking: ROption) { unsafe { let vtable = self.sabi_vtable(); @@ -2641,10 +2527,7 @@ where /// # Example /// /// ```rust - /// use abi_stable::{ - /// erased_types::interfaces::DEIteratorCloneInterface, - /// DynTrait, - /// }; + /// use abi_stable::{erased_types::interfaces::DEIteratorCloneInterface, DynTrait}; /// /// let to = || DynTrait::from_any_value(7..=10, DEIteratorCloneInterface::NEW); /// @@ -2664,37 +2547,32 @@ where } } - /** - Extends the `RVec` with the back of the `self` DoubleEndedIterator. - - Extends `buffer` with as many elements of the iterator as `taking` specifies: - - - RNone: Yields all elements.Use this with care, since Iterators can be infinite. - - - RSome(n): Yields n elements. - - ### Example - - ``` - # use abi_stable::{ - # DynTrait, - # erased_types::interfaces::DEIteratorInterface, - # std_types::{RVec, RNone}, - # traits::IntoReprC, - # }; - - let mut wrapped = DynTrait::from_any_value(0..=3 , DEIteratorInterface::NEW); - - let mut buffer = vec![ 101, 102, 103 ].into_c(); - wrapped.extending_rvec_back(&mut buffer, RNone); - assert_eq!( - &buffer[..], - &*vec![101, 102, 103, 3, 2, 1, 0] - ) - - ``` - - */ + /// Extends the `RVec` with the back of the `self` DoubleEndedIterator. + /// + /// Extends `buffer` with as many elements of the iterator as `taking` specifies: + /// + /// - RNone: Yields all elements.Use this with care, since Iterators can be infinite. + /// + /// - RSome(n): Yields n elements. + /// + /// ### Example + /// + /// ``` + /// # use abi_stable::{ + /// # DynTrait, + /// # erased_types::interfaces::DEIteratorInterface, + /// # std_types::{RVec, RNone}, + /// # traits::IntoReprC, + /// # }; + /// + /// let mut wrapped = DynTrait::from_any_value(0..=3, DEIteratorInterface::NEW); + /// + /// let mut buffer = vec![101, 102, 103].into_c(); + /// wrapped.extending_rvec_back(&mut buffer, RNone); + /// assert_eq!(&buffer[..], &*vec![101, 102, 103, 3, 2, 1, 0]) + /// + /// ``` + /// pub fn extending_rvec_back(&mut self, buffer: &mut RVec, taking: ROption) { unsafe { let vtable = self.sabi_vtable(); From 6d425cdee00d0caa4ff1f2bcd50a0bcbdb82fdf5 Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Wed, 27 Oct 2021 04:38:04 -0300 Subject: [PATCH 18/32] Replaced virtually all `/** */`-style comments with `///` style ones Formatted doc examples in those doc comments as well. --- abi_stable/src/_immovable_wrapper.rs | 4 +- abi_stable/src/abi_stability.rs | 4 +- abi_stable/src/const_utils.rs | 4 +- abi_stable/src/docs.rs | 4 +- abi_stable/src/erased_types.rs | 4 +- abi_stable/src/erased_types/trait_objects.rs | 4 +- abi_stable/src/erased_types/traits.rs | 36 +- abi_stable/src/erased_types/type_info.rs | 4 +- abi_stable/src/erased_types/vtable.rs | 5 +- abi_stable/src/external_types.rs | 11 +- .../src/external_types/crossbeam_channel.rs | 10 +- abi_stable/src/external_types/parking_lot.rs | 6 +- abi_stable/src/external_types/serde_json.rs | 4 +- abi_stable/src/inline_storage.rs | 38 +-- abi_stable/src/library/c_abi_testing.rs | 6 +- abi_stable/src/macros.rs | 12 +- abi_stable/src/marker_type.rs | 30 +- abi_stable/src/multikey_map.rs | 30 +- abi_stable/src/nonexhaustive_enum.rs | 16 +- abi_stable/src/nonexhaustive_enum/examples.rs | 5 +- .../src/nonexhaustive_enum/nonexhaustive.rs | 9 +- abi_stable/src/nonexhaustive_enum/traits.rs | 4 +- abi_stable/src/pointer_trait.rs | 5 +- abi_stable/src/prefix_type.rs | 5 +- abi_stable/src/reflection.rs | 12 +- abi_stable/src/reflection/export_module.rs | 4 +- .../src/reflection/tests/derive_reflection.rs | 4 +- abi_stable/src/sabi_trait.rs | 4 +- abi_stable/src/sabi_trait/doc_examples.rs | 4 +- abi_stable/src/sabi_trait/examples.rs | 96 +++--- abi_stable/src/sabi_trait/vtable.rs | 48 ++- abi_stable/src/sabi_types.rs | 4 +- abi_stable/src/sabi_types/ignored_wrapper.rs | 7 +- abi_stable/src/sabi_types/late_static_ref.rs | 4 +- abi_stable/src/sabi_types/move_ptr.rs | 4 +- abi_stable/src/sabi_types/rsmallbox.rs | 4 +- abi_stable/src/sabi_types/version.rs | 4 +- abi_stable/src/std_types.rs | 33 +- abi_stable/src/std_types/arc.rs | 101 +++--- abi_stable/src/std_types/boxed.rs | 76 ++--- abi_stable/src/std_types/cmp_ordering.rs | 54 ++- abi_stable/src/std_types/cow.rs | 321 ++++++++---------- abi_stable/src/std_types/map.rs | 148 ++++---- .../src/std_types/map/iterator_stuff.rs | 9 +- abi_stable/src/std_types/option.rs | 4 +- abi_stable/src/std_types/range.rs | 4 +- abi_stable/src/std_types/result.rs | 4 +- abi_stable/src/std_types/slice_mut.rs | 146 ++++---- abi_stable/src/std_types/slices.rs | 4 +- abi_stable/src/std_types/std_error.rs | 308 +++++++++-------- abi_stable/src/std_types/std_io.rs | 67 ++-- abi_stable/src/std_types/str.rs | 48 ++- abi_stable/src/std_types/string.rs | 138 ++++---- abi_stable/src/std_types/time.rs | 4 +- abi_stable/src/std_types/tuple.rs | 4 +- abi_stable/src/std_types/utypeid.rs | 8 +- abi_stable/src/std_types/vec.rs | 153 ++++----- abi_stable/src/traits.rs | 4 +- abi_stable/src/type_layout.rs | 72 ++-- abi_stable/src/type_layout/printing.rs | 8 +- abi_stable/src/type_layout/tl_enums.rs | 10 +- abi_stable/src/type_layout/tl_fields.rs | 4 +- abi_stable/src/type_layout/tl_functions.rs | 4 +- abi_stable/src/type_layout/tl_other.rs | 8 +- abi_stable/src/type_level.rs | 12 +- abi_stable/src/utils.rs | 4 +- .../src/composite_collections.rs | 11 +- .../src/export_root_module_impl.rs | 4 +- abi_stable_derive/src/fn_pointer_extractor.rs | 20 +- .../src/get_static_equivalent.rs | 4 +- .../attribute_parsing.rs | 4 +- abi_stable_derive/src/ignored_wrapper.rs | 4 +- abi_stable_derive/src/impl_interfacetype.rs | 6 +- abi_stable_derive/src/lib.rs | 31 +- abi_stable_derive/src/my_visibility.rs | 4 +- abi_stable_derive/src/parse_utils.rs | 4 +- abi_stable_derive/src/sabi_extern_fn_impl.rs | 4 +- abi_stable_derive/src/sabi_trait.rs | 44 ++- .../src/sabi_trait/common_tokens.rs | 8 +- .../src/sabi_trait/methods_tokenizer.rs | 44 ++- .../src/sabi_trait/replace_self_path.rs | 27 +- .../src/stable_abi/common_tokens.rs | 8 +- .../src/stable_abi/prefix_types.rs | 10 +- .../src/stable_abi/tl_function.rs | 4 +- abi_stable_derive/src/workaround.rs | 8 +- .../src/datastructure/field_map.rs | 12 +- .../src/datastructure/type_param_map.rs | 14 +- as_derive_utils/src/gen_params_in.rs | 10 +- .../impl/src/lib.rs | 9 +- .../interface/src/lib.rs | 104 +++--- .../user/src/main.rs | 104 +++--- examples/1_trait_objects/interface/src/lib.rs | 116 +++---- .../1_trait_objects/interface/src/utils.rs | 80 +++-- examples/1_trait_objects/plugin_0/src/lib.rs | 9 +- examples/1_trait_objects/plugin_1/src/lib.rs | 9 +- examples/2_nonexhaustive/interface/src/lib.rs | 157 ++++----- testing/0/impl_0/src/lib.rs | 5 +- testing/0/interface_0/src/lib.rs | 38 +-- testing/1 - loading errors/impl_1/src/lib.rs | 5 +- .../1 - loading errors/interface_1/src/lib.rs | 11 +- .../version_compatibility/impl_0/src/lib.rs | 5 +- tools/sabi_extract/src/main.rs | 6 +- 102 files changed, 1372 insertions(+), 1790 deletions(-) diff --git a/abi_stable/src/_immovable_wrapper.rs b/abi_stable/src/_immovable_wrapper.rs index aa5bb1e7..8c7d89c1 100644 --- a/abi_stable/src/_immovable_wrapper.rs +++ b/abi_stable/src/_immovable_wrapper.rs @@ -1,6 +1,4 @@ -/** - Wrapper type to prevent moving the referent of a pointer out. -*/ +//! Wrapper type to prevent moving the referent of a pointer out. use std::{ fmt, diff --git a/abi_stable/src/abi_stability.rs b/abi_stable/src/abi_stability.rs index 166ac54b..015a82c1 100644 --- a/abi_stable/src/abi_stability.rs +++ b/abi_stable/src/abi_stability.rs @@ -1,6 +1,4 @@ -/*! -types and traits related to abi stability. -*/ +//! types and traits related to abi stability. #[doc(hidden)] pub mod abi_checking; diff --git a/abi_stable/src/const_utils.rs b/abi_stable/src/const_utils.rs index 704c3116..30d621bf 100644 --- a/abi_stable/src/const_utils.rs +++ b/abi_stable/src/const_utils.rs @@ -1,6 +1,4 @@ -/*! -Utilities for const contexts. -*/ +//! Utilities for const contexts. use crate::std_types::RStr; diff --git a/abi_stable/src/docs.rs b/abi_stable/src/docs.rs index 480de277..e4e0da83 100644 --- a/abi_stable/src/docs.rs +++ b/abi_stable/src/docs.rs @@ -1,6 +1,4 @@ -/*! -Additional docs for macros, and guides. -*/ +//! Additional docs for macros, and guides. pub mod library_evolution; pub mod prefix_types; diff --git a/abi_stable/src/erased_types.rs b/abi_stable/src/erased_types.rs index 8a0da864..de764c0b 100644 --- a/abi_stable/src/erased_types.rs +++ b/abi_stable/src/erased_types.rs @@ -1,6 +1,4 @@ -/*! -Types and traits related to type erasure. -*/ +//! Types and traits related to type erasure. use std::{ cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}, diff --git a/abi_stable/src/erased_types/trait_objects.rs b/abi_stable/src/erased_types/trait_objects.rs index bb8733fc..f0762777 100644 --- a/abi_stable/src/erased_types/trait_objects.rs +++ b/abi_stable/src/erased_types/trait_objects.rs @@ -1,6 +1,4 @@ -/*! -Ffi-safe trait objects for individual traits. -*/ +//! Ffi-safe trait objects for individual traits. use std::fmt::{self, Debug, Display}; diff --git a/abi_stable/src/erased_types/traits.rs b/abi_stable/src/erased_types/traits.rs index ff89325a..33e5018c 100644 --- a/abi_stable/src/erased_types/traits.rs +++ b/abi_stable/src/erased_types/traits.rs @@ -1,6 +1,4 @@ -/*! -Traits for types wrapped in `DynTrait<_>` -*/ +//! Traits for types wrapped in `DynTrait<_>` use crate::{ marker_type::NonOwningPhantom, @@ -221,11 +219,9 @@ declare_InterfaceType! { /////////////////////////////////////////////////////////////////////////////// -/** -Describes how a type is serialized by [`DynTrait`]. - -[`DynTrait`]: ../struct.DynTrait.html -*/ +/// Describes how a type is serialized by [`DynTrait`]. +/// +/// [`DynTrait`]: ../struct.DynTrait.html pub trait SerializeImplType<'s> { /// An [`InterfaceType`] implementor which determines the /// intermediate type through which this is serialized. @@ -238,12 +234,10 @@ pub trait SerializeImplType<'s> { ) -> Result<>::Proxy, RBoxError>; } -/** -Determines the intermediate type a [`SerializeImplType`] implementor is converted into, -and is then serialized. - -[`SerializeImplType`]: ./trait.SerializeImplType.html -*/ +/// Determines the intermediate type a [`SerializeImplType`] implementor is converted into, +/// and is then serialized. +/// +/// [`SerializeImplType`]: ./trait.SerializeImplType.html pub trait SerializeProxyType<'borr>: InterfaceType { /// The intermediate type. type Proxy: 'borr; @@ -283,14 +277,12 @@ where /////////////////////////////////////// -/** -Describes how `D` is deserialized, using a proxy to do so. - -Generally this delegates to a library function, -so that the implementation can be delegated -to the `implementation crate`. - -*/ +/// Describes how `D` is deserialized, using a proxy to do so. +/// +/// Generally this delegates to a library function, +/// so that the implementation can be delegated +/// to the `implementation crate`. +/// pub trait DeserializeDyn<'borr, D> { /// The type that is deserialized and then converted into `D`, /// with `DeserializeDyn::deserialize_dyn`. diff --git a/abi_stable/src/erased_types/type_info.rs b/abi_stable/src/erased_types/type_info.rs index 581624a8..13a3f9c3 100644 --- a/abi_stable/src/erased_types/type_info.rs +++ b/abi_stable/src/erased_types/type_info.rs @@ -1,6 +1,4 @@ -/*! -Contains TypeInfo,metadata for a type. -*/ +//! Contains TypeInfo,metadata for a type. use std::fmt; diff --git a/abi_stable/src/erased_types/vtable.rs b/abi_stable/src/erased_types/vtable.rs index 4a93ad29..8707dfda 100644 --- a/abi_stable/src/erased_types/vtable.rs +++ b/abi_stable/src/erased_types/vtable.rs @@ -1,8 +1,5 @@ -/*! +//! Contains `DynTrait<_>`'s vtable,and related types/traits. -Contains `DynTrait<_>`'s vtable,and related types/traits. - -*/ use std::{ fmt::{self, Debug, Write as FmtWrite}, io, diff --git a/abi_stable/src/external_types.rs b/abi_stable/src/external_types.rs index 3088aca1..deb47469 100644 --- a/abi_stable/src/external_types.rs +++ b/abi_stable/src/external_types.rs @@ -1,10 +1,7 @@ -/*! -Ffi wrapper for types defined outside the standard library. - -The modules here are named after the crates whose types are being wrapped. - - -*/ +//! Ffi wrapper for types defined outside the standard library. +//! +//! The modules here are named after the crates whose types are being wrapped. +//! #[cfg(feature = "crossbeam-channel")] #[cfg_attr(feature = "docsrs", doc(cfg(feature = "channels")))] diff --git a/abi_stable/src/external_types/crossbeam_channel.rs b/abi_stable/src/external_types/crossbeam_channel.rs index b07ad8b2..20bb0646 100644 --- a/abi_stable/src/external_types/crossbeam_channel.rs +++ b/abi_stable/src/external_types/crossbeam_channel.rs @@ -1,10 +1,6 @@ -/*! - -Ffi-safe wrapper types around the -[crossbeam-channel](https://crates.io/crates/crossbeam-channel/) -channel types. - -*/ +//! Ffi-safe wrapper types around the +//! [crossbeam-channel](https://crates.io/crates/crossbeam-channel/) +//! channel types. use std::{ fmt::{self, Debug}, diff --git a/abi_stable/src/external_types/parking_lot.rs b/abi_stable/src/external_types/parking_lot.rs index 3dd9648a..2e4c4bf8 100644 --- a/abi_stable/src/external_types/parking_lot.rs +++ b/abi_stable/src/external_types/parking_lot.rs @@ -1,7 +1,5 @@ -/*! -Ffi-safe synchronization primitives,most of which are ffi-safe wrappers of -[parking_lot](https://crates.io/crates/parking_lot) types -*/ +//! Ffi-safe synchronization primitives,most of which are ffi-safe wrappers of +//! [parking_lot](https://crates.io/crates/parking_lot) types pub mod mutex; pub mod once; diff --git a/abi_stable/src/external_types/serde_json.rs b/abi_stable/src/external_types/serde_json.rs index fca30820..fad79602 100644 --- a/abi_stable/src/external_types/serde_json.rs +++ b/abi_stable/src/external_types/serde_json.rs @@ -1,6 +1,4 @@ -/*! -Ffi-safe equivalents of `serde_json` types. -*/ +//! Ffi-safe equivalents of `serde_json` types. use std::{ convert::{TryFrom, TryInto}, diff --git a/abi_stable/src/inline_storage.rs b/abi_stable/src/inline_storage.rs index 50149d3a..395c34c2 100644 --- a/abi_stable/src/inline_storage.rs +++ b/abi_stable/src/inline_storage.rs @@ -1,19 +1,15 @@ -/*! -Contains the `InlineStorage` trait,and related items. -*/ - -/** -Type used as the inline storage of a RSmallBox<>/NonExhaustive<>. - -# Safety - -Implementors must: - -- Be types for which all bitpatterns are valid. - -- Not implement Drop,and have no drop glue. - -*/ +//! Contains the `InlineStorage` trait,and related items. + +/// Type used as the inline storage of a RSmallBox<>/NonExhaustive<>. +/// +/// # Safety +/// +/// Implementors must: +/// +/// - Be types for which all bitpatterns are valid. +/// +/// - Not implement Drop,and have no drop glue. +/// pub unsafe trait InlineStorage {} macro_rules! impl_for_arrays { @@ -134,12 +130,10 @@ impl ScratchSpace { unsafe { Self::new_unchecked(value) } } - /** - # Safety - - You must ensure that `T` has a compatible size/alignement with `Inline`, - and that `Inline` si valid for all bitpatterns. - */ + /// # Safety + /// + /// You must ensure that `T` has a compatible size/alignement with `Inline`, + /// and that `Inline` si valid for all bitpatterns. #[inline] #[allow(dead_code)] pub(crate) unsafe fn new_unchecked(value: T) -> Self { diff --git a/abi_stable/src/library/c_abi_testing.rs b/abi_stable/src/library/c_abi_testing.rs index cd991b41..196d3e45 100644 --- a/abi_stable/src/library/c_abi_testing.rs +++ b/abi_stable/src/library/c_abi_testing.rs @@ -1,7 +1,5 @@ -/*! -This module runs tests on the C abi as defined by Rust, -to detect whether Rust changed how it deals with zero-sized types. -*/ +//! This module runs tests on the C abi as defined by Rust, +//! to detect whether Rust changed how it deals with zero-sized types. use super::LibraryError; use crate::std_types::{RBoxError, Tuple2, Tuple3}; diff --git a/abi_stable/src/macros.rs b/abi_stable/src/macros.rs index 70bc4510..8e71ac8b 100644 --- a/abi_stable/src/macros.rs +++ b/abi_stable/src/macros.rs @@ -431,11 +431,9 @@ macro_rules! assert_matches { /////////////////////////////////////////////////////////////////////////////// -/** -Constructs an [`ItemInfo`], with information about the place where it's called. - -[`ItemInfo`]: ./type_layout/struct.ItemInfo.html -*/ +/// Constructs an [`ItemInfo`], with information about the place where it's called. +/// +/// [`ItemInfo`]: ./type_layout/struct.ItemInfo.html #[macro_export] macro_rules! make_item_info { () => { @@ -651,9 +649,7 @@ macro_rules! multi_str { ) } -/** -Constructs a `&'static SharedVars` -*/ +/// Constructs a `&'static SharedVars` macro_rules! make_shared_vars{ ( impl[$($impl_gen:tt)*] $type:ty diff --git a/abi_stable/src/marker_type.rs b/abi_stable/src/marker_type.rs index 51d9bf00..85a62929 100644 --- a/abi_stable/src/marker_type.rs +++ b/abi_stable/src/marker_type.rs @@ -1,6 +1,4 @@ -/*! -Zero-sized types . -*/ +//! Zero-sized types . use std::{cell::Cell, marker::PhantomData, rc::Rc}; @@ -193,20 +191,18 @@ unsafe impl PrefixStableAbi for ErasedPrefix { ////////////////////////////////////////////////////////////// -/** -MarkerType which ignores its type parameter in its [`StableAbi`] implementation. - -# Safety - -`Unsafe` is part of its name, -because users can violate memory safety -if they depend on the value of the type parameter passed to `UnsafeIgnoredType` for safety, -since the type parameter is ignored when type checking dynamic libraries. - - -[`StableAbi`]: ../trait.StableAbi.html - -*/ +/// MarkerType which ignores its type parameter in its [`StableAbi`] implementation. +/// +/// # Safety +/// +/// `Unsafe` is part of its name, +/// because users can violate memory safety +/// if they depend on the value of the type parameter passed to `UnsafeIgnoredType` for safety, +/// since the type parameter is ignored when type checking dynamic libraries. +/// +/// +/// [`StableAbi`]: ../trait.StableAbi.html +/// pub struct UnsafeIgnoredType { _inner: PhantomData, } diff --git a/abi_stable/src/multikey_map.rs b/abi_stable/src/multikey_map.rs index 8bb321e8..20c4d338 100644 --- a/abi_stable/src/multikey_map.rs +++ b/abi_stable/src/multikey_map.rs @@ -142,22 +142,20 @@ where self.arena.len() } - /** - Replaces the element at the `replace` index with the one at the `with` index, - mapping all keys to the `with` index to the `replace` index. - - # Return value - - This method returns the previous value at `replace` if all these conditions are satisfied: - - - The `replace` index is not the same as the `with` index. - - - Both `replace` and `with` are valid indices - - If the conditions are not satisfied this method will return None without - modifying the collection. - - */ + /// Replaces the element at the `replace` index with the one at the `with` index, + /// mapping all keys to the `with` index to the `replace` index. + /// + /// # Return value + /// + /// This method returns the previous value at `replace` if all these conditions are satisfied: + /// + /// - The `replace` index is not the same as the `with` index. + /// + /// - Both `replace` and `with` are valid indices + /// + /// If the conditions are not satisfied this method will return None without + /// modifying the collection. + /// pub fn replace_with_index(&mut self, replace: MapIndex, with: MapIndex) -> Option { if replace == with || !self.arena.contains(replace.index) diff --git a/abi_stable/src/nonexhaustive_enum.rs b/abi_stable/src/nonexhaustive_enum.rs index 3d3e077a..9d2efad1 100644 --- a/abi_stable/src/nonexhaustive_enum.rs +++ b/abi_stable/src/nonexhaustive_enum.rs @@ -1,12 +1,10 @@ -/*! -Contains types and traits for nonexhaustive enums. - -The most important type here is [NonExhaustive](./nonexhaustive/struct.NonExhaustive.html), -which allows passing an enum which used the -`#[derive(StableAbi)] #[sabi(kind(WithNonExhaustive(...)))]` -attributes through ffi. - -*/ +//! Contains types and traits for nonexhaustive enums. +//! +//! The most important type here is [NonExhaustive](./nonexhaustive/struct.NonExhaustive.html), +//! which allows passing an enum which used the +//! `#[derive(StableAbi)] #[sabi(kind(WithNonExhaustive(...)))]` +//! attributes through ffi. +//! #[doc(hidden)] pub mod doc_enums; diff --git a/abi_stable/src/nonexhaustive_enum/examples.rs b/abi_stable/src/nonexhaustive_enum/examples.rs index 15c8efa0..ae19b938 100644 --- a/abi_stable/src/nonexhaustive_enum/examples.rs +++ b/abi_stable/src/nonexhaustive_enum/examples.rs @@ -1,6 +1,5 @@ -/*! -Example non-exhaustive enums,used in tests -*/ +//! Example non-exhaustive enums,used in tests + #![allow(dead_code)] pub mod command_one { diff --git a/abi_stable/src/nonexhaustive_enum/nonexhaustive.rs b/abi_stable/src/nonexhaustive_enum/nonexhaustive.rs index 1e4a4b0e..87a3b6d3 100644 --- a/abi_stable/src/nonexhaustive_enum/nonexhaustive.rs +++ b/abi_stable/src/nonexhaustive_enum/nonexhaustive.rs @@ -1,6 +1,4 @@ -/*! -Contains `NonExhaustive<>` and related items. -*/ +//! Contains `NonExhaustive<>` and related items. use std::{ cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}, @@ -637,10 +635,7 @@ impl NonExhaustive { } } -/** -First it serializes a `NonExhaustive<_>` into a proxy,then it serializes that proxy. - -*/ +/// First it serializes a `NonExhaustive<_>` into a proxy,then it serializes that proxy. impl Serialize for NonExhaustive where I: InterfaceBound>, diff --git a/abi_stable/src/nonexhaustive_enum/traits.rs b/abi_stable/src/nonexhaustive_enum/traits.rs index 92010374..54910d6b 100644 --- a/abi_stable/src/nonexhaustive_enum/traits.rs +++ b/abi_stable/src/nonexhaustive_enum/traits.rs @@ -1,6 +1,4 @@ -/*! -The traits releated to nonexhaustive enums. -*/ +//! The traits releated to nonexhaustive enums. use std::{ cmp::{Eq, Ord}, diff --git a/abi_stable/src/pointer_trait.rs b/abi_stable/src/pointer_trait.rs index 6fe4b791..fc9c5a50 100644 --- a/abi_stable/src/pointer_trait.rs +++ b/abi_stable/src/pointer_trait.rs @@ -1,6 +1,5 @@ -/*! -Traits for pointers. -*/ +//! Traits for pointers. + use std::{mem::ManuallyDrop, ptr::NonNull}; use crate::{ diff --git a/abi_stable/src/prefix_type.rs b/abi_stable/src/prefix_type.rs index e9f58fee..71438577 100644 --- a/abi_stable/src/prefix_type.rs +++ b/abi_stable/src/prefix_type.rs @@ -1,7 +1,4 @@ -/*! -Types,traits,and functions used by prefix-types. - -*/ +//! Types,traits,and functions used by prefix-types. use std::{ fmt::{self, Debug}, diff --git a/abi_stable/src/reflection.rs b/abi_stable/src/reflection.rs index e8826ea7..67c269ff 100644 --- a/abi_stable/src/reflection.rs +++ b/abi_stable/src/reflection.rs @@ -1,17 +1,13 @@ -/*! -Types and submodules for doing runtime reflection. -*/ +//! Types and submodules for doing runtime reflection. #[cfg(all(test, not(feature = "only_new_tests")))] pub mod tests { pub mod derive_reflection; } -/** -Implementation details of the sabi_extract tool. - -This is here so that its tests run among other abi_stable tests. -*/ +/// Implementation details of the sabi_extract tool. +/// +/// This is here so that its tests run among other abi_stable tests. #[doc(hidden)] pub mod export_module; diff --git a/abi_stable/src/reflection/export_module.rs b/abi_stable/src/reflection/export_module.rs index ce3a0c2d..f55db226 100644 --- a/abi_stable/src/reflection/export_module.rs +++ b/abi_stable/src/reflection/export_module.rs @@ -1,6 +1,4 @@ -/*! -Data structures to export a type as though it were a module. -*/ +//! Data structures to export a type as though it were a module. use std::fmt::{self, Display}; diff --git a/abi_stable/src/reflection/tests/derive_reflection.rs b/abi_stable/src/reflection/tests/derive_reflection.rs index e034ce99..8ca72f44 100644 --- a/abi_stable/src/reflection/tests/derive_reflection.rs +++ b/abi_stable/src/reflection/tests/derive_reflection.rs @@ -1,6 +1,4 @@ -/*! -Tests the fields related to reflection generated in the StableAbi derive macro. -*/ +//! Tests the fields related to reflection generated in the StableAbi derive macro. use crate::{ diff --git a/abi_stable/src/sabi_trait.rs b/abi_stable/src/sabi_trait.rs index fcb03d50..c0888fa3 100644 --- a/abi_stable/src/sabi_trait.rs +++ b/abi_stable/src/sabi_trait.rs @@ -1,6 +1,4 @@ -/*! -Contains items related to the `#[sabi_trait]` attribute. -*/ +//! Contains items related to the `#[sabi_trait]` attribute. #[doc(hidden)] pub mod reexports { diff --git a/abi_stable/src/sabi_trait/doc_examples.rs b/abi_stable/src/sabi_trait/doc_examples.rs index 276f34d2..1d37dab4 100644 --- a/abi_stable/src/sabi_trait/doc_examples.rs +++ b/abi_stable/src/sabi_trait/doc_examples.rs @@ -1,6 +1,4 @@ -/*! -Examples of `#[sabi_trait]` generated trait objects,for the documentation. -*/ +//! Examples of `#[sabi_trait]` generated trait objects,for the documentation. use crate::sabi_trait; diff --git a/abi_stable/src/sabi_trait/examples.rs b/abi_stable/src/sabi_trait/examples.rs index 9220ad54..4f6c614d 100644 --- a/abi_stable/src/sabi_trait/examples.rs +++ b/abi_stable/src/sabi_trait/examples.rs @@ -193,57 +193,51 @@ pub trait StaticTrait: 'static {} ////////////////////////////////////// -/** - -While RSomethingElse_TO can be constructed from an RArc, -no method on the trait can be called because RSomethingElse has mutable and by value methods. - -```compile_fail -use abi_stable::{ - marker_type::*, - sabi_trait::{prelude::*,examples::*}, - std_types::*, -}; - -let what=RSomethingElse_TO::from_ptr(RArc::new(100u32),TD_Opaque); -RSomethingElse::into_value(what); - - -``` - - -``` -use abi_stable::{ - marker_type::*, - sabi_trait::{prelude::*,examples::*}, - std_types::*, -}; - -use std::marker::PhantomData; - -let ptr=RBox::new(PhantomData::); -let _=RSomethingElse_TO::from_value(ptr,TD_Opaque); - -``` - -Cannot create RSomethingElse from a !Send type. -```compile_fail -use abi_stable::{ - marker_type::*, - sabi_trait::{prelude::*,examples::*}, - std_types::*, -}; - -use std::marker::PhantomData; - -let ptr=RBox::new(PhantomData::); -let _=RSomethingElse_TO::from_value(ptr,TD_Opaque); - -``` - - - -*/ +/// While RSomethingElse_TO can be constructed from an RArc, +/// no method on the trait can be called because RSomethingElse has mutable and by value methods. +/// +/// ```compile_fail +/// use abi_stable::{ +/// marker_type::*, +/// sabi_trait::{examples::*, prelude::*}, +/// std_types::*, +/// }; +/// +/// let what = RSomethingElse_TO::from_ptr(RArc::new(100u32), TD_Opaque); +/// RSomethingElse::into_value(what); +/// +/// +/// ``` +/// +/// +/// ``` +/// use abi_stable::{ +/// marker_type::*, +/// sabi_trait::{examples::*, prelude::*}, +/// std_types::*, +/// }; +/// +/// use std::marker::PhantomData; +/// +/// let ptr = RBox::new(PhantomData::); +/// let _ = RSomethingElse_TO::from_value(ptr, TD_Opaque); +/// +/// ``` +/// +/// Cannot create RSomethingElse from a !Send type. +/// ```compile_fail +/// use abi_stable::{ +/// marker_type::*, +/// sabi_trait::{examples::*, prelude::*}, +/// std_types::*, +/// }; +/// +/// use std::marker::PhantomData; +/// +/// let ptr = RBox::new(PhantomData::); +/// let _ = RSomethingElse_TO::from_value(ptr, TD_Opaque); +/// +/// ``` pub struct Dummy0; #[sabi_trait] diff --git a/abi_stable/src/sabi_trait/vtable.rs b/abi_stable/src/sabi_trait/vtable.rs index d4fda9ed..fa5e2a39 100644 --- a/abi_stable/src/sabi_trait/vtable.rs +++ b/abi_stable/src/sabi_trait/vtable.rs @@ -74,25 +74,23 @@ where } impl<_Self, OrigPtr, Downcasting, V> VTableTO<_Self, OrigPtr, Downcasting, V, ()> { - /** - Wraps an erased vtable. - - # Safety - - These are the requirements for the caller: - - - `OrigPtr` must be a pointer to the type that the vtable functions - take as the first parameter. - - - The vtable must not come from a reborrowed RObject - (created using RObject::reborrow or RObject::reborrow_mut). - - - The vtable must be the `` of a struct declared with - `#[derive(StableAbi)]``#[sabi(kind(Prefix(prefix_ref="")))]`. - - - The vtable must have `PrefixRef>` - as its first declared field - */ + /// Wraps an erased vtable. + /// + /// # Safety + /// + /// These are the requirements for the caller: + /// + /// - `OrigPtr` must be a pointer to the type that the vtable functions + /// take as the first parameter. + /// + /// - The vtable must not come from a reborrowed RObject + /// (created using RObject::reborrow or RObject::reborrow_mut). + /// + /// - The vtable must be the `` of a struct declared with + /// `#[derive(StableAbi)]``#[sabi(kind(Prefix(prefix_ref="")))]`. + /// + /// - The vtable must have `PrefixRef>` + /// as its first declared field pub const unsafe fn for_robject(vtable: PrefixRef) -> Self { Self { vtable, @@ -123,13 +121,11 @@ impl<'borr, _Self, ErasedPtr, OrigPtr, I, Downcasting, V> impl<'borr, _Self, ErasedPtr, OrigPtr, I, Downcasting, V> VTableTO_DT<'borr, _Self, ErasedPtr, OrigPtr, I, Downcasting, V> { - /** - Wraps an erased vtable,alongside the vtable for DynTrait. - - # Safety - - This has the same safety requirements as the 'for_robject' constructor - */ + /// Wraps an erased vtable,alongside the vtable for DynTrait. + /// + /// # Safety + /// + /// This has the same safety requirements as the 'for_robject' constructor pub const unsafe fn for_dyntrait( vtable: PrefixRef, for_dyn_trait: VTableDT<'borr, _Self, ErasedPtr, OrigPtr, I, Downcasting>, diff --git a/abi_stable/src/sabi_types.rs b/abi_stable/src/sabi_types.rs index 7959bdd6..53b64261 100644 --- a/abi_stable/src/sabi_types.rs +++ b/abi_stable/src/sabi_types.rs @@ -1,6 +1,4 @@ -/*! -ffi-safe types that aren't wrappers for other types. -*/ +//! ffi-safe types that aren't wrappers for other types. mod constructor; mod ignored_wrapper; diff --git a/abi_stable/src/sabi_types/ignored_wrapper.rs b/abi_stable/src/sabi_types/ignored_wrapper.rs index fdc37a29..4aff90b3 100644 --- a/abi_stable/src/sabi_types/ignored_wrapper.rs +++ b/abi_stable/src/sabi_types/ignored_wrapper.rs @@ -1,6 +1,4 @@ -/*! -Wrapper type(s) where their value is ignored in some trait impls . -*/ +//! Wrapper type(s) where their value is ignored in some trait impls . use std::{ cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}, @@ -55,7 +53,8 @@ use std::{ /// ); /// /// assert_eq!(map.len(), 1); -/// assert_eq!(map.get(&a).unwrap().alt_name.as_str(), "H___ of B_____");/// +/// assert_eq!(map.get(&a).unwrap().alt_name.as_str(), "H___ of B_____"); +/// /// ``` /// #[repr(transparent)] diff --git a/abi_stable/src/sabi_types/late_static_ref.rs b/abi_stable/src/sabi_types/late_static_ref.rs index 5753e107..2ba0860d 100644 --- a/abi_stable/src/sabi_types/late_static_ref.rs +++ b/abi_stable/src/sabi_types/late_static_ref.rs @@ -1,6 +1,4 @@ -/*! -A late-initialized static reference. -*/ +//! A late-initialized static reference. use std::{ marker::PhantomData, diff --git a/abi_stable/src/sabi_types/move_ptr.rs b/abi_stable/src/sabi_types/move_ptr.rs index 311d8353..6fa8467c 100644 --- a/abi_stable/src/sabi_types/move_ptr.rs +++ b/abi_stable/src/sabi_types/move_ptr.rs @@ -1,6 +1,4 @@ -/*! -Contains the `MovePtr<_>` type. -*/ +//! Contains the `MovePtr<_>` type. use std::{ alloc::{self, Layout}, diff --git a/abi_stable/src/sabi_types/rsmallbox.rs b/abi_stable/src/sabi_types/rsmallbox.rs index b79a93a4..71eaf1e2 100644 --- a/abi_stable/src/sabi_types/rsmallbox.rs +++ b/abi_stable/src/sabi_types/rsmallbox.rs @@ -1,6 +1,4 @@ -/*! -Contains the `RSmallBox<_>` type. -*/ +//! Contains the `RSmallBox<_>` type. use crate::{ pointer_trait::{ diff --git a/abi_stable/src/sabi_types/version.rs b/abi_stable/src/sabi_types/version.rs index 596960d9..0f7db625 100644 --- a/abi_stable/src/sabi_types/version.rs +++ b/abi_stable/src/sabi_types/version.rs @@ -1,6 +1,4 @@ -/*! -Types representing the version number of a library. -*/ +//! Types representing the version number of a library. use core_extensions::{SelfOps, StringExt}; diff --git a/abi_stable/src/std_types.rs b/abi_stable/src/std_types.rs index e26def87..170fe4ba 100644 --- a/abi_stable/src/std_types.rs +++ b/abi_stable/src/std_types.rs @@ -1,11 +1,8 @@ -/*! -Contains many ffi-safe equivalents of standard library types. -The vast majority of them can be converted to and from std equivalents. - -For ffi-safe equivalents/wrappers of types outside the standard library go to -the [external_types module](../external_types/index.html) - -*/ +//! Contains many ffi-safe equivalents of standard library types. +//! The vast majority of them can be converted to and from std equivalents. +//! +//! For ffi-safe equivalents/wrappers of types outside the standard library go to +//! the [external_types module](../external_types/index.html) pub(crate) mod arc; pub(crate) mod boxed; @@ -26,17 +23,15 @@ pub(crate) mod tuple; pub mod utypeid; pub mod vec; -/** -Some types from the `std::sync` module have ffi-safe equivalents in abi_stable::external_types. - -The `sync::{Mutex,RwLock,Once}` equivalents are declared in -`abi_stable::external_types::parking_lot` - -The `mpsc` equivalents are declared in -`abi_stable::external_types::crossbeam_channel`, -this is enabled by default with the `channels`/`crossbeam-channel` cargo feature. - -*/ +/// Some types from the `std::sync` module have ffi-safe equivalents in +/// `abi_stable::external_types`. +/// +/// The `sync::{Mutex,RwLock,Once}` equivalents are declared in +/// `abi_stable::external_types::parking_lot` +/// +/// The `mpsc` equivalents are declared in +/// `abi_stable::external_types::crossbeam_channel`, +/// this is enabled by default with the `channels`/`crossbeam-channel` cargo feature. pub mod sync {} #[doc(inline)] diff --git a/abi_stable/src/std_types/arc.rs b/abi_stable/src/std_types/arc.rs index c239a86f..b27b4f3a 100644 --- a/abi_stable/src/std_types/arc.rs +++ b/abi_stable/src/std_types/arc.rs @@ -1,6 +1,4 @@ -/*! -Contains the ffi-safe equivalent of `std::sync::Arc`. -*/ +//! Contains the ffi-safe equivalent of `std::sync::Arc`. use std::{borrow::Borrow, marker::PhantomData, mem::ManuallyDrop, sync::Arc}; @@ -25,56 +23,53 @@ mod test; mod private { use super::*; - /** - Ffi-safe version of `std::sync::Arc` - - # Example - - Using an `RArc>>` to get a list populated from multiple threads. - - ``` - use abi_stable::{ - external_types::RMutex, - std_types::{RArc, RVec}, - }; - - use std::thread; - - let arc = RArc::new(RMutex::new(RVec::new())); - - { - let arc2 = RArc::clone(&arc); - assert!( std::ptr::eq(&*arc, &*arc2) ); - } - - let mut guards = Vec::new(); - - for i in 0..10_u64 { - let arc = RArc::clone(&arc); - guards.push(thread::spawn(move||{ - for j in 0..100_u64{ - arc.lock().push(i*100+j); - } - })); - } - - for guard in guards{ - guard.join().unwrap(); - } - - let mut vec = RArc::try_unwrap(arc) - .ok() - .expect("All the threads were joined, so this must be the only RArc") - .into_inner(); - - vec.sort(); - - assert_eq!( vec, (0..1000).collect::>() ); - - - ``` - - */ + /// Ffi-safe version of `std::sync::Arc` + /// + /// # Example + /// + /// Using an `RArc>>` to get a list populated from multiple threads. + /// + /// ``` + /// use abi_stable::{ + /// external_types::RMutex, + /// std_types::{RArc, RVec}, + /// }; + /// + /// use std::thread; + /// + /// let arc = RArc::new(RMutex::new(RVec::new())); + /// + /// { + /// let arc2 = RArc::clone(&arc); + /// assert!(std::ptr::eq(&*arc, &*arc2)); + /// } + /// + /// let mut guards = Vec::new(); + /// + /// for i in 0..10_u64 { + /// let arc = RArc::clone(&arc); + /// guards.push(thread::spawn(move || { + /// for j in 0..100_u64 { + /// arc.lock().push(i * 100 + j); + /// } + /// })); + /// } + /// + /// for guard in guards { + /// guard.join().unwrap(); + /// } + /// + /// let mut vec = RArc::try_unwrap(arc) + /// .ok() + /// .expect("All the threads were joined, so this must be the only RArc") + /// .into_inner(); + /// + /// vec.sort(); + /// + /// assert_eq!(vec, (0..1000).collect::>()); + /// + /// ``` + /// #[derive(StableAbi)] #[repr(C)] pub struct RArc { diff --git a/abi_stable/src/std_types/boxed.rs b/abi_stable/src/std_types/boxed.rs index 195808d7..2012d27e 100644 --- a/abi_stable/src/std_types/boxed.rs +++ b/abi_stable/src/std_types/boxed.rs @@ -1,6 +1,4 @@ -/*! -Contains the ffi-safe equivalent of `std::boxed::Box`. -*/ +//! Contains the ffi-safe equivalent of `std::boxed::Box`. use std::{ borrow::{Borrow, BorrowMut}, @@ -39,43 +37,41 @@ mod test; mod private { use super::*; - /** - Ffi-safe equivalent of `std::box::Box`. - - # Example - - Declaring a recursive datatype. - - ``` - use abi_stable::{ - std_types::{RBox, RString}, - StableAbi, - }; - - #[repr(u8)] - #[derive(StableAbi)] - enum Command{ - SendProduct{ - id: u64, - }, - GoProtest{ - cause: RString, - place: RString, - }, - SendComplaint{ - cause: RString, - website: RString, - }, - WithMetadata{ - command: RBox, - metadata: RString, - }, - } - - - ``` - - */ + /// Ffi-safe equivalent of `std::box::Box`. + /// + /// # Example + /// + /// Declaring a recursive datatype. + /// + /// ``` + /// use abi_stable::{ + /// std_types::{RBox, RString}, + /// StableAbi, + /// }; + /// + /// #[repr(u8)] + /// #[derive(StableAbi)] + /// enum Command { + /// SendProduct { + /// id: u64, + /// }, + /// GoProtest { + /// cause: RString, + /// place: RString, + /// }, + /// SendComplaint { + /// cause: RString, + /// website: RString, + /// }, + /// WithMetadata { + /// command: RBox, + /// metadata: RString, + /// }, + /// } + /// + /// + /// ``` + /// #[repr(C)] #[derive(StableAbi)] pub struct RBox { diff --git a/abi_stable/src/std_types/cmp_ordering.rs b/abi_stable/src/std_types/cmp_ordering.rs index 835a797f..aa21c6bc 100644 --- a/abi_stable/src/std_types/cmp_ordering.rs +++ b/abi_stable/src/std_types/cmp_ordering.rs @@ -1,36 +1,30 @@ -/*! -Contains the ffi-safe equivalent of `std::cmp::Ordering`. -*/ +//! Contains the ffi-safe equivalent of `std::cmp::Ordering`. use std::cmp::Ordering; -/** -Ffi-safe equivalent of `std::cmp::Ordering`. - -# Example - -This defines an extern function, which compares a slice to another. - -``` - -use abi_stable::{ - std_types::{RCmpOrdering, RSlice}, - sabi_extern_fn, -}; -use std::cmp::Ord; - - -#[sabi_extern_fn] -pub fn compare_slices(l: RSlice<'_, T>, r: RSlice<'_, T>) -> RCmpOrdering -where - T: Ord -{ - l.cmp(&r) - .into() -} - -``` -*/ +/// Ffi-safe equivalent of `std::cmp::Ordering`. +/// +/// # Example +/// +/// This defines an extern function, which compares a slice to another. +/// +/// ```rust +/// +/// use abi_stable::{ +/// sabi_extern_fn, +/// std_types::{RCmpOrdering, RSlice}, +/// }; +/// use std::cmp::Ord; +/// +/// #[sabi_extern_fn] +/// pub fn compare_slices(l: RSlice<'_, T>, r: RSlice<'_, T>) -> RCmpOrdering +/// where +/// T: Ord, +/// { +/// l.cmp(&r).into() +/// } +/// +/// ``` #[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash, Deserialize, Serialize)] #[repr(u8)] #[derive(StableAbi)] diff --git a/abi_stable/src/std_types/cow.rs b/abi_stable/src/std_types/cow.rs index 2c778db9..de92f4f4 100644 --- a/abi_stable/src/std_types/cow.rs +++ b/abi_stable/src/std_types/cow.rs @@ -1,6 +1,4 @@ -/*! -Contains the ffi-safe equivalent of `std::borrow::Cow`, and related items. -*/ +//! Contains the ffi-safe equivalent of `std::borrow::Cow`, and related items. use std::{ borrow::{Borrow, Cow}, @@ -165,45 +163,42 @@ where //////////////////////////////////////////////////////////////////// -/** -Ffi-safe equivalent of `std::borrow::Cow`. - -The most common examples of this type are: - -- `RCow<'_, str>`: contains an `RStr<'_>` or an `RString`. - -- `RCow<'_, [T]>`: contains an `RSlice<'_, T>` or an `RVec`. - -- `RCow<'_, T>`: contains a `&T` or a `T`. - -# Example - -### Using a `RCow<'a, str>`. - -This implements a solution to the well known fizzbuzz problem. - -``` -use abi_stable::std_types::RCow; - -fn fizzbuzz(n: u32) -> RCow<'static, str>{ - match (n%3, n%5) { - (0, 0) => RCow::from("FizzBuzz"), - (0, _) => RCow::from("Fizz"), - (_, 0) => RCow::from("Buzz"), - (_, _) => RCow::from(n.to_string()), - } -} - -for n in 1 ..= 100{ - println!("{}", fizzbuzz(n)); -} - -``` - -Note: this example allocates when the number is neither a multiple of 5 or 3. - - -*/ +/// Ffi-safe equivalent of `std::borrow::Cow`. +/// +/// The most common examples of this type are: +/// +/// - `RCow<'_, str>`: contains an `RStr<'_>` or an `RString`. +/// +/// - `RCow<'_, [T]>`: contains an `RSlice<'_, T>` or an `RVec`. +/// +/// - `RCow<'_, T>`: contains a `&T` or a `T`. +/// +/// # Example +/// +/// ### Using a `RCow<'a, str>`. +/// +/// This implements a solution to the well known fizzbuzz problem. +/// +/// ``` +/// use abi_stable::std_types::RCow; +/// +/// fn fizzbuzz(n: u32) -> RCow<'static, str> { +/// match (n % 3, n % 5) { +/// (0, 0) => RCow::from("FizzBuzz"), +/// (0, _) => RCow::from("Fizz"), +/// (_, 0) => RCow::from("Buzz"), +/// (_, _) => RCow::from(n.to_string()), +/// } +/// } +/// +/// for n in 1..=100 { +/// println!("{}", fizzbuzz(n)); +/// } +/// ``` +/// +/// Note: this example allocates when the number is neither a multiple of 5 or 3. +/// +/// #[repr(C)] #[derive(StableAbi)] #[sabi( @@ -602,43 +597,38 @@ where //////////////////////////////////////////////////////////// -/** -Deserializes an `RCow<'a, [u8]>` that borrows the slice from the deserializer -whenever possible. - -# Example - -Defining a type containing an `RCow<'a, [u8]>` which borrows from the deserializer. - -``` -use abi_stable::std_types::cow::{ - deserialize_borrowed_bytes, - RCow, -}; - -use serde::{Deserialize, Serialize}; - - -#[derive(Debug, Deserialize, Serialize, PartialEq)] -pub struct TheSlice<'a>{ - #[serde(borrow, deserialize_with = "deserialize_borrowed_bytes")] - slice: RCow<'a, [u8]>, -} - - -let the_slice = TheSlice{ slice: RCow::from(vec![0, 1, 2, 3, 4, 5]) }; - -let vec = bincode::serialize(&the_slice).unwrap(); - -let deserialized_slice = bincode::deserialize(&vec).unwrap(); - -assert_eq!(the_slice, deserialized_slice); - -assert!( deserialized_slice.slice.is_borrowed() ); - -``` - -*/ +/// Deserializes an `RCow<'a, [u8]>` that borrows the slice from the deserializer +/// whenever possible. +/// +/// # Example +/// +/// Defining a type containing an `RCow<'a, [u8]>` which borrows from the deserializer. +/// +/// ``` +/// use abi_stable::std_types::cow::{deserialize_borrowed_bytes, RCow}; +/// +/// use serde::{Deserialize, Serialize}; +/// +/// #[derive(Debug, Deserialize, Serialize, PartialEq)] +/// pub struct TheSlice<'a> { +/// #[serde(borrow, deserialize_with = "deserialize_borrowed_bytes")] +/// slice: RCow<'a, [u8]>, +/// } +/// +/// let the_slice = TheSlice { +/// slice: RCow::from(vec![0, 1, 2, 3, 4, 5]), +/// }; +/// +/// let vec = bincode::serialize(&the_slice).unwrap(); +/// +/// let deserialized_slice = bincode::deserialize(&vec).unwrap(); +/// +/// assert_eq!(the_slice, deserialized_slice); +/// +/// assert!(deserialized_slice.slice.is_borrowed()); +/// +/// ``` +/// pub fn deserialize_borrowed_bytes<'de, 'a, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, @@ -656,47 +646,39 @@ where }) } -/** -Deserializes an `RCow<'a, str>` that borrows the string from the deserializer -whenever possible. - - -# Example - -Defining a type containing an `RCow<'a, str>` which borrows from the deserializer. - -``` -use abi_stable::std_types::cow::{ - deserialize_borrowed_str, - RCow, -}; - -use serde::{Deserialize, Serialize}; - - -#[derive(Debug, Deserialize, Serialize, PartialEq)] -pub struct TheSlice<'a>{ - #[serde(borrow, deserialize_with = "deserialize_borrowed_str")] - slice: RCow<'a, str>, -} - - -let the_slice = TheSlice{ slice: RCow::from("That's a lot of fish.") }; - -let string = serde_json::to_string(&the_slice).unwrap(); - -let deserialized_slice = serde_json::from_str::>(&string).unwrap(); - -assert_eq!(the_slice, deserialized_slice); - -assert!( deserialized_slice.slice.is_borrowed() ); - -``` - - - - -*/ +/// Deserializes an `RCow<'a, str>` that borrows the string from the deserializer +/// whenever possible. +/// +/// +/// # Example +/// +/// Defining a type containing an `RCow<'a, str>` which borrows from the deserializer. +/// +/// ``` +/// use abi_stable::std_types::cow::{deserialize_borrowed_str, RCow}; +/// +/// use serde::{Deserialize, Serialize}; +/// +/// #[derive(Debug, Deserialize, Serialize, PartialEq)] +/// pub struct TheSlice<'a> { +/// #[serde(borrow, deserialize_with = "deserialize_borrowed_str")] +/// slice: RCow<'a, str>, +/// } +/// +/// let the_slice = TheSlice { +/// slice: RCow::from("That's a lot of fish."), +/// }; +/// +/// let string = serde_json::to_string(&the_slice).unwrap(); +/// +/// let deserialized_slice = serde_json::from_str::>(&string).unwrap(); +/// +/// assert_eq!(the_slice, deserialized_slice); +/// +/// assert!(deserialized_slice.slice.is_borrowed()); +/// +/// ``` +/// pub fn deserialize_borrowed_str<'de, 'a, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, @@ -754,33 +736,29 @@ where } } -/** -A helper type, to deserialize an `RCow<'a, [u8]>` which borrows from the deserializer. - -# Example - -``` -use abi_stable::std_types::cow::{ - deserialize_borrowed_bytes, - BorrowingRCowU8Slice, -}; - - -let the_slice: Vec = vec![0, 1, 2, 3, 4, 5]; - -let vec = bincode::serialize(&the_slice).unwrap(); - -let deserialized_slice = bincode::deserialize::>(&vec).unwrap(); - -assert_eq!( &*deserialized_slice.cow, &*the_slice ); - -assert!( deserialized_slice.cow.is_borrowed() ); - - -``` - - -*/ +/// A helper type, to deserialize an `RCow<'a, [u8]>` which borrows from the deserializer. +/// +/// # Example +/// +/// ``` +/// use abi_stable::std_types::cow::{ +/// deserialize_borrowed_bytes, BorrowingRCowU8Slice, +/// }; +/// +/// let the_slice: Vec = vec![0, 1, 2, 3, 4, 5]; +/// +/// let vec = bincode::serialize(&the_slice).unwrap(); +/// +/// let deserialized_slice = +/// bincode::deserialize::>(&vec).unwrap(); +/// +/// assert_eq!(&*deserialized_slice.cow, &*the_slice); +/// +/// assert!(deserialized_slice.cow.is_borrowed()); +/// +/// +/// ``` +/// #[derive(Deserialize)] #[serde(transparent)] pub struct BorrowingRCowU8Slice<'a> { @@ -789,33 +767,28 @@ pub struct BorrowingRCowU8Slice<'a> { pub cow: RCow<'a, [u8]>, } -/** -A helper type, to deserialize a `RCow<'a, str>` which borrows from the deserializer. - -# Example - -Defining a type containing an `RCow<'a, str>` borrowing from the deserializer, -serializing it, and then deserializing it. - -``` -use abi_stable::std_types::cow::{ - deserialize_borrowed_str, - BorrowingRCowStr, -}; - - -let json = r##""W____ of S____""##; - -let deserialized_slice = serde_json::from_str::>(json).unwrap(); - -assert_eq!( &*deserialized_slice.cow, json.trim_matches('"') ); - -assert!( deserialized_slice.cow.is_borrowed() ); - -``` - - -*/ +/// A helper type, to deserialize a `RCow<'a, str>` which borrows from the deserializer. +/// +/// # Example +/// +/// Defining a type containing an `RCow<'a, str>` borrowing from the deserializer, +/// serializing it, and then deserializing it. +/// +/// ``` +/// use abi_stable::std_types::cow::{deserialize_borrowed_str, BorrowingRCowStr}; +/// +/// let json = r##""W____ of S____""##; +/// +/// let deserialized_slice = +/// serde_json::from_str::>(json).unwrap(); +/// +/// assert_eq!(&*deserialized_slice.cow, json.trim_matches('"')); +/// +/// assert!(deserialized_slice.cow.is_borrowed()); +/// +/// +/// ``` +/// #[derive(Deserialize)] #[serde(transparent)] pub struct BorrowingRCowStr<'a> { diff --git a/abi_stable/src/std_types/map.rs b/abi_stable/src/std_types/map.rs index 14e4a80d..8c3a1fdb 100644 --- a/abi_stable/src/std_types/map.rs +++ b/abi_stable/src/std_types/map.rs @@ -1,6 +1,4 @@ -/*! -Contains the ffi-safe equivalent of `std::collections::HashMap`, and related items. -*/ +//! Contains the ffi-safe equivalent of `std::collections::HashMap`, and related items. use std::{ borrow::Borrow, @@ -45,58 +43,55 @@ pub use self::{ iterator_stuff::{IntoIter, MutIterInterface, RefIterInterface, ValIterInterface}, }; -/** - -An ffi-safe hashmap, which wraps `std::collections::HashMap`, -only requiring the `K: Eq + Hash` bounds when constructing it. - -Most of the API in `HashMap` is implemented here, including the Entry API. - - -# Example - -This example demonstrates how one can use the RHashMap as a dictionary. - -``` -use abi_stable::std_types::{RHashMap, Tuple2, RString, RSome}; - -let mut map = RHashMap::new(); - -map.insert("dictionary", "A book/document containing definitions of words"); -map.insert("bibliophile", "Someone who loves books."); -map.insert("pictograph", "A picture representating of a word."); - -assert_eq!( - map["dictionary"], - "A book/document containing definitions of words", -); - -assert_eq!( - map.remove("bibliophile"), - RSome("Someone who loves books."), -); - -assert_eq!( - map.get("pictograph"), - Some(&"A picture representating of a word."), -); - -for Tuple2(k, v) in map { - assert!( k == "dictionary" || k == "pictograph" ); - - assert!( - v == "A book/document containing definitions of words" || - v == "A picture representating of a word.", - "{} => {}", - k, v - ); -} - - -``` - - -*/ +/// An ffi-safe hashmap, which wraps `std::collections::HashMap`, +/// only requiring the `K: Eq + Hash` bounds when constructing it. +/// +/// Most of the API in `HashMap` is implemented here, including the Entry API. +/// +/// +/// # Example +/// +/// This example demonstrates how one can use the RHashMap as a dictionary. +/// +/// ``` +/// use abi_stable::std_types::{RHashMap, RSome, RString, Tuple2}; +/// +/// let mut map = RHashMap::new(); +/// +/// map.insert( +/// "dictionary", +/// "A book/document containing definitions of words", +/// ); +/// map.insert("bibliophile", "Someone who loves books."); +/// map.insert("pictograph", "A picture representating of a word."); +/// +/// assert_eq!( +/// map["dictionary"], +/// "A book/document containing definitions of words", +/// ); +/// +/// assert_eq!(map.remove("bibliophile"), RSome("Someone who loves books."),); +/// +/// assert_eq!( +/// map.get("pictograph"), +/// Some(&"A picture representating of a word."), +/// ); +/// +/// for Tuple2(k, v) in map { +/// assert!(k == "dictionary" || k == "pictograph"); +/// +/// assert!( +/// v == "A book/document containing definitions of words" +/// || v == "A picture representating of a word.", +/// "{} => {}", +/// k, +/// v +/// ); +/// } +/// +/// +/// ``` +/// #[derive(StableAbi)] #[repr(C)] #[sabi( @@ -725,28 +720,27 @@ impl RHashMap { vtable.drain()(self.map.as_rmut()) } - /** - Gets a handle into the entry in the map for the key, - that allows operating directly on the entry. - - # Example - - ``` - use abi_stable::std_types::RHashMap; - - let mut map = RHashMap::::new(); - - // Inserting an entry that wasn't there before. - { - let mut entry = map.entry(0); - assert_eq!(entry.get(), None); - assert_eq!(entry.or_insert(3), &mut 3); - assert_eq!(map.get(&0), Some(&3)); - } - - - ``` - */ + /// Gets a handle into the entry in the map for the key, + /// that allows operating directly on the entry. + /// + /// # Example + /// + /// ``` + /// use abi_stable::std_types::RHashMap; + /// + /// let mut map = RHashMap::::new(); + /// + /// // Inserting an entry that wasn't there before. + /// { + /// let mut entry = map.entry(0); + /// assert_eq!(entry.get(), None); + /// assert_eq!(entry.or_insert(3), &mut 3); + /// assert_eq!(map.get(&0), Some(&3)); + /// } + /// + /// + /// ``` + /// pub fn entry(&mut self, key: K) -> REntry<'_, K, V> { let vtable = self.vtable(); diff --git a/abi_stable/src/std_types/map/iterator_stuff.rs b/abi_stable/src/std_types/map/iterator_stuff.rs index 377918b6..367d1273 100644 --- a/abi_stable/src/std_types/map/iterator_stuff.rs +++ b/abi_stable/src/std_types/map/iterator_stuff.rs @@ -70,12 +70,9 @@ pub struct IntoIter { } impl IntoIter { - /** - - # Safety - - This must be called only in `ErasedMap::into_val`. - */ + /// # Safety + /// + /// This must be called only in `ErasedMap::into_val`. pub(super) unsafe fn new<'a>(iter: DynTrait<'a, RBox<()>, ValIterInterface>) -> Self where K: 'a, diff --git a/abi_stable/src/std_types/option.rs b/abi_stable/src/std_types/option.rs index ed3df444..79671082 100644 --- a/abi_stable/src/std_types/option.rs +++ b/abi_stable/src/std_types/option.rs @@ -1,6 +1,4 @@ -/*! -Contains the ffi-safe equivalent of `std::option::Option`. -*/ +//! Contains the ffi-safe equivalent of `std::option::Option`. use std::mem; diff --git a/abi_stable/src/std_types/range.rs b/abi_stable/src/std_types/range.rs index 2078c10d..0a108ab8 100644 --- a/abi_stable/src/std_types/range.rs +++ b/abi_stable/src/std_types/range.rs @@ -1,6 +1,4 @@ -/*! -Contains the ffi-safe equivalent of `std::ops::Range*` types. -*/ +//! Contains the ffi-safe equivalent of `std::ops::Range*` types. use std::ops::{Range, RangeFrom, RangeInclusive, RangeTo, RangeToInclusive}; diff --git a/abi_stable/src/std_types/result.rs b/abi_stable/src/std_types/result.rs index 68f6e431..7996eb05 100644 --- a/abi_stable/src/std_types/result.rs +++ b/abi_stable/src/std_types/result.rs @@ -1,6 +1,4 @@ -/*! -Contains the ffi-safe equivalent of `std::result::Result`. -*/ +//! Contains the ffi-safe equivalent of `std::result::Result`. use std::fmt::Debug; diff --git a/abi_stable/src/std_types/slice_mut.rs b/abi_stable/src/std_types/slice_mut.rs index 7c211c4c..8b93612c 100644 --- a/abi_stable/src/std_types/slice_mut.rs +++ b/abi_stable/src/std_types/slice_mut.rs @@ -1,6 +1,4 @@ -/*! -Contains the ffi-safe equivalent of `&'a mut [T]`. -*/ +//! Contains the ffi-safe equivalent of `&'a mut [T]`. use std::{ borrow::{Borrow, BorrowMut}, @@ -20,78 +18,76 @@ use crate::std_types::{RSlice, RVec}; mod privacy { use super::*; - /** - Ffi-safe equivalent of `&'a mut [T]` - - As of the writing this documentation the abi stability of `&mut [T]` is - not yet guaranteed. - - # Lifetime problems - - Because `RSliceMut` dereferences into a mutable slice, you can call slice methods on it. - - If you call a slice method that returns a borrow into the slice, - it will have the lifetime of the `let slice: RSliceMut<'a, [T]>` variable instead of the `'a` - lifetime that it's parameterized over. - - To get a slice with the same lifetime as an `RSliceMut`, - one must use one of the `RSliceMut::{into_slice, into_mut_slice}` methods. - - - Example of what would not work: - - ```compile_fail - use abi_stable::std_types::RSliceMut; - - fn into_slice<'a, T>(slic: RSliceMut<'a, T>) -> &'a [T] { - &*slic - } - - fn into_mut_slice<'a, T>(slic: RSliceMut<'a, T>) -> &'a mut [T] { - &mut *slic - } - ``` - - Example of what would work: - - ``` - use abi_stable::std_types::RSliceMut; - - fn into_slice<'a, T>(slic: RSliceMut<'a, T>) -> &'a [T] { - slic.into_slice() - } - - fn into_mut_slice<'a, T>(slic: RSliceMut<'a, T>) -> &'a mut [T] { - slic.into_mut_slice() - } - ``` - - - # Example - - Defining an extern fn that returns a mutable reference to - the first element that compares equal to a parameter. - - ``` - use abi_stable::{ - std_types::RSliceMut, - sabi_extern_fn, - }; - - #[sabi_extern_fn] - pub fn find_first_mut<'a, T>(slice_: RSliceMut<'a, T>, element: &T) -> Option<&'a mut T> - where - T: std::cmp::PartialEq - { - slice_.iter() - .position(|x| x == element ) - .map(|i| &mut slice_.into_mut_slice()[i] ) - } - - - ``` - - */ + /// Ffi-safe equivalent of `&'a mut [T]` + /// + /// As of the writing this documentation the abi stability of `&mut [T]` is + /// not yet guaranteed. + /// + /// # Lifetime problems + /// + /// Because `RSliceMut` dereferences into a mutable slice, you can call slice methods on it. + /// + /// If you call a slice method that returns a borrow into the slice, + /// it will have the lifetime of the `let slice: RSliceMut<'a, [T]>` variable instead of the `'a` + /// lifetime that it's parameterized over. + /// + /// To get a slice with the same lifetime as an `RSliceMut`, + /// one must use one of the `RSliceMut::{into_slice, into_mut_slice}` methods. + /// + /// + /// Example of what would not work: + /// + /// ```compile_fail + /// use abi_stable::std_types::RSliceMut; + /// + /// fn into_slice<'a, T>(slic: RSliceMut<'a, T>) -> &'a [T] { + /// &*slic + /// } + /// + /// fn into_mut_slice<'a, T>(slic: RSliceMut<'a, T>) -> &'a mut [T] { + /// &mut *slic + /// } + /// ``` + /// + /// Example of what would work: + /// + /// ``` + /// use abi_stable::std_types::RSliceMut; + /// + /// fn into_slice<'a, T>(slic: RSliceMut<'a, T>) -> &'a [T] { + /// slic.into_slice() + /// } + /// + /// fn into_mut_slice<'a, T>(slic: RSliceMut<'a, T>) -> &'a mut [T] { + /// slic.into_mut_slice() + /// } + /// + /// ``` + /// + /// + /// # Example + /// + /// Defining an extern fn that returns a mutable reference to + /// the first element that compares equal to a parameter. + /// + /// ``` + /// use abi_stable::{sabi_extern_fn, std_types::RSliceMut}; + /// + /// #[sabi_extern_fn] + /// pub fn find_first_mut<'a, T>( + /// slice_: RSliceMut<'a, T>, + /// element: &T, + /// ) -> Option<&'a mut T> + /// where + /// T: std::cmp::PartialEq, + /// { + /// slice_ + /// .iter() + /// .position(|x| x == element) + /// .map(|i| &mut slice_.into_mut_slice()[i]) + /// } + /// ``` + /// #[repr(C)] #[derive(StableAbi)] #[sabi(bound = "T: 'a")] diff --git a/abi_stable/src/std_types/slices.rs b/abi_stable/src/std_types/slices.rs index 1dc36e06..328cc254 100644 --- a/abi_stable/src/std_types/slices.rs +++ b/abi_stable/src/std_types/slices.rs @@ -1,6 +1,4 @@ -/*! -Contains the ffi-safe equivalent of `&'a [T]`. -*/ +//! Contains the ffi-safe equivalent of `&'a [T]`. use std::{ borrow::Borrow, diff --git a/abi_stable/src/std_types/std_error.rs b/abi_stable/src/std_types/std_error.rs index be68b42a..c40ad517 100644 --- a/abi_stable/src/std_types/std_error.rs +++ b/abi_stable/src/std_types/std_error.rs @@ -28,162 +28,158 @@ use crate::{ // #[cfg(all(test, not(feature = "only_new_tests")))] mod test; -/** -Ffi-safe version of `Box` -whose `Send + Sync`ness is determined by the `M` type parameter. - -# Examples - -### Converting from and into `Box` - -``` -use std::{ - convert::TryFrom, - error::Error as ErrorTrait, -}; - -use abi_stable::std_types::{RBox, RBoxError, UnsyncRBoxError, SendRBoxError}; - -{ - let from: Box = "hello, error".into(); - let rbox = UnsyncRBoxError::from_box(from); - let _: Box = rbox.into_box(); -} - -{ - let arr_err=<[();0]>::try_from(&[()][..]).unwrap_err(); - let from: Box = Box::new(arr_err); - let rbox = SendRBoxError::from_box(from); - let _: Box = rbox.into_box(); -} - -{ - let arr_err=<[();0]>::try_from(&[()][..]).unwrap_err(); - let from: Box = Box::new(arr_err); - let rbox = RBoxError::from_box(from); - let _: Box = rbox.into_box(); -} - -``` - -### Downcasting by value - -``` -use std::num::{ParseFloatError, ParseIntError}; - -use abi_stable::std_types::{RBox, RBoxError}; - -// Constructing a `RBoxError` from a `Box`, then downcasting to a `ParseIntError`. -{ - let parse_err = "".parse::().unwrap_err(); - let dyn_err: Box = - Box::new(parse_err.clone()); - let err = RBoxError::from_box(dyn_err); - - assert_eq!( err.downcast::().unwrap(), RBox::new(parse_err) ); -} - -// Constructing a `RBoxError` from a `ParseFloatError`, then downcasting back to it. -{ - let parse_err = "".parse::().unwrap_err(); - let err = RBoxError::new(parse_err.clone()); - - assert_eq!( err.downcast::().unwrap(), RBox::new(parse_err) ); -} - -// Constructing a `RBoxError` from a `ParseFloatError`, -// then attempting to downcasting it to a `ParseIntError`. -{ - let parse_err = "".parse::().unwrap_err(); - let err = RBoxError::new(parse_err); - - assert!( err.downcast::().is_err() ); -} - -``` - -### Downcasting by reference - -``` -use std::{ - convert::TryFrom, - num::TryFromIntError, - str::Utf8Error, -}; - -use abi_stable::std_types::{RBox, UnsyncRBoxError}; - -// Constructing a `UnsyncRBoxError` from a `Box`, -// then downcasting to a `TryFromIntError`. -{ - let int_err = u32::try_from(-1_i32).unwrap_err(); - let dyn_err: Box = - Box::new(int_err.clone()); - let err = UnsyncRBoxError::from_box(dyn_err); - - assert_eq!( err.downcast_ref::().unwrap(), &int_err ); -} - -// Constructing a `UnsyncRBoxError` from a `Utf8Error`, then downcasting back to it. -{ - let utf8_err = std::str::from_utf8(&[255]).unwrap_err(); - let err = UnsyncRBoxError::new(utf8_err.clone()); - - assert_eq!( err.downcast_ref::().unwrap(), &utf8_err ); -} - -// Constructing a `UnsyncRBoxError` from a `Utf8Error`, -// then attempting to downcasting it to a `TryFromIntError`. -{ - let utf8_err = std::str::from_utf8(&[255]).unwrap_err(); - let err = UnsyncRBoxError::new(utf8_err); - - assert!( err.downcast_ref::().is_none() ); -} - -``` - - -### Downcasting by mutable reference - -``` -use std::string::{FromUtf8Error, FromUtf16Error}; - -use abi_stable::std_types::{RBox, SendRBoxError}; - -// Constructing a `SendRBoxError` from a `Box`, -// then downcasting to a `FromUtf8Error`. -{ - let str_err = || String::from_utf8(vec![255]).unwrap_err() ; - let dyn_err: Box = - Box::new(str_err()); - let mut err = SendRBoxError::from_box(dyn_err); - - assert!( err.downcast_ref::().is_some() , "part A"); -} - -// Constructing a `SendRBoxError` from a `FromUtf8Error`, then downcasting back to it. -{ - let str_err = || String::from_utf8(vec![255]).unwrap_err() ; - let mut err = SendRBoxError::new(str_err()); - - assert!( err.downcast_ref::().is_some() , "part B"); -} - -// Constructing a `SendRBoxError` from a `FromUtf16Error`, -// then attempting to downcasting it to a `FromUtf8Error`. -{ - let str_err = || String::from_utf16(&[0xD834]).unwrap_err() ; - let mut err = SendRBoxError::new(str_err()); - - assert!( err.downcast_ref::().is_none() , "part C"); -} - -``` - - - -*/ +/// Ffi-safe version of `Box` +/// whose `Send + Sync`ness is determined by the `M` type parameter. +/// +/// # Examples +/// +/// ### Converting from and into `Box` +/// +/// ``` +/// use std::{convert::TryFrom, error::Error as ErrorTrait}; +/// +/// use abi_stable::std_types::{RBox, RBoxError, SendRBoxError, UnsyncRBoxError}; +/// +/// { +/// let from: Box = "hello, error".into(); +/// let rbox = UnsyncRBoxError::from_box(from); +/// let _: Box = rbox.into_box(); +/// } +/// +/// { +/// let arr_err = <[(); 0]>::try_from(&[()][..]).unwrap_err(); +/// let from: Box = Box::new(arr_err); +/// let rbox = SendRBoxError::from_box(from); +/// let _: Box = rbox.into_box(); +/// } +/// +/// { +/// let arr_err = <[(); 0]>::try_from(&[()][..]).unwrap_err(); +/// let from: Box = Box::new(arr_err); +/// let rbox = RBoxError::from_box(from); +/// let _: Box = rbox.into_box(); +/// } +/// +/// +/// ``` +/// +/// ### Downcasting by value +/// +/// ``` +/// use std::num::{ParseFloatError, ParseIntError}; +/// +/// use abi_stable::std_types::{RBox, RBoxError}; +/// +/// // Constructing a `RBoxError` from a `Box`, then downcasting to a `ParseIntError`. +/// { +/// let parse_err = "".parse::().unwrap_err(); +/// let dyn_err: Box = +/// Box::new(parse_err.clone()); +/// let err = RBoxError::from_box(dyn_err); +/// +/// assert_eq!( +/// err.downcast::().unwrap(), +/// RBox::new(parse_err) +/// ); +/// } +/// +/// // Constructing a `RBoxError` from a `ParseFloatError`, then downcasting back to it. +/// { +/// let parse_err = "".parse::().unwrap_err(); +/// let err = RBoxError::new(parse_err.clone()); +/// +/// assert_eq!( +/// err.downcast::().unwrap(), +/// RBox::new(parse_err) +/// ); +/// } +/// +/// // Constructing a `RBoxError` from a `ParseFloatError`, +/// // then attempting to downcasting it to a `ParseIntError`. +/// { +/// let parse_err = "".parse::().unwrap_err(); +/// let err = RBoxError::new(parse_err); +/// +/// assert!(err.downcast::().is_err()); +/// } +/// +/// ``` +/// +/// ### Downcasting by reference +/// +/// ``` +/// use std::{convert::TryFrom, num::TryFromIntError, str::Utf8Error}; +/// +/// use abi_stable::std_types::{RBox, UnsyncRBoxError}; +/// +/// // Constructing a `UnsyncRBoxError` from a `Box`, +/// // then downcasting to a `TryFromIntError`. +/// { +/// let int_err = u32::try_from(-1_i32).unwrap_err(); +/// let dyn_err: Box = Box::new(int_err.clone()); +/// let err = UnsyncRBoxError::from_box(dyn_err); +/// +/// assert_eq!(err.downcast_ref::().unwrap(), &int_err); +/// } +/// +/// // Constructing a `UnsyncRBoxError` from a `Utf8Error`, then downcasting back to it. +/// { +/// let utf8_err = std::str::from_utf8(&[255]).unwrap_err(); +/// let err = UnsyncRBoxError::new(utf8_err.clone()); +/// +/// assert_eq!(err.downcast_ref::().unwrap(), &utf8_err); +/// } +/// +/// // Constructing a `UnsyncRBoxError` from a `Utf8Error`, +/// // then attempting to downcasting it to a `TryFromIntError`. +/// { +/// let utf8_err = std::str::from_utf8(&[255]).unwrap_err(); +/// let err = UnsyncRBoxError::new(utf8_err); +/// +/// assert!(err.downcast_ref::().is_none()); +/// } +/// +/// ``` +/// +/// +/// ### Downcasting by mutable reference +/// +/// ``` +/// use std::string::{FromUtf16Error, FromUtf8Error}; +/// +/// use abi_stable::std_types::{RBox, SendRBoxError}; +/// +/// // Constructing a `SendRBoxError` from a `Box`, +/// // then downcasting to a `FromUtf8Error`. +/// { +/// let str_err = || String::from_utf8(vec![255]).unwrap_err(); +/// let dyn_err: Box = Box::new(str_err()); +/// let mut err = SendRBoxError::from_box(dyn_err); +/// +/// assert!(err.downcast_ref::().is_some(), "part A"); +/// } +/// +/// // Constructing a `SendRBoxError` from a `FromUtf8Error`, then downcasting back to it. +/// { +/// let str_err = || String::from_utf8(vec![255]).unwrap_err(); +/// let mut err = SendRBoxError::new(str_err()); +/// +/// assert!(err.downcast_ref::().is_some(), "part B"); +/// } +/// +/// // Constructing a `SendRBoxError` from a `FromUtf16Error`, +/// // then attempting to downcasting it to a `FromUtf8Error`. +/// { +/// let str_err = || String::from_utf16(&[0xD834]).unwrap_err(); +/// let mut err = SendRBoxError::new(str_err()); +/// +/// assert!(err.downcast_ref::().is_none(), "part C"); +/// } +/// +/// ``` +/// +/// +/// #[repr(C)] #[derive(StableAbi)] pub struct RBoxError_ { diff --git a/abi_stable/src/std_types/std_io.rs b/abi_stable/src/std_types/std_io.rs index 4573c34d..3db3f8f8 100644 --- a/abi_stable/src/std_types/std_io.rs +++ b/abi_stable/src/std_types/std_io.rs @@ -1,6 +1,4 @@ -/*! -Ffi-safe equivalents of `std::io::{ErrorKind, Error, SeekFrom}`. -*/ +//! Ffi-safe equivalents of `std::io::{ErrorKind, Error, SeekFrom}`. use std::{ error::Error as ErrorTrait, @@ -155,40 +153,35 @@ impl_into_rust_repr! { /////////////////////////////////////////////////////////////////////////// -/** -Ffi safe equivalent to `std::io::Error`. - -# Example - -Defining an extern function to write a slice into a writer twice. - -``` -use abi_stable::{ - erased_types::interfaces::IoWriteInterface, - std_types::{RIoError, RResult, ROk}, - traits::IntoReprC, - DynTrait, RMut, - sabi_extern_fn, - rtry, -}; - -use std::io::Write; - -#[sabi_extern_fn] -pub fn write_slice_twice( - mut write: DynTrait, IoWriteInterface>, - slice: &[u8], -) -> RResult<(), RIoError>{ - rtry!( write.write_all(slice).into_c() ); - rtry!( write.write_all(slice).into_c() ); - ROk(()) -} - - - -``` - -*/ +/// Ffi safe equivalent to `std::io::Error`. +/// +/// # Example +/// +/// Defining an extern function to write a slice into a writer twice. +/// +/// ``` +/// use abi_stable::{ +/// erased_types::interfaces::IoWriteInterface, +/// rtry, sabi_extern_fn, +/// std_types::{RIoError, ROk, RResult}, +/// traits::IntoReprC, +/// DynTrait, RMut, +/// }; +/// +/// use std::io::Write; +/// +/// #[sabi_extern_fn] +/// pub fn write_slice_twice( +/// mut write: DynTrait, IoWriteInterface>, +/// slice: &[u8], +/// ) -> RResult<(), RIoError> { +/// rtry!(write.write_all(slice).into_c()); +/// rtry!(write.write_all(slice).into_c()); +/// ROk(()) +/// } +/// +/// ``` +/// #[repr(C)] #[derive(StableAbi)] pub struct RIoError { diff --git a/abi_stable/src/std_types/str.rs b/abi_stable/src/std_types/str.rs index 04f160c6..8aa5c445 100644 --- a/abi_stable/src/std_types/str.rs +++ b/abi_stable/src/std_types/str.rs @@ -1,6 +1,4 @@ -/*! -Contains an ffi-safe equivalent of `&'a str`. -*/ +//! Contains an ffi-safe equivalent of `&'a str`. use std::{ borrow::{Borrow, Cow}, @@ -16,31 +14,25 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer}; use crate::std_types::{RSlice, RString}; -/** -Ffi-safe equivalent of `&'a str` - -# Example - -This defines a function that returns the first word in a string. - -``` -use abi_stable::{ - std_types::RStr, - sabi_extern_fn, -}; - - -#[sabi_extern_fn] -fn first_word(phrase: RStr<'_>) -> RStr<'_>{ - match phrase.as_str().split_whitespace().next() { - Some(x) => x.into(), - None => "".into() - } -} - -``` - -*/ +/// Ffi-safe equivalent of `&'a str` +/// +/// # Example +/// +/// This defines a function that returns the first word in a string. +/// +/// ``` +/// use abi_stable::{sabi_extern_fn, std_types::RStr}; +/// +/// #[sabi_extern_fn] +/// fn first_word(phrase: RStr<'_>) -> RStr<'_> { +/// match phrase.as_str().split_whitespace().next() { +/// Some(x) => x.into(), +/// None => "".into(), +/// } +/// } +/// +/// +/// ``` #[repr(C)] #[derive(Copy, Clone, StableAbi)] pub struct RStr<'a> { diff --git a/abi_stable/src/std_types/string.rs b/abi_stable/src/std_types/string.rs index afd8f585..19418515 100644 --- a/abi_stable/src/std_types/string.rs +++ b/abi_stable/src/std_types/string.rs @@ -1,6 +1,4 @@ -/*! -Contains an ffi-safe equivalent of `std::string::String`. -*/ +//! Contains an ffi-safe equivalent of `std::string::String`. use std::{ borrow::{Borrow, Cow}, @@ -28,31 +26,26 @@ mod tests; pub use self::iters::{Drain, IntoIter}; -/** -Ffi-safe equivalent of `std::string::String`. - -# Example - -This defines a function returning the last word of an `RString`. - -``` -use abi_stable::{ - std_types::RString, - sabi_extern_fn, -}; - - -#[sabi_extern_fn] -fn first_word(phrase: RString) -> RString{ - match phrase.split_whitespace().next_back() { - Some(x) => x.into(), - None => RString::new(), - } -} - -``` - -*/ +/// Ffi-safe equivalent of `std::string::String`. +/// +/// # Example +/// +/// This defines a function returning the last word of an `RString`. +/// +/// ``` +/// use abi_stable::{sabi_extern_fn, std_types::RString}; +/// +/// #[sabi_extern_fn] +/// fn first_word(phrase: RString) -> RString { +/// match phrase.split_whitespace().next_back() { +/// Some(x) => x.into(), +/// None => RString::new(), +/// } +/// } +/// +/// +/// ``` +/// #[derive(Clone)] #[repr(C)] #[derive(StableAbi)] @@ -830,58 +823,43 @@ impl Serialize for RString { ////////////////////////////////////////////////////// impl RString { - /** - Creates an iterator that yields the chars in the `range`, - removing the characters in that range in the process. - - # Panic - - Panics if the start or end of the range are not on a on a char boundary, - or if either are out of bounds. - - # Example - - ``` - use abi_stable::std_types::RString; - - let orig = "Not a single way"; - - { - let mut str = RString::from(orig); - assert_eq!( - str.drain(..).collect::(), - orig, - ); - assert_eq!(str.as_str(), ""); - } - { - let mut str = RString::from(orig); - assert_eq!( - str.drain(..4).collect::(), - "Not ", - ); - assert_eq!(str.as_str(), "a single way"); - } - { - let mut str = RString::from(orig); - assert_eq!( - str.drain(4..).collect::(), - "a single way", - ); - assert_eq!(str.as_str(), "Not "); - } - { - let mut str = RString::from(orig); - assert_eq!( - str.drain(4..13).collect::(), - "a single ", - ); - assert_eq!(str.as_str(), "Not way"); - } - - ``` - - */ + /// Creates an iterator that yields the chars in the `range`, + /// removing the characters in that range in the process. + /// + /// # Panic + /// + /// Panics if the start or end of the range are not on a on a char boundary, + /// or if either are out of bounds. + /// + /// # Example + /// + /// ``` + /// use abi_stable::std_types::RString; + /// + /// let orig = "Not a single way"; + /// + /// { + /// let mut str = RString::from(orig); + /// assert_eq!(str.drain(..).collect::(), orig,); + /// assert_eq!(str.as_str(), ""); + /// } + /// { + /// let mut str = RString::from(orig); + /// assert_eq!(str.drain(..4).collect::(), "Not ",); + /// assert_eq!(str.as_str(), "a single way"); + /// } + /// { + /// let mut str = RString::from(orig); + /// assert_eq!(str.drain(4..).collect::(), "a single way",); + /// assert_eq!(str.as_str(), "Not "); + /// } + /// { + /// let mut str = RString::from(orig); + /// assert_eq!(str.drain(4..13).collect::(), "a single ",); + /// assert_eq!(str.as_str(), "Not way"); + /// } + /// + /// ``` pub fn drain(&mut self, range: I) -> Drain<'_> where str: Index, diff --git a/abi_stable/src/std_types/time.rs b/abi_stable/src/std_types/time.rs index 1d3886a7..6f0cc225 100644 --- a/abi_stable/src/std_types/time.rs +++ b/abi_stable/src/std_types/time.rs @@ -1,6 +1,4 @@ -/*! -Contains ffi-safe equivalent of `std::time::Duration`. -*/ +//! Contains ffi-safe equivalent of `std::time::Duration`. use std::time::Duration; diff --git a/abi_stable/src/std_types/tuple.rs b/abi_stable/src/std_types/tuple.rs index 0dbde415..e47f2006 100644 --- a/abi_stable/src/std_types/tuple.rs +++ b/abi_stable/src/std_types/tuple.rs @@ -1,6 +1,4 @@ -/*! -Contains ffi-safe equivalents of tuples up to 4 elements. -*/ +//! Contains ffi-safe equivalents of tuples up to 4 elements. #![allow(non_snake_case)] diff --git a/abi_stable/src/std_types/utypeid.rs b/abi_stable/src/std_types/utypeid.rs index fee1a593..36a9a3fc 100644 --- a/abi_stable/src/std_types/utypeid.rs +++ b/abi_stable/src/std_types/utypeid.rs @@ -1,8 +1,6 @@ -/*! -An ffi-safe equivalent of `std::any::TypeId`. - -No types coming from different dynamic libraries compare equal. -*/ +//! An ffi-safe equivalent of `std::any::TypeId`. +//! +//! No types coming from different dynamic libraries compare equal. use std::{ any::TypeId, diff --git a/abi_stable/src/std_types/vec.rs b/abi_stable/src/std_types/vec.rs index 2d15f585..d4f9fdef 100644 --- a/abi_stable/src/std_types/vec.rs +++ b/abi_stable/src/std_types/vec.rs @@ -1,6 +1,4 @@ -/*! -Contains an ffi-safe equivalent of `Vec`. -*/ +//! Contains an ffi-safe equivalent of `Vec`. use std::{ borrow::{Borrow, BorrowMut, Cow}, @@ -39,38 +37,36 @@ pub use self::iters::{Drain, IntoIter}; mod private { use super::*; - /** - Ffi-safe equivalent of `std::vec::Vec`. - - # Example - - Here is a function that partitions numbers by whether they are even or odd. - - ``` - - use abi_stable::{ - std_types::{RSlice, RVec}, - StableAbi, - sabi_extern_fn, - }; - - #[repr(C)] - #[derive(StableAbi)] - pub struct Partitioned{ - pub even: RVec, - pub odd : RVec, - } - - #[sabi_extern_fn] - pub fn partition_evenness(numbers: RSlice<'_, u32>) -> Partitioned{ - let (even, odd) = numbers.iter().cloned().partition(|n| *n % 2 == 0); - - Partitioned{even, odd} - } - - ``` - - */ + /// Ffi-safe equivalent of `std::vec::Vec`. + /// + /// # Example + /// + /// Here is a function that partitions numbers by whether they are even or odd. + /// + /// ``` + /// + /// use abi_stable::{ + /// sabi_extern_fn, + /// std_types::{RSlice, RVec}, + /// StableAbi, + /// }; + /// + /// #[repr(C)] + /// #[derive(StableAbi)] + /// pub struct Partitioned { + /// pub even: RVec, + /// pub odd: RVec, + /// } + /// + /// #[sabi_extern_fn] + /// pub fn partition_evenness(numbers: RSlice<'_, u32>) -> Partitioned { + /// let (even, odd) = numbers.iter().cloned().partition(|n| *n % 2 == 0); + /// + /// Partitioned { even, odd } + /// } + /// + /// ``` + /// #[repr(C)] #[derive(StableAbi)] // #[sabi(debug_print)] @@ -1145,50 +1141,49 @@ where ///////////////////////////////////////////////////////////////////////////////////// impl RVec { - /** - Creates a draining iterator that removes the specified range in - the `RVec` and yields the removed items. - - # Panic - - Panics if the index is out of bounds or if the start of the range is - greater than the end of the range. - - # Consumption - - The elements in the range will be removed even if the iterator - was dropped before yielding them. - - # Example - - ``` - use abi_stable::std_types::{RSlice, RVec}; - - { - let mut list = RVec::from(vec![0, 1, 2, 3, 4, 5]); - assert_eq!( list.drain(2..4).collect::>(), vec![2, 3] ); - assert_eq!( list.as_slice(), &[0, 1, 4, 5] ); - } - { - let mut list = RVec::from(vec![0, 1, 2, 3, 4, 5]); - assert_eq!( list.drain(2..).collect::>(), vec![2, 3, 4, 5] ); - assert_eq!( list.as_slice(), &[0, 1] ); - } - { - let mut list = RVec::from(vec![0, 1, 2, 3, 4, 5]); - assert_eq!( list.drain(..2).collect::>(), vec![0, 1] ); - assert_eq!( list.as_slice(), &[2, 3, 4, 5] ); - } - { - let mut list = RVec::from(vec![0, 1, 2, 3, 4, 5]); - assert_eq!( list.drain(..).collect::>(), vec![0, 1, 2, 3, 4, 5] ); - assert_eq!( list.as_rslice(), RSlice::::EMPTY ); - } - - ``` - - - */ + /// Creates a draining iterator that removes the specified range in + /// the `RVec` and yields the removed items. + /// + /// # Panic + /// + /// Panics if the index is out of bounds or if the start of the range is + /// greater than the end of the range. + /// + /// # Consumption + /// + /// The elements in the range will be removed even if the iterator + /// was dropped before yielding them. + /// + /// # Example + /// + /// ``` + /// use abi_stable::std_types::{RSlice, RVec}; + /// + /// { + /// let mut list = RVec::from(vec![0, 1, 2, 3, 4, 5]); + /// assert_eq!(list.drain(2..4).collect::>(), vec![2, 3]); + /// assert_eq!(list.as_slice(), &[0, 1, 4, 5]); + /// } + /// { + /// let mut list = RVec::from(vec![0, 1, 2, 3, 4, 5]); + /// assert_eq!(list.drain(2..).collect::>(), vec![2, 3, 4, 5]); + /// assert_eq!(list.as_slice(), &[0, 1]); + /// } + /// { + /// let mut list = RVec::from(vec![0, 1, 2, 3, 4, 5]); + /// assert_eq!(list.drain(..2).collect::>(), vec![0, 1]); + /// assert_eq!(list.as_slice(), &[2, 3, 4, 5]); + /// } + /// { + /// let mut list = RVec::from(vec![0, 1, 2, 3, 4, 5]); + /// assert_eq!(list.drain(..).collect::>(), vec![0, 1, 2, 3, 4, 5]); + /// assert_eq!(list.as_rslice(), RSlice::::EMPTY); + /// } + /// + /// + /// ``` + /// + /// pub fn drain(&mut self, index: I) -> Drain<'_, T> where [T]: IndexMut, diff --git a/abi_stable/src/traits.rs b/abi_stable/src/traits.rs index db26076d..7167a6ad 100644 --- a/abi_stable/src/traits.rs +++ b/abi_stable/src/traits.rs @@ -1,6 +1,4 @@ -/*! -Where miscellaneous traits reside. -*/ +//! Where miscellaneous traits reside. #[allow(unused_imports)] use core_extensions::SelfOps; diff --git a/abi_stable/src/type_layout.rs b/abi_stable/src/type_layout.rs index ed983deb..224b2db0 100644 --- a/abi_stable/src/type_layout.rs +++ b/abi_stable/src/type_layout.rs @@ -1,6 +1,4 @@ -/*! -Types for modeling the layout of a datatype -*/ +//! Types for modeling the layout of a datatype use std::{ cell::RefCell, @@ -205,24 +203,22 @@ impl TypeLayout { self.extra_checks.value.map(|x| x.sabi_reborrow()) } - /** - Gets the fields of the type. - - # Return value - - If this a: - - - primitive or opaque type: - It returns `None`. - - - enum: - It returns `Some()` with all the fields in the order that they were declared, - ignoring variants. - - - structs/unions/prefix types: - It returns `Some()` with all the fields in the order that they were declared. - - */ + /// Gets the fields of the type. + /// + /// # Return value + /// + /// If this a: + /// + /// - primitive or opaque type: + /// It returns `None`. + /// + /// - enum: + /// It returns `Some()` with all the fields in the order that they were declared, + /// ignoring variants. + /// + /// - structs/unions/prefix types: + /// It returns `Some()` with all the fields in the order that they were declared. + /// pub fn get_fields(&self) -> Option { let fields = self.mono.get_fields()?; Some(fields.expand(self.shared_vars)) @@ -478,24 +474,22 @@ impl MonoTypeLayout { &self.shared_vars } - /** - Gets the compressed versions of the fields of the type. - - # Return value - - If this a: - - - primitive or opaque type: - It returns `None`. - - - enum: - It returns `Some()` with all the fields in the order that they were declared, - ignoring variants. - - - structs/unions/prefix types: - It returns `Some()` with all the fields in the order that they were declared. - - */ + /// Gets the compressed versions of the fields of the type. + /// + /// # Return value + /// + /// If this a: + /// + /// - primitive or opaque type: + /// It returns `None`. + /// + /// - enum: + /// It returns `Some()` with all the fields in the order that they were declared, + /// ignoring variants. + /// + /// - structs/unions/prefix types: + /// It returns `Some()` with all the fields in the order that they were declared. + /// pub fn get_fields(&self) -> Option { match self.data { MonoTLData::Primitive { .. } => None, diff --git a/abi_stable/src/type_layout/printing.rs b/abi_stable/src/type_layout/printing.rs index b87984f0..79eb97eb 100644 --- a/abi_stable/src/type_layout/printing.rs +++ b/abi_stable/src/type_layout/printing.rs @@ -10,11 +10,9 @@ use core_extensions::SelfOps; #[cfg(test)] mod tests; -/** -A function which recursively traverses a type layout, -calling `callback` for every `TypeLayout` it goes over. - -*/ +/// A function which recursively traverses a type layout, +/// calling `callback` for every `TypeLayout` it goes over. +/// fn traverse_type_layouts<'a, F>(layout: &'a TypeLayout, mut callback: F) where F: FnMut(&'a TypeLayout), diff --git a/abi_stable/src/type_layout/tl_enums.rs b/abi_stable/src/type_layout/tl_enums.rs index d055447f..521b37f8 100644 --- a/abi_stable/src/type_layout/tl_enums.rs +++ b/abi_stable/src/type_layout/tl_enums.rs @@ -514,10 +514,8 @@ impl MakeTLNonExhaustive { //////////////////////////// -/** -An error declaring that the Storage of a nonexhaustive enum is -not compatible with the enum. -*/ +/// An error declaring that the Storage of a nonexhaustive enum is +/// not compatible with the enum. #[repr(C)] #[derive(Debug, Clone, PartialEq, Eq, StableAbi)] #[sabi(unsafe_sabi_opaque_fields)] @@ -553,9 +551,7 @@ impl std::error::Error for IncompatibleWithNonExhaustive {} ///////////////////////////////////////////////////////////////////////////// -/** -An iterator that yields the names of an enum's variants. -*/ +/// An iterator that yields the names of an enum's variants. #[derive(Debug, Clone)] struct GetVariantNames { split: std::str::Split<'static, char>, diff --git a/abi_stable/src/type_layout/tl_fields.rs b/abi_stable/src/type_layout/tl_fields.rs index a39c0d98..69c4dadb 100644 --- a/abi_stable/src/type_layout/tl_fields.rs +++ b/abi_stable/src/type_layout/tl_fields.rs @@ -193,9 +193,7 @@ impl PartialEq for TLFields { /////////////////////////////////////////////////////////////////////////////// -/** -An iterator over all the fields in a type definition. -*/ +/// An iterator over all the fields in a type definition. #[derive(Clone, Debug)] pub struct TLFieldsIterator { shared_vars: &'static SharedVars, diff --git a/abi_stable/src/type_layout/tl_functions.rs b/abi_stable/src/type_layout/tl_functions.rs index 94fdc547..f71d524c 100644 --- a/abi_stable/src/type_layout/tl_functions.rs +++ b/abi_stable/src/type_layout/tl_functions.rs @@ -82,9 +82,7 @@ impl TLFunctions { /////////////////////////////////////////////////////////////////////////////// -/** -A slice of functions from a `TLFunctions`. -*/ +/// A slice of functions from a `TLFunctions`. #[repr(C)] #[derive(Copy, Clone, StableAbi)] #[sabi(unsafe_sabi_opaque_fields)] diff --git a/abi_stable/src/type_layout/tl_other.rs b/abi_stable/src/type_layout/tl_other.rs index 0040c468..9b74277f 100644 --- a/abi_stable/src/type_layout/tl_other.rs +++ b/abi_stable/src/type_layout/tl_other.rs @@ -35,9 +35,7 @@ pub enum ReprAttr { ///////////////////////////////////////////////////// -/** -A module path. -*/ +/// A module path. #[repr(transparent)] #[derive(Debug, Copy, Clone, Eq, PartialEq, StableAbi)] #[sabi(unsafe_sabi_opaque_fields)] @@ -227,9 +225,7 @@ impl FmtFullType { //////////////////////////////////// -/** -Either a TLField or a TLFunction. -*/ +/// Either a TLField or a TLFunction. #[repr(u8)] #[derive(Copy, Clone, Debug, Eq, PartialEq, StableAbi)] #[sabi(unsafe_sabi_opaque_fields)] diff --git a/abi_stable/src/type_level.rs b/abi_stable/src/type_level.rs index 3c96314c..d984f09f 100644 --- a/abi_stable/src/type_level.rs +++ b/abi_stable/src/type_level.rs @@ -1,12 +1,10 @@ //! Types used to represent values at compile-time, eg: True/False. -/** -Type-level booleans. - -This is a re-export from `core_extensions::type_level_bool`, -so as to allow glob imports (`abi_stable::type_level::bools::*`) -without worrying about importing too many items. -*/ +/// Type-level booleans. +/// +/// This is a re-export from `core_extensions::type_level_bool`, +/// so as to allow glob imports (`abi_stable::type_level::bools::*`) +/// without worrying about importing too many items. pub mod bools { #[doc(no_inline)] pub use core_extensions::type_level_bool::{Boolean, False, True}; diff --git a/abi_stable/src/utils.rs b/abi_stable/src/utils.rs index 882f1d19..5776924c 100644 --- a/abi_stable/src/utils.rs +++ b/abi_stable/src/utils.rs @@ -1,6 +1,4 @@ -/*! -Utility functions. -*/ +//! Utility functions. use std::{ cmp::Ord, diff --git a/abi_stable_derive/src/composite_collections.rs b/abi_stable_derive/src/composite_collections.rs index 274ad015..890ef78c 100644 --- a/abi_stable_derive/src/composite_collections.rs +++ b/abi_stable_derive/src/composite_collections.rs @@ -1,10 +1,7 @@ -/*! -Helper types for constructing strings and arrays composed of other strings and arrays. - -These datatypes are special-cased for small composite collections , -whose indices fit in a u16. - -*/ +//! Helper types for constructing strings and arrays composed of other strings and arrays. +//! +//! These datatypes are special-cased for small composite collections , +//! whose indices fit in a u16. use std::{ borrow::Borrow, diff --git a/abi_stable_derive/src/export_root_module_impl.rs b/abi_stable_derive/src/export_root_module_impl.rs index f4c555a7..c46aeabf 100644 --- a/abi_stable_derive/src/export_root_module_impl.rs +++ b/abi_stable_derive/src/export_root_module_impl.rs @@ -1,6 +1,4 @@ -/*! -The implementation of the `#[export_root_module]` attribute. -*/ +//! The implementation of the `#[export_root_module]` attribute. use super::*; diff --git a/abi_stable_derive/src/fn_pointer_extractor.rs b/abi_stable_derive/src/fn_pointer_extractor.rs index b3f168f1..03e60dd9 100644 --- a/abi_stable_derive/src/fn_pointer_extractor.rs +++ b/abi_stable_derive/src/fn_pointer_extractor.rs @@ -1,7 +1,5 @@ -/*! -Contains visitor type for -extracting function pointers and the referenced lifetimes of the fields of a type declaration. -*/ +//! Contains visitor type for +//! extracting function pointers and the referenced lifetimes of the fields of a type declaration. use std::{collections::HashSet, mem}; @@ -420,14 +418,12 @@ impl<'a> VisitMut for TypeVisitor<'a> { ///////////// impl<'a, 'b> FnVisitor<'a, 'b> { - /** - This function does these things: - - - Adds the lifetime as a referenced lifetime. - - - If `lt` is `Some('someident)` returns `Some('_)`. - - */ + /// This function does these things: + /// + /// - Adds the lifetime as a referenced lifetime. + /// + /// - If `lt` is `Some('someident)` returns `Some('_)`. + /// #[inline(never)] fn setup_lifetime(&mut self, lt: Option<&Ident>, span: Span) -> Option<&'a Ident> { let ctokens = self.refs.ctokens; diff --git a/abi_stable_derive/src/get_static_equivalent.rs b/abi_stable_derive/src/get_static_equivalent.rs index 92cd547a..a82a3c66 100644 --- a/abi_stable_derive/src/get_static_equivalent.rs +++ b/abi_stable_derive/src/get_static_equivalent.rs @@ -1,6 +1,4 @@ -/*! -Stuff related to the `GetStaticEquivalent` derive macro. -*/ +//! Stuff related to the `GetStaticEquivalent` derive macro. use proc_macro2::{Span, TokenStream as TokenStream2}; diff --git a/abi_stable_derive/src/get_static_equivalent/attribute_parsing.rs b/abi_stable_derive/src/get_static_equivalent/attribute_parsing.rs index 62fd913f..d7252b56 100644 --- a/abi_stable_derive/src/get_static_equivalent/attribute_parsing.rs +++ b/abi_stable_derive/src/get_static_equivalent/attribute_parsing.rs @@ -1,6 +1,4 @@ -/*! -For parsing the helper attributess for `#[derive(GetStaticEquivalent)]`. -*/ +//! For parsing the helper attributess for `#[derive(GetStaticEquivalent)]`. use std::marker::PhantomData; diff --git a/abi_stable_derive/src/ignored_wrapper.rs b/abi_stable_derive/src/ignored_wrapper.rs index bdce01dd..fe6ecf75 100644 --- a/abi_stable_derive/src/ignored_wrapper.rs +++ b/abi_stable_derive/src/ignored_wrapper.rs @@ -1,6 +1,4 @@ -/*! -Wrapper type(s) where their value is ignored in comparisons . -*/ +//! Wrapper type(s) where their value is ignored in comparisons . use std::{ cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}, diff --git a/abi_stable_derive/src/impl_interfacetype.rs b/abi_stable_derive/src/impl_interfacetype.rs index d32e0b06..4f7ff40c 100644 --- a/abi_stable_derive/src/impl_interfacetype.rs +++ b/abi_stable_derive/src/impl_interfacetype.rs @@ -1,7 +1,5 @@ -/*! -The implementation of both the `#[sabi(impl_InterfaceType())]` helper attributes, -and the `impl_InterfaceType!{}` macro. -*/ +//! The implementation of both the `#[sabi(impl_InterfaceType())]` helper attributes, +//! and the `impl_InterfaceType!{}` macro. use std::collections::HashMap; diff --git a/abi_stable_derive/src/lib.rs b/abi_stable_derive/src/lib.rs index f8069edf..3079c3f3 100644 --- a/abi_stable_derive/src/lib.rs +++ b/abi_stable_derive/src/lib.rs @@ -1,6 +1,4 @@ -/*! -An implementation detail of abi_stable. -*/ +//! An implementation detail of abi_stable. #![recursion_limit = "192"] // #![deny(unused_variables)] @@ -15,29 +13,20 @@ An implementation detail of abi_stable. extern crate proc_macro; -/** - - -This macro is documented in abi_stable::docs::stable_abi_derive - -*/ - +/// This macro is documented in abi_stable::docs::stable_abi_derive #[proc_macro_derive(StableAbi, attributes(sabi))] pub fn derive_stable_abi(input: TokenStream1) -> TokenStream1 { parse_or_compile_err(input, stable_abi::derive).into() } -/** - -Allows implementing the InterfaceType trait, -providing default values for associated types not specified in the impl block. - - -This macro has been deprecated in favor of using the `#[sabi(impl_InterfaceType())]` -helper attribute of both `#[derive(StableAbi)]` and `#[derive(GetStaticEquivalent)]` - - -*/ +/// Allows implementing the InterfaceType trait, +/// providing default values for associated types not specified in the impl block. +/// +/// +/// This macro has been deprecated in favor of using the `#[sabi(impl_InterfaceType())]` +/// helper attribute of both `#[derive(StableAbi)]` and `#[derive(GetStaticEquivalent)]` +/// +/// #[doc(hidden)] #[proc_macro] #[allow(non_snake_case)] diff --git a/abi_stable_derive/src/my_visibility.rs b/abi_stable_derive/src/my_visibility.rs index 4b3ad1b5..1c703c79 100644 --- a/abi_stable_derive/src/my_visibility.rs +++ b/abi_stable_derive/src/my_visibility.rs @@ -1,6 +1,4 @@ -/*! -Types for conveniently representing visibility. -*/ +//! Types for conveniently representing visibility. use proc_macro2::TokenStream; use quote::ToTokens; diff --git a/abi_stable_derive/src/parse_utils.rs b/abi_stable_derive/src/parse_utils.rs index 038d3dbc..1a612bad 100644 --- a/abi_stable_derive/src/parse_utils.rs +++ b/abi_stable_derive/src/parse_utils.rs @@ -1,6 +1,4 @@ -/*! -Functions for parsing many `syn` types. -*/ +//! Functions for parsing many `syn` types. use as_derive_utils::spanned_err; diff --git a/abi_stable_derive/src/sabi_extern_fn_impl.rs b/abi_stable_derive/src/sabi_extern_fn_impl.rs index d11f27a9..51f9ac96 100644 --- a/abi_stable_derive/src/sabi_extern_fn_impl.rs +++ b/abi_stable_derive/src/sabi_extern_fn_impl.rs @@ -1,6 +1,4 @@ -/*! -Implementation details of the `#[sabi_extern_fn]` attribute. -*/ +//! Implementation details of the `#[sabi_extern_fn]` attribute. use std::mem; diff --git a/abi_stable_derive/src/sabi_trait.rs b/abi_stable_derive/src/sabi_trait.rs index 79b79747..b59a2ab8 100644 --- a/abi_stable_derive/src/sabi_trait.rs +++ b/abi_stable_derive/src/sabi_trait.rs @@ -167,22 +167,20 @@ pub fn derive_sabi_trait(item: ItemTrait) -> Result { .piped(Ok) } -/** -Outputs these items: - -- `Trait_Backend`: - A type alias to the underlying implementation of the trait object, - which is either RObject - -- `Trait_Interface` - A marker type describing the traits that are required when constructing - the underlying implementation of the trait object, - and are then implemented by it,by implementing InterfaceType. - -- `Trait_TO`: - The ffi-safe trait object for the trait. - -*/ +/// Outputs these items: +/// +/// - `Trait_Backend`: +/// A type alias to the underlying implementation of the trait object, +/// which is either RObject +/// +/// - `Trait_Interface` +/// A marker type describing the traits that are required when constructing +/// the underlying implementation of the trait object, +/// and are then implemented by it,by implementing InterfaceType. +/// +/// - `Trait_TO`: +/// The ffi-safe trait object for the trait. +/// fn first_items( TokenizerParams { config, @@ -1093,14 +1091,12 @@ fn declare_vtable( .to_tokens(mod_); } -/** -Outputs the vtable impl block with both: - -- A constant where the vtable is constructed. - -- The methods that the vtable is constructed with. - -*/ +/// Outputs the vtable impl block with both: +/// +/// - A constant where the vtable is constructed. +/// +/// - The methods that the vtable is constructed with. +/// fn vtable_impl( TokenizerParams { config, diff --git a/abi_stable_derive/src/sabi_trait/common_tokens.rs b/abi_stable_derive/src/sabi_trait/common_tokens.rs index 853100a2..7b158eee 100644 --- a/abi_stable_derive/src/sabi_trait/common_tokens.rs +++ b/abi_stable_derive/src/sabi_trait/common_tokens.rs @@ -1,8 +1,6 @@ -/*! -This module defines the CommonTokens type, -used to pass constants of type from `syn` to -many functions in the `abi_stable_derive_lib::sabi_trait` module. -*/ +//! This module defines the CommonTokens type, +//! used to pass constants of type from `syn` to +//! many functions in the `abi_stable_derive_lib::sabi_trait` module. use proc_macro2::{Span, TokenStream}; diff --git a/abi_stable_derive/src/sabi_trait/methods_tokenizer.rs b/abi_stable_derive/src/sabi_trait/methods_tokenizer.rs index d65411af..463f5adf 100644 --- a/abi_stable_derive/src/sabi_trait/methods_tokenizer.rs +++ b/abi_stable_derive/src/sabi_trait/methods_tokenizer.rs @@ -1,26 +1,24 @@ -/*! -Contains the MethodsTokenizer type, -which is used to print the definition of the method in different places. - -Where this is used is determined by WhichItem: - -- `WhichItem::Trait`: - outputs the method in the trait definition. - -- `WhichItem::TraitImpl`: - outputs the method in the trait implemetation for the generated trait object. - -- `WhichItem::TraitObjectImpl`: - outputs the methods in the inherent implemetation of the generated trait object. - -- `WhichItem::VtableDecl`: - outputs the fields of the trait object vtable. - -- `WhichItem::VtableImpl`: - outputs the methods used to construct the vtable. - - -*/ +//! Contains the MethodsTokenizer type, +//! which is used to print the definition of the method in different places. +//! +//! Where this is used is determined by WhichItem: +//! +//! - `WhichItem::Trait`: +//! outputs the method in the trait definition. +//! +//! - `WhichItem::TraitImpl`: +//! outputs the method in the trait implemetation for the generated trait object. +//! +//! - `WhichItem::TraitObjectImpl`: +//! outputs the methods in the inherent implemetation of the generated trait object. +//! +//! - `WhichItem::VtableDecl`: +//! outputs the fields of the trait object vtable. +//! +//! - `WhichItem::VtableImpl`: +//! outputs the methods used to construct the vtable. +//! +//! use super::{lifetime_unelider::BorrowKind, *}; diff --git a/abi_stable_derive/src/sabi_trait/replace_self_path.rs b/abi_stable_derive/src/sabi_trait/replace_self_path.rs index 12fe5c1b..6b5d1cc6 100644 --- a/abi_stable_derive/src/sabi_trait/replace_self_path.rs +++ b/abi_stable_derive/src/sabi_trait/replace_self_path.rs @@ -1,6 +1,5 @@ -/** -Contains the replace_self_path function,and the ReplaceWith enum. -*/ +//! Contains the `replace_self_path` function,and the `ReplaceWith` enum. + use as_derive_utils::spanned_err; use syn::visit_mut::VisitMut; @@ -53,18 +52,16 @@ impl_visit_mut_with! { (syn::Type,VisitMut::visit_type_mut), } -/** -Replaces all associated types of `Self` from `value`. - -`replace_with` determines what happens to `Self::` when `Some()` is -returned from `is_assoc_type`. - -`is_assoc_type` is used to find the associated types to replace -(when the function returns Some(_)), -as well as what to replace them with. - - -*/ +/// Replaces all associated types of `Self` from `value`. +/// +/// `replace_with` determines what happens to `Self::` when `Some()` is +/// returned from `is_assoc_type`. +/// +/// `is_assoc_type` is used to find the associated types to replace +/// (when the function returns Some(_)), +/// as well as what to replace them with. +/// +/// pub(crate) fn replace_self_path( value: &mut V, replace_with: ReplaceWith, diff --git a/abi_stable_derive/src/stable_abi/common_tokens.rs b/abi_stable_derive/src/stable_abi/common_tokens.rs index 848eeaaf..43b36f42 100644 --- a/abi_stable_derive/src/stable_abi/common_tokens.rs +++ b/abi_stable_derive/src/stable_abi/common_tokens.rs @@ -1,8 +1,6 @@ -/*! -This module defines the CommonTokens type, -used to pass constants of type from `syn` to -many functions in the `abi_stable_derive_lib::stable_abi` module. -*/ +//! This module defines the CommonTokens type, +//! used to pass constants of type from `syn` to +//! many functions in the `abi_stable_derive_lib::stable_abi` module. use proc_macro2::Span; diff --git a/abi_stable_derive/src/stable_abi/prefix_types.rs b/abi_stable_derive/src/stable_abi/prefix_types.rs index e5d5d7d9..60682d92 100644 --- a/abi_stable_derive/src/stable_abi/prefix_types.rs +++ b/abi_stable_derive/src/stable_abi/prefix_types.rs @@ -1,8 +1,4 @@ -/*! - -Code generation for prefix-types. - -*/ +//! Code generation for prefix-types. use abi_stable_shared::const_utils::low_bit_mask_u64; @@ -213,9 +209,7 @@ impl<'a> PrefixKind<'a> { ///// Code generation //////////////////////////////////////////////////////////////////////////////// -/** -Returns a value which for a prefix-type . -*/ +/// Returns a value which for a prefix-type . pub(crate) fn prefix_type_tokenizer<'a>( module: &'a Ident, mono_type_layout: &'a Ident, diff --git a/abi_stable_derive/src/stable_abi/tl_function.rs b/abi_stable_derive/src/stable_abi/tl_function.rs index 3e389df2..d7ba36e7 100644 --- a/abi_stable_derive/src/stable_abi/tl_function.rs +++ b/abi_stable_derive/src/stable_abi/tl_function.rs @@ -1,6 +1,4 @@ -/*! -Contains types related to the type layout of function pointers. -*/ +//! Contains types related to the type layout of function pointers. use super::*; diff --git a/abi_stable_derive/src/workaround.rs b/abi_stable_derive/src/workaround.rs index 37a53603..90d7f2ec 100644 --- a/abi_stable_derive/src/workaround.rs +++ b/abi_stable_derive/src/workaround.rs @@ -1,9 +1,5 @@ -/*! - -Wrote this as a workaround for -`::fmt` not working correctly for some reason. - -*/ +//! Wrote this as a workaround for +//! `::fmt` not working correctly for some reason. use std::{fmt::Write, mem}; diff --git a/as_derive_utils/src/datastructure/field_map.rs b/as_derive_utils/src/datastructure/field_map.rs index eb90d189..e1bdc0dd 100644 --- a/as_derive_utils/src/datastructure/field_map.rs +++ b/as_derive_utils/src/datastructure/field_map.rs @@ -5,13 +5,11 @@ use std::{ ops::{Index, IndexMut}, }; -/** -This is a map from fields to some value. - -If you put this in a type,and use Default to initialize it, -you must remember to replace the `FieldMap` using either `FieldMap::defaulted` or `FieldMap::with` - -*/ +/// This is a map from fields to some value. +/// +/// If you put this in a type,and use Default to initialize it, +/// you must remember to replace the `FieldMap` using either `FieldMap::defaulted` or +/// `FieldMap::with` #[derive(Default, Clone, Debug, PartialEq, Hash)] pub struct FieldMap { // The outer vec is the enum variant (if it's a struct/union it's a single element Vec), diff --git a/as_derive_utils/src/datastructure/type_param_map.rs b/as_derive_utils/src/datastructure/type_param_map.rs index 1ce1f7c3..0c152558 100644 --- a/as_derive_utils/src/datastructure/type_param_map.rs +++ b/as_derive_utils/src/datastructure/type_param_map.rs @@ -6,14 +6,12 @@ use std::{ rc::Rc, }; -/** -This is a map from type parameters to some value. - -If you put this in a type,and use Default to initialize it, -you must remember to replace the `TypeParamMap` using either -`TypeParamMap::defaulted` or `TypeParamMap::with` - -*/ +/// This is a map from type parameters to some value. +/// +/// If you put this in a type,and use Default to initialize it, +/// you must remember to replace the `TypeParamMap` using either +/// `TypeParamMap::defaulted` or `TypeParamMap::with` +/// #[derive(Default, Clone, Debug, PartialEq)] pub struct TypeParamMap<'a, T> { idents: Rc>, diff --git a/as_derive_utils/src/gen_params_in.rs b/as_derive_utils/src/gen_params_in.rs index efeb2abf..7213d212 100644 --- a/as_derive_utils/src/gen_params_in.rs +++ b/as_derive_utils/src/gen_params_in.rs @@ -1,6 +1,4 @@ -/*! -Contains the `GenParamsIn` type,for printing generic parameters. -*/ +//! Contains the `GenParamsIn` type,for printing generic parameters. use syn::{ token::{Colon, Comma, Const, Star}, @@ -44,10 +42,8 @@ pub enum InWhat { ItemDecl, /// For when using a generic as an argument for a trait/struct/enum/union. ItemUse, - /** - For defining the fields of a Dummy struct that is never instantiated, - only using its associated items. - */ + /// For defining the fields of a Dummy struct that is never instantiated, + /// only using its associated items. DummyStruct, } diff --git a/examples/0_modules_and_interface_types/impl/src/lib.rs b/examples/0_modules_and_interface_types/impl/src/lib.rs index 8b3be34c..6c565ef3 100644 --- a/examples/0_modules_and_interface_types/impl/src/lib.rs +++ b/examples/0_modules_and_interface_types/impl/src/lib.rs @@ -1,9 +1,6 @@ -/*! -This is an `implementation crate`, -It exports the root module(a struct of function pointers) required by the -`example_0_interface`(the `interface crate`). - -*/ +//! This is an `implementation crate`, +//! It exports the root module(a struct of function pointers) required by the +//! `example_0_interface`(the `interface crate`). use std::{ borrow::Cow, diff --git a/examples/0_modules_and_interface_types/interface/src/lib.rs b/examples/0_modules_and_interface_types/interface/src/lib.rs index 8b2ccaf7..5cbf1508 100644 --- a/examples/0_modules_and_interface_types/interface/src/lib.rs +++ b/examples/0_modules_and_interface_types/interface/src/lib.rs @@ -1,14 +1,11 @@ -/*! -This is an example `interface crate`, -where all publically available modules(structs of function pointers) and types are declared, - -To load the library and the modules together, -call `::load_from_directory`, -which will load the dynamic library from a directory(folder), -and all the modules inside of the library. - - -*/ +//! This is an example `interface crate`, +//! where all publically available modules(structs of function pointers) and types are declared, +//! +//! To load the library and the modules together, +//! call `::load_from_directory`, +//! which will load the dynamic library from a directory(folder), +//! and all the modules inside of the library. +//! use abi_stable::{ declare_root_module_statics, @@ -34,19 +31,16 @@ pub struct TextOpsMod { /// Constructs TOStateBox,state that is passed to other functions in this module. pub new: extern "C" fn() -> TOStateBox, - /** - The `deserializers` submodule. - - The `#[sabi(last_prefix_field)]` attribute here means that this is the last field in this struct - that was defined in the first compatible version of the library - (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), - requiring new fields to always be added below preexisting ones. - - The `#[sabi(last_prefix_field)]` attribute would stay on this field until the library - bumps its "major" version, - at which point it would be moved to the last field at the time. - - */ + /// The `deserializers` submodule. + /// + /// The `#[sabi(last_prefix_field)]` attribute here means that this is the last + /// field in this struct that was defined in the first compatible version of the library + /// (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), + /// requiring new fields to always be added below preexisting ones. + /// + /// The `#[sabi(last_prefix_field)]` attribute would stay on this field until the library + /// bumps its "major" version, + /// at which point it would be moved to the last field at the time. #[sabi(last_prefix_field)] pub deserializers: DeserializerMod_Ref, @@ -86,20 +80,18 @@ impl RootModule for TextOpsMod_Ref { pub struct DeserializerMod { pub something: std::marker::PhantomData<()>, - /** - The implementation for how TOStateBox is going to be deserialized. - - - The `#[sabi(last_prefix_field)]` attribute here means that this is the last field in this struct - that was defined in the first compatible version of the library - (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), - requiring new fields to always be added below preexisting ones. - - The `#[sabi(last_prefix_field)]` attribute would stay on this field until the library - bumps its "major" version, - at which point it would be moved to the last field at the time. - - */ + /// The implementation for how TOStateBox is going to be deserialized. + /// + /// + /// The `#[sabi(last_prefix_field)]` attribute here means that this is the + /// last field in this struct that was defined in the first compatible version of the library + /// (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), + /// requiring new fields to always be added below preexisting ones. + /// + /// The `#[sabi(last_prefix_field)]` attribute would stay on this field until the library + /// bumps its "major" version, + /// at which point it would be moved to the last field at the time. + /// #[sabi(last_prefix_field)] pub deserialize_state: extern "C" fn(RStr<'_>) -> RResult, @@ -118,11 +110,9 @@ pub struct DeserializerMod { /////////////////////////////////////////////// -/** -An `InterfaceType` describing which traits are required -when constructing `TOStateBox`(Serialize,Deserialize,and PartialEq) -and are then usable afterwards. -*/ +/// An `InterfaceType` describing which traits are required +/// when constructing `TOStateBox`(Serialize,Deserialize,and PartialEq) +/// and are then usable afterwards. #[repr(C)] #[derive(StableAbi)] #[sabi(impl_InterfaceType(Serialize, Deserialize, Debug, PartialEq))] @@ -138,9 +128,7 @@ impl<'a> SerializeProxyType<'a> for TOState { type Proxy = RawValueBox; } -/** -Describes how a `TOStateBox` is deserialized. -*/ +/// Describes how a `TOStateBox` is deserialized. impl<'borr> DeserializeDyn<'borr, TOStateBox> for TOState { /// The intermediate type that is deserialized, /// and then converted to `TOStateBox` with `DeserializeDyn::deserialize_dyn`. @@ -157,11 +145,9 @@ impl<'borr> DeserializeDyn<'borr, TOStateBox> for TOState { /////////////////////////////////////////////////////////////////////////////// -/** -An `InterfaceType` describing which traits are required -when constructing `TOCommandBox`(Send,Sync,Debug,Serialize,etc) -and are then usable afterwards. -*/ +/// An `InterfaceType` describing which traits are required +/// when constructing `TOCommandBox`(Send,Sync,Debug,Serialize,etc) +/// and are then usable afterwards. #[repr(C)] #[derive(StableAbi)] #[sabi(impl_InterfaceType(Send, Sync, Debug, Serialize, Deserialize, PartialEq, Iterator))] @@ -200,11 +186,9 @@ impl<'borr> DeserializeDyn<'borr, TOCommandBox<'static>> for TOCommand { /////////////////////////////////////////////////////////////////////////////// -/** -An `InterfaceType` describing which traits are required -when constructing `TOReturnValueArc`(Send,Sync,Debug,Serialize,Deserialize,and PartialEq) -and are then usable afterwards. -*/ +/// An `InterfaceType` describing which traits are required +/// when constructing `TOReturnValueArc`(Send,Sync,Debug,Serialize,Deserialize,and PartialEq) +/// and are then usable afterwards. #[repr(C)] #[derive(StableAbi)] #[sabi(impl_InterfaceType(Sync, Send, Debug, Serialize, Deserialize, PartialEq))] @@ -237,11 +221,9 @@ impl<'borr> DeserializeDyn<'borr, TOReturnValueArc> for TOReturnValue { /////////////////////////////////////////////////////////////////////////////// -/** -An `InterfaceType` describing which traits are required -when constructing `DynTrait<_,CowStrIter>`(Send,Sync,and Iterator) -and are then usable afterwards. -*/ +/// An `InterfaceType` describing which traits are required +/// when constructing `DynTrait<_,CowStrIter>`(Send,Sync,and Iterator) +/// and are then usable afterwards. #[repr(C)] #[derive(StableAbi)] #[sabi(impl_InterfaceType(Sync, Send, Iterator))] diff --git a/examples/0_modules_and_interface_types/user/src/main.rs b/examples/0_modules_and_interface_types/user/src/main.rs index 3fc36995..edef826e 100644 --- a/examples/0_modules_and_interface_types/user/src/main.rs +++ b/examples/0_modules_and_interface_types/user/src/main.rs @@ -46,74 +46,64 @@ where enum Command { #[structopt(name = "reverse-line-order")] #[structopt(author = "_")] - /** - - Reverse the order of all lines from stdin into stdout once stdin disconnects. - - Example: - - Running this(on linux,don't know how it would work on windows or mac): - ``` - echo -e "A\nB\nC\nD" | cargo run -- reverse-line-order - ``` - - Outputs this: - ``` - D - C - B - A - ``` - - */ + /// + /// Reverse the order of all lines from stdin into stdout once stdin disconnects. + /// + /// Example: + /// + /// Running this(on linux,don't know how it would work on windows or mac): + /// ``` + /// echo -e "A\nB\nC\nD" | cargo run -- reverse-line-order + /// ``` + /// + /// Outputs this: + /// ``` + /// D + /// C + /// B + /// A + /// ``` + /// ReverseLineOrder, - /** - - Copies the stdin into stdout,removing the words passed as command line arguments. - - Example: - - Running this - ``` - echo "This is an example phrase,try replacing this with some other sentence." | \ - cargo run -- remove-words is an try this with - ``` - Outputs this: - ``` - This example phrase,replacing some other sentence. - ``` - - */ + /// Copies the stdin into stdout,removing the words passed as command line arguments. + /// + /// Example: + /// + /// Running this + /// ``` + /// echo "This is an example phrase,try replacing this with some other sentence." | \ + /// cargo run -- remove-words is an try this with + /// ``` + /// Outputs this: + /// ``` + /// This example phrase,replacing some other sentence. + /// ``` + /// #[structopt(name = "remove-words")] #[structopt(author = "_")] RemoveWords { words: Vec }, #[structopt(name = "run-tests")] #[structopt(author = "_")] - /** - Runs some tests that require a dynamic library. - This is how some integration tests are done,may be replaced with a - dedicated test suite eventually. - */ + /// Runs some tests that require a dynamic library. + /// This is how some integration tests are done,may be replaced with a + /// dedicated test suite eventually. RunTests, - /** - - Runs some json encoded commands,outputting the json encoded return value to stdout. - The command can come from either from stdin or from a file - For some examples of json commands please look in the `data/` directory. - - Examples: - - `cargo run -- json-command data/0_reverse_lines.json` - - `cargo run -- json-command data/1_remove_words.json` - - `cargo run -- json-command data/2_get_processed_bytes.json` - - */ + /// Runs some json encoded commands,outputting the json encoded return value to stdout. + /// The command can come from either from stdin or from a file + /// For some examples of json commands please look in the `data/` directory. + /// + /// Examples: + /// + /// `cargo run -- json-command data/0_reverse_lines.json` + /// + /// `cargo run -- json-command data/1_remove_words.json` + /// + /// `cargo run -- json-command data/2_get_processed_bytes.json` + /// #[structopt(name = "json-command")] #[structopt(author = "_")] Json { diff --git a/examples/1_trait_objects/interface/src/lib.rs b/examples/1_trait_objects/interface/src/lib.rs index 68f1ac4f..705a38a0 100644 --- a/examples/1_trait_objects/interface/src/lib.rs +++ b/examples/1_trait_objects/interface/src/lib.rs @@ -1,14 +1,12 @@ -/*! -This is an example `interface crate`, -where all publically available modules(structs of function pointers) and types are declared, - -To load the library and the modules together, -call `::load_from_directory`, -which will load the dynamic library from a directory(folder), -and all the modules inside of the library. - - -*/ +//! This is an example `interface crate`, +//! where all publically available modules(structs of function pointers) and types are declared, +//! +//! To load the library and the modules together, +//! call `::load_from_directory`, +//! which will load the dynamic library from a directory(folder), +//! and all the modules inside of the library. +//! +//! use abi_stable::{ declare_root_module_statics, @@ -39,9 +37,7 @@ pub use self::{ /////////////////////////////////////////////////////////////////////////////// -/** -The identifier for a plugin. -*/ +/// The identifier for a plugin. #[repr(C)] #[derive(Debug, Clone, PartialEq, Eq, StableAbi, Serialize, Deserialize)] pub struct PluginId { @@ -87,11 +83,7 @@ impl<'a> PluginResponse<'a> { pub type PluginType = Plugin_TO<'static, RBox<()>>; -/** -A plugin which is loaded by the application,and provides some functionality. - - -*/ +/// A plugin which is loaded by the application,and provides some functionality. #[sabi_trait] //#[sabi(debug_print)] pub trait Plugin { @@ -118,24 +110,22 @@ pub trait Plugin { /// Gets a description of all commands from this Plugin. fn list_commands(&self) -> RVec; - /* - Closes the plugin, - - This does not unload the dynamic library of this plugin, - you can instantiate another instance of this plugin with - `PluginMod_Ref::get_module().new()(application_handle)`. - - - - The `#[sabi(last_prefix_field)]` attribute here means that this is the last method - that was defined in the first compatible version of the library - (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), - requiring new methods to always be added below preexisting ones. - - The `#[sabi(last_prefix_field)]` attribute would stay on this method until the library - bumps its "major" version, - at which point it would be moved to the last method at the time. - */ + /// Closes the plugin, + /// + /// This does not unload the dynamic library of this plugin, + /// you can instantiate another instance of this plugin with + /// `PluginMod_Ref::get_module().new()(application_handle)`. + /// + /// + /// + /// The `#[sabi(last_prefix_field)]` attribute here means that this is the last method + /// that was defined in the first compatible version of the library + /// (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), + /// requiring new methods to always be added below preexisting ones. + /// + /// The `#[sabi(last_prefix_field)]` attribute would stay on this method until the library + /// bumps its "major" version, + /// at which point it would be moved to the last method at the time. #[sabi(last_prefix_field)] fn close(self, app: ApplicationMut<'_>); } @@ -151,20 +141,18 @@ pub trait Plugin { #[sabi(kind(Prefix(prefix_ref = "PluginMod_Ref")))] #[sabi(missing_field(panic))] pub struct PluginMod { - /** - Constructs the plugin. - - - The `#[sabi(last_prefix_field)]` attribute here means that this is the last field in this struct - that was defined in the first compatible version of the library - (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), - requiring new fields to always be added below preexisting ones. - - The `#[sabi(last_prefix_field)]` attribute would stay on this field until the library - bumps its "major" version, - at which point it would be moved to the last field at the time. - - */ + /// Constructs the plugin. + /// + /// + /// The `#[sabi(last_prefix_field)]` attribute here means that this is the last field in this struct + /// that was defined in the first compatible version of the library + /// (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), + /// requiring new fields to always be added below preexisting ones. + /// + /// The `#[sabi(last_prefix_field)]` attribute would stay on this field until the library + /// bumps its "major" version, + /// at which point it would be moved to the last field at the time. + /// #[sabi(last_prefix_field)] pub new: extern "C" fn(RSender, PluginId) -> RResult, } @@ -195,20 +183,18 @@ pub trait Application { command: RString, ) -> RResult<(), Error>; - /** - Gets the `PluginId`s of the plugins specified by `which_plugin`. - - - The `#[sabi(last_prefix_field)]` attribute here means that this is the last method - that was defined in the first compatible version of the library - (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), - requiring new methods to always be added below preexisting ones. - - The `#[sabi(last_prefix_field)]` attribute would stay on this method until the library - bumps its "major" version, - at which point it would be moved to the last method at the time. - - */ + /// Gets the `PluginId`s of the plugins specified by `which_plugin`. + /// + /// + /// The `#[sabi(last_prefix_field)]` attribute here means that this is the last method + /// that was defined in the first compatible version of the library + /// (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), + /// requiring new methods to always be added below preexisting ones. + /// + /// The `#[sabi(last_prefix_field)]` attribute would stay on this method until the library + /// bumps its "major" version, + /// at which point it would be moved to the last method at the time. + /// #[sabi(last_prefix_field)] fn get_plugin_id(&self, which_plugin: WhichPlugin) -> RResult, Error>; diff --git a/examples/1_trait_objects/interface/src/utils.rs b/examples/1_trait_objects/interface/src/utils.rs index 42b04255..248c8ddd 100644 --- a/examples/1_trait_objects/interface/src/utils.rs +++ b/examples/1_trait_objects/interface/src/utils.rs @@ -11,24 +11,23 @@ use abi_stable::std_types::{RBoxError, RResult, RStr, RString}; use serde::{Deserialize, Serialize}; -/** -Sends a json encoded command to a plugin,and returns the response by encoding it to json. - -# Errors - -These are all error that this function returns -(this does not include error returned as part of the command): - -- Error::Serialize: - If the command/return value could not be serialized to JSON. - -- Error::Deserialize - If the command/return value could not be deserialized from JSON(this comes from the plugin). - -- Error::UnsupportedCommand - If the command is not supported by the plugin. - -*/ +/// Sends a json encoded command to a plugin,and returns the response by encoding it to json. +/// +/// # Errors +/// +/// These are all error that this function returns +/// (this does not include error returned as part of the command): +/// +/// - Error::Serialize: +/// If the command/return value could not be serialized to JSON. +/// +/// - Error::Deserialize +/// If the command/return value could not be deserialized from JSON +/// (this comes from the plugin). +/// +/// - Error::UnsupportedCommand +/// If the command is not supported by the plugin. +/// pub fn process_command<'de, P, C, R, F>( this: &mut P, command: RStr<'de>, @@ -71,29 +70,28 @@ where .into() } -/** -Sends a typed command to a plugin. - -# Errors - -These are all error that this function returns -(this does not include error returned as part of the command): - -- Error::Serialize: - If the command/return value could not be serialized to JSON. - -- Error::Deserialize - If the command/return value could not be deserialized from JSON(this comes from the plugin). - -- Error::UnsupportedReturnValue: - If the return value could not be deserialized from JSON - (after checking that it has the `{"name":"...",description: ... }` format), - containing the name of the command this is a return value for . - -- Error::UnsupportedCommand - If the command is not supported by the plugin. - -*/ +/// Sends a typed command to a plugin. +/// +/// # Errors +/// +/// These are all error that this function returns +/// (this does not include error returned as part of the command): +/// +/// - Error::Serialize: +/// If the command/return value could not be serialized to JSON. +/// +/// - Error::Deserialize +/// If the command/return value could not be deserialized from JSON +/// (this comes from the plugin). +/// +/// - Error::UnsupportedReturnValue: +/// If the return value could not be deserialized from JSON +/// (after checking that it has the `{"name":"...",description: ... }` format), +/// containing the name of the command this is a return value for . +/// +/// - Error::UnsupportedCommand +/// If the command is not supported by the plugin. +/// pub fn send_command( this: &mut PluginType, command: &C, diff --git a/examples/1_trait_objects/plugin_0/src/lib.rs b/examples/1_trait_objects/plugin_0/src/lib.rs index f4e3ac21..88e45fdf 100644 --- a/examples/1_trait_objects/plugin_0/src/lib.rs +++ b/examples/1_trait_objects/plugin_0/src/lib.rs @@ -1,9 +1,6 @@ -/*! -This is an `implementation crate`, -It exports the root module(a struct of function pointers) required by the -`example_0_interface`(the `interface crate`). - -*/ +//! This is an `implementation crate`, +//! It exports the root module(a struct of function pointers) required by the +//! `example_0_interface`(the `interface crate`). use std::collections::HashSet; diff --git a/examples/1_trait_objects/plugin_1/src/lib.rs b/examples/1_trait_objects/plugin_1/src/lib.rs index 350d9d56..de3d0e93 100644 --- a/examples/1_trait_objects/plugin_1/src/lib.rs +++ b/examples/1_trait_objects/plugin_1/src/lib.rs @@ -1,9 +1,6 @@ -/*! -This is an `implementation crate`, -It exports the root module(a struct of function pointers) required by the -`example_0_interface`(the `interface crate`). - -*/ +//! This is an `implementation crate`, +//! It exports the root module(a struct of function pointers) required by the +//! `example_0_interface`(the `interface crate`). use abi_stable::{ export_root_module, diff --git a/examples/2_nonexhaustive/interface/src/lib.rs b/examples/2_nonexhaustive/interface/src/lib.rs index f75b06f9..b458ef5d 100644 --- a/examples/2_nonexhaustive/interface/src/lib.rs +++ b/examples/2_nonexhaustive/interface/src/lib.rs @@ -29,11 +29,9 @@ pub struct ItemId { /////////////////////////////////////////////////////////////////////////////// -/** -The parameters of `Shop::run_command`. - -Every variant of this enum corresponds to a variant of `ReturnVal`. -*/ +/// The parameters of `Shop::run_command`. +/// +/// Every variant of this enum corresponds to a variant of `ReturnVal`. #[non_exhaustive] #[repr(u8)] #[derive(StableAbi, Debug, Clone, PartialEq, Deserialize, Serialize)] @@ -43,10 +41,8 @@ Every variant of this enum corresponds to a variant of `ReturnVal`. assert_nonexhaustive = "Command", )))] pub enum Command { - /** - `#[sabi(with_boxed_constructor)]` tells the `StableAbi` derive macro to - generate the `fn CreateItem_NE(ParamCreateItem)->ReturnVal_NE` associated function. - */ + /// `#[sabi(with_boxed_constructor)]` tells the `StableAbi` derive macro to + /// generate the `fn CreateItem_NE(ParamCreateItem)->ReturnVal_NE` associated function. #[sabi(with_boxed_constructor)] CreateItem(RBox), DeleteItem { @@ -68,12 +64,10 @@ pub enum Command { new_name: RString, }, - /** - This variant was added in the 1.1 version of the library. - - `#[sabi(with_constructor)]` tells the `StableAbi` derive macro to - generate the `fn Many_NE(RVec)->Command_NE` associated function. - */ + /// This variant was added in the 1.1 version of the library. + /// + /// `#[sabi(with_constructor)]` tells the `StableAbi` derive macro to + /// generate the `fn Many_NE(RVec)->Command_NE` associated function. #[cfg(feature = "v1_1")] #[sabi(with_constructor)] Many { @@ -99,13 +93,11 @@ pub struct ParamCreateItem { pub price: Cents, } -/** -This specifies how `Command_NE` is serialized. - -`Command_Interface` was generated by `#[derive(StableAbi)]`, -because `trait()` was passed as a parameter to `#[sabi(kind(WithNonExhaustive( ... )))]`. - -*/ +/// This specifies how `Command_NE` is serialized. +/// +/// `Command_Interface` was generated by `#[derive(StableAbi)]`, +/// because `trait()` was passed as a parameter to +/// `#[sabi(kind(WithNonExhaustive( ... )))]`. impl SerializeEnum for Command_Interface { /// The intermediate type the enum is converted into with `SerializeEnum::serialize_enum`, /// and then serialized. @@ -116,9 +108,7 @@ impl SerializeEnum for Command_Interface { } } -/** -This specifies how `Command_NE` is deserialized. -*/ +/// This specifies how `Command_NE` is deserialized. impl<'a> DeserializeEnum<'a, Command_NE> for Command_Interface { /// The intermediate type that is deserialized, /// and then converted to the enum with `DeserializeEnum::deserialize_enum`. @@ -175,11 +165,9 @@ fn examples_of_constructing_a_command() { /////////////////////////////////////////////////////////////////////////////// -/** -The return value of `Shop::run_command`. - -Every variant of this enum corresponds to a variant of `Command`. -*/ +/// The return value of `Shop::run_command`. +/// +/// Every variant of this enum corresponds to a variant of `Command`. #[non_exhaustive] #[repr(u8)] #[derive(StableAbi, Debug, Clone, PartialEq, Deserialize, Serialize)] @@ -205,22 +193,18 @@ pub enum ReturnVal { remaining: u32, id: ItemId, }, - /** - This variant was added in the 1.1 version of the library. - - `#[sabi(with_boxed_constructor)]` tells the `StableAbi` derive macro to - generate the `fn RenameItem_NE(RetRenameItem)->ReturnVal_NE` associated function. - */ + /// This variant was added in the 1.1 version of the library. + /// + /// `#[sabi(with_boxed_constructor)]` tells the `StableAbi` derive macro to + /// generate the `fn RenameItem_NE(RetRenameItem)->ReturnVal_NE` associated function. #[cfg(feature = "v1_1")] #[sabi(with_boxed_constructor)] RenameItem(RBox), - /** - This variant was added in the 1.1 version of the library. - - `#[sabi(with_constructor)]` tells the `StableAbi` derive macro to - generate the `fn Many_NE(RVec)->ReturnVal_NE` associated function. - */ + /// This variant was added in the 1.1 version of the library. + /// + /// `#[sabi(with_constructor)]` tells the `StableAbi` derive macro to + /// generate the `fn Many_NE(RVec)->ReturnVal_NE` associated function. #[cfg(feature = "v1_1")] #[sabi(with_constructor)] Many { @@ -238,10 +222,8 @@ pub type ReturnVal_NE= >; */ -/** -A command to rename an item in the shop, -which must be wrapped in `ReturnVal::RenameItem_NE` to pass to `Shop::run_command`. -*/ +/// A command to rename an item in the shop, +/// which must be wrapped in `ReturnVal::RenameItem_NE` to pass to `Shop::run_command`. #[cfg(feature = "v1_1")] #[repr(C)] #[derive(StableAbi, Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -251,13 +233,11 @@ pub struct RetRenameItem { pub old_name: RString, } -/** -This specifies how `ReturnVal_NE` is serialized. - -This is implemented on Command_Interface, -because `interface="Command_Interface"` was passed as a parameter to -`#[sabi(kind(WithNonExhaustive( ... )))]`. -*/ +/// This specifies how `ReturnVal_NE` is serialized. +/// +/// This is implemented on Command_Interface, +/// because `interface="Command_Interface"` was passed as a parameter to +/// `#[sabi(kind(WithNonExhaustive( ... )))]`. impl SerializeEnum for Command_Interface { /// The intermediate type the enum is converted into with `SerializeEnum::serialize_enum`, /// and then serialized. @@ -268,9 +248,7 @@ impl SerializeEnum for Command_Interface { } } -/** -This specifies how `ReturnVal_NE` is deserialized. -*/ +/// This specifies how `ReturnVal_NE` is deserialized. impl<'a> DeserializeEnum<'a, ReturnVal_NE> for Command_Interface { /// The intermediate type that is deserialized, /// and then converted to the enum with `DeserializeEnum::deserialize_enum`. @@ -383,12 +361,10 @@ fn examples_of_constructing_an_error() { }); } -/** -The root module of the `shop` dynamic library. - -To load this module, -call ::load_from_directory(some_directory_path) -*/ +/// The root module of the `shop` dynamic library. +/// +/// To load this module, +/// call ::load_from_directory(some_directory_path) #[repr(C)] #[derive(StableAbi)] #[sabi(kind(Prefix(prefix_ref = "ShopMod_Ref")))] @@ -406,20 +382,17 @@ pub struct ShopMod { /// Serializes a `Command_NE`. pub serialize_command: extern "C" fn(&Command_NE) -> RResult, - /** - Serializes a `ReturnVal_NE`. - - - The `#[sabi(last_prefix_field)]` attribute here means that this is the last field in this struct - that was defined in the first compatible version of the library - (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), - requiring new fields to always be added below preexisting ones. - - The `#[sabi(last_prefix_field)]` attribute would stay on this field until the library - bumps its "major" version, - at which point it would be moved to the last field at the time. - - */ + /// Serializes a `ReturnVal_NE`. + /// + /// The `#[sabi(last_prefix_field)]` attribute here means that this is the last field in this struct + /// that was defined in the first compatible version of the library + /// (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), + /// requiring new fields to always be added below preexisting ones. + /// + /// The `#[sabi(last_prefix_field)]` attribute would stay on this field until the library + /// bumps its "major" version, + /// at which point it would be moved to the last field at the time. + /// #[sabi(last_prefix_field)] pub serialize_ret_val: extern "C" fn(&ReturnVal_NE) -> RResult, } @@ -432,26 +405,22 @@ impl RootModule for ShopMod_Ref { const VERSION_STRINGS: VersionStrings = package_version_strings!(); } -/** -This represents a shop manager, -which can be sent a growing list of commands with each version. -*/ +/// This represents a shop manager, +/// which can be sent a growing list of commands with each version. #[sabi_trait] pub trait Shop { - /** - Runs the `cmd` command. - - - The `#[sabi(last_prefix_field)]` attribute here means that this is the last method - that was defined in the first compatible version of the library - (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), - requiring new methods to always be added below preexisting ones. - - The `#[sabi(last_prefix_field)]` attribute would stay on this method until the library - bumps its "major" version, - at which point it would be moved to the last method at the time. - - */ + /// Runs the `cmd` command. + /// + /// + /// The `#[sabi(last_prefix_field)]` attribute here means that this is the last method + /// that was defined in the first compatible version of the library + /// (0.1.0, 0.2.0, 0.3.0, 1.0.0, 2.0.0 ,etc), + /// requiring new methods to always be added below preexisting ones. + /// + /// The `#[sabi(last_prefix_field)]` attribute would stay on this method until the library + /// bumps its "major" version, + /// at which point it would be moved to the last method at the time. + /// #[sabi(last_prefix_field)] fn run_command(&mut self, cmd: Command_NE) -> RResult>; } diff --git a/testing/0/impl_0/src/lib.rs b/testing/0/impl_0/src/lib.rs index 3b9e2009..64e08d4e 100644 --- a/testing/0/impl_0/src/lib.rs +++ b/testing/0/impl_0/src/lib.rs @@ -1,7 +1,4 @@ -/*! -This crate is where extra tests which don't belong in examples go. - -*/ +//! This crate is where extra tests which don't belong in examples go. use testing_interface_0::{ForTests, PrefixTypeMod0, TestingMod, TestingMod_Ref}; diff --git a/testing/0/interface_0/src/lib.rs b/testing/0/interface_0/src/lib.rs index 37b35d1a..ec3cad13 100644 --- a/testing/0/interface_0/src/lib.rs +++ b/testing/0/interface_0/src/lib.rs @@ -1,16 +1,12 @@ -/*! - -This is an example `interface crate`, -where all publically available modules(structs of function pointers) and types are declared, - -This crate is where extra tests which don't belong in examples go. - -To load the library and the modules together, -call `::load_from_directory`, -which will load the dynamic library from a directory(folder), -and then all the modules inside of the library. - -*/ +//! This is an example `interface crate`, +//! where all publically available modules(structs of function pointers) and types are declared, +//! +//! This crate is where extra tests which don't belong in examples go. +//! +//! To load the library and the modules together, +//! call `::load_from_directory`, +//! which will load the dynamic library from a directory(folder), +//! and then all the modules inside of the library. use abi_stable::{ library::RootModule, @@ -89,15 +85,13 @@ declare_PrefixTypeMod! { } declare_PrefixTypeMod! { - /** - This is unsafely converted from PrefixTypeMod0_Ref in tests to check that - `prefix.field_a()==some_integer`, - `prefix.field_b()==None`, - `prefix.field_c()==None`. - - This only works because I know that both structs have the same alignment, - if either struct alignment changed that conversion would be unsound. - */ + /// This is unsafely converted from PrefixTypeMod0_Ref in tests to check that + /// `prefix.field_a()==some_integer`, + /// `prefix.field_b()==None`, + /// `prefix.field_c()==None`. + /// + /// This only works because I know that both structs have the same alignment, + /// if either struct alignment changed that conversion would be unsound. struct PrefixTypeMod1; prefix_ref="PrefixTypeMod1_Ref"; diff --git a/testing/1 - loading errors/impl_1/src/lib.rs b/testing/1 - loading errors/impl_1/src/lib.rs index 819fda4a..3d983be4 100644 --- a/testing/1 - loading errors/impl_1/src/lib.rs +++ b/testing/1 - loading errors/impl_1/src/lib.rs @@ -1,7 +1,4 @@ -/*! -This crate is where extra tests which don't belong in examples go. - -*/ +//! This crate is where extra tests which don't belong in examples go. use testing_interface_1::{get_env_vars, ReturnWhat, TestingMod, TestingMod_Ref}; diff --git a/testing/1 - loading errors/interface_1/src/lib.rs b/testing/1 - loading errors/interface_1/src/lib.rs index 0ede6eed..cbdab6a5 100644 --- a/testing/1 - loading errors/interface_1/src/lib.rs +++ b/testing/1 - loading errors/interface_1/src/lib.rs @@ -1,10 +1,7 @@ -/*! - -This is an example `interface crate`, -where all publically available modules(structs of function pointers) and types are declared, - -These crate test a few of the errors that are returned when loading dynamic libraries -*/ +//! This is an example `interface crate`, +//! where all publically available modules(structs of function pointers) and types are declared, +//! +//! These crate test a few of the errors that are returned when loading dynamic libraries use abi_stable::{ library::RootModule, package_version_strings, sabi_types::VersionStrings, StableAbi, diff --git a/testing/version_compatibility/impl_0/src/lib.rs b/testing/version_compatibility/impl_0/src/lib.rs index b9f4a242..d3202200 100644 --- a/testing/version_compatibility/impl_0/src/lib.rs +++ b/testing/version_compatibility/impl_0/src/lib.rs @@ -1,7 +1,4 @@ -/*! -This crate is where extra tests which don't belong in examples go. - -*/ +//! This crate is where extra tests which don't belong in examples go. use version_compatibility_interface::{RootMod, RootMod_Ref}; diff --git a/tools/sabi_extract/src/main.rs b/tools/sabi_extract/src/main.rs index 18e39cfa..55aa21e6 100644 --- a/tools/sabi_extract/src/main.rs +++ b/tools/sabi_extract/src/main.rs @@ -15,10 +15,8 @@ use structopt::StructOpt; #[derive(StructOpt)] #[structopt(author = "_")] enum Command { - /** - Extracts the module structure of an abi_stable library, - with the typenames of each function parameter/return type. - */ + /// Extracts the module structure of an abi_stable library, + /// with the typenames of each function parameter/return type. #[structopt(name = "mods")] #[structopt(author = "_")] Modules { From e419962830e34e81534bb3537f05509eede48df5 Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Wed, 27 Oct 2021 06:08:11 -0300 Subject: [PATCH 19/32] Added "rust_latest_stable" feature. Added aborting example to `extern_fn_panic_handling`. Fixed use of `vec` macro in `rvec`. Documented "rust_1_*"" features. --- abi_stable/Cargo.toml | 2 ++ abi_stable/src/derive_macro_reexports.rs | 1 + abi_stable/src/lib.rs | 6 ++++++ abi_stable/src/macros.rs | 23 +++++++++++++++++++++-- readme.md | 9 ++++++++- 5 files changed, 38 insertions(+), 3 deletions(-) diff --git a/abi_stable/Cargo.toml b/abi_stable/Cargo.toml index 20e8f73c..6803df14 100644 --- a/abi_stable/Cargo.toml +++ b/abi_stable/Cargo.toml @@ -30,6 +30,8 @@ rust_1_46=["rust_1_42"] rust_1_51=["rust_1_46", "const_params"] +rust_latest_stable = ["rust_1_51"] + const_params=["rust_1_46"] # Enables the `#![feature(min_const_generics)]` attribute in diff --git a/abi_stable/src/derive_macro_reexports.rs b/abi_stable/src/derive_macro_reexports.rs index 0fbcb04b..bf4cffd4 100644 --- a/abi_stable/src/derive_macro_reexports.rs +++ b/abi_stable/src/derive_macro_reexports.rs @@ -48,6 +48,7 @@ pub use std::{ mem::ManuallyDrop, option::Option, ptr::NonNull, + vec, }; pub use str; diff --git a/abi_stable/src/lib.rs b/abi_stable/src/lib.rs index 4e9d939d..4ce7713f 100644 --- a/abi_stable/src/lib.rs +++ b/abi_stable/src/lib.rs @@ -88,11 +88,17 @@ every one of which has a `nightly_*` equivalent. Features: +- "rust_1_46": Makes some functions `const fn`s that are otherwise not `const`, +this is documented in each function for which it applies. + - "rust_1_51_0": Enables impls which require using const generics, including implementing StableAbi for arrays of all lengths, requires Rust Rust 1.51.0 or higher. +- "rust_latest_stable": +Enables the "rust_1_*" features for all the stable releases. + # Glossary `interface crate`:the crate that declares the public functions, types, and traits that diff --git a/abi_stable/src/macros.rs b/abi_stable/src/macros.rs index 8e71ac8b..cd536907 100644 --- a/abi_stable/src/macros.rs +++ b/abi_stable/src/macros.rs @@ -239,6 +239,25 @@ macro_rules! check_unerased { /// /// ``` /// +/// # Returing in `no_early_return` +/// +/// Attempting to do any kind of returning from inside of +/// `extern_fn_panic_handling!{no_early_return}` +/// will cause an abort: +/// +/// ```should_panic +/// use abi_stable::extern_fn_panic_handling; +/// +/// pub extern "C" fn function() { +/// extern_fn_panic_handling!{no_early_return; +/// return; +/// } +/// } +/// +/// function(); +/// +/// ``` +/// /// #[macro_export] macro_rules! extern_fn_panic_handling { @@ -298,7 +317,7 @@ macro_rules! extern_fn_panic_handling { /// { /// type Interface = (); /// -/// const INFO: &'static TypeInfo = impl_get_type_info! { Foo }; +/// const INFO: &'static TypeInfo = impl_get_type_info! {Self}; /// } /// /// @@ -472,7 +491,7 @@ macro_rules! make_item_info { #[macro_export] macro_rules! rvec { ( $( $anything:tt )* ) => ( - $crate::std_types::RVec::from(vec![ $($anything)* ]) + $crate::std_types::RVec::from($crate::pmr::vec![ $($anything)* ]) ) } diff --git a/readme.md b/readme.md index 22e48567..4b8c555e 100644 --- a/readme.md +++ b/readme.md @@ -608,10 +608,17 @@ required until this library is updated to automatically detect them. Features: -- "rust_1_51": Enables impls which require using const generics, +- "rust_1_46": Makes some functions `const fn`s that are otherwise not `const`, +this is documented in each function for which it applies. + +- "rust_1_51_0": +Enables impls which require using const generics, including implementing StableAbi for arrays of all lengths, requires Rust Rust 1.51.0 or higher. +- "rust_latest_stable": +Enables the "rust_1_*" features for all the stable releases. + # Tools Here are some tools,all of which are in the "tools" directory(folder). From 5e5883a997134536df5806fb3d5d49ebf4b21c6e Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Wed, 27 Oct 2021 06:39:18 -0300 Subject: [PATCH 20/32] Made libraries always get leaked I was always kind of sketchy that they could get unloaded. --- abi_stable/src/library.rs | 10 +++++----- abi_stable/src/library/lib_header.rs | 6 ++++++ abi_stable/src/library/root_mod_trait.rs | 15 ++++++--------- abi_stable/src/std_types/std_error.rs | 3 +++ 4 files changed, 20 insertions(+), 14 deletions(-) diff --git a/abi_stable/src/library.rs b/abi_stable/src/library.rs index cab99173..199ea2c4 100644 --- a/abi_stable/src/library.rs +++ b/abi_stable/src/library.rs @@ -6,19 +6,19 @@ //! When you use the [`RootModule`]`::load_from*` associated functions, //! the root module of a library is loaded in this order: //! 1. A [`RawLibrary`] is loaded +//! (The library is leaked so that the root module loader can +//! do anything incompatible with library unloading.) //! 2. An [`AbiHeaderRef`] handle to the static that contains the root module is obtained. //! 3. The [`AbiHeaderRef`] checks that the abi_stable version used by that library is //! compatible with the loader's, upgrading to a [`&'static LibHeader`] on success. //! 4. The [`LibHeader`] checks that the layout of the types in the root module //! (and everything it references) are compatible with the loader's -//! 5. The library is leaked so that the root module loader can -//! do anything incompatible with library unloading. -//! 6. The [root module](./trait.RootModule.html) +//! 5. The [root module](./trait.RootModule.html) //! is loaded using the function from the loaded library //! that was annotated with [`#[export_root_module]`](../attr.export_root_module.html). -//! 7. [`RootModule::initialize`] is called on the root module. +//! 6. [`RootModule::initialize`] is called on the root module. //! -//! All steps (except for step 5) can return errors. +//! All steps can return errors. //! //! [`RawLibrary`]: ./struct.RawLibrary.html //! [`AbiHeaderRef`]: ./struct.AbiHeaderRef.html diff --git a/abi_stable/src/library/lib_header.rs b/abi_stable/src/library/lib_header.rs index a25ce3d2..a305ea69 100644 --- a/abi_stable/src/library/lib_header.rs +++ b/abi_stable/src/library/lib_header.rs @@ -219,6 +219,9 @@ impl LibHeader { .map_err(|e| { // Fixes the bug where printing the error causes a segfault because it // contains static references and function pointers into the unloaded library. + // + // This isn't strictly required anymore because abi_stable doesn't + // unload libraries right now. let formatted = e.to_formatted_error(); LibraryError::AbiInstability(formatted) })?; @@ -279,6 +282,9 @@ impl LibHeader { .map_err(|mut err| { // Making sure that the error doesn't contain references into // the unloaded library. + // + // This isn't strictly required anymore because abi_stable doesn't + // unload libraries right now. err.reallocate(); err })? diff --git a/abi_stable/src/library/root_mod_trait.rs b/abi_stable/src/library/root_mod_trait.rs index d6889524..5fdca558 100644 --- a/abi_stable/src/library/root_mod_trait.rs +++ b/abi_stable/src/library/root_mod_trait.rs @@ -168,24 +168,21 @@ pub trait RootModule: Sized + StableAbi + PrefixRefTrait + 'static { let statics = Self::root_module_statics(); statics.root_mod.try_init(|| { let mut items_ = None; - statics.raw_lib.try_init(|| -> Result<_, LibraryError> { + let lib = statics.raw_lib.try_init(|| -> Result<_, LibraryError> { let raw_library = load_raw_library::(where_)?; - let items = unsafe { lib_header_from_raw_library(&raw_library)? }; - - items.ensure_layout::()?; - items_ = Some(items); // if the library isn't leaked // it would cause any use of the module to be a use after free. // - // By leaking the library after type checking, - // but before calling the root module loader, + // By leaking the library // this allows the root module loader to do anything that'd prevent // sound library unloading. - // Nothing that can be done about static initializers that prevent - // library unloading though <_<. Ok(leak_value(raw_library)) })?; + let items = unsafe { lib_header_from_raw_library(lib)? }; + + items.ensure_layout::()?; + items_ = Some(items); // safety: the layout was checked in the closure above, unsafe { diff --git a/abi_stable/src/std_types/std_error.rs b/abi_stable/src/std_types/std_error.rs index c40ad517..a4566b39 100644 --- a/abi_stable/src/std_types/std_error.rs +++ b/abi_stable/src/std_types/std_error.rs @@ -346,6 +346,9 @@ impl RBoxError_ { /// This is used to decouple an `RBoxError` from the dynamic library that produced it, /// in order to unload the dynamic library. /// + // This isn't strictly required anymore because abi_stable doesn't + // unload libraries right now. + /// pub fn to_formatted_error(&self) -> RBoxError_ { if let Some(dd) = self.as_debug_display() { RBoxError_::from_debug_display(DebugDisplay { From 173a0f80385bcb84255857d016cf2de19b6cd71d Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Wed, 27 Oct 2021 07:37:46 -0300 Subject: [PATCH 21/32] Fixed all `abi_stable_derive` warnings (rustc and clippy) --- abi_stable_derive/src/fn_pointer_extractor.rs | 23 +----- .../src/get_static_equivalent.rs | 1 + abi_stable_derive/src/lib.rs | 2 +- abi_stable_derive/src/parse_utils.rs | 2 +- abi_stable_derive/src/sabi_extern_fn_impl.rs | 2 +- abi_stable_derive/src/sabi_trait.rs | 1 + .../src/sabi_trait/attribute_parsing.rs | 31 ++++---- .../src/sabi_trait/common_tokens.rs | 24 +------ .../src/sabi_trait/trait_definition.rs | 42 ++--------- abi_stable_derive/src/stable_abi.rs | 11 +-- .../src/stable_abi/attribute_parsing.rs | 8 +-- .../src/stable_abi/common_tokens.rs | 71 +++---------------- .../src/stable_abi/nonexhaustive.rs | 16 +++-- .../src/stable_abi/prefix_types.rs | 6 +- as_derive_utils/src/utils.rs | 6 +- 15 files changed, 61 insertions(+), 185 deletions(-) diff --git a/abi_stable_derive/src/fn_pointer_extractor.rs b/abi_stable_derive/src/fn_pointer_extractor.rs index 03e60dd9..aa5b494b 100644 --- a/abi_stable_derive/src/fn_pointer_extractor.rs +++ b/abi_stable_derive/src/fn_pointer_extractor.rs @@ -8,7 +8,6 @@ use as_derive_utils::{spanned_err, syn_err}; use core_extensions::SelfOps; use syn::{ - punctuated::Punctuated, spanned::Spanned, visit_mut::{self, VisitMut}, Generics, Ident, Lifetime, Type, TypeBareFn, TypeReference, @@ -90,22 +89,6 @@ pub(crate) struct FnParamRet<'a> { pub(crate) param_or_ret: ParamOrReturn, } -impl<'a> FnParamRet<'a> { - /// Constructs an `FnParamRet` for a `()` return type. - pub fn unit_ret(arenas: &'a Arenas) -> Self { - let unit = syn::TypeTuple { - paren_token: Default::default(), - elems: Punctuated::default(), - }; - FnParamRet { - name: None, - lifetime_refs: Vec::new(), - ty: arenas.alloc(syn::Type::from(unit)), - param_or_ret: ParamOrReturn::Return, - } - } -} - /// The information returned from visiting a field. pub(crate) struct VisitFieldRet<'a> { /// The lifetimes that the field references. @@ -130,7 +113,7 @@ impl<'a> TypeVisitor<'a> { allow_type_macros: false, referenced_lifetimes: Vec::default(), fn_info: FnInfo { - parent_generics: &generics, + parent_generics: generics, env_lifetimes: generics.lifetimes().map(|lt| <.lifetime.ident).collect(), initial_bound_lifetime: generics.lifetimes().count(), functions: Vec::new(), @@ -162,8 +145,8 @@ impl<'a> TypeVisitor<'a> { pub fn visit_field(&mut self, ty: &mut Type) -> VisitFieldRet<'a> { self.visit_type_mut(ty); VisitFieldRet { - referenced_lifetimes: mem::replace(&mut self.vars.referenced_lifetimes, Vec::new()), - functions: mem::replace(&mut self.vars.fn_info.functions, Vec::new()), + referenced_lifetimes: mem::take(&mut self.vars.referenced_lifetimes), + functions: mem::take(&mut self.vars.fn_info.functions), } } diff --git a/abi_stable_derive/src/get_static_equivalent.rs b/abi_stable_derive/src/get_static_equivalent.rs index a82a3c66..27a4f748 100644 --- a/abi_stable_derive/src/get_static_equivalent.rs +++ b/abi_stable_derive/src/get_static_equivalent.rs @@ -31,6 +31,7 @@ pub(crate) fn derive(data: DeriveInput) -> Result { #gse_equiv_impl ); + #[allow(clippy::if_then_panic)] if config.debug_print { panic!("\n\n\n{}\n\n\n", ret); } diff --git a/abi_stable_derive/src/lib.rs b/abi_stable_derive/src/lib.rs index 3079c3f3..470a4e90 100644 --- a/abi_stable_derive/src/lib.rs +++ b/abi_stable_derive/src/lib.rs @@ -6,10 +6,10 @@ // #![deny(unused_parens)] // #![deny(unused_assignments)] // #![deny(unused_mut)] +#![allow(clippy::field_reassign_with_default)] #![deny(unreachable_patterns)] #![deny(unused_doc_comments)] #![deny(unconditional_recursion)] -#![allow(clippy::suspicious_assignment_formatting)] extern crate proc_macro; diff --git a/abi_stable_derive/src/parse_utils.rs b/abi_stable_derive/src/parse_utils.rs index 1a612bad..d339ea1a 100644 --- a/abi_stable_derive/src/parse_utils.rs +++ b/abi_stable_derive/src/parse_utils.rs @@ -16,7 +16,7 @@ use proc_macro2::Span; //use crate::utils::SynResultExt; pub(crate) fn parse_str_as_ident(lit: &str) -> syn::Ident { - syn::Ident::new(&lit, Span::call_site()) + syn::Ident::new(lit, Span::call_site()) } pub(crate) fn parse_str_as_path(lit: &str) -> Result { diff --git a/abi_stable_derive/src/sabi_extern_fn_impl.rs b/abi_stable_derive/src/sabi_extern_fn_impl.rs index 51f9ac96..5477da7b 100644 --- a/abi_stable_derive/src/sabi_extern_fn_impl.rs +++ b/abi_stable_derive/src/sabi_extern_fn_impl.rs @@ -45,7 +45,7 @@ pub(crate) fn convert_to_sabi_extern_fn(with_early_return: WithEarlyReturn, item name: Some(syn::LitStr::new("C", Span::call_site())), }); - let statements = mem::replace(&mut item.block.stmts, Vec::new()); + let statements = mem::take(&mut item.block.stmts); let x = quote! { ::abi_stable::extern_fn_panic_handling!( diff --git a/abi_stable_derive/src/sabi_trait.rs b/abi_stable_derive/src/sabi_trait.rs index b59a2ab8..9611e46a 100644 --- a/abi_stable_derive/src/sabi_trait.rs +++ b/abi_stable_derive/src/sabi_trait.rs @@ -159,6 +159,7 @@ pub fn derive_sabi_trait(item: ItemTrait) -> Result { } ) .observe(|tokens| { + #[allow(clippy::if_then_panic)] // drop(_measure_time1); if config.debug_print_trait { panic!("\n\n\n{}\n\n\n", token_stream_to_string(tokens.clone())); diff --git a/abi_stable_derive/src/sabi_trait/attribute_parsing.rs b/abi_stable_derive/src/sabi_trait/attribute_parsing.rs index c853bc05..3d7cb34f 100644 --- a/abi_stable_derive/src/sabi_trait/attribute_parsing.rs +++ b/abi_stable_derive/src/sabi_trait/attribute_parsing.rs @@ -2,7 +2,7 @@ use super::{TraitDefinition, *}; use std::{iter, mem}; -use syn::{Attribute, Ident, ItemTrait, Meta, MetaList, NestedMeta, TraitItem, TraitItemMethod}; +use syn::{Attribute, ItemTrait, Meta, MetaList, NestedMeta, TraitItem, TraitItemMethod}; #[allow(unused_imports)] use core_extensions::SelfOps; @@ -104,8 +104,8 @@ pub(super) struct SabiTraitAttrs<'a> { /// Used as context while parsing helper attributes of #[sabi_trait]. #[derive(Debug, Copy, Clone)] -enum ParseContext<'a> { - TraitAttr { name: &'a Ident }, +enum ParseContext { + TraitAttr, Method { index: usize }, } @@ -130,14 +130,7 @@ pub(crate) fn parse_attrs_for_sabi_trait<'a>( this.disable_inherent_default.resize(assoc_fns.len(), false); - parse_inner( - &mut this, - &*trait_.attrs, - ParseContext::TraitAttr { - name: &trait_.ident, - }, - arenas, - )?; + parse_inner(&mut this, &*trait_.attrs, ParseContext::TraitAttr, arenas)?; for (index, assoc_fn) in assoc_fns.iter().cloned().enumerate() { this.methods_with_attrs.push(MethodWithAttrs::new(assoc_fn)); @@ -169,7 +162,7 @@ pub(crate) fn parse_attrs_for_sabi_trait<'a>( fn parse_inner<'a, I>( this: &mut SabiTraitAttrs<'a>, attrs: I, - pctx: ParseContext<'a>, + pctx: ParseContext, arenas: &'a Arenas, ) -> Result<(), syn::Error> where @@ -181,7 +174,7 @@ where parse_attr_list(this, pctx, list, arenas)?; } Ok(other_attr) => match pctx { - ParseContext::TraitAttr { .. } => { + ParseContext::TraitAttr => { this.attrs.other_attrs.push(other_attr); } ParseContext::Method { .. } => { @@ -204,7 +197,7 @@ where /// Parses the list attributes on an item. fn parse_attr_list<'a>( this: &mut SabiTraitAttrs<'a>, - pctx: ParseContext<'a>, + pctx: ParseContext, list: MetaList, arenas: &'a Arenas, ) -> Result<(), syn::Error> { @@ -235,11 +228,11 @@ fn parse_attr_list<'a>( /// Parses the `#[sabi()]` attributes on an item. fn parse_sabi_trait_attr<'a>( this: &mut SabiTraitAttrs<'a>, - pctx: ParseContext<'a>, + pctx: ParseContext, attr: Meta, _arenas: &'a Arenas, ) -> Result<(), syn::Error> { - fn push_attr<'a>(this: &mut SabiTraitAttrs<'a>, pctx: ParseContext<'a>, attr: Meta) { + fn push_attr(this: &mut SabiTraitAttrs<'_>, pctx: ParseContext, attr: Meta) { match pctx { ParseContext::Method { .. } => { this.methods_with_attrs @@ -249,7 +242,7 @@ fn parse_sabi_trait_attr<'a>( .derive_attrs .push(attr); } - ParseContext::TraitAttr { .. } => { + ParseContext::TraitAttr => { this.attrs.derive_attrs.push(attr); } } @@ -267,7 +260,7 @@ fn parse_sabi_trait_attr<'a>( if ident == "no_default_fallback" { match pctx { - ParseContext::TraitAttr { .. } => { + ParseContext::TraitAttr => { for is_disabled in &mut this.disable_inherent_default { *is_disabled = true; } @@ -278,7 +271,7 @@ fn parse_sabi_trait_attr<'a>( } } else if ident == "debug_print_trait" { this.debug_print_trait = true; - } else if let ParseContext::TraitAttr { .. } = pctx { + } else if let ParseContext::TraitAttr = pctx { if ident == "use_dyntrait" || ident == "use_dyn_trait" { this.which_object = WhichObject::DynTrait; } else if ident == "no_trait_impl" { diff --git a/abi_stable_derive/src/sabi_trait/common_tokens.rs b/abi_stable_derive/src/sabi_trait/common_tokens.rs index 7b158eee..88ebc252 100644 --- a/abi_stable_derive/src/sabi_trait/common_tokens.rs +++ b/abi_stable_derive/src/sabi_trait/common_tokens.rs @@ -89,8 +89,6 @@ declare_common_tokens! { token_streams[ self_sized="Self:Sized,", - makevtable_typarams="IA,_Self,_ErasedPtr,_OrigPtr,", - vtable_typarams="_Self,_ErasedPtr,", ptr_ref_bound= "_ErasedPtr: __sabi_re::AsPtr,", @@ -106,7 +104,6 @@ declare_common_tokens! { empty_ts="", ts_empty="", - ts_self ="Self", ts_uself="_Self,", ts_self_colon2 ="Self::", @@ -114,7 +111,6 @@ declare_common_tokens! { ts_make_vtable_args="Downcasting,_OrigPtr::PtrTarget,_OrigPtr::TransmutedPtr,_OrigPtr,", ts_erasedptr_and2="_ErasedPtr,_ErasedPtr2,", - ts_erasedptr="_ErasedPtr,", ts_self_erasedptr="_Self,_ErasedPtr,", ts_unit_erasedptr="(),_ErasedPtr,", ts_unit_rref_unit="(),__sabi_re::RRef<'_sub,()>,", @@ -125,34 +121,20 @@ declare_common_tokens! { ] types[ - empty_tuple="()", self_ty="Self", ] idents[ - default_trait="__DefaultTrait", - the_trait="__Trait", - u_erased_ptr="_ErasedPtr", - nope_ident="__NOPE__", - self_ident="self", - uself_ident="_self", u_capself="_Self", - capself="Self", ] lifetime[ static_lifetime="'static", - under_lifetime="'_", - uself_lifetime="'_self", ] - str_lits[ - c_abi_lit="C", - ] + str_lits[] - patterns[ - ignored_pat="_", - ] + patterns[] token[ unsafe_=Unsafe, @@ -229,8 +211,6 @@ declare_lifetime_tokens! { lt_rbox="__sabi_re::RBox<()>,", lt_rref="__sabi_re::RRef<'_sub,()>,", lt_rmut="__sabi_re::RMut<'_sub,()>,", - lt_ref="&'_sub(),", - lt_mut="&'_sub mut (),", lt_sub_lt="'_sub,", ] one_lifetime_tokens=[ diff --git a/abi_stable_derive/src/sabi_trait/trait_definition.rs b/abi_stable_derive/src/sabi_trait/trait_definition.rs index 2078ff32..640d356c 100644 --- a/abi_stable_derive/src/sabi_trait/trait_definition.rs +++ b/abi_stable_derive/src/sabi_trait/trait_definition.rs @@ -28,7 +28,7 @@ use syn::{ token::{Colon, Comma, Semi}, visit_mut::VisitMut, Abi, Block, FnArg, Ident, ItemTrait, Lifetime, LifetimeDef, Meta, TraitItem, TypeParamBound, - Visibility, WherePredicate, + WherePredicate, }; use proc_macro2::Span; @@ -63,7 +63,7 @@ pub(crate) struct TraitDefinition<'a> { #[allow(dead_code)] /// The path for the implemented serde::Deserialize trait /// (it may reference some trait lifetime parameter) - pub(crate) deserialize_bound: Option>, + pub(crate) deserialize_bound: Option, /// The traits this has as supertraits. pub(crate) impld_traits: Vec>, /// The traits this doesn't have as supertraits. @@ -97,7 +97,6 @@ pub(crate) struct TraitDefinition<'a> { /// A TokenStream with the equivalent of `::` pub(crate) ts_fq_self: &'a TokenStream2, pub(crate) ctokens: &'a CommonTokens, - pub(crate) arenas: &'a Arenas, } //////////////////////////////////////////////////////////////////////////////// @@ -127,7 +126,7 @@ impl<'a> TraitDefinition<'a> { .into_iter() .zip(disable_inherent_default) .filter_map(|(func, disable_inh_def)| { - match TraitMethod::new(func, disable_inh_def, &trait_.vis, ctokens, arenas) { + match TraitMethod::new(func, disable_inh_def, ctokens, arenas) { Ok(x) => x, Err(e) => { errors.push_err(e); @@ -261,7 +260,6 @@ impl<'a> TraitDefinition<'a> { ts_fq_self: arenas.alloc(ts_fq_self), is_static, ctokens, - arenas, }) } @@ -399,12 +397,8 @@ impl<'a> TraitDefinition<'a> { #[derive(Debug, Clone)] pub(crate) struct TraitMethod<'a> { pub(crate) disable_inherent_default: bool, - /// A refernce to the `syn` type this was derived from. - pub(crate) item: &'a syn::TraitItemMethod, pub(crate) unsafety: Option<&'a Unsafe>, pub(crate) abi: Option<&'a Abi>, - /// The visibility of the trait - pub(crate) vis: &'a Visibility, /// Attributes applied to the method in the vtable. pub(crate) derive_attrs: &'a [Meta], /// Attributes applied to the method in the trait definition. @@ -427,7 +421,6 @@ pub(crate) struct TraitMethod<'a> { /// The semicolon token for the method /// (when the method did not have a default implementation). pub(crate) semicolon: Option<&'a Semi>, - pub(crate) ctokens: &'a CommonTokens, } #[derive(Debug, Clone)] @@ -451,7 +444,6 @@ impl<'a> TraitMethod<'a> { pub fn new( mwa: MethodWithAttrs<'a>, disable_inherent_default: bool, - vis: &'a Visibility, ctokens: &'a CommonTokens, arena: &'a Arenas, ) -> Result, syn::Error> { @@ -558,10 +550,8 @@ impl<'a> TraitMethod<'a> { Ok(Some(Self { disable_inherent_default, - item: &mwa.item, unsafety: method_signature.unsafety.as_ref(), abi: method_signature.abi.as_ref(), - vis, derive_attrs: arena.alloc(mwa.attrs.derive_attrs), other_attrs: arena.alloc(mwa.attrs.other_attrs), name, @@ -573,7 +563,6 @@ impl<'a> TraitMethod<'a> { where_clause, default, semicolon: mwa.item.semi_token.as_ref(), - ctokens, })) } @@ -698,10 +687,7 @@ impl<'a> ToTokens for GenericsTokenizer<'a> { /// Represents a `Deserialize<'de>` supertrait bound. #[derive(Debug, Clone)] -pub(crate) struct DeserializeBound<'a> { - pub(crate) bound: &'a syn::TraitBound, - pub(crate) lifetime: &'a syn::Lifetime, -} +pub(crate) struct DeserializeBound; /// Used to returns the information about supertraits,to construct TraitDefinition. struct GetSupertraits<'a> { @@ -709,7 +695,7 @@ struct GetSupertraits<'a> { unimpld_traits: Vec<&'a Ident>, lifetime_bounds: Punctuated<&'a Lifetime, Comma>, iterator_item: Option<&'a syn::Type>, - deserialize_bound: Option>, + deserialize_bound: Option, trait_flags: TraitStruct, trait_spans: TraitStruct, errors: LinearResult<()>, @@ -718,8 +704,6 @@ struct GetSupertraits<'a> { /// Contains information about a supertrait,including whether it's implemented. #[derive(Debug, Clone)] pub(crate) struct TraitImplness<'a> { - pub(crate) which_trait: WhichTrait, - pub(crate) name: &'static str, pub(crate) ident: Ident, pub(crate) bound: syn::TraitBound, pub(crate) is_implemented: bool, @@ -745,8 +729,6 @@ where // A struct indexable by `WhichTrait`, // with information about all possible supertraits. let mut trait_struct = TraitStruct::TRAITS.map(|_, t| TraitImplness { - which_trait: t.which_trait, - name: t.name, ident: parse_str_as_ident(t.name), bound: parse_str_as_trait_bound(t.full_path).expect("BUG"), is_implemented: false, @@ -767,7 +749,7 @@ where }; let trait_ident = &last_path_component.ident; - match trait_map.get(&trait_ident) { + match trait_map.get(trait_ident) { Some(&which_trait) => { let usable_by = which_trait.usable_by(); match which_object { @@ -809,18 +791,6 @@ where iterator_item = iterator_item.or(iter_item); } WhichTrait::Deserialize => { - // deserialize_bound=deserialize_bound.or(Some( - // DeserializeBound{ - // bound:trait_bound - // .clone() - // .piped(|x| arenas.alloc(x) ), - // lifetime: - // extract_deserialize_lifetime( - // last_path_component, - // arenas - // ), - // } - // )); errors.push_err(spanned_err!( trait_bound.path, "Deserialize is not currently supported." diff --git a/abi_stable_derive/src/stable_abi.rs b/abi_stable_derive/src/stable_abi.rs index e6b6c58c..07435a51 100644 --- a/abi_stable_derive/src/stable_abi.rs +++ b/abi_stable_derive/src/stable_abi.rs @@ -228,7 +228,7 @@ pub(crate) fn derive(mut data: DeriveInput) -> Result } else if is_opaque_field { quote!(__sabi_re::False) } else { - let ty = visited_field.comp_field.type_(&shared_vars); + let ty = visited_field.comp_field.type_(shared_vars); quote!( <#ty as __StableAbi>::IsNonZeroType ) } } else { @@ -387,7 +387,7 @@ pub(crate) fn derive(mut data: DeriveInput) -> Result let extra_bounds = &config.extra_bounds; let prefix_type_tokenizer_ = - prefix_type_tokenizer(&module, &mono_type_layout, &ds, config, ctokens)?; + prefix_type_tokenizer(&module, mono_type_layout, ds, config, ctokens)?; let mod_refl_mode = match config.mod_refl_mode { ModReflMode::Module => quote!(__ModReflMode::Module), @@ -422,7 +422,7 @@ pub(crate) fn derive(mut data: DeriveInput) -> Result // The storage type parameter that is added if this is a nonexhaustive enum. let storage_opt = nonexh_opt.map(|_| &ctokens.und_storage); let generics_header = - GenParamsIn::with_after_types(&ds.generics, InWhat::ImplHeader, storage_opt); + GenParamsIn::with_after_types(ds.generics, InWhat::ImplHeader, storage_opt); shared_vars.extract_errs()?; @@ -431,7 +431,7 @@ pub(crate) fn derive(mut data: DeriveInput) -> Result let strings_const = &config.const_idents.strings; let strings = shared_vars.strings().piped(rstr_tokenizer); - let shared_vars_tokenizer = shared_vars.shared_vars_tokenizer(&mono_type_layout); + let shared_vars_tokenizer = shared_vars.shared_vars_tokenizer(mono_type_layout); // drop(_measure_time0); // let _measure_time1=PrintDurationOnDrop::new(abi_stable_shared::file_span!()); @@ -578,6 +578,7 @@ pub(crate) fn derive(mut data: DeriveInput) -> Result } ) .observe(|tokens| { + #[allow(clippy::if_then_panic)] // drop(_measure_time1); if config.debug_print { panic!("\n\n\n{}\n\n\n", tokens); @@ -689,7 +690,7 @@ fn fields_tokenizer_inner<'a>( to_stream!(ts;ct.some); ct.paren.surround(ts, |ts| { ct.and_.to_tokens(ts); - tokenize_tl_functions(ds, &visited_fields, ct, ts); + tokenize_tl_functions(ds, visited_fields, ct, ts); }); } to_stream! {ts; ct.comma }; diff --git a/abi_stable_derive/src/stable_abi/attribute_parsing.rs b/abi_stable_derive/src/stable_abi/attribute_parsing.rs index d2e607e1..fe0a6f87 100644 --- a/abi_stable_derive/src/stable_abi/attribute_parsing.rs +++ b/abi_stable_derive/src/stable_abi/attribute_parsing.rs @@ -589,16 +589,16 @@ fn parse_sabi_attr<'a>( let renamed = value.parse::()?.piped(|x| arenas.alloc(x)); this.renamed_fields.insert(field, Some(renamed)); } else if ident == "unsafe_change_type" { - let changed_type = parse_lit_as_type(&value)?.piped(|x| arenas.alloc(x)); + let changed_type = parse_lit_as_type(value)?.piped(|x| arenas.alloc(x)); this.changed_types.insert(field, Some(changed_type)); } else if ident == "accessible_if" { - let expr = arenas.alloc(parse_lit_as_expr(&value)?); + let expr = arenas.alloc(parse_lit_as_expr(value)?); this.prefix_kind_fields[field].accessible_if = Some(expr); } else if ident == "accessor_bound" { - let bound = parse_lit_as_type_bounds(&value)?; + let bound = parse_lit_as_type_bounds(value)?; this.accessor_bounds[field].extend(bound); } else if ident == "bound" { - let bounds = parse_lit_as_type_bounds(&value)?; + let bounds = parse_lit_as_type_bounds(value)?; let preds = where_predicate_from(field.ty.clone(), bounds); this.extra_bounds.push(preds); } else { diff --git a/abi_stable_derive/src/stable_abi/common_tokens.rs b/abi_stable_derive/src/stable_abi/common_tokens.rs index 43b36f42..2d745201 100644 --- a/abi_stable_derive/src/stable_abi/common_tokens.rs +++ b/abi_stable_derive/src/stable_abi/common_tokens.rs @@ -2,11 +2,14 @@ //! used to pass constants of type from `syn` to //! many functions in the `abi_stable_derive_lib::stable_abi` module. -use proc_macro2::Span; +use proc_macro2::{Span, TokenStream as TokenStream2}; -use crate::{fn_pointer_extractor::FnParamRet, *}; +use std::{ + cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}, + marker::PhantomData, +}; -use std::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}; +use crate::Arenas; macro_rules! declare_common_tokens { ( @@ -27,7 +30,7 @@ macro_rules! declare_common_tokens { $( pub(crate) $field_ident : ::syn::Ident , )* $( pub(crate) $lifetime_ident : ::syn::Lifetime , )* $( pub(crate) $strlit_ident : ::syn::LitStr , )* - pub(crate) unit_ret:FnParamRet<'a>, + _marker: PhantomData<&'a ()>, } impl<'a> CommonTokens<'a>{ @@ -42,7 +45,7 @@ macro_rules! declare_common_tokens { $( $field_ident : ::syn::Ident::new($ident_str,span) , )* $( $lifetime_ident : ::syn::parse_str($lifetime_str).expect("BUG") , )* $( $strlit_ident : ::syn::LitStr::new($strlit_str,span) , )* - unit_ret:FnParamRet::unit_ret(arenas), + _marker: PhantomData, } } } @@ -83,26 +86,17 @@ declare_common_tokens! { ] token[ - dot=Dot, and_=And, - add=Add, - bang=Bang, comma=Comma, equal=Eq, - semicolon=Semi, - colon=Colon, colon2=Colon2, - brace=Brace, bracket=Bracket, paren=Paren, - pound=Pound, lt=Lt, gt=Gt, - as_=As, ] token_streams[ - ts_empty="", und_storage="__Storage,", ] @@ -111,69 +105,20 @@ declare_common_tokens! { ] idents[ - cratename="abi_stable", some="Some", none="None", - rsome="__RSome", - rnone="__RNone", - tl_field="__TLField", - tl_functions="__TLFunctions", - comp_tl_function="__CompTLFunction", - value_kind ="__ValueKind", - prefix_kind="__PrefixKind", - tl_data="__TLData", - struct_="struct", - struct_under="struct_derive", - union_under="union_derive", - enum_under="enum_derive", - prefix_type="prefix_type_derive", - cap_repr_transparent="ReprTransparent", - cap_prefix_type="PrefixType", new="new", - env="env", - name="name", - fields="fields", - field_1to1="__Field1to1", comp_tl_fields="__CompTLFields", - slice_and_field_indices="__SAFI", - with_field_index="__WithFieldIndex", - from_vari_field_val="from_vari_field_val", - instantiate_field="instantiate_field", - lifetime_indices="lifetime_indices", - stable_abi="__StableAbi", - type_identity="TypeIdentity", - marker_type="MarkerType", - assert_zero_sized="__assert_zero_sized", //layout="LAYOUT", - get="get", - stable_abi_bound="__StableAbi_Bound", - unsafe_extern_fn_type_layout="__UNSAFE_EXTERN_FN_LAYOUT", - extern_fn_type_layout="__EXTERN_FN_LAYOUT", - get_type_layout_ctor="__GetTypeLayoutCtor", - sabi_reexports="_sabi_reexports", - cmp_ignored="__CmpIgnored", - lifetime_index="__LifetimeIndex", static_equivalent="__GetStaticEquivalent", - cap_static="Static", - cap_param="Param", - cap_const="CONST", cap_opaque_field="OPAQUE_FIELD", cap_sabi_opaque_field="SABI_OPAQUE_FIELD", - cap_stable_abi="STABLE_ABI", - subfields="subfields", - with_functions="with_functions", - underscore="_", - for_="for", - static_="static", - stringify_="stringify", ] lifetime[ - underscore_lt="'_", static_lt="'static", ] str_lits[ - c_abi_lit="C", ] } diff --git a/abi_stable_derive/src/stable_abi/nonexhaustive.rs b/abi_stable_derive/src/stable_abi/nonexhaustive.rs index 5b12a3ba..0bd2073d 100644 --- a/abi_stable_derive/src/stable_abi/nonexhaustive.rs +++ b/abi_stable_derive/src/stable_abi/nonexhaustive.rs @@ -207,10 +207,12 @@ impl<'a> NonExhaustive<'a> { }); for &trait_ in &enum_interface.unimpld { - if trait_map.remove(trait_).is_none() { - // This is an internal error. - panic!("Trait {} was not in TRAIT_LIST.", trait_); - } + // This is an internal error. + assert!( + trait_map.remove(trait_).is_some(), + "Trait {} was not in TRAIT_LIST.", + trait_ + ); } for (trait_, _) in trait_map { @@ -343,7 +345,7 @@ pub(crate) fn tokenize_nonexhaustive_items<'a>( let name = ds.name; - let generics_header = GenParamsIn::new(&ds.generics, InWhat::ImplHeader); + let generics_header = GenParamsIn::new(ds.generics, InWhat::ImplHeader); let mut type_generics_decl = GenParamsIn::new(ds.generics, InWhat::ImplHeader); type_generics_decl.set_no_bounds(); @@ -606,9 +608,9 @@ pub(crate) fn tokenize_enum_info<'a>( } let generics_header = - GenParamsIn::with_after_types(&ds.generics, InWhat::ImplHeader, &ct.und_storage); + GenParamsIn::with_after_types(ds.generics, InWhat::ImplHeader, &ct.und_storage); - let generics_use = GenParamsIn::new(&ds.generics, InWhat::ImplHeader); + let generics_use = GenParamsIn::new(ds.generics, InWhat::ImplHeader); let default_interface = &this.default_interface; diff --git a/abi_stable_derive/src/stable_abi/prefix_types.rs b/abi_stable_derive/src/stable_abi/prefix_types.rs index 60682d92..3f2d778e 100644 --- a/abi_stable_derive/src/stable_abi/prefix_types.rs +++ b/abi_stable_derive/src/stable_abi/prefix_types.rs @@ -175,8 +175,8 @@ impl<'a> AccessorOrMaybe<'a> { } /// Converts this to a MaybeAccessor,returning None if it is not the `Maybe` variant. - pub(crate) fn to_maybe_accessor(&self) -> Option> { - match *self { + pub(crate) fn to_maybe_accessor(self) -> Option> { + match self { AccessorOrMaybe::Maybe(x) => Some(x), _ => None, } @@ -437,7 +437,7 @@ accessible through [`{prefix_name}`](./struct.{prefix_name}.html), with `.0.pref }) => write!( acc_doc_buffer, "Returns `{function}()` if the field does not exist.", - function = (&function).into_token_stream().to_string() + function = (&function).into_token_stream() ) .drop_(), AOM::Maybe(MaybeAccessor { diff --git a/as_derive_utils/src/utils.rs b/as_derive_utils/src/utils.rs index 74b0d6db..3cd034ea 100644 --- a/as_derive_utils/src/utils.rs +++ b/as_derive_utils/src/utils.rs @@ -134,10 +134,10 @@ impl DerefMut for LinearResult { } } -impl Into> for LinearResult { +impl From> for Result { #[inline] - fn into(self) -> Result { - self.into_result() + fn from(this: LinearResult) -> Result { + this.into_result() } } From edfb2a97a7b5d7ecbc29c1f9f115f61e26f42da6 Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Wed, 27 Oct 2021 21:06:15 -0300 Subject: [PATCH 22/32] Fixed all rustc/clippy warnings in abi_stable Added safety section to `GetStaticEquivalent_` docs. Removed a bunch of redundant unsafe blocks,and made some vtable functions `unsafe` (exploiting the fact that function pointer unsafety isn't yet tracked, should add that to next version) Replaced all `impl Into for Bar` with `impl From for Foo`. Made the private `ErasedType` trait safe to implement Added a few is_empty methods to type_layout types for completeness. --- abi_stable/build.rs | 6 +- .../abi_stability/get_static_equivalent.rs | 12 +++ abi_stable/src/const_utils.rs | 7 +- abi_stable/src/erased_types/dyn_trait.rs | 8 +- abi_stable/src/erased_types/vtable.rs | 2 +- .../src/external_types/crossbeam_channel.rs | 4 +- .../src/external_types/parking_lot/mutex.rs | 1 + .../src/external_types/parking_lot/once.rs | 4 +- .../src/external_types/parking_lot/rw_lock.rs | 1 + abi_stable/src/inline_storage.rs | 6 +- abi_stable/src/lib.rs | 11 +-- abi_stable/src/library.rs | 5 +- abi_stable/src/library/c_abi_testing.rs | 8 +- abi_stable/src/library/lib_header.rs | 2 + abi_stable/src/library/root_mod_trait.rs | 20 ++-- abi_stable/src/macros.rs | 20 ++-- abi_stable/src/marker_type.rs | 2 +- abi_stable/src/multikey_map.rs | 8 +- abi_stable/src/nonexhaustive_enum.rs | 1 + .../src/nonexhaustive_enum/nonexhaustive.rs | 17 ++-- abi_stable/src/nonexhaustive_enum/vtable.rs | 20 +++- abi_stable/src/pointer_trait.rs | 6 +- abi_stable/src/prefix_type.rs | 4 + abi_stable/src/sabi_trait/vtable.rs | 30 +++++- abi_stable/src/sabi_types/late_static_ref.rs | 1 + abi_stable/src/sabi_types/move_ptr.rs | 3 +- abi_stable/src/sabi_types/nul_str.rs | 5 +- abi_stable/src/sabi_types/rmut.rs | 2 + abi_stable/src/sabi_types/rsmallbox.rs | 7 +- abi_stable/src/sabi_types/static_ref.rs | 2 +- abi_stable/src/std_types/arc.rs | 8 +- abi_stable/src/std_types/arc/test.rs | 4 +- abi_stable/src/std_types/boxed.rs | 8 +- abi_stable/src/std_types/boxed/test.rs | 4 +- abi_stable/src/std_types/map.rs | 92 +++++++++++-------- abi_stable/src/std_types/map/entry.rs | 4 +- abi_stable/src/std_types/map/extern_fns.rs | 48 +++++----- abi_stable/src/std_types/slice_mut.rs | 6 +- abi_stable/src/std_types/std_error.rs | 30 +++--- abi_stable/src/std_types/str.rs | 18 ++-- abi_stable/src/std_types/string.rs | 18 ++-- abi_stable/src/std_types/vec.rs | 13 +-- abi_stable/src/std_types/vec/iters.rs | 4 +- abi_stable/src/traits.rs | 7 +- abi_stable/src/type_layout.rs | 4 +- abi_stable/src/type_layout/construction.rs | 2 +- abi_stable/src/type_layout/printing.rs | 1 + abi_stable/src/type_layout/tl_data.rs | 4 +- abi_stable/src/type_layout/tl_multi_tl.rs | 2 +- abi_stable/src/utils.rs | 2 +- .../src/type_layout/tl_lifetimes_macro.rs | 18 +++- .../src/type_layout/tl_multi_tl_macro.rs | 22 +++-- 52 files changed, 309 insertions(+), 235 deletions(-) diff --git a/abi_stable/build.rs b/abi_stable/build.rs index 4aa183af..ae825f77 100644 --- a/abi_stable/build.rs +++ b/abi_stable/build.rs @@ -1,8 +1,8 @@ -use rustc_version::Channel; +// keeping the build.rs just in case that I want to detect +// newer language versions for soundness fixes that require them. fn main() { println!("cargo:rerun-if-changed=build.rs"); - println!("cargo:rerun-if-changed=../readme.md"); - let channel = rustc_version::version_meta().unwrap().channel; + let _channel = rustc_version::version_meta().unwrap().channel; } diff --git a/abi_stable/src/abi_stability/get_static_equivalent.rs b/abi_stable/src/abi_stability/get_static_equivalent.rs index 1cf9ea8d..97c923a1 100644 --- a/abi_stable/src/abi_stability/get_static_equivalent.rs +++ b/abi_stable/src/abi_stability/get_static_equivalent.rs @@ -3,6 +3,18 @@ /// A type that stands in for `Self`,used to create a `UTypeId` for doing layout checking. /// /// This may or may not have the same TypeId as Self. +/// +/// # Safety +/// +/// The `StaticEquivalent` associated type must be either of: +/// - the same type as `Self`, ignoring lifetime arguments. +/// - a type declared specifically to be the `StaticEquivalent` +/// associated type of `Self`(and no other type), +/// with the same type and const arguments as `Self`. +/// +/// In either case, non-`'static` type parameters can be replaced with their +/// `GetStaticEquivalent_::StaticEquivalent` associated type. +/// pub unsafe trait GetStaticEquivalent_ { type StaticEquivalent: 'static; } diff --git a/abi_stable/src/const_utils.rs b/abi_stable/src/const_utils.rs index 30d621bf..a408c5bf 100644 --- a/abi_stable/src/const_utils.rs +++ b/abi_stable/src/const_utils.rs @@ -141,13 +141,14 @@ pub const fn log2_usize(n: usize) -> u8 { /// since both types are required to be the same concrete type inside the macro. #[macro_export] macro_rules! type_identity { - ($from:ty=>$to:ty; $expr:expr ) => { + ($from:ty=>$to:ty; $expr:expr ) => {{ + let from = $expr; unsafe { let _: $crate::pmr::AssertEq<$from, $to>; - $crate::utils::Transmuter::<$from, $to> { from: $expr }.to + $crate::utils::Transmuter::<$from, $to> { from }.to } - }; + }}; } ////////////////////////////////////// diff --git a/abi_stable/src/erased_types/dyn_trait.rs b/abi_stable/src/erased_types/dyn_trait.rs index 6058dbf0..3c16d90f 100644 --- a/abi_stable/src/erased_types/dyn_trait.rs +++ b/abi_stable/src/erased_types/dyn_trait.rs @@ -1233,7 +1233,7 @@ mod priv_ { where P: AsPtr, { - unsafe { RRef::from_raw(self.object.as_ptr() as *const ErasedObject) } + RRef::from_raw(self.object.as_ptr() as *const ErasedObject) } /// Gets a mutable reference pointing to the erased object. @@ -1648,10 +1648,8 @@ mod priv_ { self.sabi_check_same_destructor::, T>() ); unsafe { - unsafe { - let this = ManuallyDrop::new(self); - Ok(ptr::read(&*this.object).transmute_element::()) - } + let this = ManuallyDrop::new(self); + Ok(ptr::read(&*this.object).transmute_element::()) } } diff --git a/abi_stable/src/erased_types/vtable.rs b/abi_stable/src/erased_types/vtable.rs index 8707dfda..66b3eafe 100644 --- a/abi_stable/src/erased_types/vtable.rs +++ b/abi_stable/src/erased_types/vtable.rs @@ -42,7 +42,7 @@ pub trait GetVtable<'borr, This, ErasedPtr, OrigPtr, I: InterfaceBound> { #[doc(hidden)] const _GET_INNER_VTABLE: VTable_Ref<'borr, ErasedPtr, I> = - unsafe { VTable_Ref(Self::_WM_VTABLE.as_prefix()) }; + VTable_Ref(Self::_WM_VTABLE.as_prefix()); } /// A helper type for constructing a `DynTrait` at compile-time, diff --git a/abi_stable/src/external_types/crossbeam_channel.rs b/abi_stable/src/external_types/crossbeam_channel.rs index 20bb0646..8892e795 100644 --- a/abi_stable/src/external_types/crossbeam_channel.rs +++ b/abi_stable/src/external_types/crossbeam_channel.rs @@ -759,7 +759,7 @@ where #[derive(StableAbi)] struct ErasedSender(PhantomData, UnsafeIgnoredType>); -unsafe impl ErasedType<'_> for ErasedSender { +impl ErasedType<'_> for ErasedSender { type Unerased = Sender; } @@ -767,7 +767,7 @@ unsafe impl ErasedType<'_> for ErasedSender { #[derive(StableAbi)] struct ErasedReceiver(PhantomData, UnsafeIgnoredType>); -unsafe impl ErasedType<'_> for ErasedReceiver { +impl ErasedType<'_> for ErasedReceiver { type Unerased = Receiver; } diff --git a/abi_stable/src/external_types/parking_lot/mutex.rs b/abi_stable/src/external_types/parking_lot/mutex.rs index 26b65694..56ac0c07 100644 --- a/abi_stable/src/external_types/parking_lot/mutex.rs +++ b/abi_stable/src/external_types/parking_lot/mutex.rs @@ -26,6 +26,7 @@ type OpaqueMutex = UnsafeOveralignedField; const OM_PADDING: usize = RAW_LOCK_SIZE - mem::size_of::(); +#[allow(clippy::declare_interior_mutable_const)] const OPAQUE_MUTEX: OpaqueMutex = OpaqueMutex::new(::INIT, [0u8; OM_PADDING]); diff --git a/abi_stable/src/external_types/parking_lot/once.rs b/abi_stable/src/external_types/parking_lot/once.rs index df397559..9a120c9f 100644 --- a/abi_stable/src/external_types/parking_lot/once.rs +++ b/abi_stable/src/external_types/parking_lot/once.rs @@ -24,6 +24,7 @@ type OpaqueOnce = UnsafeOveralignedField; const OM_PADDING: usize = RAW_LOCK_SIZE - mem::size_of::(); +#[allow(clippy::declare_interior_mutable_const)] const OPAQUE_ONCE: OpaqueOnce = OpaqueOnce::new(parking_lot::Once::new(), [0u8; OM_PADDING]); #[allow(dead_code)] @@ -99,6 +100,7 @@ impl ROnce { /// static ONCE: ROnce = ROnce::NEW; /// /// ``` + #[allow(clippy::declare_interior_mutable_const)] pub const NEW: Self = ROnce { opaque_once: OPAQUE_ONCE, vtable: VTable::VTABLE, @@ -511,8 +513,6 @@ where mod tests { use super::*; - use std::{thread, time::Duration}; - use crossbeam_utils::thread::scope as scoped_thread; use abi_stable_shared::{file_span, test_utils::must_panic}; diff --git a/abi_stable/src/external_types/parking_lot/rw_lock.rs b/abi_stable/src/external_types/parking_lot/rw_lock.rs index 98f92a72..36dfeb1b 100644 --- a/abi_stable/src/external_types/parking_lot/rw_lock.rs +++ b/abi_stable/src/external_types/parking_lot/rw_lock.rs @@ -26,6 +26,7 @@ type OpaqueRwLock = UnsafeOveralignedField; const OM_PADDING: usize = RAW_LOCK_SIZE - mem::size_of::(); +#[allow(clippy::declare_interior_mutable_const)] const OPAQUE_LOCK: OpaqueRwLock = OpaqueRwLock::new(::INIT, [0u8; OM_PADDING]); diff --git a/abi_stable/src/inline_storage.rs b/abi_stable/src/inline_storage.rs index 395c34c2..83bbc6f0 100644 --- a/abi_stable/src/inline_storage.rs +++ b/abi_stable/src/inline_storage.rs @@ -176,10 +176,8 @@ impl ScratchSpace { /// You must ensure that `Inline` is valid for all bitpatterns,ie:it implements `InlineStorage`. #[inline] pub(crate) unsafe fn uninit_unbounded() -> Self { - unsafe { - Self { - storage: std::mem::MaybeUninit::uninit(), - } + Self { + storage: std::mem::MaybeUninit::uninit(), } } } diff --git a/abi_stable/src/lib.rs b/abi_stable/src/lib.rs index 4ce7713f..035d8172 100644 --- a/abi_stable/src/lib.rs +++ b/abi_stable/src/lib.rs @@ -201,21 +201,14 @@ https://github.com/rodrimati1992/abi_stable_crates/blob/master/readme.md#readme_ // the true positives are caught by the StableAbi trait. #![allow(improper_ctypes)] #![allow(improper_ctypes_definitions)] -#![allow(unused_unsafe)] #![allow(non_camel_case_types)] #![deny(unused_must_use)] #![warn(rust_2018_idioms)] -#![allow(clippy::declare_interior_mutable_const)] #![allow(clippy::needless_doctest_main)] -#![allow(clippy::redundant_closure_call)] -#![allow(clippy::suspicious_assignment_formatting)] #![allow(clippy::zero_prefixed_literal)] #![allow(clippy::type_complexity)] -// This lint is telling me to use `#[non_exhaustive]` for structs that will never change, -// that is very silly. -#![allow(clippy::manual_non_exhaustive)] -#![allow(clippy::ptr_offset_with_cast)] #![allow(clippy::empty_loop)] +#![allow(clippy::ptr_offset_with_cast)] #![deny(clippy::missing_safety_doc)] #![cfg_attr(feature = "docsrs", feature(doc_cfg))] @@ -374,7 +367,7 @@ pub mod globals { #[inline(never)] pub fn initialized_globals() -> &'static Globals { - GLOBALS.init(|| Globals::new()) + GLOBALS.init(Globals::new) } #[inline(never)] diff --git a/abi_stable/src/library.rs b/abi_stable/src/library.rs index 199ea2c4..899235ef 100644 --- a/abi_stable/src/library.rs +++ b/abi_stable/src/library.rs @@ -52,7 +52,10 @@ pub mod c_abi_testing; pub mod development_utils; mod errors; mod lib_header; + +#[cfg(test)] mod library_tests; + mod raw_library; mod root_mod_trait; @@ -276,7 +279,7 @@ pub const ROOT_MODULE_LOADER_NAME_WITH_NUL: &str = PRIV_MANGLED_ROOT_MODULE_LOAD /// [`ROOT_MODULE_LOADER_NAME`]: ./constant.ROOT_MODULE_LOADER_NAME.html /// [`NulStr`]: ../sabi_types/struct.NulStr.html pub const ROOT_MODULE_LOADER_NAME_NULSTR: NulStr<'_> = - unsafe { NulStr::from_str(PRIV_MANGLED_ROOT_MODULE_LOADER_NAME_NUL) }; + NulStr::from_str(PRIV_MANGLED_ROOT_MODULE_LOADER_NAME_NUL); ////////////////////////////////////////////////////////////////////// diff --git a/abi_stable/src/library/c_abi_testing.rs b/abi_stable/src/library/c_abi_testing.rs index 196d3e45..623d03bd 100644 --- a/abi_stable/src/library/c_abi_testing.rs +++ b/abi_stable/src/library/c_abi_testing.rs @@ -19,10 +19,10 @@ pub use self::functions::{CAbiTestingFns, C_ABI_TESTING_FNS}; /// Tests that the abi (as defined by the compiler) of the functions in /// CAbiTestingFns is the same as the caller's. pub fn run_tests(funcs: &CAbiTestingFns) -> Result<(), LibraryError> { - pair_tests(&funcs)?; - triple_tests(&funcs)?; - two_pair_tests(&funcs)?; - mixed_units_test(&funcs)?; + pair_tests(funcs)?; + triple_tests(funcs)?; + two_pair_tests(funcs)?; + mixed_units_test(funcs)?; Ok(()) } diff --git a/abi_stable/src/library/lib_header.rs b/abi_stable/src/library/lib_header.rs index a305ea69..27fa4f36 100644 --- a/abi_stable/src/library/lib_header.rs +++ b/abi_stable/src/library/lib_header.rs @@ -349,6 +349,8 @@ impl std::ops::Deref for AbiHeaderRef { /// [`LibraryError::InvalidAbiHeader`]: ./enum.LibraryError.html#variant.InvalidAbiHeader #[repr(C)] #[derive(Debug, StableAbi, Copy, Clone)] +// This type will never have new fields clippy, that's the point <_< +#[allow(clippy::manual_non_exhaustive)] pub struct AbiHeader { /// A magic string used to check that this is actually abi_stable. pub magic_string: [u8; 32], diff --git a/abi_stable/src/library/root_mod_trait.rs b/abi_stable/src/library/root_mod_trait.rs index 5fdca558..cb2d4578 100644 --- a/abi_stable/src/library/root_mod_trait.rs +++ b/abi_stable/src/library/root_mod_trait.rs @@ -167,7 +167,6 @@ pub trait RootModule: Sized + StableAbi + PrefixRefTrait + 'static { fn load_from(where_: LibraryPath<'_>) -> Result { let statics = Self::root_module_statics(); statics.root_mod.try_init(|| { - let mut items_ = None; let lib = statics.raw_lib.try_init(|| -> Result<_, LibraryError> { let raw_library = load_raw_library::(where_)?; @@ -182,13 +181,10 @@ pub trait RootModule: Sized + StableAbi + PrefixRefTrait + 'static { let items = unsafe { lib_header_from_raw_library(lib)? }; items.ensure_layout::()?; - items_ = Some(items); - // safety: the layout was checked in the closure above, + // safety: the layout was checked in the code above, unsafe { - items_ - .as_ref() - .unwrap() + items .init_root_module_with_unchecked_layout::()? .initialization() } @@ -236,7 +232,7 @@ where M: RootModule, { let path = match where_ { - LibraryPath::Directory(directory) => M::get_library_path(&directory), + LibraryPath::Directory(directory) => M::get_library_path(directory), LibraryPath::FullPath(full_path) => full_path.to_owned(), }; RawLibrary::load_at(&path) @@ -263,7 +259,7 @@ where pub unsafe fn lib_header_from_raw_library( raw_library: &RawLibrary, ) -> Result<&'static LibHeader, LibraryError> { - unsafe { abi_header_from_raw_library(raw_library)?.upgrade() } + abi_header_from_raw_library(raw_library)?.upgrade() } /// Gets the AbiHeaderRef of a library. @@ -284,12 +280,10 @@ pub unsafe fn lib_header_from_raw_library( pub unsafe fn abi_header_from_raw_library( raw_library: &RawLibrary, ) -> Result { - unsafe { - let mangled = ROOT_MODULE_LOADER_NAME_WITH_NUL; - let header: AbiHeaderRef = *raw_library.get::(mangled.as_bytes())?; + let mangled = ROOT_MODULE_LOADER_NAME_WITH_NUL; + let header: AbiHeaderRef = *raw_library.get::(mangled.as_bytes())?; - Ok(header) - } + Ok(header) } /// Gets the LibHeader of the library at the path. diff --git a/abi_stable/src/macros.rs b/abi_stable/src/macros.rs index cd536907..682b7a4d 100644 --- a/abi_stable/src/macros.rs +++ b/abi_stable/src/macros.rs @@ -270,6 +270,7 @@ macro_rules! extern_fn_panic_handling { }; BOMB }; + let res = { $($fn_contents)* }; @@ -279,13 +280,18 @@ macro_rules! extern_fn_panic_handling { res }); ( $($fn_contents:tt)* ) => ( - $crate::extern_fn_panic_handling!{ - no_early_return; - let a = $crate::marker_type::NotCopyNotClone; - (move||{ - drop(a); - $($fn_contents)* - })() + #[allow(clippy::redundant_closure_call)] + { + $crate::extern_fn_panic_handling!{ + no_early_return; + let a = $crate::marker_type::NotCopyNotClone; + (move||{ + drop(a); + { + $($fn_contents)* + } + })() + } } ) } diff --git a/abi_stable/src/marker_type.rs b/abi_stable/src/marker_type.rs index 85a62929..38a2322e 100644 --- a/abi_stable/src/marker_type.rs +++ b/abi_stable/src/marker_type.rs @@ -111,7 +111,7 @@ mod _sabi_erasedobject { type StaticEquivalent = _static_ErasedObject<__GetStaticEquivalent>; } #[doc(hidden)] - pub(super) const _MONO_LAYOUT_ErasedObject: &'static __sabi_re::MonoTypeLayout = + pub(super) const _MONO_LAYOUT_ErasedObject: &__sabi_re::MonoTypeLayout = &__sabi_re::MonoTypeLayout::from_derive(__sabi_re::_private_MonoTypeLayoutDerive { name: abi_stable::std_types::RStr::from_str("ErasedObject"), item_info: _ITEM_INFO_CONST_ERASEDOBJECT, diff --git a/abi_stable/src/multikey_map.rs b/abi_stable/src/multikey_map.rs index 20c4d338..0dbb8134 100644 --- a/abi_stable/src/multikey_map.rs +++ b/abi_stable/src/multikey_map.rs @@ -241,9 +241,11 @@ where where K: Clone + ::std::fmt::Debug, { - if !self.arena.contains(index.index) { - panic!("Invalid index:{:?}", index); - } + assert!( + self.arena.contains(index.index), + "Invalid index:{:?}", + index, + ); let ret = match self.map.entry(key.clone()) { Entry::Occupied(mut entry) => { let index_before = *entry.get(); diff --git a/abi_stable/src/nonexhaustive_enum.rs b/abi_stable/src/nonexhaustive_enum.rs index 9d2efad1..b142ca52 100644 --- a/abi_stable/src/nonexhaustive_enum.rs +++ b/abi_stable/src/nonexhaustive_enum.rs @@ -41,6 +41,7 @@ where T: GetVTable<::DefaultStorage, ::DefaultInterface>, { #[derive(Debug)] + #[allow(dead_code)] struct TypeAndStorageLayout { type_: &'static str, type_size: usize, diff --git a/abi_stable/src/nonexhaustive_enum/nonexhaustive.rs b/abi_stable/src/nonexhaustive_enum/nonexhaustive.rs index 87a3b6d3..593d0e12 100644 --- a/abi_stable/src/nonexhaustive_enum/nonexhaustive.rs +++ b/abi_stable/src/nonexhaustive_enum/nonexhaustive.rs @@ -236,7 +236,7 @@ impl NonExhaustive { Self::assert_fits_within_storage(); let mut this = Self { - fill: unsafe { + fill: { // The fact that the vtable was constructed ensures that // `Inline` implements `InlineStorage` ScratchSpace::uninit_unbounded() @@ -589,11 +589,9 @@ where Self: PartialEq, { fn partial_cmp(&self, other: &E) -> Option { - unsafe { - match self.as_enum() { - Ok(this) => this.partial_cmp(other), - Err(_) => Some(Ordering::Greater), - } + match self.as_enum() { + Ok(this) => this.partial_cmp(other), + Err(_) => Some(Ordering::Greater), } } } @@ -809,10 +807,10 @@ where #[must_use] #[repr(transparent)] #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, StableAbi)] +#[non_exhaustive] pub struct UnwrapEnumError { /// This field is either a `NonExhaustive<>` or a `DiscrAndEnumInfo<>` pub non_exhaustive: N, - _priv: (), } impl UnwrapEnumError { @@ -839,10 +837,7 @@ impl UnwrapEnumError { impl UnwrapEnumError { #[inline] const fn new(non_exhaustive: N) -> Self { - Self { - non_exhaustive, - _priv: (), - } + Self { non_exhaustive } } } diff --git a/abi_stable/src/nonexhaustive_enum/vtable.rs b/abi_stable/src/nonexhaustive_enum/vtable.rs index 322f7526..154d638f 100644 --- a/abi_stable/src/nonexhaustive_enum/vtable.rs +++ b/abi_stable/src/nonexhaustive_enum/vtable.rs @@ -2,6 +2,7 @@ use std::{ cmp::{Ord, PartialEq, PartialOrd}, fmt::{Debug, Display}, hash::Hash, + marker::PhantomData, }; use crate::{ @@ -22,8 +23,19 @@ use crate::{ StableAbi, }; +#[doc(hidden)] +pub struct Private( + PhantomData<(PhantomData, PhantomData, PhantomData)>, +); + /// Gets the vtable of `NonExhaustive`. -pub unsafe trait GetVTable: GetEnumInfo { +/// +/// This trait cannot be implemented outside of `abi_stable`, it can only be used. +pub trait GetVTable: GetEnumInfo { + // Using privacy to make it impossible to implement this trait outside this module. + #[doc(hidden)] + const __HIDDEN_10341423423__: Private; + #[doc(hidden)] const VTABLE_VAL: NonExhaustiveVtable; @@ -35,7 +47,7 @@ pub unsafe trait GetVTable: GetEnumInfo { #[doc(hidden)] const VTABLE_REF: NonExhaustiveVtable_Ref = - unsafe { NonExhaustiveVtable_Ref(Self::VTABLE_WM.as_prefix()) }; + NonExhaustiveVtable_Ref(Self::VTABLE_WM.as_prefix()); } /// The vtable for NonExhaustive<>. @@ -106,7 +118,7 @@ pub struct NonExhaustiveVtable { unsafe impl Sync for NonExhaustiveVtable {} unsafe impl Send for NonExhaustiveVtable {} -unsafe impl GetVTable for E +impl GetVTable for E where S: InlineStorage, I: InterfaceType, @@ -122,6 +134,8 @@ where I::Ord: InitOrdField, I::Hash: InitHashField, { + const __HIDDEN_10341423423__: Private = Private(PhantomData); + #[doc(hidden)] const VTABLE_VAL: NonExhaustiveVtable = NonExhaustiveVtable { _sabi_tys: UnsafeIgnoredType::DEFAULT, diff --git a/abi_stable/src/pointer_trait.rs b/abi_stable/src/pointer_trait.rs index fc9c5a50..538589ed 100644 --- a/abi_stable/src/pointer_trait.rs +++ b/abi_stable/src/pointer_trait.rs @@ -161,7 +161,7 @@ unsafe impl<'a, T> GetPointerKind for &'a mut T { /// Whether the pointer can be transmuted to an equivalent pointer with `T` as the referent type. /// -/// # Safety for implementor +/// # Safety /// /// Implementors of this trait must ensure that: /// @@ -805,7 +805,7 @@ pub unsafe trait ImmutableRef: Copy { /// `ImmutableRef::to_raw_ptr` on an instance of `Self`. #[inline(always)] unsafe fn from_nonnull(from: NonNull) -> Self { - unsafe { Transmuter { from }.to } + Transmuter { from }.to } /// Converts this pointer to a raw pointer. @@ -821,7 +821,7 @@ pub unsafe trait ImmutableRef: Copy { /// This has the same safety requirements as [`from_nonnull`](#method.from_nonnull) #[inline(always)] unsafe fn from_raw_ptr(from: *const Self::Target) -> Option { - unsafe { Transmuter { from }.to } + Transmuter { from }.to } } diff --git a/abi_stable/src/prefix_type.rs b/abi_stable/src/prefix_type.rs index 71438577..43373dc5 100644 --- a/abi_stable/src/prefix_type.rs +++ b/abi_stable/src/prefix_type.rs @@ -37,6 +37,10 @@ pub use self::{ pub use self::pt_metadata::__PrefixTypeMetadata; /// For types deriving `StableAbi` with `#[sabi(kind(Prefix(..)))]`. +/// +/// # Safety +/// +/// This trait must be implemented by the `StableAbi` derive macro. pub unsafe trait PrefixTypeTrait: Sized { /// The metadata of the prefix-type (a FieldAccessibility and a PTStructLayout), /// for passing to `WithMetadata::new`, diff --git a/abi_stable/src/sabi_trait/vtable.rs b/abi_stable/src/sabi_trait/vtable.rs index fa5e2a39..0786da49 100644 --- a/abi_stable/src/sabi_trait/vtable.rs +++ b/abi_stable/src/sabi_trait/vtable.rs @@ -13,20 +13,40 @@ use crate::{ }, }; +use std::marker::PhantomData; + ////////////////////////////////////////////////////////////////////////////// +#[doc(hidden)] +pub struct Private( + PhantomData<( + PhantomData, + PhantomData, + PhantomData, + PhantomData, + PhantomData, + )>, +); + /// Gets an `RObjectVtable_Ref<_Self,ErasedPtr,TO>`(the vtable for RObject itself), /// which is stored as the first field of all generated trait object vtables. -pub unsafe trait GetRObjectVTable: - Sized + InterfaceType -{ +/// +/// This trait cannot be implemented outside of `abi_stable`, it can only be used. +pub trait GetRObjectVTable: Sized + InterfaceType { + // Using privacy to make it impossible to implement this trait outside this module. + #[doc(hidden)] + const __HIDDEN_10341423423AB__: Private; + const ROBJECT_VTABLE: RObjectVtable_Ref<_Self, ErasedPtr, Self>; } -unsafe impl GetRObjectVTable for I +impl GetRObjectVTable for I where I: AreTraitsImpld + InterfaceType, { + const __HIDDEN_10341423423AB__: Private = + Private(std::marker::PhantomData); + const ROBJECT_VTABLE: RObjectVtable_Ref<_Self, ErasedPtr, Self> = { GetRObjectVTableHelper::::TMP_VTABLE }; } @@ -179,7 +199,7 @@ where } const TMP_VTABLE: RObjectVtable_Ref<_Self, ErasedPtr, I> = - unsafe { RObjectVtable_Ref(Self::TMP_WM.as_prefix()) }; + RObjectVtable_Ref(Self::TMP_WM.as_prefix()); } /// The vtable for RObject,which all `#[trait_object]` derived trait objects contain. diff --git a/abi_stable/src/sabi_types/late_static_ref.rs b/abi_stable/src/sabi_types/late_static_ref.rs index 2ba0860d..ea910374 100644 --- a/abi_stable/src/sabi_types/late_static_ref.rs +++ b/abi_stable/src/sabi_types/late_static_ref.rs @@ -82,6 +82,7 @@ pub struct LateStaticRef { _marker: PhantomData, } +#[allow(clippy::declare_interior_mutable_const)] const LOCK: RMutex<()> = RMutex::new(()); unsafe impl Sync for LateStaticRef {} diff --git a/abi_stable/src/sabi_types/move_ptr.rs b/abi_stable/src/sabi_types/move_ptr.rs index 6fa8467c..5bc4e384 100644 --- a/abi_stable/src/sabi_types/move_ptr.rs +++ b/abi_stable/src/sabi_types/move_ptr.rs @@ -268,8 +268,7 @@ impl<'a, T> MovePtr<'a, T> { #[inline] pub fn into_raw(this: Self) -> *mut T { let this = ManuallyDrop::new(this); - let ptr = this.ptr.as_ptr(); - ptr + this.ptr.as_ptr() } /// Moves the value into a new `Box` diff --git a/abi_stable/src/sabi_types/nul_str.rs b/abi_stable/src/sabi_types/nul_str.rs index 487bcc64..7a7f6c7b 100644 --- a/abi_stable/src/sabi_types/nul_str.rs +++ b/abi_stable/src/sabi_types/nul_str.rs @@ -4,7 +4,7 @@ #[cfg(test)] mod tests; -use crate::{std_types::RStr, utils::ref_as_nonnull}; +use crate::std_types::RStr; use std::{ cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}, @@ -157,7 +157,6 @@ impl<'a> NulStr<'a> { pub fn try_from_str(string: &'a str) -> Result { let mut i = 0; let mut bytes = string.as_bytes(); - let len = string.len(); bytes = match bytes { [rem @ .., 0] => rem, @@ -173,7 +172,7 @@ impl<'a> NulStr<'a> { } unsafe{ - Ok(NulStr::from_str(string)) + Ok(NulStr::from_ptr(string.as_ptr())) } } } diff --git a/abi_stable/src/sabi_types/rmut.rs b/abi_stable/src/sabi_types/rmut.rs index e7f71f9a..efa949e8 100644 --- a/abi_stable/src/sabi_types/rmut.rs +++ b/abi_stable/src/sabi_types/rmut.rs @@ -596,6 +596,7 @@ impl<'a, T> RMut<'a, T> { /// } /// ``` #[inline(always)] + #[allow(clippy::needless_lifetimes)] pub fn as_rref<'r>(&'r self) -> RRef<'r, T> { unsafe { RRef::from_raw(self.ref_.as_ptr()) } } @@ -746,6 +747,7 @@ mod tests { } } + #[test] fn as_rtype_test() { let mut num = 0u8; let mut rmut = RMut::new(&mut num); diff --git a/abi_stable/src/sabi_types/rsmallbox.rs b/abi_stable/src/sabi_types/rsmallbox.rs index 71eaf1e2..8994ea1e 100644 --- a/abi_stable/src/sabi_types/rsmallbox.rs +++ b/abi_stable/src/sabi_types/rsmallbox.rs @@ -381,13 +381,12 @@ mod private { } /// Converts a RSmallBox into an RBox,currently this allocates. - #[allow(clippy::redundant_closure)] - impl Into> for RSmallBox + impl From> for RBox where Inline: InlineStorage, { - fn into(self) -> RBox { - Self::with_move_ptr(ManuallyDrop::new(self), |x| MovePtr::into_rbox(x)) + fn from(this: RSmallBox) -> RBox { + OwnedPointer::with_move_ptr(ManuallyDrop::new(this), |x| MovePtr::into_rbox(x)) } } } diff --git a/abi_stable/src/sabi_types/static_ref.rs b/abi_stable/src/sabi_types/static_ref.rs index 645c3d4e..ffb83ca6 100644 --- a/abi_stable/src/sabi_types/static_ref.rs +++ b/abi_stable/src/sabi_types/static_ref.rs @@ -147,7 +147,7 @@ impl StaticRef { /// ``` pub const unsafe fn from_raw(ref_: *const T) -> Self { Self { - ref_: unsafe { NonNull::new_unchecked(ref_ as *mut T) }, + ref_: NonNull::new_unchecked(ref_ as *mut T), } } diff --git a/abi_stable/src/std_types/arc.rs b/abi_stable/src/std_types/arc.rs index b27b4f3a..bbfcc508 100644 --- a/abi_stable/src/std_types/arc.rs +++ b/abi_stable/src/std_types/arc.rs @@ -371,7 +371,7 @@ impl_into_rust_repr! { T: Clone+StableAbi, ]{ fn(this){ - Self::into_arc(this) + RArc::into_arc(this) } } } @@ -476,7 +476,7 @@ mod vtable_mod { } unsafe extern "C" fn clone_arc(this: &RArc) -> RArc { - with_arc_ref(this, |x| Arc::clone(&x).into()) + with_arc_ref(this, |x| Arc::clone(x).into()) } unsafe extern "C" fn get_mut_arc<'a, T>(this: &'a mut RArc) -> Option<&'a mut T> { @@ -497,11 +497,11 @@ mod vtable_mod { } unsafe extern "C" fn strong_count_arc(this: &RArc) -> usize { - with_arc_ref(this, |x| Arc::strong_count(&x)) + with_arc_ref(this, |x| Arc::strong_count(x)) } unsafe extern "C" fn weak_count_arc(this: &RArc) -> usize { - with_arc_ref(this, |x| Arc::weak_count(&x)) + with_arc_ref(this, |x| Arc::weak_count(x)) } } use self::vtable_mod::{ArcVtable_Ref, VTableGetter}; diff --git a/abi_stable/src/std_types/arc/test.rs b/abi_stable/src/std_types/arc/test.rs index 97c2486b..55e941fc 100644 --- a/abi_stable/src/std_types/arc/test.rs +++ b/abi_stable/src/std_types/arc/test.rs @@ -81,7 +81,7 @@ fn make_mut() { let mut arc = Arc::new(ValueAndDod { value: 'a', - dod: dod.clone(), + _dod: dod.clone(), }) .piped(RArc::from); @@ -104,7 +104,7 @@ fn make_mut() { #[derive(Clone)] struct ValueAndDod<'a, T> { value: T, - dod: DecrementOnDrop<'a>, + _dod: DecrementOnDrop<'a>, } ///////////////////////////////////////// diff --git a/abi_stable/src/std_types/boxed.rs b/abi_stable/src/std_types/boxed.rs index 2012d27e..d456682c 100644 --- a/abi_stable/src/std_types/boxed.rs +++ b/abi_stable/src/std_types/boxed.rs @@ -281,10 +281,8 @@ unsafe impl OwnedPointer for RBox { #[inline] unsafe fn drop_allocation(this: &mut ManuallyDrop) { - unsafe { - let data: *mut T = this.data(); - (this.vtable().destructor())(data as *mut (), CallReferentDrop::No, Deallocate::Yes); - } + let data: *mut T = this.data(); + (this.vtable().destructor())(data as *mut (), CallReferentDrop::No, Deallocate::Yes); } } @@ -635,7 +633,7 @@ impl<'a, T: 'a> VTableGetter<'a, T> { } // The VTABLE for this type in this executable/library - const LIB_VTABLE: BoxVtable_Ref = unsafe { BoxVtable_Ref(Self::WM_DEFAULT.as_prefix()) }; + const LIB_VTABLE: BoxVtable_Ref = BoxVtable_Ref(Self::WM_DEFAULT.as_prefix()); #[cfg(test)] staticref! { diff --git a/abi_stable/src/std_types/boxed/test.rs b/abi_stable/src/std_types/boxed/test.rs index f61f1ded..f4fc38e7 100644 --- a/abi_stable/src/std_types/boxed/test.rs +++ b/abi_stable/src/std_types/boxed/test.rs @@ -89,7 +89,7 @@ fn with_move_ptr_runs() { fn owned_pointer_trait() { let arc = Arc::new(10); - unsafe { + { let cloned_arc = ManuallyDrop::new(RBox::new(arc.clone())); OwnedPointer::with_move_ptr(cloned_arc, |move_ptr| { @@ -100,7 +100,7 @@ fn owned_pointer_trait() { }); } assert_eq!(Arc::strong_count(&arc), 1); - unsafe { + { let cloned_arc = ManuallyDrop::new(RBox::new(arc.clone())); OwnedPointer::with_move_ptr(cloned_arc, |move_ptr| { diff --git a/abi_stable/src/std_types/map.rs b/abi_stable/src/std_types/map.rs index 8c3a1fdb..eba28515 100644 --- a/abi_stable/src/std_types/map.rs +++ b/abi_stable/src/std_types/map.rs @@ -131,7 +131,7 @@ pub type Drain<'a, K, V> = DynTrait<'a, RBox<()>, ValIterInterface>; )] struct ErasedMap(PhantomData<(K, V)>, UnsafeIgnoredType); -unsafe impl<'a, K: 'a, V: 'a, S: 'a> ErasedType<'a> for ErasedMap { +impl<'a, K: 'a, V: 'a, S: 'a> ErasedType<'a> for ErasedMap { type Unerased = BoxedHashMap<'a, K, V, S>; } @@ -225,7 +225,9 @@ impl RHashMap { S: BuildHasher + Default, { let mut map = VTable::::erased_map(hash_builder); - ErasedMap::reserve(map.as_rmut(), capacity); + unsafe { + ErasedMap::reserve(map.as_rmut(), capacity); + } RHashMap { map, vtable: VTable::VTABLE_REF, @@ -355,7 +357,7 @@ impl RHashMap { Q: Hash + Eq + ?Sized, { let vtable = self.vtable(); - vtable.remove_entry()(self.map.as_rmut(), MapQuery::new(&query)) + unsafe { vtable.remove_entry()(self.map.as_rmut(), MapQuery::new(&query)) } } } @@ -394,7 +396,7 @@ impl RHashMap { /// ``` pub fn get_p(&self, key: &K) -> Option<&V> { let vtable = self.vtable(); - unsafe { vtable.get_elem_p()(self.map.as_rref(), &key) } + unsafe { vtable.get_elem_p()(self.map.as_rref(), key) } } /// Returns a mutable reference to the value associated with the key. @@ -414,7 +416,7 @@ impl RHashMap { /// ``` pub fn get_mut_p(&mut self, key: &K) -> Option<&mut V> { let vtable = self.vtable(); - unsafe { vtable.get_mut_elem_p()(self.map.as_rmut(), &key) } + unsafe { vtable.get_mut_elem_p()(self.map.as_rmut(), key) } } /// Removes the value associated with the key. @@ -455,7 +457,7 @@ impl RHashMap { /// ``` pub fn remove_entry_p(&mut self, key: &K) -> ROption> { let vtable = self.vtable(); - vtable.remove_entry_p()(self.map.as_rmut(), &key) + unsafe { vtable.remove_entry_p()(self.map.as_rmut(), key) } } /// Returns a reference to the value associated with the key. @@ -557,7 +559,9 @@ impl RHashMap { pub fn reserve(&mut self, reserved: usize) { let vtable = self.vtable(); - vtable.reserve()(self.map.as_rmut(), reserved); + unsafe { + vtable.reserve()(self.map.as_rmut(), reserved); + } } /// Removes all the entries in the map. @@ -580,7 +584,9 @@ impl RHashMap { /// ``` pub fn clear(&mut self) { let vtable = self.vtable(); - vtable.clear_map()(self.map.as_rmut()); + unsafe { + vtable.clear_map()(self.map.as_rmut()); + } } /// Returns the amount of entries in the map. @@ -601,7 +607,7 @@ impl RHashMap { /// ``` pub fn len(&self) -> usize { let vtable = self.vtable(); - vtable.len()(self.map.as_rref()) + unsafe { vtable.len()(self.map.as_rref()) } } /// Returns the capacity of the map, the amount of elements it can store without reallocating. @@ -620,7 +626,7 @@ impl RHashMap { /// ``` pub fn capacity(&self) -> usize { let vtable = self.vtable(); - vtable.capacity()(self.map.as_rref()) + unsafe { vtable.capacity()(self.map.as_rref()) } } /// Returns whether the map contains any entries. @@ -664,7 +670,7 @@ impl RHashMap { pub fn iter(&self) -> Iter<'_, K, V> { let vtable = self.vtable(); - vtable.iter()(self.map.as_rref()) + unsafe { vtable.iter()(self.map.as_rref()) } } /// Iterates over the entries in the map, with mutable references to the values in the map. @@ -690,7 +696,7 @@ impl RHashMap { pub fn iter_mut(&mut self) -> IterMut<'_, K, V> { let vtable = self.vtable(); - vtable.iter_mut()(self.map.as_rmut()) + unsafe { vtable.iter_mut()(self.map.as_rmut()) } } /// Clears the map, returning an iterator over all the entries that were removed. @@ -717,7 +723,7 @@ impl RHashMap { pub fn drain(&mut self) -> Drain<'_, K, V> { let vtable = self.vtable(); - vtable.drain()(self.map.as_rmut()) + unsafe { vtable.drain()(self.map.as_rmut()) } } /// Gets a handle into the entry in the map for the key, @@ -744,7 +750,7 @@ impl RHashMap { pub fn entry(&mut self, key: K) -> REntry<'_, K, V> { let vtable = self.vtable(); - vtable.entry()(self.map.as_rmut(), key) + unsafe { vtable.entry()(self.map.as_rmut(), key) } } } @@ -756,7 +762,7 @@ impl IntoIterator for RHashMap { fn into_iter(self) -> IntoIter { let vtable = self.vtable(); - vtable.iter_val()(self.map) + unsafe { vtable.iter_val()(self.map) } } } @@ -790,13 +796,13 @@ where } } -impl Into> for RHashMap +impl From> for HashMap where K: Eq + Hash, S: BuildHasher + Default, { - fn into(self) -> HashMap { - self.into_iter().map(IntoReprRust::into_rust).collect() + fn from(this: RHashMap) -> HashMap { + this.into_iter().map(|x| x.into_tuple()).collect() } } @@ -1030,28 +1036,36 @@ mod serde { )] struct VTable { /// - insert_elem: extern "C" fn(RMut<'_, ErasedMap>, K, V) -> ROption, - - get_elem: for<'a> extern "C" fn(RRef<'a, ErasedMap>, MapQuery<'_, K>) -> Option<&'a V>, - get_mut_elem: - for<'a> extern "C" fn(RMut<'a, ErasedMap>, MapQuery<'_, K>) -> Option<&'a mut V>, - remove_entry: - extern "C" fn(RMut<'_, ErasedMap>, MapQuery<'_, K>) -> ROption>, - - get_elem_p: for<'a> extern "C" fn(RRef<'a, ErasedMap>, &K) -> Option<&'a V>, - get_mut_elem_p: for<'a> extern "C" fn(RMut<'a, ErasedMap>, &K) -> Option<&'a mut V>, - remove_entry_p: extern "C" fn(RMut<'_, ErasedMap>, &K) -> ROption>, - - reserve: extern "C" fn(RMut<'_, ErasedMap>, usize), - clear_map: extern "C" fn(RMut<'_, ErasedMap>), - len: extern "C" fn(RRef<'_, ErasedMap>) -> usize, - capacity: extern "C" fn(RRef<'_, ErasedMap>) -> usize, - iter: extern "C" fn(RRef<'_, ErasedMap>) -> Iter<'_, K, V>, - iter_mut: extern "C" fn(RMut<'_, ErasedMap>) -> IterMut<'_, K, V>, - drain: extern "C" fn(RMut<'_, ErasedMap>) -> Drain<'_, K, V>, - iter_val: extern "C" fn(RBox>) -> IntoIter, + insert_elem: unsafe extern "C" fn(RMut<'_, ErasedMap>, K, V) -> ROption, + + get_elem: for<'a> unsafe extern "C" fn( + RRef<'a, ErasedMap>, + MapQuery<'_, K>, + ) -> Option<&'a V>, + get_mut_elem: for<'a> unsafe extern "C" fn( + RMut<'a, ErasedMap>, + MapQuery<'_, K>, + ) -> Option<&'a mut V>, + remove_entry: unsafe extern "C" fn( + RMut<'_, ErasedMap>, + MapQuery<'_, K>, + ) -> ROption>, + + get_elem_p: for<'a> unsafe extern "C" fn(RRef<'a, ErasedMap>, &K) -> Option<&'a V>, + get_mut_elem_p: + for<'a> unsafe extern "C" fn(RMut<'a, ErasedMap>, &K) -> Option<&'a mut V>, + remove_entry_p: unsafe extern "C" fn(RMut<'_, ErasedMap>, &K) -> ROption>, + + reserve: unsafe extern "C" fn(RMut<'_, ErasedMap>, usize), + clear_map: unsafe extern "C" fn(RMut<'_, ErasedMap>), + len: unsafe extern "C" fn(RRef<'_, ErasedMap>) -> usize, + capacity: unsafe extern "C" fn(RRef<'_, ErasedMap>) -> usize, + iter: unsafe extern "C" fn(RRef<'_, ErasedMap>) -> Iter<'_, K, V>, + iter_mut: unsafe extern "C" fn(RMut<'_, ErasedMap>) -> IterMut<'_, K, V>, + drain: unsafe extern "C" fn(RMut<'_, ErasedMap>) -> Drain<'_, K, V>, + iter_val: unsafe extern "C" fn(RBox>) -> IntoIter, #[sabi(last_prefix_field)] - entry: extern "C" fn(RMut<'_, ErasedMap>, K) -> REntry<'_, K, V>, + entry: unsafe extern "C" fn(RMut<'_, ErasedMap>, K) -> REntry<'_, K, V>, } impl VTable diff --git a/abi_stable/src/std_types/map/entry.rs b/abi_stable/src/std_types/map/entry.rs index 44201a23..81430338 100644 --- a/abi_stable/src/std_types/map/entry.rs +++ b/abi_stable/src/std_types/map/entry.rs @@ -41,11 +41,11 @@ type UnerasedOccupiedEntry<'a, K, V> = ManuallyDrop, type UnerasedVacantEntry<'a, K, V> = ManuallyDrop, V>>; -unsafe impl<'a, K: 'a, V: 'a> ErasedType<'a> for ErasedOccupiedEntry { +impl<'a, K: 'a, V: 'a> ErasedType<'a> for ErasedOccupiedEntry { type Unerased = UnerasedOccupiedEntry<'a, K, V>; } -unsafe impl<'a, K: 'a, V: 'a> ErasedType<'a> for ErasedVacantEntry { +impl<'a, K: 'a, V: 'a> ErasedType<'a> for ErasedVacantEntry { type Unerased = UnerasedVacantEntry<'a, K, V>; } diff --git a/abi_stable/src/std_types/map/extern_fns.rs b/abi_stable/src/std_types/map/extern_fns.rs index 054b8e90..d4810ce1 100644 --- a/abi_stable/src/std_types/map/extern_fns.rs +++ b/abi_stable/src/std_types/map/extern_fns.rs @@ -11,59 +11,63 @@ where K: Hash + Eq, S: BuildHasher, { - fn run<'a, F, R>(this: RRef<'a, Self>, f: F) -> R + unsafe fn run<'a, F, R>(this: RRef<'a, Self>, f: F) -> R where F: FnOnce(&'a BoxedHashMap<'a, K, V, S>) -> R, { extern_fn_panic_handling! { - let map = unsafe{ this.transmute_into_ref::>() }; + let map = this.transmute_into_ref::>(); f(map) } } - fn run_mut<'a, F, R>(this: RMut<'a, Self>, f: F) -> R + unsafe fn run_mut<'a, F, R>(this: RMut<'a, Self>, f: F) -> R where F: FnOnce(&'a mut BoxedHashMap<'a, K, V, S>) -> R, { extern_fn_panic_handling! { - let map = unsafe{ this.transmute_into_mut::>() }; + let map = this.transmute_into_mut::>(); f(map) } } - fn run_val<'a, F, R>(this: RBox, f: F) -> R + unsafe fn run_val<'a, F, R>(this: RBox, f: F) -> R where F: FnOnce(RBox>) -> R, K: 'a, V: 'a, { extern_fn_panic_handling! { - let map = unsafe{ this.transmute_element::>() }; + let map = this.transmute_element::>(); f( map ) } } - pub(super) extern "C" fn insert_elem(this: RMut<'_, Self>, key: K, value: V) -> ROption { + pub(super) unsafe extern "C" fn insert_elem( + this: RMut<'_, Self>, + key: K, + value: V, + ) -> ROption { Self::run_mut(this, |this| { this.map.insert(MapKey::Value(key), value).into_c() }) } - pub(super) extern "C" fn get_elem<'a>( + pub(super) unsafe extern "C" fn get_elem<'a>( this: RRef<'a, Self>, key: MapQuery<'_, K>, ) -> Option<&'a V> { Self::run(this, |this| unsafe { this.map.get(&key.as_mapkey()) }) } - pub(super) extern "C" fn get_mut_elem<'a>( + pub(super) unsafe extern "C" fn get_mut_elem<'a>( this: RMut<'a, Self>, key: MapQuery<'_, K>, ) -> Option<&'a mut V> { Self::run_mut(this, |this| unsafe { this.map.get_mut(&key.as_mapkey()) }) } - pub(super) extern "C" fn remove_entry( + pub(super) unsafe extern "C" fn remove_entry( this: RMut<'_, Self>, key: MapQuery<'_, K>, ) -> ROption> { @@ -75,18 +79,18 @@ where }) } - pub(super) extern "C" fn get_elem_p<'a>(this: RRef<'a, Self>, key: &K) -> Option<&'a V> { + pub(super) unsafe extern "C" fn get_elem_p<'a>(this: RRef<'a, Self>, key: &K) -> Option<&'a V> { Self::run(this, |this| this.map.get(key)) } - pub(super) extern "C" fn get_mut_elem_p<'a>( + pub(super) unsafe extern "C" fn get_mut_elem_p<'a>( this: RMut<'a, Self>, key: &K, ) -> Option<&'a mut V> { Self::run_mut(this, |this| this.map.get_mut(key)) } - pub(super) extern "C" fn remove_entry_p( + pub(super) unsafe extern "C" fn remove_entry_p( this: RMut<'_, Self>, key: &K, ) -> ROption> { @@ -96,44 +100,44 @@ where }) } - pub(super) extern "C" fn reserve(this: RMut<'_, Self>, reserved: usize) { + pub(super) unsafe extern "C" fn reserve(this: RMut<'_, Self>, reserved: usize) { Self::run_mut(this, |this| this.map.reserve(reserved)) } - pub(super) extern "C" fn clear_map(this: RMut<'_, Self>) { + pub(super) unsafe extern "C" fn clear_map(this: RMut<'_, Self>) { Self::run_mut(this, |this| this.map.clear()) } - pub(super) extern "C" fn len(this: RRef<'_, Self>) -> usize { + pub(super) unsafe extern "C" fn len(this: RRef<'_, Self>) -> usize { Self::run(this, |this| this.map.len()) } - pub(super) extern "C" fn capacity(this: RRef<'_, Self>) -> usize { + pub(super) unsafe extern "C" fn capacity(this: RRef<'_, Self>) -> usize { Self::run(this, |this| this.map.capacity()) } - pub(super) extern "C" fn iter(this: RRef<'_, Self>) -> Iter<'_, K, V> { + pub(super) unsafe extern "C" fn iter(this: RRef<'_, Self>) -> Iter<'_, K, V> { Self::run(this, |this| { let iter = this.map.iter().map(map_iter_ref); DynTrait::from_borrowing_value(iter, RefIterInterface::NEW) }) } - pub(super) extern "C" fn iter_mut(this: RMut<'_, Self>) -> IterMut<'_, K, V> { + pub(super) unsafe extern "C" fn iter_mut(this: RMut<'_, Self>) -> IterMut<'_, K, V> { Self::run_mut(this, |this| { let iter = this.map.iter_mut().map(map_iter_ref); DynTrait::from_borrowing_value(iter, MutIterInterface::NEW) }) } - pub(super) extern "C" fn drain(this: RMut<'_, Self>) -> Drain<'_, K, V> { + pub(super) unsafe extern "C" fn drain(this: RMut<'_, Self>) -> Drain<'_, K, V> { Self::run_mut(this, |this| { let iter = this.map.drain().map(map_iter_val); DynTrait::from_borrowing_value(iter, ValIterInterface::NEW) }) } - pub(super) extern "C" fn iter_val(this: RBox>) -> IntoIter { + pub(super) unsafe extern "C" fn iter_val(this: RBox>) -> IntoIter { Self::run_val(this, |this| { let iter = this .piped(RBox::into_inner) @@ -145,7 +149,7 @@ where }) } - pub(super) extern "C" fn entry(this: RMut<'_, Self>, key: K) -> REntry<'_, K, V> { + pub(super) unsafe extern "C" fn entry(this: RMut<'_, Self>, key: K) -> REntry<'_, K, V> { Self::run_mut(this, |this| { this.entry = None; let map = &mut this.map; diff --git a/abi_stable/src/std_types/slice_mut.rs b/abi_stable/src/std_types/slice_mut.rs index 8b93612c..0bfc41ab 100644 --- a/abi_stable/src/std_types/slice_mut.rs +++ b/abi_stable/src/std_types/slice_mut.rs @@ -509,9 +509,9 @@ impl_into_rust_repr! { } } -impl<'a, T> Into<&'a [T]> for RSliceMut<'a, T> { - fn into(self) -> &'a [T] { - self.into_slice() +impl<'a, T> From> for &'a [T] { + fn from(this: RSliceMut<'a, T>) -> &'a [T] { + this.into_slice() } } diff --git a/abi_stable/src/std_types/std_error.rs b/abi_stable/src/std_types/std_error.rs index a4566b39..0da18b6a 100644 --- a/abi_stable/src/std_types/std_error.rs +++ b/abi_stable/src/std_types/std_error.rs @@ -325,17 +325,15 @@ impl RBoxError_ { unsafe { Self::new_with_vtable(value, MakeRErrorVTable::::LIB_VTABLE) } } - fn new_with_vtable(value: T, vtable: RErrorVTable_Ref) -> Self { - unsafe { - let value = value - .piped(RBox::new) - .piped(|x| mem::transmute::, RBox>(x)); - - Self { - value, - vtable, - _sync_send: PhantomData, - } + unsafe fn new_with_vtable(value: T, vtable: RErrorVTable_Ref) -> Self { + let value = value + .piped(RBox::new) + .piped(|x| mem::transmute::, RBox>(x)); + + Self { + value, + vtable, + _sync_send: PhantomData, } } } @@ -520,10 +518,12 @@ macro_rules! from_impls { pub fn from_box(this: $boxdyn) -> Self { match this.downcast::() { Ok(e) => *e, - Err(e) => Self::new_with_vtable::<$boxdyn>( - e, - MakeBoxedRErrorVTable::<$boxdyn>::LIB_VTABLE, - ), + Err(e) => unsafe { + Self::new_with_vtable::<$boxdyn>( + e, + MakeBoxedRErrorVTable::<$boxdyn>::LIB_VTABLE, + ) + }, } } diff --git a/abi_stable/src/std_types/str.rs b/abi_stable/src/std_types/str.rs index 8aa5c445..6f0d6baf 100644 --- a/abi_stable/src/std_types/str.rs +++ b/abi_stable/src/std_types/str.rs @@ -245,9 +245,9 @@ deref_coerced_impl_cmp_traits! { //////////////////////////////// -impl<'a> Into> for RStr<'a> { - fn into(self) -> Cow<'a, str> { - self.as_str().into() +impl<'a> From> for Cow<'a, str> { + fn from(this: RStr<'a>) -> Cow<'a, str> { + this.as_str().into() } } @@ -259,15 +259,15 @@ impl_into_rust_repr! { } } -impl<'a> Into for RStr<'a> { - fn into(self) -> String { - self.as_str().into() +impl From> for String { + fn from(this: RStr<'_>) -> String { + this.as_str().into() } } -impl<'a> Into for RStr<'a> { - fn into(self) -> RString { - self.as_str().into() +impl From> for RString { + fn from(this: RStr<'_>) -> RString { + this.as_str().into() } } diff --git a/abi_stable/src/std_types/string.rs b/abi_stable/src/std_types/string.rs index 19418515..2b272c56 100644 --- a/abi_stable/src/std_types/string.rs +++ b/abi_stable/src/std_types/string.rs @@ -707,14 +707,14 @@ impl_into_rust_repr! { } } -impl<'a> Into> for RString { - fn into(self) -> Cow<'a, str> { - self.into_string().piped(Cow::Owned) +impl<'a> From for Cow<'a, str> { + fn from(this: RString) -> Cow<'a, str> { + this.into_string().piped(Cow::Owned) } } -impl<'a> From<&'a str> for RString { - fn from(this: &'a str) -> Self { +impl From<&str> for RString { + fn from(this: &str) -> Self { this.to_owned().into() } } @@ -886,11 +886,9 @@ impl IntoIterator for RString { unsafe { // Make sure that the buffer is not deallocated as long as the iterator is accessible. let text: &'static str = &*(&*self as *const str); - unsafe { - IntoIter { - iter: text.chars(), - _buf: self, - } + IntoIter { + iter: text.chars(), + _buf: self, } } } diff --git a/abi_stable/src/std_types/vec.rs b/abi_stable/src/std_types/vec.rs index d4f9fdef..dc2a1481 100644 --- a/abi_stable/src/std_types/vec.rs +++ b/abi_stable/src/std_types/vec.rs @@ -159,14 +159,11 @@ mod private { where F: FnOnce(&mut Vec) -> U, { - unsafe { - let mut old = mem::replace(self, RVec::new()).piped(ManuallyDrop::new); - let mut list = - Vec::::from_raw_parts(old.buffer_mut(), old.len(), old.capacity()); - let ret = f(&mut list); - ptr::write(self, list.into()); - ret - } + let mut old = mem::replace(self, RVec::new()).piped(ManuallyDrop::new); + let mut list = Vec::::from_raw_parts(old.buffer_mut(), old.len(), old.capacity()); + let ret = f(&mut list); + ptr::write(self, list.into()); + ret } /// Gets a raw pointer to the start of this RVec's buffer. diff --git a/abi_stable/src/std_types/vec/iters.rs b/abi_stable/src/std_types/vec/iters.rs index 4e7a76e8..b9d4ee74 100644 --- a/abi_stable/src/std_types/vec/iters.rs +++ b/abi_stable/src/std_types/vec/iters.rs @@ -38,12 +38,12 @@ impl RawValIter { fn as_slice(&self) -> &[T] { let len = self.calculate_length(); - unsafe { unsafe { ::std::slice::from_raw_parts(self.start, len) } } + unsafe { ::std::slice::from_raw_parts(self.start, len) } } fn as_mut_slice(&mut self) -> &mut [T] { let len = self.calculate_length(); - unsafe { unsafe { ::std::slice::from_raw_parts_mut(self.start as *mut T, len) } } + unsafe { ::std::slice::from_raw_parts_mut(self.start as *mut T, len) } } } diff --git a/abi_stable/src/traits.rs b/abi_stable/src/traits.rs index 7167a6ad..a384bf43 100644 --- a/abi_stable/src/traits.rs +++ b/abi_stable/src/traits.rs @@ -85,12 +85,11 @@ macro_rules! impl_into_rust_repr { ) => ( $(#[$meta])* - impl $(< $($impl_header)* >)? Into<$into_ty> for $from_ty + impl $(< $($impl_header)* >)? From<$from_ty> for $into_ty $(where $($where_clause)*)? { #[inline] - fn into(self)->$into_ty{ - let $this=self; + fn from($this: $from_ty) -> $into_ty{ $($function_contents)* } } @@ -112,7 +111,7 @@ macro_rules! impl_into_rust_repr { /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// -pub(crate) unsafe trait ErasedType<'a>: Sized { +pub(crate) trait ErasedType<'a>: Sized { type Unerased; #[inline] diff --git a/abi_stable/src/type_layout.rs b/abi_stable/src/type_layout.rs index 224b2db0..ec77a551 100644 --- a/abi_stable/src/type_layout.rs +++ b/abi_stable/src/type_layout.rs @@ -276,7 +276,7 @@ impl TypeLayout { /// Gets information about where a type was declared. #[inline] pub fn item_info(&self) -> &ItemInfo { - &self.mono.item_info() + self.mono.item_info() } /// Gets the alignment of the type. @@ -346,7 +346,7 @@ impl TypeLayout { /// Gets the parts of the type layout that don't change with generic parameters. pub fn mono_type_layout(&self) -> &MonoTypeLayout { - &self.mono + self.mono } } diff --git a/abi_stable/src/type_layout/construction.rs b/abi_stable/src/type_layout/construction.rs index 0b5a9f04..a14ef312 100644 --- a/abi_stable/src/type_layout/construction.rs +++ b/abi_stable/src/type_layout/construction.rs @@ -92,7 +92,7 @@ impl ItemInfo { let pav = self.package_and_version.as_str(); match pav.find(';') { Some(separator) => (&pav[..separator], &pav[(separator + 1)..]), - None => (&pav[..], ""), + None => (pav, ""), } } diff --git a/abi_stable/src/type_layout/printing.rs b/abi_stable/src/type_layout/printing.rs index 79eb97eb..3456ebe6 100644 --- a/abi_stable/src/type_layout/printing.rs +++ b/abi_stable/src/type_layout/printing.rs @@ -324,6 +324,7 @@ impl Drop for DecrementLevel { //////////////// #[derive(Debug)] +#[allow(dead_code)] struct TypeLayoutPointer { key_in_map: Option, type_: FmtFullType, diff --git a/abi_stable/src/type_layout/tl_data.rs b/abi_stable/src/type_layout/tl_data.rs index 98db1948..01c05dae 100644 --- a/abi_stable/src/type_layout/tl_data.rs +++ b/abi_stable/src/type_layout/tl_data.rs @@ -94,9 +94,9 @@ impl MonoTLData { } } - pub(super) fn to_primitive(&self) -> Option { + pub(super) fn to_primitive(self) -> Option { match self { - MonoTLData::Primitive(x) => Some(*x), + MonoTLData::Primitive(x) => Some(x), _ => None, } } diff --git a/abi_stable/src/type_layout/tl_multi_tl.rs b/abi_stable/src/type_layout/tl_multi_tl.rs index c3a592ce..0f15e105 100644 --- a/abi_stable/src/type_layout/tl_multi_tl.rs +++ b/abi_stable/src/type_layout/tl_multi_tl.rs @@ -22,7 +22,7 @@ abi_stable_shared::declare_multi_tl_types! { } impl TypeLayoutRange { - pub(crate) fn to_array(&self) -> [u16; Self::STORED_INLINE] { + pub(crate) fn to_array(self) -> [u16; Self::STORED_INLINE] { [ ((self.bits0 >> Self::INDEX_0_OFFSET) & Self::INDEX_MASK) as u16, ((self.bits0 >> Self::INDEX_1_OFFSET) & Self::INDEX_MASK) as u16, diff --git a/abi_stable/src/utils.rs b/abi_stable/src/utils.rs index 5776924c..66325a60 100644 --- a/abi_stable/src/utils.rs +++ b/abi_stable/src/utils.rs @@ -59,7 +59,7 @@ pub fn manuallydrop_as_rmut(this: &mut ManuallyDrop) -> RMut<'_, T> { /// Casts a `&'a mut ManuallyDrop` to `*mut T` pub fn manuallydrop_as_raw_mut(this: &mut ManuallyDrop) -> *mut T { - unsafe { this as *mut ManuallyDrop as *mut T } + this as *mut ManuallyDrop as *mut T } ////////////////////////////////// diff --git a/abi_stable_shared/src/type_layout/tl_lifetimes_macro.rs b/abi_stable_shared/src/type_layout/tl_lifetimes_macro.rs index 8a5f01d0..aa062779 100644 --- a/abi_stable_shared/src/type_layout/tl_lifetimes_macro.rs +++ b/abi_stable_shared/src/type_layout/tl_lifetimes_macro.rs @@ -139,14 +139,20 @@ macro_rules! declare_tl_lifetime_types {( #[inline] pub const fn from_u20(bits: u32) -> Self { Self { - bits:bits&0xF_FF_FF + bits:bits & 0xF_FF_FF } } /// Gets the length of this array. #[inline] - pub const fn len(mut self)->usize{ - (8-(self.bits.leading_zeros()>>2))as usize + pub const fn len(mut self) -> usize{ + (8-(self.bits.leading_zeros() >> 2))as usize + } + + /// Gets whether the array is empty. + #[inline] + pub const fn is_empty(self) -> bool{ + self.len() == 0 } } @@ -230,6 +236,12 @@ macro_rules! declare_tl_lifetime_types {( } } + /// Whether this span of lifetimes is empty. + #[inline] + pub fn is_empty(self) -> bool { + self.len() == 0 + } + /// Whether this is a range into a slice of `LifetimePair`s. #[inline] pub const fn is_range(self)->bool{ diff --git a/abi_stable_shared/src/type_layout/tl_multi_tl_macro.rs b/abi_stable_shared/src/type_layout/tl_multi_tl_macro.rs index fd765193..2fee8999 100644 --- a/abi_stable_shared/src/type_layout/tl_multi_tl_macro.rs +++ b/abi_stable_shared/src/type_layout/tl_multi_tl_macro.rs @@ -44,7 +44,7 @@ macro_rules! declare_multi_tl_types {( /// Constructs a `TypeLayoutRange` with up to five type layout indices. #[inline] - pub const fn with_up_to_5(mut len:usize,indices:[u16;5])->Self{ + pub const fn with_up_to_5(mut len:usize,indices:[u16;5]) -> Self { let len=len & 0usize.wrapping_sub((len <= Self::STORED_INLINE) as usize); Self::with_more_than_5(len,indices) } @@ -54,11 +54,11 @@ macro_rules! declare_multi_tl_types {( /// in which the indices from `indices[4]` onwards are /// stored contiguously in the slice. #[inline] - pub const fn with_more_than_5(len:usize,indices:[u16;5])->Self{ + pub const fn with_more_than_5(len:usize,indices:[u16;5]) -> Self { Self{ bits0:len as u32 - |((indices[0] as u32 & Self::INDEX_MASK)<Self{ + pub const fn from_u64(bits:u64) -> Self { Self{ bits0:bits as u32, bits1:(bits>>32)as u32, @@ -77,15 +77,21 @@ macro_rules! declare_multi_tl_types {( /// Converts this `TypeLayoutRange` into its representation. #[inline] - pub const fn to_u64(&self)->u64{ + pub const fn to_u64(&self) -> u64 { (self.bits0 as u64) |((self.bits1 as u64) << 32) } /// The amount of `TypeLayoutCtor` in this range. #[inline] - pub const fn len(&self)->usize{ - (self.bits0&Self::LEN_MASK) as usize + pub const fn len(&self) -> usize { + (self.bits0 & Self::LEN_MASK) as usize + } + + /// Whether this range of `TypeLayoutCtor` is empty. + #[inline] + pub const fn is_empty(&self) -> bool { + self.len() == 0 } } From cf46cc3b55f04240c0a1f0eeaa3662a73cfb781f Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Thu, 28 Oct 2021 00:15:17 -0300 Subject: [PATCH 23/32] Fixed errors caused by `proc_macro_derive_resolution_fallback` lint. Only changed StableAbi to be compatible with it, `#[sabi_trait]` explicitly generates a module, and can't be changed not to. Removed some old, commented out code. --- abi_stable_derive/src/stable_abi.rs | 35 +++--- .../src/stable_abi/nonexhaustive.rs | 10 +- .../src/stable_abi/prefix_types.rs | 105 ++++++++---------- 3 files changed, 70 insertions(+), 80 deletions(-) diff --git a/abi_stable_derive/src/stable_abi.rs b/abi_stable_derive/src/stable_abi.rs index 07435a51..574792c3 100644 --- a/abi_stable_derive/src/stable_abi.rs +++ b/abi_stable_derive/src/stable_abi.rs @@ -55,7 +55,7 @@ use self::{ }, common_tokens::CommonTokens, nonexhaustive::{tokenize_enum_info, tokenize_nonexhaustive_items}, - prefix_types::prefix_type_tokenizer, + prefix_types::{prefix_type_tokenizer, PrefixTypeTokens}, reflection::ModReflMode, shared_vars::SharedVars, tl_field::CompTLField, @@ -386,8 +386,10 @@ pub(crate) fn derive(mut data: DeriveInput) -> Result let extra_bounds = &config.extra_bounds; - let prefix_type_tokenizer_ = - prefix_type_tokenizer(&module, mono_type_layout, ds, config, ctokens)?; + let PrefixTypeTokens { + prefixref_types, + prefixref_impls, + } = prefix_type_tokenizer(&module, mono_type_layout, ds, config, ctokens)?; let mod_refl_mode = match config.mod_refl_mode { ModReflMode::Module => quote!(__ModReflMode::Module), @@ -489,26 +491,27 @@ pub(crate) fn derive(mut data: DeriveInput) -> Result }; quote!( - #prefix_type_tokenizer_ + #prefixref_types #nonexhaustive_items - const #item_info_const:abi_stable::type_layout::ItemInfo= - abi_stable::make_item_info!(); - - const #strings_const: ::abi_stable::std_types::RStr<'static>=#strings; - - mod #module { - use super::*; - - pub(super) use ::abi_stable; + const _: () = { + use ::abi_stable; #[allow(unused_imports)] - pub(super) use ::abi_stable::derive_macro_reexports::{ + use ::abi_stable::pmr::{ self as __sabi_re, renamed::*, }; + #prefixref_impls + + const #item_info_const: abi_stable::type_layout::ItemInfo= + abi_stable::make_item_info!(); + + const #strings_const: ::abi_stable::std_types::RStr<'static>=#strings; + + #static_struct_decl #nonexhaustive_tokens @@ -529,7 +532,7 @@ pub(crate) fn derive(mut data: DeriveInput) -> Result } #[doc(hidden)] - pub(super) const #mono_type_layout:&'static __sabi_re::MonoTypeLayout= + const #mono_type_layout:&'static __sabi_re::MonoTypeLayout= &__sabi_re::MonoTypeLayout::from_derive( __sabi_re::_private_MonoTypeLayoutDerive{ name: #stringified_name, @@ -575,7 +578,7 @@ pub(crate) fn derive(mut data: DeriveInput) -> Result }; } - } + }; ) .observe(|tokens| { #[allow(clippy::if_then_panic)] diff --git a/abi_stable_derive/src/stable_abi/nonexhaustive.rs b/abi_stable_derive/src/stable_abi/nonexhaustive.rs index 0bd2073d..41700005 100644 --- a/abi_stable_derive/src/stable_abi/nonexhaustive.rs +++ b/abi_stable_derive/src/stable_abi/nonexhaustive.rs @@ -389,13 +389,13 @@ pub(crate) fn tokenize_nonexhaustive_items<'a>( #[doc=#alias_docs] #vis type #nonexhaustive_alias<#type_generics_decl>= - #module::__sabi_re::NonExhaustive< + ::abi_stable::pmr::NonExhaustive< #name<#type_generics_use>, #enum_storage, #default_interface, >; - unsafe impl #module::__sabi_re::InlineStorage for #enum_storage{} + unsafe impl ::abi_stable::pmr::InlineStorage for #enum_storage{} #[doc=#marker_docs] #vis struct #nonexhaustive_marker( @@ -491,7 +491,7 @@ pub(crate) fn tokenize_nonexhaustive_items<'a>( let type_param = ToTokenFnMut::new(|ts| match referent { Some(x) => x.to_tokens(ts), None => { - quote!( <#pointer as __sabi_re::GetPointerKind>::PtrTarget ) + quote!( <#pointer as ::abi_stable::pmr::GetPointerKind>::PtrTarget ) .to_tokens(ts) } }); @@ -518,7 +518,7 @@ pub(crate) fn tokenize_nonexhaustive_items<'a>( let bound = match &this.bounds_trait { Some(BoundsTrait { ident, .. }) => quote!(#ident), None => quote!( - #module::__sabi_re::GetNonExhaustiveVTable< + ::abi_stable::pmr::GetNonExhaustiveVTable< #enum_storage, #default_interface, > @@ -688,7 +688,7 @@ pub(crate) fn tokenize_enum_info<'a>( quote!( #[test] fn #tests_function(){ - use self::__sabi_re::assert_nonexhaustive; + use ::abi_stable::pmr::assert_nonexhaustive; #( assert_nonexhaustive::<#assertions>(); diff --git a/abi_stable_derive/src/stable_abi/prefix_types.rs b/abi_stable_derive/src/stable_abi/prefix_types.rs index 3f2d778e..bb923e99 100644 --- a/abi_stable_derive/src/stable_abi/prefix_types.rs +++ b/abi_stable_derive/src/stable_abi/prefix_types.rs @@ -6,7 +6,7 @@ use core_extensions::{matches, SelfOps}; use syn::{punctuated::Punctuated, Ident, TypeParamBound, Visibility, WherePredicate}; -use quote::{quote_spanned, ToTokens}; +use quote::{quote_spanned, ToTokens, TokenStreamExt}; use as_derive_utils::{ datastructure::{DataStructure, Field, FieldIndex, FieldMap}, @@ -209,6 +209,11 @@ impl<'a> PrefixKind<'a> { ///// Code generation //////////////////////////////////////////////////////////////////////////////// +pub struct PrefixTypeTokens { + pub prefixref_types: TokenStream2, + pub prefixref_impls: TokenStream2, +} + /// Returns a value which for a prefix-type . pub(crate) fn prefix_type_tokenizer<'a>( module: &'a Ident, @@ -216,7 +221,7 @@ pub(crate) fn prefix_type_tokenizer<'a>( ds: &'a DataStructure<'a>, config: &'a StableAbiOptions<'a>, _ctokens: &'a CommonTokens<'a>, -) -> Result { +) -> Result { if matches!(config.kind, StabilityKind::Prefix { .. }) { if ds .variants @@ -237,15 +242,22 @@ pub(crate) fn prefix_type_tokenizer<'a>( } } - Ok(ToTokenFnMut::new(move |ts| { + Ok({ + fn default_prefixtype_tokens() -> PrefixTypeTokens { + PrefixTypeTokens { + prefixref_types: TokenStream2::new(), + prefixref_impls: TokenStream2::new(), + } + } + let struct_ = match ds.variants.get(0) { Some(x) => x, - None => return, + None => return Ok(default_prefixtype_tokens()), }; let prefix = match &config.kind { StabilityKind::Prefix(prefix) => prefix, - _ => return, + _ => return Ok(default_prefixtype_tokens()), }; let first_suffix_field = prefix.first_suffix_field.field_pos; @@ -327,7 +339,7 @@ accessible through [`{prefix_name}`](./struct.{prefix_name}.html), with `.0.pref let prefix_ref = prefix.prefix_ref; // Generating the `` struct - { + let generated_types = { let vis = ds.vis; let generics = ds.generics; @@ -358,7 +370,7 @@ accessible through [`{prefix_name}`](./struct.{prefix_name}.html), with `.0.pref #[doc=#prefix_ref_docs] #[repr(transparent)] #vis struct #prefix_ref #generics ( - #vis #module::__sabi_re::PrefixRef< + #vis ::abi_stable::pmr::PrefixRef< #prefix_fields_struct #ty_generics, > )#where_clause; @@ -381,11 +393,10 @@ accessible through [`{prefix_name}`](./struct.{prefix_name}.html), with `.0.pref // Using this to ensure that the struct has at least the alignment of usize, // so that adding pointer fields is not an ABI breaking change. __sabi_usize_alignment: [usize; 0], - __sabi_pt_unbounds: #module::__sabi_re::NotCopyNotClone, + __sabi_pt_unbounds: ::abi_stable::pmr::NotCopyNotClone, } ) - .to_tokens(ts); - } + }; let mut accessor_buffer = String::new(); @@ -581,20 +592,18 @@ accessible through [`{prefix_name}`](./struct.{prefix_name}.html), with `.0.pref let mut pt_layout_ident = parse_str_as_ident(&format!("__sabi_PT_LAYOUT{}", deriving_name)); pt_layout_ident.set_span(deriving_name.span()); - quote!(const _: () = { - use #module::__sabi_re; - + let mut generated_impls = quote!( #[allow(non_upper_case_globals)] - const #pt_layout_ident:&'static #module::__PTStructLayout ={ + const #pt_layout_ident:&'static __sabi_re::PTStructLayout ={ &__sabi_re::PTStructLayout::new( #stringified_generics_tokenizer, - #module::#mono_type_layout, + #mono_type_layout, ) }; unsafe impl #impl_generics - __sabi_re::PrefixTypeTrait - for #deriving_name #ty_generics + __sabi_re::PrefixTypeTrait + for #deriving_name #ty_generics where #(#where_preds_a,)* #(#prefix_bounds,)* @@ -610,7 +619,7 @@ accessible through [`{prefix_name}`](./struct.{prefix_name}.html), with `.0.pref ) }; // A description of the struct used for error messages. - const PT_LAYOUT:&'static #module::__PTStructLayout =#pt_layout_ident; + const PT_LAYOUT:&'static __sabi_re::PTStructLayout =#pt_layout_ident; type PrefixFields = #prefix_fields_struct #ty_generics; type PrefixRef = #prefix_ref #ty_generics; @@ -618,7 +627,7 @@ accessible through [`{prefix_name}`](./struct.{prefix_name}.html), with `.0.pref #[allow(non_upper_case_globals, clippy::needless_lifetimes, clippy::new_ret_no_self)] impl #impl_generics #prefix_ref #ty_generics - where + where #(#where_preds_b,)* { #( @@ -632,8 +641,7 @@ accessible through [`{prefix_name}`](./struct.{prefix_name}.html), with `.0.pref #field_i_a; )* } - };) - .to_tokens(ts); + ); let first_offset = if let Some(constant) = offset_consts.first() { quote!( @@ -656,9 +664,7 @@ accessible through [`{prefix_name}`](./struct.{prefix_name}.html), with `.0.pref let prev_tys = struct_.fields.iter().map(|f| f.ty); let curr_tys = prev_tys.clone().skip(1); - quote!( const _: () = { - use #module::__sabi_re; - + generated_impls.append_all(quote!( #[allow( clippy::ptr_offset_with_cast, clippy::needless_lifetimes, @@ -666,13 +672,13 @@ accessible through [`{prefix_name}`](./struct.{prefix_name}.html), with `.0.pref non_upper_case_globals, )] impl #impl_generics #prefix_ref #ty_generics - where + where #(#where_preds_c,)* #(#prefix_bounds,)* { #first_offset #( - const #curr_offsets: usize = + const #curr_offsets: usize = __sabi_re::next_field_offset::< #deriving_name #ty_generics, #prev_tys, @@ -687,13 +693,13 @@ accessible through [`{prefix_name}`](./struct.{prefix_name}.html), with `.0.pref // 0:the field is inaccessible. // 1:the field is accessible. const __SABI_PTT_FAM:u64= - <#deriving_name #ty_generics as - __sabi_re::PrefixTypeTrait + <#deriving_name #ty_generics as + __sabi_re::PrefixTypeTrait >::PT_FIELD_ACCESSIBILITY.bits(); /// Accessor to get the layout of the type,used for error messages. #[inline(always)] - pub fn _prefix_type_layout(self)-> &'static #module::__PTStructLayout { + pub fn _prefix_type_layout(self)-> &'static __sabi_re::PTStructLayout { self.0.metadata().type_layout() } @@ -703,7 +709,7 @@ accessible through [`{prefix_name}`](./struct.{prefix_name}.html), with `.0.pref )* } - unsafe impl #impl_generics __sabi_re::ImmutableRef for #prefix_ref #ty_generics + unsafe impl #impl_generics __sabi_re::ImmutableRef for #prefix_ref #ty_generics where #(#where_preds_rl,)* { @@ -713,43 +719,20 @@ accessible through [`{prefix_name}`](./struct.{prefix_name}.html), with `.0.pref >; } - unsafe impl #impl_generics __sabi_re::PrefixRefTrait for #prefix_ref #ty_generics + unsafe impl #impl_generics __sabi_re::PrefixRefTrait for #prefix_ref #ty_generics where #(#where_preds_r2,)* { type PrefixFields = #prefix_fields_struct #ty_generics; } - // unsafe impl #impl_generics __sabi_re::GetStaticEquivalent_ - // for #prefix_ref #ty_generics - // where - // #(#where_preds_d0,)* - // #prefix_fields_struct #ty_generics: __sabi_re::GetStaticEquivalent_ - // { - // type StaticEquivalent = - // __sabi_re::GetStaticEquivalent<#prefix_fields_struct #ty_generics>; - // } - - // unsafe impl #impl_generics __sabi_re::StableAbi for #prefix_ref #ty_generics - // where - // #(#where_preds_d1,)* - // #prefix_fields_struct #ty_generics: __sabi_re::PrefixStableAbi - // { - // type IsNonZeroType = __sabi_re::True; - - // const LAYOUT: &'static __sabi_re::TypeLayout = - // <__sabi_re::PrefixRef<#prefix_fields_struct #ty_generics> - // as __sabi_re::StableAbi - // >::LAYOUT; - // } - impl #impl_generics Copy for #prefix_ref #ty_generics - where + where #(#where_preds_e,)* {} impl #impl_generics Clone for #prefix_ref #ty_generics - where + where #(#where_preds_f,)* { fn clone(&self) -> Self { @@ -757,7 +740,11 @@ accessible through [`{prefix_name}`](./struct.{prefix_name}.html), with `.0.pref } } - };) - .to_tokens(ts); - })) + )); + + PrefixTypeTokens { + prefixref_types: generated_types, + prefixref_impls: generated_impls, + } + }) } From d7567304e0fbe8c15dbccfaa3fcba20f144ebd34 Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Thu, 28 Oct 2021 00:38:59 -0300 Subject: [PATCH 24/32] Added f32 and f64 support --- .../src/abi_stability/stable_abi_trait.rs | 49 +++++++++++++++++++ abi_stable/tests/layout_tests/value.rs | 2 + .../interface/src/lib.rs | 7 +++ 3 files changed, 58 insertions(+) diff --git a/abi_stable/src/abi_stability/stable_abi_trait.rs b/abi_stable/src/abi_stability/stable_abi_trait.rs index c3b11039..ab038f28 100644 --- a/abi_stable/src/abi_stability/stable_abi_trait.rs +++ b/abi_stable/src/abi_stability/stable_abi_trait.rs @@ -1062,6 +1062,55 @@ impl_for_primitive_ints! { (bool ,"bool" ,TLPrimitive::Bool), } +// This is a workaround due to it being ABI breaking to add variants to TLPrimitive. +macro_rules! impl_for_floating_point { + ( + $( ($type:ty, $type_name:literal) ,)* + ) => ( + $( + unsafe impl GetStaticEquivalent_ for $type { + type StaticEquivalent=Self; + } + unsafe impl StableAbi for $type { + type IsNonZeroType=False; + + const LAYOUT: &'static TypeLayout = { + const MONO_TYPE_LAYOUT: &MonoTypeLayout = &MonoTypeLayout::new( + *mono_shared_vars, + rstr!($type_name), + ItemInfo::primitive(), + MonoTLData::Opaque, + tl_genparams!(;;), + ReprAttr::Primitive, + ModReflMode::Module, + RSlice::EMPTY, + ); + + make_shared_vars!{ + impl[] $type; + + let (mono_shared_vars, shared_vars)={ + type_layouts=[], + }; + } + + &TypeLayout::from_std::( + shared_vars, + MONO_TYPE_LAYOUT, + Self::ABI_CONSTS, + GenericTLData::Opaque, + ) + }; + } + )* + ) +} + +impl_for_floating_point! { + (f32, "f32"), + (f64, "f64"), +} + macro_rules! impl_for_concrete { ( type IsNonZeroType=$zeroness:ty; diff --git a/abi_stable/tests/layout_tests/value.rs b/abi_stable/tests/layout_tests/value.rs index 3790818a..8959b064 100644 --- a/abi_stable/tests/layout_tests/value.rs +++ b/abi_stable/tests/layout_tests/value.rs @@ -293,6 +293,8 @@ fn same_different_abi_stability() { <[u32; 3]>::LAYOUT, ::LAYOUT, ::LAYOUT, + ::LAYOUT, + ::LAYOUT, ::LAYOUT, ::LAYOUT, ::LAYOUT, diff --git a/testing/version_compatibility/interface/src/lib.rs b/testing/version_compatibility/interface/src/lib.rs index 7caaa7cf..3be7e763 100644 --- a/testing/version_compatibility/interface/src/lib.rs +++ b/testing/version_compatibility/interface/src/lib.rs @@ -98,6 +98,12 @@ mod many_types { marker_type::NonOwningPhantom, marker_type::NonOwningPhantom, ); + + // Adding more types in a patch release, + // you can merge this with ManyTypes in the next breaking release. + #[repr(C)] + #[derive(abi_stable::StableAbi)] + pub struct ManyTypes2(f32, f64); } pub use many_types::ManyTypes; @@ -109,6 +115,7 @@ pub use many_types::ManyTypes; pub struct RootMod { pub abi_stable_version: VersionStrings, pub _marker: NonOwningPhantom, + pub _marker2: NonOwningPhantom, } impl RootModule for RootMod_Ref { From acf661e00b0b7afc92405d58278bc8d02fbc5c5b Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Thu, 28 Oct 2021 03:21:08 -0300 Subject: [PATCH 25/32] Bumped patch versions to 0.10.3 Added f32 and f64 to version compatibility testing, currently conditional on new_abi_stable. Please remove the cfg when the 0.10.3 is uploaded. --- abi_stable/Cargo.toml | 6 +++--- abi_stable_derive/Cargo.toml | 8 ++++---- abi_stable_shared/Cargo.toml | 2 +- as_derive_utils/Cargo.toml | 2 +- testing/version_compatibility/interface/src/lib.rs | 2 ++ 5 files changed, 11 insertions(+), 9 deletions(-) diff --git a/abi_stable/Cargo.toml b/abi_stable/Cargo.toml index 6803df14..50a06c40 100644 --- a/abi_stable/Cargo.toml +++ b/abi_stable/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "abi_stable" -version = "0.10.2" +version = "0.10.3" authors = ["rodrimati1992 "] edition="2018" license = "MIT/Apache-2.0" @@ -56,8 +56,8 @@ channels=["crossbeam-channel"] [dependencies] -abi_stable_derive= {version="0.10.2",path="../abi_stable_derive"} -abi_stable_shared= {version="0.10.2",path="../abi_stable_shared"} +abi_stable_derive= {version="0.10.3",path="../abi_stable_derive"} +abi_stable_shared= {version="0.10.3",path="../abi_stable_shared"} serde = { version = "1.0.127", features = ["derive"] } repr_offset = { version = "0.2.1", default_features = false } serde_derive = "1.0.127" diff --git a/abi_stable_derive/Cargo.toml b/abi_stable_derive/Cargo.toml index dfe5f7b1..afc87f5a 100644 --- a/abi_stable_derive/Cargo.toml +++ b/abi_stable_derive/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "abi_stable_derive" -version = "0.10.2" +version = "0.10.3" authors = ["rodrimati1992 "] edition = "2018" description = "Implementation detail of abi_stable." @@ -20,7 +20,7 @@ include = [ [features] [dependencies] -abi_stable_shared= {version="0.10.2",path="../abi_stable_shared"} +abi_stable_shared= {version="0.10.3",path="../abi_stable_shared"} quote = "1.0.7" typed-arena = "2.0.1" @@ -39,11 +39,11 @@ features=["full","extra-traits","visit","visit-mut"] ###### as_derive_utils [dependencies.as_derive_utils] -version="0.10.0" +version="0.10.3" path="../as_derive_utils" [dev-dependencies.as_derive_utils] -version="0.10.0" +version="0.10.3" path="../as_derive_utils" features=["testing"] diff --git a/abi_stable_shared/Cargo.toml b/abi_stable_shared/Cargo.toml index 6813ae91..08a91001 100644 --- a/abi_stable_shared/Cargo.toml +++ b/abi_stable_shared/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "abi_stable_shared" -version = "0.10.2" +version = "0.10.3" authors = ["rodrimati1992 "] edition = "2018" description = "Implementation detail of abi_stable." diff --git a/as_derive_utils/Cargo.toml b/as_derive_utils/Cargo.toml index 2fc27e38..f88e8eba 100644 --- a/as_derive_utils/Cargo.toml +++ b/as_derive_utils/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "as_derive_utils" -version = "0.10.2" +version = "0.10.3" authors = ["rodrimati1992 "] edition = "2018" description = "private derive utilities used by abi_stable and structural." diff --git a/testing/version_compatibility/interface/src/lib.rs b/testing/version_compatibility/interface/src/lib.rs index 3be7e763..1d87ad24 100644 --- a/testing/version_compatibility/interface/src/lib.rs +++ b/testing/version_compatibility/interface/src/lib.rs @@ -101,6 +101,7 @@ mod many_types { // Adding more types in a patch release, // you can merge this with ManyTypes in the next breaking release. + #[cfg(feature = "new_abi_stable")] #[repr(C)] #[derive(abi_stable::StableAbi)] pub struct ManyTypes2(f32, f64); @@ -115,6 +116,7 @@ pub use many_types::ManyTypes; pub struct RootMod { pub abi_stable_version: VersionStrings, pub _marker: NonOwningPhantom, + #[cfg(feature = "new_abi_stable")] pub _marker2: NonOwningPhantom, } From 185a0c62fa2101f6bfbffd93d29bc425d7153745 Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Thu, 28 Oct 2021 03:57:55 -0300 Subject: [PATCH 26/32] Updated CI config and Changelog Added 1.51.0 version to CI config. Added check in CI that code is formatted. Fixed compilation error in vec.rs due to bad merge --- .github/workflows/rust.yml | 15 +++++++- Changelog.md | 65 ++++++++++++++++++++++++++++++++- abi_stable/src/std_types/vec.rs | 2 +- 3 files changed, 78 insertions(+), 4 deletions(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index a8c407de..5a2f45f7 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -12,14 +12,25 @@ jobs: strategy: max-parallel: 2 matrix: - rust: [stable, beta, nightly, 1.41.0] + rust: [stable, beta, nightly, 1.41.0, 1.51.0] os: [ubuntu-latest, windows-latest, macOS-latest] steps: - name: enable-rust-stable - if: matrix.rust == 'stable' || matrix.rust == 'beta' || matrix.rust == 'nightly' + if: matrix.rust == '1.51.0' run: echo "rustv=rust_1_51" >> $GITHUB_ENV + - name: enable-rust-stable + if: matrix.rust == 'stable' || matrix.rust == 'beta' || matrix.rust == 'nightly' + run: echo "rustv=rust_latest_stable" >> $GITHUB_ENV + + - uses: actions/checkout@v2 + - name: ci-format + run: | + rustup override set ${{ matrix.rust }} + cd "${{github.workspace}}/" + cargo fmt -- --check + - uses: actions/checkout@v2 - name: ci-all-versions run: | diff --git a/Changelog.md b/Changelog.md index a107450e..a7e38a75 100644 --- a/Changelog.md +++ b/Changelog.md @@ -1,7 +1,70 @@ -This is the changelog,summarising changes in each version(some minor changes may be ommited). +This is the changelog,summarising changes in each version + +Minor changes may be ommited, as well as improvements to documentation. # 0.10 +### 0.10.3 + + +Added `StableAbi` impls for `f32` and `f64`. + +Fixed error in `StableAbi` derive caused by using the derive inside a function with the `proc_macro_derive_resolution_fallback` lint enabled (deny-by-default in nightly). + +Deprecated `abi_stable::library::mangled_root_module_loader_name` function. + +Superceeded the `mangled_root_module_loader_name` function (and uses of it) with these `abi_stable::library` constants: +- `ROOT_MODULE_LOADER_NAME` +- `ROOT_MODULE_LOADER_NAME_WITH_NUL` +- `ROOT_MODULE_LOADER_NAME_NULSTR` + +Added `NulStr::{as_ptr, try_from_str}` associated functions. + +Added `ǸulStrError`, returned by `NulStr::try_from_str` + +Added `PartialEq` impls for comparing `str` and `NulStr` in both directions. + +Added Default, PartialOrd, and Ord impls for NulStr. + +Made `NulStr::from_str` safe, by not requiring no internal nul bytes. + +Deprecated `nul_str` macro. + +Added `nulstr` and `nulstr_trunc` macros. + +Added "rust_1_46" feature. + +Added "rust_latest_stable" feature. + +Added `LibHeader::ensure_layout` method. + +Fixed `StaticRef::as_prefix` doc example. + +Added `for_examples::PhantModule` struct + +Added `RHashMap::{keys, values}` methods for iterating over the map, which return the `Keys` and `Values` iterators respectively. + +Added `Index` and `IndexMut` impls for `RSliceMut` and `RVec` + +Added `Index` impl for `RSlice` + +Changed these methods to use `R: RangeBounds` instead of `[T]: Index` or `Index`: +- `RVec::slice` +- `RVec::slice_mut` +- `RVec::drain` + +Replaced all `Into` implementations converting from `abi_stable` types with `From` impls converting in the same direction. + +Rewrote `staticref` macro to support more cases of static promotion, this breaks non-inherent-impl uses of the macro(it was documented that this breaking change could happen). + +Made libraries loaded with `RootModule` never be unloaded, previously they were unloaded when the type layout of the root module isn't compatible (this was possibly unsound?). + +Formatted documentation examples (all doc examples up to `sabi_types` were formatted with `rustfmt`, every one from `std_types` up to the last module were manually formatted). + +Added dependency on `paste` 1.0 + +Enabled the "macro_utils" feature of `core_extensions` + ### 0.10.1 Fixed support for building in ARM, from this pull request: https://github.com/rodrimati1992/abi_stable_crates/pull/50 diff --git a/abi_stable/src/std_types/vec.rs b/abi_stable/src/std_types/vec.rs index fd88e6ab..7fdc0467 100644 --- a/abi_stable/src/std_types/vec.rs +++ b/abi_stable/src/std_types/vec.rs @@ -1201,7 +1201,7 @@ impl RVec { /// ``` /// /// - pub fn drain(&mut self, index: I) -> Drain<'_, T> + pub fn drain(&mut self, range: R) -> Drain<'_, T> where R: RangeBounds, { From 1aaf9e31938c9b5005eb6907bf5e1555c44e9f63 Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Thu, 28 Oct 2021 05:47:55 -0300 Subject: [PATCH 27/32] Formatted std_types examples. --- abi_stable/src/erased_types/dyn_trait.rs | 2 +- abi_stable/src/std_types/arc.rs | 26 +++--- abi_stable/src/std_types/boxed.rs | 11 ++- abi_stable/src/std_types/cmp_ordering.rs | 7 +- abi_stable/src/std_types/cow.rs | 30 +++---- abi_stable/src/std_types/map.rs | 6 +- abi_stable/src/std_types/map/entry.rs | 28 +++--- abi_stable/src/std_types/option.rs | 90 ++++++++++---------- abi_stable/src/std_types/result.rs | 56 +++++++----- abi_stable/src/std_types/slice_mut.rs | 91 +++++++++++++------- abi_stable/src/std_types/slices.rs | 40 ++++----- abi_stable/src/std_types/std_io.rs | 34 ++++---- abi_stable/src/std_types/str.rs | 8 +- abi_stable/src/std_types/string.rs | 39 ++++----- abi_stable/src/std_types/time.rs | 36 ++++---- abi_stable/src/std_types/tuple.rs | 8 +- abi_stable/src/std_types/utypeid.rs | 20 ++--- abi_stable/src/std_types/vec.rs | 103 ++++++++++++++--------- abi_stable/src/std_types/vec/iters.rs | 40 ++++----- 19 files changed, 359 insertions(+), 316 deletions(-) diff --git a/abi_stable/src/erased_types/dyn_trait.rs b/abi_stable/src/erased_types/dyn_trait.rs index 3c16d90f..e9ed5600 100644 --- a/abi_stable/src/erased_types/dyn_trait.rs +++ b/abi_stable/src/erased_types/dyn_trait.rs @@ -352,7 +352,7 @@ mod priv_ { /// serde_json::to_string(&object).unwrap(), /// r##"{"name":"nope"}"## /// ); - /// # } + /// } /// /// ``` /// diff --git a/abi_stable/src/std_types/arc.rs b/abi_stable/src/std_types/arc.rs index bbfcc508..96954de1 100644 --- a/abi_stable/src/std_types/arc.rs +++ b/abi_stable/src/std_types/arc.rs @@ -178,7 +178,7 @@ impl RArc { /// /// let arc = RArc::new(100); /// - /// assert_eq!( RArc::into_arc(arc), Arc::new(100) ); + /// assert_eq!(RArc::into_arc(arc), Arc::new(100)); /// /// ``` pub fn into_arc(this: Self) -> Arc @@ -207,11 +207,11 @@ impl RArc { /// use abi_stable::std_types::RArc; /// /// let arc0 = RArc::new(100); - /// assert_eq!( RArc::try_unwrap(arc0), Ok(100) ); + /// assert_eq!(RArc::try_unwrap(arc0), Ok(100)); /// /// let arc1 = RArc::new(100); /// let arc1_clone = RArc::clone(&arc1); - /// assert_eq!( RArc::try_unwrap(arc1), Err(arc1_clone.clone()) ); + /// assert_eq!(RArc::try_unwrap(arc1), Err(arc1_clone.clone())); /// /// ``` #[inline] @@ -230,11 +230,11 @@ impl RArc { /// /// let mut arc0 = RArc::new(100); /// *RArc::get_mut(&mut arc0).unwrap() += 400; - /// assert_eq!( *arc0, 500 ); + /// assert_eq!(*arc0, 500); /// /// let mut arc1 = RArc::new(100); /// let _arc1_clone = RArc::clone(&arc1); - /// assert_eq!( RArc::get_mut(&mut arc1), None ); + /// assert_eq!(RArc::get_mut(&mut arc1), None); /// /// ``` #[inline] @@ -262,13 +262,13 @@ impl RArc { /// /// let mut arc0 = RArc::new(100); /// *RArc::make_mut(&mut arc0) += 400; - /// assert_eq!( *arc0, 500 ); + /// assert_eq!(*arc0, 500); /// /// let mut arc1 = RArc::new(100); /// let arc1_clone = RArc::clone(&arc1); /// *RArc::make_mut(&mut arc1) += 400; - /// assert_eq!( *arc1, 500 ); - /// assert_eq!( *arc1_clone, 100 ); + /// assert_eq!(*arc1, 500); + /// assert_eq!(*arc1_clone, 100); /// /// ``` #[inline] @@ -298,10 +298,10 @@ impl RArc { /// use abi_stable::std_types::RArc; /// /// let arc = RArc::new(0); - /// assert_eq!( RArc::strong_count(&arc), 1 ); + /// assert_eq!(RArc::strong_count(&arc), 1); /// /// let clone = RArc::clone(&arc); - /// assert_eq!( RArc::strong_count(&arc), 2 ); + /// assert_eq!(RArc::strong_count(&arc), 2); /// /// ``` pub fn strong_count(this: &Self) -> usize { @@ -320,13 +320,13 @@ impl RArc { /// /// let rustarc = Arc::new(0); /// let arc = RArc::from(rustarc.clone()); - /// assert_eq!( RArc::weak_count(&arc), 0 ); + /// assert_eq!(RArc::weak_count(&arc), 0); /// /// let weak_0 = Arc::downgrade(&rustarc); - /// assert_eq!( RArc::weak_count(&arc), 1 ); + /// assert_eq!(RArc::weak_count(&arc), 1); /// /// let weak_1 = Arc::downgrade(&rustarc); - /// assert_eq!( RArc::weak_count(&arc), 2 ); + /// assert_eq!(RArc::weak_count(&arc), 2); /// ``` pub fn weak_count(this: &Self) -> usize { let vtable = this.vtable(); diff --git a/abi_stable/src/std_types/boxed.rs b/abi_stable/src/std_types/boxed.rs index d456682c..f7a74c6c 100644 --- a/abi_stable/src/std_types/boxed.rs +++ b/abi_stable/src/std_types/boxed.rs @@ -69,7 +69,6 @@ mod private { /// }, /// } /// - /// /// ``` /// #[repr(C)] @@ -135,8 +134,8 @@ mod private { /// std_types::RBox, /// }; /// - /// let b = RSmallBox::<_, [u8;1]>::new(77u8); - /// let rbox: RBox<_> = b.in_move_ptr(|x| RBox::from_move_ptr(x) ); + /// let b = RSmallBox::<_, [u8; 1]>::new(77u8); + /// let rbox: RBox<_> = b.in_move_ptr(|x| RBox::from_move_ptr(x)); /// /// assert_eq!(*rbox, 77); /// @@ -209,8 +208,8 @@ impl RBox { /// ``` /// use abi_stable::std_types::RBox; /// - /// let baux: RBox = RBox::new(200); - /// let baux: Box = RBox::into_box(baux); + /// let baux: RBox = RBox::new(200); + /// let baux: Box = RBox::into_box(baux); /// assert_eq!(*baux, 200); /// /// ``` @@ -244,7 +243,7 @@ impl RBox { /// ``` /// use abi_stable::std_types::RBox; /// - /// let baux: RBox = RBox::new(200); + /// let baux: RBox = RBox::new(200); /// let baux: u32 = RBox::into_inner(baux); /// assert_eq!(baux, 200); /// diff --git a/abi_stable/src/std_types/cmp_ordering.rs b/abi_stable/src/std_types/cmp_ordering.rs index aa21c6bc..16aca567 100644 --- a/abi_stable/src/std_types/cmp_ordering.rs +++ b/abi_stable/src/std_types/cmp_ordering.rs @@ -43,10 +43,9 @@ impl RCmpOrdering { /// use abi_stable::std_types::RCmpOrdering; /// use std::cmp::Ordering; /// - /// - /// assert_eq!( RCmpOrdering::Less.into_ordering(), Ordering::Less ); - /// assert_eq!( RCmpOrdering::Equal.into_ordering(), Ordering::Equal ); - /// assert_eq!( RCmpOrdering::Greater.into_ordering(), Ordering::Greater ); + /// assert_eq!(RCmpOrdering::Less.into_ordering(), Ordering::Less); + /// assert_eq!(RCmpOrdering::Equal.into_ordering(), Ordering::Equal); + /// assert_eq!(RCmpOrdering::Greater.into_ordering(), Ordering::Greater); /// /// ``` #[inline] diff --git a/abi_stable/src/std_types/cow.rs b/abi_stable/src/std_types/cow.rs index de92f4f4..4ac8aed4 100644 --- a/abi_stable/src/std_types/cow.rs +++ b/abi_stable/src/std_types/cow.rs @@ -230,7 +230,7 @@ where /// ``` /// use abi_stable::std_types::RCow; /// - /// let mut cow: RCow<'_, str> = RCow::from("Hello"); + /// let mut cow: RCow<'_, str> = RCow::from("Hello"); /// /// assert_eq!(&*cow, "Hello"); /// assert!(cow.is_borrowed()); @@ -259,7 +259,7 @@ where /// ``` /// use abi_stable::std_types::RCow; /// - /// let mut cow: RCow<'_, str> = RCow::from("Hello"); + /// let mut cow: RCow<'_, str> = RCow::from("Hello"); /// /// assert_eq!(&*cow, "Hello"); /// @@ -283,12 +283,12 @@ where /// ``` /// use abi_stable::std_types::{RCow, RSlice}; /// { - /// let cow: RCow<'_, [u8]> = RCow::from(&[0, 1, 2, 3][..]); - /// assert_eq!( cow.borrowed(), RSlice::from_slice(&[0, 1, 2, 3]) ); + /// let cow: RCow<'_, [u8]> = RCow::from(&[0, 1, 2, 3][..]); + /// assert_eq!(cow.borrowed(), RSlice::from_slice(&[0, 1, 2, 3])); /// } /// { - /// let cow: RCow<'_, [u8]> = RCow::from(vec![0, 1, 2, 3]); - /// assert_eq!( cow.borrowed(), RSlice::from_slice(&[0, 1, 2, 3]) ); + /// let cow: RCow<'_, [u8]> = RCow::from(vec![0, 1, 2, 3]); + /// assert_eq!(cow.borrowed(), RSlice::from_slice(&[0, 1, 2, 3])); /// } /// ``` pub fn borrowed<'b: 'a>(&'b self) -> >::RBorrowed { @@ -306,12 +306,12 @@ where /// use abi_stable::std_types::RCow; /// /// { - /// let cow: RCow<'_, [u8]> = RCow::from(&[0, 1, 2, 3][..]); - /// assert!( cow.is_borrowed() ); + /// let cow: RCow<'_, [u8]> = RCow::from(&[0, 1, 2, 3][..]); + /// assert!(cow.is_borrowed()); /// } /// { - /// let cow: RCow<'_, [u8]> = RCow::from(vec![0, 1, 2, 3]); - /// assert!( !cow.is_borrowed() ); + /// let cow: RCow<'_, [u8]> = RCow::from(vec![0, 1, 2, 3]); + /// assert!(!cow.is_borrowed()); /// } /// /// ``` @@ -326,11 +326,11 @@ where /// ``` /// use abi_stable::std_types::RCow; /// - /// let cow: RCow<'_, [u8]> = RCow::from(&[0, 1, 2, 3][..]); - /// assert!( !cow.is_owned() ); + /// let cow: RCow<'_, [u8]> = RCow::from(&[0, 1, 2, 3][..]); + /// assert!(!cow.is_owned()); /// - /// let cow: RCow<'_, [u8]> = RCow::from(vec![0, 1, 2, 3]); - /// assert!( cow.is_owned() ); + /// let cow: RCow<'_, [u8]> = RCow::from(vec![0, 1, 2, 3]); + /// assert!(cow.is_owned()); /// /// ``` pub fn is_owned(&self) -> bool { @@ -756,7 +756,6 @@ where /// /// assert!(deserialized_slice.cow.is_borrowed()); /// -/// /// ``` /// #[derive(Deserialize)] @@ -786,7 +785,6 @@ pub struct BorrowingRCowU8Slice<'a> { /// /// assert!(deserialized_slice.cow.is_borrowed()); /// -/// /// ``` /// #[derive(Deserialize)] diff --git a/abi_stable/src/std_types/map.rs b/abi_stable/src/std_types/map.rs index 18d98fd2..e34586a1 100644 --- a/abi_stable/src/std_types/map.rs +++ b/abi_stable/src/std_types/map.rs @@ -81,11 +81,11 @@ pub use self::{ /// assert!(k == "dictionary" || k == "pictograph"); /// /// assert!( -/// v == "A book/document containing definitions of words" -/// || v == "A picture representating of a word.", +/// v == "A book/document containing definitions of words" || +/// v == "A picture representating of a word.", /// "{} => {}", /// k, -/// v +/// v, /// ); /// } /// diff --git a/abi_stable/src/std_types/map/entry.rs b/abi_stable/src/std_types/map/entry.rs index 81430338..7e4ffeda 100644 --- a/abi_stable/src/std_types/map/entry.rs +++ b/abi_stable/src/std_types/map/entry.rs @@ -87,7 +87,7 @@ impl<'a, K, V> REntry<'a, K, V> { /// ``` /// use abi_stable::std_types::RHashMap; /// - /// let mut map: RHashMap = vec![(1, 100)].into_iter().collect(); + /// let mut map: RHashMap = vec![(1, 100)].into_iter().collect(); /// /// assert_eq!(map.entry(0).get(), None); /// assert_eq!(map.entry(1).get(), Some(&100)); @@ -107,7 +107,7 @@ impl<'a, K, V> REntry<'a, K, V> { /// ``` /// use abi_stable::std_types::RHashMap; /// - /// let mut map: RHashMap = vec![(1, 100)].into_iter().collect(); + /// let mut map: RHashMap = vec![(1, 100)].into_iter().collect(); /// /// assert_eq!(map.entry(0).get_mut(), None); /// assert_eq!(map.entry(1).get_mut(), Some(&mut 100)); @@ -153,12 +153,12 @@ impl<'a, K, V> REntry<'a, K, V> { /// let mut map = RHashMap::::new(); /// /// assert_eq!( - /// map.entry(0).or_insert_with(|| "foo".into() ), + /// map.entry(0).or_insert_with(|| "foo".into()), /// &mut RString::from("foo") /// ); /// /// assert_eq!( - /// map.entry(0).or_insert_with(|| "bar".into() ), + /// map.entry(0).or_insert_with(|| "bar".into()), /// &mut RString::from("foo") /// ); /// @@ -183,10 +183,7 @@ impl<'a, K, V> REntry<'a, K, V> { /// let mut map = RHashMap::::new(); /// map.insert("foo".into(), "bar".into()); /// - /// assert_eq!( - /// map.entry("foo".into()).key(), - /// &RString::from("foo") - /// ); + /// assert_eq!(map.entry("foo".into()).key(), &RString::from("foo")); /// ``` pub fn key(&self) -> &K { match self { @@ -209,8 +206,8 @@ impl<'a, K, V> REntry<'a, K, V> { /// /// assert_eq!( /// map.entry("foo".into()) - /// .and_modify(|x| x.push_str("hoo") ) - /// .get(), + /// .and_modify(|x| x.push_str("hoo")) + /// .get(), /// Some(&RString::from("barhoo")) /// ); /// ``` @@ -331,7 +328,6 @@ impl<'a, K, V> ROccupiedEntry<'a, K, V> { /// REntry::Vacant(_) => unreachable!(), /// }; /// - /// /// ``` pub fn key(&self) -> &K { let vtable = self.vtable(); @@ -440,7 +436,7 @@ impl<'a, K, V> ROccupiedEntry<'a, K, V> { /// } /// } /// - /// assert_eq!( map.get("baz"), Some(&0xDEAD)); + /// assert_eq!(map.get("baz"), Some(&0xDEAD)); /// /// ``` pub fn insert(&mut self, value: V) -> V { @@ -469,7 +465,7 @@ impl<'a, K, V> ROccupiedEntry<'a, K, V> { /// } /// } /// - /// assert!( ! map.contains_key("baz") ); + /// assert!(!map.contains_key("baz")); /// /// ``` pub fn remove(self) -> V { @@ -547,7 +543,7 @@ impl<'a, K, V> RVacantEntry<'a, K, V> { /// } /// } /// - /// assert_eq!( map.get(&1337), None ); + /// assert_eq!(map.get(&1337), None); /// /// ``` pub fn key(&self) -> &K { @@ -574,7 +570,7 @@ impl<'a, K, V> RVacantEntry<'a, K, V> { /// } /// } /// - /// assert_eq!( map.get("lol"), None ); + /// assert_eq!(map.get("lol"), None); /// /// ``` pub fn into_key(self) -> K { @@ -601,7 +597,7 @@ impl<'a, K, V> RVacantEntry<'a, K, V> { /// } /// } /// - /// assert_eq!( map.get("lol"), Some(&67) ); + /// assert_eq!(map.get("lol"), Some(&67)); /// /// ``` pub fn insert(self, value: V) -> &'a mut V { diff --git a/abi_stable/src/std_types/option.rs b/abi_stable/src/std_types/option.rs index 79671082..7149f341 100644 --- a/abi_stable/src/std_types/option.rs +++ b/abi_stable/src/std_types/option.rs @@ -29,8 +29,8 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10) .as_ref(), RSome(&10)); - /// assert_eq!(RNone::.as_ref(), RNone ); + /// assert_eq!(RSome(10).as_ref(), RSome(&10)); + /// assert_eq!(RNone::.as_ref(), RNone); /// /// ``` #[inline] @@ -48,8 +48,8 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10) .as_mut(), RSome(&mut 10)); - /// assert_eq!(RNone::.as_mut(), RNone ); + /// assert_eq!(RSome(10).as_mut(), RSome(&mut 10)); + /// assert_eq!(RNone::.as_mut(), RNone); /// /// ``` #[inline] @@ -67,7 +67,7 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10) .is_rsome(), true); + /// assert_eq!(RSome(10).is_rsome(), true); /// assert_eq!(RNone::.is_rsome(), false); /// /// ``` @@ -83,7 +83,7 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10) .is_rnone(), false); + /// assert_eq!(RSome(10).is_rnone(), false); /// assert_eq!(RNone::.is_rnone(), true); /// /// ``` @@ -99,7 +99,7 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10) .is_some(), true); + /// assert_eq!(RSome(10).is_some(), true); /// assert_eq!(RNone::.is_some(), false); /// /// ``` @@ -115,7 +115,7 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10) .is_none(), false); + /// assert_eq!(RSome(10).is_none(), false); /// assert_eq!(RNone::.is_none(), true); /// /// ``` @@ -131,8 +131,8 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10) .into_option(), Some(10)); - /// assert_eq!(RNone::.into_option(), None ); + /// assert_eq!(RSome(10).into_option(), Some(10)); + /// assert_eq!(RNone::.into_option(), None); /// /// ``` #[inline] @@ -151,7 +151,7 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!( RSome(100).expect("must contain a value"), 100 ); + /// assert_eq!(RSome(100).expect("must contain a value"), 100); /// /// ``` /// @@ -176,7 +176,7 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!( RSome(500).unwrap(), 500 ); + /// assert_eq!(RSome(500).unwrap(), 500); /// /// ``` /// @@ -198,7 +198,7 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10) .unwrap_or(99), 10); + /// assert_eq!(RSome(10).unwrap_or(99), 10); /// assert_eq!(RNone::.unwrap_or(99), 99); /// /// ``` @@ -217,7 +217,7 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10) .unwrap_or_default(), 10); + /// assert_eq!(RSome(10).unwrap_or_default(), 10); /// assert_eq!(RNone::.unwrap_or_default(), 0); /// /// ``` @@ -240,8 +240,8 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10) .unwrap_or_else(|| 77 ), 10); - /// assert_eq!(RNone::.unwrap_or_else(|| 77 ), 77); + /// assert_eq!(RSome(10).unwrap_or_else(|| 77), 10); + /// assert_eq!(RNone::.unwrap_or_else(|| 77), 77); /// /// ``` #[inline] @@ -263,8 +263,8 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10) .map(|x| x*2 ), RSome(20)); - /// assert_eq!(RNone::.map(|x| x*2 ), RNone); + /// assert_eq!(RSome(10).map(|x| x * 2), RSome(20)); + /// assert_eq!(RNone::.map(|x| x * 2), RNone); /// /// ``` #[inline] @@ -286,8 +286,8 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10) .map_or(77, |x| x*2 ), 20); - /// assert_eq!(RNone::.map_or(77, |x| x*2 ), 77); + /// assert_eq!(RSome(10).map_or(77, |x| x * 2), 20); + /// assert_eq!(RNone::.map_or(77, |x| x * 2), 77); /// /// ``` #[inline] @@ -309,8 +309,8 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10) .map_or_else(||77, |x| x*2 ), 20); - /// assert_eq!(RNone::.map_or_else(||77, |x| x*2 ), 77); + /// assert_eq!(RSome(10).map_or_else(|| 77, |x| x * 2), 20); + /// assert_eq!(RNone::.map_or_else(|| 77, |x| x * 2), 77); /// /// ``` #[inline] @@ -332,10 +332,10 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10).filter(|x| (x%2) == 0 ), RSome(10)); - /// assert_eq!(RSome(10).filter(|x| (x%2) == 1 ), RNone ); - /// assert_eq!(RNone::.filter(|_| true ), RNone ); - /// assert_eq!(RNone::.filter(|_| false ), RNone ); + /// assert_eq!(RSome(10).filter(|x| (x % 2) == 0), RSome(10)); + /// assert_eq!(RSome(10).filter(|x| (x % 2) == 1), RNone); + /// assert_eq!(RNone::.filter(|_| true), RNone); + /// assert_eq!(RNone::.filter(|_| false), RNone); /// /// ``` pub fn filter

(self, predicate: P) -> Self @@ -358,9 +358,9 @@ impl ROption { /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(10).and(RSome(20)), RSome(20)); - /// assert_eq!(RSome(10).and(RNone ), RNone); + /// assert_eq!(RSome(10).and(RNone), RNone); /// assert_eq!(RNone::.and(RSome(20)), RNone); - /// assert_eq!(RNone::.and(RNone ), RNone); + /// assert_eq!(RNone::.and(RNone), RNone); /// /// ``` #[inline] @@ -379,10 +379,10 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10).and_then(|x|RSome(x * 2)), RSome(20)); - /// assert_eq!(RSome(10).and_then(|_|RNone::), RNone); - /// assert_eq!(RNone::.and_then(|x|RSome(x * 2)), RNone); - /// assert_eq!(RNone::.and_then(|_|RNone::), RNone); + /// assert_eq!(RSome(10).and_then(|x| RSome(x * 2)), RSome(20)); + /// assert_eq!(RSome(10).and_then(|_| RNone::), RNone); + /// assert_eq!(RNone::.and_then(|x| RSome(x * 2)), RNone); + /// assert_eq!(RNone::.and_then(|_| RNone::), RNone); /// /// ``` #[inline] @@ -425,10 +425,10 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10).or_else(|| RSome(20) ), RSome(10)); - /// assert_eq!(RSome(10).or_else(|| RNone ), RSome(10)); - /// assert_eq!(RNone::.or_else(|| RSome(20) ), RSome(20)); - /// assert_eq!(RNone::.or_else(|| RNone ), RNone); + /// assert_eq!(RSome(10).or_else(|| RSome(20)), RSome(10)); + /// assert_eq!(RSome(10).or_else(|| RNone), RSome(10)); + /// assert_eq!(RNone::.or_else(|| RSome(20)), RSome(20)); + /// assert_eq!(RNone::.or_else(|| RNone), RNone); /// /// ``` #[inline] @@ -450,10 +450,10 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10).xor(RSome(20)), RNone ); - /// assert_eq!(RSome(10).xor(RNone ), RSome(10)); + /// assert_eq!(RSome(10).xor(RSome(20)), RNone); + /// assert_eq!(RSome(10).xor(RNone), RSome(10)); /// assert_eq!(RNone::.xor(RSome(20)), RSome(20)); - /// assert_eq!(RNone::.xor(RNone ), RNone ); + /// assert_eq!(RNone::.xor(RNone), RNone); /// /// ``` #[inline] @@ -498,9 +498,9 @@ impl ROption { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(RSome(10).get_or_insert_with(||40), &mut 10); - /// assert_eq!(RSome(20).get_or_insert_with(||55), &mut 20); - /// assert_eq!(RNone::.get_or_insert_with(||77), &mut 77); + /// assert_eq!(RSome(10).get_or_insert_with(|| 40), &mut 10); + /// assert_eq!(RSome(20).get_or_insert_with(|| 55), &mut 20); + /// assert_eq!(RNone::.get_or_insert_with(|| 77), &mut 77); /// /// ``` #[inline] @@ -578,7 +578,7 @@ impl ROption<&T> { /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(&vec![()]).cloned(), RSome(vec![()])); - /// assert_eq!(RNone::<&Vec<()>>.cloned(), RNone ); + /// assert_eq!(RNone::<&Vec<()>>.cloned(), RNone); /// /// ``` #[inline] @@ -624,7 +624,7 @@ impl ROption<&mut T> { /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(&mut vec![()]).cloned(), RSome(vec![()])); - /// assert_eq!(RNone::<&mut Vec<()>>.cloned(), RNone ); + /// assert_eq!(RNone::<&mut Vec<()>>.cloned(), RNone); /// /// ``` #[inline] @@ -646,7 +646,7 @@ impl ROption<&mut T> { /// # use abi_stable::std_types::*; /// /// assert_eq!(RSome(&mut 7).copied(), RSome(7)); - /// assert_eq!(RNone::<&mut u32>.copied(), RNone ); + /// assert_eq!(RNone::<&mut u32>.copied(), RNone); /// /// ``` #[inline] diff --git a/abi_stable/src/std_types/result.rs b/abi_stable/src/std_types/result.rs index 7996eb05..7199444c 100644 --- a/abi_stable/src/std_types/result.rs +++ b/abi_stable/src/std_types/result.rs @@ -129,7 +129,7 @@ impl RResult { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(ROk::(10).into_result(), Ok (10)); + /// assert_eq!(ROk::(10).into_result(), Ok(10)); /// assert_eq!(RErr::(5).into_result(), Err(5)); /// /// ``` @@ -146,8 +146,8 @@ impl RResult { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(ROk::(10).map(|x| x*3 ), ROk(30)); - /// assert_eq!(RErr::(5).map(|x| x/2 ), RErr(5)); + /// assert_eq!(ROk::(10).map(|x| x * 3), ROk(30)); + /// assert_eq!(RErr::(5).map(|x| x / 2), RErr(5)); /// /// ``` #[inline] @@ -169,8 +169,8 @@ impl RResult { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(ROk::(10).map_err(|x| x*3 ), ROk(10)); - /// assert_eq!(RErr::(5).map_err(|x| x/2 ), RErr(2)); + /// assert_eq!(ROk::(10).map_err(|x| x * 3), ROk(10)); + /// assert_eq!(RErr::(5).map_err(|x| x / 2), RErr(2)); /// /// ``` #[inline] @@ -193,8 +193,8 @@ impl RResult { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(ROk::(10).map_or_else(|_|77 , |x| x*3 ), 30); - /// assert_eq!(RErr::(5).map_or_else(|e|e*4, |x| x/2 ), 20); + /// assert_eq!(ROk::(10).map_or_else(|_| 77, |x| x * 3), 30); + /// assert_eq!(RErr::(5).map_or_else(|e| e * 4, |x| x / 2), 20); /// /// ``` #[inline] @@ -215,19 +215,19 @@ impl RResult { /// # use abi_stable::std_types::*; /// /// assert_eq!( - /// ROk::(10).and_then(|x| ROk ::(x*3) ), - /// ROk (30), + /// ROk::(10).and_then(|x| ROk::(x * 3)), + /// ROk(30), /// ); /// assert_eq!( - /// ROk::(10).and_then(|x| RErr::(x*3)), + /// ROk::(10).and_then(|x| RErr::(x * 3)), /// RErr(30), /// ); /// assert_eq!( - /// RErr::(5).and_then(|x| ROk ::(x/2) ), + /// RErr::(5).and_then(|x| ROk::(x / 2)), /// RErr(5), /// ); /// assert_eq!( - /// RErr::(5).and_then(|x| RErr::(x/2) ), + /// RErr::(5).and_then(|x| RErr::(x / 2)), /// RErr(5), /// ); /// @@ -251,10 +251,22 @@ impl RResult { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(ROk::(10).or_else(|e| ROk ::(e*3) ) , ROk(10)); - /// assert_eq!(ROk::(10).or_else(|e| RErr::(e*3)) , ROk(10)); - /// assert_eq!(RErr::(5).or_else(|e| ROk ::(e/2) ), ROk (2)); - /// assert_eq!(RErr::(5).or_else(|e| RErr::(e/2) ), RErr(2)); + /// assert_eq!( + /// ROk::(10).or_else(|e| ROk::(e * 3)), + /// ROk(10) + /// ); + /// assert_eq!( + /// ROk::(10).or_else(|e| RErr::(e * 3)), + /// ROk(10) + /// ); + /// assert_eq!( + /// RErr::(5).or_else(|e| ROk::(e / 2)), + /// ROk(2) + /// ); + /// assert_eq!( + /// RErr::(5).or_else(|e| RErr::(e / 2)), + /// RErr(2) + /// ); /// /// ``` #[inline] @@ -280,7 +292,7 @@ impl RResult { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!( ROk::<_, ()>(500).unwrap(), 500 ); + /// assert_eq!(ROk::<_, ()>(500).unwrap(), 500); /// /// ``` /// @@ -310,7 +322,7 @@ impl RResult { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!( ROk::<_, ()>(500).expect("Are you OK?"), 500 ); + /// assert_eq!(ROk::<_, ()>(500).expect("Are you OK?"), 500); /// /// ``` /// @@ -339,7 +351,7 @@ impl RResult { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!( RErr::<(), u32>(0xB007).unwrap_err(), 0xB007 ); + /// assert_eq!(RErr::<(), u32>(0xB007).unwrap_err(), 0xB007); /// /// ``` /// @@ -369,7 +381,7 @@ impl RResult { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!( RErr::<(), u32>(0xB001).expect_err("Murphy's law"), 0xB001 ); + /// assert_eq!(RErr::<(), u32>(0xB001).expect_err("Murphy's law"), 0xB001); /// /// ``` /// @@ -413,8 +425,8 @@ impl RResult { /// ``` /// # use abi_stable::std_types::*; /// - /// assert_eq!(ROk::(10).unwrap_or_else(|e| e*3 ), 10); - /// assert_eq!(RErr::(5).unwrap_or_else(|e| e/2 ), 2); + /// assert_eq!(ROk::(10).unwrap_or_else(|e| e * 3), 10); + /// assert_eq!(RErr::(5).unwrap_or_else(|e| e / 2), 2); /// /// ``` #[inline] diff --git a/abi_stable/src/std_types/slice_mut.rs b/abi_stable/src/std_types/slice_mut.rs index 383ad7d8..eb021be2 100644 --- a/abi_stable/src/std_types/slice_mut.rs +++ b/abi_stable/src/std_types/slice_mut.rs @@ -144,10 +144,9 @@ mod privacy { /// ``` /// use abi_stable::std_types::RSliceMut; /// - /// assert_eq!(RSliceMut::::from_mut_slice(&mut[]).len(), 0); - /// assert_eq!(RSliceMut::from_mut_slice(&mut[0]).len(), 1); - /// assert_eq!(RSliceMut::from_mut_slice(&mut[0, 1]).len(), 2); - /// + /// assert_eq!(RSliceMut::::from_mut_slice(&mut []).len(), 0); + /// assert_eq!(RSliceMut::from_mut_slice(&mut [0]).len(), 1); + /// assert_eq!(RSliceMut::from_mut_slice(&mut [0, 1]).len(), 2); /// /// ``` #[inline(always)] @@ -195,11 +194,9 @@ mod privacy { /// ``` /// use abi_stable::std_types::RSliceMut; /// - /// fn convert(slice_: &mut [T]) -> RSliceMut<'_, T>{ + /// fn convert(slice_: &mut [T]) -> RSliceMut<'_, T> { /// let len = slice_.len(); - /// unsafe{ - /// RSliceMut::from_raw_parts_mut( slice_.as_mut_ptr(), len ) - /// } + /// unsafe { RSliceMut::from_raw_parts_mut(slice_.as_mut_ptr(), len) } /// } /// /// ``` @@ -230,10 +227,18 @@ impl<'a, T> RSliceMut<'a, T> { /// ``` /// use abi_stable::std_types::RSliceMut; /// - /// assert_eq!(RSliceMut::from_mut(&mut 0), RSliceMut::from_mut_slice(&mut [0]) ); - /// assert_eq!(RSliceMut::from_mut(&mut 1), RSliceMut::from_mut_slice(&mut [1]) ); - /// assert_eq!(RSliceMut::from_mut(&mut 2), RSliceMut::from_mut_slice(&mut [2]) ); - /// + /// assert_eq!( + /// RSliceMut::from_mut(&mut 0), + /// RSliceMut::from_mut_slice(&mut [0]) + /// ); + /// assert_eq!( + /// RSliceMut::from_mut(&mut 1), + /// RSliceMut::from_mut_slice(&mut [1]) + /// ); + /// assert_eq!( + /// RSliceMut::from_mut(&mut 2), + /// RSliceMut::from_mut_slice(&mut [2]) + /// ); /// /// ``` pub fn from_mut(ref_: &'a mut T) -> Self { @@ -249,9 +254,18 @@ impl<'a, T> RSliceMut<'a, T> { /// /// let empty: &mut [u8] = &mut []; /// - /// assert_eq!(RSliceMut::::from_mut_slice(&mut[]).as_mut_slice(), empty); - /// assert_eq!(RSliceMut::from_mut_slice(&mut[0]).as_mut_slice() , &mut [0][..]); - /// assert_eq!(RSliceMut::from_mut_slice(&mut[0, 1]).as_mut_slice() , &mut [0, 1][..]); + /// assert_eq!( + /// RSliceMut::::from_mut_slice(&mut []).as_mut_slice(), + /// empty + /// ); + /// assert_eq!( + /// RSliceMut::from_mut_slice(&mut [0]).as_mut_slice(), + /// &mut [0][..] + /// ); + /// assert_eq!( + /// RSliceMut::from_mut_slice(&mut [0, 1]).as_mut_slice(), + /// &mut [0, 1][..] + /// ); /// /// ``` #[inline] @@ -267,9 +281,9 @@ impl<'a, T> RSliceMut<'a, T> { /// # Example /// /// ``` - /// use abi_stable::std_types::{RSliceMut, RSlice}; + /// use abi_stable::std_types::{RSlice, RSliceMut}; /// - /// let slic = &mut[0, 1, 2, 3]; + /// let slic = &mut [0, 1, 2, 3]; /// let slic = RSliceMut::from_mut_slice(slic); /// /// assert_eq!(slic.slice(..), RSlice::from_slice(&[0, 1, 2, 3])); @@ -296,13 +310,16 @@ impl<'a, T> RSliceMut<'a, T> { /// ``` /// use abi_stable::std_types::RSliceMut; /// - /// let slic = &mut[0, 1, 2, 3]; + /// let slic = &mut [0, 1, 2, 3]; /// let mut slic = RSliceMut::from_mut_slice(slic); /// - /// assert_eq!(slic.slice_mut(..), RSliceMut::from_mut_slice(&mut[0, 1, 2, 3])); - /// assert_eq!(slic.slice_mut(..2), RSliceMut::from_mut_slice(&mut[0, 1])); - /// assert_eq!(slic.slice_mut(2..), RSliceMut::from_mut_slice(&mut[2, 3])); - /// assert_eq!(slic.slice_mut(1..3), RSliceMut::from_mut_slice(&mut[1, 2])); + /// assert_eq!( + /// slic.slice_mut(..), + /// RSliceMut::from_mut_slice(&mut [0, 1, 2, 3]) + /// ); + /// assert_eq!(slic.slice_mut(..2), RSliceMut::from_mut_slice(&mut [0, 1])); + /// assert_eq!(slic.slice_mut(2..), RSliceMut::from_mut_slice(&mut [2, 3])); + /// assert_eq!(slic.slice_mut(1..3), RSliceMut::from_mut_slice(&mut [1, 2])); /// /// ``` #[allow(clippy::needless_lifetimes)] @@ -320,7 +337,7 @@ impl<'a, T> RSliceMut<'a, T> { /// ``` /// use abi_stable::std_types::{RSliceMut, RVec}; /// - /// let slic = &mut[0, 1, 2, 3]; + /// let slic = &mut [0, 1, 2, 3]; /// let slic = RSliceMut::from_mut_slice(slic); /// /// assert_eq!(slic.slice(..).to_rvec(), RVec::from_slice(&[0, 1, 2, 3])); @@ -351,7 +368,10 @@ impl<'a, T> RSliceMut<'a, T> { /// ``` /// use abi_stable::std_types::RSliceMut; /// - /// assert_eq!(RSliceMut::from_mut_slice(&mut[0, 1, 2, 3]).as_slice(), &[0, 1, 2, 3]); + /// assert_eq!( + /// RSliceMut::from_mut_slice(&mut [0, 1, 2, 3]).as_slice(), + /// &[0, 1, 2, 3] + /// ); /// /// ``` pub fn as_slice(&self) -> &[T] { @@ -368,7 +388,10 @@ impl<'a, T> RSliceMut<'a, T> { /// ``` /// use abi_stable::std_types::RSliceMut; /// - /// assert_eq!(RSliceMut::from_mut_slice(&mut[0, 1, 2, 3]).into_slice(), &[0, 1, 2, 3]); + /// assert_eq!( + /// RSliceMut::from_mut_slice(&mut [0, 1, 2, 3]).into_slice(), + /// &[0, 1, 2, 3] + /// ); /// /// ``` pub fn into_slice(self) -> &'a [T] { @@ -380,10 +403,10 @@ impl<'a, T> RSliceMut<'a, T> { /// # Example /// /// ``` - /// use abi_stable::std_types::{RSliceMut, RSlice}; + /// use abi_stable::std_types::{RSlice, RSliceMut}; /// /// assert_eq!( - /// RSliceMut::from_mut_slice(&mut[0, 1, 2, 3]).as_rslice(), + /// RSliceMut::from_mut_slice(&mut [0, 1, 2, 3]).as_rslice(), /// RSlice::from_slice(&[0, 1, 2, 3]), /// ); /// @@ -400,10 +423,10 @@ impl<'a, T> RSliceMut<'a, T> { /// # Example /// /// ``` - /// use abi_stable::std_types::{RSliceMut, RSlice}; + /// use abi_stable::std_types::{RSlice, RSliceMut}; /// /// assert_eq!( - /// RSliceMut::from_mut_slice(&mut[0, 1, 2, 3]).into_rslice(), + /// RSliceMut::from_mut_slice(&mut [0, 1, 2, 3]).into_rslice(), /// RSlice::from_slice(&[0, 1, 2, 3]), /// ); /// @@ -419,7 +442,10 @@ impl<'a, T> RSliceMut<'a, T> { /// ``` /// use abi_stable::std_types::RSliceMut; /// - /// assert_eq!(RSliceMut::from_mut_slice(&mut[0, 1, 2, 3]).as_mut_slice(), &mut [0, 1, 2, 3]); + /// assert_eq!( + /// RSliceMut::from_mut_slice(&mut [0, 1, 2, 3]).as_mut_slice(), + /// &mut [0, 1, 2, 3] + /// ); /// /// ``` pub fn as_mut_slice(&mut self) -> &mut [T] { @@ -436,7 +462,10 @@ impl<'a, T> RSliceMut<'a, T> { /// ``` /// use abi_stable::std_types::RSliceMut; /// - /// assert_eq!(RSliceMut::from_mut_slice(&mut[0, 1, 2, 3]).into_mut_slice(), &mut [0, 1, 2, 3]); + /// assert_eq!( + /// RSliceMut::from_mut_slice(&mut [0, 1, 2, 3]).into_mut_slice(), + /// &mut [0, 1, 2, 3] + /// ); /// /// ``` pub fn into_mut_slice(mut self) -> &'a mut [T] { diff --git a/abi_stable/src/std_types/slices.rs b/abi_stable/src/std_types/slices.rs index c40a3e34..246fd37f 100644 --- a/abi_stable/src/std_types/slices.rs +++ b/abi_stable/src/std_types/slices.rs @@ -63,22 +63,19 @@ mod private { /// the first element that compares equal to a parameter. /// /// ``` - /// use abi_stable::{ - /// std_types::RSlice, - /// sabi_extern_fn, - /// }; + /// use abi_stable::{sabi_extern_fn, std_types::RSlice}; /// /// #[sabi_extern_fn] /// pub fn find_first_mut<'a, T>(slice_: RSlice<'a, T>, element: &T) -> Option<&'a T> /// where - /// T: std::cmp::PartialEq + /// T: std::cmp::PartialEq, /// { - /// slice_.iter() - /// .position(|x| x == element ) - /// .map(|i| &slice_.as_slice()[i] ) + /// slice_ + /// .iter() + /// .position(|x| x == element) + /// .map(|i| &slice_.as_slice()[i]) /// } /// - /// /// ``` #[repr(C)] #[derive(StableAbi)] @@ -134,10 +131,8 @@ mod private { /// ``` /// use abi_stable::std_types::RSlice; /// - /// fn convert(slice_: &[T]) -> RSlice<'_, T>{ - /// unsafe{ - /// RSlice::from_raw_parts( slice_.as_ptr(), slice_.len() ) - /// } + /// fn convert(slice_: &[T]) -> RSlice<'_, T> { + /// unsafe { RSlice::from_raw_parts(slice_.as_ptr(), slice_.len()) } /// } /// /// ``` @@ -232,10 +227,9 @@ impl<'a, T> RSlice<'a, T> { /// ``` /// use abi_stable::std_types::RSlice; /// - /// assert_eq!(RSlice::from_ref(&0), RSlice::from_slice(&[0]) ); - /// assert_eq!(RSlice::from_ref(&1), RSlice::from_slice(&[1]) ); - /// assert_eq!(RSlice::from_ref(&2), RSlice::from_slice(&[2]) ); - /// + /// assert_eq!(RSlice::from_ref(&0), RSlice::from_slice(&[0])); + /// assert_eq!(RSlice::from_ref(&1), RSlice::from_slice(&[1])); + /// assert_eq!(RSlice::from_ref(&2), RSlice::from_slice(&[2])); /// /// ``` pub const fn from_ref(ref_: &'a T) -> Self { @@ -252,8 +246,8 @@ impl<'a, T> RSlice<'a, T> { /// let empty: &[u8] = &[]; /// /// assert_eq!(RSlice::::from_slice(&[]).as_slice(), empty); - /// assert_eq!(RSlice::from_slice(&[0]).as_slice() , &[0][..]); - /// assert_eq!(RSlice::from_slice(&[0, 1]).as_slice() , &[0, 1][..]); + /// assert_eq!(RSlice::from_slice(&[0]).as_slice(), &[0][..]); + /// assert_eq!(RSlice::from_slice(&[0, 1]).as_slice(), &[0, 1][..]); /// /// ``` #[inline] @@ -295,10 +289,10 @@ impl<'a, T> RSlice<'a, T> { /// /// let slic = RSlice::from_slice(&[0, 1, 2, 3]); /// - /// assert_eq!( slic.slice(..).to_rvec(), RVec::from_slice(&[0, 1, 2, 3]) ); - /// assert_eq!( slic.slice(..2).to_rvec(), RVec::from_slice(&[0, 1]) ); - /// assert_eq!( slic.slice(2..).to_rvec(), RVec::from_slice(&[2, 3]) ); - /// assert_eq!( slic.slice(1..3).to_rvec(), RVec::from_slice(&[1, 2]) ); + /// assert_eq!(slic.slice(..).to_rvec(), RVec::from_slice(&[0, 1, 2, 3])); + /// assert_eq!(slic.slice(..2).to_rvec(), RVec::from_slice(&[0, 1])); + /// assert_eq!(slic.slice(2..).to_rvec(), RVec::from_slice(&[2, 3])); + /// assert_eq!(slic.slice(1..3).to_rvec(), RVec::from_slice(&[1, 2])); /// /// ``` pub fn to_rvec(&self) -> RVec diff --git a/abi_stable/src/std_types/std_io.rs b/abi_stable/src/std_types/std_io.rs index 3db3f8f8..6bb26714 100644 --- a/abi_stable/src/std_types/std_io.rs +++ b/abi_stable/src/std_types/std_io.rs @@ -236,7 +236,7 @@ impl RIoError { /// use abi_stable::std_types::RIoError; /// use std::io::ErrorKind; /// - /// let err = RIoError::new( ErrorKind::Other, "".parse::().unwrap_err()); + /// let err = RIoError::new(ErrorKind::Other, "".parse::().unwrap_err()); /// ``` pub fn new(kind: ErrorKind, error: E) -> Self where @@ -259,7 +259,7 @@ impl RIoError { /// /// let str_err = "Timeout receiving the response from server."; /// - /// let err = RIoError::new_( ErrorKind::TimedOut, str_err); + /// let err = RIoError::new_(ErrorKind::TimedOut, str_err); /// ``` #[inline] pub fn new_(kind: ErrorKind, error: E) -> Self @@ -277,7 +277,7 @@ impl RIoError { /// use abi_stable::std_types::RIoError; /// use std::io::ErrorKind; /// - /// let err = RIoError::from_kind( ErrorKind::AlreadyExists ); + /// let err = RIoError::from_kind(ErrorKind::AlreadyExists); /// ``` pub fn from_kind(kind: ErrorKind) -> Self { Self { @@ -297,7 +297,7 @@ impl RIoError { /// /// let str_err = "Could not create file \"memes.txt\" because it already exists."; /// - /// let err = RIoError::with_box( ErrorKind::AlreadyExists, str_err.into()); + /// let err = RIoError::with_box(ErrorKind::AlreadyExists, str_err.into()); /// ``` pub fn with_box(kind: ErrorKind, error: Box) -> Self { RIoError { @@ -318,7 +318,7 @@ impl RIoError { /// /// let str_err: DynErr = "IP address `256.256.256.256` is already in use.".into(); /// - /// let err = RIoError::with_rboxerror( ErrorKind::AddrInUse, str_err.into() ); + /// let err = RIoError::with_rboxerror(ErrorKind::AddrInUse, str_err.into()); /// ``` pub fn with_rboxerror(kind: ErrorKind, error: RBoxError) -> Self { RIoError { @@ -335,7 +335,7 @@ impl RIoError { /// use abi_stable::std_types::{RIoError, RIoErrorKind}; /// use std::io::ErrorKind; /// - /// let err = RIoError::from_kind( ErrorKind::AlreadyExists ); + /// let err = RIoError::from_kind(ErrorKind::AlreadyExists); /// /// assert_eq!(err.kind(), RIoErrorKind::AlreadyExists); /// ``` @@ -349,16 +349,16 @@ impl RIoError { /// # Example /// /// ``` - /// use abi_stable::std_types::{RIoError, RIoErrorKind, RBoxError}; + /// use abi_stable::std_types::{RBoxError, RIoError, RIoErrorKind}; /// use std::io::ErrorKind; /// /// { - /// let err = RIoError::from_kind( ErrorKind::AlreadyExists ); - /// assert_eq!(err.get_ref().map(|_|()), None); + /// let err = RIoError::from_kind(ErrorKind::AlreadyExists); + /// assert_eq!(err.get_ref().map(|_| ()), None); /// } /// { /// let msg = "Cannot access directory at \"/home/Steve/memes/\"."; - /// let err = RIoError::new_( ErrorKind::PermissionDenied, msg ); + /// let err = RIoError::new_(ErrorKind::PermissionDenied, msg); /// /// assert!(err.get_ref().is_some()); /// } @@ -374,16 +374,16 @@ impl RIoError { /// # Example /// /// ``` - /// use abi_stable::std_types::{RIoError, RIoErrorKind, RBoxError}; + /// use abi_stable::std_types::{RBoxError, RIoError, RIoErrorKind}; /// use std::io::ErrorKind; /// /// { - /// let mut err = RIoError::from_kind( ErrorKind::AlreadyExists ); - /// assert_eq!(err.get_mut().map(|_|()), None); + /// let mut err = RIoError::from_kind(ErrorKind::AlreadyExists); + /// assert_eq!(err.get_mut().map(|_| ()), None); /// } /// { /// let mut msg = "Cannot access directory at \"/home/Patrick/373.15K takes/\"."; - /// let mut err = RIoError::new_( ErrorKind::PermissionDenied, msg ); + /// let mut err = RIoError::new_(ErrorKind::PermissionDenied, msg); /// assert!(err.get_mut().is_some()); /// } /// @@ -402,12 +402,12 @@ impl RIoError { /// use std::io::ErrorKind; /// /// { - /// let err = RIoError::from_kind( ErrorKind::AlreadyExists ); - /// assert_eq!(err.into_inner().map(|_|()), None); + /// let err = RIoError::from_kind(ErrorKind::AlreadyExists); + /// assert_eq!(err.into_inner().map(|_| ()), None); /// } /// { /// let mut msg = "Cannot access directory at \"/home/wo_boat/blog/\"."; - /// let err = RIoError::new_( ErrorKind::PermissionDenied, msg ); + /// let err = RIoError::new_(ErrorKind::PermissionDenied, msg); /// assert!(err.into_inner().is_some()); /// } /// diff --git a/abi_stable/src/std_types/str.rs b/abi_stable/src/std_types/str.rs index 6f0d6baf..00c85a8d 100644 --- a/abi_stable/src/std_types/str.rs +++ b/abi_stable/src/std_types/str.rs @@ -54,7 +54,7 @@ impl<'a> RStr<'a> { /// ``` /// use abi_stable::std_types::RStr; /// - /// const STR: RStr<'static> = RStr::empty(); + /// const STR: RStr<'static> = RStr::empty(); /// /// assert_eq!(STR, RStr::from("")); /// @@ -85,10 +85,8 @@ impl<'a> RStr<'a> { /// ``` /// use abi_stable::std_types::RStr; /// - /// fn convert(slice_: &str) -> RStr<'_>{ - /// unsafe{ - /// RStr::from_raw_parts( slice_.as_ptr(), slice_.len() ) - /// } + /// fn convert(slice_: &str) -> RStr<'_> { + /// unsafe { RStr::from_raw_parts(slice_.as_ptr(), slice_.len()) } /// } /// /// ``` diff --git a/abi_stable/src/std_types/string.rs b/abi_stable/src/std_types/string.rs index 2b272c56..6faf66e1 100644 --- a/abi_stable/src/std_types/string.rs +++ b/abi_stable/src/std_types/string.rs @@ -141,10 +141,7 @@ impl RString { /// use abi_stable::std_types::{RStr, RString}; /// /// let str = "What is that."; - /// assert_eq!( - /// RString::from(str).as_rstr(), - /// RStr::from(str), - /// ); + /// assert_eq!(RString::from(str).as_rstr(), RStr::from(str),); /// /// ``` #[inline] @@ -229,8 +226,8 @@ impl RString { /// /// let bytes = RVec::from("hello".as_bytes()); /// - /// unsafe{ - /// assert_eq!( RString::from_utf8_unchecked(bytes).as_str(), "hello" ); + /// unsafe { + /// assert_eq!(RString::from_utf8_unchecked(bytes).as_str(), "hello"); /// } /// /// ``` @@ -253,8 +250,11 @@ impl RString { /// let bytes_ok = RVec::from("hello".as_bytes()); /// let bytes_err = RVec::from(vec![255]); /// - /// assert_eq!( RString::from_utf8(bytes_ok).unwrap(), RString::from("hello") ); - /// assert!( RString::from_utf8(bytes_err).is_err() ); + /// assert_eq!( + /// RString::from_utf8(bytes_ok).unwrap(), + /// RString::from("hello") + /// ); + /// assert!(RString::from_utf8(bytes_err).is_err()); /// /// ``` pub fn from_utf8(vec: V) -> Result @@ -286,10 +286,7 @@ impl RString { /// let str = "What the 😈."; /// let str_utf16 = str.encode_utf16().collect::>(); /// - /// assert_eq!( - /// RString::from_utf16(&str_utf16).unwrap(), - /// RString::from(str), - /// ); + /// assert_eq!(RString::from_utf16(&str_utf16).unwrap(), RString::from(str),); /// ``` pub fn from_utf16(s: &[u16]) -> Result { String::from_utf16(s).map(From::from) @@ -596,17 +593,17 @@ impl RString { /// /// { /// let mut str = RString::from("There were 10 people."); - /// str.retain(|c| !c.is_numeric() ); + /// str.retain(|c| !c.is_numeric()); /// assert_eq!(str.as_str(), "There were people."); /// } /// { /// let mut str = RString::from("There were 10 people."); - /// str.retain(|c| !c.is_whitespace() ); + /// str.retain(|c| !c.is_whitespace()); /// assert_eq!(str.as_str(), "Therewere10people."); /// } /// { /// let mut str = RString::from("There were 10 people."); - /// str.retain(|c| c.is_numeric() ); + /// str.retain(|c| c.is_numeric()); /// assert_eq!(str.as_str(), "10"); /// } /// @@ -923,7 +920,7 @@ impl<'a> FromIterator<&'a char> for RString { /// /// let err = RString::from_utf8(vec![0, 0, 0, 255]).unwrap_err(); /// -/// assert_eq!( err.as_bytes() , &[0, 0, 0, 255] ) +/// assert_eq!(err.as_bytes(), &[0, 0, 0, 255]) /// /// ``` #[derive(Debug)] @@ -944,7 +941,7 @@ impl FromUtf8Error { /// /// let err = RString::from_utf8(bytes.clone()).unwrap_err(); /// - /// assert_eq!( err.into_bytes(), bytes ); + /// assert_eq!(err.into_bytes(), bytes); /// /// ``` pub fn into_bytes(self) -> RVec { @@ -957,11 +954,11 @@ impl FromUtf8Error { /// ``` /// use abi_stable::std_types::RString; /// - /// let bytes= vec![99, 114, 121, 115, 116, 97, 108, 255]; + /// let bytes = vec![99, 114, 121, 115, 116, 97, 108, 255]; /// /// let err = RString::from_utf8(bytes.clone()).unwrap_err(); /// - /// assert_eq!( err.as_bytes(), &bytes[..] ); + /// assert_eq!(err.as_bytes(), &bytes[..]); /// /// ``` pub fn as_bytes(&self) -> &[u8] { @@ -975,9 +972,9 @@ impl FromUtf8Error { /// ``` /// use abi_stable::std_types::RString; /// - /// let err = RString::from_utf8( vec![0, 0, 255] ).unwrap_err(); + /// let err = RString::from_utf8(vec![0, 0, 255]).unwrap_err(); /// - /// assert_eq!( err.error().valid_up_to(), 2 ); + /// assert_eq!(err.error().valid_up_to(), 2); /// /// ``` pub fn error(&self) -> Utf8Error { diff --git a/abi_stable/src/std_types/time.rs b/abi_stable/src/std_types/time.rs index 6f0cc225..6d996090 100644 --- a/abi_stable/src/std_types/time.rs +++ b/abi_stable/src/std_types/time.rs @@ -10,8 +10,8 @@ use std::time::Duration; /// use abi_stable::std_types::RDuration; /// /// let dur = RDuration::from_millis(31416); -/// assert_eq!( dur.as_secs(), 31 ); -/// assert_eq!( dur.as_nanos(), 31_416_000_000 ); +/// assert_eq!(dur.as_secs(), 31); +/// assert_eq!(dur.as_nanos(), 31_416_000_000); /// /// ``` #[derive( @@ -32,8 +32,8 @@ impl RDuration { /// use abi_stable::std_types::RDuration; /// /// let dur = RDuration::new(1, 456_000_000); - /// assert_eq!( dur.as_millis(), 1_456 ); - /// assert_eq!( dur.as_micros(), 1_456_000 ); + /// assert_eq!(dur.as_millis(), 1_456); + /// assert_eq!(dur.as_micros(), 1_456_000); /// /// ``` pub const fn new(seconds: u64, subsec_nanos: u32) -> Self { @@ -51,8 +51,8 @@ impl RDuration { /// use abi_stable::std_types::RDuration; /// /// let dur = RDuration::from_secs(14); - /// assert_eq!( dur.as_millis(), 14_000 ); - /// assert_eq!( dur.as_micros(), 14_000_000 ); + /// assert_eq!(dur.as_millis(), 14_000); + /// assert_eq!(dur.as_micros(), 14_000_000); /// /// ``` pub const fn from_secs(secs: u64) -> RDuration { @@ -70,8 +70,8 @@ impl RDuration { /// use abi_stable::std_types::RDuration; /// /// let dur = RDuration::from_millis(628); - /// assert_eq!( dur.as_micros(), 628_000 ); - /// assert_eq!( dur.as_nanos(), 628_000_000 ); + /// assert_eq!(dur.as_micros(), 628_000); + /// assert_eq!(dur.as_nanos(), 628_000_000); /// /// ``` pub const fn from_millis(milli: u64) -> RDuration { @@ -89,8 +89,8 @@ impl RDuration { /// use abi_stable::std_types::RDuration; /// /// let dur = RDuration::from_micros(1024); - /// assert_eq!( dur.as_millis(), 1 ); - /// assert_eq!( dur.as_nanos(), 1024_000 ); + /// assert_eq!(dur.as_millis(), 1); + /// assert_eq!(dur.as_nanos(), 1024_000); /// /// ``` pub const fn from_micros(micro: u64) -> RDuration { @@ -109,8 +109,8 @@ impl RDuration { /// use abi_stable::std_types::RDuration; /// /// let dur = RDuration::from_nanos(128_256_512); - /// assert_eq!( dur.as_millis(), 128 ); - /// assert_eq!( dur.as_micros(), 128_256 ); + /// assert_eq!(dur.as_millis(), 128); + /// assert_eq!(dur.as_micros(), 128_256); /// /// ``` pub const fn from_nanos(nano: u64) -> RDuration { @@ -130,7 +130,7 @@ impl RDuration { /// use abi_stable::std_types::RDuration; /// /// let dur = RDuration::from_nanos(64_128_256_512); - /// assert_eq!( dur.subsec_nanos(), 128_256_512 ); + /// assert_eq!(dur.subsec_nanos(), 128_256_512); /// /// ``` pub const fn subsec_nanos(&self) -> u32 { @@ -145,7 +145,7 @@ impl RDuration { /// use abi_stable::std_types::RDuration; /// /// let dur = RDuration::from_nanos(64_128_256_512); - /// assert_eq!( dur.seconds(), 64 ); + /// assert_eq!(dur.seconds(), 64); /// /// ``` pub const fn seconds(&self) -> u64 { @@ -160,7 +160,7 @@ impl RDuration { /// use abi_stable::std_types::RDuration; /// /// let dur = RDuration::from_nanos(64_128_256_512); - /// assert_eq!( dur.as_secs(), 64 ); + /// assert_eq!(dur.as_secs(), 64); /// /// ``` pub const fn as_secs(&self) -> u64 { @@ -175,7 +175,7 @@ impl RDuration { /// use abi_stable::std_types::RDuration; /// /// let dur = RDuration::from_nanos(64_128_256_512); - /// assert_eq!( dur.as_millis(), 64_128 ); + /// assert_eq!(dur.as_millis(), 64_128); /// /// ``` pub const fn as_millis(&self) -> u128 { @@ -190,7 +190,7 @@ impl RDuration { /// use abi_stable::std_types::RDuration; /// /// let dur = RDuration::from_nanos(64_128_256_512); - /// assert_eq!( dur.as_micros(), 64_128_256 ); + /// assert_eq!(dur.as_micros(), 64_128_256); /// /// ``` pub const fn as_micros(&self) -> u128 { @@ -205,7 +205,7 @@ impl RDuration { /// use abi_stable::std_types::RDuration; /// /// let dur = RDuration::from_micros(256); - /// assert_eq!( dur.as_nanos(), 256_000 ); + /// assert_eq!(dur.as_nanos(), 256_000); /// /// ``` pub const fn as_nanos(&self) -> u128 { diff --git a/abi_stable/src/std_types/tuple.rs b/abi_stable/src/std_types/tuple.rs index e47f2006..0ab691a5 100644 --- a/abi_stable/src/std_types/tuple.rs +++ b/abi_stable/src/std_types/tuple.rs @@ -58,7 +58,7 @@ declare_tuple! { /// ``` /// use abi_stable::std_types::*; /// - /// assert_eq!( Tuple1(1).into_tuple(), (1,) ); + /// assert_eq!(Tuple1(1).into_tuple(), (1,)); /// /// ``` ] @@ -81,7 +81,7 @@ declare_tuple! { /// ``` /// use abi_stable::std_types::*; /// - /// assert_eq!( Tuple2(1, 2).into_tuple(), (1, 2) ); + /// assert_eq!(Tuple2(1, 2).into_tuple(), (1, 2)); /// /// ``` ] @@ -105,7 +105,7 @@ declare_tuple! { /// ``` /// use abi_stable::std_types::*; /// - /// assert_eq!( Tuple3(1, 2, 3).into_tuple(), (1, 2, 3) ); + /// assert_eq!(Tuple3(1, 2, 3).into_tuple(), (1, 2, 3)); /// /// ``` ] @@ -130,7 +130,7 @@ declare_tuple! { /// ``` /// use abi_stable::std_types::*; /// - /// assert_eq!( Tuple4(1, 2, 3, 4).into_tuple(), (1, 2, 3, 4) ); + /// assert_eq!(Tuple4(1, 2, 3, 4).into_tuple(), (1, 2, 3, 4)); /// /// ``` ] diff --git a/abi_stable/src/std_types/utypeid.rs b/abi_stable/src/std_types/utypeid.rs index 36a9a3fc..7a39f05d 100644 --- a/abi_stable/src/std_types/utypeid.rs +++ b/abi_stable/src/std_types/utypeid.rs @@ -21,17 +21,17 @@ use crate::{sabi_types::MaybeCmp, EXECUTABLE_IDENTITY}; /// use abi_stable::std_types::utypeid::new_utypeid; /// use std::collections::HashMap; /// -/// let hashmap_id = new_utypeid::< HashMap >(); -/// let vec_id = new_utypeid::< Vec >(); -/// let u32_id = new_utypeid::< u32 >(); +/// let hashmap_id = new_utypeid::>(); +/// let vec_id = new_utypeid::>(); +/// let u32_id = new_utypeid::(); /// -/// assert_eq!( hashmap_id, hashmap_id ); -/// assert_eq!( vec_id, vec_id ); -/// assert_eq!( u32_id, u32_id ); +/// assert_eq!(hashmap_id, hashmap_id); +/// assert_eq!(vec_id, vec_id); +/// assert_eq!(u32_id, u32_id); /// -/// assert_ne!( vec_id, hashmap_id ); -/// assert_ne!( u32_id, hashmap_id ); -/// assert_ne!( vec_id, u32_id ); +/// assert_ne!(vec_id, hashmap_id); +/// assert_ne!(u32_id, hashmap_id); +/// assert_ne!(vec_id, u32_id); /// /// ``` pub extern "C" fn new_utypeid() -> UTypeId @@ -92,7 +92,7 @@ impl UTypeId { /// use abi_stable::std_types::UTypeId; /// use std::collections::HashMap; /// - /// let id = UTypeId::new::< HashMap >(); + /// let id = UTypeId::new::>(); /// # drop(id); /// ``` #[inline(always)] diff --git a/abi_stable/src/std_types/vec.rs b/abi_stable/src/std_types/vec.rs index 7fdc0467..f2e95892 100644 --- a/abi_stable/src/std_types/vec.rs +++ b/abi_stable/src/std_types/vec.rs @@ -211,7 +211,7 @@ impl RVec { /// assert_eq!(list.len(), 0); /// assert_eq!(list.capacity(), 7); /// - /// list.extend( std::iter::repeat(11).take(7) ); + /// list.extend(std::iter::repeat(11).take(7)); /// assert_eq!(list.len(), 7); /// assert_eq!(list.capacity(), 7); /// @@ -232,10 +232,13 @@ impl RVec { /// /// let list = RVec::from(vec![0, 1, 2, 3, 4, 5, 6, 7, 8]); /// - /// assert_eq!( list.slice(..), RSlice::from_slice(&[0, 1, 2, 3, 4, 5, 6, 7, 8]) ); - /// assert_eq!( list.slice(..4), RSlice::from_slice(&[0, 1, 2, 3]) ); - /// assert_eq!( list.slice(4..), RSlice::from_slice(&[4, 5, 6, 7, 8]) ); - /// assert_eq!( list.slice(4..7), RSlice::from_slice(&[4, 5, 6]) ); + /// assert_eq!( + /// list.slice(..), + /// RSlice::from_slice(&[0, 1, 2, 3, 4, 5, 6, 7, 8]) + /// ); + /// assert_eq!(list.slice(..4), RSlice::from_slice(&[0, 1, 2, 3])); + /// assert_eq!(list.slice(4..), RSlice::from_slice(&[4, 5, 6, 7, 8])); + /// assert_eq!(list.slice(4..7), RSlice::from_slice(&[4, 5, 6])); /// /// ``` #[inline] @@ -267,10 +270,22 @@ impl RVec { /// /// let mut list = RVec::from(vec![0, 1, 2, 3, 4, 5, 6, 7, 8]); /// - /// assert_eq!( list.slice_mut(..), RSliceMut::from_mut_slice(&mut [0, 1, 2, 3, 4, 5, 6, 7, 8]) ); - /// assert_eq!( list.slice_mut(..4), RSliceMut::from_mut_slice(&mut [0, 1, 2, 3]) ); - /// assert_eq!( list.slice_mut(4..), RSliceMut::from_mut_slice(&mut [4, 5, 6, 7, 8]) ); - /// assert_eq!( list.slice_mut(4..7), RSliceMut::from_mut_slice(&mut [4, 5, 6]) ); + /// assert_eq!( + /// list.slice_mut(..), + /// RSliceMut::from_mut_slice(&mut [0, 1, 2, 3, 4, 5, 6, 7, 8]) + /// ); + /// assert_eq!( + /// list.slice_mut(..4), + /// RSliceMut::from_mut_slice(&mut [0, 1, 2, 3]) + /// ); + /// assert_eq!( + /// list.slice_mut(4..), + /// RSliceMut::from_mut_slice(&mut [4, 5, 6, 7, 8]) + /// ); + /// assert_eq!( + /// list.slice_mut(4..7), + /// RSliceMut::from_mut_slice(&mut [4, 5, 6]) + /// ); /// /// ``` #[inline] @@ -346,7 +361,10 @@ impl RVec { /// use abi_stable::std_types::{RSliceMut, RVec}; /// /// let mut list = RVec::from(vec![0, 1, 2, 3]); - /// assert_eq!(list.as_mut_rslice(), RSliceMut::from_mut_slice(&mut [0, 1, 2, 3])); + /// assert_eq!( + /// list.as_mut_rslice(), + /// RSliceMut::from_mut_slice(&mut [0, 1, 2, 3]) + /// ); /// /// ``` pub fn as_mut_rslice(&mut self) -> RSliceMut<'_, T> { @@ -393,7 +411,7 @@ impl RVec { /// /// list.reserve_exact(10); /// - /// unsafe{ + /// unsafe { /// let start = list.as_mut_ptr(); /// for i in 0..10 { /// start.add(i as usize).write(i); @@ -401,7 +419,7 @@ impl RVec { /// list.set_len(10); /// } /// - /// assert_eq!( list, (0..10).collect::>() ); + /// assert_eq!(list, (0..10).collect::>()); /// /// ``` pub unsafe fn set_len(&mut self, new_len: usize) { @@ -417,7 +435,7 @@ impl RVec { /// /// let mut list = RVec::::with_capacity(7); /// - /// list.extend( std::iter::repeat(11).take(4) ); + /// list.extend(std::iter::repeat(11).take(4)); /// assert_eq!(list.len(), 4); /// assert_eq!(list.capacity(), 7); /// @@ -505,9 +523,9 @@ impl RVec { /// /// let mut list = RVec::::new(); /// - /// list.extend( (4 ..= 7).rev() ); + /// list.extend((4..=7).rev()); /// - /// assert_eq!(list.to_vec(), vec![7, 6, 5, 4] ); + /// assert_eq!(list.to_vec(), vec![7, 6, 5, 4]); /// /// ``` pub fn to_vec(&self) -> Vec @@ -636,11 +654,11 @@ impl RVec { /// let mut list: RVec> = /// vec!["foo".into_c(), "bar".into(), "baz".into()].into_c(); /// - /// assert_eq!( list.remove(2), "baz".into_c() ); - /// assert_eq!(list.as_slice(), &["foo".into_c(), "bar".into_c()] ); + /// assert_eq!(list.remove(2), "baz".into_c()); + /// assert_eq!(list.as_slice(), &["foo".into_c(), "bar".into_c()]); /// - /// assert_eq!( list.remove(0), "foo".into_c() ); - /// assert_eq!(list.as_slice(), &["bar".into_c()] ); + /// assert_eq!(list.remove(0), "foo".into_c()); + /// assert_eq!(list.as_slice(), &["bar".into_c()]); /// ``` pub fn remove(&mut self, index: usize) -> T { match self.try_remove(index) { @@ -667,11 +685,14 @@ impl RVec { /// let mut list: RVec> = /// vec!["foo".into_c(), "bar".into(), "baz".into(), "geo".into()].into_c(); /// - /// assert_eq!( list.swap_remove(1), "bar".into_c() ); - /// assert_eq!( list.as_slice(), &["foo".into_c(), "geo".into(), "baz".into()] ); + /// assert_eq!(list.swap_remove(1), "bar".into_c()); + /// assert_eq!( + /// list.as_slice(), + /// &["foo".into_c(), "geo".into(), "baz".into()] + /// ); /// - /// assert_eq!( list.swap_remove(0), "foo".into_c() ); - /// assert_eq!( list.as_slice(), &["baz".to_string(), "geo".into()] ); + /// assert_eq!(list.swap_remove(0), "foo".into_c()); + /// assert_eq!(list.as_slice(), &["baz".to_string(), "geo".into()]); /// /// ``` pub fn swap_remove(&mut self, index: usize) -> T { @@ -729,7 +750,7 @@ impl RVec { /// assert_eq!(list.as_slice(), &[11]); /// /// assert_eq!(list.pop(), Some(11)); - /// assert_eq!(list.as_rslice(), RSlice::::EMPTY ); + /// assert_eq!(list.as_rslice(), RSlice::::EMPTY); /// /// assert_eq!(list.pop(), None); /// @@ -758,10 +779,10 @@ impl RVec { /// let mut list = RVec::::from_slice(&[11, 22, 55, 66, 77]); /// /// list.truncate(3); - /// assert_eq!(list.as_slice(), &[11, 22, 55] ); + /// assert_eq!(list.as_slice(), &[11, 22, 55]); /// /// list.truncate(0); - /// assert_eq!(list.as_rslice(), RSlice::::EMPTY ); + /// assert_eq!(list.as_rslice(), RSlice::::EMPTY); /// /// list.truncate(5555); //This is a no-op. /// ``` @@ -782,11 +803,11 @@ impl RVec { /// /// let mut list = RVec::::from_slice(&[11, 22, 55]); /// - /// assert_eq!( list.as_slice(), &[11, 22, 55] ); + /// assert_eq!(list.as_slice(), &[11, 22, 55]); /// /// list.clear(); - /// assert_eq!( list.as_rslice(), RSlice::::EMPTY ); - /// assert_ne!( list.capacity(), 0 ); + /// assert_eq!(list.as_rslice(), RSlice::::EMPTY); + /// assert_ne!(list.capacity(), 0); /// /// ``` pub fn clear(&mut self) { @@ -804,13 +825,13 @@ impl RVec { /// use abi_stable::std_types::RVec; /// /// { - /// let mut list = (0 ..= 10).collect::>(); - /// list.retain(|x| *x%3 == 0 ); + /// let mut list = (0..=10).collect::>(); + /// list.retain(|x| *x % 3 == 0); /// assert_eq!(list.as_slice(), &[0, 3, 6, 9]); /// } /// { - /// let mut list = (0 ..= 10).collect::>(); - /// list.retain(|x| *x%5 == 0 ); + /// let mut list = (0..=10).collect::>(); + /// list.retain(|x| *x % 5 == 0); /// assert_eq!(list.as_slice(), &[0, 5, 10]); /// } /// @@ -856,11 +877,11 @@ impl RVec { /// let mut list = RVec::::new(); /// /// list.reserve(10); - /// assert!( list.capacity() >= 10 ); + /// assert!(list.capacity() >= 10); /// /// let cap = list.capacity(); /// list.extend(0..10); - /// assert_eq!( list.capacity(), cap ); + /// assert_eq!(list.capacity(), cap); /// /// ``` pub fn reserve(&mut self, additional: usize) { @@ -879,11 +900,11 @@ impl RVec { /// let mut list = RVec::::new(); /// /// list.reserve_exact(17); - /// assert_eq!( list.capacity(), 17 ); + /// assert_eq!(list.capacity(), 17); /// /// let cap = list.capacity(); /// list.extend(0..17); - /// assert_eq!( list.capacity(), cap ); + /// assert_eq!(list.capacity(), cap); /// /// ``` pub fn reserve_exact(&mut self, additional: usize) { @@ -920,13 +941,13 @@ where /// let mut list = RVec::::new(); /// /// list.resize(5, 88); - /// assert_eq!( list.as_slice(), &[88, 88, 88, 88, 88] ); + /// assert_eq!(list.as_slice(), &[88, 88, 88, 88, 88]); /// /// list.resize(3, 0); - /// assert_eq!( list.as_slice(), &[88, 88, 88] ); + /// assert_eq!(list.as_slice(), &[88, 88, 88]); /// /// list.resize(6, 123); - /// assert_eq!( list.as_slice(), &[88, 88, 88, 123, 123, 123] ); + /// assert_eq!(list.as_slice(), &[88, 88, 88, 123, 123, 123]); /// /// ``` pub fn resize(&mut self, new_len: usize, value: T) { @@ -965,7 +986,7 @@ where /// list.extend_from_slice(&[99, 88]); /// list.extend_from_slice(&[77, 66]); /// - /// assert_eq!( list.as_slice(), &[99, 88, 77, 66] ); + /// assert_eq!(list.as_slice(), &[99, 88, 77, 66]); /// ``` pub fn extend_from_slice(&mut self, slic_: &[T]) { self.reserve(slic_.len()); diff --git a/abi_stable/src/std_types/vec/iters.rs b/abi_stable/src/std_types/vec/iters.rs index b9d4ee74..b3a15057 100644 --- a/abi_stable/src/std_types/vec/iters.rs +++ b/abi_stable/src/std_types/vec/iters.rs @@ -108,13 +108,13 @@ impl IntoIter { /// /// let mut iter = RVec::from(vec![0, 1, 2, 3]).into_iter(); /// - /// assert_eq!( iter.as_slice(), &[0, 1, 2, 3] ); + /// assert_eq!(iter.as_slice(), &[0, 1, 2, 3]); /// - /// assert_eq!( iter.next(), Some(0) ); - /// assert_eq!( iter.as_slice(), &[1, 2, 3] ); + /// assert_eq!(iter.next(), Some(0)); + /// assert_eq!(iter.as_slice(), &[1, 2, 3]); /// - /// assert_eq!( iter.next_back(), Some(3) ); - /// assert_eq!( iter.as_slice(), &[1, 2] ); + /// assert_eq!(iter.next_back(), Some(3)); + /// assert_eq!(iter.as_slice(), &[1, 2]); /// /// ``` pub fn as_slice(&self) -> &[T] { @@ -130,13 +130,13 @@ impl IntoIter { /// /// let mut iter = RVec::from(vec![0, 1, 2, 3]).into_iter(); /// - /// assert_eq!( iter.as_mut_slice(), &mut [0, 1, 2, 3] ); + /// assert_eq!(iter.as_mut_slice(), &mut [0, 1, 2, 3]); /// - /// assert_eq!( iter.next(), Some(0) ); - /// assert_eq!( iter.as_mut_slice(), &mut [1, 2, 3] ); + /// assert_eq!(iter.next(), Some(0)); + /// assert_eq!(iter.as_mut_slice(), &mut [1, 2, 3]); /// - /// assert_eq!( iter.next_back(), Some(3) ); - /// assert_eq!( iter.as_mut_slice(), &mut [1, 2] ); + /// assert_eq!(iter.next_back(), Some(3)); + /// assert_eq!(iter.as_mut_slice(), &mut [1, 2]); /// /// ``` pub fn as_mut_slice(&mut self) -> &mut [T] { @@ -194,13 +194,13 @@ impl<'a, T> Drain<'a, T> { /// let mut list = (0..8).collect::>(); /// let mut iter = list.drain(3..7); /// - /// assert_eq!( iter.as_slice(), &[3, 4, 5, 6] ); + /// assert_eq!(iter.as_slice(), &[3, 4, 5, 6]); /// - /// assert_eq!( iter.next(), Some(3) ); - /// assert_eq!( iter.as_slice(), &[4, 5, 6] ); + /// assert_eq!(iter.next(), Some(3)); + /// assert_eq!(iter.as_slice(), &[4, 5, 6]); /// - /// assert_eq!( iter.next(), Some(4) ); - /// assert_eq!( iter.as_slice(), &[5, 6] ); + /// assert_eq!(iter.next(), Some(4)); + /// assert_eq!(iter.as_slice(), &[5, 6]); /// /// drop(iter); /// @@ -221,13 +221,13 @@ impl<'a, T> Drain<'a, T> { /// let mut list = (0..8).collect::>(); /// let mut iter = list.drain(3..7); /// - /// assert_eq!( iter.as_mut_slice(), &mut [3, 4, 5, 6] ); + /// assert_eq!(iter.as_mut_slice(), &mut [3, 4, 5, 6]); /// - /// assert_eq!( iter.next(), Some(3) ); - /// assert_eq!( iter.as_mut_slice(), &mut [4, 5, 6] ); + /// assert_eq!(iter.next(), Some(3)); + /// assert_eq!(iter.as_mut_slice(), &mut [4, 5, 6]); /// - /// assert_eq!( iter.next(), Some(4) ); - /// assert_eq!( iter.as_mut_slice(), &mut [5, 6] ); + /// assert_eq!(iter.next(), Some(4)); + /// assert_eq!(iter.as_mut_slice(), &mut [5, 6]); /// /// drop(iter); /// From 86e380c83c945830b53a01e0fb377e52cf676382 Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Thu, 28 Oct 2021 06:15:49 -0300 Subject: [PATCH 28/32] Fixed RHashMap::keys docs Fixed abi_stable_derive warnings --- abi_stable/src/std_types/map.rs | 8 ++++++++ abi_stable_derive/src/stable_abi.rs | 5 ++--- abi_stable_derive/src/stable_abi/nonexhaustive.rs | 1 - abi_stable_derive/src/stable_abi/prefix_types.rs | 1 - 4 files changed, 10 insertions(+), 5 deletions(-) diff --git a/abi_stable/src/std_types/map.rs b/abi_stable/src/std_types/map.rs index e34586a1..c6289f3f 100644 --- a/abi_stable/src/std_types/map.rs +++ b/abi_stable/src/std_types/map.rs @@ -753,6 +753,14 @@ impl RHashMap { unsafe { vtable.entry()(self.map.as_rmut(), key) } } + /// An iterator visiting all keys in arbitrary order. + /// The iterator element type is `&'a K`. + /// + /// # Examples + /// + /// ``` + /// use abi_stable::std_types::RHashMap; + /// /// let mut map = RHashMap::new(); /// map.insert("a", 1); /// map.insert("b", 2); diff --git a/abi_stable_derive/src/stable_abi.rs b/abi_stable_derive/src/stable_abi.rs index 574792c3..b4c1301f 100644 --- a/abi_stable_derive/src/stable_abi.rs +++ b/abi_stable_derive/src/stable_abi.rs @@ -96,7 +96,6 @@ pub(crate) fn derive(mut data: DeriveInput) -> Result let visited_fields = &VisitedFieldMap::new(ds, config, shared_vars, ctokens); shared_vars.extract_errs()?; - let module = Ident::new(&format!("_sabi_{}", name), Span::call_site()); let mono_type_layout = &Ident::new(&format!("_MONO_LAYOUT_{}", name), Span::call_site()); let (_, _, where_clause) = generics.split_for_impl(); @@ -214,7 +213,7 @@ pub(crate) fn derive(mut data: DeriveInput) -> Result }; // tokenizes the items for nonexhaustive enums outside of the module this generates. - let nonexhaustive_items = tokenize_nonexhaustive_items(&module, ds, config, ctokens); + let nonexhaustive_items = tokenize_nonexhaustive_items(ds, config, ctokens); // tokenizes the items for nonexhaustive enums inside of the module this generates. let nonexhaustive_tokens = tokenize_enum_info(ds, variant_names_start_len, config, ctokens)?; @@ -389,7 +388,7 @@ pub(crate) fn derive(mut data: DeriveInput) -> Result let PrefixTypeTokens { prefixref_types, prefixref_impls, - } = prefix_type_tokenizer(&module, mono_type_layout, ds, config, ctokens)?; + } = prefix_type_tokenizer(mono_type_layout, ds, config, ctokens)?; let mod_refl_mode = match config.mod_refl_mode { ModReflMode::Module => quote!(__ModReflMode::Module), diff --git a/abi_stable_derive/src/stable_abi/nonexhaustive.rs b/abi_stable_derive/src/stable_abi/nonexhaustive.rs index 41700005..e85dc23e 100644 --- a/abi_stable_derive/src/stable_abi/nonexhaustive.rs +++ b/abi_stable_derive/src/stable_abi/nonexhaustive.rs @@ -312,7 +312,6 @@ where /// Outputs the nonexhausitve-enum-related items, /// outside the module generated by StableAbi. pub(crate) fn tokenize_nonexhaustive_items<'a>( - module: &'a Ident, ds: &'a DataStructure<'a>, config: &'a StableAbiOptions<'a>, _ct: &'a CommonTokens<'a>, diff --git a/abi_stable_derive/src/stable_abi/prefix_types.rs b/abi_stable_derive/src/stable_abi/prefix_types.rs index bb923e99..151caaa7 100644 --- a/abi_stable_derive/src/stable_abi/prefix_types.rs +++ b/abi_stable_derive/src/stable_abi/prefix_types.rs @@ -216,7 +216,6 @@ pub struct PrefixTypeTokens { /// Returns a value which for a prefix-type . pub(crate) fn prefix_type_tokenizer<'a>( - module: &'a Ident, mono_type_layout: &'a Ident, ds: &'a DataStructure<'a>, config: &'a StableAbiOptions<'a>, From 54517abd294903ecc522479de2ea5f8f11323a9b Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Thu, 28 Oct 2021 22:16:39 -0300 Subject: [PATCH 29/32] Update rust.yml --- .github/workflows/rust.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 5a2f45f7..ad9e73dd 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -28,6 +28,7 @@ jobs: - name: ci-format run: | rustup override set ${{ matrix.rust }} + rustup component add rustfmt cd "${{github.workspace}}/" cargo fmt -- --check From 9ca4c7931a9318ba4049c82810b8944a4995da00 Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Fri, 29 Oct 2021 02:27:59 -0300 Subject: [PATCH 30/32] Bumped MSRV to 1.46.0 due to ICEs in older versions Updated code conditional on Rust versions Changed Github CI to only test all Rust versions on ubuntu, testing Rust nightly on mac and windows. --- .github/workflows/rust.yml | 14 +++- Changelog.md | 4 +- abi_stable/src/lib.rs | 21 +++-- abi_stable/src/macros/internal.rs | 24 ------ abi_stable/src/macros/nul_str_macros.rs | 2 - abi_stable/src/sabi_types/nul_str.rs | 94 ++++++++++------------ abi_stable/src/sabi_types/nul_str/tests.rs | 2 - abi_stable/src/utils.rs | 9 +-- readme.md | 21 ++--- 9 files changed, 76 insertions(+), 115 deletions(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index ad9e73dd..3e562c24 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -12,8 +12,20 @@ jobs: strategy: max-parallel: 2 matrix: - rust: [stable, beta, nightly, 1.41.0, 1.51.0] + rust: nightly os: [ubuntu-latest, windows-latest, macOS-latest] + include: + - rust: stable + os: ubuntu-latest + + - rust: beta + os: ubuntu-latest + + - rust: 1.46.0 + os: ubuntu-latest + + - rust: 1.51.0 + os: ubuntu-latest steps: - name: enable-rust-stable diff --git a/Changelog.md b/Changelog.md index a7e38a75..0fc2268e 100644 --- a/Changelog.md +++ b/Changelog.md @@ -7,6 +7,8 @@ Minor changes may be ommited, as well as improvements to documentation. ### 0.10.3 +Bumped Minimum Supported Rust Version to 1.46.0 because fixing support for Rust nightly caused Internal Compiler Errors in older Rust versions. + Added `StableAbi` impls for `f32` and `f64`. Fixed error in `StableAbi` derive caused by using the derive inside a function with the `proc_macro_derive_resolution_fallback` lint enabled (deny-by-default in nightly). @@ -32,8 +34,6 @@ Deprecated `nul_str` macro. Added `nulstr` and `nulstr_trunc` macros. -Added "rust_1_46" feature. - Added "rust_latest_stable" feature. Added `LibHeader::ensure_layout` method. diff --git a/abi_stable/src/lib.rs b/abi_stable/src/lib.rs index 035d8172..00b5cf25 100644 --- a/abi_stable/src/lib.rs +++ b/abi_stable/src/lib.rs @@ -53,10 +53,16 @@ To run the example crates you'll generally have to build the `*_impl` crate, then run the `*_user` crate (all `*_user` crates should have a help message and a readme.md). -# Cargo Features +# Minimum Rust version -If it becomes possible to disable build scripts, -you can manually enable support for Rust past 1.41.0 features with the `rust_*_*` cargo features. +This crate support Rust back to 1.46.0 + +You can manually enable support for Rust past 1.46.0 with the `rust_*_*` cargo features. + +Had to bump the MSRV from 1.41.0 to 1.46.0 because fixing Rust nightly +compatibility caused Internal Compiler Errors in older Rust versions. + +# Crate Features These are default cargo features that enable optional crates : @@ -82,14 +88,7 @@ enabling the features you need in the `features` array. ### Manually enabled -These are features to manually enable support for newer language features, -required until this library is updated to automatically detect them, -every one of which has a `nightly_*` equivalent. - -Features: - -- "rust_1_46": Makes some functions `const fn`s that are otherwise not `const`, -this is documented in each function for which it applies. +These are crate features to manually enable support for newer language features: - "rust_1_51_0": Enables impls which require using const generics, diff --git a/abi_stable/src/macros/internal.rs b/abi_stable/src/macros/internal.rs index 072aa733..378b5ed8 100644 --- a/abi_stable/src/macros/internal.rs +++ b/abi_stable/src/macros/internal.rs @@ -121,27 +121,3 @@ macro_rules! zst_assert { } ///////////////////////////////////////////////////////////////////////////////7 - -#[cfg(feature = "rust_1_46")] -macro_rules! const_fn_if_1_46 { - ( - $(#[$attr:meta])* - $vis:vis $(unsafe $(@$unsafe:tt@)?)? fn $($rem:tt)* - ) => { - $(#[$attr])* - $vis const $(unsafe $(@$unsafe@)?)? fn $($rem)* - }; -} - -#[cfg(not(feature = "rust_1_46"))] -macro_rules! const_fn_if_1_46 { - ( - $(#[$attr:meta])* - $vis:vis $(unsafe $(@$unsafe:tt@)?)? fn $($rem:tt)* - ) => { - $(#[$attr])* - $vis $(unsafe $(@$unsafe@)?)? fn $($rem)* - }; -} - -///////////////////////////////////////////////////////////////////////////////7 diff --git a/abi_stable/src/macros/nul_str_macros.rs b/abi_stable/src/macros/nul_str_macros.rs index 73dfe0a4..074cfa7b 100644 --- a/abi_stable/src/macros/nul_str_macros.rs +++ b/abi_stable/src/macros/nul_str_macros.rs @@ -80,8 +80,6 @@ macro_rules! nulstr_trunc { /// /// [`NulStr`]: ./sabi_types/struct.NulStr.html #[macro_export] -#[cfg(feature = "rust_1_46")] -#[cfg_attr(feature = "docsrs", doc(cfg(feature = "rust_1_46")))] macro_rules! nulstr { ($str:expr $(,)*) => {{ const __STR_NHPMWYD3NJA: $crate::sabi_types::NulStr<'_> = diff --git a/abi_stable/src/sabi_types/nul_str.rs b/abi_stable/src/sabi_types/nul_str.rs index 7a7f6c7b..4c7f7712 100644 --- a/abi_stable/src/sabi_types/nul_str.rs +++ b/abi_stable/src/sabi_types/nul_str.rs @@ -121,64 +121,54 @@ impl<'a> NulStr<'a> { [this /* expected a nul terminator */][last_byte] } - const_fn_if_1_46! { - /// Constructs an NulStr from a string slice. - /// - /// # Cosntness - /// - /// This is a `const fn` if the `"rust_1_46"` feature is enabled, - /// otherwise it is a non-`const` function. - /// - /// # Errors - /// - /// This returns a [`NulStrError::NoNulTerminator`] when the string does not end - /// with `'\0'`. - /// - /// This returns a [`NulStrError::InnerNul`] when the string contains a - /// `'\0'` before the `'\0'` terminator. - /// - /// # Example - /// - /// ```rust - /// use abi_stable::sabi_types::{NulStr, NulStrError}; - /// - /// // `NulStr`s can be compared with `str`s - /// assert_eq!(NulStr::try_from_str("hello\0").unwrap(), "hello"); - /// - /// assert_eq!( - /// NulStr::try_from_str("hello\0world\0"), - /// Err(NulStrError::InnerNul { pos: 5 }), - /// ); - /// - /// ``` - /// - /// [`NulStrError::InnerNul`]: enum.NulStrError.html#variant.InnerNul - /// [`NulStrError::NoNulTerminator`]: enum.NulStrError.html#variant.NoNulTerminator - pub fn try_from_str(string: &'a str) -> Result { - let mut i = 0; - let mut bytes = string.as_bytes(); - - bytes = match bytes { - [rem @ .., 0] => rem, - _ => return Err(NulStrError::NoNulTerminator), - }; - - while let [b, ref rem @ ..] = *bytes { - if b == 0 { - return Err(NulStrError::InnerNul {pos : i}); - } - i += 1; - bytes = rem; - } + /// Constructs an NulStr from a string slice. + /// + /// # Errors + /// + /// This returns a [`NulStrError::NoNulTerminator`] when the string does not end + /// with `'\0'`. + /// + /// This returns a [`NulStrError::InnerNul`] when the string contains a + /// `'\0'` before the `'\0'` terminator. + /// + /// # Example + /// + /// ```rust + /// use abi_stable::sabi_types::{NulStr, NulStrError}; + /// + /// // `NulStr`s can be compared with `str`s + /// assert_eq!(NulStr::try_from_str("hello\0").unwrap(), "hello"); + /// + /// assert_eq!( + /// NulStr::try_from_str("hello\0world\0"), + /// Err(NulStrError::InnerNul { pos: 5 }), + /// ); + /// + /// ``` + /// + /// [`NulStrError::InnerNul`]: enum.NulStrError.html#variant.InnerNul + /// [`NulStrError::NoNulTerminator`]: enum.NulStrError.html#variant.NoNulTerminator + pub const fn try_from_str(string: &'a str) -> Result { + let mut i = 0; + let mut bytes = string.as_bytes(); + + bytes = match bytes { + [rem @ .., 0] => rem, + _ => return Err(NulStrError::NoNulTerminator), + }; - unsafe{ - Ok(NulStr::from_ptr(string.as_ptr())) + while let [b, ref rem @ ..] = *bytes { + if b == 0 { + return Err(NulStrError::InnerNul { pos: i }); } + i += 1; + bytes = rem; } + + unsafe { Ok(NulStr::from_ptr(string.as_ptr())) } } #[doc(hidden)] - #[cfg(feature = "rust_1_46")] pub const fn __try_from_str_unwrapping(s: &'a str) -> Self { match Self::try_from_str(s) { Ok(x) => x, diff --git a/abi_stable/src/sabi_types/nul_str/tests.rs b/abi_stable/src/sabi_types/nul_str/tests.rs index 8d9088de..038e97a2 100644 --- a/abi_stable/src/sabi_types/nul_str/tests.rs +++ b/abi_stable/src/sabi_types/nul_str/tests.rs @@ -43,7 +43,6 @@ fn nulstr_try_from_str_tests() { for (strwn, str) in pairs.iter().copied() { let nuls = [ NulStr::try_from_str(strwn).unwrap(), - #[cfg(feature = "rust_1_46")] NulStr::__try_from_str_unwrapping(strwn), ]; for &nul in &nuls { @@ -65,7 +64,6 @@ fn nulstr_try_from_str_tests() { dbg!(strwn); assert_eq!(NulStr::try_from_str(strwn), Err(err)); - #[cfg(feature = "rust_1_46")] must_panic(file_span!(), || NulStr::__try_from_str_unwrapping(strwn)).unwrap(); } } diff --git a/abi_stable/src/utils.rs b/abi_stable/src/utils.rs index 35d4f6dc..08953b9b 100644 --- a/abi_stable/src/utils.rs +++ b/abi_stable/src/utils.rs @@ -252,14 +252,7 @@ impl_fmt_padding! { RString } /// After this function is called `slot` will become uninitialized and /// must not be read again. pub unsafe fn take_manuallydrop(slot: &mut ManuallyDrop) -> T { - #[cfg(feature = "rust_1_42")] - { - ManuallyDrop::take(slot) - } - #[cfg(not(feature = "rust_1_42"))] - { - ManuallyDrop::into_inner(std::ptr::read(slot)) - } + ManuallyDrop::take(slot) } #[doc(hidden)] diff --git a/readme.md b/readme.md index 4b8c555e..879db6b1 100644 --- a/readme.md +++ b/readme.md @@ -253,7 +253,7 @@ pub trait Appender{ /// Converts this collection into an `RVec`. /// - /// As opposed to regular trait objects (as of Rust 1.47), + /// As opposed to regular trait objects, /// it is possible to call by-value methods on trait objects generated by `#[sabi_trait]`. /// /// The `#[sabi(last_prefix_field)]` attribute here means that this is the last method @@ -570,13 +570,14 @@ and loads the pre-compiled `implementation crate` dynamic library from some path # Minimum Rust version -This crate support Rust back to 1.41.0 , -using a build script to automatically enable features from newer versions. +This crate support Rust back to 1.46.0 -# Cargo Features +You can manually enable support for Rust past 1.46.0 with the `rust_*_*` cargo features. -If it becomes possible to disable build scripts, -you can manually enable support for Rust past 1.41.0 features with the `rust_*_*` cargo features. +Had to bump the MSRV from 1.41.0 to 1.46.0 because fixing Rust nightly +compatibility caused Internal Compiler Errors in older Rust versions. + +# Crate Features These are default cargo features that enable optional crates : @@ -603,13 +604,7 @@ enabling the features you need in the `features` array. ### Manually enabled -These are features to manually enable support for newer language features, -required until this library is updated to automatically detect them. - -Features: - -- "rust_1_46": Makes some functions `const fn`s that are otherwise not `const`, -this is documented in each function for which it applies. +These are crate features to manually enable support for newer language features: - "rust_1_51_0": Enables impls which require using const generics, From 38402fa6c7856858bb53c0f6552e1e3a9cfefe33 Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Fri, 29 Oct 2021 02:32:36 -0300 Subject: [PATCH 31/32] Update rust.yml --- .github/workflows/rust.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 3e562c24..bbe9a181 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -12,7 +12,7 @@ jobs: strategy: max-parallel: 2 matrix: - rust: nightly + rust: [nightly] os: [ubuntu-latest, windows-latest, macOS-latest] include: - rust: stable From ec2638d8c37329e6bb7d47a25bee7fba2b79010b Mon Sep 17 00:00:00 2001 From: rodrimati1992 Date: Fri, 29 Oct 2021 03:12:42 -0300 Subject: [PATCH 32/32] Update rust.yml --- .github/workflows/rust.yml | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index bbe9a181..f83c66c7 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -28,22 +28,23 @@ jobs: os: ubuntu-latest steps: - - name: enable-rust-stable - if: matrix.rust == '1.51.0' - run: echo "rustv=rust_1_51" >> $GITHUB_ENV - - - name: enable-rust-stable - if: matrix.rust == 'stable' || matrix.rust == 'beta' || matrix.rust == 'nightly' - run: echo "rustv=rust_latest_stable" >> $GITHUB_ENV - - uses: actions/checkout@v2 - name: ci-format + if: matrix.rust == 'stable' run: | rustup override set ${{ matrix.rust }} rustup component add rustfmt cd "${{github.workspace}}/" cargo fmt -- --check + - name: enable-rust-stable + if: matrix.rust == '1.51.0' + run: echo "rustv=rust_1_51" >> $GITHUB_ENV + + - name: enable-rust-stable + if: matrix.rust == 'stable' || matrix.rust == 'beta' || matrix.rust == 'nightly' + run: echo "rustv=rust_latest_stable" >> $GITHUB_ENV + - uses: actions/checkout@v2 - name: ci-all-versions run: |