fusabi-host 0.1.0

Shared host/runtime utilities for Fusabi across Scarab/Tolaria/Hibana/Phage
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
//! Value conversion traits and helpers.
//!
//! This module provides traits and implementations for converting between
//! Fusabi [`Value`] and Rust types, including serde support when enabled.

use std::collections::HashMap;
use thiserror::Error;

use crate::value::{Value, ValueType};

/// Error that occurs during value conversion.
#[derive(Error, Debug, Clone, PartialEq)]
pub enum ValueConversionError {
    /// Type mismatch during conversion.
    #[error("type mismatch: expected {expected}, got {actual}")]
    TypeMismatch {
        /// The expected type.
        expected: ValueType,
        /// The actual type.
        actual: ValueType,
    },

    /// Missing required field in map.
    #[error("missing field: {0}")]
    MissingField(String),

    /// Invalid value for the target type.
    #[error("invalid value: {0}")]
    InvalidValue(String),

    /// Out of range for numeric conversion.
    #[error("value out of range: {0}")]
    OutOfRange(String),

    /// Custom conversion error.
    #[error("{0}")]
    Custom(String),
}

impl ValueConversionError {
    /// Create a type mismatch error.
    pub fn type_mismatch(expected: ValueType, actual: ValueType) -> Self {
        Self::TypeMismatch { expected, actual }
    }

    /// Create a missing field error.
    pub fn missing_field(field: impl Into<String>) -> Self {
        Self::MissingField(field.into())
    }

    /// Create an invalid value error.
    pub fn invalid_value(msg: impl Into<String>) -> Self {
        Self::InvalidValue(msg.into())
    }

    /// Create an out of range error.
    pub fn out_of_range(msg: impl Into<String>) -> Self {
        Self::OutOfRange(msg.into())
    }

    /// Create a custom error.
    pub fn custom(msg: impl Into<String>) -> Self {
        Self::Custom(msg.into())
    }
}

/// Trait for types that can be created from a [`Value`].
pub trait FromValue: Sized {
    /// Convert from a Value, returning an error if conversion fails.
    fn from_value(value: Value) -> Result<Self, ValueConversionError>;

    /// Convert from a Value reference, cloning as needed.
    fn from_value_ref(value: &Value) -> Result<Self, ValueConversionError> {
        Self::from_value(value.clone())
    }
}

/// Trait for types that can be converted into a [`Value`].
pub trait IntoValue {
    /// Convert into a Value.
    fn into_value(self) -> Value;
}

// Blanket implementation for types that implement Into<Value>
impl<T: Into<Value>> IntoValue for T {
    fn into_value(self) -> Value {
        self.into()
    }
}

// FromValue implementations for primitive types

impl FromValue for Value {
    fn from_value(value: Value) -> Result<Self, ValueConversionError> {
        Ok(value)
    }
}

impl FromValue for () {
    fn from_value(value: Value) -> Result<Self, ValueConversionError> {
        match value {
            Value::Null => Ok(()),
            _ => Err(ValueConversionError::type_mismatch(
                ValueType::Null,
                value.value_type(),
            )),
        }
    }
}

impl FromValue for bool {
    fn from_value(value: Value) -> Result<Self, ValueConversionError> {
        match value {
            Value::Bool(b) => Ok(b),
            _ => Err(ValueConversionError::type_mismatch(
                ValueType::Bool,
                value.value_type(),
            )),
        }
    }
}

impl FromValue for i64 {
    fn from_value(value: Value) -> Result<Self, ValueConversionError> {
        match value {
            Value::Int(i) => Ok(i),
            _ => Err(ValueConversionError::type_mismatch(
                ValueType::Int,
                value.value_type(),
            )),
        }
    }
}

impl FromValue for i32 {
    fn from_value(value: Value) -> Result<Self, ValueConversionError> {
        match value {
            Value::Int(i) => i.try_into().map_err(|_| {
                ValueConversionError::out_of_range(format!(
                    "{} is out of range for i32",
                    i
                ))
            }),
            _ => Err(ValueConversionError::type_mismatch(
                ValueType::Int,
                value.value_type(),
            )),
        }
    }
}

