json_ld_syntax/
direction.rs

1use std::{fmt, str::FromStr};
2
3#[derive(Debug, thiserror::Error)]
4#[error("invalid JSON-LD text direction `{0}`")]
5pub struct InvalidDirection<T>(pub T);
6
7impl<'a, T: ?Sized + ToOwned> InvalidDirection<&'a T> {
8	pub fn into_owned(self) -> InvalidDirection<T::Owned> {
9		InvalidDirection(self.0.to_owned())
10	}
11}
12
13/// Internationalized string direction.
14///
15/// Specifies the direction used to read a string.
16/// This can be either left-to-right (`"ltr"`) or right-to-left (`"rtl"`).
17#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
18pub enum Direction {
19	/// Left-to-right direction.
20	Ltr,
21
22	/// Right-to-left direction.
23	Rtl,
24}
25
26impl Direction {
27	pub fn as_str(&self) -> &'static str {
28		match self {
29			Direction::Ltr => "ltr",
30			Direction::Rtl => "rtl",
31		}
32	}
33
34	pub fn into_str(self) -> &'static str {
35		self.as_str()
36	}
37}
38
39impl FromStr for Direction {
40	type Err = InvalidDirection<String>;
41
42	fn from_str(s: &str) -> Result<Self, Self::Err> {
43		Self::try_from(s).map_err(InvalidDirection::into_owned)
44	}
45}
46
47impl<'a> TryFrom<&'a str> for Direction {
48	type Error = InvalidDirection<&'a str>;
49
50	/// Convert the strings `"rtl"` and `"ltr"` into a `Direction`.
51	#[inline(always)]
52	fn try_from(name: &'a str) -> Result<Direction, InvalidDirection<&'a str>> {
53		match name {
54			"ltr" => Ok(Direction::Ltr),
55			"rtl" => Ok(Direction::Rtl),
56			_ => Err(InvalidDirection(name)),
57		}
58	}
59}
60
61impl fmt::Display for Direction {
62	#[inline(always)]
63	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
64		match self {
65			Direction::Ltr => write!(f, "ltr"),
66			Direction::Rtl => write!(f, "rtl"),
67		}
68	}
69}
70
71#[cfg(feature = "serde")]
72impl serde::Serialize for Direction {
73	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
74	where
75		S: serde::Serializer,
76	{
77		self.as_str().serialize(serializer)
78	}
79}
80
81#[cfg(feature = "serde")]
82impl<'de> serde::Deserialize<'de> for Direction {
83	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
84	where
85		D: serde::Deserializer<'de>,
86	{
87		struct Visitor;
88
89		impl<'de> serde::de::Visitor<'de> for Visitor {
90			type Value = Direction;
91
92			fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
93				formatter.write_str("JSON-LD text direction")
94			}
95
96			fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
97			where
98				E: serde::de::Error,
99			{
100				v.parse().map_err(|e| E::custom(e))
101			}
102		}
103
104		deserializer.deserialize_str(Visitor)
105	}
106}