rxml 0.13.3

Minimalistic, restricted XML 1.0 parser which does not include dangerous XML features.
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
/*!
# Strongly-typed strings for use with XML 1.0 documents

These are mostly re-exported from [`rxml_validation`]. See that crate's
documentation for an overview over the different types and their use cases.

## Construction

In addition to the construction methods described in [`rxml_validation`],
[`str`]-like references ([`&NameStr`][`NameStr`], [`&NcNameStr`][`NcNameStr`])
can be created from a string literal, using the macros offered when this crate
is built with the `macros` feature:
[`xml_name!`][`crate::xml_name`], [`xml_ncname!`][`crate::xml_ncname`].
*/
use alloc::borrow::ToOwned;
use alloc::string::String;
use alloc::sync::Arc;
use core::borrow::Borrow;
use core::cmp::Ordering;
use core::fmt;
use core::hash::{Hash, Hasher};
use core::ops::Deref;

pub use rxml_validation::{CompactString, Error, Name, NameStr, NcName, NcNameStr};

use crate::error::{Error as XmlError, ErrorContext};

enum Shared {
	Static(&'static str),
	Ptr(Arc<String>),
}

enum Inner {
	Owned(String),
	Shared(Shared),
}

/// An XML namespace name.
///
/// Commonly, XML namespace names are URIs. Almost all URIs are also valid
/// namespace names, with the prominent exception of the empty URI: namespace
/// names in XML must not be empty. The empty namespace name signals that an
/// element is not namespaced. For purposes of comparison and others, we can
/// treat the empty namespace name as just another namespace, which is why it
/// is an allowed value for this struct.
///
/// Internally, `Namespace` is based on [`String`] or a static [`str`]
/// slice. It can be accessed mutably through [`Namespace::make_mut`].
///
/// Depending on the history of a specific `Namespace` instance, cloning
/// is either `O(1)` or `O(n)`. To ensure that the next clone is `O(1)`, call
/// [`Namespace::make_shared`] or use [`Namespace::share`] instead of
/// `clone()`.
///
/// `Namespace` is designed such that, no matter which internal
/// representation is at work, it hashes, compares, and orders exactly like a
/// `String` (or `str`), allowing it to be borrowed as such.
///
/// # Advantages over `String`
///
/// Unlike [`String`], `Namespace` is optimized for strings which:
///
/// - are not known by the `rxml` library at compile-time
/// - need to be passed around freely (static lifetime)
///
/// Internally, `Namespace` can keep either a `&'static str`, a
/// shared (ref-counted) pointer to a `String` or an owned instance of a
/// `String`. If the crate is built with the `shared_ns` feature,
/// `Namespace` is `Send` and `Sync`, otherwise it is neither.
pub struct Namespace(Inner);

const fn xml() -> Namespace {
	Namespace(Inner::Shared(Shared::Static(crate::XMLNS_XML)))
}

const fn xmlns() -> Namespace {
	Namespace(Inner::Shared(Shared::Static(crate::XMLNS_XMLNS)))
}

const fn none() -> Namespace {
	Namespace(Inner::Shared(Shared::Static(
		crate::parser::XMLNS_UNNAMESPACED,
	)))
}

impl Namespace {
	/// `Namespace` representing the built-in XML namespace.
	///
	/// See also [`crate::XMLNS_XML`].
	pub const XML: Namespace = xml();

	/// `Namespace` representing the built-in XML namespacing namespace.
	///
	/// See also [`crate::XMLNS_XMLNS`].
	pub const XMLNS: Namespace = xmlns();

	/// `Namespace` representing the empty namespace name.
	pub const NONE: Namespace = none();

	/// Construct a namespace name for the built-in XML namespace.
	///
	/// This function does not allocate.
	///
	/// # Example
	///
	/// ```
	/// # use rxml::strings::Namespace;
	/// let ns = Namespace::xml();
	/// assert_eq!(ns, rxml::XMLNS_XML);
	/// ```
	#[inline(always)]
	pub fn xml() -> &'static Self {
		static RESULT: Namespace = Namespace::XML;
		&RESULT
	}

