reinhardt-urls 0.3.0

URL routing and proxy utilities for Reinhardt framework
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
//! Path parameter extraction for typed route handlers.
//!
//! This module provides typed parameter extraction from URL paths,
//! similar to backend's `Path<T>` extractor.

use std::collections::HashMap;
use std::ops::Deref;

use super::error::PathError;

/// Context for parameter extraction.
///
/// Contains both named parameters (for backward compatibility)
/// and ordered parameter values (for tuple extraction).
#[derive(Debug, Clone)]
pub struct ParamContext {
	/// Matched path without the query string.
	///
	/// Populated by [`ClientRouter::render_current`] for routes registered
	/// via [`ClientRouter::page`] so [`RouteContext::path`] can expose the
	/// router's matched path to [`FromRequest`] implementations.
	///
	/// `None` for direct test construction and for routes registered via
	/// the legacy `route` / `route_params` / `route_result` / `route_path*`
	/// APIs (those handlers do not read the path through `RouteContext`).
	///
	/// [`ClientRouter::render_current`]: super::core::ClientRouter::render_current
	/// [`ClientRouter::page`]: super::core::ClientRouter::page
	/// [`RouteContext::path`]: super::from_request::RouteContext::path
	/// [`FromRequest`]: super::from_request::FromRequest
	pub(crate) path: Option<String>,
	/// Named parameters extracted from the path.
	pub(crate) params: HashMap<String, String>,
	/// Parameter values in the order they appear in the pattern.
	///
	/// This guarantees that tuple extraction works correctly by index,
	/// matching the order of parameters in the URL pattern.
	pub(crate) param_values: Vec<String>,
	/// Raw query string (without the leading `?`), populated by
	/// [`ClientRouter::render_current`] for routes registered via
	/// [`ClientRouter::page`] so [`QueryParam<T>`] can extract values.
	///
	/// `None` for paths without a `?` segment or for routes registered
	/// via the legacy `route` / `route_params` / `route_result` /
	/// `route_path*` APIs (those handlers do not read the query).
	///
	/// [`ClientRouter::render_current`]: super::core::ClientRouter::render_current
	/// [`ClientRouter::page`]: super::core::ClientRouter::page
	/// [`QueryParam<T>`]: super::from_request::QueryParam
	pub(crate) query: Option<String>,
}

impl ParamContext {
	/// Creates a new parameter context.
	pub fn new(params: HashMap<String, String>, param_values: Vec<String>) -> Self {
		Self {
			path: None,
			params,
			param_values,
			query: None,
		}
	}

	/// Creates a new parameter context with an attached matched path.
	///
	/// Used by [`ClientRouter::render_current`] when dispatching a
	/// [`ClientRouter::page`] handler so [`RouteContext::path`] exposes
	/// the matched path without any query string.
	///
	/// [`ClientRouter::render_current`]: super::core::ClientRouter::render_current
	/// [`ClientRouter::page`]: super::core::ClientRouter::page
	/// [`RouteContext::path`]: super::from_request::RouteContext::path
	pub fn with_path(mut self, path: String) -> Self {
		self.path = Some(path);
		self
	}

	/// Creates a new parameter context with an attached query string.
	///
	/// Used by [`ClientRouter::render_current`] when dispatching a
	/// [`ClientRouter::page`] handler so [`QueryParam<T>`] extractors
	/// can see the captured query.
	///
	/// [`ClientRouter::render_current`]: super::core::ClientRouter::render_current
	/// [`ClientRouter::page`]: super::core::ClientRouter::page
	/// [`QueryParam<T>`]: super::from_request::QueryParam
	pub fn with_query(mut self, query: Option<String>) -> Self {
		self.query = query;
		self
	}

	/// Returns the named-parameter map (path parameters captured by the
	/// route pattern, keyed by their `{name}` placeholder).
	pub fn params(&self) -> &HashMap<String, String> {
		&self.params
	}

	/// Returns the matched path (without the query string), if present.
	pub fn path(&self) -> Option<&str> {
		self.path.as_deref()
	}

	/// Returns the raw query string (without the leading `?`), if any.
	pub fn query(&self) -> Option<&str> {
		self.query.as_deref()
	}

	/// Returns the number of parameters.
	pub fn len(&self) -> usize {
		self.param_values.len()
	}

	/// Returns whether there are no parameters.
	pub fn is_empty(&self) -> bool {
		self.param_values.is_empty()
	}
}

