1use std::hash::{Hash, Hasher};
2
3use serde::Serialize;
4
5use crate::color::Color;
6use crate::conversion::value_to_json;
7use crate::expression::formatted::Formatted;
8use crate::expression::image::Image;
9use crate::expression::locale::collator::Collator;
10use crate::expression::type_::Type;
11use crate::expression::{EvaluationContext, Expr};
12use crate::feature::{Value as FeatureValue, ValueObject};
13use crate::geo::LatLng;
14use crate::padding::Padding;
15use crate::string::to_string_double;
16use crate::types::{
17 AlignmentType, CirclePitchScaleType, HillshadeIlluminationAnchorType, HillshadeMethodType, IconOverlapType,
18 IconTextFitType, LayerBlendType, LightAnchorType, LineCapType, LineJoinType, Position, ProjectionDefinition,
19 RasterResamplingType, ResamplingType, RotateAnchorType, Rotation, SymbolAnchorType, SymbolHeightAnchorType,
20 SymbolPlacementType, SymbolZOrderType, TextJustifyType, TextRotationAlignmentType, TextTransformType,
21 TextWritingModeType, TranslateAnchorType, VariableAnchorOffsetCollection, VisibilityType,
22};
23
24pub type ObjectType = crate::collections::VecMap<String, Value>;
26
27#[derive(Clone, Debug, Default, PartialEq, mln_wire::Wire)]
29pub enum Value {
30 #[default]
31 Null,
32 Bool(bool),
33 Number(f64),
34 String(String),
35 Color(Color),
36 VariableAnchorOffsetCollection(VariableAnchorOffsetCollection),
37 Collator(#[wire(with = "no_collator")] Collator),
39 Formatted(Formatted),
40 Image(Image),
41 Padding(Padding),
42 ProjectionDefinition(ProjectionDefinition),
43 Array(Vec<Value>),
44 Object(ObjectType),
45}
46
47mod no_collator {
50
51 use crate::expression::locale::collator::Collator;
52
53 pub(super) fn write(_: &Collator, w: &mut mln_wire::Writer) {
54 w.fail("a collator value doesn't cross".to_owned());
55 }
56
57 pub(super) fn read(r: &mut mln_wire::Reader<'_>) -> Option<Collator> {
58 r.fail("a collator value doesn't cross")
59 }
60}
61
62impl Value {
63 #[must_use]
65 pub(crate) const fn max_safe_integer() -> u64 {
66 9_007_199_254_740_991
67 }
68
69 #[must_use]
70 pub(crate) const fn is_safe_integer_u64(x: u64) -> bool {
71 x <= Self::max_safe_integer()
72 }
73
74 #[must_use]
75 pub(crate) const fn is_safe_integer_i64(x: i64) -> bool {
76 x.unsigned_abs() <= Self::max_safe_integer()
77 }
78
79 #[must_use]
80 pub(crate) fn is_safe_integer_f64(x: f64) -> bool {
81 x.abs() <= Self::max_safe_integer() as f64
82 }
83
84 #[must_use]
85 pub(crate) fn as_number(&self) -> Option<f64> {
86 match self {
87 Value::Number(n) => Some(*n),
88 _ => None,
89 }
90 }
91
92 #[must_use]
93 pub(crate) fn as_bool(&self) -> Option<bool> {
94 match self {
95 Value::Bool(b) => Some(*b),
96 _ => None,
97 }
98 }
99
100 #[must_use]
101 pub(crate) fn as_str(&self) -> Option<&str> {
102 match self {
103 Value::String(s) => Some(s),
104 _ => None,
105 }
106 }
107}
108
109impl From<bool> for Value {
110 fn from(v: bool) -> Self {
111 Value::Bool(v)
112 }
113}
114impl From<f64> for Value {
115 fn from(v: f64) -> Self {
116 Value::Number(v)
117 }
118}
119impl From<&str> for Value {
120 fn from(v: &str) -> Self {
121 Value::String(v.to_owned())
122 }
123}
124impl From<String> for Value {
125 fn from(v: String) -> Self {
126 Value::String(v)
127 }
128}
129impl From<Color> for Value {
130 fn from(v: Color) -> Self {
131 Value::Color(v)
132 }
133}
134impl From<Padding> for Value {
135 fn from(v: Padding) -> Self {
136 Value::Padding(v)
137 }
138}
139impl From<ProjectionDefinition> for Value {
140 fn from(v: ProjectionDefinition) -> Self {
141 Value::ProjectionDefinition(v)
142 }
143}
144impl From<VariableAnchorOffsetCollection> for Value {
145 fn from(v: VariableAnchorOffsetCollection) -> Self {
146 Value::VariableAnchorOffsetCollection(v)
147 }
148}
149impl From<Collator> for Value {
150 fn from(v: Collator) -> Self {
151 Value::Collator(v)
152 }
153}
154impl From<Formatted> for Value {
155 fn from(v: Formatted) -> Self {
156 Value::Formatted(v)
157 }
158}
159impl From<Image> for Value {
160 fn from(v: Image) -> Self {
161 Value::Image(v)
162 }
163}
164impl From<Vec<Value>> for Value {
165 fn from(v: Vec<Value>) -> Self {
166 Value::Array(v)
167 }
168}
169impl From<ObjectType> for Value {
170 fn from(v: ObjectType) -> Self {
171 Value::Object(v)
172 }
173}
174
175pub(crate) fn hash_value(value: &Value, mut state: &mut dyn Hasher) {
179 std::mem::discriminant(value).hash(&mut state);
180 match value {
181 Value::Bool(b) => b.hash(&mut state),
182 Value::Number(n) => (if *n == 0.0 { 0.0_f64 } else { *n }).to_bits().hash(&mut state),
184 Value::String(s) => s.hash(&mut state),
185 Value::Array(values) => {
186 values.len().hash(&mut state);
187 for value in values {
188 hash_value(value, state);
189 }
190 }
191 _ => {}
192 }
193}
194
195#[must_use]
196pub fn type_of(value: &Value) -> Type {
197 match value {
198 Value::Bool(_) => Type::Boolean,
199 Value::Number(_) => Type::Number,
200 Value::String(_) => Type::String,
201 Value::Color(_) => Type::Color,
202 Value::Padding(_) => Type::Padding,
203 Value::ProjectionDefinition(_) => Type::ProjectionDefinition,
204 Value::VariableAnchorOffsetCollection(_) => Type::VariableAnchorOffsetCollection,
205 Value::Collator(_) => Type::Collator,
206 Value::Formatted(_) => Type::Formatted,
207 Value::Image(_) => Type::Image,
208 Value::Null => Type::Null,
209 Value::Object(_) => Type::Object,
210 Value::Array(arr) => {
211 let mut item_type: Option<Type> = None;
212 for item in arr {
213 let t = type_of(item);
214 match &item_type {
215 None => item_type = Some(t),
216 Some(it) if *it == t => {}
217 Some(_) => {
218 item_type = Some(Type::Value);
219 break;
220 }
221 }
222 }
223
224 Type::array_n(item_type.unwrap_or(Type::Value), arr.len())
225 }
226 }
227}
228
229#[must_use]
233pub(crate) fn to_string(value: &Value) -> String {
234 match value {
235 Value::Null => String::new(),
236 Value::Number(n) => to_string_double(*n),
237 Value::Color(c) => c.stringify(), Value::VariableAnchorOffsetCollection(v) => v.to_string(), Value::Formatted(f) => f.to_string(),
240 Value::Image(i) => i.id().to_owned(),
241 Value::String(s) => s.clone(), v => stringify(v),
243 }
244}
245
246fn json_number(n: f64) -> serde_json::Value {
249 serde_json::Number::from_f64(n).map_or(serde_json::Value::Null, serde_json::Value::Number)
250}
251
252fn to_json(value: &Value) -> serde_json::Value {
253 use serde_json::Value as Json;
254 match value {
255 Value::Null => Json::Null,
256 Value::Bool(b) => Json::Bool(*b),
257 Value::Number(n) => json_number(*n),
258 Value::String(s) => Json::String(s.clone()),
259 Value::Color(c) => Json::String(c.stringify()),
260 Value::Padding(p) => Json::Array([p.top, p.right, p.bottom, p.left].map(|v| json_number(v.into())).into()),
262 Value::ProjectionDefinition(p) => value_to_json(&p.serialize()),
263 Value::VariableAnchorOffsetCollection(v) => value_to_json(&v.serialize()),
264 Value::Collator(_) => {
265 debug_assert!(false, "stringify of a Collator");
269 Json::Null
270 }
271 Value::Formatted(_) | Value::Image(_) => value_to_json(&to_feature_value(value)),
274 Value::Array(arr) => Json::Array(arr.iter().map(to_json).collect()),
275 Value::Object(obj) => Json::Object(obj.iter().map(|(k, v)| (k.clone(), to_json(v))).collect()),
276 }
277}
278
279struct JsNumbers;
281
282impl serde_json::ser::Formatter for JsNumbers {
283 fn write_f64<W: ?Sized + std::io::Write>(&mut self, writer: &mut W, value: f64) -> std::io::Result<()> {
284 writer.write_all(to_string_double(value).as_bytes())
285 }
286}
287
288#[must_use]
291pub fn stringify(value: &Value) -> String {
292 let mut json = Vec::new();
293 let _ = to_json(value).serialize(&mut serde_json::Serializer::with_formatter(&mut json, JsNumbers));
295 String::from_utf8(json).unwrap_or_default()
296}
297
298pub fn from_feature_value(value: &FeatureValue) -> Value {
299 match value {
300 FeatureValue::Array(v) => Value::Array(v.iter().map(from_feature_value).collect()),
301 FeatureValue::Object(v) => Value::Object(v.iter().map(|(k, v)| (k.clone(), from_feature_value(v))).collect()),
302 FeatureValue::String(s) => Value::String(s.clone()),
303 FeatureValue::Bool(b) => Value::Bool(*b),
304 FeatureValue::Null => Value::Null,
305 FeatureValue::Double(v) => Value::Number(*v),
306 FeatureValue::Uint(v) => Value::Number(*v as f64),
307 FeatureValue::Int(v) => Value::Number(*v as f64),
308 }
309}
310
311pub(crate) fn from_feature_value_owned(value: FeatureValue) -> Value {
314 match value {
315 FeatureValue::Array(v) => Value::Array(v.into_iter().map(from_feature_value_owned).collect()),
316 FeatureValue::Object(v) => {
317 Value::Object(v.into_iter().map(|(k, v)| (k, from_feature_value_owned(v))).collect())
318 }
319 FeatureValue::String(s) => Value::String(s),
320 other => from_feature_value(&other),
321 }
322}
323
324pub fn to_feature_value(value: &Value) -> FeatureValue {
325 match value {
326 Value::Color(color) => color.serialize(),
327 Value::Padding(padding) => padding.serialize(),
328 Value::ProjectionDefinition(projection) => projection.serialize(),
329 Value::VariableAnchorOffsetCollection(anchor_offset) => anchor_offset.serialize(),
330 Value::Collator(_) => {
331 debug_assert!(false, "to_feature_value of a Collator");
333 FeatureValue::Null
334 }
335 Value::Formatted(formatted) => {
336 let mut serialized = vec![FeatureValue::String("format".to_owned())];
339 for section in &formatted.sections {
340 let mut options = ValueObject::new();
341 if let Some(vertical_align) = section.vertical_align {
342 options
343 .insert("vertical-align".to_owned(), FeatureValue::String(vertical_align.as_str().to_owned()));
344 }
345
346 if let Some(image) = §ion.image {
347 serialized.push(FeatureValue::Array(vec![
348 FeatureValue::String("image".to_owned()),
349 FeatureValue::String(image.id().to_owned()),
350 ]));
351 if !options.is_empty() {
352 serialized.push(FeatureValue::Object(options));
353 }
354 continue;
355 }
356
357 serialized.push(FeatureValue::String(section.text.clone()));
358
359 if let Some(font_scale) = section.font_scale {
360 options.insert("font-scale".to_owned(), FeatureValue::Double(font_scale));
361 }
362
363 if let Some(font_stack) = §ion.font_stack {
364 let font_stack: Vec<FeatureValue> =
365 font_stack.iter().map(|f| FeatureValue::String(f.clone())).collect();
366 options.insert(
367 "text-font".to_owned(),
368 FeatureValue::Array(vec![
369 FeatureValue::String("literal".to_owned()),
370 FeatureValue::Array(font_stack),
371 ]),
372 );
373 }
374
375 if let Some(text_color) = §ion.text_color {
376 options.insert("text-color".to_owned(), to_feature_value(&Value::Color(*text_color)));
377 }
378
379 serialized.push(FeatureValue::Object(options));
380 }
381 FeatureValue::Array(serialized)
382 }
383 Value::Image(i) => i.to_value(),
384 Value::Array(values) => FeatureValue::Array(values.iter().map(to_feature_value).collect()),
385 Value::Object(values) => {
386 FeatureValue::Object(values.iter().map(|(k, v)| (k.clone(), to_feature_value(v))).collect())
387 }
388 Value::Null => FeatureValue::Null,
389 Value::Bool(b) => FeatureValue::Bool(*b),
390 Value::Number(d) => FeatureValue::Double(*d),
391 Value::String(s) => FeatureValue::String(s.clone()),
392 }
393}
394
395pub trait ValueConverter: Sized {
398 fn expression_type() -> Type;
399 fn to_expression_value(&self) -> Value;
400 fn from_expression_value(value: &Value) -> Option<Self>;
401
402 #[must_use]
406 fn evaluate(expression: &Expr, context: &EvaluationContext<'_>) -> Option<Self> {
407 Self::from_expression_value(&expression.evaluate(context).ok()?)
408 }
409
410 fn vec_from_expression_value(value: &Value) -> Option<Vec<Self>> {
413 match value {
414 Value::Array(v) => v.iter().map(Self::from_expression_value).collect(),
415 _ => None,
416 }
417 }
418}
419
420#[must_use]
421pub fn from_expression_value<T: ValueConverter>(value: &Value) -> Option<T> {
422 T::from_expression_value(value)
423}
424
425#[must_use]
426pub fn from_expression_values<T: ValueConverter>(values: &[Option<Value>]) -> Vec<Option<T>> {
427 values.iter().map(|value| value.as_ref().and_then(from_expression_value::<T>)).collect()
428}
429
430impl ValueConverter for Value {
431 fn expression_type() -> Type {
432 Type::Value
433 }
434 fn to_expression_value(&self) -> Value {
435 self.clone()
436 }
437 fn from_expression_value(value: &Value) -> Option<Self> {
438 Some(value.clone())
439 }
440}
441
442impl ValueConverter for FeatureValue {
443 fn expression_type() -> Type {
445 Type::Value
446 }
447 fn to_expression_value(&self) -> Value {
448 from_feature_value(self)
449 }
450 fn from_expression_value(value: &Value) -> Option<Self> {
451 Some(to_feature_value(value))
452 }
453}
454
455impl ValueConverter for f32 {
458 fn expression_type() -> Type {
459 Type::Number
460 }
461 fn evaluate(expression: &Expr, context: &EvaluationContext<'_>) -> Option<Self> {
462 f64::evaluate(expression, context).map(|n| n as f32)
463 }
464 fn to_expression_value(&self) -> Value {
465 Value::Number(f64::from(*self))
466 }
467 fn from_expression_value(value: &Value) -> Option<Self> {
468 f64::from_expression_value(value).map(|d| d as f32)
469 }
470}
471
472impl ValueConverter for f64 {
475 fn expression_type() -> Type {
476 Type::Number
477 }
478 fn evaluate(expression: &Expr, context: &EvaluationContext<'_>) -> Option<Self> {
479 if expression.type_() != Type::Number {
480 return Self::from_expression_value(&expression.evaluate(context).ok()?);
481 }
482 expression.eval_num(context).ok().filter(|n| !n.is_nan())
483 }
484 fn to_expression_value(&self) -> Value {
485 Value::Number(*self)
486 }
487 fn from_expression_value(value: &Value) -> Option<Self> {
488 value.as_number().filter(|n| !n.is_nan())
489 }
490}
491
492fn evaluate_as_value<T: ValueConverter>(expression: &Expr, context: &EvaluationContext<'_>) -> Option<T> {
493 T::from_expression_value(&expression.evaluate(context).ok()?)
494}
495
496fn evaluate_bool(expression: &Expr, context: &EvaluationContext<'_>) -> Option<bool> {
497 expression.eval_bool(context).ok()
498}
499
500fn evaluate_string(expression: &Expr, context: &EvaluationContext<'_>) -> Option<String> {
501 expression.eval_str(context).ok().map(std::borrow::Cow::into_owned)
502}
503
504macro_rules! simple_value_converter {
505 ($t:ty, $variant:ident, $type_:expr) => {
506 simple_value_converter!($t, $variant, $type_, evaluate_as_value);
507 };
508 ($t:ty, $variant:ident, $type_:expr, $evaluate:path) => {
509 impl ValueConverter for $t {
510 fn expression_type() -> Type {
511 $type_
512 }
513 fn evaluate(expression: &Expr, context: &EvaluationContext<'_>) -> Option<Self> {
514 if expression.type_() != $type_ {
515 return Self::from_expression_value(&expression.evaluate(context).ok()?);
516 }
517 $evaluate(expression, context)
518 }
519 fn to_expression_value(&self) -> Value {
520 Value::$variant(self.clone())
521 }
522 fn from_expression_value(value: &Value) -> Option<Self> {
523 match value {
524 Value::$variant(v) => Some(v.clone()),
525 _ => None,
526 }
527 }
528 }
529 };
530}
531
532simple_value_converter!(bool, Bool, Type::Boolean, evaluate_bool);
533simple_value_converter!(String, String, Type::String, evaluate_string);
534impl ValueConverter for Color {
535 fn expression_type() -> Type {
536 Type::Color
537 }
538 fn evaluate(expression: &Expr, context: &EvaluationContext<'_>) -> Option<Self> {
539 if expression.type_() != Type::Color {
540 return Self::from_expression_value(&expression.evaluate(context).ok()?);
541 }
542 expression.eval_color(context).ok()
543 }
544 fn to_expression_value(&self) -> Value {
545 Value::Color(*self)
546 }
547 fn from_expression_value(value: &Value) -> Option<Self> {
548 match value {
549 Value::Color(v) => Some(*v),
550 _ => None,
551 }
552 }
553
554 fn vec_from_expression_value(value: &Value) -> Option<Vec<Self>> {
557 if let Value::Array(values) = value {
558 let mut result = Vec::with_capacity(values.len());
559 for v in values {
560 result.push(Color::from_expression_value(v)?);
561 }
562 return Some(result);
563 }
564
565 let color = Color::from_expression_value(value)?;
567 Some(vec![color])
568 }
569}
570simple_value_converter!(Padding, Padding, Type::Padding);
571simple_value_converter!(ProjectionDefinition, ProjectionDefinition, Type::ProjectionDefinition);
572simple_value_converter!(
573 VariableAnchorOffsetCollection,
574 VariableAnchorOffsetCollection,
575 Type::VariableAnchorOffsetCollection
576);
577simple_value_converter!(Collator, Collator, Type::Collator);
578simple_value_converter!(Formatted, Formatted, Type::Formatted);
579simple_value_converter!(Image, Image, Type::Image);
580simple_value_converter!(ObjectType, Object, Type::Object);
581
582impl<T: ValueConverter> ValueConverter for Vec<T> {
583 fn expression_type() -> Type {
584 Type::array(T::expression_type())
585 }
586 fn to_expression_value(&self) -> Value {
587 Value::Array(self.iter().map(T::to_expression_value).collect())
588 }
589 fn from_expression_value(value: &Value) -> Option<Self> {
590 T::vec_from_expression_value(value)
591 }
592}
593
594impl<T: ValueConverter, const N: usize> ValueConverter for [T; N] {
595 fn expression_type() -> Type {
596 Type::array_n(T::expression_type(), N)
597 }
598 fn to_expression_value(&self) -> Value {
599 Value::Array(self.iter().map(T::to_expression_value).collect())
600 }
601 fn from_expression_value(value: &Value) -> Option<Self> {
602 match value {
603 Value::Array(v) => {
604 if v.len() != N {
605 return None;
606 }
607 let items: Option<Vec<T>> = v.iter().map(T::from_expression_value).collect();
608 items.and_then(|items| items.try_into().ok())
609 }
610 _ => None,
611 }
612 }
613}
614
615impl ValueConverter for Position {
616 fn expression_type() -> Type {
617 Type::array_n(Type::Number, 3)
618 }
619 fn to_expression_value(&self) -> Value {
620 self.spherical().to_expression_value()
621 }
622 fn from_expression_value(value: &Value) -> Option<Self> {
623 <[f32; 3]>::from_expression_value(value).map(Position::new)
624 }
625}
626
627impl ValueConverter for Rotation {
628 fn expression_type() -> Type {
629 Type::Number
630 }
631 fn to_expression_value(&self) -> Value {
632 self.angle().to_expression_value()
633 }
634 fn from_expression_value(value: &Value) -> Option<Self> {
635 f64::from_expression_value(value).map(Rotation::new)
636 }
637}
638
639impl ValueConverter for LatLng {
641 fn expression_type() -> Type {
642 Type::array_n(Type::Number, 2)
643 }
644 fn to_expression_value(&self) -> Value {
645 Value::Array(vec![Value::Number(self.longitude()), Value::Number(self.latitude())])
646 }
647 fn from_expression_value(value: &Value) -> Option<Self> {
648 let [longitude, latitude] = <[f64; 2]>::from_expression_value(value)?;
649 LatLng::new(latitude, longitude).ok()
650 }
651}
652
653macro_rules! enum_value_converter {
654 ($($t:ty),* $(,)?) => {
655 $(
656 impl ValueConverter for $t {
657 fn expression_type() -> Type {
658 Type::String
659 }
660 fn to_expression_value(&self) -> Value {
661 Value::String(self.as_str().to_owned())
662 }
663 fn from_expression_value(value: &Value) -> Option<Self> {
664 match value {
665 Value::String(v) => v.parse().ok(),
666 _ => None,
667 }
668 }
669 }
670 )*
671 };
672}
673
674enum_value_converter!(
675 AlignmentType,
676 CirclePitchScaleType,
677 HillshadeIlluminationAnchorType,
678 HillshadeMethodType,
679 IconOverlapType,
680 IconTextFitType,
681 LayerBlendType,
682 LightAnchorType,
683 LineCapType,
684 LineJoinType,
685 RasterResamplingType,
686 ResamplingType,
687 RotateAnchorType,
688 SymbolAnchorType,
689 SymbolHeightAnchorType,
690 SymbolPlacementType,
691 SymbolZOrderType,
692 TextJustifyType,
693 TextRotationAlignmentType,
694 TextTransformType,
695 TextWritingModeType,
696 TranslateAnchorType,
697 VisibilityType,
698);
699
700#[cfg(test)]
701mod tests {
702 use super::*;
703
704 #[test]
705 fn type_of_arrays() {
706 let v = Value::Array(vec![Value::Number(1.0), Value::Number(2.0)]);
707 assert_eq!(type_of(&v), Type::array_n(Type::Number, 2));
708 let v = Value::Array(vec![Value::Number(1.0), Value::String("a".into())]);
709 assert_eq!(type_of(&v), Type::array_n(Type::Value, 2));
710 assert_eq!(type_of(&Value::Array(vec![])), Type::array_n(Type::Value, 0));
711 }
712
713 #[test]
714 fn safe_integers() {
715 assert!(Value::is_safe_integer_f64(9_007_199_254_740_991.0));
716 assert!(!Value::is_safe_integer_f64(9_007_199_254_740_992.0));
717 assert!(!Value::is_safe_integer_i64(i64::MIN));
718 }
719
720 #[test]
723 fn to_string_formats_numbers_as_javascript() {
724 let n = Value::Number;
725 assert_eq!(to_string(&n(1.0)), "1");
726 assert_eq!(to_string(&n(1e21)), "1e+21");
727 assert_eq!(to_string(&n(f64::NAN)), "NaN");
728 let array = Value::Array(vec![n(1.0), n(0.5), n(1e10), n(f64::INFINITY)]);
729 assert_eq!(to_string(&array), "[1,0.5,10000000000,null]");
730 let object = Value::Object([("a\n".to_owned(), n(-0.0))].into_iter().collect());
731 assert_eq!(to_string(&object), r#"{"a\n":0}"#);
732 }
733}