	/// Construct a namespace name for the built-in XML namespacing namespace.
	///
	/// This function does not allocate.
	///
	/// # Example
	///
	/// ```
	/// # use rxml::strings::Namespace;
	/// let ns = Namespace::xmlns();
	/// assert_eq!(ns, rxml::XMLNS_XMLNS);
	/// ```
	#[inline(always)]
	pub fn xmlns() -> &'static Self {
		static RESULT: Namespace = Namespace::XMLNS;
		&RESULT
	}

	/// Construct an empty namespace name, representing unnamespaced elements.
	///
	/// # Example
	///
	/// ```
	/// # use rxml::strings::Namespace;
	/// let ns = Namespace::none();
	/// assert_eq!(ns, "");
	/// ```
	#[inline(always)]
	pub fn none() -> &'static Self {
		static RESULT: Namespace = Namespace::NONE;
		&RESULT
	}

	/// Attempts to deduplicate the given namespace name with a set of
	/// statically compiled well-known namespaces.
	///
	/// If no matching statically compiled namespace is found, `None` is
	/// returned.
	///
	/// Otherwise, a `Namespace` is created without allocating and without
	/// sharing data with `s`.
	pub fn try_share_static(s: &str) -> Option<Self> {
		if s.is_empty() {
			return Some(Self::NONE);
		}
		if s == crate::XMLNS_XML {
			return Some(Self::XML);
		}
		if s == crate::XMLNS_XMLNS {
			return Some(Self::XMLNS);
		}
		None
	}

	/// Construct a namespace name for a custom namespace from a static string.
	///
	/// This function is provided for use in `const` contexts, while normally
	/// you would use the `From<&'static str>` implementation.
	///
	/// # Example
	///
	/// ```
	/// # use rxml::strings::Namespace;
	/// static NS: Namespace = Namespace::from_str("jabber:client");
	/// assert_eq!(NS, "jabber:client");
	/// ```
	pub const fn from_str(s: &'static str) -> Self {
		Self(Inner::Shared(Shared::Static(s)))
	}

	/// Make the `Namespace` mutable and return a mutable reference to its
	/// inner [`String`].
	///
	/// Depending on how the `Namespace` was constructed and how it has
	/// been used, calling this function may require copying its contents.
	pub fn make_mut(&mut self) -> &mut String {
		match self.0 {
			Inner::Shared(Shared::Static(v)) => {
				let mut tmp = Inner::Owned(v.to_owned());
				core::mem::swap(&mut self.0, &mut tmp);
				let Inner::Owned(ref mut v) = self.0 else {
					unreachable!()
				};
				v
			}
			Inner::Shared(Shared::Ptr(ref mut v)) => Arc::make_mut(v),
			Inner::Owned(ref mut v) => v,
		}
	}

	/// Change the representation of this `Namespace` such that it can be
	/// cloned cheaply.
	///
	/// This may make the next call to a mutating method, such as
	/// [`make_mut`][`Self::make_mut`] more expensive as it may then require
	/// copying the data.
	pub fn make_shared(&mut self) {
		if let Inner::Owned(ref mut v) = self.0 {
			if let Some(result) = Self::try_share_static(v) {
				*self = result;
				return;
			}
			let mut tmp = String::new();
			core::mem::swap(&mut tmp, v);
			self.0 = Inner::Shared(Shared::Ptr(Arc::new(tmp)));
		}
	}

	/// Make this `Namespace` instance cheaply cloneable and clone it.
	///
	/// Because this may change the layout of the `Namespace` to make it
	/// efficiently cloneable, it requires mutating access.
	pub fn share(&mut self) -> Self {
		self.make_shared();
		self.clone()
	}

	/// Consume this `Namespace` instance, make it cheaply cloneable, and
	/// return it.
	pub fn shared(mut self) -> Self {
		self.make_shared();
		self.clone()
	}

	/// Clone this `Namespace` instance and then make sure that further
	/// clones from the returned value can be made efficiently.
	pub fn clone_shared(&self) -> Self {
		self.clone().shared()
	}

	/// Return a reference to the inner namespace name if it is not empty or
	/// `None` otherwise.
	pub fn as_namespace_name(&self) -> Option<&str> {
		let s = self.deref();
		if s.is_empty() {
			None
		} else {
			Some(s)
		}
	}

	/// Return true if this `Namespace` is the empty namespace name.
	///
	/// The empty namespace name is not a valid namespace and is thus used to
	/// identify unnamespaced elements.
	pub fn is_none(&self) -> bool {
		self.deref().is_empty()
	}

	/// Return true if this `Namespace` is a valid namespace name.
	pub fn is_some(&self) -> bool {
		!self.deref().is_empty()
	}

	/// Return a reference to the string slice inside this [`Namespace`].
	pub fn as_str(&self) -> &str {
		self.deref()
	}
}

