ecow/lib.rs
1/*!
2Compact, clone-on-write vector and string.
3
4## Types
5- An [`EcoVec`] is a reference-counted clone-on-write vector. It takes up two
6 words of space (= 2 usize) and has the same memory layout as a `&[T]` slice.
7 Within its allocation, it stores a reference count, its capacity and its
8 elements.
9
10- An [`EcoString`] is a reference-counted clone-on-write string with inline
11 storage. It takes up 16 bytes of space. It has 15 bytes of inline storage and
12 starting from 16 bytes it becomes an [`EcoVec<u8>`].
13
14## Example
15```
16// This is stored inline.
17let small = ecow::EcoString::from("Welcome");
18
19// This spills to the heap, but only once: `big` and `third` share the
20// same underlying allocation. Vectors and spilled strings are only
21// really cloned upon mutation.
22let big = small + " to earth! 🌱";
23let mut third = big.clone();
24
25// This allocates again to mutate `third` without affecting `big`.
26assert_eq!(third.pop(), Some('🌱'));
27assert_eq!(third, "Welcome to earth! ");
28```
29
30## Why should I use this instead of ...
31
32| Type | Details |
33|:----------------------------------|:--------|
34| [`Vec<T>`]/ [`String`] | Normal vectors are a great general purpose data structure. But they have a quite big footprint (3 machine words) and are expensive to clone. The [`EcoVec`] has a bit of overhead for mutation, but is cheap to clone and only takes two words. |
35| [`Arc<Vec<T>>`] / [`Arc<String>`] | These require two allocations instead of one and are less convenient to mutate. |
36| [`Arc<[T]>`] / [`Arc<str>`] | While these require only one allocation, they aren't mutable. |
37| Small vector | Different trade-off. Great when there are few, small `T`s, but expensive to clone when spilled to the heap. |
38| Small string | The [`EcoString`] combines different small string qualities into a very practical package: It has inline storage, a smaller footprint than a normal [`String`][string], is efficient to clone even when spilled, and at the same time mutable. |
39*/
40
41#![cfg_attr(not(feature = "std"), no_std)]
42#![deny(missing_docs)]
43// See https://github.com/tokio-rs/loom/issues/352
44#![allow(unknown_lints, unexpected_cfgs)]
45
46extern crate alloc;
47
48pub mod string;
49pub mod vec;
50
51mod dynamic;
52
53pub use self::string::EcoString;
54pub use self::vec::EcoVec;
55
56#[cfg(doc)]
57use alloc::{string::String, sync::Arc, vec::Vec};
58
59// Run doctests on the README too
60#[doc = include_str!("../README.md")]
61#[cfg(doctest)]
62pub struct ReadmeDoctests;
63
64/// Loom needs its own synchronization types to be used in order to work
65mod sync {
66 /// Atomics stub
67 pub mod atomic {
68 #[cfg(not(loom))]
69 pub use core::sync::atomic::*;
70
71 #[cfg(loom)]
72 pub use loom::sync::atomic::*;
73 }
74}