use std::collections::HashMap;
use crate::foundation::{id, NSData, NSMutableDictionary, NSNumber, NSString};
#[derive(Clone, Debug, PartialEq)]
pub enum Value {
Bool(bool),
String(String),
Float(f64),
Integer(i64),
Data(Vec<u8>)
}
impl Value {
pub fn string<S: Into<String>>(value: S) -> Self {
Value::String(value.into())
}
pub fn is_boolean(&self) -> bool {
match self {
Value::Bool(_) => true,
_ => false
}
}
pub fn as_bool(&self) -> Option<bool> {
match self {
Value::Bool(v) => Some(*v),
_ => None
}
}
pub fn is_string(&self) -> bool {
match self {
Value::String(_) => true,
_ => false
}
}
pub fn as_str(&self) -> Option<&str> {
match self {
Value::String(s) => Some(s),
_ => None
}
}
pub fn is_integer(&self) -> bool {
match self {
Value::Integer(_) => true,
_ => false
}
}
pub fn as_i32(&self) -> Option<i32> {
match self {
Value::Integer(i) => Some(*i as i32),
_ => None
}
}
pub fn as_i64(&self) -> Option<i64> {
match self {
Value::Integer(i) => Some(*i as i64),
_ => None
}
}
pub fn is_float(&self) -> bool {
match self {
Value::Float(_) => true,
_ => false
}
}
pub fn as_f32(&self) -> Option<f32> {
match self {
Value::Float(f) => Some(*f as f32),
_ => None
}
}
pub fn as_f64(&self) -> Option<f64> {
match self {
Value::Float(f) => Some(*f as f64),
_ => None
}
}
pub fn is_data(&self) -> bool {
match self {
Value::Data(_) => true,
_ => false
}
}
pub fn as_data(&self) -> Option<&[u8]> {
match self {
Value::Data(data) => Some(data),
_ => None
}
}
}
impl From<Value> for id {
fn from(value: Value) -> Self {
match value {
Value::Bool(b) => NSNumber::bool(b).into(),
Value::String(s) => NSString::new(&s).into(),
Value::Float(f) => NSNumber::float(f).into(),
Value::Integer(i) => NSNumber::integer(i).into(),
Value::Data(data) => NSData::new(data).into()
}
}
}
impl<K> From<HashMap<K, Value>> for NSMutableDictionary
where
K: AsRef<str>
{
fn from(map: HashMap<K, Value>) -> Self {
let mut dictionary = NSMutableDictionary::new();
for (key, value) in map.into_iter() {
let k = NSString::new(key.as_ref());
dictionary.insert(k, value.into());
}
dictionary
}
}