impl Deref for Namespace {
	type Target = str;

	fn deref(&self) -> &Self::Target {
		match self.0 {
			Inner::Shared(Shared::Static(v)) => v,
			Inner::Shared(Shared::Ptr(ref v)) => v.deref().deref(),
			Inner::Owned(ref v) => v.deref(),
		}
	}
}

impl AsRef<str> for Namespace {
	fn as_ref(&self) -> &str {
		self.deref()
	}
}

impl Borrow<str> for Namespace {
	fn borrow(&self) -> &str {
		self.deref()
	}
}

impl Clone for Namespace {
	fn clone(&self) -> Self {
		Self(match self.0 {
			Inner::Shared(Shared::Static(v)) => Inner::Shared(Shared::Static(v)),
			Inner::Shared(Shared::Ptr(ref v)) => Inner::Shared(Shared::Ptr(Arc::clone(v))),
			Inner::Owned(ref v) => Inner::Owned(v.clone()),
		})
	}
}

impl fmt::Debug for Namespace {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		let mut wrapper = match self.0 {
			Inner::Shared(Shared::Static(_)) => f.debug_tuple("Namespace<{Static}>"),
			Inner::Shared(Shared::Ptr(_)) => f.debug_tuple("Namespace<{Ptr}>"),
			Inner::Owned(_) => f.debug_tuple("Namespace<{Owned}>"),
		};
		wrapper.field(&self.deref()).finish()
	}
}

impl fmt::Display for Namespace {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		<str as fmt::Display>::fmt(self.deref(), f)
	}
}

impl Eq for Namespace {}

impl From<Namespace> for String {
	fn from(other: Namespace) -> Self {
		match other.0 {
			Inner::Owned(v) => v,
			Inner::Shared(Shared::Static(v)) => v.to_owned(),
			Inner::Shared(Shared::Ptr(v)) => Arc::unwrap_or_clone(v),
		}
	}
}

impl From<Namespace> for Arc<String> {
	fn from(other: Namespace) -> Self {
		match other.0 {
			Inner::Owned(v) => Arc::new(v),
			Inner::Shared(Shared::Static(v)) => Arc::new(v.to_owned()),
			Inner::Shared(Shared::Ptr(v)) => v,
		}
	}
}

impl From<Name> for Namespace {
	fn from(other: Name) -> Self {
		let v: String = other.into();
		debug_assert!(!v.is_empty()); // enforced by Name
		Self(Inner::Owned(v))
	}
}

impl From<NcName> for Namespace {
	fn from(other: NcName) -> Self {
		let v: String = other.into();
		debug_assert!(!v.is_empty()); // enforced by NcName
		Self(Inner::Owned(v))
	}
}

impl From<&'static Name> for Namespace {
	fn from(other: &'static Name) -> Self {
		let v: &'static str = other.as_ref();
		debug_assert!(!v.is_empty()); // enforced by NameStr
		Self(Inner::Shared(Shared::Static(v)))
	}
}

impl From<&'static NcName> for Namespace {
	fn from(other: &'static NcName) -> Self {
		let v: &'static str = other.as_ref();
		debug_assert!(!v.is_empty()); // enforced by NcNameStr
		Self(Inner::Shared(Shared::Static(v)))
	}
}

