reinhardt-http 0.4.0-alpha.6

HTTP primitives, request and response handling for Reinhardt
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
//! Ordered path parameter storage.
//!
//! `PathParams` preserves the order in which path parameters appear in the URL
//! pattern, which is essential for correct tuple-based extraction such as
//! `Path<(T1, T2)>`. Internally it uses inline storage for the common small
//! parameter sets, but it exposes a small subset of the `HashMap`-like API
//! (`get`, `iter`, `len`, `is_empty`, `insert`, `values`) so existing callers
//! can continue to look up parameters by name without any code changes.
//!
//! # Why ordered storage and not a `HashMap`?
//!
//! `HashMap` iteration order is non-deterministic. URL routers (matchit in
//! particular) yield parameters in URL declaration order, which is the order
//! users expect when destructuring `Path<(T1, T2)>`. Storing parameters as an
//! ordered sequence preserves that order all the way from the router to the
//! extractor.
//!
//! See issue #4013 for details.

use std::{collections::HashMap, sync::Arc};

use smallvec::SmallVec;

const INLINE_PARAM_CAPACITY: usize = 4;
const INLINE_VALUE_CAPACITY: usize = 32;
type PathParamNames = SmallVec<[String; INLINE_PARAM_CAPACITY]>;
type PathParamValues = SmallVec<[PathParamValue; INLINE_PARAM_CAPACITY]>;
type PathParamValueBytes = SmallVec<[u8; INLINE_VALUE_CAPACITY]>;

#[derive(Debug, Clone, PartialEq, Eq)]
struct PathParamValue {
	inner: PathParamValueBytes,
}

impl PathParamValue {
	fn as_str(&self) -> &str {
		std::str::from_utf8(&self.inner)
			.expect("path parameter values are created from valid UTF-8 strings")
	}

	fn into_string(self) -> String {
		String::from_utf8(self.inner.into_vec())
			.expect("path parameter values are created from valid UTF-8 strings")
	}
}

impl From<&str> for PathParamValue {
	fn from(value: &str) -> Self {
		Self {
			inner: PathParamValueBytes::from_slice(value.as_bytes()),
		}
	}
}

impl From<String> for PathParamValue {
	fn from(value: String) -> Self {
		Self {
			inner: value.into_bytes().into_iter().collect(),
		}
	}
}

impl From<&String> for PathParamValue {
	fn from(value: &String) -> Self {
		value.as_str().into()
	}
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum PathParamNameStorage {
	Owned(PathParamNames),
	Shared(Arc<[String]>),
}

impl Default for PathParamNameStorage {
	fn default() -> Self {
		Self::Owned(PathParamNames::new())
	}
}

impl PathParamNameStorage {
	fn with_capacity(capacity: usize) -> Self {
		Self::Owned(PathParamNames::with_capacity(capacity))
	}

	fn get(&self, index: usize) -> Option<&String> {
		match self {
			Self::Owned(names) => names.get(index),
			Self::Shared(names) => names.get(index),
		}
	}

	fn position(&self, key: &str) -> Option<usize> {
		match self {
			Self::Owned(names) => names.iter().position(|name| name == key),
			Self::Shared(names) => names.iter().position(|name| name == key),
		}
	}

	fn push(&mut self, key: String) {
		self.ensure_owned().push(key);
	}

	fn ensure_owned(&mut self) -> &mut PathParamNames {
		if let Self::Shared(names) = self {
			*self = Self::Owned(names.iter().cloned().collect());
		}
		match self {
			Self::Owned(names) => names,
			Self::Shared(_) => unreachable!("shared names are materialized before mutation"),
		}
	}
}

/// Iterator over `(key, value)` pairs in declaration order.
pub struct PathParamsIter<'a> {
	params: &'a PathParams,
	index: usize,
}

impl<'a> Iterator for PathParamsIter<'a> {
	type Item = (&'a String, &'a str);

	fn next(&mut self) -> Option<Self::Item> {
		let index = self.index;
		self.index += 1;
		Some((
			self.params.names.get(index)?,
			self.params.values.get(index)?.as_str(),
		))
	}

	fn size_hint(&self) -> (usize, Option<usize>) {
		let remaining = self.params.len().saturating_sub(self.index);
		(remaining, Some(remaining))
	}
}

