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
use std::fmt;

/// Formats the arguments while escaping `&<>"'` with their equivalent entities.
///
/// Accepts an expression or a [string template](crate::template!).
///
/// # Examples
///
/// ```
/// # use format_xml::escape;
/// assert_eq!(
/// 	escape!({"Friday"} "'s the " {13} "th").to_string(),
/// 	"Friday&apos;s the 13th");
/// assert_eq!(
/// 	escape!("<script>alert(" {42;#x} ")</script>").to_string(),
/// 	"&lt;script&gt;alert(0x2a)&lt;/script&gt;");
/// ```
#[macro_export]
macro_rules! escape {
	($e:expr) => {
		$crate::escape($e)
	};
	({$e:expr}) => {
		$crate::escape($e)
	};
	($($tt:tt)*) => {
		$crate::escape($crate::fmt(|_f| { $crate::_template_!({_f} $($tt)*); Ok(()) }))
	};
}

/// Escapes `&<>"'` with their equivalent entities.
///
/// ```
/// # use format_xml::escape;
/// assert_eq!(escape("&<>\"\'").to_string(), "&amp;&lt;&gt;&quot;&apos;");
/// ```
#[inline]
pub fn escape<T: fmt::Display>(value: T) -> impl fmt::Display {
	fn inner(s: &str, f: &mut fmt::Formatter) -> fmt::Result {
		let mut start = 0;
		for i in 0..s.len() {
			let replace = match s.as_bytes()[i] {
				b'&' => "&amp;",
				b'<' => "&lt;",
				b'>' => "&gt;",
				b'\'' => "&apos;",
				b'\"' => "&quot;",
				_ => continue,
			};
			let pre = unsafe { s.get_unchecked(start..i) };
			if pre.len() > 0 {
				f.write_str(pre)?;
			}
			f.write_str(replace)?;
			start = i + 1;
		}
		let post = unsafe { s.get_unchecked(start..) };
		if post.len() > 0 {
			f.write_str(post)?;
		}
		Ok(())
	}
	crate::fmt(move |f| {
		inner(&value.to_string(), f)
	})
}

#[test]
fn test_escape() {
	fn check(input: &str, escaped: &str) {
		assert_eq!(escape(input).to_string(), escaped);
	}
	check("hello", "hello");
	check("'world'", "&apos;world&apos;");
	check("pre<script>post", "pre&lt;script&gt;post");
	check("&<>\"\'", "&amp;&lt;&gt;&quot;&apos;");
	check("&a'b<c>", "&amp;a&apos;b&lt;c&gt;");
}

//----------------------------------------------------------------

/// Displays an iterable with given separator between each item.
///
/// ```
/// # use format_xml::join;
/// let result = join("--", &[1, 2, 3, 4]).to_string();
/// assert_eq!(result, "1--2--3--4");
/// ```
#[inline]
pub fn join<T>(sep: &'static str, collection: T) -> impl fmt::Display where T: IntoIterator, <T as IntoIterator>::Item: fmt::Display, <T as IntoIterator>::IntoIter: Clone {
	let iter = collection.into_iter();
	crate::fmt(move |f| {
		let mut draw = false;
		for item in iter.clone() {
			if sep.len() > 0 {
				if draw {
					f.write_str(sep)?;
				}
				draw = true;
			}
			fmt::Display::fmt(&item, f)?;
		}
		Ok(())
	})
}

/// Displays an iterable with spaces between each item.
///
/// ```
/// # use format_xml::spaced;
/// let result = spaced(&[1, 2, 3, 4]).to_string();
/// assert_eq!(result, "1 2 3 4");
/// ```
#[inline]
pub fn spaced<T>(collection: T) -> impl fmt::Display where T: IntoIterator, <T as IntoIterator>::Item: fmt::Display, <T as IntoIterator>::IntoIter: Clone {
	join(" ", collection)
}

/// Displays an iterable with commas between each item.
///
/// ```
/// # use format_xml::csv;
/// let result = csv(&[1, 2, 3, 4]).to_string();
/// assert_eq!(result, "1,2,3,4");
/// ```
#[inline]
pub fn csv<T>(collection: T) -> impl fmt::Display where T: IntoIterator, <T as IntoIterator>::Item: fmt::Display, <T as IntoIterator>::IntoIter: Clone {
	join(",", collection)
}

//----------------------------------------------------------------

#[doc(hidden)]
#[macro_export]
macro_rules! _join_impl_ {
	(concat!($($fmt:expr,)*), $($arg:expr,)*; $s:literal; $sep:literal, $e:expr, ) => {
		$crate::fmt(move |f| {
			f.write_fmt(format_args!(concat!($($fmt,)* $s), $($arg,)* $e))
		})
	};
	(concat!($($fmt:expr,)*), $($arg:expr,)*; $s:literal; $sep:literal, $e:expr, $($tail:expr,)*) => {
		$crate::_join_impl_!(concat!($($fmt,)* $s, $sep,), $($arg,)* $e,; $s; $sep, $($tail,)*)
	};
}

/// Displays the arguments joined with the given separator.
///
/// The arguments are moved instead of captured by reference unlike `format_args!`.
///
/// ```
/// # use format_xml::join;
/// let result = join!("--", 1, 2.0, true).to_string();
/// assert_eq!(result, "1--2--true");
/// ```
///
/// Optionally, the formatting can be specified:
///
/// ```
/// # use format_xml::join;
/// let result = join!("--", 10, 11, 12; "{:#x}").to_string();
/// assert_eq!(result, "0xa--0xb--0xc");
/// ```
#[macro_export]
macro_rules! join {
	($sep:literal, $($e:expr),+) => {
		$crate::_join_impl_!(concat!(), ; "{}"; $sep, $($e,)+)
	};
	($sep:literal, $($e:expr),+; $s:literal) => {
		$crate::_join_impl_!(concat!(), ; $s; $sep, $($e,)+)
	};
}

/// Displays the arguments as comma-separated values.
///
/// The arguments are moved instead of captured by reference unlike `format_args!`.
///
/// ```
/// # use format_xml::csv;
/// let result = csv!(1, 2.0, true).to_string();
/// assert_eq!(result, "1,2,true");
/// ```
///
/// Optionally, the formatting can be specified:
///
/// ```
/// # use format_xml::csv;
/// let result = csv!(10, 11, 12; "{:#x}").to_string();
/// assert_eq!(result, "0xa,0xb,0xc");
/// ```
#[macro_export]
macro_rules! csv {
	($($e:expr),+) => {
		$crate::_join_impl_!(concat!(), ; "{}"; ",", $($e,)+)
	};
	($($e:expr),+; $s:literal) => {
		$crate::_join_impl_!(concat!(), ; $s; ",", $($e,)+)
	};
}

/// Displays the arguments as space-separated values.
///
/// The arguments are moved instead of captured by reference unlike `format_args!`.
///
/// ```
/// # use format_xml::spaced;
/// let result = spaced!(1, 2.0, true).to_string();
/// assert_eq!(result, "1 2 true");
/// ```
///
/// Optionally, the formatting can be specified:
///
/// ```
/// # use format_xml::spaced;
/// let result = spaced!(10, 11, 12; "{:#x}").to_string();
/// assert_eq!(result, "0xa 0xb 0xc");
/// ```
#[macro_export]
macro_rules! spaced {
	($($e:expr),+) => {
		$crate::_join_impl_!(concat!(), ; "{}"; " ", $($e,)+)
	};
	($($e:expr),+; $s:literal) => {
		$crate::_join_impl_!(concat!(), ; $s; " ", $($e,)+)
	};
}