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