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
136
137
138
139
140
141
use std::error::Error;
use std::fmt;
use anyhow::bail;
use proptest_derive::Arbitrary;
use serde::{Deserialize, Serialize};
use mz_lowertest::MzReflect;
use mz_ore::cast::CastFrom;
use mz_proto::{RustType, TryFromProtoError};
include!(concat!(env!("OUT_DIR"), "/mz_repr.adt.varchar.rs"));
pub const MAX_MAX_LENGTH: u32 = 10_485_760;
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct VarChar<S: AsRef<str>>(pub S);
#[derive(
Arbitrary,
Debug,
Clone,
Copy,
Eq,
PartialEq,
Ord,
PartialOrd,
Hash,
Serialize,
Deserialize,
MzReflect,
)]
pub struct VarCharMaxLength(pub(crate) u32);
impl VarCharMaxLength {
pub fn into_u32(self) -> u32 {
self.0
}
}
impl TryFrom<i64> for VarCharMaxLength {
type Error = InvalidVarCharMaxLengthError;
fn try_from(max_length: i64) -> Result<Self, Self::Error> {
match u32::try_from(max_length) {
Ok(max_length) if max_length > 0 && max_length < MAX_MAX_LENGTH => {
Ok(VarCharMaxLength(max_length))
}
_ => Err(InvalidVarCharMaxLengthError),
}
}
}
impl RustType<ProtoVarCharMaxLength> for VarCharMaxLength {
fn into_proto(&self) -> ProtoVarCharMaxLength {
ProtoVarCharMaxLength { value: self.0 }
}
fn from_proto(proto: ProtoVarCharMaxLength) -> Result<Self, TryFromProtoError> {
Ok(VarCharMaxLength(proto.value))
}
}
#[derive(Debug, Clone)]
pub struct InvalidVarCharMaxLengthError;
impl fmt::Display for InvalidVarCharMaxLengthError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"length for type character varying must be between 1 and {}",
MAX_MAX_LENGTH
)
}
}
impl Error for InvalidVarCharMaxLengthError {}
pub fn format_str(
s: &str,
length: Option<VarCharMaxLength>,
fail_on_len: bool,
) -> Result<String, anyhow::Error> {
Ok(match length {
Some(l) => {
let l = usize::cast_from(l.into_u32());
match s.char_indices().nth(l) {
None => s.to_string(),
Some((idx, _)) => {
if !fail_on_len || s[idx..].chars().all(|c| c.is_ascii_whitespace()) {
s[..idx].to_string()
} else {
bail!("{} exceeds maximum length of {}", s, l)
}
}
}
}
None => s.to_string(),
})
}
#[cfg(test)]
mod tests {
use super::*;
use mz_proto::protobuf_roundtrip;
use proptest::prelude::*;
proptest! {
#[test]
fn var_char_max_length_protobuf_roundtrip(expect in any::<VarCharMaxLength>()) {
let actual = protobuf_roundtrip::<_, ProtoVarCharMaxLength>(&expect);
assert!(actual.is_ok());
assert_eq!(actual.unwrap(), expect);
}
}
}