syslog_fmt 0.5.0

Zero-allocation RFC 5424 syslog message formatter
Documentation
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
//! RFC 5424 message formatter.
//!
//! All write methods accept an [`io::Write`] target so that callers can stream output directly into
//! a socket buffer or a fixed-size stack array without any intermediate heap allocation. The one
//! unavoidable allocation happens at [`Formatter`] construction time, where the static header fields
//! are pre-formatted once and reused across every subsequent write.
use core::fmt;
use std::io;

#[cfg(feature = "chrono")]
use chrono::Offset as _;

use crate::{Facility, Priority, Severity};

const SPACE_BYTE: u8 = 0x20;

/// Builder for a [`Formatter`].
///
/// Keeping configuration separate from [`Formatter`] lets callers hold borrowed strings (`&str`)
/// during setup, while [`Formatter`] owns its pre-formatted representation and can therefore outlive
/// the original string references.
#[derive(Default)]
pub struct Config<'a> {
    pub facility: Facility,
    pub hostname: Option<&'a Hostname>,
    pub app_name: Option<&'a AppName>,
    pub proc_id: Option<&'a ProcId>,
}

impl Config<'_> {
    /// Consumes the config and produces a [`Formatter`].
    pub fn into_formatter(self) -> Formatter {
        self.into()
    }
}

impl<'a> From<Config<'a>> for Formatter {
    fn from(config: Config<'a>) -> Self {
        Formatter::from_config(config)
    }
}

/// Produces [RFC 5424](https://datatracker.ietf.org/doc/html/rfc5424) syslog messages.
///
/// The fields that are constant for the lifetime of a process (hostname, app-name, proc-id) are
/// formatted once at construction and reused on every write, so the per-message hot path performs
/// no heap allocation.
#[derive(Clone, Debug)]
pub struct Formatter {
    facility: Facility,

    /// Pre-formatted `"HOSTNAME APP-NAME PROCID"` substring.
    ///
    /// These three fields never change within a syslog session, so paying the formatting cost once
    /// at construction amortises it across all messages.
    host_app_proc_id: Box<str>,
}

impl Default for Formatter {
    fn default() -> Self {
        Config::default().into_formatter()
    }
}

impl Formatter {
    /// Creates a formatter from the given config.
    ///
    /// This is where the crate's only allocation occurs. Always provide a hostname; many syslog
    /// collectors use it for routing and deduplication.
    ///
    /// [spec](https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.4)
    pub fn from_config(config: Config<'_>) -> Self {
        let hostname = config.hostname;
        let app_name = config.app_name;
        let proc_id = config.proc_id;

        let hostname = hostname.unwrap_or(NILVALUE);
        let app_name = app_name.unwrap_or(NILVALUE);
        let proc_id = proc_id.unwrap_or(NILVALUE);

        let host_app_proc_id = format!("{hostname} {app_name} {proc_id}").into_boxed_str();

        Self {
            facility: config.facility,
            host_app_proc_id,
        }
    }

