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
#![warn(
    missing_docs,
    missing_debug_implementations,
    rust_2018_idioms,
    missing_copy_implementations
)]
#![deny(unsafe_code)]

/*!
# sqlx-pg-uint

`SQLx` extension to support working with Rust unsigned integers in PostgreSQL.

---

This crate provides types with `sqlx::{Encode, Decode, Type}` implemented for them, which allow you
to work with fixed-size unsigned integers in PostgreSQL.

```
use sqlx_pg_uint::PgU64;

let a_u64_number = 2937854645u64;
let pg_u_64 = PgU64::from(a_u64_number);
println!("PgU64: {}", pg_u_64);
let back_to_u64: u64 = pg_u_64.to_uint();
println!("Back to u64: {}", back_to_u64);
println!(
    "Maths work the same way as you'd expect: {}",
    PgU64::from(67) + PgU64::from(2) * PgU64::from(3) / PgU64::from(3)
);
println!(
    "Interact with the underlying BigDecimal type directly: {}",
    pg_u_64.as_big_decimal()
);
println!("PgUint types can be converted to and from BigDecimals, and are storable in an sqlx::Postgres database.");
println!("If you load a PgUint from a database successfully, you can be sure that it's a valid fixed-size unsigned integer.");
```
*/

mod u128;
mod u16;
mod u32;
mod u64;
mod u8;

pub(crate) use bigdecimal::BigDecimal;
use thiserror::Error;
pub use u128::*;
pub use u16::*;
pub use u32::*;
pub use u64::*;
pub use u8::*;

#[derive(Debug, PartialEq, Eq, Clone, Hash, PartialOrd, Ord, Error)]
/// Error type for conversions between `BigDecimal` and `PgUint` types.
pub enum Error {
    #[error("Value is either too large, to small or not an integer")]
    /// Error when the value is either too large, too small or not an integer.
    InvalidValue(BigDecimal),
    #[error("Invalid value for target type")]
    /// Provided value is a floating point number, which is not supported by the target type.
    Fractional(BigDecimal),
}

mod private {
    pub trait Sealed {}
}

/// Helper trait to define the underlying integer type for a given `PgUint` type. Used in the
/// `sqlx-pg-uint-macros` crate to generate the necessary code for the `UIntWrapper` derive.
///
/// Not intended to be implemented by users, nor is it required to be used directly.
pub trait UIntType: private::Sealed {
    /// The underlying integer type for the `PgUint` type.
    type Uint;
}