/// Trait for extracting typed values from path parameters.
///
/// This trait is similar to the backend's `FromRequest` trait,
/// but simplified for client-side routing (no async required).
pub trait FromPath: Sized {
	/// Extracts Self from the parameter context.
	///
	/// # Errors
	///
	/// Returns [`PathError::CountMismatch`] if the number of parameters doesn't match.
	/// Returns [`PathError::ParseError`] if parameter parsing fails.
	fn from_path(ctx: &ParamContext) -> Result<Self, PathError>;
}

/// Single path parameter extractor.
///
/// This is the primary type for extracting path parameters from URLs.
/// Use multiple `Path<T>` arguments for routes with multiple parameters.
///
/// # Example
///
/// ```ignore
/// use reinhardt_urls::routers::client_router::Path;
///
/// // Single parameter
/// fn user_detail(Path(id): Path<i64>) -> View {
///     user_page(id)
/// }
///
/// // Multiple parameters (use multiple Path arguments)
/// fn post_detail(Path(user_id): Path<i64>, Path(post_id): Path<i64>) -> View {
///     post_page(user_id, post_id)
/// }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Path<T>(pub T);

impl<T> Path<T> {
	/// Unwraps the inner value.
	pub fn into_inner(self) -> T {
		self.0
	}
}

impl<T> Deref for Path<T> {
	type Target = T;

	fn deref(&self) -> &Self::Target {
		&self.0
	}
}

impl<T> AsRef<T> for Path<T> {
	fn as_ref(&self) -> &T {
		&self.0
	}
}

// Macro for implementing FromPath for primitive types
macro_rules! impl_from_path_for_primitive {
	($($ty:ty => $type_name:expr),* $(,)?) => {
		$(
			impl FromPath for $ty {
				fn from_path(ctx: &ParamContext) -> Result<Self, PathError> {
					if ctx.param_values.len() != 1 {
						return Err(PathError::CountMismatch {
							expected: 1,
							actual: ctx.param_values.len(),
						});
					}

					ctx.param_values[0]
						.parse::<$ty>()
						.map_err(|e| PathError::ParseError {
							param_index: Some(0),
							param_type: $type_name,
							raw_value: ctx.param_values[0].clone(),
							source: format!("{}", e),
						})
				}
			}
		)*
	};
}

// Implement FromPath for common primitive types
impl_from_path_for_primitive! {
	i32 => "i32",
	i64 => "i64",
	u32 => "u32",
	u64 => "u64",
	bool => "bool",
}

// Special implementation for String (no parsing needed)
impl FromPath for String {
	fn from_path(ctx: &ParamContext) -> Result<Self, PathError> {
		if ctx.param_values.len() != 1 {
			return Err(PathError::CountMismatch {
				expected: 1,
				actual: ctx.param_values.len(),
			});
		}

		Ok(ctx.param_values[0].clone())
	}
}

// Implementation for Path<T>
impl<T: FromPath> FromPath for Path<T> {
	fn from_path(ctx: &ParamContext) -> Result<Self, PathError> {
		T::from_path(ctx).map(Path)
	}
}

/// Trait for extracting a single value at a specific index from path parameters.
///
/// This is used internally to support the multi-argument `Path<T>` style:
/// `|Path(user_id): Path<Uuid>, Path(post_id): Path<i64>|`
pub trait SingleFromPath: Sized {
	/// Extracts a single value at the given index.
	fn from_path_at(ctx: &ParamContext, index: usize) -> Result<Self, PathError>;
}

// Implement SingleFromPath for types that implement FromStr
impl<T> SingleFromPath for T
where
	T: std::str::FromStr,
	T::Err: std::fmt::Display,
{
	fn from_path_at(ctx: &ParamContext, index: usize) -> Result<Self, PathError> {
		if index >= ctx.param_values.len() {
			return Err(PathError::CountMismatch {
				expected: index + 1,
				actual: ctx.param_values.len(),
			});
		}

		ctx.param_values[index]
			.parse::<T>()
			.map_err(|e| PathError::ParseError {
				param_index: Some(index),
				param_type: std::any::type_name::<T>(),
				raw_value: ctx.param_values[index].clone(),
				source: format!("{}", e),
			})
	}
}

// Helper macro for parsing tuple elements
macro_rules! parse_tuple_element {
	($ctx:expr, $idx:expr, $ty:ty) => {{
		if $idx >= $ctx.param_values.len() {
			return Err(PathError::CountMismatch {
				expected: $idx + 1,
				actual: $ctx.param_values.len(),
			});
		}

		$ctx.param_values[$idx]
			.parse::<$ty>()
			.map_err(|e| PathError::ParseError {
				param_index: Some($idx),
				param_type: std::any::type_name::<$ty>(),
				raw_value: $ctx.param_values[$idx].clone(),
				source: format!("{}", e),
			})?
	}};
}