    /// Writes a complete RFC 5424 message including structured data.
    ///
    /// Structured data is kept in a separate method from [`Self::write_without_data`] because the
    /// iterator generics it requires would otherwise burden every caller that only needs a plain text
    /// message.
    ///
    /// ```rust
    /// use std::io::Write;
    ///
    /// use syslog_fmt::{Severity, Facility, v5424::{Config, Formatter, Timestamp}};
    ///
    /// let mut buf = Vec::<u8>::new();
    /// let formatter = Config {
    ///     facility: Facility::Local7,
    ///     hostname: Some("localhost"),
    ///     app_name: Some("app-name"),
    ///     proc_id: Some("proc-id"),
    /// }
    /// .into_formatter();
    /// formatter.write_with_data(
    ///     &mut buf,
    ///     Severity::Info,
    ///     Timestamp::PreformattedStr("2025-01-01T00:00:00.000000+00:00"),
    ///     "this is a message",
    ///     Some("msg-id"),
    ///     vec![("elem-a", vec![("param-a", "value-a")])]
    /// );
    /// ```
    pub fn write_with_data<'a, W, TS, M, I, P>(
        &self,
        w: &mut W,
        severity: Severity,
        timestamp: TS,
        msg: M,
        msg_id: Option<&MsgId>,
        data: I,
    ) -> io::Result<()>
    where
        W: io::Write,
        TS: Into<Timestamp<'a>>,
        M: Into<Msg<'a>>,
        I: IntoIterator<Item = (&'a SdId, P)> + 'a,
        P: IntoIterator<Item = SdParam<'a>> + 'a,
    {
        self.write_header(w, severity, timestamp, msg_id)?;
        write_data(w, data)?;
        write_msg(w, msg)
    }

    /// Writes a complete RFC 5424 message without structured data.
    ///
    /// The STRUCTURED-DATA field is set to NILVALUE (`-`) as the RFC requires a placeholder rather than
    /// simply omitting the field, so that parsers can rely on a fixed number of space-delimited fields
    /// in the header.
    ///
    /// ```rust
    /// use std::io::Write;
    ///
    /// use syslog_fmt::{Severity, Facility, v5424::{Config, Formatter, Timestamp}};
    ///
    /// let mut buf = Vec::<u8>::new();
    /// let formatter = Config {
    ///     facility: Facility::Local7,
    ///     hostname: Some("localhost"),
    ///     app_name: Some("app-name"),
    ///     proc_id: Some("proc-id"),
    /// }
    /// .into_formatter();
    /// formatter.write_without_data(
    ///     &mut buf,
    ///     Severity::Info,
    ///     Timestamp::PreformattedStr("2025-01-01T00:00:00.000000+00:00"),
    ///     "this is a message",
    ///     Some("msg-id")
    /// );
    /// ```
    pub fn write_without_data<'a, W, TS, M>(
        &self,
        w: &mut W,
        severity: Severity,
        timestamp: TS,
        msg: M,
        msg_id: Option<&MsgId>,
    ) -> io::Result<()>
    where
        W: io::Write,
        TS: Into<Timestamp<'a>>,
        M: Into<Msg<'a>>,
    {
        self.write_header(w, severity, timestamp, msg_id)?;
        write_nil_value(w)?;
        write_msg(w, msg)
    }

    /// Writes the RFC 5424 header (PRIORITY VERSION TIMESTAMP HOSTNAME APP-NAME PROCID MSGID).
    ///
    /// Exposed publicly so that callers can compose messages manually by interleaving their own
    /// [`io::Write`] calls between the header, structured-data, and message sections.
    pub fn write_header<'a, W, TS>(
        &self,
        w: &mut W,
        severity: Severity,
        timestamp: TS,
        msg_id: Option<&MsgId>,
    ) -> io::Result<()>
    where
        W: io::Write,
        TS: Into<Timestamp<'a>>,
    {
        let Self {
            facility,
            host_app_proc_id,
        } = self;

        let prio = encode_priority(severity, *facility);
        let msg_id = msg_id.unwrap_or(NILVALUE);

        write!(w, "<{prio}>{VERSION} ")?;

        let timestamp = timestamp.into();

        match timestamp {
            #[cfg(feature = "chrono")]
            Timestamp::Chrono(datetime) => {
                write_chrono_datetime(w, datetime)?;
            }
            #[cfg(feature = "chrono")]
            Timestamp::CreateChronoLocal => {
                let datetime = chrono::Local::now();
                write_chrono_datetime(w, &datetime)?;
            }
            Timestamp::PreformattedStr(s) => w.write_all(s.as_bytes())?,
            Timestamp::PreformattedString(s) => w.write_all(s.as_bytes())?,
            Timestamp::None => write_nil_value(w)?,
        };

        write!(w, " {host_app_proc_id} {msg_id}")?;
        Ok(())
    }
}

/// Writes the STRUCTURED-DATA field, prefixed by a space.
///
/// Exposed publicly for the same reason as [`Formatter::write_header`]: to allow callers to build
/// messages section by section. When `data` is empty the RFC requires NILVALUE rather than an
/// absent field, so parsers can assume a fixed header structure.
///
/// [spec](https://datatracker.ietf.org/doc/html/rfc5424#section-6.3)
pub fn write_data<'a, W, I, P>(w: &mut W, data: I) -> io::Result<()>
where
    W: io::Write,
    I: IntoIterator<Item = (&'a SdId, P)> + 'a,
    P: IntoIterator<Item = SdParam<'a>> + 'a,
{
    let mut elems = data.into_iter();

    let Some(elem) = elems.next() else {
        write!(w, " {NILVALUE}")?;
        return Ok(());
    };

    write!(w, " ")?;
    write_data_elem(w, elem)?;

    for elem in elems {
        write_data_elem(w, elem)?;
    }

    Ok(())
}

/// Writes a PARAM-VALUE with the escaping required by RFC 5424 §6.3.3.
/// The characters `"`, `\`, and `]` must be escaped with a leading `\`.
fn write_param_value<W: io::Write>(w: &mut W, value: &str) -> io::Result<()> {
    for c in value.chars() {
        match c {
            '"' => w.write_all(b"\\\"")?,
            '\\' => w.write_all(b"\\\\")?,
            ']' => w.write_all(b"\\]")?,
            _ => write!(w, "{c}")?,
        }
    }
    Ok(())
}

fn write_data_elem<'a, W, P>(w: &mut W, elem: (&'a SdId, P)) -> io::Result<()>
where
    W: io::Write,
    P: IntoIterator<Item = SdParam<'a>> + 'a,
{
    let (id, params) = elem;

    let mut params = params.into_iter();

    let Some(param) = params.next() else {
        write!(w, "[{id}]")?;
        return Ok(());
    };

    let (name, value) = param;
    write!(w, "[{id} {name}=\"")?;
    write_param_value(w, value)?;
    write!(w, "\"")?;

    for param in params {
        let (name, value) = param;
        write!(w, " {name}=\"")?;
        write_param_value(w, value)?;
        write!(w, "\"")?;
    }

    write!(w, "]")
}

