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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
//! Guarded [string](std::string) type

use crate::auxiliary::zero;
use crate::guard;
use crate::vec::{InnerVec, Vec};

use std::cmp::{PartialEq, min, max};
use std::convert::From;
use std::iter::FromIterator;
use std::mem::MaybeUninit;
use std::str::Chars;

use unicode_normalization::UnicodeNormalization;
use unicode_normalization::char::decompose_canonical;

/// Guarded [string](std::string::String) type
#[must_use]
#[derive(Debug, Default)]
pub struct String(Vec<u8>);

/// Reference to immutably borrowed guarded [`String`]
#[must_use]
#[derive(Debug)]
pub struct Ref<'t>(guard::Ref<'t, InnerVec<u8>>);

/// Reference to mutably borrowed guarded [`String`]
#[must_use]
#[derive(Debug)]
pub struct RefMut<'t>(guard::RefMut<'t, InnerVec<u8>>);

impl String {
	const CMP_MIN: usize = 32;

	fn eq_slice(a: &InnerVec<u8>, b: &[u8]) -> bool {
		if a.capacity() == 0 {
			debug_assert!(a.is_empty());
			b.is_empty()
		} else {
			debug_assert!(a.capacity() >= Self::CMP_MIN);

			b.iter().take(a.capacity()).enumerate().fold(0, |d, (i, e)| {
				d | unsafe { a.as_ptr().add(i).read() as usize ^ *e as usize }
			}) | (max(a.len(), b.len()) - min(a.len(), b.len())) == 0
		}
	}

	#[inline]
	pub fn new() -> Self {
		Self(Vec::new())
	}

	#[inline]
	pub fn with_capacity(capacity: usize) -> Self {
		Self(Vec::with_capacity(capacity))
	}

	#[inline]
	pub fn capacity(&self) -> usize {
		self.0.capacity()
	}

	#[inline]
	pub fn len(&self) -> usize {
		self.0.len()
	}

	#[inline]
	pub fn is_empty(&self) -> bool {
		self.0.is_empty()
	}

	#[inline]
	pub fn reserve(&mut self, capacity: usize) {
		self.0.reserve(capacity);
	}

	#[inline]
	pub fn reserve_exact(&mut self, capacity: usize) {
		self.0.reserve_exact(capacity);
	}

	#[inline]
	pub fn borrow(&self) -> Ref<'_> {
		Ref(self.0.borrow())
	}

	#[inline]
	pub fn borrow_mut(&mut self) -> RefMut<'_> {
		RefMut(self.0.borrow_mut())
	}
}

impl FromIterator<char> for String {
	fn from_iter<I>(into: I) -> Self
		where I: IntoIterator<Item = char> {
		let iter = into.into_iter();
		let (lower, upper) = iter.size_hint();
		let mut string = Self::with_capacity(upper.unwrap_or(lower));

		{
			let mut mutable = string.borrow_mut();

			for ch in iter {
				mutable.push(ch);
			}
		}

		string
	}
}

impl From<&str> for String {
	fn from(source: &str) -> Self {
		let iter = source.nfd();
		let (lower, upper) = iter.size_hint();
		let mut string = Self::with_capacity(upper.unwrap_or(lower));

		{
			let mut mutable = string.borrow_mut();

			for decomp in iter {
				mutable.reserve(decomp.len_utf8());
				decomp.encode_utf8(unsafe { MaybeUninit::slice_assume_init_mut(mutable.0.spare_capacity_mut()) });
				unsafe { mutable.0.set_len(mutable.0.len() + decomp.len_utf8()); }
			}
		}

		string
	}
}

impl From<std::string::String> for String {
	fn from(mut source: std::string::String) -> Self {
		let string = Self::from(source.as_str());

		// Zero out source
		unsafe { zero(source.as_mut_ptr(), source.len()); }

		string
	}
}

impl Ref<'_> {
	#[must_use] #[inline]
	pub fn as_bytes(&self) -> &[u8] {
		self.0.as_slice()
	}

	#[must_use] #[inline]
	pub fn as_str(&self) -> &str {
		unsafe { std::str::from_utf8_unchecked(self.0.as_slice()) }
	}

	#[inline]
	pub fn chars(&self) -> Chars<'_> {
		self.as_str().chars()
	}
}

