|
4 | 4 | * |
5 | 5 | * This source code is licensed under the MIT license found in the |
6 | 6 | * LICENSE file in the root directory of this source tree. |
7 | | - */ |
| 7 | +*/ |
| 8 | + |
| 9 | +//! Core byte container types. |
| 10 | +//! |
| 11 | +//! [`Bytes`] provides cheap, zero-copy access to immutable bytes from a |
| 12 | +//! variety of sources. Implement the [`ByteSource`] trait for your type to |
| 13 | +//! integrate it with the container. Each `Bytes` keeps its backing storage |
| 14 | +//! alive through a reference-counted [`ByteOwner`], ensuring the data stays |
| 15 | +//! valid for as long as needed. |
| 16 | +//! |
| 17 | +//! `Bytes` decouples data access from ownership so that callers can obtain a |
| 18 | +//! slice and then release any external locks. After reading the bytes from a |
| 19 | +//! [`ByteSource`], convert it into its [`ByteOwner`] to keep the data alive |
| 20 | +//! without retaining the original guard. This is especially useful for Python |
| 21 | +//! integration where acquiring the raw pointer to a `bytes` object requires |
| 22 | +//! holding the GIL, but once the slice is acquired, only the owner needs to be |
| 23 | +//! kept alive. |
| 24 | +//! |
| 25 | +//! ## Weak references |
| 26 | +//! |
| 27 | +//! A `Bytes` can be downgraded to a [`WeakBytes`] to hold a non-owning reference |
| 28 | +//! without keeping the underlying data alive: |
| 29 | +//! |
| 30 | +//! ``` |
| 31 | +//! use anybytes::Bytes; |
| 32 | +//! |
| 33 | +//! let bytes = Bytes::from(vec![1u8, 2, 3]); |
| 34 | +//! let weak = bytes.downgrade(); |
| 35 | +//! assert!(weak.upgrade().is_some()); |
| 36 | +//! drop(bytes); |
| 37 | +//! assert!(weak.upgrade().is_none()); |
| 38 | +//! ``` |
| 39 | +//! |
| 40 | +//! ## Downcasting owners |
| 41 | +//! |
| 42 | +//! When the backing type is known, [`Bytes::downcast_to_owner`] retrieves it |
| 43 | +//! again: |
| 44 | +//! |
| 45 | +//! ``` |
| 46 | +//! use anybytes::Bytes; |
| 47 | +//! use std::sync::Arc; |
| 48 | +//! |
| 49 | +//! let bytes = Bytes::from_source(vec![1u8, 2, 3, 4]); |
| 50 | +//! let owner: Arc<Vec<u8>> = bytes.downcast_to_owner().unwrap(); |
| 51 | +//! assert_eq!(&*owner, &[1, 2, 3, 4]); |
| 52 | +//! ``` |
8 | 53 |
|
9 | 54 | use std::any::Any; |
10 | 55 | use std::ascii::escape_default; |
|
0 commit comments