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
use crate::{object::InvalidExpandedJson, Direction, LenientLangTag, LenientLangTagBuf};

/// Language string.
///
/// A language string is a string tagged with language and reading direction information.
///
/// A valid language string is associated to either a language tag or a direction, or both.
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct LangString {
	/// Actual content of the string.
	#[cfg_attr(feature = "serde", serde(rename = "@value"))]
	data: json_ld_syntax::String,

	#[cfg_attr(
		feature = "serde",
		serde(rename = "@language", skip_serializing_if = "Option::is_none")
	)]
	language: Option<LenientLangTagBuf>,

	#[cfg_attr(
		feature = "serde",
		serde(rename = "@direction", skip_serializing_if = "Option::is_none")
	)]
	direction: Option<Direction>,
}

/// Raised when something tried to build a language string without language tag or direction.
#[derive(Clone, Copy, Debug)]
pub struct InvalidLangString;

impl LangString {
	/// Create a new language string.
	pub fn new(
		data: json_ld_syntax::String,
		language: Option<LenientLangTagBuf>,
		direction: Option<Direction>,
	) -> Result<Self, json_ld_syntax::String> {
		if language.is_some() || direction.is_some() {
			Ok(Self {
				data,
				language,
				direction,
			})
		} else {
			Err(data)
		}
	}

	pub fn into_parts(
		self,
	) -> (
		json_ld_syntax::String,
		Option<LenientLangTagBuf>,
		Option<Direction>,
	) {
		(self.data, self.language, self.direction)
	}

	pub fn parts(&self) -> (&str, Option<&LenientLangTagBuf>, Option<&Direction>) {
		(&self.data, self.language.as_ref(), self.direction.as_ref())
	}

	/// Reference to the underlying `str`.
	#[inline(always)]
	pub fn as_str(&self) -> &str {
		self.data.as_ref()
	}

	/// Gets the associated language tag, if any.
	#[inline(always)]
	pub fn language(&self) -> Option<&LenientLangTag> {
		self.language
			.as_ref()
			.map(|tag| tag.as_lenient_lang_tag_ref())
	}

	/// Sets the associated language tag.
	///
	/// If `None` is given, the direction must be set,
	/// otherwise this function will fail with an [`InvalidLangString`] error.
	pub fn set_language(
		&mut self,
		language: Option<LenientLangTagBuf>,
	) -> Result<(), InvalidLangString> {
		if self.direction.is_some() || language.is_some() {
			self.language = language;
			Ok(())
		} else {
			Err(InvalidLangString)
		}
	}

	/// Gets the associated direction, if any.
	#[inline(always)]
	pub fn direction(&self) -> Option<Direction> {
		self.direction
	}

	/// Sets the associated direction.
	///
	/// If `None` is given, a language tag must be set,
	/// otherwise this function will fail with an [`InvalidLangString`] error.
	pub fn set_direction(&mut self, direction: Option<Direction>) -> Result<(), InvalidLangString> {
		if direction.is_some() || self.language.is_some() {
			self.direction = direction;
			Ok(())
		} else {
			Err(InvalidLangString)
		}
	}

	/// Set both the language tag and direction.
	///
	/// If both `language` and `direction` are `None`,
	/// this function will fail with an [`InvalidLangString`] error.
	pub fn set(
		&mut self,
		language: Option<LenientLangTagBuf>,
		direction: Option<Direction>,
	) -> Result<(), InvalidLangString> {
		if direction.is_some() || language.is_some() {
			self.language = language;
			self.direction = direction;
			Ok(())
		} else {
			Err(InvalidLangString)
		}
	}

	/// Returns a reference to this lang string as a [`LangStr`].
	pub fn as_lang_str(&self) -> LangStr {
		LangStr {
			data: &self.data,
			language: self.language.as_deref(),
			direction: self.direction,
		}
	}

	pub(crate) fn try_from_json(
		object: json_syntax::Object,
		value: json_syntax::Value,
		language: Option<json_syntax::Value>,
		direction: Option<json_syntax::Value>,
	) -> Result<Self, InvalidExpandedJson> {
		let data = match value {
			json_syntax::Value::String(s) => s,
			v => {
				return Err(InvalidExpandedJson::Unexpected(
					v.kind(),
					json_syntax::Kind::String,
				))
			}
		};

		let language = match language {
			Some(json_syntax::Value::String(value)) => {
				let (tag, _) = LenientLangTagBuf::new(value.to_string());
				Some(tag)
			}
			Some(v) => {
				return Err(InvalidExpandedJson::Unexpected(
					v.kind(),
					json_syntax::Kind::String,
				))
			}
			None => None,
		};

		let direction = match direction {
			Some(json_syntax::Value::String(value)) => match Direction::try_from(value.as_str()) {
				Ok(direction) => Some(direction),
				Err(_) => return Err(InvalidExpandedJson::InvalidDirection),
			},
			Some(v) => {
				return Err(InvalidExpandedJson::Unexpected(
					v.kind(),
					json_syntax::Kind::String,
				))
			}
			None => None,
		};

		match object.into_iter().next() {
			None => Ok(Self::new(data, language, direction).unwrap()),
			Some(_) => Err(InvalidExpandedJson::UnexpectedEntry),
		}
	}
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for LangString {
	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
	where
		D: serde::Deserializer<'de>,
	{
		#[derive(serde::Deserialize)]
		struct Value {
			#[serde(rename = "@value")]
			data: json_ld_syntax::String,
			#[serde(rename = "@language")]
			language: Option<LenientLangTagBuf>,
			#[serde(rename = "@direction")]
			direction: Option<Direction>,
		}

		let value = Value::deserialize(deserializer)?;

		Self::new(value.data, value.language, value.direction).map_err(serde::de::Error::custom)
	}
}

/// Language string reference.
///
/// A language string is a string tagged with language and reading direction information.
///
/// A valid language string is associated to either a language tag or a direction, or both.
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct LangStr<'a> {
	/// Actual content of the string.
	#[cfg_attr(feature = "serde", serde(rename = "@value"))]
	data: &'a str,

	#[cfg_attr(
		feature = "serde",
		serde(rename = "@language", skip_serializing_if = "Option::is_none")
	)]
	language: Option<&'a LenientLangTag>,

	#[cfg_attr(
		feature = "serde",
		serde(rename = "@direction", skip_serializing_if = "Option::is_none")
	)]
	direction: Option<Direction>,
}

impl<'a> LangStr<'a> {
	/// Create a new language string reference.
	pub fn new(
		data: &'a str,
		language: Option<&'a LenientLangTag>,
		direction: Option<Direction>,
	) -> Result<Self, InvalidLangString> {
		if language.is_some() || direction.is_some() {
			Ok(Self {
				data,
				language,
				direction,
			})
		} else {
			Err(InvalidLangString)
		}
	}

	pub fn into_parts(self) -> (&'a str, Option<&'a LenientLangTag>, Option<Direction>) {
		(self.data, self.language, self.direction)
	}

	/// Reference to the underlying `str`.
	#[inline(always)]
	pub fn as_str(&self) -> &'a str {
		self.data
	}

	/// Gets the associated language tag, if any.
	#[inline(always)]
	pub fn language(&self) -> Option<&'a LenientLangTag> {
		self.language
	}

	/// Gets the associated direction, if any.
	#[inline(always)]
	pub fn direction(&self) -> Option<Direction> {
		self.direction
	}
}