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