/// Writes the MSG field, prefixed by a space.
///
/// Exposed publicly for the same reason as [`Formatter::write_header`]: to allow callers to build
/// messages section by section.
pub fn write_msg<'a, W, M>(w: &mut W, msg: M) -> io::Result<()>
where
    W: io::Write,
    M: Into<Msg<'a>>,
{
    let msg = msg.into();

    match msg {
        Msg::Utf8Str(s) => write_str_msg(w, s),
        Msg::Utf8String(s) => write_str_msg(w, &s),
        Msg::NonUnicodeBytes(bytes) => {
            w.write_all(&[SPACE_BYTE])?;
            w.write_all(bytes)
        }
        Msg::FmtArguments(args) => write!(w, " {args}"),
        Msg::FmtArgumentsRef(args) => write!(w, " {args}"),
    }
}

/// Writes a NILVALUE (`-`) prefixed with a space.
///
/// The RFC requires NILVALUE as a placeholder for any absent optional field so that parsers can rely
/// on a fixed number of space-delimited fields.
pub fn write_nil_value<W>(w: &mut W) -> io::Result<()>
where
    W: io::Write,
{
    write!(w, " {NILVALUE}")?;
    Ok(())
}

/// Formats a [`chrono::DateTime<Local>`] as an RFC 3339 timestamp and writes it without any heap
/// allocation.
///
/// Chrono's built-in `to_rfc3339` allocates a `String`; writing field-by-field into the output
/// avoids that and keeps the per-message write path allocation-free.
#[cfg(feature = "chrono")]
pub fn write_chrono_datetime<W, Tz>(w: &mut W, datetime: &chrono::DateTime<Tz>) -> io::Result<()>
where
    W: io::Write,
    Tz: chrono::TimeZone,
{
    use chrono::Timelike;

    const MICRO_IN_NANO: u32 = 1_000;
    const SEC_IN_HOUR: u32 = 3600;
    const PLUS: &str = "+";
    const MIN: &str = "-";

    // reuse chrono `Debug` impls which already print ISO 8601 format.
    let date = datetime.date_naive();
    let time = datetime.time();
    let h = time.hour();
    let m = time.minute();
    let s = time.second();
    let us = time.nanosecond() / MICRO_IN_NANO;
    let total_offset_secs = datetime.offset().fix().local_minus_utc();
    let sign = if total_offset_secs >= 0 { PLUS } else { MIN };
    let total_offset_abs = total_offset_secs.unsigned_abs();
    let offset_hour = total_offset_abs / SEC_IN_HOUR;
    let offset_min = (total_offset_abs % SEC_IN_HOUR) / 60;

    write!(
        w,
        "{date:?}T{h:02}:{m:02}:{s:02}.{us:06}{sign}{offset_hour:02}:{offset_min:02}"
    )?;

    Ok(())
}

/// Writes a UTF-8 BOM prefixed by a space.
///
/// The RFC requires the BOM at the start of a UTF-8 MSG field so that receivers can detect the
/// encoding without inspecting every byte.
pub fn write_utf8_bom<W: io::Write>(w: &mut W) -> io::Result<()> {
    // the BOM is prefixed by an ASCII space
    const BOM: [u8; 4] = [SPACE_BYTE, 0xEF, 0xBB, 0xBF];
    w.write_all(&BOM)
}

/// Writes a UTF-8 string prefixed with a space and a BOM.
///
/// Empty strings skip the BOM because an absent MSG and an empty MSG are treated the same way by
/// receivers; emitting just a BOM with no content would be misleading.
fn write_str_msg<W: io::Write>(w: &mut W, s: &str) -> io::Result<()> {
    if !s.is_empty() {
        write_utf8_bom(w)?;
        w.write_all(s.as_bytes())?;
    }

    Ok(())
}

/// Placeholder written whenever a header field is absent.
///
/// The RFC requires a literal `-` rather than an omitted field so that parsers can rely on a fixed
/// number of space-delimited fields in every message.
const NILVALUE: &str = "-";

/// Protocol version, always `"1"` for RFC 5424.
///
/// A future breaking change to the HEADER format would warrant a new version number and, in this
/// crate, a new module alongside `v5424`.
///
/// [spec](https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.2)
const VERSION: &str = "1";

