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
#[cfg(test)]
#[macro_use]
extern crate lazy_static;
extern crate memchr;
extern crate objpool;
extern crate take_mut;
use std::error::Error;
use std::ffi::{CStr, CString};
use std::fmt;
use std::sync::Arc;
use objpool::{Item, Pool};
#[derive(Debug, Clone, Copy)]
pub struct NulError {
pub position: usize,
}
impl fmt::Display for NulError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "nul byte found in provided data at position: {}", self.position)
}
}
impl Error for NulError {
fn description(&self) -> &str { "nul byte found in data" }
}
#[derive(Debug, Clone)]
pub struct CStringPool {
pool: Arc<Pool<CString>>,
}
impl CStringPool {
pub fn new(default_string_capacity: usize) -> CStringPool {
CStringPool {
pool: Pool::new(move || {
let vec = Vec::with_capacity(default_string_capacity);
unsafe { CString::from_vec_unchecked(vec) }
}),
}
}
pub fn with_capacity(pool_capacity: usize, default_string_capacity: usize) -> CStringPool {
CStringPool {
pool: Pool::with_capacity(pool_capacity, move || {
let vec = Vec::with_capacity(default_string_capacity);
unsafe { CString::from_vec_unchecked(vec) }
}),
}
}
pub fn get_str<T: AsRef<str>>(&self, s: T) -> Result<Item<CString>, NulError> {
let str_ref = s.as_ref();
if let Some(i) = memchr::memchr(0, str_ref.as_bytes()) {
return Err(NulError { position: i });
}
let mut item = self.pool.get();
take_mut::take(&mut *item, |cstring| {
let mut string = unsafe { String::from_utf8_unchecked(cstring.into_bytes()) };
string.clear();
string.push_str(str_ref);
unsafe { CString::from_vec_unchecked(string.into_bytes()) }
});
Ok(item)
}
pub fn get_c_str<T: AsRef<CStr>>(&self, s: T) -> Item<CString> {
let str_ref = s.as_ref();
let mut item = self.pool.get();
take_mut::take(&mut *item, |cstring| {
let mut bytes = cstring.into_bytes();
bytes.clear();
bytes.extend(str_ref.to_bytes());
unsafe { CString::from_vec_unchecked(bytes) }
});
item
}
}
#[cfg(test)]
mod tests {
use super::*;
lazy_static! {
static ref POOL: CStringPool = CStringPool::new(128);
}
#[test]
fn round_trip() {
let s = "foo";
let cstr = POOL.get_str(s).unwrap();
assert_eq!(cstr.to_str().unwrap(), s);
}
#[test]
#[should_panic]
fn bad_string() {
let s = "fo\0o";
let _cstr = POOL.get_str(s).unwrap();
}
}