impl FromValue for u64 {
    fn from_value(value: Value) -> Result<Self, ValueConversionError> {
        match value {
            Value::Int(i) => i.try_into().map_err(|_| {
                ValueConversionError::out_of_range(format!(
                    "{} is out of range for u64",
                    i
                ))
            }),
            _ => Err(ValueConversionError::type_mismatch(
                ValueType::Int,
                value.value_type(),
            )),
        }
    }
}

impl FromValue for u32 {
    fn from_value(value: Value) -> Result<Self, ValueConversionError> {
        match value {
            Value::Int(i) => i.try_into().map_err(|_| {
                ValueConversionError::out_of_range(format!(
                    "{} is out of range for u32",
                    i
                ))
            }),
            _ => Err(ValueConversionError::type_mismatch(
                ValueType::Int,
                value.value_type(),
            )),
        }
    }
}

impl FromValue for usize {
    fn from_value(value: Value) -> Result<Self, ValueConversionError> {
        match value {
            Value::Int(i) => i.try_into().map_err(|_| {
                ValueConversionError::out_of_range(format!(
                    "{} is out of range for usize",
                    i
                ))
            }),
            _ => Err(ValueConversionError::type_mismatch(
                ValueType::Int,
                value.value_type(),
            )),
        }
    }
}

impl FromValue for f64 {
    fn from_value(value: Value) -> Result<Self, ValueConversionError> {
        match value {
            Value::Float(f) => Ok(f),
            Value::Int(i) => Ok(i as f64),
            _ => Err(ValueConversionError::type_mismatch(
                ValueType::Float,
                value.value_type(),
            )),
        }
    }
}

impl FromValue for f32 {
    fn from_value(value: Value) -> Result<Self, ValueConversionError> {
        match value {
            Value::Float(f) => Ok(f as f32),
            Value::Int(i) => Ok(i as f32),
            _ => Err(ValueConversionError::type_mismatch(
                ValueType::Float,
                value.value_type(),
            )),
        }
    }
}

impl FromValue for String {
    fn from_value(value: Value) -> Result<Self, ValueConversionError> {
        match value {
            Value::String(s) => Ok(s),
            _ => Err(ValueConversionError::type_mismatch(
                ValueType::String,
                value.value_type(),
            )),
        }
    }
}

impl<T: FromValue> FromValue for Vec<T> {
    fn from_value(value: Value) -> Result<Self, ValueConversionError> {
        match value {
            Value::List(list) => list.into_iter().map(T::from_value).collect(),
            _ => Err(ValueConversionError::type_mismatch(
                ValueType::List,
                value.value_type(),
            )),
        }
    }
}

impl<T: FromValue> FromValue for HashMap<String, T> {
    fn from_value(value: Value) -> Result<Self, ValueConversionError> {
        match value {
            Value::Map(map) => map
                .into_iter()
                .map(|(k, v)| T::from_value(v).map(|v| (k, v)))
                .collect(),
            _ => Err(ValueConversionError::type_mismatch(
                ValueType::Map,
                value.value_type(),
            )),
        }
    }
}

impl<T: FromValue> FromValue for Option<T> {
    fn from_value(value: Value) -> Result<Self, ValueConversionError> {
        match value {
            Value::Null => Ok(None),
            other => T::from_value(other).map(Some),
        }
    }
}

impl FromValue for Vec<u8> {
    fn from_value(value: Value) -> Result<Self, ValueConversionError> {
        match value {
            Value::Bytes(b) => Ok(b),
            _ => Err(ValueConversionError::type_mismatch(
                ValueType::Bytes,
                value.value_type(),
            )),
        }
    }
}

// Additional Into<Value> implementations for common types

impl From<()> for Value {
    fn from(_: ()) -> Self {
        Value::Null
    }
}

impl From<usize> for Value {
    fn from(u: usize) -> Self {
        Value::Int(u as i64)
    }
}

impl From<u64> for Value {
    fn from(u: u64) -> Self {
        Value::Int(u as i64)
    }
}

impl From<u32> for Value {
    fn from(u: u32) -> Self {
        Value::Int(u as i64)
    }
}

impl<T: IntoValue> From<Vec<T>> for Value {
    fn from(v: Vec<T>) -> Self {
        Value::List(v.into_iter().map(|x| x.into_value()).collect())
    }
}

