qubit_json/decode/json_number_token_error.rs
1// =============================================================================
2// Copyright (c) 2026 Haixing Hu.
3//
4// SPDX-License-Identifier: Apache-2.0
5//
6// Licensed under the Apache License, Version 2.0.
7// =============================================================================
8//! Errors from exact-safe-integer conversion.
9
10use std::error::Error;
11use std::fmt::Display;
12use std::fmt::Formatter;
13use std::fmt::Result;
14
15/// Explains why a validated JSON number cannot be represented as a safe
16/// integer.
17///
18/// `JsonNumberToken::exact_safe_integer` returns this error when the exact
19/// decimal value is fractional or outside the IEEE-754 safe-integer range.
20///
21/// # Examples
22///
23/// ```
24/// use qubit_json::decode::JsonNumberTokenError;
25///
26/// let error = JsonNumberTokenError::Fractional;
27/// assert_eq!(error.to_string(), "number is fractional");
28/// ```
29#[must_use]
30#[non_exhaustive]
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
32pub enum JsonNumberTokenError {
33 /// The token has a non-integral mathematical value.
34 Fractional,
35 /// The integer is outside the inclusive safe-integer range.
36 OutOfSafeIntegerRange,
37}
38
39impl Display for JsonNumberTokenError {
40 /// Formats the error as a concise description of the failed conversion.
41 ///
42 /// Fractional values and integers outside the safe range have distinct
43 /// messages so callers can preserve the failure category in diagnostics.
44 ///
45 /// # Parameters
46 ///
47 /// - `formatter`: Receives the formatted error text.
48 ///
49 /// # Returns
50 ///
51 /// Returns `Ok(())` when the message is written.
52 ///
53 /// # Errors
54 ///
55 /// Returns the formatter's error if writing the message fails.
56 fn fmt(&self, formatter: &mut Formatter<'_>) -> Result {
57 match self {
58 Self::Fractional => formatter.write_str("number is fractional"),
59 Self::OutOfSafeIntegerRange => formatter.write_str("integer is outside the safe range"),
60 }
61 }
62}
63
64impl Error for JsonNumberTokenError {}