/// Concrete datetime type used by the [`Timestamp::Chrono`] and [`Timestamp::CreateChronoLocal`]
/// variants.
#[cfg(feature = "chrono")]
type ChronoLocalTime = chrono::DateTime<chrono::Local>;

/// The timestamp field of a syslog message.
///
/// RFC 5424 restricts RFC 3339: `T` and `Z` must be uppercase, `T` is mandatory, and leap seconds
/// are forbidden. Use a `Chrono` variant to get a compliant timestamp without heap allocation, or
/// supply a pre-formatted string when bridging from an external timestamp source.
///
/// If the system clock is unavailable the RFC requires NILVALUE rather than omitting the field —
/// use [`Timestamp::None`] in that case.
///
/// [spec](https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.3)
pub enum Timestamp<'a> {
    /// Use an existing `DateTime<Local>` — avoids capturing a new timestamp.
    /// Written without heap allocation.
    #[cfg(feature = "chrono")]
    Chrono(&'a ChronoLocalTime),
    /// Capture the current wall-clock time at write time. Written without heap allocation.
    #[cfg(feature = "chrono")]
    CreateChronoLocal,
    /// A pre-formatted RFC 3339 timestamp string.
    ///
    /// Written verbatim without validation — the caller is responsible for producing a
    /// spec-compliant value.
    PreformattedStr(&'a str),
    /// Same as [`Timestamp::PreformattedStr`] but owns the string.
    ///
    /// Written verbatim without validation — the caller is responsible for producing a
    /// spec-compliant value.
    PreformattedString(String),
    /// The system clock is unavailable; NILVALUE will be written.
    None,
}

impl<'a> From<&'a str> for Timestamp<'a> {
    fn from(s: &'a str) -> Self {
        Self::PreformattedStr(s)
    }
}

impl From<String> for Timestamp<'_> {
    fn from(s: String) -> Self {
        Self::PreformattedString(s)
    }
}

#[cfg(feature = "chrono")]
impl<'a> From<&'a ChronoLocalTime> for Timestamp<'a> {
    fn from(datetime: &'a ChronoLocalTime) -> Self {
        Self::Chrono(datetime)
    }
}

/// Prefer an FQDN; fall back to a static IP, short hostname, or dynamic IP in that order.
///
/// [spec](https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.4)
type Hostname = str;

/// Name of the logging application.
///
/// [spec](https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.5)
type AppName = str;

/// Typically a PID; on embedded systems it could be a reboot counter or transaction ID.
///
/// [spec](https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.6)
type ProcId = str;

/// Identifies the type of event, e.g. `"TCPIN"` or `"AUTHFAIL"`.
///
/// [spec](https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.7)
type MsgId = str;

/// The free-form message body.
///
/// [spec](https://datatracker.ietf.org/doc/html/rfc5424#section-6.4)
pub enum Msg<'a> {
    /// UTF-8 string; a BOM is prepended automatically as required by the spec.
    Utf8Str(&'a str),
    /// Owned UTF-8 string; a BOM is prepended automatically as required by the spec.
    Utf8String(String),
    /// Raw bytes for content that is not valid UTF-8.
    ///
    /// No BOM is written. Some receivers may not handle non-UTF-8 content gracefully; prefer the
    /// `Utf8*` variants when possible.
    NonUnicodeBytes(&'a [u8]),
    /// Output of `format_args!`, written directly to avoid the heap allocation that `format!` would
    /// require. The common case when integrating with the `log` crate.
    FmtArguments(fmt::Arguments<'a>),
    /// Borrowed `fmt::Arguments`, for when the value is already behind a reference.
    FmtArgumentsRef(&'a fmt::Arguments<'a>),
}

impl<'a> From<&'a str> for Msg<'a> {
    fn from(s: &'a str) -> Self {
        Self::Utf8Str(s)
    }
}

impl From<String> for Msg<'_> {
    fn from(s: String) -> Self {
        Self::Utf8String(s)
    }
}

impl<'a> From<&'a [u8]> for Msg<'a> {
    fn from(bytes: &'a [u8]) -> Self {
        Self::NonUnicodeBytes(bytes)
    }
}

impl<'a> From<fmt::Arguments<'a>> for Msg<'a> {
    fn from(args: fmt::Arguments<'a>) -> Self {
        Self::FmtArguments(args)
    }
}

impl<'a> From<&'a fmt::Arguments<'a>> for Msg<'a> {
    fn from(args: &'a fmt::Arguments<'a>) -> Self {
        Self::FmtArgumentsRef(args)
    }
}

/// Structured data element identifier.
///
/// Names without `@` are IANA-reserved. To avoid clashing with registered names,
/// application-specific IDs must use the `name@<enterprise-number>` format (e.g. `"myapp@32473"`).
/// Use your own IANA private enterprise number; `32473` is reserved for documentation examples
/// only.
///
/// [spec](https://datatracker.ietf.org/doc/html/rfc5424#section-6.3.2)
type SdId = str;