impl PartialEq<Self> for Ref<'_> {
	#[inline]
	fn eq(&self, other: &Self) -> bool {
		String::eq_slice(unsafe { self.0.0.inner() }, unsafe { other.0.0.inner() })
	}
}

impl PartialEq<RefMut<'_>> for Ref<'_> {
	#[inline]
	fn eq(&self, other: &RefMut<'_>) -> bool {
		String::eq_slice(unsafe { self.0.0.inner() }, unsafe { other.0.0.inner() })
	}
}

impl RefMut<'_> {
	#[must_use] #[inline]
	pub fn as_bytes(&self) -> &[u8] {
		self.0.as_slice()
	}

	#[must_use] #[inline]
	pub fn as_str(&self) -> &str {
		unsafe { std::str::from_utf8_unchecked(self.0.as_slice()) }
	}

	#[inline]
	pub fn chars(&self) -> Chars<'_> {
		self.as_str().chars()
	}

	#[inline]
	pub fn reserve(&mut self, capacity: usize) {
		self.0.reserve(capacity);
	}

	#[inline]
	pub fn reserve_exact(&mut self, capacity: usize) {
		self.0.reserve_exact(capacity);
	}

	pub fn push(&mut self, ch: char) {
		decompose_canonical(ch, |decomp| {
			self.0.0.reserve(decomp.len_utf8());
			decomp.encode_utf8(unsafe { MaybeUninit::slice_assume_init_mut(self.0.spare_capacity_mut()) });
			unsafe { self.0.0.set_len(self.0.len() + decomp.len_utf8()); }
		});
	}

	pub fn push_str(&mut self, string: &str) {
		let iter = string.nfd();
		let (lower, upper) = iter.size_hint();

		self.0.0.reserve(upper.unwrap_or(lower));

		for decomp in iter {
			self.0.0.reserve(decomp.len_utf8());
			decomp.encode_utf8(unsafe { MaybeUninit::slice_assume_init_mut(self.0.spare_capacity_mut()) });
			unsafe { self.0.0.set_len(self.0.len() + decomp.len_utf8()); }
		}
	}

	pub fn pop(&mut self) -> Option<char> {
		let ch = self.chars().next_back()?;
		unsafe { self.0.0.set_len(self.0.len() - ch.len_utf8()); }
		unsafe { zero(self.0.as_mut_ptr().add(self.0.len()), ch.len_utf8()); }
		Some(ch)
	}
}

impl PartialEq<Self> for RefMut<'_> {
	#[inline]
	fn eq(&self, other: &Self) -> bool {
		String::eq_slice(unsafe { self.0.0.inner() }, unsafe { other.0.0.inner() })
	}
}

impl PartialEq<Ref<'_>> for RefMut<'_> {
	#[inline]
	fn eq(&self, other: &Ref<'_>) -> bool {
		String::eq_slice(unsafe { self.0.0.inner() }, unsafe { other.0.0.inner() })
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn eq() {
		assert_eq!(String::from("").borrow(), String::from("").borrow());
		assert_eq!(String::from("ÄÖÜäöüß").borrow(), String::from("A\u{308}O\u{308}U\u{308}a\u{308}o\u{308}u\u{308}ß").borrow());

		assert_ne!(String::from("empty").borrow(), String::from("").borrow());
		assert_ne!(String::from("Warum Thunfische das?").borrow(), String::from("Darum Thunfische das!").borrow());
	}

	#[test]
	fn pop() {
		let mut string = String::from("Warum Thunfische das?");
		let mut immutable = string.borrow_mut();

		assert_eq!(immutable.pop(), Some('?'));
		assert_eq!(immutable.pop(), Some('s'));
		assert_eq!(immutable.pop(), Some('a'));
		assert_eq!(immutable.pop(), Some('d'));
		assert_eq!(immutable.pop(), Some(' '));
		assert_eq!(immutable, String::from("Warum Thunfische").borrow());
	}
}