1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
#![cfg_attr(
all(feature = "lifetime", feature = "serde"),
doc = r##"
This example shows how to use [`Abos`] in a struct
using the [`lifetime`] and [`serde`] crates.
```rust
# fn main() -> Result<(), Box<dyn std::error::Error>> {
use assert_matches::assert_matches;
use bos::AbosStr;
use lifetime::{IntoStatic, ToBorrowed};
use serde::{Deserialize, Deserializer};
use std::sync::Arc;
#[derive(IntoStatic, ToBorrowed, Deserialize)]
struct Header<'a> {
name: AbosStr<'a>,
#[serde(deserialize_with = "arc_string_if_long")]
value: AbosStr<'a>,
}
fn arc_string_if_long<'b, 'de, D>(d: D) -> Result<AbosStr<'b>, D::Error>
where
D: Deserializer<'de>,
{
let s: String = Deserialize::deserialize(d)?;
Ok(if s.len() < 10 { // 10 is way too small. Try something like 1000 in your code.
AbosStr::Owned(s)
} else {
AbosStr::Arc(Arc::new(s))
})
}
// Let's pretend this JSON String came over the network.
let header_json =
String::from(r#"{ "name":"content", "value":"text/html; charset=UTF-8" }"#);
let content: Header<'static> = serde_json::from_str(&header_json)?;
let mut content_type: Header<'_> = content.to_borrowed();
content_type.name += "-type"; // creates a new String
// content header has not moved
assert_eq!(content.name, "content");
assert_eq!(content_type.name, "content-type");
assert_matches!(&content_type.value, AbosStr::BorrowedArc(arc) if Arc::strong_count(arc) == 1);
let static_content_type: Header<'static> = content_type.into_static();
assert_eq!(static_content_type.value, "text/html; charset=UTF-8");
assert_matches!(&static_content_type.value, AbosStr::Arc(arc) if Arc::strong_count(arc) == 2);
# Ok(()) }
```
"##
)]
#![forbid(unsafe_code)]
mod abos;
mod bos;
#[cfg(feature = "serde")]
mod serde_support;
pub use self::abos::Abos;
pub use self::bos::Bos;
pub type AbosTo<'b, B> = Abos<'b, B, <B as ToOwned>::Owned, <B as ToOwned>::Owned>;
pub type BosTo<'b, B> = Bos<'b, B, <B as ToOwned>::Owned, <B as ToOwned>::Owned>;
pub type AbosBox<'b, T> = Abos<'b, T, Box<T>, T>;
pub type BosBox<'b, T> = Bos<'b, T, Box<T>, T>;
pub type AbosStr<'b> = AbosTo<'b, str>;
pub type BosStr<'b> = BosTo<'b, str>;
pub type AbosVec<'b, T> = Abos<'b, [T], Vec<T>>;
pub type BosVec<'b, T> = Bos<'b, [T], Vec<T>>;