/// A `(name, value)` parameter pair within an [`SdId`] element.
///
/// PARAM-NAME must be ASCII; PARAM-VALUE must be UTF-8. The characters `"`, `\`, and `]` must be
/// escaped in PARAM-VALUE (`\"`, `\\`, `\]`) so that structured data blocks remain parseable.
///
/// [spec](https://datatracker.ietf.org/doc/html/rfc5424#section-6.3.3)
type SdParam<'a> = (ParamName<'a>, ParamValue<'a>);
type ParamName<'a> = &'a str;
type ParamValue<'a> = &'a str;

/// Encodes facility and severity into the single-byte PRIORITY field.
///
/// Bitwise OR works because the `Facility` repr values are pre-shifted left by 3 bits, leaving the
/// low 3 bits clear for the `Severity` value.
fn encode_priority(severity: Severity, facility: Facility) -> Priority {
    facility as u8 | severity as u8
}

#[cfg(test)]
mod tests {
    use std::io::ErrorKind;

    use assert_matches::assert_matches;

    use super::*;

    #[test]
    #[cfg(feature = "chrono")]
    fn should_format_date_like_chrono() {
        let datetime = chrono::Local::now();
        let use_z = false;
        let chrono_s = datetime.to_rfc3339_opts(chrono::SecondsFormat::Micros, use_z);

        let mut buf = Vec::with_capacity(32);
        write_chrono_datetime(&mut buf, &datetime).unwrap();
        let s = String::from_utf8(buf).unwrap();

        assert_eq!(
            chrono_s, s,
            "syslog-fmt date formatter should be char for char equal to Chrono"
        );
    }

    /// For a negative UTC offset (e.g. UTC-5), the timezone portion of the formatted timestamp was
    /// wrong. `offset_hour` is `-5` (a signed i32), and the sign character is prepended separately,
    /// so `{sign}{offset_hour:02}` produces `"--5"` instead of the correct `"-05"`.
    #[test]
    #[cfg(feature = "chrono")]
    fn bug_negative_timezone_offset_formats_incorrectly() {
        // 2025-01-15T10:30:00-05:00  (local time in UTC-5)
        // UTC equivalent: 2025-01-15T15:30:00Z
        let tz = chrono::FixedOffset::west_opt(5 * 3600).unwrap();
        let naive_utc = chrono::NaiveDate::from_ymd_opt(2025, 1, 15)
            .unwrap()
            .and_hms_opt(15, 30, 0)
            .unwrap();
        let datetime =
            chrono::DateTime::<chrono::FixedOffset>::from_naive_utc_and_offset(naive_utc, tz);

        let mut buf = Vec::new();
        write_chrono_datetime(&mut buf, &datetime).unwrap();
        let actual = String::from_utf8(buf).unwrap();

        // With the bug the offset portion is "--5:00" instead of "-05:00".
        assert_eq!(
            actual, "2025-01-15T10:30:00.000000-05:00",
            "negative timezone offset should format as -05:00, got: {actual:?}"
        );
    }

    #[test]
    #[cfg(feature = "chrono")]
    fn should_write_message_in_sections() {
        let hostname = "mymachine.example.com";
        let app_name = "su";
        let severity = Severity::Crit;
        let msg_id = "ID47";
        let msg = "'su root' failed for lonvick on /dev/pts/8";
        let fmt = Config {
            facility: Facility::Auth,
            hostname: hostname.into(),
            app_name: app_name.into(),
            proc_id: None,
        }
        .into_formatter();
        let mut buf = vec![];

        fmt.write_header(
            &mut buf,
            severity,
            Timestamp::CreateChronoLocal,
            Some(msg_id),
        )
        .unwrap();

        // we are not using any structured data
        write_nil_value(&mut buf).unwrap();
        write_msg(&mut buf, msg).unwrap();

        let parts = parse_syslog_message(&buf);
        assert_matches!(
            parts,
            Parts {
                prio: "<34>1",
                timestamp: _,
                hostname: "mymachine.example.com",
                app_name: "su",
                proc_id: NILVALUE,
                msg_id,
                data: NILVALUE,
                msg
            } if msg_id == msg_id && msg == msg
        );
    }

