use std::hash::{Hash, Hasher};
use serde::Serialize;
use crate::color::Color;
use crate::conversion::value_to_json;
use crate::expression::formatted::Formatted;
use crate::expression::image::Image;
use crate::expression::locale::collator::Collator;
use crate::expression::type_::Type;
use crate::expression::{EvaluationContext, Expr};
use crate::feature::{Value as FeatureValue, ValueObject};
use crate::geo::LatLng;
use crate::padding::Padding;
use crate::string::to_string_double;
use crate::types::{
AlignmentType, CirclePitchScaleType, HillshadeIlluminationAnchorType, HillshadeMethodType, IconOverlapType,
IconTextFitType, LayerBlendType, LightAnchorType, LineCapType, LineJoinType, Position, ProjectionDefinition,
RasterResamplingType, ResamplingType, RotateAnchorType, Rotation, SymbolAnchorType, SymbolHeightAnchorType,
SymbolPlacementType, SymbolZOrderType, TextJustifyType, TextRotationAlignmentType, TextTransformType,
TextWritingModeType, TranslateAnchorType, VariableAnchorOffsetCollection, VisibilityType,
};
pub type ObjectType = crate::collections::VecMap<String, Value>;
#[derive(Clone, Debug, Default, PartialEq, mln_wire::Wire)]
pub enum Value {
#[default]
Null,
Bool(bool),
Number(f64),
String(String),
Color(Color),
VariableAnchorOffsetCollection(VariableAnchorOffsetCollection),
Collator(#[wire(with = "no_collator")] Collator),
Formatted(Formatted),
Image(Image),
Padding(Padding),
ProjectionDefinition(ProjectionDefinition),
Array(Vec<Value>),
Object(ObjectType),
}
mod no_collator {
use crate::expression::locale::collator::Collator;
pub(super) fn write(_: &Collator, w: &mut mln_wire::Writer) {
w.fail("a collator value doesn't cross".to_owned());
}
pub(super) fn read(r: &mut mln_wire::Reader<'_>) -> Option<Collator> {
r.fail("a collator value doesn't cross")
}
}
impl Value {
#[must_use]
pub(crate) const fn max_safe_integer() -> u64 {
9_007_199_254_740_991
}
#[must_use]
pub(crate) const fn is_safe_integer_u64(x: u64) -> bool {
x <= Self::max_safe_integer()
}
#[must_use]
pub(crate) const fn is_safe_integer_i64(x: i64) -> bool {
x.unsigned_abs() <= Self::max_safe_integer()
}
#[must_use]
pub(crate) fn is_safe_integer_f64(x: f64) -> bool {
x.abs() <= Self::max_safe_integer() as f64
}
#[must_use]
pub(crate) fn as_number(&self) -> Option<f64> {
match self {
Value::Number(n) => Some(*n),
_ => None,
}
}
#[must_use]
pub(crate) fn as_bool(&self) -> Option<bool> {
match self {
Value::Bool(b) => Some(*b),
_ => None,
}
}
#[must_use]
pub(crate) fn as_str(&self) -> Option<&str> {
match self {
Value::String(s) => Some(s),
_ => None,
}
}
}
impl From<bool> for Value {
fn from(v: bool) -> Self {
Value::Bool(v)
}
}
impl From<f64> for Value {
fn from(v: f64) -> Self {
Value::Number(v)
}
}
impl From<&str> for Value {
fn from(v: &str) -> Self {
Value::String(v.to_owned())
}
}
impl From<String> for Value {
fn from(v: String) -> Self {
Value::String(v)
}
}
impl From<Color> for Value {
fn from(v: Color) -> Self {
Value::Color(v)
}
}
impl From<Padding> for Value {
fn from(v: Padding) -> Self {
Value::Padding(v)
}
}
impl From<ProjectionDefinition> for Value {
fn from(v: ProjectionDefinition) -> Self {
Value::ProjectionDefinition(v)
}
}
impl From<VariableAnchorOffsetCollection> for Value {
fn from(v: VariableAnchorOffsetCollection) -> Self {
Value::VariableAnchorOffsetCollection(v)
}
}
impl From<Collator> for Value {
fn from(v: Collator) -> Self {
Value::Collator(v)
}
}
impl From<Formatted> for Value {
fn from(v: Formatted) -> Self {
Value::Formatted(v)
}
}
impl From<Image> for Value {
fn from(v: Image) -> Self {
Value::Image(v)
}
}
impl From<Vec<Value>> for Value {
fn from(v: Vec<Value>) -> Self {
Value::Array(v)
}
}
impl From<ObjectType> for Value {
fn from(v: ObjectType) -> Self {
Value::Object(v)
}
}
pub(crate) fn hash_value(value: &Value, mut state: &mut dyn Hasher) {
std::mem::discriminant(value).hash(&mut state);
match value {
Value::Bool(b) => b.hash(&mut state),
Value::Number(n) => (if *n == 0.0 { 0.0_f64 } else { *n }).to_bits().hash(&mut state),
Value::String(s) => s.hash(&mut state),
Value::Array(values) => {
values.len().hash(&mut state);
for value in values {
hash_value(value, state);
}
}
_ => {}
}
}
#[must_use]
pub fn type_of(value: &Value) -> Type {
match value {
Value::Bool(_) => Type::Boolean,
Value::Number(_) => Type::Number,
Value::String(_) => Type::String,
Value::Color(_) => Type::Color,
Value::Padding(_) => Type::Padding,
Value::ProjectionDefinition(_) => Type::ProjectionDefinition,
Value::VariableAnchorOffsetCollection(_) => Type::VariableAnchorOffsetCollection,
Value::Collator(_) => Type::Collator,
Value::Formatted(_) => Type::Formatted,
Value::Image(_) => Type::Image,
Value::Null => Type::Null,
Value::Object(_) => Type::Object,
Value::Array(arr) => {
let mut item_type: Option<Type> = None;
for item in arr {
let t = type_of(item);
match &item_type {
None => item_type = Some(t),
Some(it) if *it == t => {}
Some(_) => {
item_type = Some(Type::Value);
break;
}
}
}
Type::array_n(item_type.unwrap_or(Type::Value), arr.len())
}
}
}
#[must_use]
pub(crate) fn to_string(value: &Value) -> String {
match value {
Value::Null => String::new(),
Value::Number(n) => to_string_double(*n),
Value::Color(c) => c.stringify(), Value::VariableAnchorOffsetCollection(v) => v.to_string(), Value::Formatted(f) => f.to_string(),
Value::Image(i) => i.id().to_owned(),
Value::String(s) => s.clone(), v => stringify(v),
}
}
fn json_number(n: f64) -> serde_json::Value {
serde_json::Number::from_f64(n).map_or(serde_json::Value::Null, serde_json::Value::Number)
}
fn to_json(value: &Value) -> serde_json::Value {
use serde_json::Value as Json;
match value {
Value::Null => Json::Null,
Value::Bool(b) => Json::Bool(*b),
Value::Number(n) => json_number(*n),
Value::String(s) => Json::String(s.clone()),
Value::Color(c) => Json::String(c.stringify()),
Value::Padding(p) => Json::Array([p.top, p.right, p.bottom, p.left].map(|v| json_number(v.into())).into()),
Value::ProjectionDefinition(p) => value_to_json(&p.serialize()),
Value::VariableAnchorOffsetCollection(v) => value_to_json(&v.serialize()),
Value::Collator(_) => {
debug_assert!(false, "stringify of a Collator");
Json::Null
}
Value::Formatted(_) | Value::Image(_) => value_to_json(&to_feature_value(value)),
Value::Array(arr) => Json::Array(arr.iter().map(to_json).collect()),
Value::Object(obj) => Json::Object(obj.iter().map(|(k, v)| (k.clone(), to_json(v))).collect()),
}
}
struct JsNumbers;
impl serde_json::ser::Formatter for JsNumbers {
fn write_f64<W: ?Sized + std::io::Write>(&mut self, writer: &mut W, value: f64) -> std::io::Result<()> {
writer.write_all(to_string_double(value).as_bytes())
}
}
#[must_use]
pub fn stringify(value: &Value) -> String {
let mut json = Vec::new();
let _ = to_json(value).serialize(&mut serde_json::Serializer::with_formatter(&mut json, JsNumbers));
String::from_utf8(json).unwrap_or_default()
}
pub fn from_feature_value(value: &FeatureValue) -> Value {
match value {
FeatureValue::Array(v) => Value::Array(v.iter().map(from_feature_value).collect()),
FeatureValue::Object(v) => Value::Object(v.iter().map(|(k, v)| (k.clone(), from_feature_value(v))).collect()),
FeatureValue::String(s) => Value::String(s.clone()),
FeatureValue::Bool(b) => Value::Bool(*b),
FeatureValue::Null => Value::Null,
FeatureValue::Double(v) => Value::Number(*v),
FeatureValue::Uint(v) => Value::Number(*v as f64),
FeatureValue::Int(v) => Value::Number(*v as f64),
}
}
pub(crate) fn from_feature_value_owned(value: FeatureValue) -> Value {
match value {
FeatureValue::Array(v) => Value::Array(v.into_iter().map(from_feature_value_owned).collect()),
FeatureValue::Object(v) => {
Value::Object(v.into_iter().map(|(k, v)| (k, from_feature_value_owned(v))).collect())
}
FeatureValue::String(s) => Value::String(s),
other => from_feature_value(&other),
}
}
pub fn to_feature_value(value: &Value) -> FeatureValue {
match value {
Value::Color(color) => color.serialize(),
Value::Padding(padding) => padding.serialize(),
Value::ProjectionDefinition(projection) => projection.serialize(),
Value::VariableAnchorOffsetCollection(anchor_offset) => anchor_offset.serialize(),
Value::Collator(_) => {
debug_assert!(false, "to_feature_value of a Collator");
FeatureValue::Null
}
Value::Formatted(formatted) => {
let mut serialized = vec![FeatureValue::String("format".to_owned())];
for section in &formatted.sections {
let mut options = ValueObject::new();
if let Some(vertical_align) = section.vertical_align {
options
.insert("vertical-align".to_owned(), FeatureValue::String(vertical_align.as_str().to_owned()));
}
if let Some(image) = §ion.image {
serialized.push(FeatureValue::Array(vec![
FeatureValue::String("image".to_owned()),
FeatureValue::String(image.id().to_owned()),
]));
if !options.is_empty() {
serialized.push(FeatureValue::Object(options));
}
continue;
}
serialized.push(FeatureValue::String(section.text.clone()));
if let Some(font_scale) = section.font_scale {
options.insert("font-scale".to_owned(), FeatureValue::Double(font_scale));
}
if let Some(font_stack) = §ion.font_stack {
let font_stack: Vec<FeatureValue> =
font_stack.iter().map(|f| FeatureValue::String(f.clone())).collect();
options.insert(
"text-font".to_owned(),
FeatureValue::Array(vec![
FeatureValue::String("literal".to_owned()),
FeatureValue::Array(font_stack),
]),
);
}
if let Some(text_color) = §ion.text_color {
options.insert("text-color".to_owned(), to_feature_value(&Value::Color(*text_color)));
}
serialized.push(FeatureValue::Object(options));
}
FeatureValue::Array(serialized)
}
Value::Image(i) => i.to_value(),
Value::Array(values) => FeatureValue::Array(values.iter().map(to_feature_value).collect()),
Value::Object(values) => {
FeatureValue::Object(values.iter().map(|(k, v)| (k.clone(), to_feature_value(v))).collect())
}
Value::Null => FeatureValue::Null,
Value::Bool(b) => FeatureValue::Bool(*b),
Value::Number(d) => FeatureValue::Double(*d),
Value::String(s) => FeatureValue::String(s.clone()),
}
}
pub trait ValueConverter: Sized {
fn expression_type() -> Type;
fn to_expression_value(&self) -> Value;
fn from_expression_value(value: &Value) -> Option<Self>;
#[must_use]
fn evaluate(expression: &Expr, context: &EvaluationContext<'_>) -> Option<Self> {
Self::from_expression_value(&expression.evaluate(context).ok()?)
}
fn vec_from_expression_value(value: &Value) -> Option<Vec<Self>> {
match value {
Value::Array(v) => v.iter().map(Self::from_expression_value).collect(),
_ => None,
}
}
}
#[must_use]
pub fn from_expression_value<T: ValueConverter>(value: &Value) -> Option<T> {
T::from_expression_value(value)
}
#[must_use]
pub fn from_expression_values<T: ValueConverter>(values: &[Option<Value>]) -> Vec<Option<T>> {
values.iter().map(|value| value.as_ref().and_then(from_expression_value::<T>)).collect()
}
impl ValueConverter for Value {
fn expression_type() -> Type {
Type::Value
}
fn to_expression_value(&self) -> Value {
self.clone()
}
fn from_expression_value(value: &Value) -> Option<Self> {
Some(value.clone())
}
}
impl ValueConverter for FeatureValue {
fn expression_type() -> Type {
Type::Value
}
fn to_expression_value(&self) -> Value {
from_feature_value(self)
}
fn from_expression_value(value: &Value) -> Option<Self> {
Some(to_feature_value(value))
}
}
impl ValueConverter for f32 {
fn expression_type() -> Type {
Type::Number
}
fn evaluate(expression: &Expr, context: &EvaluationContext<'_>) -> Option<Self> {
f64::evaluate(expression, context).map(|n| n as f32)
}
fn to_expression_value(&self) -> Value {
Value::Number(f64::from(*self))
}
fn from_expression_value(value: &Value) -> Option<Self> {
f64::from_expression_value(value).map(|d| d as f32)
}
}
impl ValueConverter for f64 {
fn expression_type() -> Type {
Type::Number
}
fn evaluate(expression: &Expr, context: &EvaluationContext<'_>) -> Option<Self> {
if expression.type_() != Type::Number {
return Self::from_expression_value(&expression.evaluate(context).ok()?);
}
expression.eval_num(context).ok().filter(|n| !n.is_nan())
}
fn to_expression_value(&self) -> Value {
Value::Number(*self)
}
fn from_expression_value(value: &Value) -> Option<Self> {
value.as_number().filter(|n| !n.is_nan())
}
}
fn evaluate_as_value<T: ValueConverter>(expression: &Expr, context: &EvaluationContext<'_>) -> Option<T> {
T::from_expression_value(&expression.evaluate(context).ok()?)
}
fn evaluate_bool(expression: &Expr, context: &EvaluationContext<'_>) -> Option<bool> {
expression.eval_bool(context).ok()
}
fn evaluate_string(expression: &Expr, context: &EvaluationContext<'_>) -> Option<String> {
expression.eval_str(context).ok().map(std::borrow::Cow::into_owned)
}
macro_rules! simple_value_converter {
($t:ty, $variant:ident, $type_:expr) => {
simple_value_converter!($t, $variant, $type_, evaluate_as_value);
};
($t:ty, $variant:ident, $type_:expr, $evaluate:path) => {
impl ValueConverter for $t {
fn expression_type() -> Type {
$type_
}
fn evaluate(expression: &Expr, context: &EvaluationContext<'_>) -> Option<Self> {
if expression.type_() != $type_ {
return Self::from_expression_value(&expression.evaluate(context).ok()?);
}
$evaluate(expression, context)
}
fn to_expression_value(&self) -> Value {
Value::$variant(self.clone())
}
fn from_expression_value(value: &Value) -> Option<Self> {
match value {
Value::$variant(v) => Some(v.clone()),
_ => None,
}
}
}
};
}
simple_value_converter!(bool, Bool, Type::Boolean, evaluate_bool);
simple_value_converter!(String, String, Type::String, evaluate_string);
impl ValueConverter for Color {
fn expression_type() -> Type {
Type::Color
}
fn evaluate(expression: &Expr, context: &EvaluationContext<'_>) -> Option<Self> {
if expression.type_() != Type::Color {
return Self::from_expression_value(&expression.evaluate(context).ok()?);
}
expression.eval_color(context).ok()
}
fn to_expression_value(&self) -> Value {
Value::Color(*self)
}
fn from_expression_value(value: &Value) -> Option<Self> {
match value {
Value::Color(v) => Some(*v),
_ => None,
}
}
fn vec_from_expression_value(value: &Value) -> Option<Vec<Self>> {
if let Value::Array(values) = value {
let mut result = Vec::with_capacity(values.len());
for v in values {
result.push(Color::from_expression_value(v)?);
}
return Some(result);
}
let color = Color::from_expression_value(value)?;
Some(vec![color])
}
}
simple_value_converter!(Padding, Padding, Type::Padding);
simple_value_converter!(ProjectionDefinition, ProjectionDefinition, Type::ProjectionDefinition);
simple_value_converter!(
VariableAnchorOffsetCollection,
VariableAnchorOffsetCollection,
Type::VariableAnchorOffsetCollection
);
simple_value_converter!(Collator, Collator, Type::Collator);
simple_value_converter!(Formatted, Formatted, Type::Formatted);
simple_value_converter!(Image, Image, Type::Image);
simple_value_converter!(ObjectType, Object, Type::Object);
impl<T: ValueConverter> ValueConverter for Vec<T> {
fn expression_type() -> Type {
Type::array(T::expression_type())
}
fn to_expression_value(&self) -> Value {
Value::Array(self.iter().map(T::to_expression_value).collect())
}
fn from_expression_value(value: &Value) -> Option<Self> {
T::vec_from_expression_value(value)
}
}
impl<T: ValueConverter, const N: usize> ValueConverter for [T; N] {
fn expression_type() -> Type {
Type::array_n(T::expression_type(), N)
}
fn to_expression_value(&self) -> Value {
Value::Array(self.iter().map(T::to_expression_value).collect())
}
fn from_expression_value(value: &Value) -> Option<Self> {
match value {
Value::Array(v) => {
if v.len() != N {
return None;
}
let items: Option<Vec<T>> = v.iter().map(T::from_expression_value).collect();
items.and_then(|items| items.try_into().ok())
}
_ => None,
}
}
}
impl ValueConverter for Position {
fn expression_type() -> Type {
Type::array_n(Type::Number, 3)
}
fn to_expression_value(&self) -> Value {
self.spherical().to_expression_value()
}
fn from_expression_value(value: &Value) -> Option<Self> {
<[f32; 3]>::from_expression_value(value).map(Position::new)
}
}
impl ValueConverter for Rotation {
fn expression_type() -> Type {
Type::Number
}
fn to_expression_value(&self) -> Value {
self.angle().to_expression_value()
}
fn from_expression_value(value: &Value) -> Option<Self> {
f64::from_expression_value(value).map(Rotation::new)
}
}
impl ValueConverter for LatLng {
fn expression_type() -> Type {
Type::array_n(Type::Number, 2)
}
fn to_expression_value(&self) -> Value {
Value::Array(vec![Value::Number(self.longitude()), Value::Number(self.latitude())])
}
fn from_expression_value(value: &Value) -> Option<Self> {
let [longitude, latitude] = <[f64; 2]>::from_expression_value(value)?;
LatLng::new(latitude, longitude).ok()
}
}
macro_rules! enum_value_converter {
($($t:ty),* $(,)?) => {
$(
impl ValueConverter for $t {
fn expression_type() -> Type {
Type::String
}
fn to_expression_value(&self) -> Value {
Value::String(self.as_str().to_owned())
}
fn from_expression_value(value: &Value) -> Option<Self> {
match value {
Value::String(v) => v.parse().ok(),
_ => None,
}
}
}
)*
};
}
enum_value_converter!(
AlignmentType,
CirclePitchScaleType,
HillshadeIlluminationAnchorType,
HillshadeMethodType,
IconOverlapType,
IconTextFitType,
LayerBlendType,
LightAnchorType,
LineCapType,
LineJoinType,
RasterResamplingType,
ResamplingType,
RotateAnchorType,
SymbolAnchorType,
SymbolHeightAnchorType,
SymbolPlacementType,
SymbolZOrderType,
TextJustifyType,
TextRotationAlignmentType,
TextTransformType,
TextWritingModeType,
TranslateAnchorType,
VisibilityType,
);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn type_of_arrays() {
let v = Value::Array(vec![Value::Number(1.0), Value::Number(2.0)]);
assert_eq!(type_of(&v), Type::array_n(Type::Number, 2));
let v = Value::Array(vec![Value::Number(1.0), Value::String("a".into())]);
assert_eq!(type_of(&v), Type::array_n(Type::Value, 2));
assert_eq!(type_of(&Value::Array(vec![])), Type::array_n(Type::Value, 0));
}
#[test]
fn safe_integers() {
assert!(Value::is_safe_integer_f64(9_007_199_254_740_991.0));
assert!(!Value::is_safe_integer_f64(9_007_199_254_740_992.0));
assert!(!Value::is_safe_integer_i64(i64::MIN));
}
#[test]
fn to_string_formats_numbers_as_javascript() {
let n = Value::Number;
assert_eq!(to_string(&n(1.0)), "1");
assert_eq!(to_string(&n(1e21)), "1e+21");
assert_eq!(to_string(&n(f64::NAN)), "NaN");
let array = Value::Array(vec![n(1.0), n(0.5), n(1e10), n(f64::INFINITY)]);
assert_eq!(to_string(&array), "[1,0.5,10000000000,null]");
let object = Value::Object([("a\n".to_owned(), n(-0.0))].into_iter().collect());
assert_eq!(to_string(&object), r#"{"a\n":0}"#);
}
}