test_vectors/
utf8str.rs

1use std::cmp::PartialEq;
2use std::ops::Deref;
3use std::str::Utf8Error;
4
5/// Convenience type for tests with string vectors
6///
7/// A `Utf8Str<'a>` should behave identically to `&'a str` except it implements
8/// `TryFrom<&[u8]>` with UTF-8 decoding.  This provides a convenient short hand for
9/// [test_vectors](crate::test_vectors) tests which operate on strings, rather than bytes.
10///
11/// # Example
12///
13/// ```
14/// use test_vectors::{test_vectors, Utf8Str};
15///
16/// #[test_vectors(dir = "test-data")]
17/// fn utf8str_test_replace_spaces(input: Utf8Str<'static>, expected: Utf8Str<'static>) {
18///     let output = input.replace(' ', "_");
19///     assert_eq!(expected, output);
20/// }
21/// ```
22#[derive(Debug)]
23pub struct Utf8Str<'a>(&'a str);
24
25impl<'a> Deref for Utf8Str<'a> {
26    type Target = str;
27
28    fn deref(&self) -> &str {
29        self.0
30    }
31}
32
33impl<'a> TryFrom<&'a [u8]> for Utf8Str<'a> {
34    type Error = Utf8Error;
35
36    fn try_from(bytes: &'a [u8]) -> Result<Utf8Str<'a>, Utf8Error> {
37        std::str::from_utf8(bytes).map(Utf8Str)
38    }
39}
40
41impl<'a, Rhs> PartialEq<Rhs> for Utf8Str<'a>
42where
43    str: PartialEq<Rhs>,
44{
45    fn eq(&self, other: &Rhs) -> bool {
46        self.0.eq(other)
47    }
48}