Skip to content

Commit 8c78966

Browse files
committed
Rust: Wrap labels in Cow
This allows us to generate non-generic code to turn strings into the correct type.
1 parent 4b1eb17 commit 8c78966

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

glean_parser/metrics.py

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -364,14 +364,38 @@ def __init__(self, *args, **kwargs):
364364
)
365365

366366

367+
class CowString(str):
368+
"""
369+
Wrapper class for strings that should be represented
370+
as a `Cow<'static, str>` in Rust,
371+
or `String` in other target languages.
372+
373+
This wraps `str`, so unless `CowString` is specifically
374+
handled it acts (and serializes)
375+
as a string.
376+
"""
377+
378+
def __init__(self, val: str):
379+
self.inner: str = val
380+
381+
def __eq__(self, other):
382+
return self.inner == other.inner
383+
384+
def __hash__(self):
385+
return self.inner.__hash__()
386+
387+
def __lt__(self, other):
388+
return self.inner.__lt__(other.inner)
389+
390+
367391
class Labeled(Metric):
368392
labeled = True
369393

370394
def __init__(self, *args, **kwargs):
371395
labels = kwargs.pop("labels", None)
372396
if labels is not None:
373397
self.ordered_labels = labels
374-
self.labels = set(labels)
398+
self.labels = set([CowString(label) for label in labels])
375399
else:
376400
self.ordered_labels = None
377401
self.labels = None

glean_parser/rust.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,9 @@ def iterencode(self, value):
6161
yield "]"
6262
elif value is None:
6363
yield "None"
64+
# `CowStr` is a `str`, so needs to be before next case
65+
elif isinstance(value, metrics.CowString):
66+
yield f'::std::borrow::Cow::from("{value.inner}")'
6467
elif isinstance(value, str):
6568
yield f'"{value}".into()'
6669
elif isinstance(value, metrics.Rate):

0 commit comments

Comments
 (0)