Skip to content

Commit 331044e

Browse files
Merge pull request #11 from triblespace/codex/document-crate
Improve crate documentation
2 parents 5450c98 + 88a4505 commit 331044e

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,6 @@
33
## Unreleased
44
- limit Kani loop unwind by default and set per-harness bounds
55
- increase unwind for prefix/suffix overflow proofs
6+
- move weak reference and downcasting examples into module docs
7+
- expand module introduction describing use cases
8+
- document rationale for separating `ByteSource` and `ByteOwner`

src/bytes.rs

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,52 @@
44
*
55
* This source code is licensed under the MIT license found in the
66
* 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+
//! ```
853
954
use std::any::Any;
1055
use std::ascii::escape_default;

0 commit comments

Comments
 (0)