ref_str
ref_str provides compact string types for no_std Rust.
Install
[]
= "0.1"
With serde support:
[]
= { = "0.1", = ["serde"] }
With serde + std support:
[]
= { = "0.1", = ["serde", "std"] }
With arbitrary support:
[]
= { = "0.1", = ["arbitrary"] }
Overview
LocalRefStr<'a> and RefStr<'a> store either a borrowed &'a str or an owned shared string, while keeping the representation compact and clone-friendly.
Why Two Types
LocalRefStr<'a>is optimized for single-threaded code and usesRc<str>when it needs shared ownership.RefStr<'a>is the thread-safe counterpart and usesArc<str>when it needs shared ownership.- Both types expose the same high-level API, so you can switch between them without changing your call sites much.
API
| Item | Purpose |
|---|---|
LocalRefStr<'a> |
Compact string backed by Rc<str> when shared |
RefStr<'a> |
Compact string backed by Arc<str> when shared |
new(&str) |
Build a borrowed value |
from_str(&str) |
Alias of new |
from_shared(...) |
Build from Rc<str> or Arc<str> |
from_static(&'static str) |
Build from a static string |
into_raw_parts() |
Split into (raw_ptr, len, tag) |
into_raw() |
Convert into a raw *const str |
into_bytes() |
Convert into Vec<u8> |
into_boxed_str() |
Convert into Box<str> |
into_string() |
Convert into String |
Conversion Map
&str / String / Box<str> / Cow<str>
│
▼
LocalRefStr<'a> <──────► RefStr<'a>
│ │
├──── into_bytes ───┤
├─ into_boxed_str ──┤
└── into_string ───┘
Safety Boundaries
into_raw_parts,into_raw, andincrement_strong_countareunsafebecause they hand ownership or reference-count control to the caller.from_raw_partsisunsafebecause the caller must provide a valid non-null pointer and a correct length/tag combination.- Conversions between
LocalRefStrandRefStrpreserve borrowed strings without allocation, but shared strings are re-materialized into the target backend.
Example
extern crate alloc;
use String;
use ;
let local: = Stringfrom.into;
let shared: = Stringfrom.into;
assert_eq!;
assert_eq!;
let back: = shared.into;
assert_eq!;
Examples
Borrowed:
use LocalRefStr;
let value = from;
assert!;
assert_eq!;
Shared:
use Rc;
use LocalRefStr;
let value = from_shared;
assert!;
assert_eq!;
Raw:
use Arc;
use RefStr;
let value = from_shared;
let = unsafe ;
let value = unsafe ;
assert_eq!;
Cow:
use Cow;
use RefStr;
let value: = Borrowed.into;
assert_eq!;
Notes
- This crate is
no_stdand depends onalloc. - The
stdfeature does not enableserdeby itself; it only forwardsserde/stdwhenserdeis already enabled. - The
arbitraryfeature enablesArbitrarysupport for fuzzing and property testing. - The raw-pointer APIs are intentionally
unsafe.
License
Dual licensed under MIT or Apache-2.0.