Vendor dependencies

This commit is contained in:
2026-08-01 16:11:49 +03:00
parent 7f139a0241
commit 6b5e7f0f8b
29706 changed files with 9575646 additions and 0 deletions
@@ -0,0 +1 @@
{"$comment":"This file only protects against accidental modifications. It is not a security mechanism and does not protect against malicious changes.","files":{".cargo_vcs_info.json":"de03757fbce6641ef9ffc8f79cc090cb97ea5db7567b35cd405c4baf968a1376","Cargo.lock":"c376d29aa837899933a650d028b329f537e011c8669aa927d0ff979b748a1714","Cargo.toml":"5be1f0ed60e65d33569c25e87fa41483b03d86f564d7af9820ab8b1a9a386a39","Cargo.toml.orig":"889f9d2c8a2a4c84cf2c2abb254a7b966e29ef4f1c8f8fd13743515a55969781","LICENSE-APACHE":"62c7a1e35f56406896d7aa7ca52d0cc0d272ac022b5d2796e7d6905db8a3636a","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","src/lib.rs":"db0a1d93a9ab05a440efd2bc0c799ad55a02d9e7d1a945d36ff6eaee95e8da09"},"package":"2c9283685feec7d69af75fb0e858d5e7378f33fe4fc699383b2916ab9273e03c"}
@@ -0,0 +1,6 @@
{
"git": {
"sha1": "751d639d563d2a427829101fd1e5801fb17cb1be"
},
"path_in_vcs": "derive"
}
+79
View File
@@ -0,0 +1,79 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "proc-macro2"
version = "1.0.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"
dependencies = [
"proc-macro2",
]
[[package]]
name = "ref-cast"
version = "1.0.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f354300ae66f76f1c85c5f84693f0ce81d747e2c3f21a45fef496d89c960bf7d"
dependencies = [
"ref-cast-impl 1.0.25",
]
[[package]]
name = "ref-cast-impl"
version = "1.0.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7186006dcb21920990093f30e3dea63b7d6e977bf1256be20c3563a5db070da"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "ref-cast-impl"
version = "1.0.26"
dependencies = [
"proc-macro2",
"quote",
"ref-cast",
"syn 3.0.0",
]
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2fac314a64dc9a36e61a9eb4261a5e9bbfbc922b27e518af97bc32b926cf967"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+56
View File
@@ -0,0 +1,56 @@
# 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.71"
name = "ref-cast-impl"
version = "1.0.26"
authors = ["David Tolnay <dtolnay@gmail.com>"]
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]
targets = ["x86_64-unknown-linux-gnu"]
rustdoc-args = [
"--generate-link-to-definition",
"--generate-macro-expansion",
"--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",
]
[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 = "3"
[dev-dependencies.ref-cast]
version = "1"
+32
View File
@@ -0,0 +1,32 @@
[package]
name = "ref-cast-impl"
version = "1.0.26"
authors = ["David Tolnay <dtolnay@gmail.com>"]
description = "Derive implementation for ref_cast::RefCast."
documentation = "https://docs.rs/ref-cast"
edition = "2021"
license = "MIT OR Apache-2.0"
repository = "https://github.com/dtolnay/ref-cast"
rust-version = "1.71"
[lib]
proc-macro = true
[dependencies]
proc-macro2 = "1.0.74"
quote = "1.0.35"
syn = "3"
[dev-dependencies]
ref-cast = "1"
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
rustdoc-args = [
"--generate-link-to-definition",
"--generate-macro-expansion",
"--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",
]
+176
View File
@@ -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
+23
View File
@@ -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.
+554
View File
@@ -0,0 +1,554 @@
#![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, ToTokens, TokenStreamExt as _};
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<T, U> {
/// raw: Vec<U>,
/// #[trivial]
/// aux: Variance<T, U>,
/// }
///
/// type Variance<T, U> = PhantomData<fn(T) -> 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<T: AsRef<[u8]>>(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<Token![const]> = input.parse()?;
let asyncness: Option<Token![async]> = input.parse()?;
let unsafety: Option<Token![unsafe]> = input.parse()?;
let abi: Option<Abi> = 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<Token![,]> = 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::<Nothing>(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)
}
#[allow(non_camel_case_types)]
struct private;
impl ToTokens for private {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
tokens.append(Ident::new(
concat!("__private", env!("CARGO_PKG_VERSION_PATCH")),
Span::call_site(),
));
}
}
struct Function {
attrs: Vec<Attribute>,
vis: Visibility,
constness: Option<Token![const]>,
asyncness: Option<Token![async]>,
unsafety: Option<Token![unsafe]>,
abi: Option<Abi>,
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<TokenStream2> {
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 private2 = private;
let assert_trivial_fields = if !trivial.is_empty() {
Some(quote! {
if false {
#(
::ref_cast::#private2::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::<Self, Self::From>(
#name_str,
::ref_cast::#private::Layout::<Self>::SIZE,
::ref_cast::#private::Layout::<Self::From>::SIZE,
::ref_cast::#private::Layout::<Self>::ALIGN,
::ref_cast::#private::Layout::<Self::From>::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::<Self, Self::From>(
#name_str,
::ref_cast::#private::Layout::<Self>::SIZE,
::ref_cast::#private::Layout::<Self::From>::SIZE,
::ref_cast::#private::Layout::<Self>::ALIGN,
::ref_cast::#private::Layout::<Self::From>::ALIGN,
);
}
unsafe {
&mut *(_from as *mut Self::From as *mut Self)
}
}
}
})
}
fn expand_ref_cast_custom(input: &DeriveInput) -> Result<TokenStream2> {
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 private2 = private;
let assert_trivial_fields = if !trivial.is_empty() {
Some(quote! {
fn __static_assert() {
if false {
#(
::ref_cast::#private2::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::<Token![,]>()?;
}
}
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<Field, Token![,]>;
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<Vec<&Type>> {
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<fn(&Field) -> Result<bool>> {
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<bool> {
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<bool> {
for attr in &field.attrs {
if attr.path().is_ident("trivial") {
attr.meta.require_path_only()?;
return Ok(true);
}
}
Ok(false)
}