| 1 | # string-cache |
| 2 | |
| 3 | [](https://github.com/servo/string-cache/actions) |
| 4 | |
| 5 | [Documentation](https://docs.rs/string_cache/) |
| 6 | |
| 7 | A string interning library for Rust, developed as part of the [Servo](https://github.com/servo/servo) project. |
| 8 | |
| 9 | ## Simple usage |
| 10 | |
| 11 | In `Cargo.toml`: |
| 12 | |
| 13 | ```toml |
| 14 | [dependencies] |
| 15 | string_cache = "0.9" |
| 16 | ``` |
| 17 | |
| 18 | In `lib.rs`: |
| 19 | |
| 20 | ```rust |
| 21 | extern crate string_cache; |
| 22 | use string_cache::DefaultAtom as Atom; |
| 23 | ``` |
| 24 | |
| 25 | ## With static atoms |
| 26 | |
| 27 | In `Cargo.toml`: |
| 28 | |
| 29 | ```toml |
| 30 | [package] |
| 31 | build = "build.rs" |
| 32 | |
| 33 | [dependencies] |
| 34 | string_cache = "0.9" |
| 35 | |
| 36 | [build-dependencies] |
| 37 | string_cache_codegen = "0.6" |
| 38 | ``` |
| 39 | |
| 40 | In `build.rs`: |
| 41 | |
| 42 | ```rust |
| 43 | extern crate string_cache_codegen; |
| 44 | |
| 45 | use std::env; |
| 46 | use std::path::Path; |
| 47 | |
| 48 | fn main() { |
| 49 | string_cache_codegen::AtomType::new("foo::FooAtom", "foo_atom!") |
| 50 | .atoms(&["foo", "bar"]) |
| 51 | .write_to_file(&Path::new(&env::var("OUT_DIR").unwrap()).join("foo_atom.rs")) |
| 52 | .unwrap() |
| 53 | } |
| 54 | ``` |
| 55 | |
| 56 | In `lib.rs`: |
| 57 | |
| 58 | ```rust |
| 59 | extern crate string_cache; |
| 60 | |
| 61 | mod foo { |
| 62 | include!(concat!(env!("OUT_DIR"), "/foo_atom.rs")); |
| 63 | } |
| 64 | ``` |
| 65 | |
| 66 | The generated code will define a `FooAtom` type and a `foo_atom!` macro. |
| 67 | The macro can be used in expression or patterns, with strings listed in `build.rs`. |
| 68 | For example: |
| 69 | |
| 70 | ```rust |
| 71 | fn compute_something(input: &foo::FooAtom) -> u32 { |
| 72 | match *input { |
| 73 | foo_atom!("foo") => 1, |
| 74 | foo_atom!("bar") => 2, |
| 75 | _ => 3, |
| 76 | } |
| 77 | } |
| 78 | ``` |