    #[test]
    #[cfg(feature = "chrono")]
    fn should_write_message_with_custom_formatting() {
        use std::io::Write;

        let hostname = "mymachine.example.com";
        let app_name = "su";
        let severity = Severity::Crit;
        let msg_id = "ID47";
        let fmt = Config {
            facility: Facility::Auth,
            hostname: hostname.into(),
            app_name: app_name.into(),
            proc_id: None,
        }
        .into_formatter();
        let mut buf = vec![];

        fmt.write_header(
            &mut buf,
            severity,
            Timestamp::CreateChronoLocal,
            Some(msg_id),
        )
        .unwrap();

        // we are not using any structured data
        write_nil_value(&mut buf).unwrap();
        write_utf8_bom(&mut buf).unwrap();

        let msg = "'su root' failed for lonvick on /dev/pts/8";
        let module = "app::connection";
        let lineno = "101";
        write!(&mut buf, "{module} l:{lineno} {msg}").unwrap();

        let parts = parse_syslog_message(&buf);
        let comp = format!("{module} l:{lineno} {msg}");
        assert_matches!(
            parts,
            Parts {
                prio: "<34>1",
                timestamp: _,
                hostname: "mymachine.example.com",
                app_name: "su",
                proc_id: NILVALUE,
                msg_id,
                data: NILVALUE,
                msg
            } if msg_id == msg_id && msg == comp
        );
    }

    #[test]
    #[cfg(feature = "chrono")]
    fn should_format_message_without_msg_id() {
        let hostname = "mymachine.example.com";
        let app_name = "su";
        let severity = Severity::Crit;
        let msg = "'su root' failed for lonvick on /dev/pts/8";
        let fmt = Config {
            facility: Facility::Auth,
            hostname: hostname.into(),
            app_name: app_name.into(),
            proc_id: None,
        }
        .into_formatter();
        let mut buf = vec![];
        fmt.write_without_data(&mut buf, severity, Timestamp::CreateChronoLocal, msg, None)
            .unwrap();

        let parts = parse_syslog_message(&buf);

        assert_matches!(
            parts,
            Parts {
                prio: "<34>1",
                timestamp: _,
                hostname,
                app_name,
                proc_id: NILVALUE,
                msg_id: NILVALUE,
                data: NILVALUE,
                msg
            } if hostname == hostname && app_name == app_name && msg == msg
        );
    }

    #[test]
    #[cfg(feature = "chrono")]
    fn should_format_message_with_msg_id() {
        let hostname = "mymachine.example.com";
        let app_name = "su";
        let severity = Severity::Crit;
        let msg_id = "ID47";
        let msg = "'su root' failed for lonvick on /dev/pts/8";
        let fmt = Config {
            facility: Facility::Auth,
            hostname: hostname.into(),
            app_name: app_name.into(),
            proc_id: None,
        }
        .into_formatter();
        let mut buf = vec![];

        fmt.write_without_data(
            &mut buf,
            severity,
            Timestamp::CreateChronoLocal,
            msg,
            Some(msg_id),
        )
        .unwrap();

        let parts = parse_syslog_message(&buf);
        assert_matches!(
            parts,
            Parts {
                prio: "<34>1",
                timestamp: _,
                hostname: "mymachine.example.com",
                app_name: "su",
                proc_id: NILVALUE,
                msg_id,
                data: NILVALUE,
                msg
            } if msg_id == msg_id && msg == msg
        );
    }

    #[test]
    #[cfg(feature = "chrono")]
    fn should_format_message_with_structured_data_and_message() {
        let hostname = "mymachine.example.com";
        let app_name = "evntslog";
        let severity = Severity::Notice;
        let msg_id = "ID47";
        let msg = "An application event log entry...";
        let fmt = Config {
            facility: Facility::Local4,
            hostname: hostname.into(),
            app_name: app_name.into(),
            proc_id: None,
        }
        .into_formatter();
        let mut buf = vec![];

        fmt.write_with_data(
            &mut buf,
            severity,
            Timestamp::CreateChronoLocal,
            msg,
            Some(msg_id),
            vec![(
                "exampleSDID@32473",
                vec![
                    ("iut", "3"),
                    ("eventSource", "Application"),
                    ("eventID", "1011"),
                ],
            )],
        )
        .unwrap();

        let parts = parse_syslog_message(&buf);

        assert_matches!(
            parts,
            Parts {
                prio: "<165>1",
                timestamp: _,
                hostname: "mymachine.example.com",
                app_name: "evntslog",
                proc_id: NILVALUE,
                msg_id,
                data: r#"[exampleSDID@32473 iut="3" eventSource="Application" eventID="1011"]"#,
                msg
            } if hostname == hostname && app_name == app_name && msg_id == msg_id && msg == msg
        );
    }

