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
//! The contract of a typed cast: a model field whose column holds something else.
use crateCastError;
use ;
/// A model field stored as another type: the column holds [`ColumnCast::Repr`], the program works with `Self`.
///
/// | Laravel | here |
/// |-----------------------|-------------------------------|
/// | `get(..., $value)` | [`ColumnCast::from_repr`] |
/// | `set(..., $value)` | [`ColumnCast::to_repr`] |
/// | `serialize(...)` | the type's own `Serialize` |
/// | the incoming request | the type's own `Deserialize` |
///
/// Implement it, then call [`impl_column_cast!`](crate::impl_column_cast) once: it gives the type the `laravel-rust`
/// traits a model field needs (`Decode`, `Nullable` and `From` for [`Value`]). SQL `NULL` is the one of `Repr`, so what
/// `None` writes always has the encoding of the column. [`crate::DateCast`] and [`crate::DateTimeCast`] implement it
/// too.
///
/// For a newtype that is stored as its one field, with nothing to check or convert, `#[derive(laravel::Newtype)]`
/// already does this: use that instead.
///
/// How the type looks outside the database is not part of the contract. Derive or implement `serde` for it; the
/// example goes through `String` both ways, so the request is checked by the same code as everything else.
///
/// ```
/// use laravel::db::Value;
/// use laravel_casts::{CastError, ColumnCast, impl_column_cast};
/// use serde::{Deserialize, Serialize};
///
/// /// Cents in the column, `12.50` outside.
/// #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
/// #[serde(try_from = "String", into = "String")]
/// struct Money(i64);
///
/// impl ColumnCast for Money {
/// type Repr = i64;
///
/// fn from_repr(cents: i64) -> Result<Self, CastError> {
/// Ok(Self(cents))
/// }
/// fn to_repr(&self) -> i64 {
/// self.0
/// }
/// }
/// impl_column_cast!(Money);
///
/// impl From<Money> for String {
/// fn from(money: Money) -> Self {
/// // The sign apart: -5 cents is `-0.05`.
/// let sign = if money.0 < 0 { "-" } else { "" };
/// let cents = money.0.unsigned_abs();
/// format!("{sign}{}.{:02}", cents / 100, cents % 100)
/// }
/// }
///
/// impl TryFrom<String> for Money {
/// type Error = CastError;
///
/// fn try_from(text: String) -> Result<Self, CastError> {
/// let refused = || CastError::Rejected(format!("\"{text}\" is not an amount"));
/// let (sign, amount) = text.strip_prefix('-').map_or(("", text.as_str()), |rest| ("-", rest));
/// let (whole, cents) = amount.split_once('.').unwrap_or((amount, ""));
/// let digits = |part: &str| part.bytes().all(|byte| byte.is_ascii_digit());
/// // `12.5` is 1250 cents; a third decimal is refused, not rounded away.
/// if whole.is_empty() || cents.len() > 2 || !digits(whole) || !digits(cents) {
/// return Err(refused());
/// }
/// format!("{sign}{whole}{cents:0<2}").parse().map(Self).map_err(|_| refused())
/// }
/// }
///
/// let bound: Value = Money(1250).into();
/// assert_eq!(bound, Value::BigInteger(Some(1250)));
/// assert_eq!(serde_json::to_string(&Money(1250)).unwrap(), "\"12.50\"");
/// assert_eq!(serde_json::from_str::<Money>("\"-1.5\"").unwrap(), Money(-150));
/// assert!(serde_json::from_str::<Money>("\"12.005\"").is_err());
/// ```
/// Gives a type that implements [`ColumnCast`] the traits a `laravel-rust` model field asks for: `Decode`, `Nullable`,
/// and `From<T>`, `From<&T>` and `From<&&T>` for `Value`.