Skip to main content

vld_web/
common.rs

1//! Shared HTTP helpers for the `vld` web integrations.
2//!
3//! The common parsing helpers and the shared [`VldHttpError`] type used by
4//! every framework module of this crate.
5//!
6//! Applications normally use it through a framework module. Use it
7//! directly to write an adapter for another framework or to build the same
8//! error body by hand. It is framework-agnostic: no HTTP framework or `http`
9//! crate dependency.
10//!
11//! Guide: <https://s00d.github.io/vld/integrations/web/common>
12//! (the rules below, per framework:
13//! <https://s00d.github.io/vld/integrations/web/overview>).
14//!
15//! # Example
16//!
17//! ```
18//! use vld_web::common::{parse_json_body, require_json_content_type, VldHttpError};
19//!
20//! vld::schema! {
21//!     #[derive(Debug)]
22//!     pub struct User {
23//!         pub name: String => vld::string().min(2),
24//!     }
25//! }
26//!
27//! fn extract(content_type: Option<&str>, body: &[u8]) -> Result<User, VldHttpError> {
28//!     require_json_content_type(content_type)?; // 415
29//!     let value = parse_json_body(body)?;       // 422 on malformed JSON
30//!     Ok(User::parse_value(&value)?)            // 422 on validation errors
31//! }
32//!
33//! let err = extract(Some("application/json"), br#"{"name": "A"}"#).unwrap_err();
34//! assert_eq!(err.status(), 422);
35//! assert_eq!(err.body()["issues"][0]["code"], "too_small");
36//! assert_eq!(extract(Some("text/plain"), b"{}").unwrap_err().status(), 415);
37//!
38//! // Text sources (query, form, path, headers, cookies) use `parse_coerced`.
39//! vld::schema! {
40//!     #[derive(Debug)]
41//!     pub struct Search {
42//!         pub q: String => vld::string(),
43//!         pub page: i64 => vld::number().int().min(1),
44//!         pub tags: Vec<String> => vld::array(vld::string()),
45//!     }
46//! }
47//!
48//! let value = vld_web::common::query_string_to_json("q=123&page=2&tags=a");
49//! let s: Search = vld_web::common::parse_coerced(&value).unwrap();
50//! assert_eq!((s.q.as_str(), s.page, s.tags.len()), ("123", 2, 1));
51//! ```
52//!
53//! # Value semantics (all adapters)
54//!
55//! - Query strings and form bodies: repeated keys (`a=1&a=2`) and `a[]=1`
56//!   become arrays; `?flag` and `?x=` become `""`.
57//! - Values are coerced with [`coerce_value`], which never loses information.
58//! - Coerced sources are validated with [`parse_coerced`]: a coerced number /
59//!   boolean is turned back into text where the schema expects a string
60//!   (`?q=123` into `vld::string()` is `"123"`), and a single value is
61//!   wrapped into an array where the schema expects one (`?tags=a`).
62//! - JSON body extractors require a JSON `Content-Type` (`application/json`
63//!   or `application/*+json`, see [`is_json_content_type`]) and form
64//!   extractors `application/x-www-form-urlencoded`
65//!   ([`require_form_content_type`]); a missing or different type is **415**
66//!   `{"error": "Unsupported Media Type", "message": ...}`.
67//! - Malformed bodies (JSON, non-UTF-8 forms, more than [`MAX_FORM_FIELDS`]
68//!   form fields) → **422** with the [`ValidationErrorBody`] shape; oversized
69//!   bodies → **413** `{"error": "Payload too large"}`.
70//! - Header names containing `_` are ignored (see [`headers_to_json`]); all
71//!   `Cookie` headers are read and the first occurrence of a cookie name wins
72//!   (see [`cookie_headers_to_json`]).
73//!
74//! # Error bodies
75//!
76//! | Status | Body |
77//! |---|---|
78//! | 422 | `{"error": "Validation failed", "issues": [{"path": ".name", "message": "...", "code": "too_small"}]}` |
79//! | 413 | `{"error": "Payload too large"}` |
80//! | 415 | `{"error": "Unsupported Media Type", "message": "Expected Content-Type: ..."}` |
81//!
82//! `path` is `""` for the root (e.g. malformed JSON), `.field` for fields and
83//! `[0]` for array items (`.items[0].name`); `code` is
84//! [`IssueCode::key()`](vld::error::IssueCode::key).
85pub use vld::schema::parse_coerced;
86
87/// Default max request body size (2 MiB — same as axum `DefaultBodyLimit`).
88///
89/// Every adapter applies it to JSON and form bodies unless a limit is
90/// configured ([`VldBodyLimit`], the framework's own setting, or a
91/// constructor argument; per adapter:
92/// <https://s00d.github.io/vld/integrations/web/overview#body-limits>).
93pub const DEFAULT_BODY_LIMIT: usize = 2 * 1024 * 1024;
94
95/// Max number of `&`-separated fields in a form body ([`parse_form_body`]).
96///
97/// Caps the memory a small body can expand into (`a&a&a&…` turns every two
98/// bytes into a JSON value); more fields are a 422 parse error.
99pub const MAX_FORM_FIELDS: usize = 1000;
100
101/// Body size limit in bytes, registered as request/app data for the adapters
102/// without a framework-native body limit setting (`vld-actix` `app_data`,
103/// `vld-ntex` app state, `vld-poem` `.data(..)`; `vld-rama` has its own
104/// extension type).
105///
106/// Without it those adapters use [`DEFAULT_BODY_LIMIT`].
107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108pub struct VldBodyLimit(pub usize);
109
110/// Coerce a raw string value (query, form, path, header, cookie) into JSON.
111///
112/// Coercion never loses information: a value is only converted when the
113/// conversion round-trips to exactly the same text.
114///
115/// - `"true"` / `"false"` (lowercase only) → `Bool`
116/// - canonical integers (`0`, `42`, `-7`; no `+`, no leading zeros) that fit
117///   `i64`/`u64` → `Number`
118/// - canonical decimals (`3.14`, `-0.5`; no exponent, no trailing zeros, no
119///   precision loss in `f64`) → `Number`
120/// - everything else — including `""`, `"null"`, `"01234"`, `"+1555"`,
121///   `"1e3"`, `"TRUE"` and ids beyond `u64` — stays a `String`
122///
123/// Use `vld::string().coerce()` / `vld::number().coerce()` in schemas when a
124/// field must accept both forms (e.g. a string field that may look numeric).
125pub fn coerce_value(raw: &str) -> serde_json::Value {
126    use serde_json::Value;
127    match raw {
128        "true" => return Value::Bool(true),
129        "false" => return Value::Bool(false),
130        _ => {}
131    }
132    if is_canonical_number(raw) {
133        if !raw.contains('.') {
134            if let Ok(n) = raw.parse::<i64>() {
135                return Value::Number(n.into());
136            }
137            if let Ok(n) = raw.parse::<u64>() {
138                return Value::Number(n.into());
139            }
140        } else if let Ok(f) = raw.parse::<f64>() {
141            // `f64` Display is the shortest round-trip form: `1.50` → `1.5`,
142            // `0.1000000000000000001` → `0.1`; both stay strings.
143            if f.is_finite() && f.to_string() == raw {
144                if let Some(n) = serde_json::Number::from_f64(f) {
145                    return Value::Number(n);
146                }
147            }
148        }
149    }
150    Value::String(raw.to_string())
151}
152
153/// `-?(0|[1-9][0-9]*)(\.[0-9]+)?`, excluding `-0`.
154fn is_canonical_number(s: &str) -> bool {
155    let negative = s.starts_with('-');
156    let digits = s.strip_prefix('-').unwrap_or(s);
157    let (int, frac) = match digits.split_once('.') {
158        Some((i, f)) => (i, Some(f)),
159        None => (digits, None),
160    };
161    let all_digits = |p: &str| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit());
162    if !all_digits(int) || (int.len() > 1 && int.starts_with('0')) {
163        return false;
164    }
165    if frac.is_some_and(|f| !all_digits(f)) {
166        return false;
167    }
168    !(negative && frac.is_none() && int == "0")
169}
170
171/// Parse a URL query string (or `application/x-www-form-urlencoded` body)
172/// into a `serde_json::Map`.
173///
174/// - keys and values are form-decoded ([`url_decode`]) and values coerced via
175///   [`coerce_value`];
176/// - a key without `=` (`?flag`) yields `""`, like `URLSearchParams`;
177/// - a repeated key (`a=1&a=2`) yields an array `[1, 2]`;
178/// - a key ending in `[]` (`a[]=1`) always yields an array under `a`.
179pub fn parse_query_string(query: &str) -> serde_json::Map<String, serde_json::Value> {
180    use serde_json::Value;
181    let mut map = serde_json::Map::new();
182
183    for pair in query.split('&').filter(|p| !p.is_empty()) {
184        let (key, raw_value) = pair.split_once('=').unwrap_or((pair, ""));
185        let mut key = url_decode(key);
186        let value = coerce_value(&url_decode(raw_value));
187
188        let force_array = key.ends_with("[]");
189        if force_array {
190            key.truncate(key.len() - 2);
191        }
192
193        match map.get_mut(&key) {
194            Some(Value::Array(items)) => items.push(value),
195            Some(existing) => {
196                let first = existing.take();
197                *existing = Value::Array(vec![first, value]);
198            }
199            None if force_array => {
200                map.insert(key, Value::Array(vec![value]));
201            }
202            None => {
203                map.insert(key, value);
204            }
205        }
206    }
207
208    map
209}
210
211/// Parse a URL query string into a `serde_json::Value::Object`.
212///
213/// Convenience wrapper around [`parse_query_string`].
214pub fn query_string_to_json(query: &str) -> serde_json::Value {
215    serde_json::Value::Object(parse_query_string(query))
216}
217
218/// Build a JSON object from a `Cookie` header value.
219///
220/// Cookie names are used as-is. Values are unquoted (`"abc"` → `abc`),
221/// percent-decoded (`+` is kept) and coerced via [`coerce_value`].
222///
223/// When a name repeats (`sid=legit; sid=evil`) the **first** occurrence
224/// wins, as in most cookie parsers (browsers send the most specific path
225/// first); letting a later one win enables cookie tossing from a sibling
226/// subdomain.
227pub fn cookies_to_json(cookie_header: &str) -> serde_json::Value {
228    let mut map = serde_json::Map::new();
229
230    for cookie in cookie_header.split(';') {
231        let cookie = cookie.trim();
232        if cookie.is_empty() {
233            continue;
234        }
235        let (name, value) = cookie.split_once('=').unwrap_or((cookie, ""));
236        let value = value.trim();
237        let value = value
238            .strip_prefix('"')
239            .and_then(|v| v.strip_suffix('"'))
240            .unwrap_or(value);
241        map.entry(name.trim())
242            .or_insert_with(|| coerce_value(&percent_decode(value)));
243    }
244
245    serde_json::Value::Object(map)
246}
247
248/// Build a JSON object from **all** `Cookie` header values of a request.
249///
250/// HTTP/2 clients may send one `Cookie` header per cookie, so the values are
251/// joined with `"; "` before [`cookies_to_json`] (the first occurrence of a
252/// name wins). Non-UTF-8 bytes become `U+FFFD`.
253pub fn cookie_headers_to_json<'a, I>(values: I) -> serde_json::Value
254where
255    I: IntoIterator<Item = &'a [u8]>,
256{
257    let values: Vec<_> = values.into_iter().map(String::from_utf8_lossy).collect();
258    cookies_to_json(&values.join("; "))
259}
260
261/// Build a JSON object from HTTP header name/value pairs.
262///
263/// - names are lowercased and `-` becomes `_` (`X-Request-Id` → `x_request_id`);
264/// - names that already contain `_` (`x_user`) are **skipped**: a client
265///   could otherwise fill the `x_user` field past a proxy that strips only
266///   `X-User` (nginx, for one, also drops such names by default);
267/// - non-UTF-8 bytes become `U+FFFD` instead of silently dropping the header;
268/// - repeated headers are joined with `", "` (RFC 9110 §5.3);
269/// - the joined value is coerced via [`coerce_value`].
270pub fn headers_to_json<'a, I>(headers: I) -> serde_json::Value
271where
272    I: IntoIterator<Item = (&'a str, &'a [u8])>,
273{
274    let mut map = serde_json::Map::new();
275    let mut raw: Vec<(String, String)> = Vec::new();
276    for (name, value) in headers {
277        if name.contains('_') {
278            continue;
279        }
280        let key = name.to_ascii_lowercase().replace('-', "_");
281        let value = String::from_utf8_lossy(value);
282        match raw.iter_mut().find(|(k, _)| *k == key) {
283            Some((_, v)) => {
284                v.push_str(", ");
285                v.push_str(&value);
286            }
287            None => raw.push((key, value.into_owned())),
288        }
289    }
290    for (k, v) in raw {
291        map.insert(k, coerce_value(&v));
292    }
293    serde_json::Value::Object(map)
294}
295
296/// Build a JSON object from already-decoded path parameters, coercing each
297/// value via [`coerce_value`].
298pub fn path_params_to_json<'a, I>(params: I) -> serde_json::Value
299where
300    I: IntoIterator<Item = (&'a str, &'a str)>,
301{
302    serde_json::Value::Object(
303        params
304            .into_iter()
305            .map(|(k, v)| (k.to_string(), coerce_value(v)))
306            .collect(),
307    )
308}
309
310/// Parse an `application/x-www-form-urlencoded` body.
311///
312/// Fails with a 422 parse error when the body is not valid UTF-8 or has more
313/// than [`MAX_FORM_FIELDS`] fields.
314pub fn parse_form_body(body: &[u8]) -> Result<serde_json::Value, VldHttpError> {
315    let s = std::str::from_utf8(body)
316        .map_err(|_| VldHttpError::parse("Form body is not valid UTF-8"))?;
317    if s.split('&').filter(|p| !p.is_empty()).count() > MAX_FORM_FIELDS {
318        return Err(VldHttpError::parse(format!(
319            "Too many form fields (max {MAX_FORM_FIELDS})"
320        )));
321    }
322    Ok(query_string_to_json(s))
323}
324
325/// Parse a JSON body; malformed JSON is a 422 parse error.
326pub fn parse_json_body(body: &[u8]) -> Result<serde_json::Value, VldHttpError> {
327    serde_json::from_slice(body).map_err(|e| VldHttpError::parse(format!("Invalid JSON: {e}")))
328}
329
330/// The media type without parameters, trimmed and lowercased
331/// (`Application/JSON; charset=utf-8` → `application/json`).
332fn media_type_essence(content_type: &str) -> String {
333    content_type
334        .split(';')
335        .next()
336        .unwrap_or("")
337        .trim()
338        .to_ascii_lowercase()
339}
340
341/// `true` for `application/json` and any `application/<x>+json` media type
342/// with a non-empty `<x>` (case-insensitive; parameters such as
343/// `; charset=utf-8` are ignored, even malformed ones).
344pub fn is_json_content_type(content_type: &str) -> bool {
345    let essence = media_type_essence(content_type);
346    essence == "application/json"
347        || essence
348            .strip_prefix("application/")
349            .and_then(|s| s.strip_suffix("+json"))
350            .is_some_and(|prefix| !prefix.is_empty())
351}
352
353/// Check the `Content-Type` of a JSON body: `Ok` for JSON media types
354/// ([`is_json_content_type`]), otherwise a **415** error (also when the
355/// header is missing or not valid UTF-8).
356pub fn require_json_content_type(content_type: Option<&str>) -> Result<(), VldHttpError> {
357    match content_type {
358        Some(ct) if is_json_content_type(ct) => Ok(()),
359        _ => Err(VldHttpError::unsupported_media_type()),
360    }
361}
362
363/// Check the `Content-Type` of a form body: `Ok` for
364/// `application/x-www-form-urlencoded` (case-insensitive, parameters
365/// allowed), otherwise a **415** error (also when the header is missing or
366/// not valid UTF-8).
367pub fn require_form_content_type(content_type: Option<&str>) -> Result<(), VldHttpError> {
368    match content_type.map(media_type_essence) {
369        Some(ct) if ct == "application/x-www-form-urlencoded" => Ok(()),
370        _ => Err(VldHttpError::unsupported_form_media_type()),
371    }
372}
373
374// ---------------------------------------------------------------------------
375// Shared error type
376// ---------------------------------------------------------------------------
377
378/// Framework-independent error produced by all `vld` HTTP adapters.
379///
380/// | Constructor | Status | Body |
381/// |---|---|---|
382/// | [`validation`](Self::validation) / [`parse`](Self::parse) | 422 | [`ValidationErrorBody`] |
383/// | [`payload_too_large`](Self::payload_too_large) | 413 | [`ErrorBody`] |
384/// | [`unsupported_media_type`](Self::unsupported_media_type) / [`unsupported_form_media_type`](Self::unsupported_form_media_type) | 415 | [`ErrorWithMessage`] |
385///
386/// Adapters only convert [`status`](Self::status) and [`body`](Self::body)
387/// into their framework's response type.
388#[derive(Debug, Clone)]
389pub struct VldHttpError {
390    status: u16,
391    error: vld::error::VldError,
392}
393
394impl VldHttpError {
395    /// 422 — schema validation failed.
396    pub fn validation(error: vld::error::VldError) -> Self {
397        Self { status: 422, error }
398    }
399
400    /// 422 — the input could not be parsed (malformed JSON, bad UTF-8, ...).
401    pub fn parse(message: impl Into<String>) -> Self {
402        Self::validation(vld::error::VldError::single(
403            vld::error::IssueCode::ParseError,
404            message.into(),
405        ))
406    }
407
408    /// 413 — the body exceeds the size limit.
409    ///
410    /// [`error`](Self::error) holds a single `ParseError` issue
411    /// `"Payload too large"` (also what `Display` prints).
412    pub fn payload_too_large() -> Self {
413        Self {
414            status: 413,
415            error: vld::error::VldError::single(
416                vld::error::IssueCode::ParseError,
417                "Payload too large",
418            ),
419        }
420    }
421
422    /// 415 — a JSON body was sent without a JSON `Content-Type`.
423    ///
424    /// [`error`](Self::error) holds a single `ParseError` issue with
425    /// [`UNSUPPORTED_MEDIA_TYPE_MESSAGE`].
426    pub fn unsupported_media_type() -> Self {
427        Self::unsupported(UNSUPPORTED_MEDIA_TYPE_MESSAGE)
428    }
429
430    /// 415 — a form body was sent without
431    /// `Content-Type: application/x-www-form-urlencoded`.
432    ///
433    /// [`error`](Self::error) holds a single `ParseError` issue with
434    /// [`UNSUPPORTED_FORM_MEDIA_TYPE_MESSAGE`].
435    pub fn unsupported_form_media_type() -> Self {
436        Self::unsupported(UNSUPPORTED_FORM_MEDIA_TYPE_MESSAGE)
437    }
438
439    fn unsupported(message: &str) -> Self {
440        Self {
441            status: 415,
442            error: vld::error::VldError::single(vld::error::IssueCode::ParseError, message),
443        }
444    }
445
446    /// HTTP status code (422, 413 or 415).
447    #[must_use]
448    pub fn status(&self) -> u16 {
449        self.status
450    }
451
452    /// The underlying validation error.
453    pub fn error(&self) -> &vld::error::VldError {
454        &self.error
455    }
456
457    /// Consume and return the underlying validation error.
458    pub fn into_error(self) -> vld::error::VldError {
459        self.error
460    }
461
462    /// JSON response body for this error.
463    pub fn body(&self) -> serde_json::Value {
464        match self.status {
465            413 => format_payload_too_large(),
466            415 => serde_json::to_value(ErrorWithMessage {
467                error: "Unsupported Media Type".into(),
468                message: self
469                    .error
470                    .issues
471                    .first()
472                    .map_or(UNSUPPORTED_MEDIA_TYPE_MESSAGE, |i| i.message.as_str())
473                    .into(),
474            })
475            .expect("ErrorWithMessage serialization cannot fail"),
476            _ => format_vld_error(&self.error),
477        }
478    }
479}
480
481impl From<vld::error::VldError> for VldHttpError {
482    fn from(error: vld::error::VldError) -> Self {
483        Self::validation(error)
484    }
485}
486
487impl std::fmt::Display for VldHttpError {
488    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
489        match self.status {
490            413 => f.write_str("Payload too large"),
491            415 => f.write_str("Unsupported Media Type"),
492            _ => write!(f, "Validation failed: {}", self.error),
493        }
494    }
495}
496
497impl std::error::Error for VldHttpError {}
498
499// ---------------------------------------------------------------------------
500// Error response schemas (defined via vld::schema!)
501// ---------------------------------------------------------------------------
502
503use serde::Serialize;
504
505vld::schema! {
506    /// Simple error body: `{ "error": "..." }`.
507    ///
508    /// Used for generic HTTP errors such as "Payload too large",
509    /// "Not Found", "Method Not Allowed", etc.
510    #[derive(Debug, Clone, Serialize)]
511    pub struct ErrorBody {
512        /// Short error title.
513        pub error: String => vld::string(),
514    }
515}
516
517vld::schema! {
518    /// Error body with a message: `{ "error": "...", "message": "..." }`.
519    ///
520    /// The **415** body ([`VldHttpError::unsupported_media_type`],
521    /// [`VldHttpError::unsupported_form_media_type`]).
522    #[derive(Debug, Clone, Serialize)]
523    pub struct ErrorWithMessage {
524        /// Short error title.
525        pub error: String   => vld::string(),
526        /// Details.
527        pub message: String => vld::string(),
528    }
529}
530
531vld::schema! {
532    /// A single validation issue:
533    /// `{ "path": "...", "message": "...", "code": "..." }` (`code` is
534    /// [`IssueCode::key()`](vld::error::IssueCode::key)).
535    #[derive(Debug, Clone, Serialize)]
536    pub struct ValidationIssue {
537        /// Path of the invalid value (`.user.email`, `[0]`).
538        pub path: String    => vld::string(),
539        /// Human-readable message.
540        pub message: String => vld::string(),
541        /// Issue code key (`too_small`, `invalid_string`, …).
542        pub code: String    => vld::string(),
543    }
544}
545
546vld::schema! {
547    /// Validation error response body:
548    /// `{ "error": "Validation failed", "issues": [...] }`.
549    #[derive(Debug, Clone, Serialize)]
550    pub struct ValidationErrorBody {
551        /// Always `"Validation failed"`.
552        pub error: String => vld::string(),
553        /// Every issue found.
554        pub issues: Vec<ValidationIssue> => vld::array(vld::nested(ValidationIssue::parse_value)),
555    }
556}
557
558// ---------------------------------------------------------------------------
559// Formatting helpers
560// ---------------------------------------------------------------------------
561
562/// `.user.name`, `.items[0]` — spelled out instead of relying on
563/// `PathSegment`'s `Display` so the wire format stays stable.
564fn format_path(path: &[vld::error::PathSegment]) -> String {
565    use std::fmt::Write;
566    use vld::error::PathSegment;
567    let mut out = String::new();
568    for seg in path {
569        let _ = match seg {
570            PathSegment::Field(name) => write!(out, ".{name}"),
571            PathSegment::Index(idx) => write!(out, "[{idx}]"),
572        };
573    }
574    out
575}
576
577/// Format a [`VldError`](vld::error::VldError) into a list of
578/// [`ValidationIssue`] structs.
579pub fn format_issues(err: &vld::error::VldError) -> Vec<ValidationIssue> {
580    err.issues
581        .iter()
582        .map(|i| ValidationIssue {
583            path: format_path(&i.path),
584            message: i.message.clone(),
585            code: i.code.key().to_string(),
586        })
587        .collect()
588}
589
590/// Format a [`VldError`](vld::error::VldError) into a JSON object with
591/// `"error"` and `"issues"` keys — ready to be sent as a 422 response body.
592///
593/// Internally constructs a [`ValidationErrorBody`] and serializes it.
594pub fn format_vld_error(err: &vld::error::VldError) -> serde_json::Value {
595    let body = ValidationErrorBody {
596        error: "Validation failed".into(),
597        issues: format_issues(err),
598    };
599    serde_json::to_value(body).expect("ValidationErrorBody serialization cannot fail")
600}
601
602/// Decode a form/query component: `+` → space, then [`percent_decode`].
603pub fn url_decode(input: &str) -> String {
604    percent_decode(&input.replace('+', " "))
605}
606
607/// Percent-decode a URL component (path segment, cookie value); `+` is kept.
608///
609/// Only `%` followed by exactly two hex digits is decoded; anything else is
610/// kept literally. Decoded bytes are read as UTF-8 (`%C3%A9` → `é`); invalid
611/// sequences become `U+FFFD`.
612pub fn percent_decode(input: &str) -> String {
613    let bytes = input.as_bytes();
614    let hex = |i: usize| bytes.get(i).and_then(|&b| (b as char).to_digit(16));
615    let mut out = Vec::with_capacity(bytes.len());
616    let mut i = 0;
617    while i < bytes.len() {
618        if bytes[i] == b'%' {
619            if let (Some(h), Some(l)) = (hex(i + 1), hex(i + 2)) {
620                out.push((h * 16 + l) as u8);
621                i += 3;
622                continue;
623            }
624        }
625        out.push(bytes[i]);
626        i += 1;
627    }
628    String::from_utf8(out).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
629}
630
631// ---------------------------------------------------------------------------
632// Standard HTTP error response helpers
633// ---------------------------------------------------------------------------
634
635/// Build a JSON error body for payloads that exceed the size limit.
636///
637/// Returns `{ "error": "Payload too large" }`.
638///
639/// Internally constructs an [`ErrorBody`] and serializes it.
640pub fn format_payload_too_large() -> serde_json::Value {
641    format_generic_error("Payload too large")
642}
643
644/// Message of the 415 body and error for JSON extractors.
645pub const UNSUPPORTED_MEDIA_TYPE_MESSAGE: &str =
646    "Expected Content-Type: application/json (or application/*+json)";
647
648/// Message of the 415 body and error for form extractors.
649pub const UNSUPPORTED_FORM_MEDIA_TYPE_MESSAGE: &str =
650    "Expected Content-Type: application/x-www-form-urlencoded";
651
652/// Build the JSON error body for a non-JSON `Content-Type`.
653///
654/// Returns `{ "error": "Unsupported Media Type", "message": "Expected Content-Type: ..." }`.
655pub fn format_unsupported_media_type() -> serde_json::Value {
656    VldHttpError::unsupported_media_type().body()
657}
658
659/// Build a generic JSON error body with a custom error string.
660///
661/// Returns `{ "error": "<error>" }`.
662///
663/// Internally constructs an [`ErrorBody`] and serializes it.
664pub fn format_generic_error(error: &str) -> serde_json::Value {
665    serde_json::to_value(ErrorBody {
666        error: error.into(),
667    })
668    .expect("ErrorBody serialization cannot fail")
669}