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
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
//!Fluentd forward protocol definitions.
use serde::ser::{Serialize, Serializer, SerializeTuple, SerializeMap};

#[derive(Clone)]
#[repr(transparent)]
///HashMap object suitable for fluent record.
pub struct Map(indexmap::IndexMap<String, Value>);

impl Map {
    #[inline(always)]
    ///Creates new empty map.
    pub fn new() -> Self {
        Self(indexmap::IndexMap::new())
    }
}

impl core::fmt::Debug for Map {
    #[inline(always)]
    fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
        core::fmt::Debug::fmt(&self.0, fmt)
    }
}

impl core::ops::Deref for Map {
    type Target = indexmap::IndexMap<String, Value>;

    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl core::ops::DerefMut for Map {
    #[inline(always)]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

use core::fmt;

#[derive(Debug)]
pub(crate) struct Opts {
    size: usize,
}

#[derive(Clone)]
///Map value type.
pub enum Value {
    ///Boolean
    Bool(bool),
    ///Integer
    Int(i64),
    ///Unsigned integer
    Uint(u64),
    ///String
    Str(String),
    ///Event level
    EventLevel(tracing_core::Level),
    ///Object
    Object(Map),
}

impl From<bool> for Value {
    #[inline(always)]
    fn from(val: bool) -> Self {
        Self::Bool(val)
    }
}

impl From<i64> for Value {
    #[inline(always)]
    fn from(val: i64) -> Self {
        Self::Int(val)
    }
}

impl From<u32> for Value {
    #[inline(always)]
    fn from(val: u32) -> Self {
        Self::Uint(val as _)
    }
}

impl From<u64> for Value {
    #[inline(always)]
    fn from(val: u64) -> Self {
        Self::Uint(val)
    }
}

impl From<String> for Value {
    #[inline(always)]
    fn from(val: String) -> Self {
        Self::Str(val)
    }
}

impl From<tracing::Level> for Value {
    #[inline(always)]
    fn from(val: tracing::Level) -> Self {
        Self::EventLevel(val)
    }
}

impl From<Map> for Value {
    #[inline(always)]
    fn from(val: Map) -> Self {
        Self::Object(val)
    }
}

impl fmt::Debug for Value {
    #[inline(always)]
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Value::Bool(val) => fmt.write_fmt(format_args!("{}", val)),
            Value::Int(val) => fmt.write_fmt(format_args!("{}", val)),
            Value::Uint(val) => fmt.write_fmt(format_args!("{}", val)),
            Value::EventLevel(val) => fmt.write_fmt(format_args!("{:?}", val)),
            Value::Str(val) => fmt.write_fmt(format_args!("{:?}", val)),
            Value::Object(val) => fmt.write_fmt(format_args!("{:?}", val)),
        }
    }
}

#[derive(Debug)]
///Representation of fluent entry within `Message`
pub struct Record {
    time: u64,
    entries: Map,
}

impl Record {
    ///Creates record with current timestamp
    pub fn now() -> Self {
        let time = match std::time::SystemTime::now().duration_since(std::time::SystemTime::UNIX_EPOCH) {
            Ok(time) => time.as_secs(),
            Err(_) => panic!("SystemTime is before UNIX!?"),
        };

        Self {
            time,
            entries: Map::new(),
        }
    }

    ///Merges record entries with provided map
    pub fn update(&mut self, other: &Map) {
        for (key, value) in other.iter() {
            if !self.entries.contains_key(key) {
                self.entries.insert(key.clone(), value.clone());
            }
        }
    }
}

impl core::ops::Deref for Record {
    type Target = Map;

    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        &self.entries
    }
}

impl core::ops::DerefMut for Record {
    #[inline(always)]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.entries
    }
}

#[derive(Debug)]
///Forward mode message.
pub struct Message {
    tag: &'static str,
    entries: Vec<Record>,
    opts: Opts,
    //option
}

impl Message {
    #[inline(always)]
    ///Creates new message with provided tag.
    pub const fn new(tag: &'static str) -> Self {
        Self {
            tag,
            entries: Vec::new(),
            opts: Opts {
                size: 0,
            }
        }
    }

    #[inline(always)]
    ///Adds record to the message.
    pub fn add(&mut self, record: Record) {
        self.entries.push(record);
        self.opts.size += 1;
    }

    #[inline(always)]
    ///Returns number of records inside message.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    #[inline(always)]
    ///Clears records from the message
    pub fn clear(&mut self) {
        self.entries.clear();
        self.opts.size = 0;
    }
}

fn tracing_level_to_str(level: tracing_core::Level) -> &'static str {
    if level == tracing_core::Level::ERROR {
        "ERROR"
    } else if level == tracing_core::Level::WARN {
        "WARN"
    } else if level == tracing_core::Level::INFO {
        "INFO"
    } else if level == tracing_core::Level::DEBUG {
        "DEBUG"
    } else {
        "TRACE"
    }
}

impl Serialize for Value {
    #[inline]
    fn serialize<SER: Serializer>(&self, ser: SER) -> Result<SER::Ok, SER::Error> {
        match self {
            Value::Bool(val) => ser.serialize_bool(*val),
            Value::Int(val) => ser.serialize_i64(*val),
            Value::Uint(val) => ser.serialize_u64(*val),
            Value::EventLevel(val) => ser.serialize_str(tracing_level_to_str(*val)),
            Value::Str(val) => ser.serialize_str(val),
            Value::Object(val) => {
                let mut map = ser.serialize_map(Some(val.len()))?;
                for (key, value) in val.iter() {
                    map.serialize_entry(key, value)?;
                }
                map.end()
            },
        }
    }
}

impl Serialize for Map {
    #[inline]
    fn serialize<SER: Serializer>(&self, ser: SER) -> Result<SER::Ok, SER::Error> {
        let mut map = ser.serialize_map(Some(self.0.len()))?;
        for (key, value) in self.0.iter() {
            map.serialize_entry(key, value)?;
        }
        map.end()
    }
}

impl Serialize for Opts {
    #[inline]
    fn serialize<SER: Serializer>(&self, ser: SER) -> Result<SER::Ok, SER::Error> {
        let mut map = ser.serialize_map(Some(1))?;
        map.serialize_entry("size", &self.size)?;
        map.end()
    }
}

impl Serialize for Record {
    #[inline]
    fn serialize<SER: Serializer>(&self, ser: SER) -> Result<SER::Ok, SER::Error> {
        let mut seq = ser.serialize_tuple(2)?;
        seq.serialize_element(&self.time)?;
        seq.serialize_element(&self.entries)?;
        seq.end()
    }
}

impl Serialize for Message {
    #[inline]
    fn serialize<SER: Serializer>(&self, ser: SER) -> Result<SER::Ok, SER::Error> {
        let mut seq = ser.serialize_tuple(3)?;
        seq.serialize_element(&self.tag)?;
        seq.serialize_element(&self.entries)?;
        seq.serialize_element(&self.opts)?;
        seq.end()
    }
}