From 8cdfa445d6629ffef4cb84967ff7017654045bc2 Mon Sep 17 00:00:00 2001 From: mo khan Date: Wed, 2 Jul 2025 18:36:06 -0600 Subject: chore: add vendor directory --- vendor/ref-cast-impl/.cargo-checksum.json | 1 + vendor/ref-cast-impl/Cargo.lock | 68 ++++ vendor/ref-cast-impl/Cargo.toml | 55 +++ vendor/ref-cast-impl/LICENSE-APACHE | 176 ++++++++++ vendor/ref-cast-impl/LICENSE-MIT | 23 ++ vendor/ref-cast-impl/src/lib.rs | 540 ++++++++++++++++++++++++++++++ 6 files changed, 863 insertions(+) create mode 100644 vendor/ref-cast-impl/.cargo-checksum.json create mode 100644 vendor/ref-cast-impl/Cargo.lock create mode 100644 vendor/ref-cast-impl/Cargo.toml create mode 100644 vendor/ref-cast-impl/LICENSE-APACHE create mode 100644 vendor/ref-cast-impl/LICENSE-MIT create mode 100644 vendor/ref-cast-impl/src/lib.rs (limited to 'vendor/ref-cast-impl') diff --git a/vendor/ref-cast-impl/.cargo-checksum.json b/vendor/ref-cast-impl/.cargo-checksum.json new file mode 100644 index 00000000..7ff21176 --- /dev/null +++ b/vendor/ref-cast-impl/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.lock":"c34c2c2c4469ab40c230adbbde14ea5e5da80b2af59a4b0549f7d2df2381c1fa","Cargo.toml":"3ba3d72a378f554020ae4546ae2235470987e39e76cae1c9be87c69d0e5a0555","LICENSE-APACHE":"62c7a1e35f56406896d7aa7ca52d0cc0d272ac022b5d2796e7d6905db8a3636a","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","src/lib.rs":"09b5912a147200d1899ad446603a547342a866eb38dd1296d1545210092faf9c"},"package":"1165225c21bff1f3bbce98f5a1f889949bc902d3575308cc7b0de30b4f6d27c7"} \ No newline at end of file diff --git a/vendor/ref-cast-impl/Cargo.lock b/vendor/ref-cast-impl/Cargo.lock new file mode 100644 index 00000000..88268367 --- /dev/null +++ b/vendor/ref-cast-impl/Cargo.lock @@ -0,0 +1,68 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "proc-macro2" +version = "1.0.93" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60946a68e5f9d28b0dc1c21bb8a97ee7d018a8b322fa57838ba31cc878e22d99" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e4dccaaaf89514f546c693ddc140f729f958c247918a13380cccc6078391acc" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "ref-cast" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf0a6f84d5f1d581da8b41b47ec8600871962f2a528115b542b362d4b744931" +dependencies = [ + "ref-cast-impl 1.0.23", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bcc303e793d3734489387d205e9b186fac9c6cfacedd98cbb2e8a5943595f3e6" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.24" +dependencies = [ + "proc-macro2", + "quote", + "ref-cast", + "syn", +] + +[[package]] +name = "syn" +version = "2.0.98" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36147f1a48ae0ec2b5b3bc5b537d267457555a10dc06f3dbc8cb11ba3006d3b1" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00e2473a93778eb0bad35909dff6a10d28e63f792f16ed15e404fca9d5eeedbe" diff --git a/vendor/ref-cast-impl/Cargo.toml b/vendor/ref-cast-impl/Cargo.toml new file mode 100644 index 00000000..6d69c622 --- /dev/null +++ b/vendor/ref-cast-impl/Cargo.toml @@ -0,0 +1,55 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +rust-version = "1.56" +name = "ref-cast-impl" +version = "1.0.24" +authors = ["David Tolnay "] +build = false +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "Derive implementation for ref_cast::RefCast." +documentation = "https://docs.rs/ref-cast" +readme = false +license = "MIT OR Apache-2.0" +repository = "https://github.com/dtolnay/ref-cast" + +[package.metadata.docs.rs] +rustdoc-args = [ + "--generate-link-to-definition", + "--extern-html-root-url=core=https://doc.rust-lang.org", + "--extern-html-root-url=alloc=https://doc.rust-lang.org", + "--extern-html-root-url=std=https://doc.rust-lang.org", + "--extern-html-root-url=proc_macro=https://doc.rust-lang.org", +] +targets = ["x86_64-unknown-linux-gnu"] + +[lib] +name = "ref_cast_impl" +path = "src/lib.rs" +proc-macro = true + +[dependencies.proc-macro2] +version = "1.0.74" + +[dependencies.quote] +version = "1.0.35" + +[dependencies.syn] +version = "2.0.46" + +[dev-dependencies.ref-cast] +version = "1" diff --git a/vendor/ref-cast-impl/LICENSE-APACHE b/vendor/ref-cast-impl/LICENSE-APACHE new file mode 100644 index 00000000..1b5ec8b7 --- /dev/null +++ b/vendor/ref-cast-impl/LICENSE-APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS diff --git a/vendor/ref-cast-impl/LICENSE-MIT b/vendor/ref-cast-impl/LICENSE-MIT new file mode 100644 index 00000000..31aa7938 --- /dev/null +++ b/vendor/ref-cast-impl/LICENSE-MIT @@ -0,0 +1,23 @@ +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/vendor/ref-cast-impl/src/lib.rs b/vendor/ref-cast-impl/src/lib.rs new file mode 100644 index 00000000..96da08a0 --- /dev/null +++ b/vendor/ref-cast-impl/src/lib.rs @@ -0,0 +1,540 @@ +#![allow( + clippy::blocks_in_conditions, + clippy::needless_pass_by_value, + clippy::if_not_else +)] + +extern crate proc_macro; + +use proc_macro::TokenStream; +use proc_macro2::{Ident, Span, TokenStream as TokenStream2, TokenTree}; +use quote::{quote, quote_spanned}; +use syn::parse::{Nothing, ParseStream, Parser}; +use syn::punctuated::Punctuated; +use syn::{ + parenthesized, parse_macro_input, token, Abi, Attribute, Data, DeriveInput, Error, Expr, Field, + Generics, Path, Result, Token, Type, Visibility, +}; + +/// Derive the `RefCast` trait. +/// +/// See the [crate-level documentation](./index.html) for usage examples! +/// +/// # Attributes +/// +/// Use the `#[trivial]` attribute to mark any zero-sized fields that are *not* +/// the one that references are going to be converted from. +/// +/// ``` +/// use ref_cast::RefCast; +/// use std::marker::PhantomData; +/// +/// #[derive(RefCast)] +/// #[repr(transparent)] +/// pub struct Generic { +/// raw: Vec, +/// #[trivial] +/// aux: Variance, +/// } +/// +/// type Variance = PhantomData U>; +/// ``` +/// +/// Fields with a type named `PhantomData` or `PhantomPinned` are automatically +/// recognized and do not need to be marked with this attribute. +/// +/// ``` +/// use ref_cast::RefCast; +/// use std::marker::{PhantomData, PhantomPinned}; +/// +/// #[derive(RefCast)] // generates a conversion from &[u8] to &Bytes<'_> +/// #[repr(transparent)] +/// pub struct Bytes<'arena> { +/// lifetime: PhantomData<&'arena ()>, +/// pin: PhantomPinned, +/// bytes: [u8], +/// } +/// ``` +#[proc_macro_derive(RefCast, attributes(trivial))] +pub fn derive_ref_cast(input: TokenStream) -> TokenStream { + let input = parse_macro_input!(input as DeriveInput); + expand_ref_cast(&input) + .unwrap_or_else(Error::into_compile_error) + .into() +} + +/// Derive that makes the `ref_cast_custom` attribute able to generate +/// freestanding reference casting functions for a type. +/// +/// Please refer to the documentation of +/// [`#[ref_cast_custom]`][macro@ref_cast_custom] where these two macros are +/// documented together. +#[proc_macro_derive(RefCastCustom, attributes(trivial))] +pub fn derive_ref_cast_custom(input: TokenStream) -> TokenStream { + let input = parse_macro_input!(input as DeriveInput); + expand_ref_cast_custom(&input) + .unwrap_or_else(Error::into_compile_error) + .into() +} + +/// Create a function for a RefCast-style reference cast. Call site gets control +/// of the visibility, function name, argument name, `const`ness, unsafety, and +/// documentation. +/// +/// The `derive(RefCast)` macro produces a trait impl, which means the function +/// names are predefined, and public if your type is public, and not callable in +/// `const` (at least today on stable Rust). As an alternative to that, +/// `derive(RefCastCustom)` exposes greater flexibility so that instead of a +/// trait impl, the casting functions can be made associated functions or free +/// functions, can be named what you want, documented, `const` or `unsafe` if +/// you want, and have your exact choice of visibility. +/// +/// ```rust +/// use ref_cast::{ref_cast_custom, RefCastCustom}; +/// +/// #[derive(RefCastCustom)] // does not generate any public API by itself +/// #[repr(transparent)] +/// pub struct Frame([u8]); +/// +/// impl Frame { +/// #[ref_cast_custom] // requires derive(RefCastCustom) on the return type +/// pub(crate) const fn new(bytes: &[u8]) -> &Self; +/// +/// #[ref_cast_custom] +/// pub(crate) fn new_mut(bytes: &mut [u8]) -> &mut Self; +/// } +/// +/// // example use of the const fn +/// const FRAME: &Frame = Frame::new(b"..."); +/// ``` +/// +/// The above shows associated functions, but you might alternatively want to +/// generate free functions: +/// +/// ```rust +/// # use ref_cast::{ref_cast_custom, RefCastCustom}; +/// # +/// # #[derive(RefCastCustom)] +/// # #[repr(transparent)] +/// # pub struct Frame([u8]); +/// # +/// impl Frame { +/// pub fn new>(bytes: &T) -> &Self { +/// #[ref_cast_custom] +/// fn ref_cast(bytes: &[u8]) -> &Frame; +/// +/// ref_cast(bytes.as_ref()) +/// } +/// } +/// ``` +#[proc_macro_attribute] +pub fn ref_cast_custom(args: TokenStream, input: TokenStream) -> TokenStream { + let input = TokenStream2::from(input); + let expanded = match (|input: ParseStream| { + let attrs = input.call(Attribute::parse_outer)?; + let vis: Visibility = input.parse()?; + let constness: Option = input.parse()?; + let asyncness: Option = input.parse()?; + let unsafety: Option = input.parse()?; + let abi: Option = input.parse()?; + let fn_token: Token![fn] = input.parse()?; + let ident: Ident = input.parse()?; + let mut generics: Generics = input.parse()?; + + let content; + let paren_token = parenthesized!(content in input); + let arg: Ident = content.parse()?; + let colon_token: Token![:] = content.parse()?; + let from_type: Type = content.parse()?; + let _trailing_comma: Option = content.parse()?; + if !content.is_empty() { + let rest: TokenStream2 = content.parse()?; + return Err(Error::new_spanned( + rest, + "ref_cast_custom function is required to have a single argument", + )); + } + + let arrow_token: Token![->] = input.parse()?; + let to_type: Type = input.parse()?; + generics.where_clause = input.parse()?; + let semi_token: Token![;] = input.parse()?; + + let _: Nothing = syn::parse::(args)?; + + Ok(Function { + attrs, + vis, + constness, + asyncness, + unsafety, + abi, + fn_token, + ident, + generics, + paren_token, + arg, + colon_token, + from_type, + arrow_token, + to_type, + semi_token, + }) + }) + .parse2(input.clone()) + { + Ok(function) => expand_function_body(function), + Err(parse_error) => { + let compile_error = parse_error.to_compile_error(); + quote!(#compile_error #input) + } + }; + TokenStream::from(expanded) +} + +struct Function { + attrs: Vec, + vis: Visibility, + constness: Option, + asyncness: Option, + unsafety: Option, + abi: Option, + fn_token: Token![fn], + ident: Ident, + generics: Generics, + paren_token: token::Paren, + arg: Ident, + colon_token: Token![:], + from_type: Type, + arrow_token: Token![->], + to_type: Type, + semi_token: Token![;], +} + +fn expand_ref_cast(input: &DeriveInput) -> Result { + check_repr(input)?; + + let name = &input.ident; + let name_str = name.to_string(); + let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); + + let fields = fields(input)?; + let from = only_field_ty(fields)?; + let trivial = trivial_fields(fields)?; + + let assert_trivial_fields = if !trivial.is_empty() { + Some(quote! { + if false { + #( + ::ref_cast::__private::assert_trivial::<#trivial>(); + )* + } + }) + } else { + None + }; + + Ok(quote! { + impl #impl_generics ::ref_cast::RefCast for #name #ty_generics #where_clause { + type From = #from; + + #[inline] + fn ref_cast(_from: &Self::From) -> &Self { + #assert_trivial_fields + #[cfg(debug_assertions)] + { + #[allow(unused_imports)] + use ::ref_cast::__private::LayoutUnsized; + ::ref_cast::__private::assert_layout::( + #name_str, + ::ref_cast::__private::Layout::::SIZE, + ::ref_cast::__private::Layout::::SIZE, + ::ref_cast::__private::Layout::::ALIGN, + ::ref_cast::__private::Layout::::ALIGN, + ); + } + unsafe { + &*(_from as *const Self::From as *const Self) + } + } + + #[inline] + fn ref_cast_mut(_from: &mut Self::From) -> &mut Self { + #[cfg(debug_assertions)] + { + #[allow(unused_imports)] + use ::ref_cast::__private::LayoutUnsized; + ::ref_cast::__private::assert_layout::( + #name_str, + ::ref_cast::__private::Layout::::SIZE, + ::ref_cast::__private::Layout::::SIZE, + ::ref_cast::__private::Layout::::ALIGN, + ::ref_cast::__private::Layout::::ALIGN, + ); + } + unsafe { + &mut *(_from as *mut Self::From as *mut Self) + } + } + } + }) +} + +fn expand_ref_cast_custom(input: &DeriveInput) -> Result { + check_repr(input)?; + + let vis = &input.vis; + let name = &input.ident; + let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); + + let fields = fields(input)?; + let from = only_field_ty(fields)?; + let trivial = trivial_fields(fields)?; + + let assert_trivial_fields = if !trivial.is_empty() { + Some(quote! { + fn __static_assert() { + if false { + #( + ::ref_cast::__private::assert_trivial::<#trivial>(); + )* + } + } + }) + } else { + None + }; + + Ok(quote! { + const _: () = { + #[non_exhaustive] + #vis struct RefCastCurrentCrate {} + + unsafe impl #impl_generics ::ref_cast::__private::RefCastCustom<#from> for #name #ty_generics #where_clause { + type CurrentCrate = RefCastCurrentCrate; + #assert_trivial_fields + } + }; + }) +} + +fn expand_function_body(function: Function) -> TokenStream2 { + let Function { + attrs, + vis, + constness, + asyncness, + unsafety, + abi, + fn_token, + ident, + generics, + paren_token, + arg, + colon_token, + from_type, + arrow_token, + to_type, + semi_token, + } = function; + + let args = quote_spanned! {paren_token.span=> + (#arg #colon_token #from_type) + }; + + let allow_unused_unsafe = if unsafety.is_some() { + Some(quote!(#[allow(unused_unsafe)])) + } else { + None + }; + + let mut inline_attr = Some(quote!(#[inline])); + for attr in &attrs { + if attr.path().is_ident("inline") { + inline_attr = None; + break; + } + } + + // Apply a macro-generated span to the "unsafe" token for the unsafe block. + // This is instead of reusing the caller's function signature's #unsafety + // across both the generated function signature and generated unsafe block, + // and instead of using `semi_token.span` like for the rest of the generated + // code below, both of which would cause `forbid(unsafe_code)` located in + // the caller to reject the expanded code. + let macro_generated_unsafe = quote!(unsafe); + + quote_spanned! {semi_token.span=> + #(#attrs)* + #inline_attr + #vis #constness #asyncness #unsafety #abi + #fn_token #ident #generics #args #arrow_token #to_type { + // check lifetime + let _ = || { + ::ref_cast::__private::ref_cast_custom::<#from_type, #to_type>(#arg); + }; + + // check same crate + let _ = ::ref_cast::__private::CurrentCrate::<#from_type, #to_type> {}; + + #allow_unused_unsafe // in case they are building with deny(unsafe_op_in_unsafe_fn) + #[allow(clippy::transmute_ptr_to_ptr)] + #macro_generated_unsafe { + ::ref_cast::__private::transmute::<#from_type, #to_type>(#arg) + } + } + } +} + +fn check_repr(input: &DeriveInput) -> Result<()> { + let mut has_repr = false; + let mut errors = None; + let mut push_error = |error| match &mut errors { + Some(errors) => Error::combine(errors, error), + None => errors = Some(error), + }; + + for attr in &input.attrs { + if attr.path().is_ident("repr") { + if let Err(error) = attr.parse_args_with(|input: ParseStream| { + while !input.is_empty() { + let path = input.call(Path::parse_mod_style)?; + if path.is_ident("transparent") || path.is_ident("C") { + has_repr = true; + } else if path.is_ident("packed") { + // ignore + } else { + let meta_item_span = if input.peek(token::Paren) { + let group: TokenTree = input.parse()?; + quote!(#path #group) + } else if input.peek(Token![=]) { + let eq_token: Token![=] = input.parse()?; + let value: Expr = input.parse()?; + quote!(#path #eq_token #value) + } else { + quote!(#path) + }; + let msg = if path.is_ident("align") { + "aligned repr on struct that implements RefCast is not supported" + } else { + "unrecognized repr on struct that implements RefCast" + }; + push_error(Error::new_spanned(meta_item_span, msg)); + } + if !input.is_empty() { + input.parse::()?; + } + } + Ok(()) + }) { + push_error(error); + } + } + } + + if !has_repr { + let mut requires_repr = Error::new( + Span::call_site(), + "RefCast trait requires #[repr(transparent)]", + ); + if let Some(errors) = errors { + requires_repr.combine(errors); + } + errors = Some(requires_repr); + } + + match errors { + None => Ok(()), + Some(errors) => Err(errors), + } +} + +type Fields = Punctuated; + +fn fields(input: &DeriveInput) -> Result<&Fields> { + use syn::Fields; + + match &input.data { + Data::Struct(data) => match &data.fields { + Fields::Named(fields) => Ok(&fields.named), + Fields::Unnamed(fields) => Ok(&fields.unnamed), + Fields::Unit => Err(Error::new( + Span::call_site(), + "RefCast does not support unit structs", + )), + }, + Data::Enum(_) => Err(Error::new( + Span::call_site(), + "RefCast does not support enums", + )), + Data::Union(_) => Err(Error::new( + Span::call_site(), + "RefCast does not support unions", + )), + } +} + +fn only_field_ty(fields: &Fields) -> Result<&Type> { + let is_trivial = decide_trivial(fields)?; + let mut only_field = None; + + for field in fields { + if !is_trivial(field)? { + if only_field.take().is_some() { + break; + } + only_field = Some(&field.ty); + } + } + + only_field.ok_or_else(|| { + Error::new( + Span::call_site(), + "RefCast requires a struct with a single field", + ) + }) +} + +fn trivial_fields(fields: &Fields) -> Result> { + let is_trivial = decide_trivial(fields)?; + let mut trivial = Vec::new(); + + for field in fields { + if is_trivial(field)? { + trivial.push(&field.ty); + } + } + + Ok(trivial) +} + +fn decide_trivial(fields: &Fields) -> Result Result> { + for field in fields { + if is_explicit_trivial(field)? { + return Ok(is_explicit_trivial); + } + } + Ok(is_implicit_trivial) +} + +#[allow(clippy::unnecessary_wraps)] // match signature of is_explicit_trivial +fn is_implicit_trivial(field: &Field) -> Result { + match &field.ty { + Type::Tuple(ty) => Ok(ty.elems.is_empty()), + Type::Path(ty) => { + let ident = &ty.path.segments.last().unwrap().ident; + Ok(ident == "PhantomData" || ident == "PhantomPinned") + } + _ => Ok(false), + } +} + +fn is_explicit_trivial(field: &Field) -> Result { + for attr in &field.attrs { + if attr.path().is_ident("trivial") { + attr.meta.require_path_only()?; + return Ok(true); + } + } + Ok(false) +} -- cgit v1.2.3