Skip to content

Commit

Permalink
Rust: Wrap labels in Cow
Browse files Browse the repository at this point in the history
This allows us to generate non-generic code to turn strings into the
correct type.
  • Loading branch information
badboy committed Dec 7, 2022
1 parent 1de9e0f commit d1128bc
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
26 changes: 25 additions & 1 deletion glean_parser/metrics.py
Expand Up @@ -364,14 +364,38 @@ def __init__(self, *args, **kwargs):
)


class CowString(str):
"""
Wrapper class for strings that should be represented
as a `Cow<'static, str>` in Rust,
or `String` in other target languages.
This wraps `str`, so unless `CowString` is specifically
handled it acts (and serializes)
as a string.
"""

def __init__(self, val: str):
self.inner: str = val

def __eq__(self, other):
return self.inner == other.inner

def __hash__(self):
return self.inner.__hash__()

def __lt__(self, other):
return self.inner.__lt__(other.inner)


class Labeled(Metric):
labeled = True

def __init__(self, *args, **kwargs):
labels = kwargs.pop("labels", None)
if labels is not None:
self.ordered_labels = labels
self.labels = set(labels)
self.labels = set([CowString(label) for label in labels])
else:
self.ordered_labels = None
self.labels = None
Expand Down
3 changes: 3 additions & 0 deletions glean_parser/rust.py
Expand Up @@ -61,6 +61,9 @@ def iterencode(self, value):
yield "]"
elif value is None:
yield "None"
# `CowStr` is a `str`, so needs to be before next case
elif isinstance(value, metrics.CowString):
yield f'::std::borrow::Cow::from("{value.inner}")'
elif isinstance(value, str):
yield f'"{value}".into()'
elif isinstance(value, metrics.Rate):
Expand Down

0 comments on commit d1128bc

Please sign in to comment.