impl From<&'static str> for Namespace {
	fn from(other: &'static str) -> Self {
		Self(Inner::Shared(Shared::Static(other)))
	}
}

impl From<String> for Namespace {
	fn from(other: String) -> Self {
		if let Some(result) = Self::try_share_static(&other) {
			return result;
		}
		Self(Inner::Owned(other))
	}
}

impl From<Arc<String>> for Namespace {
	fn from(other: Arc<String>) -> Self {
		if let Some(result) = Self::try_share_static(&other) {
			return result;
		}
		Self(Inner::Shared(Shared::Ptr(other)))
	}
}

impl Hash for Namespace {
	fn hash<H: Hasher>(&self, h: &mut H) {
		self.deref().hash(h)
	}
}

impl Ord for Namespace {
	fn cmp(&self, other: &Namespace) -> Ordering {
		self.deref().cmp(other.deref())
	}
}

impl PartialEq for Namespace {
	fn eq(&self, other: &Namespace) -> bool {
		self.deref() == other.deref()
	}
}

impl PartialEq<&str> for Namespace {
	fn eq(&self, other: &&str) -> bool {
		self.deref() == *other
	}
}

impl PartialEq<Namespace> for &str {
	fn eq(&self, other: &Namespace) -> bool {
		*self == other.deref()
	}
}

impl PartialEq<str> for Namespace {
	fn eq(&self, other: &str) -> bool {
		self.deref() == other
	}
}

impl PartialEq<Namespace> for str {
	fn eq(&self, other: &Namespace) -> bool {
		self == other.deref()
	}
}

impl PartialOrd for Namespace {
	fn partial_cmp(&self, other: &Namespace) -> Option<Ordering> {
		Some(self.cmp(other))
	}
}

/**
Check whether a str is valid XML 1.0 CData

# Example

```rust
use rxml::Error;
use rxml::strings::validate_cdata;

assert!(validate_cdata("foo bar baz <fnord!>").is_ok());
assert!(matches!(validate_cdata("\x01"), Err(Error::UnexpectedChar(_, '\x01', _))));
*/
pub fn validate_cdata(s: &str) -> Result<(), XmlError> {
	rxml_validation::validate_cdata(s).map_err(|e| XmlError::from_validation(e, None))
}

/**
Check whether a str is a valid XML 1.0 Name

**Note:** This does *not* enforce that the name contains only a single colon.

# Example

```rust
use rxml::Error;
use rxml::strings::validate_name;

assert!(validate_name("foobar").is_ok());
assert!(validate_name("foo:bar").is_ok());
assert!(matches!(validate_name("foo bar"), Err(Error::UnexpectedChar(_, ' ', _))));
assert!(matches!(validate_name(""), Err(Error::InvalidSyntax(_))));
*/
pub fn validate_name(s: &str) -> Result<(), XmlError> {
	rxml_validation::validate_name(s)
		.map_err(|e| XmlError::from_validation(e, Some(ErrorContext::Name)))
}

/**
Check whether a str is a valid XML 1.0 Name, without colons.

# Example

```rust
use rxml::Error;
use rxml::strings::validate_ncname;

assert!(validate_ncname("foobar").is_ok());
assert!(matches!(validate_ncname("foo:bar"), Err(Error::MultiColonName(_))));
assert!(matches!(validate_ncname(""), Err(Error::EmptyNamePart(_))));
*/
pub fn validate_ncname(s: &str) -> Result<(), XmlError> {
	match rxml_validation::validate_ncname(s)
		.map_err(|e| XmlError::from_validation(e, Some(ErrorContext::Name)))
	{
		Err(XmlError::UnexpectedChar(ctx, ':', _)) => Err(XmlError::MultiColonName(ctx)),
		Err(XmlError::InvalidSyntax(_)) => Err(XmlError::EmptyNamePart(None)),
		other => other,
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn can_slice_namespace_name() {
		let nsn = Namespace::xml();
		assert_eq!(&nsn[..4], "http");
	}
}