1use crate::seqstring::global_string;
37use crate::value::{MapKey as RuntimeMapKey, Value, VariantData};
38use serde::{Deserialize, Serialize};
39use std::collections::{BTreeMap, HashMap};
40use std::sync::Arc;
41
42#[derive(Debug)]
44pub enum SerializeError {
45 QuotationNotSerializable,
47 ClosureNotSerializable,
49 ChannelNotSerializable,
51 BincodeError(Box<bincode::Error>),
53 InvalidData(String),
55 NonFiniteFloat(f64),
57}
58
59impl std::fmt::Display for SerializeError {
60 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61 match self {
62 SerializeError::QuotationNotSerializable => {
63 write!(f, "Quotations cannot be serialized - code is not data")
64 }
65 SerializeError::ClosureNotSerializable => {
66 write!(f, "Closures cannot be serialized - code is not data")
67 }
68 SerializeError::ChannelNotSerializable => {
69 write!(f, "Channels cannot be serialized - runtime state")
70 }
71 SerializeError::BincodeError(e) => write!(f, "Bincode error: {}", e),
72 SerializeError::InvalidData(msg) => write!(f, "Invalid data: {}", msg),
73 SerializeError::NonFiniteFloat(v) => {
74 write!(f, "Cannot serialize non-finite float: {}", v)
75 }
76 }
77 }
78}
79
80impl std::error::Error for SerializeError {
81 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
82 match self {
83 SerializeError::BincodeError(e) => Some(e.as_ref()),
84 _ => None,
85 }
86 }
87}
88
89impl From<bincode::Error> for SerializeError {
90 fn from(e: bincode::Error) -> Self {
91 SerializeError::BincodeError(Box::new(e))
92 }
93}
94
95#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
100pub enum TypedMapKey {
101 Int(i64),
102 Bool(bool),
103 String(String),
104}
105
106impl TypedMapKey {
107 pub fn to_typed_value(&self) -> TypedValue {
109 match self {
110 TypedMapKey::Int(v) => TypedValue::Int(*v),
111 TypedMapKey::Bool(v) => TypedValue::Bool(*v),
112 TypedMapKey::String(v) => TypedValue::String(v.clone()),
113 }
114 }
115
116 pub fn from_runtime(key: &RuntimeMapKey) -> Self {
118 match key {
119 RuntimeMapKey::Int(v) => TypedMapKey::Int(*v),
120 RuntimeMapKey::Bool(v) => TypedMapKey::Bool(*v),
121 RuntimeMapKey::String(s) => TypedMapKey::String(s.as_str().to_string()),
122 }
123 }
124
125 pub fn to_runtime(&self) -> RuntimeMapKey {
127 match self {
128 TypedMapKey::Int(v) => RuntimeMapKey::Int(*v),
129 TypedMapKey::Bool(v) => RuntimeMapKey::Bool(*v),
130 TypedMapKey::String(s) => RuntimeMapKey::String(global_string(s.clone())),
131 }
132 }
133}
134
135#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
140pub enum TypedValue {
141 Int(i64),
142 Float(f64),
143 Bool(bool),
144 String(String),
145 Map(BTreeMap<TypedMapKey, TypedValue>),
147 Variant {
149 tag: u32,
150 fields: Vec<TypedValue>,
151 },
152}
153
154impl TypedValue {
155 pub fn from_value(value: &Value) -> Result<Self, SerializeError> {
161 match value {
162 Value::Int(v) => Ok(TypedValue::Int(*v)),
163 Value::Float(v) => {
164 if !v.is_finite() {
165 return Err(SerializeError::NonFiniteFloat(*v));
166 }
167 Ok(TypedValue::Float(*v))
168 }
169 Value::Bool(v) => Ok(TypedValue::Bool(*v)),
170 Value::String(s) => Ok(TypedValue::String(s.as_str().to_string())),
171 Value::Map(map) => {
172 let mut typed_map = BTreeMap::new();
173 for (k, v) in map.iter() {
174 let typed_key = TypedMapKey::from_runtime(k);
175 let typed_value = TypedValue::from_value(v)?;
176 typed_map.insert(typed_key, typed_value);
177 }
178 Ok(TypedValue::Map(typed_map))
179 }
180 Value::Variant(data) => {
181 let mut typed_fields = Vec::with_capacity(data.fields.len());
182 for field in data.fields.iter() {
183 typed_fields.push(TypedValue::from_value(field)?);
184 }
185 Ok(TypedValue::Variant {
186 tag: data.tag,
187 fields: typed_fields,
188 })
189 }
190 Value::Quotation { .. } => Err(SerializeError::QuotationNotSerializable),
191 Value::Closure { .. } => Err(SerializeError::ClosureNotSerializable),
192 Value::Channel(_) => Err(SerializeError::ChannelNotSerializable),
193 }
194 }
195
196 pub fn to_value(&self) -> Value {
201 match self {
202 TypedValue::Int(v) => Value::Int(*v),
203 TypedValue::Float(v) => Value::Float(*v),
204 TypedValue::Bool(v) => Value::Bool(*v),
205 TypedValue::String(s) => Value::String(global_string(s.clone())),
206 TypedValue::Map(map) => {
207 let mut runtime_map = HashMap::new();
208 for (k, v) in map.iter() {
209 runtime_map.insert(k.to_runtime(), v.to_value());
210 }
211 Value::Map(Box::new(runtime_map))
212 }
213 TypedValue::Variant { tag, fields } => {
214 let runtime_fields: Vec<Value> = fields.iter().map(|f| f.to_value()).collect();
215 Value::Variant(Arc::new(VariantData::new(*tag, runtime_fields)))
216 }
217 }
218 }
219
220 pub fn to_map_key(&self) -> Result<TypedMapKey, SerializeError> {
222 match self {
223 TypedValue::Int(v) => Ok(TypedMapKey::Int(*v)),
224 TypedValue::Bool(v) => Ok(TypedMapKey::Bool(*v)),
225 TypedValue::String(v) => Ok(TypedMapKey::String(v.clone())),
226 TypedValue::Float(_) => Err(SerializeError::InvalidData(
227 "Float cannot be a map key".to_string(),
228 )),
229 TypedValue::Map(_) => Err(SerializeError::InvalidData(
230 "Map cannot be a map key".to_string(),
231 )),
232 TypedValue::Variant { .. } => Err(SerializeError::InvalidData(
233 "Variant cannot be a map key".to_string(),
234 )),
235 }
236 }
237
238 pub fn to_bytes(&self) -> Result<Vec<u8>, SerializeError> {
240 bincode::serialize(self).map_err(SerializeError::from)
241 }
242
243 pub fn from_bytes(bytes: &[u8]) -> Result<Self, SerializeError> {
245 bincode::deserialize(bytes).map_err(SerializeError::from)
246 }
247
248 pub fn to_debug_string(&self) -> String {
250 match self {
251 TypedValue::Int(v) => format!("{}", v),
252 TypedValue::Float(v) => format!("{}", v),
253 TypedValue::Bool(v) => format!("{}", v),
254 TypedValue::String(v) => format!("{:?}", v),
255 TypedValue::Map(m) => {
256 let entries: Vec<String> = m
257 .iter()
258 .map(|(k, v)| format!("{}: {}", key_to_debug_string(k), v.to_debug_string()))
259 .collect();
260 format!("{{ {} }}", entries.join(", "))
261 }
262 TypedValue::Variant { tag, fields } => {
263 if fields.is_empty() {
264 format!("(Variant#{})", tag)
265 } else {
266 let field_strs: Vec<String> =
267 fields.iter().map(|f| f.to_debug_string()).collect();
268 format!("(Variant#{} {})", tag, field_strs.join(" "))
269 }
270 }
271 }
272 }
273}
274
275fn key_to_debug_string(key: &TypedMapKey) -> String {
276 match key {
277 TypedMapKey::Int(v) => format!("{}", v),
278 TypedMapKey::Bool(v) => format!("{}", v),
279 TypedMapKey::String(v) => format!("{:?}", v),
280 }
281}
282
283pub trait ValueSerialize {
285 fn to_typed(&self) -> Result<TypedValue, SerializeError>;
287
288 fn to_bytes(&self) -> Result<Vec<u8>, SerializeError>;
290}
291
292impl ValueSerialize for Value {
293 fn to_typed(&self) -> Result<TypedValue, SerializeError> {
294 TypedValue::from_value(self)
295 }
296
297 fn to_bytes(&self) -> Result<Vec<u8>, SerializeError> {
298 TypedValue::from_value(self)?.to_bytes()
299 }
300}
301
302#[cfg(test)]
303mod tests {
304 use super::*;
305 use crate::seqstring::global_string;
306
307 #[test]
308 fn test_int_roundtrip() {
309 let value = Value::Int(42);
310 let typed = TypedValue::from_value(&value).unwrap();
311 let back = typed.to_value();
312 assert_eq!(value, back);
313 }
314
315 #[test]
316 fn test_float_roundtrip() {
317 let value = Value::Float(1.23456);
318 let typed = TypedValue::from_value(&value).unwrap();
319 let back = typed.to_value();
320 assert_eq!(value, back);
321 }
322
323 #[test]
324 fn test_bool_roundtrip() {
325 let value = Value::Bool(true);
326 let typed = TypedValue::from_value(&value).unwrap();
327 let back = typed.to_value();
328 assert_eq!(value, back);
329 }
330
331 #[test]
332 fn test_string_roundtrip() {
333 let value = Value::String(global_string("hello".to_string()));
334 let typed = TypedValue::from_value(&value).unwrap();
335 let back = typed.to_value();
336 match (&value, &back) {
338 (Value::String(a), Value::String(b)) => assert_eq!(a.as_str(), b.as_str()),
339 _ => panic!("Expected strings"),
340 }
341 }
342
343 #[test]
344 fn test_map_roundtrip() {
345 let mut map = HashMap::new();
346 map.insert(
347 RuntimeMapKey::String(global_string("key".to_string())),
348 Value::Int(42),
349 );
350 map.insert(RuntimeMapKey::Int(1), Value::Bool(true));
351
352 let value = Value::Map(Box::new(map));
353 let typed = TypedValue::from_value(&value).unwrap();
354 let back = typed.to_value();
355
356 if let Value::Map(m) = back {
358 assert_eq!(m.len(), 2);
359 } else {
360 panic!("Expected map");
361 }
362 }
363
364 #[test]
365 fn test_variant_roundtrip() {
366 let data = VariantData::new(1, vec![Value::Int(100), Value::Bool(false)]);
367 let value = Value::Variant(Arc::new(data));
368
369 let typed = TypedValue::from_value(&value).unwrap();
370 let back = typed.to_value();
371
372 if let Value::Variant(v) = back {
373 assert_eq!(v.tag, 1);
374 assert_eq!(v.fields.len(), 2);
375 } else {
376 panic!("Expected variant");
377 }
378 }
379
380 #[test]
381 fn test_quotation_not_serializable() {
382 let value = Value::Quotation {
383 wrapper: 12345,
384 impl_: 12345,
385 };
386 let result = TypedValue::from_value(&value);
387 assert!(matches!(
388 result,
389 Err(SerializeError::QuotationNotSerializable)
390 ));
391 }
392
393 #[test]
394 fn test_closure_not_serializable() {
395 use std::sync::Arc;
396 let value = Value::Closure {
397 fn_ptr: 12345,
398 env: Arc::from(vec![Value::Int(1)].into_boxed_slice()),
399 };
400 let result = TypedValue::from_value(&value);
401 assert!(matches!(
402 result,
403 Err(SerializeError::ClosureNotSerializable)
404 ));
405 }
406
407 #[test]
408 fn test_bytes_roundtrip() {
409 let typed = TypedValue::Map(BTreeMap::from([
410 (TypedMapKey::String("x".to_string()), TypedValue::Int(10)),
411 (TypedMapKey::Int(42), TypedValue::Bool(true)),
412 ]));
413
414 let bytes = typed.to_bytes().unwrap();
415 let parsed = TypedValue::from_bytes(&bytes).unwrap();
416 assert_eq!(typed, parsed);
417 }
418
419 #[test]
420 fn test_bincode_is_compact() {
421 let typed = TypedValue::Int(42);
422 let bytes = typed.to_bytes().unwrap();
423 assert!(
424 bytes.len() < 20,
425 "Expected compact encoding, got {} bytes",
426 bytes.len()
427 );
428 }
429
430 #[test]
431 fn test_debug_string() {
432 let typed = TypedValue::String("hello".to_string());
433 assert_eq!(typed.to_debug_string(), "\"hello\"");
434
435 let typed = TypedValue::Int(42);
436 assert_eq!(typed.to_debug_string(), "42");
437 }
438
439 #[test]
440 fn test_nested_structure() {
441 let inner_variant = TypedValue::Variant {
443 tag: 2,
444 fields: vec![TypedValue::String("inner".to_string())],
445 };
446
447 let mut inner_map = BTreeMap::new();
448 inner_map.insert(TypedMapKey::String("nested".to_string()), inner_variant);
449
450 let outer = TypedValue::Map(inner_map);
451
452 let bytes = outer.to_bytes().unwrap();
453 let parsed = TypedValue::from_bytes(&bytes).unwrap();
454 assert_eq!(outer, parsed);
455 }
456
457 #[test]
458 fn test_nan_not_serializable() {
459 let value = Value::Float(f64::NAN);
460 let result = TypedValue::from_value(&value);
461 assert!(matches!(result, Err(SerializeError::NonFiniteFloat(_))));
462 }
463
464 #[test]
465 fn test_infinity_not_serializable() {
466 let value = Value::Float(f64::INFINITY);
467 let result = TypedValue::from_value(&value);
468 assert!(matches!(result, Err(SerializeError::NonFiniteFloat(_))));
469
470 let value = Value::Float(f64::NEG_INFINITY);
471 let result = TypedValue::from_value(&value);
472 assert!(matches!(result, Err(SerializeError::NonFiniteFloat(_))));
473 }
474
475 #[test]
476 fn test_corrupted_data_returns_error() {
477 let corrupted = vec![0xFF, 0xFF, 0xFF, 0xFF, 0xFF];
479 let result = TypedValue::from_bytes(&corrupted);
480 assert!(result.is_err());
481 }
482
483 #[test]
484 fn test_empty_data_returns_error() {
485 let result = TypedValue::from_bytes(&[]);
486 assert!(result.is_err());
487 }
488
489 #[test]
490 fn test_truncated_data_returns_error() {
491 let typed = TypedValue::String("hello world".to_string());
493 let bytes = typed.to_bytes().unwrap();
494 let truncated = &bytes[..bytes.len() / 2];
495 let result = TypedValue::from_bytes(truncated);
496 assert!(result.is_err());
497 }
498}