impl ExactSizeIterator for PathParamsIter<'_> {}

/// Ordered collection of path parameters extracted from a URL pattern.
///
/// Preserves insertion order so that tuple extractors like `Path<(T1, T2)>`
/// can rely on URL pattern declaration order when populating tuple fields.
///
/// # Example
///
/// ```
/// use reinhardt_http::PathParams;
///
/// let mut params = PathParams::new();
/// params.insert("org", "myslug");
/// params.insert("cluster_id", "5");
///
/// // Insertion order is preserved.
/// let collected: Vec<_> = params.iter().map(|(k, v)| (k.as_str(), v)).collect();
/// assert_eq!(collected, vec![("org", "myslug"), ("cluster_id", "5")]);
///
/// // Named lookup still works.
/// assert_eq!(params.get("org"), Some("myslug"));
/// ```
#[derive(Debug, Clone, Default)]
pub struct PathParams {
	names: PathParamNameStorage,
	values: PathParamValues,
}

impl PartialEq for PathParams {
	fn eq(&self, other: &Self) -> bool {
		self.iter().eq(other.iter())
	}
}

impl Eq for PathParams {}

impl PathParams {
	/// Create a new, empty `PathParams`.
	pub fn new() -> Self {
		Self {
			names: PathParamNameStorage::default(),
			values: PathParamValues::new(),
		}
	}

	/// Create an empty `PathParams` with capacity for `capacity` entries.
	pub fn with_capacity(capacity: usize) -> Self {
		Self {
			names: PathParamNameStorage::with_capacity(capacity),
			values: PathParamValues::with_capacity(capacity),
		}
	}

	/// Build path params from shared route parameter names and request-local values.
	///
	/// Routers use this to avoid allocating key strings on every request.
	pub fn from_shared_names<I, V>(names: Arc<[String]>, values: I) -> Self
	where
		I: IntoIterator<Item = V>,
		V: AsRef<str>,
	{
		let mut path_values = PathParamValues::with_capacity(names.len());
		for value in values {
			path_values.push(PathParamValue::from(value.as_ref()));
		}
		assert_eq!(
			names.len(),
			path_values.len(),
			"shared path parameter names and values must have the same length"
		);
		Self {
			names: PathParamNameStorage::Shared(names),
			values: path_values,
		}
	}

	/// Number of stored parameters.
	pub fn len(&self) -> usize {
		self.values.len()
	}

	/// `true` if no parameters are stored.
	pub fn is_empty(&self) -> bool {
		self.values.is_empty()
	}

	/// Look up a parameter by name.
	///
	/// Returns the first match if multiple entries share the same name (which
	/// should not happen in practice because URL patterns require unique names).
	pub fn get(&self, key: &str) -> Option<&str> {
		let index = self.names.position(key)?;
		self.values.get(index).map(PathParamValue::as_str)
	}

	/// Insert or update a parameter.
	///
	/// If `key` already exists, its value is replaced and its position is kept.
	/// Otherwise the new entry is appended, preserving insertion order.
	pub fn insert(&mut self, key: impl Into<String>, value: impl AsRef<str>) {
		let key = key.into();
		let value = PathParamValue::from(value.as_ref());
		if let Some(index) = self.names.position(&key) {
			self.values[index] = value;
		} else {
			self.names.push(key);
			self.values.push(value);
		}
	}

	/// Iterate over `(key, value)` pairs in insertion order.
	pub fn iter(&self) -> PathParamsIter<'_> {
		PathParamsIter {
			params: self,
			index: 0,
		}
	}

	/// Iterate over values in insertion order.
	pub fn values(&self) -> impl Iterator<Item = &str> {
		self.values.iter().map(PathParamValue::as_str)
	}

	/// Clone the ordered `(key, value)` pairs into a `Vec`.
	pub fn to_vec(&self) -> Vec<(String, String)> {
		self.iter()
			.map(|(key, value)| (key.clone(), value.to_string()))
			.collect()
	}

	/// Consume the wrapper and return the inner ordered `Vec`.
	pub fn into_vec(self) -> Vec<(String, String)> {
		match self.names {
			PathParamNameStorage::Owned(names) => names
				.into_iter()
				.zip(self.values.into_iter().map(PathParamValue::into_string))
				.collect(),
			PathParamNameStorage::Shared(names) => names
				.iter()
				.cloned()
				.zip(self.values.into_iter().map(PathParamValue::into_string))
				.collect(),
		}
	}
}

