Skip to content

Commit

Permalink
feat: serialize AST to json (#94)
Browse files Browse the repository at this point in the history
* feat: serialize AST to json

* chore: make header check happy again

* feat: implement serialize for vectorSelector and call

* test: improve converage

* feat: implement serialization for more

* test: cover more expression

* fix: subquery

* refactor: address review comments
  • Loading branch information
sunng87 authored Oct 23, 2024
1 parent 4ea4cbf commit 7691247
Show file tree
Hide file tree
Showing 9 changed files with 703 additions and 1 deletion.
6 changes: 6 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@ lazy_static = "1.4.0"
lrlex = "0.13.5"
lrpar = "0.13.5"
regex = "1"
serde = { version = "1", optional = true }
serde_json = { version = "1", optional = true }

[features]
default = []
ser = ["serde", "serde_json"]

[build-dependencies]
cfgrammar = "0.13.5"
Expand Down
15 changes: 15 additions & 0 deletions src/label/matcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ use crate::util::join_vector;
pub enum MatchOp {
Equal,
NotEqual,
// TODO: do we need regex here?
Re(Regex),
NotRe(Regex),
}
Expand Down Expand Up @@ -64,9 +65,21 @@ impl Hash for MatchOp {
}
}

#[cfg(feature = "ser")]
impl serde::Serialize for MatchOp {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(&self.to_string())
}
}

// Matcher models the matching of a label.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "ser", derive(serde::Serialize))]
pub struct Matcher {
#[cfg_attr(feature = "ser", serde(rename = "type"))]
pub op: MatchOp,
pub name: String,
pub value: String,
Expand Down Expand Up @@ -183,8 +196,10 @@ fn try_escape_for_repeat_re(re: &str) -> String {
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ser", derive(serde::Serialize))]
pub struct Matchers {
pub matchers: Vec<Matcher>,
#[cfg_attr(feature = "ser", serde(skip_serializing_if = "<[_]>::is_empty"))]
pub or_matchers: Vec<Vec<Matcher>>,
}

Expand Down
17 changes: 17 additions & 0 deletions src/label/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,23 @@ impl fmt::Display for Labels {
}
}

#[cfg(feature = "ser")]
impl serde::Serialize for Labels {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
use serde::ser::SerializeSeq;
let mut seq = serializer.serialize_seq(Some(self.labels.len()))?;

for l in &self.labels {
seq.serialize_element(&l)?;
}

seq.end()
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
Loading

0 comments on commit 7691247

Please sign in to comment.