    #[test]
    #[cfg(feature = "chrono")]
    fn should_format_message_with_structured_data_and_no_message() {
        let hostname = "mymachine.example.com";
        let app_name = "evntslog";
        let severity = Severity::Notice;
        let msg_id = "ID47";
        let msg = "";
        let fmt = Config {
            facility: Facility::Local4,
            hostname: hostname.into(),
            app_name: app_name.into(),
            proc_id: None,
        }
        .into_formatter();
        let mut buf = vec![];

        fmt.write_with_data(
            &mut buf,
            severity,
            Timestamp::CreateChronoLocal,
            msg,
            Some(msg_id),
            vec![(
                "exampleSDID@32473",
                vec![
                    ("iut", "3"),
                    ("eventSource", "Application"),
                    ("eventID", "1011"),
                ],
            )],
        )
        .unwrap();

        let parts = parse_syslog_message(&buf);

        assert_matches!(
            parts,
            Parts {
                prio: "<165>1",
                timestamp: _,
                hostname,
                app_name,
                proc_id: NILVALUE,
                msg_id,
                data: r#"[exampleSDID@32473 iut="3" eventSource="Application" eventID="1011"]"#,
                msg
            } if hostname == hostname && app_name == app_name && msg_id == msg_id && msg == msg
        );
    }

    /// RFC 5424 §6.3.3 requires `"`, `\`, and `]` in PARAM-VALUE to be
    /// escaped as `\"`, `\\`, and `\]` respectively.
    #[test]
    fn should_escape_param_value_special_chars() {
        let mut buf = Vec::new();
        let id: &SdId = "test@12345";
        let params: Vec<SdParam<'_>> = vec![
            ("quote", r#"foo"bar"#),
            ("backslash", r"foo\bar"),
            ("bracket", "foo]bar"),
            ("combined", r#"a"b\c]d"#),
        ];
        write_data_elem(&mut buf, (&id, params)).unwrap();
        let actual = String::from_utf8(buf).unwrap();
        assert_eq!(
            actual,
            r#"[test@12345 quote="foo\"bar" backslash="foo\\bar" bracket="foo\]bar" combined="a\"b\\c\]d"]"#,
        );
    }

    #[test]
    fn should_truncate_message_to_buffer_size() {
        use arrayvec::ArrayVec;

        let timestamp = "1985-04-12T23:20:50.52Z";
        let hostname = "mymachine.example.com";
        let app_name = "su";
        let severity = Severity::Crit;
        let msg = "'su root' failed for lonvick on /dev/pts/8";
        let fmt = Config {
            facility: Facility::Auth,
            hostname: hostname.into(),
            app_name: app_name.into(),
            proc_id: None,
        }
        .into_formatter();
        let mut buf = ArrayVec::<u8, 100>::new();

        let err = fmt
            .write_without_data(&mut buf, severity, timestamp, msg, None)
            .unwrap_err();

        assert_eq!(
            err.kind(),
            ErrorKind::WriteZero,
            "The given buffer is too small for the message. But the formatter should write as much as possible"
        );

        let parts = parse_syslog_message(&buf);

        assert_matches!(
            parts,
            Parts {
                prio: "<34>1",
                timestamp,
                hostname,
                app_name,
                proc_id: NILVALUE,
                msg_id: NILVALUE,
                data: NILVALUE,
                msg: "'su root' failed for lonvick on /dev"
            } if timestamp == timestamp && hostname == hostname && app_name == app_name
        );
    }

    #[test]
    fn should_fmt_structured_data() {
        use arrayvec::ArrayVec;

        let mut buf = ArrayVec::<u8, 100>::new();

        buf.clear();

        write_data::<_, [(&str, [(&str, &str); 0]); 0], _>(&mut buf, []).unwrap();
        assert_eq!(std::str::from_utf8(&buf).unwrap(), " -");

        buf.clear();
        write_data(&mut buf, [("first", [])]).unwrap();
        assert_eq!(std::str::from_utf8(&buf).unwrap(), " [first]");

        buf.clear();
        write_data(&mut buf, [("first", []), ("second", [])]).unwrap();
        assert_eq!(std::str::from_utf8(&buf).unwrap(), " [first][second]");

        buf.clear();
        write_data(&mut buf, [("first", [("p-one", "pv-one")])]).unwrap();
        assert_eq!(
            std::str::from_utf8(&buf).unwrap(),
            r#" [first p-one="pv-one"]"#
        );

        buf.clear();
        write_data(
            &mut buf,
            [("first", [("p-one", "pv-one"), ("p-two", "pv-two")])],
        )
        .unwrap();
        assert_eq!(
            std::str::from_utf8(&buf).unwrap(),
            r#" [first p-one="pv-one" p-two="pv-two"]"#
        );

        buf.clear();
        write_data(
            &mut buf,
            [
                ("first", [("p-one", "pv-one"), ("p-two", "pv-two")]),
                ("second", [("p-one", "pv-one"), ("p-two", "pv-two")]),
            ],
        )
        .unwrap();
        assert_eq!(
            std::str::from_utf8(&buf).unwrap(),
            r#" [first p-one="pv-one" p-two="pv-two"][second p-one="pv-one" p-two="pv-two"]"#
        );
    }

    #[derive(Debug)]
    struct Parts<'a> {
        prio: &'a str,
        timestamp: &'a str,
        hostname: &'a str,
        app_name: &'a str,
        proc_id: &'a str,
        msg_id: &'a str,
        data: &'a str,
        msg: &'a str,
    }

