implement builtin function unique-id

This commit is contained in:
ConnorSkees 2020-04-05 18:20:58 -04:00
parent 3024c3894a
commit d67fe948d6
3 changed files with 18 additions and 2 deletions

View File

@ -34,7 +34,7 @@ default = ["commandline", "random"]
commandline = ["clap"]
# Option: enable nightly-only features (for right now, only the `track_caller` attribute)
nightly = []
# Option (enabled by default): enable the builtin function `random([$limit])`
# Option (enabled by default): enable the builtin functions `random([$limit])` and `unique-id()`
random = ["rand"]
[dev-dependencies]

View File

@ -17,7 +17,7 @@ The large features remaining are
```
special case certain functions (min, max, calc, element, expression, progid, url)
all builtin selector functions (274 tests)
content-exists, unique-id, min, min
content-exists, min, min
@extend (~600 tests)
indented syntax (27 tests)
a special parser for plain css

View File

@ -3,6 +3,9 @@ use std::collections::HashMap;
use num_bigint::BigInt;
use num_traits::{Signed, ToPrimitive, Zero};
#[cfg(feature = "random")]
use rand::{distributions::Alphanumeric, thread_rng, Rng};
use super::Builtin;
use crate::common::QuoteKind;
use crate::unit::Unit;
@ -217,4 +220,17 @@ pub(crate) fn register(f: &mut HashMap<String, Builtin>) {
Ok(Value::Ident(string, quotes))
}),
);
#[cfg(feature = "random")]
f.insert(
"unique-id".to_owned(),
Builtin::new(|args, _, _| {
max_args!(args, 0);
let mut rng = thread_rng();
let string = std::iter::repeat(())
.map(|()| rng.sample(Alphanumeric))
.take(7)
.collect();
Ok(Value::Ident(string, QuoteKind::None))
}),
);
}