1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
56//! Errors for Smithy codegen
78use std::fmt;
910pub mod display;
11pub mod metadata;
12pub mod operation;
1314pub use metadata::ErrorMetadata;
1516#[derive(Debug)]
17pub(super) enum TryFromNumberErrorKind {
18/// Used when the conversion from an integer type into a smaller integer type would be lossy.
19OutsideIntegerRange(std::num::TryFromIntError),
20/// Used when the conversion from an `u64` into a floating point type would be lossy.
21U64ToFloatLossyConversion(u64),
22/// Used when the conversion from an `i64` into a floating point type would be lossy.
23I64ToFloatLossyConversion(i64),
24/// Used when attempting to convert an `f64` into an `f32`.
25F64ToF32LossyConversion(f64),
26/// Used when attempting to convert a decimal, infinite, or `NaN` floating point type into an
27 /// integer type.
28FloatToIntegerLossyConversion(f64),
29/// Used when attempting to convert a negative [`Number`](crate::Number) into an unsigned integer type.
30NegativeToUnsignedLossyConversion(i64),
31}
3233/// The error type returned when conversion into an integer type or floating point type is lossy.
34#[derive(Debug)]
35pub struct TryFromNumberError {
36pub(super) kind: TryFromNumberErrorKind,
37}
3839impl fmt::Display for TryFromNumberError {
40fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41use TryFromNumberErrorKind::*;
42match self.kind {
43 OutsideIntegerRange(_) => write!(f, "integer too large"),
44 FloatToIntegerLossyConversion(v) => write!(
45 f,
46"cannot convert floating point number {v} into an integer"
47),
48 NegativeToUnsignedLossyConversion(v) => write!(
49 f,
50"cannot convert negative integer {v} into an unsigned integer type"
51),
52 U64ToFloatLossyConversion(v) => {
53write!(
54 f,
55"cannot convert {v}u64 into a floating point type without precision loss"
56)
57 }
58 I64ToFloatLossyConversion(v) => {
59write!(
60 f,
61"cannot convert {v}i64 into a floating point type without precision loss"
62)
63 }
64 F64ToF32LossyConversion(v) => {
65write!(f, "will not attempt to convert {v}f64 into a f32")
66 }
67 }
68 }
69}
7071impl std::error::Error for TryFromNumberError {
72fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
73use TryFromNumberErrorKind::*;
74match &self.kind {
75 OutsideIntegerRange(err) => Some(err as _),
76 FloatToIntegerLossyConversion(_)
77 | NegativeToUnsignedLossyConversion(_)
78 | U64ToFloatLossyConversion(_)
79 | I64ToFloatLossyConversion(_)
80 | F64ToF32LossyConversion(_) => None,
81 }
82 }
83}
8485impl From<std::num::TryFromIntError> for TryFromNumberError {
86fn from(value: std::num::TryFromIntError) -> Self {
87Self {
88 kind: TryFromNumberErrorKind::OutsideIntegerRange(value),
89 }
90 }
91}
9293impl From<TryFromNumberErrorKind> for TryFromNumberError {
94fn from(kind: TryFromNumberErrorKind) -> Self {
95Self { kind }
96 }
97}