// Serde integration when feature is enabled
#[cfg(feature = "serde-support")]
mod serde_support {
    use super::*;
    use serde::{de::DeserializeOwned, Serialize};
    use serde_json;

    /// Convert a Value to a JSON value.
    pub fn value_to_json(value: &Value) -> serde_json::Value {
        match value {
            Value::Null => serde_json::Value::Null,
            Value::Bool(b) => serde_json::Value::Bool(*b),
            Value::Int(i) => serde_json::Value::Number((*i).into()),
            Value::Float(f) => {
                serde_json::Number::from_f64(*f)
                    .map(serde_json::Value::Number)
                    .unwrap_or(serde_json::Value::Null)
            }
            Value::String(s) => serde_json::Value::String(s.clone()),
            Value::List(l) => {
                serde_json::Value::Array(l.iter().map(value_to_json).collect())
            }
            Value::Map(m) => {
                let obj: serde_json::Map<String, serde_json::Value> = m
                    .iter()
                    .map(|(k, v)| (k.clone(), value_to_json(v)))
                    .collect();
                serde_json::Value::Object(obj)
            }
            Value::Function(_) => serde_json::Value::Null,
            Value::Bytes(b) => {
                use base64::Engine as _;
                let encoded = base64::engine::general_purpose::STANDARD.encode(b);
                serde_json::Value::String(encoded)
            }
            Value::Error(e) => {
                let mut obj = serde_json::Map::new();
                obj.insert("error".into(), serde_json::Value::String(e.clone()));
                serde_json::Value::Object(obj)
            }
        }
    }

    /// Convert a JSON value to a Value.
    pub fn json_to_value(json: serde_json::Value) -> Value {
        match json {
            serde_json::Value::Null => Value::Null,
            serde_json::Value::Bool(b) => Value::Bool(b),
            serde_json::Value::Number(n) => {
                if let Some(i) = n.as_i64() {
                    Value::Int(i)
                } else if let Some(f) = n.as_f64() {
                    Value::Float(f)
                } else {
                    Value::Null
                }
            }
            serde_json::Value::String(s) => Value::String(s),
            serde_json::Value::Array(arr) => {
                Value::List(arr.into_iter().map(json_to_value).collect())
            }
            serde_json::Value::Object(obj) => {
                let map: HashMap<String, Value> = obj
                    .into_iter()
                    .map(|(k, v)| (k, json_to_value(v)))
                    .collect();
                Value::Map(map)
            }
        }
    }

    /// Deserialize a Value into a type implementing DeserializeOwned.
    pub fn from_value_serde<T: DeserializeOwned>(
        value: Value,
    ) -> Result<T, ValueConversionError> {
        let json = value_to_json(&value);
        serde_json::from_value(json)
            .map_err(|e| ValueConversionError::custom(e.to_string()))
    }

    /// Serialize a type implementing Serialize into a Value.
    pub fn to_value_serde<T: Serialize>(value: &T) -> Result<Value, ValueConversionError> {
        let json = serde_json::to_value(value)
            .map_err(|e| ValueConversionError::custom(e.to_string()))?;
        Ok(json_to_value(json))
    }

    impl Value {
        /// Deserialize this Value into a serde-compatible type.
        pub fn deserialize<T: DeserializeOwned>(self) -> Result<T, ValueConversionError> {
            from_value_serde(self)
        }

        /// Convert to JSON string.
        pub fn to_json_string(&self) -> String {
            let json = value_to_json(self);
            serde_json::to_string(&json).unwrap_or_else(|_| "null".to_string())
        }

        /// Convert to pretty JSON string.
        pub fn to_json_string_pretty(&self) -> String {
            let json = value_to_json(self);
            serde_json::to_string_pretty(&json).unwrap_or_else(|_| "null".to_string())
        }

        /// Parse from JSON string.
        pub fn from_json_str(s: &str) -> Result<Self, ValueConversionError> {
            let json: serde_json::Value = serde_json::from_str(s)
                .map_err(|e| ValueConversionError::custom(e.to_string()))?;
            Ok(json_to_value(json))
        }
    }
}

#[cfg(feature = "serde-support")]
pub use serde_support::*;

