copstr/lib.rs
1// Copyright (C) 2021 Leandro Lisboa Penz <lpenz@lpenz.org>
2// This file is subject to the terms and conditions defined in
3// file 'LICENSE', which is part of this source code package.
4
5#![warn(rust_2018_idioms)]
6#![warn(missing_docs)]
7
8//! copstr is a COPy STRing module
9//!
10//! [`copstr::Str`] wraps a fixed-size array of `u8` and provides a
11//! string-like interface on top. The size is specified using a const
12//! generic argument.
13//!
14//! The internal `u8` array corresponds to UTF-8 encoded `chars`. All
15//! functions guarantee that the contents are valid UTF-8 and return
16//! an error if they are not. Truncation only happens at UTF-8
17//! boundaries.
18//!
19//! [`copstr`] is very useful when we want to add a string-like field
20//! to a struct that implements `Copy` but we don't want to give up
21//! this trait.
22//!
23//! # Example usage
24//!
25//! ```rust
26//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
27//! use copstr;
28//! use std::convert::TryFrom;
29//!
30//! // Create an owned fixed-size string with size 6 *on the stack*:
31//! let mut string = copstr::Str::<6>::try_from("string")?;
32//!
33//! // Use it as a regular string:
34//! println!("contents: {}", string);
35//!
36//! // Replace the contents with another string that fits the size 6:
37//! string.replace("str")?;
38//!
39//! // Append a letter:
40//! string.push('i')?;
41//!
42//! // Instead of returning a potential error, we can instead use
43//! // truncating methods:
44//! string.replace_trunc("stringification");
45//! assert_eq!(string.as_str(), "string");
46//!
47//! // `copstr::Str` implements Deref<Target=str>, so all `str`
48//! // methods are available:
49//! let split = format!("{:?}", string.split_at(3));
50//! assert_eq!(split, r#"("str", "ing")"#);
51//!
52//! // We can add a `copstr` to a struct without having to give up the
53//! // `Copy` trait:
54//! #[derive(Clone, Copy)]
55//! pub struct Mystruct {
56//! // ...
57//! comment: copstr::Str<10>,
58//! }
59//!
60//! // We can (and should) create a type alias:
61//! type MyStr = copstr::Str::<4>;
62//!
63//! // We can create `copstr` in const contexts:
64//! const TEST: MyStr = MyStr::new_const("TEST");
65//! # Ok(()) }
66//! ```
67//!
68//! When using a const context, strings that don't fit generate a
69//! compilation error. For instance, the following doesn't compile:
70//!
71//! ```compile_fail
72//! const TEST_BAD: copstr::Str<3> = copstr::Str::<3>::new_const("TEST");
73//! ```
74//!
75
76pub mod copstr;
77pub use self::copstr::*;