syslog_ng_common/
formatter.rs

1// Copyright (c) 2016 Tibor Benke <ihrwein@gmail.com>
2//
3// Licensed under the Apache License, Version 2.0
4// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
5// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. All files in the project carrying such notice may not be copied,
7// modified, or distributed except according to those terms.
8
9use std::fmt::Write;
10
11#[derive(Clone)]
12pub struct MessageFormatter {
13    buffer: String,
14    prefix: Option<String>,
15}
16
17impl MessageFormatter {
18    pub fn new() -> MessageFormatter {
19        MessageFormatter {
20            buffer: String::new(),
21            prefix: None,
22        }
23    }
24
25    pub fn set_prefix(&mut self, prefix: String) {
26        self.prefix = Some(prefix)
27    }
28
29    pub fn format<'a, 'b, 'c>(&'a mut self, key: &'b str, value: &'c str) -> (&'a str, &'c str) {
30        self.buffer.clear();
31        self.apply_prefix(key);
32        (&self.buffer, value)
33    }
34
35    fn apply_prefix(&mut self, key: &str) {
36        match self.prefix.as_ref() {
37            Some(prefix) => {
38                let _ = self.buffer.write_str(prefix);
39                let _ = self.buffer.write_str(key);
40            }
41            None => {
42                let _ = self.buffer.write_str(key);
43            }
44        };
45    }
46}