impl<K, V> FromIterator<(K, V)> for PathParams
where
	K: Into<String>,
	V: AsRef<str>,
{
	fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
		let mut params = PathParams::new();
		for (k, v) in iter {
			params.insert(k, v);
		}
		params
	}
}

impl IntoIterator for PathParams {
	type Item = (String, String);
	type IntoIter = std::vec::IntoIter<(String, String)>;

	fn into_iter(self) -> Self::IntoIter {
		self.into_vec().into_iter()
	}
}

impl<'a> IntoIterator for &'a PathParams {
	type Item = (&'a String, &'a str);
	type IntoIter = PathParamsIter<'a>;

	fn into_iter(self) -> Self::IntoIter {
		self.iter()
	}
}

impl From<Vec<(String, String)>> for PathParams {
	fn from(inner: Vec<(String, String)>) -> Self {
		// Caller is responsible for the ordering of the supplied vector.
		let mut params = Self::with_capacity(inner.len());
		for (key, value) in inner {
			params.insert(key, value);
		}
		params
	}
}

impl From<HashMap<String, String>> for PathParams {
	/// Convert from a `HashMap`. Iteration order is **not** preserved because
	/// `HashMap` does not have a defined order. Prefer `From<Vec<_>>` when
	/// order matters.
	fn from(map: HashMap<String, String>) -> Self {
		map.into_iter().collect()
	}
}

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

	#[rstest]
	fn insert_preserves_order() {
		// Arrange
		let mut params = PathParams::new();

		// Act
		params.insert("z", "first");
		params.insert("a", "second");
		params.insert("m", "third");

		// Assert
		let order: Vec<&str> = params.iter().map(|(k, _)| k.as_str()).collect();
		assert_eq!(order, vec!["z", "a", "m"]);
	}

	#[rstest]
	fn get_finds_by_name() {
		// Arrange
		let mut params = PathParams::new();
		params.insert("org", "myslug");
		params.insert("cluster_id", "5");

		// Act
		let org = params.get("org");
		let cluster_id = params.get("cluster_id");
		let missing = params.get("missing");

		// Assert
		assert_eq!(org, Some("myslug"));
		assert_eq!(cluster_id, Some("5"));
		assert_eq!(missing, None);
	}

	#[rstest]
	fn insert_replaces_existing_in_place() {
		// Arrange
		let mut params = PathParams::new();
		params.insert("a", "1");
		params.insert("b", "2");

		// Act
		params.insert("a", "updated");

		// Assert: order unchanged, value replaced
		let collected: Vec<_> = params.iter().map(|(k, v)| (k.as_str(), v)).collect();
		assert_eq!(collected, vec![("a", "updated"), ("b", "2")]);
	}

	#[rstest]
	fn from_vec_preserves_caller_order() {
		// Arrange
		let vec = vec![
			("org".to_string(), "myslug".to_string()),
			("cluster_id".to_string(), "5".to_string()),
		];

		// Act
		let params = PathParams::from(vec);

		// Assert
		let order: Vec<&str> = params.iter().map(|(k, _)| k.as_str()).collect();
		assert_eq!(order, vec!["org", "cluster_id"]);
	}

	#[rstest]
	fn from_iter_collects_in_order() {
		// Arrange
		let pairs = vec![("z", "1"), ("a", "2")];

		// Act
		let params: PathParams = pairs.into_iter().collect();

		// Assert
		let order: Vec<&str> = params.iter().map(|(k, _)| k.as_str()).collect();
		assert_eq!(order, vec!["z", "a"]);
	}

	#[rstest]
	fn consuming_iterator_keeps_public_vec_iterator_type() {
		// Arrange
		let params = PathParams::from(vec![("org".to_string(), "myslug".to_string())]);

		// Act
		let mut iter: std::vec::IntoIter<(String, String)> = params.into_iter();

		// Assert
		assert_eq!(iter.next(), Some(("org".to_string(), "myslug".to_string())));
		assert_eq!(iter.next(), None);
	}
}