#string #newtype #wrapper #alias

string-newtype

New Type idiom helper for string-like types

2 releases

0.1.1 Apr 22, 2024
0.1.0 Apr 21, 2024

#1362 in Encoding

Apache-2.0

16KB
364 lines

string-newtype: New Type idiom helper for string-like types

build_status msrv codecov

string-newtype is a helper library for using the newtype idiom with string-like types, including newtyped string slices.

Usage

Define an empty enum as a marker for your type, and add aliases based on it:

// A marker type, can be anything.
enum S {}

// The newtype definitions.
// `StringBuf` acts as a `String`, while `StringRef` acts as a `str`.
type SBuf = StringBuf<S>;
type SRef = StringRef<S>;

// Define functions that only accept the newtype.
fn my_func(owned: SBuf, reference: &SRef) {
    // ...
}

// Only the newtype can be passed to the function.
let s: SBuf = "hello".into();
my_func(s.clone(), &s);

The crate also defines SmolStrBuf and SmolStrRef types, which are newtypes for smol_str::SmolStr.

Features

  • smol_str Enables newtypes for smol_str::SmolStrs.

  • serde Enables serialization and deserialization implementations.

Developing string-newtype

See DEVELOPMENT.md for instructions on setting up the development environment.

License

This project is licensed under Apache License, Version 2.0 (LICENSE or http://www.apache.org/licenses/LICENSE-2.0).

Dependencies

~0.4–0.9MB
~20K SLoC