Skip to content

Commit

Permalink
Make PgLTree::push infallible and take PgLTreeLabel directly. (#1734)
Browse files Browse the repository at this point in the history
* 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>
  • Loading branch information
sebpuetz and abonander committed Apr 14, 2022
1 parent c7478dc commit babd353
Showing 1 changed file with 10 additions and 7 deletions.
17 changes: 10 additions & 7 deletions sqlx-core/src/postgres/types/ltree.rs
Expand Up @@ -27,13 +27,17 @@ pub enum PgLTreeParseError {
pub struct PgLTreeLabel(String);

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
&& label
.bytes()
.all(|c| c.is_ascii_alphabetic() || c.is_ascii_digit() || c == b'_')
{
Ok(Self(label.to_owned()))
Ok(Self(label))
} else {
Err(PgLTreeParseError::InvalidLtreeLabel)
}
Expand Down Expand Up @@ -101,20 +105,19 @@ impl PgLTree {
/// creates ltree from an iterator with checking labels
pub fn from_iter<I, S>(labels: I) -> Result<Self, PgLTreeParseError>
where
S: Into<String>,
String: From<S>,
I: IntoIterator<Item = S>,
{
let mut ltree = Self::default();
for label in labels {
ltree.push(&label.into())?;
ltree.push(PgLTreeLabel::new(label)?);
}
Ok(ltree)
}

/// push a label to ltree
pub fn push(&mut self, label: &str) -> Result<(), PgLTreeParseError> {
self.labels.push(PgLTreeLabel::new(label)?);
Ok(())
pub fn push(&mut self, label: PgLTreeLabel) {
self.labels.push(label);
}

/// pop a label from ltree
Expand Down

0 comments on commit babd353

Please sign in to comment.