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
use std::fmt::Display;

use serde::{Serialize, Serializer};
use serde_json::json;

use crate::Message;

/// Print a single value result of a computation to the user.
///
/// In JSON mode, this will emit like this:
/// ```json
/// {"name":value}
/// ```
///
/// In text mode, `name` is omitted.
pub struct ValueMessage<'a, T> {
    name: &'a str,
    value: &'a T,
}

impl<'a, T> ValueMessage<'a, T> {
    /// Create a new value message.
    pub fn new(name: &'a str, value: &'a T) -> Self {
        Self { name, value }
    }
}

impl<'a, T> Message for ValueMessage<'a, T>
where
    T: Display + Serialize,
{
    fn text(self) -> String {
        self.value.to_string()
    }

    fn structured<S: Serializer>(self, ser: S) -> Result<S::Ok, S::Error> {
        json!({
            self.name: self.value
        })
        .serialize(ser)
    }
}