You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
A simple wrapper type for `String`s that ensures that the string inside is not `.empty()`, meaning that the length > 0.
3
7
8
+
## Example
9
+
10
+
```rust
11
+
usenon_empty_string::NonEmptyString;
12
+
13
+
// Constructing it from a normal (non-zero-length) String works fine.
14
+
lets="A string with a length".to_owned();
15
+
assert!(NonEmptyString::new(s).is_ok());
16
+
17
+
// But constructing it from a non-zero-length String results in an `Err`, where we get the `String` back that we passed in.
18
+
letempty="".to_owned();
19
+
letresult=NonEmptyString::new(empty);
20
+
assert!(result.is_err());
21
+
assert_eq!(result.unwrap_err(), "".to_owned())
22
+
23
+
```
24
+
25
+
## Methods of std::string::String
26
+
`NonEmptyString` implements a subset of the functions of `std::string::String`, only the ones which are guaranteed to leave the `NonEmptyString` in a valid state.
27
+
This means i.e. `push()` is implemented, but `pop()` is not.
28
+
29
+
This allows you to mostly treat it as a String without having to constantly turn it into the inner `String` before you can do any sort of operation on it and then having to reconstruct a `NonEmptyString` afterwards.
30
+
31
+
32
+
## Serde Support
33
+
34
+
[serde] support is available behind the `serde` feature flag:
35
+
```toml
36
+
[dependencies]
37
+
serde = { version = "1", features = ["derive"] }
38
+
non-empty-string = { version = "*", features = ["serde"]}
39
+
```
40
+
41
+
Afterwards you can use it in a struct:
42
+
```rust
43
+
useserde::{Serialize, Deserialize};
44
+
usenon_empty_string::NonEmptyString;
45
+
46
+
#[derive(Serialize, Deserialize)]
47
+
structMyApiObject {
48
+
username:NonEmptyString,
49
+
}
50
+
```
51
+
52
+
Deserialization will fail if the field is present as a String, but the length of the `String` is 0.
4
53
5
54
## License
6
55
@@ -17,4 +66,6 @@ at your option.
17
66
18
67
Unless you explicitly state otherwise, any contribution intentionally submitted
19
68
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
20
-
dual licensed as above, without any additional terms or conditions.
69
+
dual licensed as above, without any additional terms or conditions.
0 commit comments