| 1 |
// This file is part of ICU4X. For terms of use, please see the file |
| 2 |
// called LICENSE at the top level of the ICU4X source tree |
| 3 |
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). |
| 4 |
|
| 5 |
// https://github.com/unicode-org/icu4x/blob/main/documents/process/boilerplate.md#library-annotations |
| 6 |
#![cfg_attr(not(any(test, doc)), no_std)] |
| 7 |
#![cfg_attr( |
| 8 |
not(test), |
| 9 |
deny( |
| 10 |
clippy::indexing_slicing, |
| 11 |
clippy::unwrap_used, |
| 12 |
clippy::expect_used, |
| 13 |
clippy::panic, |
| 14 |
) |
| 15 |
)] |
| 16 |
// #![warn(missing_docs)] |
| 17 |
|
| 18 |
//! Zero-copy vector abstractions for arbitrary types, backed by byte slices. |
| 19 |
//! |
| 20 |
//! `zerovec` enables a far wider range of types — beyond just `&[u8]` and `&str` — to participate in |
| 21 |
//! zero-copy deserialization from byte slices. It is `serde` compatible and comes equipped with |
| 22 |
//! proc macros |
| 23 |
//! |
| 24 |
//! Clients upgrading to `zerovec` benefit from zero heap allocations when deserializing |
| 25 |
//! read-only data. |
| 26 |
//! |
| 27 |
//! This crate has four main types: |
| 28 |
//! |
| 29 |
//! - [`ZeroVec<'a, T>`] (and [`ZeroSlice<T>`](ZeroSlice)) for fixed-width types like `u32` |
| 30 |
//! - [`VarZeroVec<'a, T>`] (and [`VarZeroSlice<T>`](ZeroSlice)) for variable-width types like `str` |
| 31 |
//! - [`ZeroMap<'a, K, V>`] to map from `K` to `V` |
| 32 |
//! - [`ZeroMap2d<'a, K0, K1, V>`] to map from the pair `(K0, K1)` to `V` |
| 33 |
//! |
| 34 |
//! The first two are intended as close-to-drop-in replacements for `Vec<T>` in Serde structs. The third and fourth are |
| 35 |
//! intended as a replacement for `HashMap` or [`LiteMap`](https://docs.rs/litemap). When used with Serde derives, **be sure to apply |
| 36 |
//! `#[serde(borrow)]` to these types**, same as one would for [`Cow<'a, T>`]. |
| 37 |
//! |
| 38 |
//! [`ZeroVec<'a, T>`], [`VarZeroVec<'a, T>`], [`ZeroMap<'a, K, V>`], and [`ZeroMap2d<'a, K0, K1, V>`] all behave like |
| 39 |
//! [`Cow<'a, T>`] in that they abstract over either borrowed or owned data. When performing deserialization |
| 40 |
//! from human-readable formats (like `json` and `xml`), typically these types will allocate and fully own their data, whereas if deserializing |
| 41 |
//! from binary formats like `bincode` and `postcard`, these types will borrow data directly from the buffer being deserialized from, |
| 42 |
//! avoiding allocations and only performing validity checks. As such, this crate can be pretty fast (see [below](#Performance) for more information) |
| 43 |
//! on deserialization. |
| 44 |
//! |
| 45 |
//! See [the design doc](https://github.com/unicode-org/icu4x/blob/main/utils/zerovec/design_doc.md) for details on how this crate |
| 46 |
//! works under the hood. |
| 47 |
//! |
| 48 |
//! # Cargo features |
| 49 |
//! |
| 50 |
//! This crate has several optional Cargo features: |
| 51 |
//! - `serde`: Allows serializing and deserializing `zerovec`'s abstractions via [`serde`](https://docs.rs/serde) |
| 52 |
//! - `yoke`: Enables implementations of `Yokeable` from the [`yoke`](https://docs.rs/yoke/) crate, which is also useful |
| 53 |
//! in situations involving a lot of zero-copy deserialization. |
| 54 |
//! - `derive`: Makes it easier to use custom types in these collections by providing the [`#[make_ule]`](crate::make_ule) and |
| 55 |
//! [`#[make_varule]`](crate::make_varule) proc macros, which generate appropriate [`ULE`](crate::ule::ULE) and |
| 56 |
//! [`VarULE`](crate::ule::VarULE)-conformant types for a given "normal" type. |
| 57 |
//! - `std`: Enabled `std::Error` implementations for error types. This crate is by default `no_std` with a dependency on `alloc`. |
| 58 |
//! |
| 59 |
//! [`ZeroVec<'a, T>`]: ZeroVec |
| 60 |
//! [`VarZeroVec<'a, T>`]: VarZeroVec |
| 61 |
//! [`ZeroMap<'a, K, V>`]: ZeroMap |
| 62 |
//! [`ZeroMap2d<'a, K0, K1, V>`]: ZeroMap2d |
| 63 |
//! [`Cow<'a, T>`]: alloc::borrow::Cow |
| 64 |
//! |
| 65 |
//! # Examples |
| 66 |
//! |
| 67 |
//! Serialize and deserialize a struct with [`ZeroVec`] and [`VarZeroVec`] with Bincode: |
| 68 |
//! |
| 69 |
//! ``` |
| 70 |
//! # #[cfg(feature = "serde")] { |
| 71 |
//! use zerovec::{VarZeroVec, ZeroVec}; |
| 72 |
//! |
| 73 |
//! // This example requires the "serde" feature |
| 74 |
//! #[derive(serde::Serialize, serde::Deserialize)] |
| 75 |
//! pub struct DataStruct<'data> { |
| 76 |
//! #[serde(borrow)] |
| 77 |
//! nums: ZeroVec<'data, u32>, |
| 78 |
//! #[serde(borrow)] |
| 79 |
//! chars: ZeroVec<'data, char>, |
| 80 |
//! #[serde(borrow)] |
| 81 |
//! strs: VarZeroVec<'data, str>, |
| 82 |
//! } |
| 83 |
//! |
| 84 |
//! let data = DataStruct { |
| 85 |
//! nums: ZeroVec::from_slice_or_alloc(&[211, 281, 421, 461]), |
| 86 |
//! chars: ZeroVec::alloc_from_slice(&['ö', '冇', 'म']), |
| 87 |
//! strs: VarZeroVec::from(&["hello", "world"]), |
| 88 |
//! }; |
| 89 |
//! let bincode_bytes = |
| 90 |
//! bincode::serialize(&data).expect("Serialization should be successful"); |
| 91 |
//! assert_eq!(bincode_bytes.len(), 63); |
| 92 |
//! |
| 93 |
//! let deserialized: DataStruct = bincode::deserialize(&bincode_bytes) |
| 94 |
//! .expect("Deserialization should be successful"); |
| 95 |
//! assert_eq!(deserialized.nums.first(), Some(211)); |
| 96 |
//! assert_eq!(deserialized.chars.get(1), Some('冇')); |
| 97 |
//! assert_eq!(deserialized.strs.get(1), Some("world")); |
| 98 |
//! // The deserialization will not have allocated anything |
| 99 |
//! assert!(!deserialized.nums.is_owned()); |
| 100 |
//! # } // feature = "serde" |
| 101 |
//! ``` |
| 102 |
//! |
| 103 |
//! Use custom types inside of [`ZeroVec`]: |
| 104 |
//! |
| 105 |
//! ```rust |
| 106 |
//! # #[cfg(all(feature = "serde", feature = "derive"))] { |
| 107 |
//! use zerovec::{ZeroVec, VarZeroVec, ZeroMap}; |
| 108 |
//! use std::borrow::Cow; |
| 109 |
//! use zerovec::ule::encode_varule_to_box; |
| 110 |
//! |
| 111 |
//! // custom fixed-size ULE type for ZeroVec |
| 112 |
//! #[zerovec::make_ule(DateULE)] |
| 113 |
//! #[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd, serde::Serialize, serde::Deserialize)] |
| 114 |
//! struct Date { |
| 115 |
//! y: u64, |
| 116 |
//! m: u8, |
| 117 |
//! d: u8 |
| 118 |
//! } |
| 119 |
//! |
| 120 |
//! // custom variable sized VarULE type for VarZeroVec |
| 121 |
//! #[zerovec::make_varule(PersonULE)] |
| 122 |
//! #[zerovec::derive(Serialize, Deserialize)] // add Serde impls to PersonULE |
| 123 |
//! #[derive(Clone, PartialEq, Eq, Ord, PartialOrd, serde::Serialize, serde::Deserialize)] |
| 124 |
//! struct Person<'a> { |
| 125 |
//! birthday: Date, |
| 126 |
//! favorite_character: char, |
| 127 |
//! #[serde(borrow)] |
| 128 |
//! name: Cow<'a, str>, |
| 129 |
//! } |
| 130 |
//! |
| 131 |
//! #[derive(serde::Serialize, serde::Deserialize)] |
| 132 |
//! struct Data<'a> { |
| 133 |
//! #[serde(borrow)] |
| 134 |
//! important_dates: ZeroVec<'a, Date>, |
| 135 |
//! // note: VarZeroVec always must reference the ULE type directly |
| 136 |
//! #[serde(borrow)] |
| 137 |
//! important_people: VarZeroVec<'a, PersonULE>, |
| 138 |
//! #[serde(borrow)] |
| 139 |
//! birthdays_to_people: ZeroMap<'a, Date, PersonULE> |
| 140 |
//! } |
| 141 |
//! |
| 142 |
//! |
| 143 |
//! let person1 = Person { |
| 144 |
//! birthday: Date { y: 1990, m: 9, d: 7}, |
| 145 |
//! favorite_character: 'π', |
| 146 |
//! name: Cow::from("Kate") |
| 147 |
//! }; |
| 148 |
//! let person2 = Person { |
| 149 |
//! birthday: Date { y: 1960, m: 5, d: 25}, |
| 150 |
//! favorite_character: '冇', |
| 151 |
//! name: Cow::from("Jesse") |
| 152 |
//! }; |
| 153 |
//! |
| 154 |
//! let important_dates = ZeroVec::alloc_from_slice(&[Date { y: 1943, m: 3, d: 20}, Date { y: 1976, m: 8, d: 2}, Date { y: 1998, m: 2, d: 15}]); |
| 155 |
//! let important_people = VarZeroVec::from(&[&person1, &person2]); |
| 156 |
//! let mut birthdays_to_people: ZeroMap<Date, PersonULE> = ZeroMap::new(); |
| 157 |
//! // `.insert_var_v()` is slightly more convenient over `.insert()` for custom ULE types |
| 158 |
//! birthdays_to_people.insert_var_v(&person1.birthday, &person1); |
| 159 |
//! birthdays_to_people.insert_var_v(&person2.birthday, &person2); |
| 160 |
//! |
| 161 |
//! let data = Data { important_dates, important_people, birthdays_to_people }; |
| 162 |
//! |
| 163 |
//! let bincode_bytes = bincode::serialize(&data) |
| 164 |
//! .expect("Serialization should be successful"); |
| 165 |
//! assert_eq!(bincode_bytes.len(), 160); |
| 166 |
//! |
| 167 |
//! let deserialized: Data = bincode::deserialize(&bincode_bytes) |
| 168 |
//! .expect("Deserialization should be successful"); |
| 169 |
//! |
| 170 |
//! assert_eq!(deserialized.important_dates.get(0).unwrap().y, 1943); |
| 171 |
//! assert_eq!(&deserialized.important_people.get(1).unwrap().name, "Jesse"); |
| 172 |
//! assert_eq!(&deserialized.important_people.get(0).unwrap().name, "Kate"); |
| 173 |
//! assert_eq!(&deserialized.birthdays_to_people.get(&person1.birthday).unwrap().name, "Kate"); |
| 174 |
//! |
| 175 |
//! } // feature = serde and derive |
| 176 |
//! ``` |
| 177 |
//! |
| 178 |
//! # Performance |
| 179 |
//! |
| 180 |
//! `zerovec` is designed for fast deserialization from byte buffers with zero memory allocations |
| 181 |
//! while minimizing performance regressions for common vector operations. |
| 182 |
//! |
| 183 |
//! Benchmark results on `x86_64`: |
| 184 |
//! |
| 185 |
//! | Operation | `Vec<T>` | `zerovec` | |
| 186 |
//! |---|---|---| |
| 187 |
//! | Deserialize vec of 100 `u32` | 233.18 ns | 14.120 ns | |
| 188 |
//! | Compute sum of vec of 100 `u32` (read every element) | 8.7472 ns | 10.775 ns | |
| 189 |
//! | Binary search vec of 1000 `u32` 50 times | 442.80 ns | 472.51 ns | |
| 190 |
//! | Deserialize vec of 100 strings | 7.3740 μs\* | 1.4495 μs | |
| 191 |
//! | Count chars in vec of 100 strings (read every element) | 747.50 ns | 955.28 ns | |
| 192 |
//! | Binary search vec of 500 strings 10 times | 466.09 ns | 790.33 ns | |
| 193 |
//! |
| 194 |
//! \* *This result is reported for `Vec<String>`. However, Serde also supports deserializing to the partially-zero-copy `Vec<&str>`; this gives 1.8420 μs, much faster than `Vec<String>` but a bit slower than `zerovec`.* |
| 195 |
//! |
| 196 |
//! | Operation | `HashMap<K,V>` | `LiteMap<K,V>` | `ZeroMap<K,V>` | |
| 197 |
//! |---|---|---|---| |
| 198 |
//! | Deserialize a small map | 2.72 μs | 1.28 μs | 480 ns | |
| 199 |
//! | Deserialize a large map | 50.5 ms | 18.3 ms | 3.74 ms | |
| 200 |
//! | Look up from a small deserialized map | 49 ns | 42 ns | 54 ns | |
| 201 |
//! | Look up from a large deserialized map | 51 ns | 155 ns | 213 ns | |
| 202 |
//! |
| 203 |
//! Small = 16 elements, large = 131,072 elements. Maps contain `<String, String>`. |
| 204 |
//! |
| 205 |
//! The benches used to generate the above table can be found in the `benches` directory in the project repository. |
| 206 |
//! `zeromap` benches are named by convention, e.g. `zeromap/deserialize/small`, `zeromap/lookup/large`. The type |
| 207 |
//! is appended for baseline comparisons, e.g. `zeromap/lookup/small/hashmap`. |
| 208 |
|
| 209 |
// this crate does a lot of nuanced lifetime manipulation, being explicit |
| 210 |
// is better here. |
| 211 |
#![allow(clippy::needless_lifetimes)] |
| 212 |
|
| 213 |
#[cfg(feature = "alloc")] |
| 214 |
extern crate alloc; |
| 215 |
|
| 216 |
mod cow; |
| 217 |
#[cfg(feature = "hashmap")] |
| 218 |
pub mod hashmap; |
| 219 |
#[cfg(feature = "alloc")] |
| 220 |
mod map; |
| 221 |
#[cfg(feature = "alloc")] |
| 222 |
mod map2d; |
| 223 |
#[cfg(test)] |
| 224 |
pub mod samples; |
| 225 |
#[cfg(feature = "schemars")] |
| 226 |
mod schemars; |
| 227 |
mod varzerovec; |
| 228 |
mod zerovec; |
| 229 |
|
| 230 |
// This must be after `mod zerovec` for some impls on `ZeroSlice<RawBytesULE>` |
| 231 |
// to show up in the right spot in the docs |
| 232 |
pub mod ule; |
| 233 |
#[cfg(feature = "yoke")] |
| 234 |
mod yoke_impls; |
| 235 |
mod zerofrom_impls; |
| 236 |
|
| 237 |
pub use crate::cow::VarZeroCow; |
| 238 |
#[cfg(feature = "hashmap")] |
| 239 |
pub use crate::hashmap::ZeroHashMap; |
| 240 |
#[cfg(feature = "alloc")] |
| 241 |
pub use crate::map::map::ZeroMap; |
| 242 |
#[cfg(feature = "alloc")] |
| 243 |
pub use crate::map2d::map::ZeroMap2d; |
| 244 |
pub use crate::varzerovec::{slice::VarZeroSlice, vec::VarZeroVec}; |
| 245 |
pub use crate::zerovec::{ZeroSlice, ZeroVec}; |
| 246 |
|
| 247 |
#[doc(hidden)] // macro use |
| 248 |
pub mod __zerovec_internal_reexport { |
| 249 |
pub use zerofrom::ZeroFrom; |
| 250 |
|
| 251 |
#[cfg(feature = "alloc")] |
| 252 |
pub use alloc::borrow; |
| 253 |
#[cfg(feature = "alloc")] |
| 254 |
pub use alloc::boxed; |
| 255 |
|
| 256 |
#[cfg(feature = "serde")] |
| 257 |
pub use serde; |
| 258 |
} |
| 259 |
|
| 260 |
#[cfg(feature = "alloc")] |
| 261 |
pub mod maps { |
| 262 |
//! This module contains additional utility types and traits for working with |
| 263 |
//! [`ZeroMap`] and [`ZeroMap2d`]. See their docs for more details on the general purpose |
| 264 |
//! of these types. |
| 265 |
//! |
| 266 |
//! [`ZeroMapBorrowed`] and [`ZeroMap2dBorrowed`] are versions of [`ZeroMap`] and [`ZeroMap2d`] |
| 267 |
//! that can be used when you wish to guarantee that the map data is always borrowed, leading to |
| 268 |
//! relaxed lifetime constraints. |
| 269 |
//! |
| 270 |
//! The [`ZeroMapKV`] trait is required to be implemented on any type that needs to be used |
| 271 |
//! within a map type. [`ZeroVecLike`] and [`MutableZeroVecLike`] are traits used in the |
| 272 |
//! internal workings of the map types, and should typically not be used or implemented by |
| 273 |
//! users of this crate. |
| 274 |
#[doc(no_inline)] |
| 275 |
pub use crate::map::ZeroMap; |
| 276 |
pub use crate::map::ZeroMapBorrowed; |
| 277 |
|
| 278 |
#[doc(no_inline)] |
| 279 |
pub use crate::map2d::ZeroMap2d; |
| 280 |
pub use crate::map2d::ZeroMap2dBorrowed; |
| 281 |
|
| 282 |
pub use crate::map::{MutableZeroVecLike, ZeroMapKV, ZeroVecLike}; |
| 283 |
|
| 284 |
pub use crate::map2d::ZeroMap2dCursor; |
| 285 |
} |
| 286 |
|
| 287 |
pub mod vecs { |
| 288 |
//! This module contains additional utility types for working with |
| 289 |
//! [`ZeroVec`] and [`VarZeroVec`]. See their docs for more details on the general purpose |
| 290 |
//! of these types. |
| 291 |
//! |
| 292 |
//! [`ZeroSlice`] and [`VarZeroSlice`] provide slice-like versions of the vector types |
| 293 |
//! for use behind references and in custom ULE types. |
| 294 |
//! |
| 295 |
//! [`VarZeroVecOwned`] is a special owned/mutable version of [`VarZeroVec`], allowing |
| 296 |
//! direct manipulation of the backing buffer. |
| 297 |
|
| 298 |
#[doc(no_inline)] |
| 299 |
pub use crate::zerovec::{ZeroSlice, ZeroVec}; |
| 300 |
|
| 301 |
pub use crate::zerovec::ZeroSliceIter; |
| 302 |
|
| 303 |
#[doc(no_inline)] |
| 304 |
pub use crate::varzerovec::{VarZeroSlice, VarZeroVec}; |
| 305 |
|
| 306 |
#[cfg(feature = "alloc")] |
| 307 |
pub use crate::varzerovec::VarZeroVecOwned; |
| 308 |
pub use crate::varzerovec::{Index16, Index32, Index8, VarZeroSliceIter, VarZeroVecFormat}; |
| 309 |
|
| 310 |
pub type VarZeroVec16<'a, T> = VarZeroVec<'a, T, Index16>; |
| 311 |
pub type VarZeroVec32<'a, T> = VarZeroVec<'a, T, Index32>; |
| 312 |
pub type VarZeroSlice16<T> = VarZeroSlice<T, Index16>; |
| 313 |
pub type VarZeroSlice32<T> = VarZeroSlice<T, Index32>; |
| 314 |
} |
| 315 |
|
| 316 |
// Proc macro reexports |
| 317 |
// |
| 318 |
// These exist so that our docs can use intra-doc links. |
| 319 |
// Due to quirks of how rustdoc does documentation on reexports, these must be in this module and not reexported from |
| 320 |
// a submodule |
| 321 |
|
| 322 |
/// Generate a corresponding [`ULE`] type and the relevant [`AsULE`] implementations for this type |
| 323 |
/// |
| 324 |
/// This can be attached to structs containing only [`AsULE`] types, or C-like enums that have `#[repr(u8)]` |
| 325 |
/// and all explicit discriminants. |
| 326 |
/// |
| 327 |
/// The type must be [`Copy`], [`PartialEq`], and [`Eq`]. |
| 328 |
/// |
| 329 |
/// `#[make_ule]` will automatically derive the following traits on the [`ULE`] type: |
| 330 |
/// |
| 331 |
/// - [`Ord`] and [`PartialOrd`] |
| 332 |
/// - [`ZeroMapKV`] |
| 333 |
/// |
| 334 |
/// To disable one of the automatic derives, use `#[zerovec::skip_derive(...)]` like so: `#[zerovec::skip_derive(ZeroMapKV)]`. |
| 335 |
/// `Ord` and `PartialOrd` are implemented as a unit and can only be disabled as a group with `#[zerovec::skip_derive(Ord)]`. |
| 336 |
/// |
| 337 |
/// The following traits are available to derive, but not automatic: |
| 338 |
/// |
| 339 |
/// - [`Debug`] |
| 340 |
/// |
| 341 |
/// To enable one of these additional derives, use `#[zerovec::derive(...)]` like so: `#[zerovec::derive(Debug)]`. |
| 342 |
/// |
| 343 |
/// In most cases these derives will defer to the impl of the same trait on the current type, so such impls must exist. |
| 344 |
/// |
| 345 |
/// For enums, this attribute will generate a crate-public `fn new_from_u8(value: u8) -> Option<Self>` |
| 346 |
/// method on the main type that allows one to construct the value from a u8. If this method is desired |
| 347 |
/// to be more public, it should be wrapped. |
| 348 |
/// |
| 349 |
/// [`ULE`]: ule::ULE |
| 350 |
/// [`AsULE`]: ule::AsULE |
| 351 |
/// [`ZeroMapKV`]: maps::ZeroMapKV |
| 352 |
/// |
| 353 |
/// # Example |
| 354 |
/// |
| 355 |
/// ```rust |
| 356 |
/// use zerovec::ZeroVec; |
| 357 |
/// |
| 358 |
/// #[zerovec::make_ule(DateULE)] |
| 359 |
/// #[derive( |
| 360 |
/// Copy, |
| 361 |
/// Clone, |
| 362 |
/// PartialEq, |
| 363 |
/// Eq, |
| 364 |
/// Ord, |
| 365 |
/// PartialOrd, |
| 366 |
/// serde::Serialize, |
| 367 |
/// serde::Deserialize, |
| 368 |
/// )] |
| 369 |
/// struct Date { |
| 370 |
/// y: u64, |
| 371 |
/// m: u8, |
| 372 |
/// d: u8, |
| 373 |
/// } |
| 374 |
/// |
| 375 |
/// #[derive(serde::Serialize, serde::Deserialize)] |
| 376 |
/// struct Dates<'a> { |
| 377 |
/// #[serde(borrow)] |
| 378 |
/// dates: ZeroVec<'a, Date>, |
| 379 |
/// } |
| 380 |
/// |
| 381 |
/// let dates = Dates { |
| 382 |
/// dates: ZeroVec::alloc_from_slice(&[ |
| 383 |
/// Date { |
| 384 |
/// y: 1985, |
| 385 |
/// m: 9, |
| 386 |
/// d: 3, |
| 387 |
/// }, |
| 388 |
/// Date { |
| 389 |
/// y: 1970, |
| 390 |
/// m: 2, |
| 391 |
/// d: 20, |
| 392 |
/// }, |
| 393 |
/// Date { |
| 394 |
/// y: 1990, |
| 395 |
/// m: 6, |
| 396 |
/// d: 13, |
| 397 |
/// }, |
| 398 |
/// ]), |
| 399 |
/// }; |
| 400 |
/// |
| 401 |
/// let bincode_bytes = |
| 402 |
/// bincode::serialize(&dates).expect("Serialization should be successful"); |
| 403 |
/// |
| 404 |
/// // Will deserialize without allocations |
| 405 |
/// let deserialized: Dates = bincode::deserialize(&bincode_bytes) |
| 406 |
/// .expect("Deserialization should be successful"); |
| 407 |
/// |
| 408 |
/// assert_eq!(deserialized.dates.get(1).unwrap().y, 1970); |
| 409 |
/// assert_eq!(deserialized.dates.get(2).unwrap().d, 13); |
| 410 |
/// ``` |
| 411 |
#[cfg(feature = "derive")] |
| 412 |
pub use zerovec_derive::make_ule; |
| 413 |
|
| 414 |
/// Generate a corresponding [`VarULE`] type and the relevant [`EncodeAsVarULE`]/[`zerofrom::ZeroFrom`] |
| 415 |
/// implementations for this type |
| 416 |
/// |
| 417 |
/// This can be attached to structs containing only [`AsULE`] types with the last fields being |
| 418 |
/// [`Cow<'a, str>`](alloc::borrow::Cow), [`ZeroSlice`], or [`VarZeroSlice`]. If there is more than one such field, it will be represented |
| 419 |
/// using [`MultiFieldsULE`](crate::ule::MultiFieldsULE) and getters will be generated. Other [`VarULE`] fields will be detected if they are |
| 420 |
/// tagged with `#[zerovec::varule(NameOfVarULETy)]`. |
| 421 |
/// |
| 422 |
/// The type must be [`PartialEq`] and [`Eq`]. |
| 423 |
/// |
| 424 |
/// [`EncodeAsVarULE`] and [`zerofrom::ZeroFrom`] are useful for avoiding the need to deal with |
| 425 |
/// the [`VarULE`] type directly. In particular, it is recommended to use [`zerofrom::ZeroFrom`] |
| 426 |
/// to convert the [`VarULE`] type back to this type in a cheap, zero-copy way (see the example below |
| 427 |
/// for more details). |
| 428 |
/// |
| 429 |
/// `#[make_varule]` will automatically derive the following traits on the [`VarULE`] type: |
| 430 |
/// |
| 431 |
/// - [`Ord`] and [`PartialOrd`] |
| 432 |
/// - [`ZeroMapKV`] |
| 433 |
/// - [`alloc::borrow::ToOwned`] |
| 434 |
/// |
| 435 |
/// To disable one of the automatic derives, use `#[zerovec::skip_derive(...)]` like so: `#[zerovec::skip_derive(ZeroMapKV)]`. |
| 436 |
/// `Ord` and `PartialOrd` are implemented as a unit and can only be disabled as a group with `#[zerovec::skip_derive(Ord)]`. |
| 437 |
/// |
| 438 |
/// The following traits are available to derive, but not automatic: |
| 439 |
/// |
| 440 |
/// - [`Debug`] |
| 441 |
/// - [`Serialize`](serde::Serialize) |
| 442 |
/// - [`Deserialize`](serde::Deserialize) |
| 443 |
/// |
| 444 |
/// To enable one of these additional derives, use `#[zerovec::derive(...)]` like so: `#[zerovec::derive(Debug)]`. |
| 445 |
/// |
| 446 |
/// In most cases these derives will defer to the impl of the same trait on the current type, so such impls must exist. |
| 447 |
/// |
| 448 |
/// This implementation will also by default autogenerate [`Ord`] and [`PartialOrd`] on the [`VarULE`] type based on |
| 449 |
/// the implementation on `Self`. You can opt out of this with `#[zerovec::skip_derive(Ord)]` |
| 450 |
/// |
| 451 |
/// Note that this implementation will autogenerate [`EncodeAsVarULE`] impls for _both_ `Self` and `&Self` |
| 452 |
/// for convenience. This allows for a little more flexibility encoding slices. |
| 453 |
/// |
| 454 |
/// In case there are multiple [`VarULE`] (i.e., variable-sized) fields, this macro will produce private fields that |
| 455 |
/// appropriately pack the data together, with the packing format by default being [`crate::vecs::Index16`], but can be |
| 456 |
/// overridden with `#[zerovec::format(zerovec::vecs::Index8)]`. |
| 457 |
/// |
| 458 |
/// [`EncodeAsVarULE`]: ule::EncodeAsVarULE |
| 459 |
/// [`VarULE`]: ule::VarULE |
| 460 |
/// [`ULE`]: ule::ULE |
| 461 |
/// [`AsULE`]: ule::AsULE |
| 462 |
/// [`ZeroMapKV`]: maps::ZeroMapKV |
| 463 |
/// |
| 464 |
/// # Example |
| 465 |
/// |
| 466 |
/// ```rust |
| 467 |
/// use std::borrow::Cow; |
| 468 |
/// use zerofrom::ZeroFrom; |
| 469 |
/// use zerovec::ule::encode_varule_to_box; |
| 470 |
/// use zerovec::{VarZeroVec, ZeroMap, ZeroVec}; |
| 471 |
/// |
| 472 |
/// // custom fixed-size ULE type for ZeroVec |
| 473 |
/// #[zerovec::make_ule(DateULE)] |
| 474 |
/// #[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd, serde::Serialize, serde::Deserialize)] |
| 475 |
/// struct Date { |
| 476 |
/// y: u64, |
| 477 |
/// m: u8, |
| 478 |
/// d: u8, |
| 479 |
/// } |
| 480 |
/// |
| 481 |
/// // custom variable sized VarULE type for VarZeroVec |
| 482 |
/// #[zerovec::make_varule(PersonULE)] |
| 483 |
/// #[zerovec::derive(Serialize, Deserialize)] |
| 484 |
/// #[derive(Clone, PartialEq, Eq, Ord, PartialOrd, serde::Serialize, serde::Deserialize)] |
| 485 |
/// struct Person<'a> { |
| 486 |
/// birthday: Date, |
| 487 |
/// favorite_character: char, |
| 488 |
/// #[serde(borrow)] |
| 489 |
/// name: Cow<'a, str>, |
| 490 |
/// } |
| 491 |
/// |
| 492 |
/// #[derive(serde::Serialize, serde::Deserialize)] |
| 493 |
/// struct Data<'a> { |
| 494 |
/// // note: VarZeroVec always must reference the ULE type directly |
| 495 |
/// #[serde(borrow)] |
| 496 |
/// important_people: VarZeroVec<'a, PersonULE>, |
| 497 |
/// } |
| 498 |
/// |
| 499 |
/// let person1 = Person { |
| 500 |
/// birthday: Date { |
| 501 |
/// y: 1990, |
| 502 |
/// m: 9, |
| 503 |
/// d: 7, |
| 504 |
/// }, |
| 505 |
/// favorite_character: 'π', |
| 506 |
/// name: Cow::from("Kate"), |
| 507 |
/// }; |
| 508 |
/// let person2 = Person { |
| 509 |
/// birthday: Date { |
| 510 |
/// y: 1960, |
| 511 |
/// m: 5, |
| 512 |
/// d: 25, |
| 513 |
/// }, |
| 514 |
/// favorite_character: '冇', |
| 515 |
/// name: Cow::from("Jesse"), |
| 516 |
/// }; |
| 517 |
/// |
| 518 |
/// let important_people = VarZeroVec::from(&[person1, person2]); |
| 519 |
/// let data = Data { important_people }; |
| 520 |
/// |
| 521 |
/// let bincode_bytes = bincode::serialize(&data).expect("Serialization should be successful"); |
| 522 |
/// |
| 523 |
/// // Will deserialize without allocations |
| 524 |
/// let deserialized: Data = |
| 525 |
/// bincode::deserialize(&bincode_bytes).expect("Deserialization should be successful"); |
| 526 |
/// |
| 527 |
/// assert_eq!(&deserialized.important_people.get(1).unwrap().name, "Jesse"); |
| 528 |
/// assert_eq!(&deserialized.important_people.get(0).unwrap().name, "Kate"); |
| 529 |
/// |
| 530 |
/// // Since VarZeroVec produces PersonULE types, it's convenient to use ZeroFrom |
| 531 |
/// // to recoup Person values in a zero-copy way |
| 532 |
/// let person_converted: Person = |
| 533 |
/// ZeroFrom::zero_from(deserialized.important_people.get(1).unwrap()); |
| 534 |
/// assert_eq!(person_converted.name, "Jesse"); |
| 535 |
/// assert_eq!(person_converted.birthday.y, 1960); |
| 536 |
/// ``` |
| 537 |
#[cfg(feature = "derive")] |
| 538 |
pub use zerovec_derive::make_varule; |
| 539 |
|
| 540 |
#[cfg(test)] |
| 541 |
// Expected sizes are based on a 64-bit architecture |
| 542 |
#[cfg(target_pointer_width = "64")] |
| 543 |
mod tests { |
| 544 |
use super::*; |
| 545 |
|
| 546 |
/// Checks that the size of the type is one of the given sizes. |
| 547 |
/// The size might differ across Rust versions or channels. |
| 548 |
macro_rules! check_size_of { |
| 549 |
($sizes:pat, $type:path) => { |
| 550 |
assert!( |
| 551 |
matches!(size_of::<$type>(), $sizes), |
| 552 |
concat!(stringify!($type), " is of size {}"), |
| 553 |
size_of::<$type>() |
| 554 |
); |
| 555 |
}; |
| 556 |
} |
| 557 |
|
| 558 |
#[test] |
| 559 |
fn check_sizes() { |
| 560 |
check_size_of!(24, ZeroVec<u8>); |
| 561 |
check_size_of!(24, ZeroVec<u32>); |
| 562 |
check_size_of!(32 | 24, VarZeroVec<[u8]>); |
| 563 |
check_size_of!(32 | 24, VarZeroVec<str>); |
| 564 |
check_size_of!(48, ZeroMap<u32, u32>); |
| 565 |
check_size_of!(56 | 48, ZeroMap<u32, str>); |
| 566 |
check_size_of!(56 | 48, ZeroMap<str, u32>); |
| 567 |
check_size_of!(64 | 48, ZeroMap<str, str>); |
| 568 |
check_size_of!(120 | 96, ZeroMap2d<str, str, str>); |
| 569 |
|
| 570 |
check_size_of!(24, Option<ZeroVec<u8>>); |
| 571 |
check_size_of!(32 | 24, Option<VarZeroVec<str>>); |
| 572 |
check_size_of!(64 | 56 | 48, Option<ZeroMap<str, str>>); |
| 573 |
check_size_of!(120 | 104 | 96, Option<ZeroMap2d<str, str, str>>); |
| 574 |
} |
| 575 |
|
| 576 |
#[test] |
| 577 |
fn test_miri_repro_eyepatch_hack_truncate() { |
| 578 |
let slice: &[u16] = &[1, 2, 3, 4]; |
| 579 |
let zv: ZeroVec<u16> = ZeroVec::try_from_slice(slice).unwrap(); |
| 580 |
let _truncated = zv.truncated(2); |
| 581 |
} |
| 582 |
|
| 583 |
#[test] |
| 584 |
fn test_miri_repro_encode_varule_to_box() { |
| 585 |
let str_slice: &str = "hello world"; |
| 586 |
let _boxed: Box<str> = ule::encode_varule_to_box(str_slice); |
| 587 |
} |
| 588 |
|
| 589 |
#[test] |
| 590 |
fn test_miri_repro_varzerocow_new_owned() { |
| 591 |
let boxed_str: Box<str> = Box::from("hello world"); |
| 592 |
let _cow: VarZeroCow<str> = VarZeroCow::new_owned(boxed_str); |
| 593 |
} |
| 594 |
} |