wary 0.3.1

A simple validation and transformation library.
Documentation
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! Rule for validation of slice or string containments.
//!
//! See [`ContainsRule`] for more information.

use core::fmt;

use crate::{
	options::{DebugDisplay, ItemSlice},
	toolbox::rule::*,
};

#[doc(hidden)]
pub type Rule<C, Mode, Kind> = ContainsRule<C, Mode, Kind>;

#[derive(Debug, thiserror::Error, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize), serde(untagged))]
pub enum Error {
	#[error("expected string to contain \"{value}\"")]
	ShouldContain { value: &'static str },
	#[error("found unexpected string \"{value}\" at position {position}")]
	ShouldNotContain {
		position: usize,
		value: &'static str,
	},
	#[error("expected slice to contain")]
	ShouldContainSlice { value: ItemSlice },
	#[error("found unexpected value at position {position}")]
	ShouldNotContainSlice { position: usize, value: ItemSlice },
}

impl Error {
	#[must_use]
	pub(crate) fn code(&self) -> &'static str {
		match self {
			Self::ShouldContain { .. } => "should_contain",
			Self::ShouldNotContain { .. } => "should_not_contain",
			Self::ShouldContainSlice { .. } => "should_contain_slice",
			Self::ShouldNotContainSlice { .. } => "should_not_contain_slice",
		}
	}

	#[cfg(feature = "alloc")]
	#[must_use]
	pub(crate) fn message(&self) -> Cow<'static, str> {
		match self {
			Self::ShouldContain { value } => format!("expected to contain {value}"),
			Self::ShouldNotContain { position, value } => {
				format!("found unexpected value at position {position}: {value}")
			}
			Self::ShouldContainSlice { value } => format!("expected to contain {value:?}"),
			Self::ShouldNotContainSlice { position, value } => {
				format!("found unexpected value at position {position}: {value:?}")
			}
		}
		.into()
	}

	#[cfg(not(feature = "alloc"))]
	pub(crate) fn message(&self) -> &'static str {
		match self {
			Self::ShouldContain { .. } => "did not contain expected value",
			Self::ShouldNotContain { .. } => "found unexpected value",
			Self::ShouldContainSlice { .. } => "did not contain expected sequence",
			Self::ShouldNotContainSlice { .. } => "found unexpected sequence",
		}
	}
}

pub struct InOrder;
pub struct AnyOrder;
pub struct InOrderNot;
pub struct AnyOrderNot;

pub struct Str;
pub struct Slice;

/// Rule for validation of slice or string containments.
///
/// # Example
///
/// ```
/// use wary::{Wary, Validate};
///
/// #[derive(Wary)]
/// struct Person {
///   #[validate(contains(str = "hello"))]
///   name: String,
///   #[validate(contains(slice = [5, 6, 7, 8]))]
///   numbers: Vec<u8>,
///   #[validate(contains(any_order, slice = [5, 6, 7, 8]))]
///   greeting: Vec<u8>,
/// }
///
/// let person = Person {
///   name: "abchelloxyz".into(),
///   numbers: vec![1, 2, 3, 4, 5, 6, 7, 8, 9],
///   greeting: vec![8, 6, 7, 5],
/// };
///
/// assert!(person.validate(&()).is_ok());
///
/// let person = Person {
///   name: "abcworldxyz".into(),
///   numbers: vec![1, 2, 3, 4, 5, 6, 7, 9],
///   greeting: vec![3, 4, 5, 6],
/// };
///
/// assert!(person.validate(&()).is_err());
/// ```
#[must_use]
pub struct ContainsRule<C, Mode, Kind> {
	contains: C,
	mode: PhantomData<Mode>,
	kind: PhantomData<Kind>,
}

impl ContainsRule<Unset, InOrder, Unset> {
	#[inline]
	pub const fn new() -> ContainsRule<Unset, InOrder, Unset> {
		ContainsRule {
			contains: Unset,
			mode: PhantomData,
			kind: PhantomData,
		}
	}
}

impl<M> ContainsRule<Unset, M, Unset> {
	/// Ensure the input contains the given string.
	#[inline]
	pub fn str(self, contains: &'static str) -> ContainsRule<&'static str, M, Str> {
		ContainsRule {
			contains,
			mode: PhantomData,
			kind: PhantomData,
		}
	}

	/// Ensure the input contains the given slice.
	#[inline]
	pub fn slice<C>(self, contains: C) -> ContainsRule<C, M, Slice> {
		ContainsRule {
			contains,
			mode: PhantomData,
			kind: PhantomData,
		}
	}
}

impl<C, M, K> ContainsRule<C, M, K> {
	/// Validates that all of the items in the `contains` list are in the `inner`
	/// list in the same order. This is the default behavior.
	#[inline]
	pub fn in_order(self) -> ContainsRule<C, InOrder, K> {
		ContainsRule {
			contains: self.contains,
			mode: PhantomData,
			kind: PhantomData,
		}
	}

