Skip to main content

troupekit_trace/
value.rs

1use std::borrow::Cow;
2
3/// One field value of a trace record.
4/// `Content` holds user text (prompts, replies, queries) and is written
5/// only when the scope keeps content; otherwise only its byte count.
6#[derive(Clone, Debug, PartialEq)]
7#[non_exhaustive]
8pub enum Value {
9    Str(String),
10    Int(i64),
11    UInt(u64),
12    Float(f64),
13    Bool(bool),
14    Content(String),
15}
16
17/// Marks `text` as user content, withheld unless the scope keeps content.
18/// Input: the text. Output: a `Value::Content`.
19pub fn content(text: impl Into<String>) -> Value {
20    Value::Content(text.into())
21}
22
23/// Returns the longest prefix of `text` of at most `bytes_max` bytes that
24/// ends on a char boundary. Input: text and byte limit. Output: the prefix.
25pub(crate) fn cut_to(text: &str, bytes_max: usize) -> &str {
26    if text.len() <= bytes_max {
27        return text;
28    }
29    let mut end = bytes_max;
30    while !text.is_char_boundary(end) {
31        end -= 1;
32    }
33    assert!(end <= bytes_max);
34    assert!(bytes_max - end < 4);
35    &text[..end]
36}
37
38macro_rules! from_as {
39    ($variant:ident, $target:ty, $($source:ty),*) => {
40        $(impl From<$source> for Value {
41            fn from(value: $source) -> Value {
42                Value::$variant(<$target>::from(value))
43            }
44        })*
45    };
46}
47
48from_as!(Int, i64, i8, i16, i32, i64);
49from_as!(UInt, u64, u8, u16, u32, u64);
50from_as!(Float, f64, f32, f64);
51from_as!(Bool, bool, bool);
52from_as!(Str, String, &str, String, &String, Box<str>, char);
53
54impl From<isize> for Value {
55    fn from(value: isize) -> Value {
56        Value::Int(i64::try_from(value).unwrap_or(if value < 0 { i64::MIN } else { i64::MAX }))
57    }
58}
59
60impl From<usize> for Value {
61    fn from(value: usize) -> Value {
62        Value::UInt(u64::try_from(value).unwrap_or(u64::MAX))
63    }
64}
65
66impl From<Cow<'_, str>> for Value {
67    fn from(value: Cow<'_, str>) -> Value {
68        Value::Str(value.into_owned())
69    }
70}
71
72impl From<std::time::Duration> for Value {
73    fn from(value: std::time::Duration) -> Value {
74        Value::UInt(u64::try_from(value.as_micros()).unwrap_or(u64::MAX))
75    }
76}