Skip to main content

sql_values/postgres/
bpchar.rs

1//! PostgreSQL 18's `bpchar`, the type of `char(n)`, whose equality ignores trailing blanks.
2
3use alloc::borrow::Cow;
4use core::{
5    fmt,
6    hash::{Hash, Hasher},
7};
8
9/// A `bpchar` or `char(n)` value, held as written or as a row image carries it, blank-padded to
10/// its length.
11///
12/// Two values are equal as `bpchareq` finds them under a deterministic collation, ignoring
13/// trailing blanks (U+0020) on both sides, while a leading blank, a tab or any other whitespace
14/// counts. That is the rule `=`, `<>`, `IN` and `IS [NOT] DISTINCT FROM` follow when the other
15/// side is a `bpchar`, a `varchar` or an untyped literal. Against `text`, PostgreSQL casts the
16/// `bpchar` to `text` instead, which [`PgBpchar::as_text`] models, and compares the result with
17/// the `text` exactly.
18///
19/// ```
20/// use sql_values::postgres::PgBpchar;
21///
22/// let row = PgBpchar::new("ab  ");
23/// assert_eq!(row, PgBpchar::new("ab"));
24/// assert_eq!(row, PgBpchar::new("ab   "));
25/// assert_ne!(row, PgBpchar::new(" ab"));
26/// assert_ne!(PgBpchar::new("ab\t "), PgBpchar::new("ab"));
27/// assert_eq!(PgBpchar::new("    "), PgBpchar::new(""));
28///
29/// assert_eq!(row.as_text(), "ab");
30/// assert_ne!(row.as_text(), "ab ");
31/// assert_eq!(row.to_string(), "ab  ");
32/// ```
33#[derive(Debug, Clone)]
34pub struct PgBpchar<'a>(Cow<'a, str>);
35
36impl<'a> PgBpchar<'a> {
37    /// The value whose text is `text`, kept as it is, blanks included.
38    pub fn new(text: impl Into<Cow<'a, str>>) -> Self {
39        Self(text.into())
40    }
41
42    /// The text as held, blanks included, as the output function prints it.
43    pub fn as_str(&self) -> &str {
44        &self.0
45    }
46
47    /// The `text` the cast `bpchar::text` produces, without the trailing blanks.
48    pub fn as_text(&self) -> &str {
49        self.0.trim_end_matches(' ')
50    }
51}
52
53impl PartialEq<PgBpchar<'_>> for PgBpchar<'_> {
54    fn eq(&self, other: &PgBpchar<'_>) -> bool {
55        self.as_text() == other.as_text()
56    }
57}
58
59impl Eq for PgBpchar<'_> {}
60
61impl Hash for PgBpchar<'_> {
62    fn hash<H: Hasher>(&self, state: &mut H) {
63        self.as_text().hash(state);
64    }
65}
66
67impl fmt::Display for PgBpchar<'_> {
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        f.write_str(&self.0)
70    }
71}