	/// Validates that all of the items in the `contains` list are in the `inner`
	/// list in any order. Note that this does not enforce the `inner` list to
	/// contain only the items in the `contains` list.
	///
	/// This can only be used with slices.
	#[inline]
	pub fn any_order(self) -> ContainsRule<C, AnyOrder, K> {
		ContainsRule {
			contains: self.contains,
			mode: PhantomData,
			kind: PhantomData,
		}
	}
}

impl<C, K> ContainsRule<C, InOrder, K> {
	/// Inverts the rule.
	#[inline]
	pub fn not(self) -> ContainsRule<C, InOrderNot, K> {
		ContainsRule {
			contains: self.contains,
			mode: PhantomData,
			kind: PhantomData,
		}
	}
}

impl<C, K> ContainsRule<C, AnyOrder, K> {
	/// Validates that all of the items in the `contains` list are not in the
	/// `inner` list in any order. Note that this does not enforce the `inner`
	/// list to contain only the items in the `contains` list.
	#[inline]
	pub fn not(self) -> ContainsRule<C, AnyOrderNot, K> {
		ContainsRule {
			contains: self.contains,
			mode: PhantomData,
			kind: PhantomData,
		}
	}
}

impl<I, C, O> crate::Rule<I> for ContainsRule<C, InOrder, Slice>
where
	I: AsSlice<Item = O>,
	C: AsSlice<Item = O> + fmt::Debug,
	O: PartialEq,
{
	type Context = ();

	fn validate(&self, _ctx: &Self::Context, item: &I) -> Result<()> {
		let inner = item.as_slice();
		let contains = self.contains.as_slice();

		let [first, contains @ ..] = contains else {
			return Ok(());
		};

		let mut inner_iter = inner.iter();

		while let Some(inner_item) = inner_iter.next() {
			if inner_item == first && inner_iter.as_slice().starts_with(contains) {
				return Ok(());
			}
		}

		Err(
			Error::ShouldContainSlice {
				value: DebugDisplay(&self.contains).to_string(),
			}
			.into(),
		)
	}
}

impl<I, C, D> crate::Rule<I> for ContainsRule<C, InOrderNot, Slice>
where
	I: AsSlice<Item = D>,
	C: AsSlice<Item = D> + fmt::Debug,
	D: PartialEq,
{
	type Context = ();

	fn validate(&self, _ctx: &Self::Context, item: &I) -> Result<()> {
		let inner = item.as_slice();
		let contains = self.contains.as_slice();

		let [first, contains @ ..] = contains else {
			return Ok(());
		};

		let mut inner_iter = inner.iter();
		let mut idx = 0;

		while let Some(inner_item) = inner_iter.next() {
			if inner_item == first && inner_iter.as_slice().starts_with(contains) {
				return Err(
					Error::ShouldNotContainSlice {
						position: idx,
						value: DebugDisplay(&self.contains).to_string(),
					}
					.into(),
				);
			}

			idx += 1;
		}

		Ok(())
	}
}

impl<I, C, O> crate::Rule<I> for ContainsRule<C, AnyOrder, Slice>
where
	I: AsSlice<Item = O>,
	C: AsSlice<Item = O> + fmt::Debug,
	O: PartialEq,
{
	type Context = ();

	fn validate(&self, _ctx: &Self::Context, item: &I) -> Result<()> {
		let inner = item.as_slice();
		let contains = self.contains.as_slice();

		for item in contains {
			if !inner.contains(item) {
				return Err(
					Error::ShouldContainSlice {
						value: DebugDisplay(&self.contains).to_string(),
					}
					.into(),
				);
			}
		}

		Ok(())
	}
}

impl<I, C, D> crate::Rule<I> for ContainsRule<C, AnyOrderNot, Slice>
where
	I: AsSlice<Item = D>,
	C: AsSlice<Item = D> + fmt::Debug,
	D: PartialEq,
{
	type Context = ();

	fn validate(&self, _ctx: &Self::Context, item: &I) -> Result<()> {
		let inner = item.as_slice();
		let contains = self.contains.as_slice();

		for (idx, item) in contains.iter().enumerate() {
			if inner.contains(item) {
				return Err(
					Error::ShouldNotContainSlice {
						position: idx,
						value: DebugDisplay(&self.contains).to_string(),
					}
					.into(),
				);
			}
		}

		Ok(())
	}
}

impl<I> crate::Rule<I> for ContainsRule<&'static str, InOrder, Str>
where
	I: AsRef<str>,
{
	type Context = ();

	fn validate(&self, _ctx: &Self::Context, item: &I) -> Result<()> {
		let inner = item.as_ref();
		let contains = self.contains;

		if inner.contains(contains) {
			Ok(())
		} else {
			Err(
				Error::ShouldContain {
					value: self.contains,
				}
				.into(),
			)
		}
	}
}

impl<I> crate::Rule<I> for ContainsRule<&'static str, InOrderNot, Str>
where
	I: AsRef<str>,
{
	type Context = ();

	fn validate(&self, _ctx: &Self::Context, item: &I) -> Result<()> {
		let inner = item.as_ref();
		let contains = self.contains;

		if let Some(idx) = inner.find(contains) {
			Err(
				Error::ShouldNotContain {
					position: idx,
					value: self.contains,
				}
				.into(),
			)
		} else {
			Ok(())
		}
	}
}

#[cfg(test)]
mod test {
	use crate::toolbox::test::*;

	#[test]
	fn test_contains_str_rule() {
		#[derive(Wary)]
		#[wary(crate = "crate")]
		struct Person<'name> {
			#[validate(contains(str = "hello"))]
			name: Cow<'name, str>,
		}

		let person = Person {
			name: Cow::Borrowed("abchelloxyz"),
		};

		assert!(person.validate(&()).is_ok());

		let person = Person {
			name: Cow::Borrowed("abcworldxyz"),
		};

		assert!(person.validate(&()).is_err());
	}

	#[test]
	fn test_contains_slice_rule() {
		#[derive(Wary)]
		#[wary(crate = "crate")]
		struct Person {
			#[validate(contains(slice = [5, 6, 7, 8]))]
			name: Vec<u8>,
		}

		let person = Person {
			name: vec![1, 2, 3, 4, 5, 6, 7, 8, 9],
		};

		assert!(person.validate(&()).is_ok());

		let person = Person {
			name: vec![1, 2, 3, 4, 5, 6, 7, 9],
		};

		assert!(person.validate(&()).is_err());
	}
}