Make PgLTree::push infallible and take PgLTreeLabel directly. (#1734)

* Make PgLTree::push infallible and take PgLTreeLabel directly.

Previously the function took strings and parsed them into
PgLTreeLabel internally, now it's possible to directlry push
PgLTreeLabels onto a PgLTree.

* Push PgLTree String conversion to label.

* rebase and fix compile error

Co-authored-by: Austin Bonander <austin@launchbadge.com>
This commit is contained in:
Sebastian Pütz 2022-04-15 01:16:00 +02:00 committed by GitHub
parent c7478dcc66
commit babd353c2c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -27,13 +27,17 @@ pub enum PgLTreeParseError {
pub struct PgLTreeLabel(String); pub struct PgLTreeLabel(String);
impl PgLTreeLabel { impl PgLTreeLabel {
pub fn new(label: &str) -> Result<Self, PgLTreeParseError> { pub fn new<S>(label: S) -> Result<Self, PgLTreeParseError>
where
String: From<S>,
{
let label = String::from(label);
if label.len() <= 256 if label.len() <= 256
&& label && label
.bytes() .bytes()
.all(|c| c.is_ascii_alphabetic() || c.is_ascii_digit() || c == b'_') .all(|c| c.is_ascii_alphabetic() || c.is_ascii_digit() || c == b'_')
{ {
Ok(Self(label.to_owned())) Ok(Self(label))
} else { } else {
Err(PgLTreeParseError::InvalidLtreeLabel) Err(PgLTreeParseError::InvalidLtreeLabel)
} }
@ -101,20 +105,19 @@ impl PgLTree {
/// creates ltree from an iterator with checking labels /// creates ltree from an iterator with checking labels
pub fn from_iter<I, S>(labels: I) -> Result<Self, PgLTreeParseError> pub fn from_iter<I, S>(labels: I) -> Result<Self, PgLTreeParseError>
where where
S: Into<String>, String: From<S>,
I: IntoIterator<Item = S>, I: IntoIterator<Item = S>,
{ {
let mut ltree = Self::default(); let mut ltree = Self::default();
for label in labels { for label in labels {
ltree.push(&label.into())?; ltree.push(PgLTreeLabel::new(label)?);
} }
Ok(ltree) Ok(ltree)
} }
/// push a label to ltree /// push a label to ltree
pub fn push(&mut self, label: &str) -> Result<(), PgLTreeParseError> { pub fn push(&mut self, label: PgLTreeLabel) {
self.labels.push(PgLTreeLabel::new(label)?); self.labels.push(label);
Ok(())
} }
/// pop a label from ltree /// pop a label from ltree