// Macro for implementing FromPath for tuples
macro_rules! impl_from_path_for_tuple {
	($($idx:tt => $ty:ident),+ $(,)?) => {
		impl<$($ty),+> FromPath for ($($ty,)+)
		where
			$($ty: std::str::FromStr,)+
			$(<$ty as std::str::FromStr>::Err: std::fmt::Display,)+
		{
			fn from_path(ctx: &ParamContext) -> Result<Self, PathError> {
				let expected_count = [$($idx),+].len();
				if ctx.param_values.len() != expected_count {
					return Err(PathError::CountMismatch {
						expected: expected_count,
						actual: ctx.param_values.len(),
					});
				}

				Ok((
					$(parse_tuple_element!(ctx, $idx, $ty),)+
				))
			}
		}
	};
}

// Implement FromPath for tuples of 2 to 6 elements
impl_from_path_for_tuple!(0 => A, 1 => B);
impl_from_path_for_tuple!(0 => A, 1 => B, 2 => C);
impl_from_path_for_tuple!(0 => A, 1 => B, 2 => C, 3 => D);
impl_from_path_for_tuple!(0 => A, 1 => B, 2 => C, 3 => D, 4 => E);
impl_from_path_for_tuple!(0 => A, 1 => B, 2 => C, 3 => D, 4 => E, 5 => F);

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

	#[test]
	fn test_param_context_new() {
		let mut params = HashMap::new();
		params.insert("id".to_string(), "42".to_string());
		let param_values = vec!["42".to_string()];

		let ctx = ParamContext::new(params.clone(), param_values.clone());

		assert_eq!(ctx.params, params);
		assert_eq!(ctx.param_values, param_values);
		assert_eq!(ctx.len(), 1);
		assert!(!ctx.is_empty());
	}

	#[test]
	fn test_param_context_empty() {
		let ctx = ParamContext::new(HashMap::new(), Vec::new());

		assert_eq!(ctx.len(), 0);
		assert!(ctx.is_empty());
	}

	#[test]
	fn test_path_deref() {
		let params = Path(42i64);
		assert_eq!(*params, 42);
	}

	#[test]
	fn test_path_into_inner() {
		let params = Path("hello".to_string());
		assert_eq!(params.into_inner(), "hello");
	}

	#[test]
	fn test_path_as_ref() {
		let params = Path(42i64);
		let value: &i64 = params.as_ref();
		assert_eq!(*value, 42);
	}

	// FromPath implementation tests
	#[test]
	fn test_from_path_i32() {
		let mut params = HashMap::new();
		params.insert("id".to_string(), "42".to_string());
		let ctx = ParamContext::new(params, vec!["42".to_string()]);

		let result = i32::from_path(&ctx);
		assert!(result.is_ok());
		assert_eq!(result.unwrap(), 42);
	}

	#[test]
	fn test_from_path_i64() {
		let ctx = ParamContext::new(HashMap::new(), vec!["9223372036854775807".to_string()]);

		let result = i64::from_path(&ctx);
		assert!(result.is_ok());
		assert_eq!(result.unwrap(), 9223372036854775807);
	}

	#[test]
	fn test_from_path_u32() {
		let ctx = ParamContext::new(HashMap::new(), vec!["42".to_string()]);

		let result = u32::from_path(&ctx);
		assert!(result.is_ok());
		assert_eq!(result.unwrap(), 42);
	}

	#[test]
	fn test_from_path_u64() {
		let ctx = ParamContext::new(HashMap::new(), vec!["18446744073709551615".to_string()]);

		let result = u64::from_path(&ctx);
		assert!(result.is_ok());
		assert_eq!(result.unwrap(), 18446744073709551615);
	}

	#[test]
	fn test_from_path_bool() {
		let ctx_true = ParamContext::new(HashMap::new(), vec!["true".to_string()]);
		let result = bool::from_path(&ctx_true);
		assert!(result.is_ok());
		assert!(result.unwrap());

		let ctx_false = ParamContext::new(HashMap::new(), vec!["false".to_string()]);
		let result = bool::from_path(&ctx_false);
		assert!(result.is_ok());
		assert!(!result.unwrap());
	}

	#[test]
	fn test_from_path_string() {
		let ctx = ParamContext::new(HashMap::new(), vec!["hello".to_string()]);

		let result = String::from_path(&ctx);
		assert!(result.is_ok());
		assert_eq!(result.unwrap(), "hello");
	}

	#[test]
	fn test_from_path_parse_error() {
		let ctx = ParamContext::new(HashMap::new(), vec!["not_a_number".to_string()]);

		let result = i32::from_path(&ctx);
		assert!(result.is_err());

		match result {
			Err(PathError::ParseError {
				param_index,
				param_type,
				raw_value,
				..
			}) => {
				assert_eq!(param_index, Some(0));
				assert_eq!(param_type, "i32");
				assert_eq!(raw_value, "not_a_number");
			}
			_ => panic!("Expected ParseError"),
		}
	}

	#[test]
	fn test_from_path_count_mismatch() {
		let ctx = ParamContext::new(HashMap::new(), vec!["42".to_string(), "43".to_string()]);

		let result = i32::from_path(&ctx);
		assert!(result.is_err());

		match result {
			Err(PathError::CountMismatch { expected, actual }) => {
				assert_eq!(expected, 1);
				assert_eq!(actual, 2);
			}
			_ => panic!("Expected CountMismatch"),
		}
	}

	#[test]
	fn test_path_from_path() {
		let ctx = ParamContext::new(HashMap::new(), vec!["42".to_string()]);

		let result = Path::<i32>::from_path(&ctx);
		assert!(result.is_ok());
		assert_eq!(result.unwrap().0, 42);
	}

	// Tuple FromPath implementation tests
	#[test]
	fn test_from_path_tuple_2() {
		let ctx = ParamContext::new(HashMap::new(), vec!["42".to_string(), "hello".to_string()]);

		let result = <(i32, String)>::from_path(&ctx);
		assert!(result.is_ok());
		let (a, b) = result.unwrap();
		assert_eq!(a, 42);
		assert_eq!(b, "hello");
	}

	#[test]
	fn test_from_path_tuple_3() {
		let ctx = ParamContext::new(
			HashMap::new(),
			vec!["42".to_string(), "true".to_string(), "100".to_string()],
		);

		let result = <(i32, bool, u32)>::from_path(&ctx);
		assert!(result.is_ok());
		let (a, b, c) = result.unwrap();
		assert_eq!(a, 42);
		assert!(b);
		assert_eq!(c, 100);
	}

	#[test]
	fn test_from_path_tuple_mixed_types() {
		let ctx = ParamContext::new(
			HashMap::new(),
			vec![
				"123".to_string(),
				"456".to_string(),
				"test".to_string(),
				"true".to_string(),
			],
		);

		let result = <(i64, u64, String, bool)>::from_path(&ctx);
		assert!(result.is_ok());
		let (a, b, c, d) = result.unwrap();
		assert_eq!(a, 123);
		assert_eq!(b, 456);
		assert_eq!(c, "test");
		assert!(d);
	}

	#[test]
	fn test_from_path_tuple_count_mismatch() {
		let ctx = ParamContext::new(HashMap::new(), vec!["42".to_string()]);

		let result = <(i32, String)>::from_path(&ctx);
		assert!(result.is_err());

		match result {
			Err(PathError::CountMismatch { expected, actual }) => {
				assert_eq!(expected, 2);
				assert_eq!(actual, 1);
			}
			_ => panic!("Expected CountMismatch"),
		}
	}

	#[test]
	fn test_from_path_tuple_parse_error() {
		let ctx = ParamContext::new(
			HashMap::new(),
			vec!["not_a_number".to_string(), "hello".to_string()],
		);

		let result = <(i32, String)>::from_path(&ctx);
		assert!(result.is_err());

		match result {
			Err(PathError::ParseError {
				param_index,
				raw_value,
				..
			}) => {
				assert_eq!(param_index, Some(0));
				assert_eq!(raw_value, "not_a_number");
			}
			_ => panic!("Expected ParseError"),
		}
	}

	#[test]
	fn test_from_path_tuple_6_elements() {
		let ctx = ParamContext::new(
			HashMap::new(),
			vec![
				"1".to_string(),
				"2".to_string(),
				"3".to_string(),
				"4".to_string(),
				"5".to_string(),
				"6".to_string(),
			],
		);

		let result = <(i32, i32, i32, i32, i32, i32)>::from_path(&ctx);
		assert!(result.is_ok());
		let (a, b, c, d, e, f) = result.unwrap();
		assert_eq!((a, b, c, d, e, f), (1, 2, 3, 4, 5, 6));
	}
}