/// Helper macro to extract a required field from a map Value.
#[macro_export]
macro_rules! extract_field {
    ($map:expr, $field:expr, $type:ty) => {{
        let map = match $map {
            $crate::Value::Map(m) => m,
            other => {
                return Err($crate::ValueConversionError::type_mismatch(
                    $crate::ValueType::Map,
                    other.value_type(),
                ))
            }
        };
        let value = map
            .get($field)
            .ok_or_else(|| $crate::ValueConversionError::missing_field($field))?
            .clone();
        <$type as $crate::FromValue>::from_value(value)?
    }};
}

/// Helper macro to extract an optional field from a map Value.
#[macro_export]
macro_rules! extract_field_opt {
    ($map:expr, $field:expr, $type:ty) => {{
        let map = match $map {
            $crate::Value::Map(ref m) => m,
            other => {
                return Err($crate::ValueConversionError::type_mismatch(
                    $crate::ValueType::Map,
                    other.value_type(),
                ))
            }
        };
        match map.get($field) {
            Some(v) => Some(<$type as $crate::FromValue>::from_value(v.clone())?),
            None => None,
        }
    }};
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_from_value_primitives() {
        assert_eq!(bool::from_value(Value::Bool(true)).unwrap(), true);
        assert_eq!(i64::from_value(Value::Int(42)).unwrap(), 42);
        assert_eq!(f64::from_value(Value::Float(3.14)).unwrap(), 3.14);
        assert_eq!(
            String::from_value(Value::String("hello".into())).unwrap(),
            "hello"
        );
    }

    #[test]
    fn test_from_value_type_mismatch() {
        let err = bool::from_value(Value::Int(42)).unwrap_err();
        assert!(matches!(err, ValueConversionError::TypeMismatch { .. }));
    }

    #[test]
    fn test_from_value_collections() {
        let list = Value::List(vec![Value::Int(1), Value::Int(2), Value::Int(3)]);
        let vec: Vec<i64> = Vec::from_value(list).unwrap();
        assert_eq!(vec, vec![1, 2, 3]);

        let mut map = HashMap::new();
        map.insert("a".into(), Value::Int(1));
        map.insert("b".into(), Value::Int(2));
        let value = Value::Map(map);
        let result: HashMap<String, i64> = HashMap::from_value(value).unwrap();
        assert_eq!(result.get("a"), Some(&1));
        assert_eq!(result.get("b"), Some(&2));
    }

    #[test]
    fn test_from_value_option() {
        let opt: Option<i64> = Option::from_value(Value::Null).unwrap();
        assert_eq!(opt, None);

        let opt: Option<i64> = Option::from_value(Value::Int(42)).unwrap();
        assert_eq!(opt, Some(42));
    }

    #[test]
    fn test_numeric_range() {
        let err = i32::from_value(Value::Int(i64::MAX)).unwrap_err();
        assert!(matches!(err, ValueConversionError::OutOfRange(_)));
    }

    #[cfg(feature = "serde-support")]
    mod serde_tests {
        use super::*;
        use serde::{Deserialize, Serialize};

        #[derive(Debug, PartialEq, Serialize, Deserialize)]
        struct TestStruct {
            name: String,
            value: i32,
            optional: Option<String>,
        }

        #[test]
        fn test_serde_roundtrip() {
            let original = TestStruct {
                name: "test".into(),
                value: 42,
                optional: Some("opt".into()),
            };

            let value = to_value_serde(&original).unwrap();
            let restored: TestStruct = from_value_serde(value).unwrap();
            assert_eq!(original, restored);
        }

        #[test]
        fn test_json_conversion() {
            let value = Value::Map({
                let mut m = HashMap::new();
                m.insert("key".into(), Value::String("value".into()));
                m.insert("number".into(), Value::Int(42));
                m
            });

            let json_str = value.to_json_string();
            let parsed = Value::from_json_str(&json_str).unwrap();

            // Map ordering may differ, so check individual fields
            let parsed_map = parsed.as_map().unwrap();
            assert_eq!(
                parsed_map.get("key"),
                Some(&Value::String("value".into()))
            );
            assert_eq!(parsed_map.get("number"), Some(&Value::Int(42)));
        }
    }
}