substr_iterator/lib.rs
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 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
//! This library is made to iterate over a `&str` by a number of characters without allocating.
//!
//! ```rust
//! use substr_iterator::{Trigram, TrigramIter};
//!
//! let mut iter = TrigramIter::from("whatever");
//! assert_eq!(iter.next(), Some(['w', 'h', 'a']));
//! let mut iter = TrigramIter::from("今天我吃饭");
//! assert_eq!(iter.next(), Some(['今', '天', '我']));
//! ```
//!
//! It's also possible to handle bigger windows.
//!
//! ```rust
//! use substr_iterator::{Substr, SubstrIter};
//!
//! let mut iter = SubstrIter::<2>::from("whatever");
//! assert_eq!(iter.next(), Some(['w', 'h']));
//! let mut iter = SubstrIter::<2>::from("今天我吃饭");
//! assert_eq!(iter.next(), Some(['今', '天']));
//! ```
//!
//! When the `std` feature is enabled, the [SubstrWrapper] allows to display [Substr] as a [String].
//!
//! ```rust
//! use substr_iterator::{SubstrWrapper, Trigram, TrigramIter};
//!
//! let mut iter = TrigramIter::from("whatever");
//! let item = SubstrWrapper(iter.next().unwrap());
//! assert_eq!(item.to_string(), "wha");
//! ```
//!
//! When the `serde` feature is enabled, the [SubstrWrapper] allows to serialize and deserialize.
//!
//! ```rust
//! use substr_iterator::{SubstrWrapper, Trigram, TrigramIter};
//!
//! let data: Vec<SubstrWrapper<3>> = vec![
//! SubstrWrapper(['a', 'b', 'c']),
//! SubstrWrapper(['今', '天', '我']),
//! ];
//! assert_eq!(
//! serde_json::to_string(&data).unwrap(),
//! "[\"abc\",\"今天我\"]",
//! );
//! ```
/// A set of N characters stored as an array.
pub type Substr<const N: usize> = [char; N];
/// A set of 3 characters stored as an array.
pub type Trigram = Substr<3>;
/// An iterator for only 3 characters. This is just an alias to [SubstrIter].
pub type TrigramIter<'a> = SubstrIter<'a, 3>;
/// This is an iterator that allows to take a number of characters out of a string
/// and iterate like a window.
///
/// ```rust
/// let mut iter = substr_iterator::TrigramIter::from("whatever");
/// ```
pub struct SubstrIter<'a, const N: usize> {
iter: std::str::Chars<'a>,
}
impl<'a, const N: usize> From<&'a str> for SubstrIter<'a, N> {
fn from(origin: &'a str) -> Self {
Self {
iter: origin.chars(),
}
}
}
impl<const N: usize> Iterator for SubstrIter<'_, N> {
type Item = Substr<N>;
fn next(&mut self) -> Option<Self::Item> {
let mut res = [' '; N];
res[0] = self.iter.next()?;
let mut iter = self.iter.clone();
for item in res.iter_mut().take(N).skip(1) {
*item = iter.next()?;
}
Some(res)
}
}
/// Wrapper around [Substr] in order to bring extra capabilities.
///
/// ```rust
/// use substr_iterator::SubstrWrapper;
/// use std::str::FromStr;
///
/// let value: [char; 3] = ['a', 'b', 'c'];
/// let wrapped = SubstrWrapper(value);
/// // implements Display
/// assert_eq!(wrapped.to_string(), "abc");
///
/// // parsing &str
/// let parsed = SubstrWrapper::from_str("abc").unwrap();
/// assert_eq!(wrapped, parsed);
/// ```
///
/// When the `serde` feature is enabled, [SubstrWrapper] provides a way to [serde::Serialize] and [serde::Deserialize].
///
/// ```rust
/// let value: [char; 3] = ['a', 'b', 'c'];
/// let wrapped = substr_iterator::SubstrWrapper(value);
/// assert_eq!(serde_json::to_string(&wrapped).unwrap(), "\"abc\"");
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SubstrWrapper<const N: usize>(pub Substr<N>);
impl<const N: usize> SubstrWrapper<N> {
/// Extract the [Substr] from the wrapper
pub fn inner(self) -> Substr<N> {
self.0
}
}
impl<const N: usize> From<Substr<N>> for SubstrWrapper<N> {
fn from(value: Substr<N>) -> Self {
Self(value)
}
}
#[cfg(feature = "std")]
impl<const N: usize> std::fmt::Display for SubstrWrapper<N> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use std::fmt::Write;
for c in self.0 {
f.write_char(c)?;
}
Ok(())
}
}
/// String parsing error for [SubstrWrapper].
///
/// ```rust
/// use substr_iterator::SubstrWrapper;
/// use std::str::FromStr;
///
/// let err = SubstrWrapper::<3>::from_str("abcd").unwrap_err();
/// assert_eq!(err.expected, 3);
/// assert_eq!(err.current, 4);
/// ```
#[cfg(feature = "std")]
#[derive(Clone, Copy, Debug)]
pub struct SubstrParserError {
/// The expected number of characters
pub expected: usize,
/// The given number of characters in the [&str]
pub current: usize,
}
#[cfg(feature = "std")]
impl std::fmt::Display for SubstrParserError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"invalid length {}, expected {}",
self.current, self.expected
)
}
}
#[cfg(feature = "std")]
impl<const N: usize> std::str::FromStr for SubstrWrapper<N> {
type Err = SubstrParserError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut chars = s.chars();
let mut res = [' '; N];
for (idx, item) in res.iter_mut().enumerate() {
*item = chars.next().ok_or_else(|| SubstrParserError {
expected: N,
current: idx,
})?
}
let rest = chars.count();
if rest == 0 {
Ok(SubstrWrapper(res))
} else {
Err(SubstrParserError {
expected: N,
current: res.len() + rest,
})
}
}
}
#[cfg(feature = "serde")]
impl<const N: usize> serde::Serialize for SubstrWrapper<N> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.collect_str(self)
}
}
#[cfg(feature = "serde")]
struct SubstrVisitor<const N: usize>;
#[cfg(feature = "serde")]
impl<'de, const N: usize> serde::de::Visitor<'de> for SubstrVisitor<N> {
type Value = SubstrWrapper<N>;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "a string of {} characters", N)
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
std::str::FromStr::from_str(v).map_err(serde::de::Error::custom)
}
}
#[cfg(feature = "serde")]
impl<'de, const N: usize> serde::de::Deserialize<'de> for SubstrWrapper<N> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::de::Deserializer<'de>,
{
deserializer.deserialize_str(SubstrVisitor)
}
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use test_case::test_case;
use crate::*;
#[test_case("whatever", vec!["wha", "hat", "ate", "tev", "eve", "ver"]; "with simple characters")]
#[test_case("今天我吃饭", vec!["今天我", "天我吃", "我吃饭"]; "with chinese characters")]
fn should_window(word: &str, expected: Vec<&'static str>) {
let all = Vec::from_iter(SubstrIter::<'_, 3>::from(word).map(|v| SubstrWrapper(v)));
assert_eq!(
all,
expected
.iter()
.map(|v| SubstrWrapper::from_str(v).unwrap())
.collect::<Vec<_>>()
);
}
#[test_case(vec![['a', 'b', 'c']], vec!["abc"]; "with simple characters")]
#[test_case(vec![['今','天','我'], ['天','我','吃'], ['我','吃','饭']], vec!["今天我", "天我吃", "我吃饭"]; "with chinese characters")]
#[cfg(feature = "std")]
fn should_display(subsets: Vec<[char; 3]>, expected: Vec<&'static str>) {
let displayed = subsets
.into_iter()
.map(|v| SubstrWrapper(v).to_string())
.collect::<Vec<_>>();
assert_eq!(displayed, expected);
}
#[test]
fn should_serialize() {
let res: Vec<SubstrWrapper<3>> = vec![
SubstrWrapper(['a', 'b', 'c']),
SubstrWrapper(['今', '天', '我']),
];
let json = serde_json::to_string(&res).unwrap();
assert_eq!(json, "[\"abc\",\"今天我\"]");
let decoded: Vec<SubstrWrapper<3>> = serde_json::from_str(&json).unwrap();
assert_eq!(res, decoded);
}
#[test]
#[should_panic(expected = "invalid length 4, expected 3")]
fn should_not_deserialize_with_invalid_length() {
let _: Vec<SubstrWrapper<3>> = serde_json::from_str("[\"abcd\",\"今天我\"]").unwrap();
}
#[test]
#[should_panic(expected = "invalid type: integer `42`, expected a string of 3 characters")]
fn should_not_deserialize_with_invalid_type() {
let _: SubstrWrapper<3> = serde_json::from_str("42").unwrap();
}
}