#string #cow #sso #vector #memory-layout

no-std ecow

Compact, clone-on-write vector and string

7 releases

0.2.3 Oct 30, 2024
0.2.2 Mar 23, 2024
0.2.0 Oct 9, 2023
0.1.2 Aug 19, 2023
0.1.0 Mar 1, 2023

#61 in Data structures

Download history 2846/week @ 2024-08-21 2732/week @ 2024-08-28 3082/week @ 2024-09-04 3061/week @ 2024-09-11 3335/week @ 2024-09-18 3406/week @ 2024-09-25 3071/week @ 2024-10-02 3458/week @ 2024-10-09 4961/week @ 2024-10-16 3607/week @ 2024-10-23 4760/week @ 2024-10-30 3561/week @ 2024-11-06 5264/week @ 2024-11-13 6490/week @ 2024-11-20 6934/week @ 2024-11-27 4545/week @ 2024-12-04

23,881 downloads per month
Used in 75 crates (25 directly)

MIT/Apache

74KB
1.5K SLoC

ecow

Crates.io Documentation

Compact, clone-on-write vector and string.

Types

  • An EcoVec is a reference-counted clone-on-write vector. It takes up two words of space (= 2 usize) and has the same memory layout as a &[T] slice. Within its allocation, it stores a reference count, its capacity and its elements.

  • An EcoString is a reference-counted clone-on-write string with inline storage. It takes up 16 bytes of space. It has 15 bytes of inline storage and starting from 16 bytes it becomes an EcoVec<u8>.

Example

// This is stored inline.
let small = ecow::EcoString::from("Welcome");

// This spills to the heap, but only once: `big` and `third` share the
// same underlying allocation. Vectors and spilled strings are only
// really cloned upon mutation.
let big = small + " to earth! 🌱";
let mut third = big.clone();

// This allocates again to mutate `third` without affecting `big`.
assert_eq!(third.pop(), Some('🌱'));
assert_eq!(third, "Welcome to earth! ");

Why should I use this instead of ...

Type Details
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.
Arc<Vec<T>> / Arc<String> These require two allocations instead of one and are less convenient to mutate.
Arc<[T]> / Arc<str> While these require only one allocation, they aren't mutable.
Small vector Different trade-off. Great when there are few, small Ts, but expensive to clone when spilled to the heap.
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, is efficient to clone even when spilled, and at the same time mutable.

License

This crate is dual-licensed under the MIT and Apache 2.0 licenses.

Dependencies

~0–24MB
~334K SLoC