scarb_ui/components/
value.rs

1use std::fmt::Display;
2
3use serde::{Serialize, Serializer};
4use serde_json::json;
5
6use crate::Message;
7
8/// Print a single value result of a computation to the user.
9///
10/// In JSON mode, this will emit like this:
11/// ```json
12/// {"name":value}
13/// ```
14///
15/// In text mode, `name` is omitted.
16pub struct ValueMessage<'a, T> {
17    name: &'a str,
18    value: &'a T,
19}
20
21impl<'a, T> ValueMessage<'a, T> {
22    /// Create a new value message.
23    pub fn new(name: &'a str, value: &'a T) -> Self {
24        Self { name, value }
25    }
26}
27
28impl<T> Message for ValueMessage<'_, T>
29where
30    T: Display + Serialize,
31{
32    fn text(self) -> String {
33        self.value.to_string()
34    }
35
36    fn structured<S: Serializer>(self, ser: S) -> Result<S::Ok, S::Error> {
37        json!({
38            self.name: self.value
39        })
40        .serialize(ser)
41    }
42}