1use std::hash::{Hash, Hasher};
2
3use feature::{Value as MbglValue, ValueObject};
4use mln_conversion::value_to_json;
5use mln_style_types::{
6 AlignmentType, CirclePitchScaleType, HillshadeIlluminationAnchorType, HillshadeMethodType, IconOverlapType,
7 IconTextFitType, LayerBlendType, LightAnchorType, LineCapType, LineJoinType, Position, ProjectionDefinition,
8 RasterResamplingType, ResamplingType, RotateAnchorType, Rotation, SymbolAnchorType, SymbolPlacementType,
9 SymbolZOrderType, TextJustifyType, TextRotationAlignmentType, TextTransformType, TextWritingModeType,
10 TranslateAnchorType, VariableAnchorOffsetCollection, VisibilityType,
11};
12use mln_util::string::to_string_double;
13use mln_util::{Color, Padding};
14use serde::Serialize;
15
16use crate::collator::Collator;
17use crate::expression::{EvaluationContext, Expr};
18use crate::formatted::Formatted;
19use crate::image::Image;
20use crate::type_::Type;
21
22pub type ObjectType = mln_vec_map::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::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 (if x > 0 { x } else { x.wrapping_neg() }) as u64 <= Self::max_safe_integer()
78 }
79
80 #[must_use]
81 pub(crate) fn is_safe_integer_f64(x: f64) -> bool {
82 ((if x > 0.0 { x } else { -x }) as u64) <= Self::max_safe_integer()
85 }
86
87 #[must_use]
88 pub(crate) fn as_number(&self) -> Option<f64> {
89 match self {
90 Value::Number(n) => Some(*n),
91 _ => None,
92 }
93 }
94
95 #[must_use]
96 pub(crate) fn as_bool(&self) -> Option<bool> {
97 match self {
98 Value::Bool(b) => Some(*b),
99 _ => None,
100 }
101 }
102
103 #[must_use]
104 pub(crate) fn as_str(&self) -> Option<&str> {
105 match self {
106 Value::String(s) => Some(s),
107 _ => None,
108 }
109 }
110}
111
112impl From<bool> for Value {
113 fn from(v: bool) -> Self {
114 Value::Bool(v)
115 }
116}
117impl From<f64> for Value {
118 fn from(v: f64) -> Self {
119 Value::Number(v)
120 }
121}
122impl From<&str> for Value {
123 fn from(v: &str) -> Self {
124 Value::String(v.to_owned())
125 }
126}
127impl From<String> for Value {
128 fn from(v: String) -> Self {
129 Value::String(v)
130 }
131}
132impl From<Color> for Value {
133 fn from(v: Color) -> Self {
134 Value::Color(v)
135 }
136}
137impl From<Padding> for Value {
138 fn from(v: Padding) -> Self {
139 Value::Padding(v)
140 }
141}
142impl From<ProjectionDefinition> for Value {
143 fn from(v: ProjectionDefinition) -> Self {
144 Value::ProjectionDefinition(v)
145 }
146}
147impl From<VariableAnchorOffsetCollection> for Value {
148 fn from(v: VariableAnchorOffsetCollection) -> Self {
149 Value::VariableAnchorOffsetCollection(v)
150 }
151}
152impl From<Collator> for Value {
153 fn from(v: Collator) -> Self {
154 Value::Collator(v)
155 }
156}
157impl From<Formatted> for Value {
158 fn from(v: Formatted) -> Self {
159 Value::Formatted(v)
160 }
161}
162impl From<Image> for Value {
163 fn from(v: Image) -> Self {
164 Value::Image(v)
165 }
166}
167impl From<Vec<Value>> for Value {
168 fn from(v: Vec<Value>) -> Self {
169 Value::Array(v)
170 }
171}
172impl From<ObjectType> for Value {
173 fn from(v: ObjectType) -> Self {
174 Value::Object(v)
175 }
176}
177
178pub(crate) fn hash_value(value: &Value, mut state: &mut dyn Hasher) {
182 std::mem::discriminant(value).hash(&mut state);
183 match value {
184 Value::Bool(b) => b.hash(&mut state),
185 Value::Number(n) => (if *n == 0.0 { 0.0_f64 } else { *n }).to_bits().hash(&mut state),
187 Value::String(s) => s.hash(&mut state),
188 Value::Array(values) => {
189 values.len().hash(&mut state);
190 for value in values {
191 hash_value(value, state);
192 }
193 }
194 _ => {}
195 }
196}
197
198#[must_use]
199pub fn type_of(value: &Value) -> Type {
200 match value {
201 Value::Bool(_) => Type::Boolean,
202 Value::Number(_) => Type::Number,
203 Value::String(_) => Type::String,
204 Value::Color(_) => Type::Color,
205 Value::Padding(_) => Type::Padding,
206 Value::ProjectionDefinition(_) => Type::ProjectionDefinition,
207 Value::VariableAnchorOffsetCollection(_) => Type::VariableAnchorOffsetCollection,
208 Value::Collator(_) => Type::Collator,
209 Value::Formatted(_) => Type::Formatted,
210 Value::Image(_) => Type::Image,
211 Value::Null => Type::Null,
212 Value::Object(_) => Type::Object,
213 Value::Array(arr) => {
214 let mut item_type: Option<Type> = None;
215 for item in arr {
216 let t = type_of(item);
217 match &item_type {
218 None => item_type = Some(t),
219 Some(it) if *it == t => {}
220 Some(_) => {
221 item_type = Some(Type::Value);
222 break;
223 }
224 }
225 }
226
227 Type::array_n(item_type.unwrap_or(Type::Value), arr.len())
228 }
229 }
230}
231
232#[must_use]
236pub(crate) fn to_string(value: &Value) -> String {
237 match value {
238 Value::Null => String::new(),
239 Value::Number(n) => to_string_double(*n),
240 Value::Color(c) => c.stringify(), Value::VariableAnchorOffsetCollection(v) => v.to_string(), Value::Formatted(f) => f.to_string(),
243 Value::Image(i) => i.id().to_owned(),
244 Value::String(s) => s.clone(), v => stringify(v),
246 }
247}
248
249fn json_number(n: f64) -> serde_json::Value {
252 serde_json::Number::from_f64(n).map_or(serde_json::Value::Null, serde_json::Value::Number)
253}
254
255fn to_json(value: &Value) -> serde_json::Value {
256 use serde_json::Value as Json;
257 match value {
258 Value::Null => Json::Null,
259 Value::Bool(b) => Json::Bool(*b),
260 Value::Number(n) => json_number(*n),
261 Value::String(s) => Json::String(s.clone()),
262 Value::Color(c) => Json::String(c.stringify()),
263 Value::Padding(p) => Json::Array([p.top, p.right, p.bottom, p.left].map(|v| json_number(v.into())).into()),
265 Value::ProjectionDefinition(p) => value_to_json(&p.serialize()),
266 Value::VariableAnchorOffsetCollection(v) => value_to_json(&v.serialize()),
267 Value::Collator(_) => {
268 debug_assert!(false, "stringify of a Collator");
272 Json::Null
273 }
274 Value::Formatted(_) | Value::Image(_) => value_to_json(&to_mbgl_value(value)),
277 Value::Array(arr) => Json::Array(arr.iter().map(to_json).collect()),
278 Value::Object(obj) => Json::Object(obj.iter().map(|(k, v)| (k.clone(), to_json(v))).collect()),
279 }
280}
281
282struct JsNumbers;
284
285impl serde_json::ser::Formatter for JsNumbers {
286 fn write_f64<W: ?Sized + std::io::Write>(&mut self, writer: &mut W, value: f64) -> std::io::Result<()> {
287 writer.write_all(to_string_double(value).as_bytes())
288 }
289}
290
291#[must_use]
294pub fn stringify(value: &Value) -> String {
295 let mut json = Vec::new();
296 let _ = to_json(value).serialize(&mut serde_json::Serializer::with_formatter(&mut json, JsNumbers));
298 String::from_utf8(json).unwrap_or_default()
299}
300
301pub fn from_mbgl_value(value: &MbglValue) -> Value {
302 match value {
303 MbglValue::Array(v) => Value::Array(v.iter().map(from_mbgl_value).collect()),
304 MbglValue::Object(v) => Value::Object(v.iter().map(|(k, v)| (k.clone(), from_mbgl_value(v))).collect()),
305 MbglValue::String(s) => Value::String(s.clone()),
306 MbglValue::Bool(b) => Value::Bool(*b),
307 MbglValue::Null => Value::Null,
308 MbglValue::Double(v) => Value::Number(*v),
309 MbglValue::Uint(v) => Value::Number(*v as f64),
310 MbglValue::Int(v) => Value::Number(*v as f64),
311 }
312}
313
314pub(crate) fn from_mbgl_value_owned(value: MbglValue) -> Value {
317 match value {
318 MbglValue::Array(v) => Value::Array(v.into_iter().map(from_mbgl_value_owned).collect()),
319 MbglValue::Object(v) => Value::Object(v.into_iter().map(|(k, v)| (k, from_mbgl_value_owned(v))).collect()),
320 MbglValue::String(s) => Value::String(s),
321 other => from_mbgl_value(&other),
322 }
323}
324
325pub fn to_mbgl_value(value: &Value) -> MbglValue {
326 match value {
327 Value::Color(color) => color.serialize(),
328 Value::Padding(padding) => padding.serialize(),
329 Value::ProjectionDefinition(projection) => projection.serialize(),
330 Value::VariableAnchorOffsetCollection(anchor_offset) => anchor_offset.serialize(),
331 Value::Collator(_) => {
332 debug_assert!(false, "to_mbgl_value of a Collator");
335 MbglValue::Null
336 }
337 Value::Formatted(formatted) => {
338 let mut serialized = vec![MbglValue::String("format".to_owned())];
341 for section in &formatted.sections {
342 let mut options = ValueObject::new();
343 if let Some(vertical_align) = section.vertical_align {
344 options.insert("vertical-align".to_owned(), MbglValue::String(vertical_align.as_str().to_owned()));
345 }
346
347 if let Some(image) = §ion.image {
348 serialized.push(MbglValue::Array(vec![
349 MbglValue::String("image".to_owned()),
350 MbglValue::String(image.id().to_owned()),
351 ]));
352 if !options.is_empty() {
353 serialized.push(MbglValue::Object(options));
354 }
355 continue;
356 }
357
358 serialized.push(MbglValue::String(section.text.clone()));
359
360 if let Some(font_scale) = section.font_scale {
361 options.insert("font-scale".to_owned(), MbglValue::Double(font_scale));
362 }
363
364 if let Some(font_stack) = §ion.font_stack {
365 let font_stack: Vec<MbglValue> = font_stack.iter().map(|f| MbglValue::String(f.clone())).collect();
366 options.insert(
367 "text-font".to_owned(),
368 MbglValue::Array(vec![MbglValue::String("literal".to_owned()), MbglValue::Array(font_stack)]),
369 );
370 }
371
372 if let Some(text_color) = §ion.text_color {
373 options.insert("text-color".to_owned(), to_mbgl_value(&Value::Color(*text_color)));
374 }
375
376 serialized.push(MbglValue::Object(options));
377 }
378 MbglValue::Array(serialized)
379 }
380 Value::Image(i) => i.to_value(),
381 Value::Array(values) => MbglValue::Array(values.iter().map(to_mbgl_value).collect()),
382 Value::Object(values) => MbglValue::Object(values.iter().map(|(k, v)| (k.clone(), to_mbgl_value(v))).collect()),
383 Value::Null => MbglValue::Null,
384 Value::Bool(b) => MbglValue::Bool(*b),
385 Value::Number(d) => MbglValue::Double(*d),
386 Value::String(s) => MbglValue::String(s.clone()),
387 }
388}
389
390pub trait ValueConverter: Sized {
393 fn expression_type() -> Type;
394 fn to_expression_value(&self) -> Value;
395 fn from_expression_value(value: &Value) -> Option<Self>;
396
397 #[must_use]
401 fn evaluate(expression: &Expr, context: &EvaluationContext<'_>) -> Option<Self> {
402 Self::from_expression_value(&expression.evaluate(context).ok()?)
403 }
404
405 fn vec_from_expression_value(value: &Value) -> Option<Vec<Self>> {
408 match value {
409 Value::Array(v) => v.iter().map(Self::from_expression_value).collect(),
410 _ => None,
411 }
412 }
413}
414
415#[must_use]
416pub fn from_expression_value<T: ValueConverter>(value: &Value) -> Option<T> {
417 T::from_expression_value(value)
418}
419
420#[must_use]
421pub fn from_expression_values<T: ValueConverter>(values: &[Option<Value>]) -> Vec<Option<T>> {
422 values.iter().map(|value| value.as_ref().and_then(from_expression_value::<T>)).collect()
423}
424
425impl ValueConverter for Value {
426 fn expression_type() -> Type {
427 Type::Value
428 }
429 fn to_expression_value(&self) -> Value {
430 self.clone()
431 }
432 fn from_expression_value(value: &Value) -> Option<Self> {
433 Some(value.clone())
434 }
435}
436
437impl ValueConverter for MbglValue {
438 fn expression_type() -> Type {
440 Type::Value
441 }
442 fn to_expression_value(&self) -> Value {
443 from_mbgl_value(self)
444 }
445 fn from_expression_value(value: &Value) -> Option<Self> {
446 Some(to_mbgl_value(value))
447 }
448}
449
450impl ValueConverter for f32 {
451 fn expression_type() -> Type {
452 Type::Number
453 }
454 fn evaluate(expression: &Expr, context: &EvaluationContext<'_>) -> Option<Self> {
455 if expression.get_type() != Type::Number {
456 return Self::from_expression_value(&expression.evaluate(context).ok()?);
457 }
458 expression.eval_num(context).ok().map(|n| n as f32)
459 }
460 fn to_expression_value(&self) -> Value {
461 Value::Number(f64::from(*self))
462 }
463 fn from_expression_value(value: &Value) -> Option<Self> {
464 value.as_number().map(|d| d as f32)
465 }
466}
467
468fn evaluate_as_value<T: ValueConverter>(expression: &Expr, context: &EvaluationContext<'_>) -> Option<T> {
469 T::from_expression_value(&expression.evaluate(context).ok()?)
470}
471
472fn evaluate_bool(expression: &Expr, context: &EvaluationContext<'_>) -> Option<bool> {
473 expression.eval_bool(context).ok()
474}
475
476fn evaluate_number(expression: &Expr, context: &EvaluationContext<'_>) -> Option<f64> {
477 expression.eval_num(context).ok()
478}
479
480fn evaluate_string(expression: &Expr, context: &EvaluationContext<'_>) -> Option<String> {
481 expression.eval_str(context).ok().map(std::borrow::Cow::into_owned)
482}
483
484macro_rules! simple_value_converter {
485 ($t:ty, $variant:ident, $type_:expr) => {
486 simple_value_converter!($t, $variant, $type_, evaluate_as_value);
487 };
488 ($t:ty, $variant:ident, $type_:expr, $evaluate:path) => {
489 impl ValueConverter for $t {
490 fn expression_type() -> Type {
491 $type_
492 }
493 fn evaluate(expression: &Expr, context: &EvaluationContext<'_>) -> Option<Self> {
494 if expression.get_type() != $type_ {
495 return Self::from_expression_value(&expression.evaluate(context).ok()?);
496 }
497 $evaluate(expression, context)
498 }
499 fn to_expression_value(&self) -> Value {
500 Value::$variant(self.clone())
501 }
502 fn from_expression_value(value: &Value) -> Option<Self> {
503 match value {
504 Value::$variant(v) => Some(v.clone()),
505 _ => None,
506 }
507 }
508 }
509 };
510}
511
512simple_value_converter!(bool, Bool, Type::Boolean, evaluate_bool);
513simple_value_converter!(f64, Number, Type::Number, evaluate_number);
514simple_value_converter!(String, String, Type::String, evaluate_string);
515impl ValueConverter for Color {
516 fn expression_type() -> Type {
517 Type::Color
518 }
519 fn evaluate(expression: &Expr, context: &EvaluationContext<'_>) -> Option<Self> {
520 if expression.get_type() != Type::Color {
521 return Self::from_expression_value(&expression.evaluate(context).ok()?);
522 }
523 expression.eval_color(context).ok()
524 }
525 fn to_expression_value(&self) -> Value {
526 Value::Color(*self)
527 }
528 fn from_expression_value(value: &Value) -> Option<Self> {
529 match value {
530 Value::Color(v) => Some(*v),
531 _ => None,
532 }
533 }
534
535 fn vec_from_expression_value(value: &Value) -> Option<Vec<Self>> {
538 if let Value::Array(values) = value {
539 let mut result = Vec::with_capacity(values.len());
540 for v in values {
541 result.push(Color::from_expression_value(v)?);
542 }
543 return Some(result);
544 }
545
546 let color = Color::from_expression_value(value)?;
548 Some(vec![color])
549 }
550}
551simple_value_converter!(Padding, Padding, Type::Padding);
552simple_value_converter!(ProjectionDefinition, ProjectionDefinition, Type::ProjectionDefinition);
553simple_value_converter!(
554 VariableAnchorOffsetCollection,
555 VariableAnchorOffsetCollection,
556 Type::VariableAnchorOffsetCollection
557);
558simple_value_converter!(Collator, Collator, Type::Collator);
559simple_value_converter!(Formatted, Formatted, Type::Formatted);
560simple_value_converter!(Image, Image, Type::Image);
561simple_value_converter!(ObjectType, Object, Type::Object);
562
563impl<T: ValueConverter> ValueConverter for Vec<T> {
564 fn expression_type() -> Type {
565 Type::array(T::expression_type())
566 }
567 fn to_expression_value(&self) -> Value {
568 Value::Array(self.iter().map(T::to_expression_value).collect())
569 }
570 fn from_expression_value(value: &Value) -> Option<Self> {
571 T::vec_from_expression_value(value)
572 }
573}
574
575impl<T: ValueConverter, const N: usize> ValueConverter for [T; N] {
576 fn expression_type() -> Type {
577 Type::array_n(T::expression_type(), N)
578 }
579 fn to_expression_value(&self) -> Value {
580 Value::Array(self.iter().map(T::to_expression_value).collect())
581 }
582 fn from_expression_value(value: &Value) -> Option<Self> {
583 match value {
584 Value::Array(v) => {
585 if v.len() != N {
586 return None;
587 }
588 let items: Option<Vec<T>> = v.iter().map(T::from_expression_value).collect();
589 items.and_then(|items| items.try_into().ok())
590 }
591 _ => None,
592 }
593 }
594}
595
596impl ValueConverter for Position {
597 fn expression_type() -> Type {
598 Type::array_n(Type::Number, 3)
599 }
600 fn to_expression_value(&self) -> Value {
601 self.get_spherical().to_expression_value()
602 }
603 fn from_expression_value(value: &Value) -> Option<Self> {
604 <[f32; 3]>::from_expression_value(value).map(Position::new)
605 }
606}
607
608impl ValueConverter for Rotation {
609 fn expression_type() -> Type {
610 Type::Number
611 }
612 fn to_expression_value(&self) -> Value {
613 (self.get_angle() as f32).to_expression_value()
614 }
615 fn from_expression_value(value: &Value) -> Option<Self> {
616 f32::from_expression_value(value).map(|angle| Rotation::new(f64::from(angle)))
617 }
618}
619
620macro_rules! enum_value_converter {
621 ($($t:ty),* $(,)?) => {
622 $(
623 impl ValueConverter for $t {
624 fn expression_type() -> Type {
625 Type::String
626 }
627 fn to_expression_value(&self) -> Value {
628 Value::String(self.as_str().to_owned())
629 }
630 fn from_expression_value(value: &Value) -> Option<Self> {
631 match value {
632 Value::String(v) => v.parse().ok(),
633 _ => None,
634 }
635 }
636 }
637 )*
638 };
639}
640
641enum_value_converter!(
642 AlignmentType,
643 CirclePitchScaleType,
644 HillshadeIlluminationAnchorType,
645 HillshadeMethodType,
646 IconOverlapType,
647 IconTextFitType,
648 LayerBlendType,
649 LightAnchorType,
650 LineCapType,
651 LineJoinType,
652 RasterResamplingType,
653 ResamplingType,
654 RotateAnchorType,
655 SymbolAnchorType,
656 SymbolPlacementType,
657 SymbolZOrderType,
658 TextJustifyType,
659 TextRotationAlignmentType,
660 TextTransformType,
661 TextWritingModeType,
662 TranslateAnchorType,
663 VisibilityType,
664);
665
666#[cfg(test)]
667mod tests {
668 use super::*;
669
670 #[test]
671 fn type_of_arrays() {
672 let v = Value::Array(vec![Value::Number(1.0), Value::Number(2.0)]);
673 assert_eq!(type_of(&v), Type::array_n(Type::Number, 2));
674 let v = Value::Array(vec![Value::Number(1.0), Value::String("a".into())]);
675 assert_eq!(type_of(&v), Type::array_n(Type::Value, 2));
676 assert_eq!(type_of(&Value::Array(vec![])), Type::array_n(Type::Value, 0));
677 }
678
679 #[test]
680 fn safe_integers() {
681 assert!(Value::is_safe_integer_f64(9_007_199_254_740_991.0));
682 assert!(!Value::is_safe_integer_f64(9_007_199_254_740_992.0));
683 assert!(!Value::is_safe_integer_i64(i64::MIN));
684 }
685
686 #[test]
689 fn to_string_formats_numbers_as_javascript() {
690 let n = Value::Number;
691 assert_eq!(to_string(&n(1.0)), "1");
692 assert_eq!(to_string(&n(1e21)), "1e+21");
693 assert_eq!(to_string(&n(f64::NAN)), "NaN");
694 let array = Value::Array(vec![n(1.0), n(0.5), n(1e10), n(f64::INFINITY)]);
695 assert_eq!(to_string(&array), "[1,0.5,10000000000,null]");
696 let object = Value::Object([("a\n".to_owned(), n(-0.0))].into_iter().collect());
697 assert_eq!(to_string(&object), r#"{"a\n":0}"#);
698 }
699}