Commit c40e990b authored by Simon Sapin's avatar Simon Sapin
Browse files

Initial implementation

parent 8676df109694
......@@ -2,6 +2,13 @@
name = "bytes-cast"
version = "0.1.0"
authors = ["Octobus"]
license = "Zlib OR Apache-2.0 OR MIT"
repository = "https://foss.heptapod.net/octobus/rust/bytes-cast"
description = "Safely re-interpreting &[u8] bytes as custom structs without copying, for efficiently reading structured binary data."
edition = "2018"
[lib]
test = false # Tests are doctests
[dependencies]
bytes-cast-derive = { version = "0.1", path = "derive" }
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
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
MIT License
Copyright (c) 2019 Daniel "Lokathor" Gee.
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 (including the next paragraph) 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.
Copyright (c) 2019 Daniel "Lokathor" Gee.
This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
# `bytes-cast`
Safely re-interpreting `&[u8]` bytes as custom structs without copying,
for efficiently reading structured binary data.
[![crates.io](https://img.shields.io/crates/v/bytes-cast.svg)](https://crates.io/crates/bytes-cast)
[![docs.rs](https://docs.rs/bytes-cast/badge.svg)](https://docs.rs/bytes-cast/)
## Credits
This crate contains code derived from <https://github.com/Lokathor/bytemuck>.
## Problem statement
When reading from disk a file in a given format, “traditional” parsing techniques such
with the `nom` crate typically involve creating a different data structure in memory
where allocation and copying can be costly.
For binary formats amenable to this it can be more efficient to have in memory
a bytes buffer in the same format as on disk, possibly memory-mapped directly by the kernel,
and only access parts of it as needed.
But doing this entierly with manual index or pointer manipulation can be error-prone.
By defining `struct`s whose memory layout matches the binary format
then casting pointers to manipulate reference, arrays, or slices of those structs
we can let the compiler do most of the offset computations and have much more readable code.
## Issues and checking
* Some Rust types have validity constraints and must not be cast from arbitrary bytes.
For example creating a `bool` whose value in memory is not `0_u8` or `1_u8` is Undefined Behavior.
Similarly for `enum`s.
* When `align_of` for a type is greater than one,
accessing values of that type at addresses not a multiple of alignment is Undefined Behavior.
Alignment can also cause struct to have padding, making field offsets not what we might expect.
Instead, we can make helper types that wrap for example `[u8; 4]` and convert to/from `u32`.
* Binary formats for storage or transmission typically mandate one of little-endian or big-endian.
Helper types again can take care of conversion to and from the CPU’s native endianness.
* By default the Rust compiler can choose reorder struct fields (in order to reduce padding).
This again can make field offsets not what we’d expect.
This can be disabled by marking a struct with `#[repr(C)]` or `#[repr(transparent)]`.
This crate combines Rust’s check for all of the above at compile-time.
The the [documentation](https://docs.rs/bytes-cast/) for API details.
## Why another crate
`bytemuck` and other projects already exist with very similar goals.
This crate make some different design choices and is opinionated in some ways:
* It only converts from `&[u8]` bytes
and does not try to be more general or accomodate many use cases.
* Providing more bytes than necessary is not an error.
Instead the start of the slice is re-interpreted,
and the remaining bytes are part of the return value for further processing.
(The caller can check or assert `remaining.is_empty()` if an exact length is desired.)
* It mandates `align_of() == 1` at compile-time instead of checking pointer alignment at runtime,
removing one category of panics or errors that needs to be handled.
Not enough bytes is the only error case.
Fields with `align_of() == 1` also removes any padding in structs.
\ No newline at end of file
[package]
name = "bytes-cast-derive"
version = "0.1.0"
authors = ["Octobus"]
license = "Zlib OR Apache-2.0 OR MIT"
repository = "https://foss.heptapod.net/octobus/rust/bytes-cast"
description = "Safely re-interpreting &[u8] bytes as custom structs without copying, for efficiently reading structured binary data. Procedural macro for compile-time soundness checking."
edition = "2018"
[lib]
proc-macro = true
test = false
[dependencies]
proc-macro2 = "1.0"
quote = "1.0"
syn = "1.0"
\ No newline at end of file
../LICENSE-APACHE
\ No newline at end of file
../LICENSE-MIT
\ No newline at end of file
../LICENSE-ZLIB
\ No newline at end of file
# `bytes-cast-derive`
The `#[derive(BytesCast)]` procedural macro for the `bytes-cast` crate.
This statically checks the safety invariants required of custom structs.
This crate contains code derived from <https://github.com/Lokathor/bytemuck>.
extern crate proc_macro;
use proc_macro2::{TokenStream, TokenTree};
use quote::{quote, quote_spanned};
use syn::{parse_macro_input, Data, DataStruct, DeriveInput, Ident};
/// Derive the `BytesCast` trait. See trait documentation.
#[proc_macro_derive(BytesCast)]
pub fn derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
derive_inner(parse_macro_input!(input as DeriveInput))
.unwrap_or_else(|error| quote!( compile_error!(#error); ))
.into()
}
fn derive_inner(input: DeriveInput) -> Result<TokenStream, &'static str> {
if !input.generics.params.is_empty() {
return Err(
"BytesCast cannot be derived for structs containing generic parameters \
because the alignment requirement can’t be verified for generic structs",
)?;
}
let fields = if let Data::Struct(DataStruct { fields, .. }) = &input.data {
fields
} else {
return Err("Deriving BytesCast is only supported for structs");
};
check_repr(&input).map_err(|()| {
"BytesCast may give unexpected results without #[repr(C)] or #[repr(transparent)]"
})?;
let name = &input.ident;
let span = input.ident.span();
let field_types = fields.iter().map(|field| &field.ty);
let asserts = quote_spanned!(span =>
const _: fn() = || {
let _static_assert_align_1: [(); 1] =
[(); ::core::mem::align_of::<#name>()];
fn _static_assert_is_bytes_cast<T: BytesCast>() {}
#(
_static_assert_is_bytes_cast::<#field_types>();
)*
};
);
Ok(quote! {
#asserts
unsafe impl BytesCast for #name {}
})
}
fn check_repr(input: &DeriveInput) -> Result<(), ()> {
for attr in &input.attrs {
if let (Some(path_ident), Some(inner_ident)) = (
attr.path.get_ident(),
get_ident_from_stream(attr.tokens.clone()),
) {
if path_ident == "repr" {
return if inner_ident == "C" || inner_ident == "transparent" {
Ok(())
} else {
Err(())
};
}
}
}
Err(())
}
fn get_ident_from_stream(tokens: TokenStream) -> Option<Ident> {
match tokens.into_iter().next() {
Some(TokenTree::Group(group)) => get_ident_from_stream(group.stream()),
Some(TokenTree::Ident(ident)) => Some(ident),
_ => None,
}
}
/*!
Doctests not part of the documentation are used instead of “normal” tests
because they support expecting a compilation error with `compile_fail`.
## Good
```
use bytes_cast::*;
#[derive(BytesCast)]
#[repr(C)]
struct Example {}
#[derive(BytesCast)]
#[repr(C)]
struct Example2(
u8,
unaligned::U32Be,
);
```
## Bad
```compile_fail
use bytes_cast::*;
#[derive(BytesCast)]
#[repr(C)]
enum NotAStruct {
A,
B,
}
```
```compile_fail
use bytes_cast::*;
#[derive(BytesCast)]
struct NoReprAttribute {}
```
```compile_fail
use bytes_cast::*;
#[derive(BytesCast)]
#[repr(C)]
struct Generic<T>(T);
```
```compile_fail
use bytes_cast::*;
#[derive(BytesCast)]
#[repr(C)]
struct FieldIsNotBytesCast(
u8,
u32,
);
```
```compile_fail
use bytes_cast::*;
#[derive(BytesCast)]
#[repr(C)]
#[repr(align(2))]
struct HasAlignmentRequirement {}
```
*/
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
//! Utilities for safely re-interpreting `&[u8]` bytes as custom structs
//! without copying, for efficiently reading structured binary data.
//!
//! # Example
//!
//! ```
//! use bytes_cast::{BytesCast, unaligned};
//!
//! #[derive(BytesCast)]
//! #[repr(C)]
//! struct Foo {
//! bar: [u8; 2],
//! baz: unaligned::U32Be,
//! }
//!
//! let input = &[1_u8, 2, 3, 4, 5, 6, 7, 8];
//!
//! let (foo, rest) = Foo::from_bytes(input).unwrap();
//! assert_eq!(foo.bar, [1_u8, 2]);
//! assert_eq!(foo.baz.get(), 0x0304_0506_u32);
//! assert_eq!(rest, &[7_u8, 8]);
//!
//! assert!(<[Foo; 2]>::from_bytes(input).is_err()); // input is too short
//!
//! let (values, rest) = unaligned::U16Le::slice_from_bytes(input, 2).unwrap();
//! assert_eq!(values.len(), 2);
//! assert_eq!(values[0].get(), 0x02_01_u16);
//! assert_eq!(values[1].get(), 0x04_03_u16);
//! assert_eq!(rest, &[5_u8, 6, 7, 8]);
//!
//! assert!(unaligned::U16Le::slice_from_bytes(input, 5).is_err()); // input is too short
//! ```
#![no_std]
pub use bytes_cast_derive::BytesCast;
use core::fmt;
use core::mem;
use core::slice;
pub mod unaligned;
#[cfg(doctest)]
mod compile_fail_tests;
/// Marks a type as safe to interpret from bytes without copying.
///
/// # Safety
///
/// For a type to implement this trait:
///
/// * All bit patterns must be valid. (This excludes `bool`, enums, etc.)
/// * There must not be an alignment requirement. (`align_of() == 1`)
///
/// # Deriving
///
/// Instead of writing `unsafe impl` blocks this trait should be derived.
/// `#[derive(BytesCast)]` on a type definition invokes a procedural macro
/// that implements the trait after checking that the type:
///
/// * Is a `struct`
/// * Is not generic
/// * Has a `#[repr(C)]` or `#[repr(transparent)]` attribute
/// * Has `align_of() == 1`
/// * Only has fields whose respective type implement `BytesCast`.
///
/// Failing any of these checks causes a compile-time error.
/// This excludes some types that could implement `BytesCast` without memory safety
/// issue:
///
/// * By choice: disabling field reordering with `repr` is not about memory
/// safety but making memory layout / field offsets predictable.
/// * By necessity: generics would make `align_of` potentially depend on type
/// parameters and not possible to statically check at the struct definition
/// site.
///
/// Finally, mandating `BytesCast` for all fields means they also have `align_of() ==
/// 1` and therefore the struct does not have any padding.
/// This makes memory layout / field offsets easier to reason about.
pub unsafe trait BytesCast: Sized {
/// Interpret the start of the given slice of bytes as reference to this
/// type.
///
/// If the given input is large enough, returns a tuple of the new
/// reference and the remaining of the bytes.
#[inline]
fn from_bytes(bytes: &[u8]) -> Result<(&Self, &[u8]), FromBytesError> {
let expected_len = mem::size_of::<Self>();
remaining_bytes(bytes, expected_len).map(|rest| {
// Safety: this cast and dereference are made sound by the length
// check done in `remaining_bytes` together with the
// invariants of `FromByteSafe`.
let this = unsafe { &*bytes.as_ptr().cast::<Self>() };
(this, rest)
})
}
/// Interpret the start of the given slice of bytes as slice of this type.
///
/// If the given input is large enough, returns a tuple of the new
/// slice and the remaining of the bytes.
#[inline]
fn slice_from_bytes(
bytes: &[u8],
slice_len: usize,
) -> Result<(&[Self], &[u8]), FromBytesError> {
let expected_byte_len =
mem::size_of::<Self>()
.checked_mul(slice_len)
.ok_or(FromBytesError {
input_len: bytes.len(),
expected_len: None,
})?;
remaining_bytes(bytes, expected_byte_len).map(|rest| {
// Safety: this cast and call are made sound by the length check
// done in `remaining_bytes` together with the invariants of
// `FromByteSafe`.
let this = unsafe { slice::from_raw_parts(bytes.as_ptr().cast::<Self>(), slice_len) };
(this, rest)
})
}
}
/// If the given slice is long enough, return the the remaining bytes after the
/// given length.
#[inline]
fn remaining_bytes(bytes: &[u8], expected_byte_len: usize) -> Result<&[u8], FromBytesError> {
bytes.get(expected_byte_len..).ok_or(FromBytesError {
input_len: bytes.len(),
expected_len: Some(expected_byte_len),
})
}
/// The error type for [`BytesCast::from_bytes`] and
/// [`BytesCast::slice_from_bytes`].
pub struct FromBytesError {
expected_len: Option<usize>,
input_len: usize,
}
impl fmt::Display for FromBytesError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(expected_len) = self.expected_len {
write!(
f,
"Expected at least {} bytes, got {}",
expected_len, self.input_len
)
} else {
write!(f, "Expected byte size overflowed in slice_from_bytes")
}
}
}
impl fmt::Debug for FromBytesError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
unsafe impl<T: ?Sized> BytesCast for core::marker::PhantomData<T> {}
unsafe impl BytesCast for () {}
unsafe impl BytesCast for u8 {}
// NOTE: We don’t implement BytesCast for tuples with 2 or more fields
// because they are subject to field reordering.
// Like with default-`repr` structs this is not a memory safety issue but still
// a footgun. Single-field tuples don’t have that problem but are much less
// useful in the first place.
// FIXME: Use const generics when we require Rust 1.51+
macro_rules! array_impls {
($($N: expr)+) => {
$(
unsafe impl<T: BytesCast> BytesCast for [T; $N] {}
)+
};
}
array_impls!(
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
);
//! Integer and float types without alignment requirement, for each endianness.
//!
//! They implement `BytesCast` as well as standard convertion traits
//! to and from the corresponding primitive integer type.
//!
//! # The `u8` type
//!
//! There is no need for types such as `U8Be`
//! since `u8` already does not have endianness or alignement requirements.
//! Use `u8` directly.
use super::BytesCast;
macro_rules! unaligned {
($Int: ident $BeStruct: ident $LeStruct: ident $NeStruct: ident) => {
unaligned!(@doc $Int $BeStruct from_be_bytes to_be_bytes "Big", "");
unaligned!(@doc $Int $LeStruct from_le_bytes to_le_bytes "Little", "");
unaligned!(@doc $Int $NeStruct from_ne_bytes to_ne_bytes "CPU-native",
"\n\nThe byte order depends on the target CPU architecture.");
};
// This is a separate macro invocation to work around
// https://github.com/rust-lang/rust/issues/52607
(
@doc $Int: ident $Struct: ident
$from_bytes: ident $to_bytes: ident
$endian: expr, $extra_doc: expr
) => {
unaligned!(
@def $Int $Struct $from_bytes $to_bytes concat!(
$endian, "-endian `", stringify!($Int), "`, \
without alignment requirement.\n\
\n\
Implements the [`BytesCast`] trait to reinterpret `&[u8]` byte slices, \
and the [`From`] and [`Into`] traits to convert to and from \
`", stringify!($Int), "`.",
$extra_doc
)
);
};
(
@def $Int: ident $Struct: ident
$from_bytes: ident $to_bytes: ident
$doc: expr
) => {
#[derive(BytesCast)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
#[doc = $doc]
#[repr(transparent)]
pub struct $Struct([u8; ::core::mem::size_of::<$Int>()]);
/// Converts to native-endian. Same as `.into()`, but `.into()` may need a type annotation.
impl $Struct {
#[inline]
pub fn get(self) -> $Int {
self.into()
}
}
/// Converts to native-endian
impl From<$Struct> for $Int {
#[inline]
fn from(value: $Struct) -> Self {
$Int::$from_bytes(value.0)
}
}
/// Converts from native-endian
impl From<$Int> for $Struct {
#[inline]
fn from(value: $Int) -> Self {
Self(value.$to_bytes())
}
}
};
}
unaligned!(u16 U16Be U16Le U16Ne);
unaligned!(u32 U32Be U32Le U32Ne);
unaligned!(u64 U64Be U64Le U64Ne);
unaligned!(u128 U128Be U128Le U128Ne);
unaligned!(i16 I16Be I16Le I16Ne);
unaligned!(i32 I32Be I32Le I32Ne);
unaligned!(i64 I64Be I64Le I64Ne);
unaligned!(i128 I128Be I128Le I128Ne);
unaligned!(f32 F32Be F32Le F32Ne);
unaligned!(f64 F64Be F64Le F64Ne);