    fn parse_syslog_message(buf: &[u8]) -> Parts<'_> {
        const DELIM: char = ' ';
        const UTF8_BOM: char = '\u{feff}';

        let s = std::str::from_utf8(buf).unwrap();
        let (prio, s) = s.split_once(DELIM).unwrap();
        let (timestamp, s) = s.split_once(DELIM).unwrap();
        let (hostname, s) = s.split_once(DELIM).unwrap();
        let (app_name, s) = s.split_once(DELIM).unwrap();
        let (proc_id, s) = s.split_once(DELIM).unwrap();
        let (msg_id, s) = s.split_once(DELIM).unwrap();

        let (data, msg) = if s.starts_with('[') {
            let index = s.rfind(']').expect("There should be a closing delimiter");
            let (data, s) = s.split_at(index + 1);
            let s = s.trim();

            (data, s.strip_prefix(UTF8_BOM).unwrap_or(s))
        } else {
            let (data, s) = s.split_once(DELIM).unwrap();
            (data, s.strip_prefix(UTF8_BOM).unwrap_or(s))
        };

        Parts {
            prio,
            timestamp,
            hostname,
            app_name,
            proc_id,
            msg_id,
            data,
            msg,
        }
    }

    // See: <https://datatracker.ietf.org/doc/html/rfc5424#section-6.5>
    #[test]
    fn should_parse_example_1_with_no_structured_data() {
        let msg_buf= b"<34>1 2003-10-11T22:14:15.003Z mymachine.example.com su - ID47 - 'su root' failed for lonvick on /dev/pts/8";
        let parts = parse_syslog_message(msg_buf);

        assert_matches!(
            parts,
            Parts {
                prio: "<34>1",
                timestamp: "2003-10-11T22:14:15.003Z",
                hostname: "mymachine.example.com",
                app_name: "su",
                proc_id: NILVALUE,
                msg_id: "ID47",
                data: NILVALUE,
                msg: "'su root' failed for lonvick on /dev/pts/8"
            }
        );
    }

    // See: <https://datatracker.ietf.org/doc/html/rfc5424#section-6.5>
    #[test]
    fn should_parse_example_2_with_no_structured_data() {
        let msg_buf= b"<165>1 2003-08-24T05:14:15.000003-07:00 192.0.2.1 myproc 8710 - - %% It's time to make the do-nuts.";
        let parts = parse_syslog_message(msg_buf);

        assert_matches!(
            parts,
            Parts {
                prio: "<165>1",
                timestamp: "2003-08-24T05:14:15.000003-07:00",
                hostname: "192.0.2.1",
                app_name: "myproc",
                proc_id: "8710",
                msg_id: NILVALUE,
                data: NILVALUE,
                msg: "%% It's time to make the do-nuts."
            }
        );
    }

    // See: <https://datatracker.ietf.org/doc/html/rfc5424#section-6.5>
    #[test]
    fn should_parse_example_3_with_structured_data() {
        let msg_buf= br#"<165>1 2003-10-11T22:14:15.003Z mymachine.example.com evntslog - ID47 [exampleSDID@32473 iut="3" eventSource="Application" eventID="1011"] An application event log entry..."#;
        let parts = parse_syslog_message(msg_buf);

        assert_matches!(
            parts,
            Parts {
                prio: "<165>1",
                timestamp: "2003-10-11T22:14:15.003Z",
                hostname: "mymachine.example.com",
                app_name: "evntslog",
                proc_id: NILVALUE,
                msg_id: "ID47",
                data: r#"[exampleSDID@32473 iut="3" eventSource="Application" eventID="1011"]"#,
                msg: "An application event log entry..."
            }
        );
    }

    // See: <https://datatracker.ietf.org/doc/html/rfc5424#section-6.5>
    #[test]
    fn should_parse_example_4_structured_data_only() {
        let msg_buf= br#"<165>1 2003-10-11T22:14:15.003Z mymachine.example.com evntslog - ID47 [exampleSDID@32473 iut="3" eventSource="Application" eventID="1011"][examplePriority@32473 class="high"]"#;
        let parts = parse_syslog_message(msg_buf);

        assert_matches!(
            parts,
            Parts {
                prio: "<165>1",
                timestamp: "2003-10-11T22:14:15.003Z",
                hostname: "mymachine.example.com",
                app_name: "evntslog",
                proc_id: NILVALUE,
                msg_id: "ID47",
                data: r#"[exampleSDID@32473 iut="3" eventSource="Application" eventID="1011"][examplePriority@32473 class="high"]"#,
                msg: ""
            }
        );
    }
}