syslog_rs/sync/
syslog_stream.rs

1/*-
2 * syslog-rs - a syslog client translated from libc to rust
3 * 
4 * Copyright 2025 Aleksandr Morozov
5 * 
6 * The syslog-rs crate can be redistributed and/or modified
7 * under the terms of either of the following licenses:
8 *
9 *   1. the Mozilla Public License Version 2.0 (the “MPL”) OR
10 *                     
11 *   2. EUROPEAN UNION PUBLIC LICENCE v. 1.2 EUPL © the European Union 2007, 2016
12 */
13
14use std::{fmt::{self, Arguments, Write}, marker::PhantomData};
15
16
17use crate::{formatters::SyslogFormatter, sync::syslog_trait::SyslogApi, Priority, SyslogDestination};
18
19/// A standart trait which provides the access to the instance which implements [std::fmt::Write].
20/// 
21/// The syslog requres the [Priority] of the message to be specified. The `Write` does not 
22/// allow to provide additional arguments. For this reason, a function `stream` borrows the
23/// current syslog instance and stores the [Priority] which will be used later.
24pub trait SyStreamApi<'stream, F: SyslogFormatter, D: SyslogDestination, S: SyslogApi<F, D>>
25{
26    /// Creates the temporary structure which holds the [Priority] and implements 
27    /// [std::fmt::Write]. A [SyStream] is returned which can be used directly
28    /// with [write].
29    /// 
30    /// ```ignore
31    /// write!(SYSLOG.stream(Priority::LOG_DEBUG),
32    /// ```
33    fn stream(&'stream self, pri: Priority) -> SyStream<'stream, D, F, S>;
34}
35
36/// A structure which holds the [Priority] and reference to the syslog instance.
37/// 
38/// It implements [std::fmt::Write] so, the macro [write] can be used direclty.
39pub struct SyStream<'stream, D: SyslogDestination, F: SyslogFormatter, S: SyslogApi<F, D>>
40{
41    /// Syslog instance
42    pub(crate) inner: &'stream S,
43
44    /// Priority
45    pub(crate) pri: Priority,
46
47    pub(crate) _p: PhantomData<F>,
48
49    pub(crate) _p1: PhantomData<D>,
50}
51
52impl<'stream, D: SyslogDestination, F: SyslogFormatter, S: SyslogApi<F, D>> Write 
53for SyStream<'stream, D, F, S>
54{
55    fn write_str(&mut self, s: &str) -> fmt::Result 
56    {
57        let s = s.to_string();
58
59        self.inner.syslog(self.pri, s.into());
60
61        return Ok(());
62    }
63
64    fn write_fmt(self: &mut Self, args: Arguments<'_>) -> fmt::Result
65    {
66        if let Some(s) = args.as_str() 
67        {
68            self.inner.syslog(self.pri, s.into());
69
70            return Ok(());
71        } 
72        else 
73        {
74            self.inner.syslog(self.pri, args.to_string().into());
75
76            return Ok(());
77        }
78    }
79}
80