1use std::collections::BTreeMap;
2use std::sync::Arc;
3
4#[cfg(feature = "image")]
5use photon_rs::PhotonImage;
6
7use serde::{
8 Deserialize, Deserializer, Serialize, Serializer,
9 ser::{SerializeMap, SerializeSeq},
10};
11
12use super::error::AgentError;
13
14#[cfg(feature = "image")]
15const IMAGE_BASE64_PREFIX: &str = "data:image/png;base64,";
16
17#[derive(Debug, Clone)]
18pub enum AgentValue {
19 Unit,
21 Boolean(bool),
22 Integer(i64),
23 Number(f64),
24
25 String(Arc<String>),
27
28 #[cfg(feature = "image")]
29 Image(Arc<PhotonImage>),
30
31 Array(Arc<Vec<AgentValue>>),
33 Object(Arc<AgentValueMap<String, AgentValue>>),
34}
35
36pub type AgentValueMap<S, T> = BTreeMap<S, T>;
37
38impl AgentValue {
39 pub fn unit() -> Self {
40 AgentValue::Unit
41 }
42
43 pub fn boolean(value: bool) -> Self {
44 AgentValue::Boolean(value)
45 }
46
47 pub fn integer(value: i64) -> Self {
48 AgentValue::Integer(value)
49 }
50
51 pub fn number(value: f64) -> Self {
52 AgentValue::Number(value)
53 }
54
55 pub fn string(value: impl Into<String>) -> Self {
56 AgentValue::String(Arc::new(value.into()))
57 }
58
59 #[cfg(feature = "image")]
60 pub fn image(value: PhotonImage) -> Self {
61 AgentValue::Image(Arc::new(value))
62 }
63
64 #[cfg(feature = "image")]
65 pub fn image_arc(value: Arc<PhotonImage>) -> Self {
66 AgentValue::Image(value)
67 }
68
69 pub fn object(value: AgentValueMap<String, AgentValue>) -> Self {
70 AgentValue::Object(Arc::new(value))
71 }
72
73 pub fn array(value: Vec<AgentValue>) -> Self {
74 AgentValue::Array(Arc::new(value))
75 }
76
77 pub fn boolean_default() -> Self {
78 AgentValue::Boolean(false)
79 }
80
81 pub fn integer_default() -> Self {
82 AgentValue::Integer(0)
83 }
84
85 pub fn number_default() -> Self {
86 AgentValue::Number(0.0)
87 }
88
89 pub fn string_default() -> Self {
90 AgentValue::String(Arc::new(String::new()))
91 }
92
93 #[cfg(feature = "image")]
94 pub fn image_default() -> Self {
95 AgentValue::Image(Arc::new(PhotonImage::new(vec![0u8, 0u8, 0u8, 0u8], 1, 1)))
96 }
97
98 pub fn array_default() -> Self {
99 AgentValue::Array(Arc::new(Vec::new()))
100 }
101
102 pub fn object_default() -> Self {
103 AgentValue::Object(Arc::new(AgentValueMap::new()))
104 }
105
106 pub fn from_json(value: serde_json::Value) -> Result<Self, AgentError> {
107 match value {
108 serde_json::Value::Null => Ok(AgentValue::Unit),
109 serde_json::Value::Bool(b) => Ok(AgentValue::Boolean(b)),
110 serde_json::Value::Number(n) => {
111 if let Some(i) = n.as_i64() {
112 Ok(AgentValue::Integer(i))
113 } else if let Some(f) = n.as_f64() {
114 Ok(AgentValue::Number(f))
115 } else {
116 Ok(AgentValue::Integer(0))
118 }
119 }
120 serde_json::Value::String(s) => {
121 #[cfg(feature = "image")]
122 if s.starts_with(IMAGE_BASE64_PREFIX) {
123 let img =
124 PhotonImage::new_from_base64(&s.trim_start_matches(IMAGE_BASE64_PREFIX));
125 Ok(AgentValue::Image(Arc::new(img)))
126 } else {
127 Ok(AgentValue::String(Arc::new(s)))
128 }
129 #[cfg(not(feature = "image"))]
130 Ok(AgentValue::String(Arc::new(s)))
131 }
132 serde_json::Value::Array(arr) => {
133 let mut agent_arr = Vec::new();
134 for v in arr {
135 agent_arr.push(AgentValue::from_json(v)?);
136 }
137 Ok(AgentValue::array(agent_arr))
138 }
139 serde_json::Value::Object(obj) => {
140 let mut map = AgentValueMap::new();
141 for (k, v) in obj {
142 map.insert(k, AgentValue::from_json(v)?);
143 }
144 Ok(AgentValue::object(map))
145 }
146 }
147 }
148
149 pub fn from_kind_json(kind: &str, value: serde_json::Value) -> Result<Self, AgentError> {
150 match kind {
151 "unit" => {
152 if let serde_json::Value::Array(a) = value {
153 Ok(AgentValue::Array(Arc::new(
154 a.into_iter().map(|_| AgentValue::Unit).collect(),
155 )))
156 } else {
157 Ok(AgentValue::Unit)
158 }
159 }
160 "boolean" => match value {
161 serde_json::Value::Bool(b) => Ok(AgentValue::Boolean(b)),
162 serde_json::Value::Array(a) => {
163 let mut agent_arr = Vec::new();
164 for v in a {
165 if let serde_json::Value::Bool(b) = v {
166 agent_arr.push(AgentValue::Boolean(b));
167 } else {
168 return Err(AgentError::InvalidArrayValue("boolean".into()));
169 }
170 }
171 Ok(AgentValue::Array(Arc::new(agent_arr)))
172 }
173 _ => Err(AgentError::InvalidValue("boolean".into())),
174 },
175 "integer" => match value {
176 serde_json::Value::Number(n) => {
177 if let Some(i) = n.as_i64() {
178 Ok(AgentValue::Integer(i))
179 } else if let Some(f) = n.as_f64() {
180 Ok(AgentValue::Integer(f as i64))
181 } else {
182 Err(AgentError::InvalidValue("integer".into()))
183 }
184 }
185 serde_json::Value::Array(a) => {
186 let mut agent_arr = Vec::new();
187 for n in a {
188 if let Some(i) = n.as_i64() {
189 agent_arr.push(AgentValue::Integer(i));
190 } else if let Some(f) = n.as_f64() {
191 agent_arr.push(AgentValue::Integer(f as i64));
192 } else {
193 return Err(AgentError::InvalidArrayValue("integer".into()));
194 }
195 }
196 Ok(AgentValue::Array(Arc::new(agent_arr)))
197 }
198 _ => Err(AgentError::InvalidValue("integer".into())),
199 },
200 "number" => match value {
201 serde_json::Value::Number(n) => {
202 if let Some(f) = n.as_f64() {
203 Ok(AgentValue::Number(f))
204 } else if let Some(i) = n.as_i64() {
205 Ok(AgentValue::Number(i as f64))
206 } else {
207 Err(AgentError::InvalidValue("number".into()))
208 }
209 }
210 serde_json::Value::Array(a) => {
211 let mut agent_arr = Vec::new();
212 for n in a {
213 if let Some(f) = n.as_f64() {
214 agent_arr.push(AgentValue::Number(f));
215 } else if let Some(i) = n.as_i64() {
216 agent_arr.push(AgentValue::Number(i as f64));
217 } else {
218 return Err(AgentError::InvalidArrayValue("number".into()));
219 }
220 }
221 Ok(AgentValue::Array(Arc::new(agent_arr)))
222 }
223 _ => Err(AgentError::InvalidValue("number".into())),
224 },
225 "string" => match value {
226 serde_json::Value::String(s) => Ok(AgentValue::string(s)),
227 serde_json::Value::Array(a) => {
228 let mut agent_arr = Vec::new();
229 for v in a {
230 if let serde_json::Value::String(s) = v {
231 agent_arr.push(AgentValue::string(s));
232 } else {
233 return Err(AgentError::InvalidArrayValue("string".into()));
234 }
235 }
236 Ok(AgentValue::Array(Arc::new(agent_arr)))
237 }
238 _ => Err(AgentError::InvalidValue("string".into())),
239 },
240 #[cfg(feature = "image")]
241 "image" => match value {
242 serde_json::Value::String(s) => Ok(AgentValue::Image(Arc::new(
243 PhotonImage::new_from_base64(&s.trim_start_matches(IMAGE_BASE64_PREFIX)),
244 ))),
245 serde_json::Value::Array(a) => {
246 let mut agent_arr = Vec::new();
247 for v in a {
248 if let serde_json::Value::String(s) = v {
249 agent_arr.push(AgentValue::image(PhotonImage::new_from_base64(
250 &s.trim_start_matches(IMAGE_BASE64_PREFIX),
251 )));
252 } else {
253 return Err(AgentError::InvalidArrayValue("image".into()));
254 }
255 }
256 Ok(AgentValue::Array(Arc::new(agent_arr)))
257 }
258 _ => Err(AgentError::InvalidValue("image".into())),
259 },
260 _ => match value {
261 serde_json::Value::Null => Ok(AgentValue::Unit),
262 serde_json::Value::Bool(b) => Ok(AgentValue::Boolean(b)),
263 serde_json::Value::Number(n) => {
264 if let Some(i) = n.as_i64() {
265 Ok(AgentValue::Integer(i))
266 } else if let Some(f) = n.as_f64() {
267 Ok(AgentValue::Number(f))
268 } else {
269 Err(AgentError::InvalidValue("number".into()))
270 }
271 }
272 serde_json::Value::String(s) => Ok(AgentValue::string(s)),
273 serde_json::Value::Array(a) => {
274 let mut agent_arr = Vec::new();
275 for v in a {
276 let agent_v = AgentValue::from_kind_json(kind, v)?;
277 agent_arr.push(agent_v);
278 }
279 Ok(AgentValue::Array(Arc::new(agent_arr)))
280 }
281 serde_json::Value::Object(obj) => {
282 let mut map = AgentValueMap::new();
283 for (k, v) in obj {
284 map.insert(k.clone(), AgentValue::from_json(v)?);
285 }
286 Ok(AgentValue::object(map))
287 }
288 },
289 }
290 }
291
292 pub fn to_json(&self) -> serde_json::Value {
293 match self {
294 AgentValue::Unit => serde_json::Value::Null,
295 AgentValue::Boolean(b) => (*b).into(),
296 AgentValue::Integer(i) => (*i).into(),
297 AgentValue::Number(n) => (*n).into(),
298 AgentValue::String(s) => s.as_str().into(),
299 #[cfg(feature = "image")]
300 AgentValue::Image(img) => img.get_base64().into(),
301 AgentValue::Object(o) => {
302 let mut map = serde_json::Map::new();
303 for (k, v) in o.iter() {
304 map.insert(k.clone(), v.to_json());
305 }
306 serde_json::Value::Object(map)
307 }
308 AgentValue::Array(a) => {
309 let arr: Vec<serde_json::Value> = a.iter().map(|v| v.to_json()).collect();
310 serde_json::Value::Array(arr)
311 }
312 }
313 }
314
315 pub fn from_serialize<T: Serialize>(value: &T) -> Result<Self, AgentError> {
317 let json_value = serde_json::to_value(value)
318 .map_err(|e| AgentError::InvalidValue(format!("Failed to serialize: {}", e)))?;
319 Self::from_json(json_value)
320 }
321
322 pub fn to_deserialize<T: for<'de> Deserialize<'de>>(&self) -> Result<T, AgentError> {
324 let json_value = self.to_json();
325 serde_json::from_value(json_value)
326 .map_err(|e| AgentError::InvalidValue(format!("Failed to deserialize: {}", e)))
327 }
328
329 #[allow(unused)]
330 pub fn is_unit(&self) -> bool {
331 matches!(self, AgentValue::Unit)
332 }
333
334 #[allow(unused)]
335 pub fn is_boolean(&self) -> bool {
336 matches!(self, AgentValue::Boolean(_))
337 }
338
339 #[allow(unused)]
340 pub fn is_integer(&self) -> bool {
341 matches!(self, AgentValue::Integer(_))
342 }
343
344 #[allow(unused)]
345 pub fn is_number(&self) -> bool {
346 matches!(self, AgentValue::Number(_))
347 }
348
349 #[allow(unused)]
350 pub fn is_string(&self) -> bool {
351 matches!(self, AgentValue::String(_))
352 }
353
354 #[cfg(feature = "image")]
355 #[allow(unused)]
356 pub fn is_image(&self) -> bool {
357 matches!(self, AgentValue::Image(_))
358 }
359
360 #[allow(unused)]
361 pub fn is_array(&self) -> bool {
362 matches!(self, AgentValue::Array(_))
363 }
364
365 #[allow(unused)]
366 pub fn is_object(&self) -> bool {
367 matches!(self, AgentValue::Object(_))
368 }
369
370 pub fn as_bool(&self) -> Option<bool> {
371 match self {
372 AgentValue::Boolean(b) => Some(*b),
373 _ => None,
374 }
375 }
376
377 pub fn as_i64(&self) -> Option<i64> {
378 match self {
379 AgentValue::Integer(i) => Some(*i),
380 AgentValue::Number(n) => Some(*n as i64),
381 _ => None,
382 }
383 }
384
385 pub fn as_f64(&self) -> Option<f64> {
386 match self {
387 AgentValue::Integer(i) => Some(*i as f64),
388 AgentValue::Number(n) => Some(*n),
389 _ => None,
390 }
391 }
392
393 pub fn as_str(&self) -> Option<&str> {
394 match self {
395 AgentValue::String(s) => Some(s),
396 _ => None,
397 }
398 }
399
400 #[cfg(feature = "image")]
401 pub fn as_image(&self) -> Option<Arc<PhotonImage>> {
402 match self {
403 AgentValue::Image(img) => Some(img.clone()),
404 _ => None,
405 }
406 }
407
408 pub fn as_object(&self) -> Option<&AgentValueMap<String, AgentValue>> {
409 match self {
410 AgentValue::Object(o) => Some(o),
411 _ => None,
412 }
413 }
414
415 pub fn as_object_mut(&mut self) -> Option<&mut AgentValueMap<String, AgentValue>> {
416 match self {
417 AgentValue::Object(o) => Some(Arc::make_mut(o)),
418 _ => None,
419 }
420 }
421
422 pub fn as_array(&self) -> Option<&Vec<AgentValue>> {
423 match self {
424 AgentValue::Array(a) => Some(a),
425 _ => None,
426 }
427 }
428
429 pub fn as_array_mut(&mut self) -> Option<&mut Vec<AgentValue>> {
430 match self {
431 AgentValue::Array(a) => Some(Arc::make_mut(a)),
432 _ => None,
433 }
434 }
435
436 #[allow(unused)]
437 pub fn get(&self, key: &str) -> Option<&AgentValue> {
438 self.as_object().and_then(|o| o.get(key))
439 }
440
441 #[allow(unused)]
442 pub fn get_mut(&mut self, key: &str) -> Option<&mut AgentValue> {
443 self.as_object_mut().and_then(|o| o.get_mut(key))
444 }
445
446 #[allow(unused)]
447 pub fn get_bool(&self, key: &str) -> Option<bool> {
448 self.get(key).and_then(|v| v.as_bool())
449 }
450
451 #[allow(unused)]
452 pub fn get_i64(&self, key: &str) -> Option<i64> {
453 self.get(key).and_then(|v| v.as_i64())
454 }
455
456 #[allow(unused)]
457 pub fn get_f64(&self, key: &str) -> Option<f64> {
458 self.get(key).and_then(|v| v.as_f64())
459 }
460
461 #[allow(unused)]
462 pub fn get_str(&self, key: &str) -> Option<&str> {
463 self.get(key).and_then(|v| v.as_str())
464 }
465
466 #[cfg(feature = "image")]
467 #[allow(unused)]
468 pub fn get_image(&self, key: &str) -> Option<Arc<PhotonImage>> {
469 self.get(key).and_then(|v| v.as_image())
470 }
471
472 #[allow(unused)]
473 pub fn get_object(&self, key: &str) -> Option<&AgentValueMap<String, AgentValue>> {
474 self.get(key).and_then(|v| v.as_object())
475 }
476
477 #[allow(unused)]
478 pub fn get_object_mut(&mut self, key: &str) -> Option<&mut AgentValueMap<String, AgentValue>> {
479 self.get_mut(key).and_then(|v| v.as_object_mut())
480 }
481
482 #[allow(unused)]
483 pub fn get_array(&self, key: &str) -> Option<&Vec<AgentValue>> {
484 self.get(key).and_then(|v| v.as_array())
485 }
486
487 #[allow(unused)]
488 pub fn get_array_mut(&mut self, key: &str) -> Option<&mut Vec<AgentValue>> {
489 self.get_mut(key).and_then(|v| v.as_array_mut())
490 }
491
492 pub fn set(&mut self, key: String, value: AgentValue) -> Result<(), AgentError> {
493 if let Some(obj) = self.as_object_mut() {
494 obj.insert(key, value);
495 Ok(())
496 } else {
497 Err(AgentError::InvalidValue(
498 "set can only be called on Object AgentValue".into(),
499 ))
500 }
501 }
502}
503
504impl Default for AgentValue {
505 fn default() -> Self {
506 AgentValue::Unit
507 }
508}
509
510impl PartialEq for AgentValue {
511 fn eq(&self, other: &Self) -> bool {
512 match (self, other) {
513 (AgentValue::Unit, AgentValue::Unit) => true,
514 (AgentValue::Boolean(b1), AgentValue::Boolean(b2)) => b1 == b2,
515 (AgentValue::Integer(i1), AgentValue::Integer(i2)) => i1 == i2,
516 (AgentValue::Number(n1), AgentValue::Number(n2)) => n1 == n2,
517 (AgentValue::String(s1), AgentValue::String(s2)) => s1 == s2,
518 #[cfg(feature = "image")]
519 (AgentValue::Image(i1), AgentValue::Image(i2)) => {
520 i1.get_width() == i2.get_width()
521 && i1.get_height() == i2.get_height()
522 && i1.get_raw_pixels() == i2.get_raw_pixels()
523 }
524 (AgentValue::Object(o1), AgentValue::Object(o2)) => o1 == o2,
525 (AgentValue::Array(a1), AgentValue::Array(a2)) => a1 == a2,
526 _ => false,
527 }
528 }
529}
530
531impl Serialize for AgentValue {
532 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
533 where
534 S: Serializer,
535 {
536 match self {
537 AgentValue::Unit => serializer.serialize_none(),
538 AgentValue::Boolean(b) => serializer.serialize_bool(*b),
539 AgentValue::Integer(i) => serializer.serialize_i64(*i),
540 AgentValue::Number(n) => serializer.serialize_f64(*n),
541 AgentValue::String(s) => serializer.serialize_str(s),
542 #[cfg(feature = "image")]
543 AgentValue::Image(img) => serializer.serialize_str(&img.get_base64()),
544 AgentValue::Object(o) => {
545 let mut map = serializer.serialize_map(Some(o.len()))?;
546 for (k, v) in o.iter() {
547 map.serialize_entry(k, v)?;
548 }
549 map.end()
550 }
551 AgentValue::Array(a) => {
552 let mut seq = serializer.serialize_seq(Some(a.len()))?;
553 for e in a.iter() {
554 seq.serialize_element(e)?;
555 }
556 seq.end()
557 }
558 }
559 }
560}
561
562impl<'de> Deserialize<'de> for AgentValue {
563 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
564 where
565 D: Deserializer<'de>,
566 {
567 let value = serde_json::Value::deserialize(deserializer)?;
568 AgentValue::from_json(value).map_err(|e| {
569 serde::de::Error::custom(format!("Failed to deserialize AgentValue: {}", e))
570 })
571 }
572}
573
574impl From<()> for AgentValue {
575 fn from(_: ()) -> Self {
576 AgentValue::unit()
577 }
578}
579
580impl From<bool> for AgentValue {
581 fn from(value: bool) -> Self {
582 AgentValue::boolean(value)
583 }
584}
585
586impl From<i32> for AgentValue {
587 fn from(value: i32) -> Self {
588 AgentValue::integer(value as i64)
589 }
590}
591
592impl From<i64> for AgentValue {
593 fn from(value: i64) -> Self {
594 AgentValue::integer(value)
595 }
596}
597
598impl From<f64> for AgentValue {
599 fn from(value: f64) -> Self {
600 AgentValue::number(value)
601 }
602}
603
604impl From<String> for AgentValue {
605 fn from(value: String) -> Self {
606 AgentValue::string(value)
607 }
608}
609
610impl From<&str> for AgentValue {
611 fn from(value: &str) -> Self {
612 AgentValue::string(value)
613 }
614}
615
616#[cfg(test)]
617mod tests {
618 use super::*;
619 use serde_json::json;
620
621 #[test]
622 fn test_agent_value_constructors() {
623 let unit = AgentValue::unit();
625 assert_eq!(unit, AgentValue::Unit);
626
627 let boolean = AgentValue::boolean(true);
628 assert_eq!(boolean, AgentValue::Boolean(true));
629
630 let integer = AgentValue::integer(42);
631 assert_eq!(integer, AgentValue::Integer(42));
632
633 let number = AgentValue::number(3.14);
634 assert!(matches!(number, AgentValue::Number(_)));
635 if let AgentValue::Number(num) = number {
636 assert!((num - 3.14).abs() < f64::EPSILON);
637 }
638
639 let string = AgentValue::string("hello");
640 assert!(matches!(string, AgentValue::String(_)));
641 assert_eq!(string.as_str().unwrap(), "hello");
642
643 let text = AgentValue::string("multiline\ntext");
644 assert!(matches!(text, AgentValue::String(_)));
645 assert_eq!(text.as_str().unwrap(), "multiline\ntext");
646
647 let array = AgentValue::array(vec![AgentValue::integer(1), AgentValue::integer(2)]);
648 assert!(matches!(array, AgentValue::Array(_)));
649 if let AgentValue::Array(arr) = array {
650 assert_eq!(arr.len(), 2);
651 assert_eq!(arr[0].as_i64().unwrap(), 1);
652 assert_eq!(arr[1].as_i64().unwrap(), 2);
653 }
654
655 let obj = AgentValue::object(
656 [
657 ("key1".to_string(), AgentValue::string("string1")),
658 ("key2".to_string(), AgentValue::integer(2)),
659 ]
660 .into(),
661 );
662 assert!(matches!(obj, AgentValue::Object(_)));
663 if let AgentValue::Object(obj) = obj {
664 assert_eq!(obj.get("key1").and_then(|v| v.as_str()), Some("string1"));
665 assert_eq!(obj.get("key2").and_then(|v| v.as_i64()), Some(2));
666 } else {
667 panic!("Object was not deserialized correctly");
668 }
669 }
670
671 #[test]
672 fn test_agent_value_from_json_value() {
673 let null = AgentValue::from_json(json!(null)).unwrap();
675 assert_eq!(null, AgentValue::Unit);
676
677 let boolean = AgentValue::from_json(json!(true)).unwrap();
678 assert_eq!(boolean, AgentValue::Boolean(true));
679
680 let integer = AgentValue::from_json(json!(42)).unwrap();
681 assert_eq!(integer, AgentValue::Integer(42));
682
683 let number = AgentValue::from_json(json!(3.14)).unwrap();
684 assert!(matches!(number, AgentValue::Number(_)));
685 if let AgentValue::Number(num) = number {
686 assert!((num - 3.14).abs() < f64::EPSILON);
687 }
688
689 let string = AgentValue::from_json(json!("hello")).unwrap();
690 assert!(matches!(string, AgentValue::String(_)));
691 if let AgentValue::String(s) = string {
692 assert_eq!(*s, "hello");
693 } else {
694 panic!("Expected string value");
695 }
696
697 let array = AgentValue::from_json(json!([1, "test", true])).unwrap();
698 assert!(matches!(array, AgentValue::Array(_)));
699 if let AgentValue::Array(arr) = array {
700 assert_eq!(arr.len(), 3);
701 assert_eq!(arr[0], AgentValue::Integer(1));
702 assert!(matches!(&arr[1], AgentValue::String(_)));
703 if let AgentValue::String(s) = &arr[1] {
704 assert_eq!(**s, "test");
705 } else {
706 panic!("Expected string value");
707 }
708 assert_eq!(arr[2], AgentValue::Boolean(true));
709 }
710
711 let object = AgentValue::from_json(json!({"key1": "string1", "key2": 2})).unwrap();
712 assert!(matches!(object, AgentValue::Object(_)));
713 if let AgentValue::Object(obj) = object {
714 assert_eq!(obj.get("key1").and_then(|v| v.as_str()), Some("string1"));
715 assert_eq!(obj.get("key2").and_then(|v| v.as_i64()), Some(2));
716 } else {
717 panic!("Object was not deserialized correctly");
718 }
719 }
720
721 #[test]
722 fn test_agent_value_from_kind_value() {
723 let unit = AgentValue::from_kind_json("unit", json!(null)).unwrap();
725 assert_eq!(unit, AgentValue::Unit);
726
727 let boolean = AgentValue::from_kind_json("boolean", json!(true)).unwrap();
728 assert_eq!(boolean, AgentValue::Boolean(true));
729
730 let integer = AgentValue::from_kind_json("integer", json!(42)).unwrap();
731 assert_eq!(integer, AgentValue::Integer(42));
732
733 let integer = AgentValue::from_kind_json("integer", json!(42.0)).unwrap();
734 assert_eq!(integer, AgentValue::Integer(42));
735
736 let number = AgentValue::from_kind_json("number", json!(3.14)).unwrap();
737 assert!(matches!(number, AgentValue::Number(_)));
738 if let AgentValue::Number(num) = number {
739 assert!((num - 3.14).abs() < f64::EPSILON);
740 }
741
742 let number = AgentValue::from_kind_json("number", json!(3)).unwrap();
743 assert!(matches!(number, AgentValue::Number(_)));
744 if let AgentValue::Number(num) = number {
745 assert!((num - 3.0).abs() < f64::EPSILON);
746 }
747
748 let string = AgentValue::from_kind_json("string", json!("hello")).unwrap();
749 assert!(matches!(string, AgentValue::String(_)));
750 if let AgentValue::String(s) = string {
751 assert_eq!(*s, "hello");
752 } else {
753 panic!("Expected string value");
754 }
755
756 let text = AgentValue::from_kind_json("string", json!("multiline\ntext")).unwrap();
757 assert!(matches!(text, AgentValue::String(_)));
758 if let AgentValue::String(t) = text {
759 assert_eq!(*t, "multiline\ntext");
760 } else {
761 panic!("Expected text value");
762 }
763
764 let array = AgentValue::from_kind_json("array", json!([1, "test", true])).unwrap();
765 assert!(matches!(array, AgentValue::Array(_)));
766 if let AgentValue::Array(arr) = array {
767 assert_eq!(arr.len(), 3);
768 assert_eq!(arr[0], AgentValue::Integer(1));
769 assert!(matches!(&arr[1], AgentValue::String(_)));
770 if let AgentValue::String(s) = &arr[1] {
771 assert_eq!(**s, "test");
772 } else {
773 panic!("Expected string value");
774 }
775 assert_eq!(arr[2], AgentValue::Boolean(true));
776 }
777
778 let obj = AgentValue::from_kind_json("object", json!({"key1": "test", "key2": 2})).unwrap();
779 assert!(matches!(obj, AgentValue::Object(_)));
780 if let AgentValue::Object(obj) = obj {
781 assert_eq!(obj.get("key1").and_then(|v| v.as_str()), Some("test"));
782 assert_eq!(obj.get("key2").and_then(|v| v.as_i64()), Some(2));
783 } else {
784 panic!("Object was not deserialized correctly");
785 }
786
787 let unit_array = AgentValue::from_kind_json("unit", json!([null, null])).unwrap();
789 assert!(matches!(unit_array, AgentValue::Array(_)));
790 if let AgentValue::Array(arr) = unit_array {
791 assert_eq!(arr.len(), 2);
792 for val in arr.iter() {
793 assert_eq!(*val, AgentValue::Unit);
794 }
795 }
796
797 let bool_array = AgentValue::from_kind_json("boolean", json!([true, false])).unwrap();
798 assert!(matches!(bool_array, AgentValue::Array(_)));
799 if let AgentValue::Array(arr) = bool_array {
800 assert_eq!(arr.len(), 2);
801 assert_eq!(arr[0], AgentValue::Boolean(true));
802 assert_eq!(arr[1], AgentValue::Boolean(false));
803 }
804
805 let int_array = AgentValue::from_kind_json("integer", json!([1, 2, 3])).unwrap();
806 assert!(matches!(int_array, AgentValue::Array(_)));
807 if let AgentValue::Array(arr) = int_array {
808 assert_eq!(arr.len(), 3);
809 assert_eq!(arr[0], AgentValue::Integer(1));
810 assert_eq!(arr[1], AgentValue::Integer(2));
811 assert_eq!(arr[2], AgentValue::Integer(3));
812 }
813
814 let num_array = AgentValue::from_kind_json("number", json!([1.1, 2.2, 3.3])).unwrap();
815 assert!(matches!(num_array, AgentValue::Array(_)));
816 if let AgentValue::Array(arr) = num_array {
817 assert_eq!(arr.len(), 3);
818 assert_eq!(arr[0], AgentValue::Number(1.1));
819 assert_eq!(arr[1], AgentValue::Number(2.2));
820 assert_eq!(arr[2], AgentValue::Number(3.3));
821 }
822
823 let string_array = AgentValue::from_kind_json("string", json!(["hello", "world"])).unwrap();
824 assert!(matches!(string_array, AgentValue::Array(_)));
825 if let AgentValue::Array(arr) = string_array {
826 assert_eq!(arr.len(), 2);
827 assert!(matches!(&arr[0], AgentValue::String(_)));
828 if let AgentValue::String(s) = &arr[0] {
829 assert_eq!(**s, "hello".to_string());
830 }
831 assert!(matches!(&arr[1], AgentValue::String(_)));
832 if let AgentValue::String(s) = &arr[1] {
833 assert_eq!(**s, "world".to_string());
834 }
835 }
836
837 let text_array =
838 AgentValue::from_kind_json("string", json!(["hello", "world!\n"])).unwrap();
839 assert!(matches!(text_array, AgentValue::Array(_)));
840 if let AgentValue::Array(arr) = text_array {
841 assert_eq!(arr.len(), 2);
842 assert!(matches!(&arr[0], AgentValue::String(_)));
843 if let AgentValue::String(s) = &arr[0] {
844 assert_eq!(**s, "hello".to_string());
845 }
846 assert!(matches!(&arr[1], AgentValue::String(_)));
847 if let AgentValue::String(s) = &arr[1] {
848 assert_eq!(**s, "world!\n".to_string());
849 }
850 }
851
852 }
856
857 #[test]
858 fn test_agent_value_test_methods() {
859 let unit = AgentValue::unit();
861 assert_eq!(unit.is_unit(), true);
862 assert_eq!(unit.is_boolean(), false);
863 assert_eq!(unit.is_integer(), false);
864 assert_eq!(unit.is_number(), false);
865 assert_eq!(unit.is_string(), false);
866 assert_eq!(unit.is_array(), false);
867 assert_eq!(unit.is_object(), false);
868
869 let boolean = AgentValue::boolean(true);
870 assert_eq!(boolean.is_unit(), false);
871 assert_eq!(boolean.is_boolean(), true);
872 assert_eq!(boolean.is_integer(), false);
873 assert_eq!(boolean.is_number(), false);
874 assert_eq!(boolean.is_string(), false);
875 assert_eq!(boolean.is_array(), false);
876 assert_eq!(boolean.is_object(), false);
877
878 let integer = AgentValue::integer(42);
879 assert_eq!(integer.is_unit(), false);
880 assert_eq!(integer.is_boolean(), false);
881 assert_eq!(integer.is_integer(), true);
882 assert_eq!(integer.is_number(), false);
883 assert_eq!(integer.is_string(), false);
884 assert_eq!(integer.is_array(), false);
885 assert_eq!(integer.is_object(), false);
886
887 let number = AgentValue::number(3.14);
888 assert_eq!(number.is_unit(), false);
889 assert_eq!(number.is_boolean(), false);
890 assert_eq!(number.is_integer(), false);
891 assert_eq!(number.is_number(), true);
892 assert_eq!(number.is_string(), false);
893 assert_eq!(number.is_array(), false);
894 assert_eq!(number.is_object(), false);
895
896 let string = AgentValue::string("hello");
897 assert_eq!(string.is_unit(), false);
898 assert_eq!(string.is_boolean(), false);
899 assert_eq!(string.is_integer(), false);
900 assert_eq!(string.is_number(), false);
901 assert_eq!(string.is_string(), true);
902 assert_eq!(string.is_array(), false);
903 assert_eq!(string.is_object(), false);
904
905 let array = AgentValue::array(vec![AgentValue::integer(1), AgentValue::integer(2)]);
906 assert_eq!(array.is_unit(), false);
907 assert_eq!(array.is_boolean(), false);
908 assert_eq!(array.is_integer(), false);
909 assert_eq!(array.is_number(), false);
910 assert_eq!(array.is_string(), false);
911 assert_eq!(array.is_array(), true);
912 assert_eq!(array.is_object(), false);
913
914 let obj = AgentValue::object(
915 [
916 ("key1".to_string(), AgentValue::string("string1")),
917 ("key2".to_string(), AgentValue::integer(2)),
918 ]
919 .into(),
920 );
921 assert_eq!(obj.is_unit(), false);
922 assert_eq!(obj.is_boolean(), false);
923 assert_eq!(obj.is_integer(), false);
924 assert_eq!(obj.is_number(), false);
925 assert_eq!(obj.is_string(), false);
926 assert_eq!(obj.is_array(), false);
927 assert_eq!(obj.is_object(), true);
928 }
929
930 #[test]
931 fn test_agent_value_accessor_methods() {
932 let boolean = AgentValue::boolean(true);
934 assert_eq!(boolean.as_bool(), Some(true));
935 assert_eq!(boolean.as_i64(), None);
936 assert_eq!(boolean.as_f64(), None);
937 assert_eq!(boolean.as_str(), None);
938 assert!(boolean.as_array().is_none());
939 assert_eq!(boolean.as_object(), None);
940
941 let integer = AgentValue::integer(42);
942 assert_eq!(integer.as_bool(), None);
943 assert_eq!(integer.as_i64(), Some(42));
944 assert_eq!(integer.as_f64(), Some(42.0));
945 assert_eq!(integer.as_str(), None);
946 assert!(integer.as_array().is_none());
947 assert_eq!(integer.as_object(), None);
948
949 let number = AgentValue::number(3.14);
950 assert_eq!(number.as_bool(), None);
951 assert_eq!(number.as_i64(), Some(3)); assert_eq!(number.as_f64().unwrap(), 3.14);
953 assert_eq!(number.as_str(), None);
954 assert!(number.as_array().is_none());
955 assert_eq!(number.as_object(), None);
956
957 let string = AgentValue::string("hello");
958 assert_eq!(string.as_bool(), None);
959 assert_eq!(string.as_i64(), None);
960 assert_eq!(string.as_f64(), None);
961 assert_eq!(string.as_str(), Some("hello"));
962 assert!(string.as_array().is_none());
963 assert_eq!(string.as_object(), None);
964
965 let array = AgentValue::array(vec![AgentValue::integer(1), AgentValue::integer(2)]);
966 assert_eq!(array.as_bool(), None);
967 assert_eq!(array.as_i64(), None);
968 assert_eq!(array.as_f64(), None);
969 assert_eq!(array.as_str(), None);
970 assert!(array.as_array().is_some());
971 if let Some(arr) = array.as_array() {
972 assert_eq!(arr.len(), 2);
973 assert_eq!(arr[0].as_i64().unwrap(), 1);
974 assert_eq!(arr[1].as_i64().unwrap(), 2);
975 }
976 assert_eq!(array.as_object(), None);
977
978 let obj = AgentValue::object(
979 [
980 ("key1".to_string(), AgentValue::string("string1")),
981 ("key2".to_string(), AgentValue::integer(2)),
982 ]
983 .into(),
984 );
985 assert_eq!(obj.as_bool(), None);
986 assert_eq!(obj.as_i64(), None);
987 assert_eq!(obj.as_f64(), None);
988 assert_eq!(obj.as_str(), None);
989 assert!(obj.as_array().is_none());
990 assert!(obj.as_object().is_some());
991 if let Some(value) = obj.as_object() {
992 assert_eq!(value.get("key1").and_then(|v| v.as_str()), Some("string1"));
993 assert_eq!(value.get("key2").and_then(|v| v.as_i64()), Some(2));
994 }
995 }
996
997 #[test]
998 fn test_agent_value_default() {
999 assert_eq!(AgentValue::default(), AgentValue::Unit);
1000 }
1001
1002 #[test]
1003 fn test_agent_value_serialization() {
1004 {
1006 let null = AgentValue::Unit;
1007 assert_eq!(serde_json::to_string(&null).unwrap(), "null");
1008 }
1009
1010 {
1012 let boolean_t = AgentValue::boolean(true);
1013 assert_eq!(serde_json::to_string(&boolean_t).unwrap(), "true");
1014
1015 let boolean_f = AgentValue::boolean(false);
1016 assert_eq!(serde_json::to_string(&boolean_f).unwrap(), "false");
1017 }
1018
1019 {
1021 let integer = AgentValue::integer(42);
1022 assert_eq!(serde_json::to_string(&integer).unwrap(), "42");
1023 }
1024
1025 {
1027 let num = AgentValue::number(3.14);
1028 assert_eq!(serde_json::to_string(&num).unwrap(), "3.14");
1029
1030 let num = AgentValue::number(3.0);
1031 assert_eq!(serde_json::to_string(&num).unwrap(), "3.0");
1032 }
1033
1034 {
1036 let s = AgentValue::string("Hello, world!");
1037 assert_eq!(serde_json::to_string(&s).unwrap(), "\"Hello, world!\"");
1038
1039 let s = AgentValue::string("hello\nworld\n\n");
1040 assert_eq!(serde_json::to_string(&s).unwrap(), r#""hello\nworld\n\n""#);
1041 }
1042
1043 #[cfg(feature = "image")]
1045 {
1046 let img = AgentValue::image(PhotonImage::new(vec![0u8; 4], 1, 1));
1047 assert_eq!(
1048 serde_json::to_string(&img).unwrap(),
1049 r#""data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAEElEQVR4AQEFAPr/AAAAAAAABQABZHiVOAAAAABJRU5ErkJggg==""#
1050 );
1051 }
1052
1053 {
1055 let array = AgentValue::array(vec![
1056 AgentValue::integer(1),
1057 AgentValue::string("test"),
1058 AgentValue::object(
1059 [
1060 ("key1".to_string(), AgentValue::string("test")),
1061 ("key2".to_string(), AgentValue::integer(2)),
1062 ]
1063 .into(),
1064 ),
1065 ]);
1066 assert_eq!(
1067 serde_json::to_string(&array).unwrap(),
1068 r#"[1,"test",{"key1":"test","key2":2}]"#
1069 );
1070 }
1071
1072 {
1074 let obj = AgentValue::object(
1075 [
1076 ("key1".to_string(), AgentValue::string("test")),
1077 ("key2".to_string(), AgentValue::integer(3)),
1078 ]
1079 .into(),
1080 );
1081 assert_eq!(
1082 serde_json::to_string(&obj).unwrap(),
1083 r#"{"key1":"test","key2":3}"#
1084 );
1085 }
1086 }
1087
1088 #[test]
1089 fn test_agent_value_deserialization() {
1090 {
1092 let deserialized: AgentValue = serde_json::from_str("null").unwrap();
1093 assert_eq!(deserialized, AgentValue::Unit);
1094 }
1095
1096 {
1098 let deserialized: AgentValue = serde_json::from_str("false").unwrap();
1099 assert_eq!(deserialized, AgentValue::boolean(false));
1100
1101 let deserialized: AgentValue = serde_json::from_str("true").unwrap();
1102 assert_eq!(deserialized, AgentValue::boolean(true));
1103 }
1104
1105 {
1107 let deserialized: AgentValue = serde_json::from_str("123").unwrap();
1108 assert_eq!(deserialized, AgentValue::integer(123));
1109 }
1110
1111 {
1113 let deserialized: AgentValue = serde_json::from_str("3.14").unwrap();
1114 assert_eq!(deserialized, AgentValue::number(3.14));
1115
1116 let deserialized: AgentValue = serde_json::from_str("3.0").unwrap();
1117 assert_eq!(deserialized, AgentValue::number(3.0));
1118 }
1119
1120 {
1122 let deserialized: AgentValue = serde_json::from_str("\"Hello, world!\"").unwrap();
1123 assert_eq!(deserialized, AgentValue::string("Hello, world!"));
1124
1125 let deserialized: AgentValue = serde_json::from_str(r#""hello\nworld\n\n""#).unwrap();
1126 assert_eq!(deserialized, AgentValue::string("hello\nworld\n\n"));
1127 }
1128
1129 #[cfg(feature = "image")]
1131 {
1132 let deserialized: AgentValue = serde_json::from_str(
1133 r#""data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAEElEQVR4AQEFAPr/AAAAAAAABQABZHiVOAAAAABJRU5ErkJggg==""#,
1134 )
1135 .unwrap();
1136 assert!(matches!(deserialized, AgentValue::Image(_)));
1137 }
1138
1139 {
1141 let deserialized: AgentValue =
1142 serde_json::from_str(r#"[1,"test",{"key1":"test","key2":2}]"#).unwrap();
1143 assert!(matches!(deserialized, AgentValue::Array(_)));
1144 if let AgentValue::Array(arr) = deserialized {
1145 assert_eq!(arr.len(), 3, "Array length mismatch after serialization");
1146 assert_eq!(arr[0], AgentValue::integer(1));
1147 assert_eq!(arr[1], AgentValue::string("test"));
1148 assert_eq!(
1149 arr[2],
1150 AgentValue::object(
1151 [
1152 ("key1".to_string(), AgentValue::string("test")),
1153 ("key2".to_string(), AgentValue::integer(2)),
1154 ]
1155 .into()
1156 )
1157 );
1158 }
1159 }
1160
1161 {
1163 let deserialized: AgentValue =
1164 serde_json::from_str(r#"{"key1":"test","key2":3}"#).unwrap();
1165 assert_eq!(
1166 deserialized,
1167 AgentValue::object(
1168 [
1169 ("key1".to_string(), AgentValue::string("test")),
1170 ("key2".to_string(), AgentValue::integer(3)),
1171 ]
1172 .into()
1173 )
1174 );
1175 }
1176 }
1177
1178 #[test]
1179 fn test_serialize_deserialize_roundtrip() {
1180 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1181 struct TestStruct {
1182 name: String,
1183 age: i64,
1184 active: bool,
1185 }
1186
1187 let test_data = TestStruct {
1188 name: "Alice".to_string(),
1189 age: 30,
1190 active: true,
1191 };
1192
1193 let agent_data = AgentValue::from_serialize(&test_data).unwrap();
1195 assert_eq!(agent_data.get_str("name"), Some("Alice"));
1196 assert_eq!(agent_data.get_i64("age"), Some(30));
1197 assert_eq!(agent_data.get_bool("active"), Some(true));
1198
1199 let restored: TestStruct = agent_data.to_deserialize().unwrap();
1200 assert_eq!(restored, test_data);
1201 }
1202
1203 #[test]
1204 fn test_serialize_deserialize_nested() {
1205 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1206 struct Address {
1207 street: String,
1208 city: String,
1209 zip: String,
1210 }
1211
1212 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1213 struct Person {
1214 name: String,
1215 age: i64,
1216 address: Address,
1217 tags: Vec<String>,
1218 }
1219
1220 let person = Person {
1221 name: "Bob".to_string(),
1222 age: 25,
1223 address: Address {
1224 street: "123 Main St".to_string(),
1225 city: "Springfield".to_string(),
1226 zip: "12345".to_string(),
1227 },
1228 tags: vec!["developer".to_string(), "rust".to_string()],
1229 };
1230
1231 let agent_data = AgentValue::from_serialize(&person).unwrap();
1233 assert_eq!(agent_data.get_str("name"), Some("Bob"));
1234
1235 let address = agent_data.get_object("address").unwrap();
1236 assert_eq!(
1237 address.get("city").and_then(|v| v.as_str()),
1238 Some("Springfield")
1239 );
1240
1241 let tags = agent_data.get_array("tags").unwrap();
1242 assert_eq!(tags.len(), 2);
1243 assert_eq!(tags[0].as_str(), Some("developer"));
1244
1245 let restored: Person = agent_data.to_deserialize().unwrap();
1246 assert_eq!(restored, person);
1247 }
1248}