ticklog 0.1.2

A fast, minimal logging library for Rust, designed for performance-critical applications, e.g. high-frequency trading.
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
//! The on-the-wire log record format.
//!
//! Layout constants are shared by the producer (which assembles records here)
//! and the drain (which decodes them), so the two sides cannot drift. The
//! record is a fixed 16-byte header followed by flagged sections:
//!
//! ```text
//! header:  version u8 | type u8 | total_size u16 | level u8 | flags u16 | pad u8 | timestamp u64
//! format:  fmt_ptr u64 | fmt_len u16                          (FLAG_FORMAT)
//! source:  file_ptr u64 | file_len u16 | line u32             (FLAG_SOURCE)
//! thread:  thread_id u64 | name_len u16 | name bytes          (FLAG_THREAD)
//! args:    count u8 | tag u8 * count | payload bytes * count
//! ```
//!
//! The format and source strings are `&'static str` referenced by pointer, not
//! copied, so they cost nothing on the hot path and are read directly from the
//! binary's read-only data by the drain.

use crate::level::Level;
use core::mem::size_of;

/// Record format version written in byte 0 of every header.
pub(crate) const VERSION: u8 = 0x01;
/// Record type: a normal encoded log record.
pub(crate) const LOG_RECORD: u8 = 1;
/// Record type: filler written before a ring wrap so no record straddles the
/// physical end of the buffer.
pub(crate) const END_OF_BUFFER: u8 = 2;

/// Fixed record header size in bytes: version, type, total_size, level, flags,
/// pad, timestamp. Summed from field widths so it tracks the layout above.
pub(crate) const HEADER_SIZE: usize = size_of::<u8>()  // version
    + size_of::<u8>()   // type
    + size_of::<u16>()  // total_size
    + size_of::<u8>()   // level
    + size_of::<u16>()  // flags
    + size_of::<u8>()   // _pad
    + size_of::<u64>(); // timestamp
/// Encoded size of the format section: an 8-byte pointer and a 2-byte length.
pub(crate) const FORMAT_SECTION_SIZE: usize = size_of::<u64>()  // fmt_ptr
    + size_of::<u16>(); // fmt_len
/// Encoded size of the source section: an 8-byte pointer, a 2-byte length, and
/// a 4-byte line number.
pub(crate) const SOURCE_SECTION_SIZE: usize = size_of::<u64>()  // file_ptr
    + size_of::<u16>()  // file_len
    + size_of::<u32>(); // line
/// Size of the argument count byte that precedes the tags and payloads.
pub(crate) const COUNT_SIZE: usize = size_of::<u8>();
/// Encoded size of the thread section without the name bytes:
/// an 8-byte thread id and a 2-byte name length prefix.
pub(crate) const THREAD_SECTION_BASE_SIZE: usize = size_of::<u64>()  // thread_id
    + size_of::<u16>(); // name_len

/// Total size of a record's fixed sections, before any arguments: header,
/// format, source, thread, and the count byte. The logging macros hardcode this
/// base (they expand in the caller's crate and cannot read this const); a
/// compile-time assertion in `macros` guards the two against drift.
pub const BASE_RECORD_SIZE: usize =
    HEADER_SIZE + FORMAT_SECTION_SIZE + SOURCE_SECTION_SIZE + COUNT_SIZE;

/// Flag bit: the format-string section is present.
pub(crate) const FLAG_FORMAT: u16 = 0x01;
/// Flag bit: the source-location section is present.
pub(crate) const FLAG_SOURCE: u16 = 0x02;
/// Flag bit: the thread section is present.
pub(crate) const FLAG_THREAD: u16 = 0x04;
/// Flag bit: the process section is present.
pub(crate) const FLAG_PROCESS: u16 = 0x08;
/// Flag bit: the complex-type section is present.
pub(crate) const FLAG_COMPLEX: u16 = 0x10;

/// Largest record the u16 `total_size` header field can frame. A record that
/// would encode larger than this is dropped rather than truncated.
pub(crate) const MAX_RECORD_SIZE: usize = u16::MAX as usize;

/// Assembles a record by writing the fixed sections (header, format, source)
/// into `dst`, then delegating argument encoding to the caller's
/// monomorphized closure.
///
/// The closure receives a mutable slice starting right after the count byte,
/// sized to fit exactly `args_bytes + n_args` bytes (tags + payloads). It is
/// monomorphized per unique argument-type signature, so `Loggable::type_tag()`
/// and `Loggable::encode()` calls inside it resolve to concrete impls with no
/// vtable dispatch.
///
/// # Safety
///
/// `dst` must point to a writable region of at least `total_size` bytes. The
/// caller must guarantee that `write_args` writes exactly `n_args` tag bytes
/// followed by `args_bytes` payload bytes.
// The record fields (header, source location, arg count/size, and the arg-
// writing closure) are genuinely distinct inputs to this monomorphized hot-path
// assembler; bundling them into a struct would add indirection at the single
// call site without making anything clearer.
#[allow(clippy::too_many_arguments)]
#[inline]
pub(crate) fn assemble(
    dst: *mut u8,
    level: Level,
    timestamp: u64,
    flags: u16,
    fmt: &'static str,
    file: &'static str,
    line: u32,
    thread_id: u64,
    thread_name: &str,
    n_args: u8,
    total_size: usize,
    write_args: impl FnOnce(&mut [u8]),
) {
    let total = total_size as u16;
    let level_u8 = level.to_u8();

    debug_assert!(total_size <= MAX_RECORD_SIZE);
    debug_assert!(fmt.len() <= u16::MAX as usize);
    debug_assert!(file.len() <= u16::MAX as usize);

    // SAFETY: The caller guarantees `dst` points to `total_size` writable
    // bytes. Every one of those bytes is written by the `put!`
    // header/section stores and the caller's `write_args` closure, so no
    // uninitialized byte is ever read. The caller's documented contract
    // guarantees `write_args` fills exactly the tags + payloads region.
    unsafe {
        let buf = std::slice::from_raw_parts_mut(dst, total_size);
        let mut pos = 0usize;

        // Writes `$bytes` (a little-endian `[u8; N]`) at `pos` and advances by
        // its own length, so field widths come from the encoding, never a literal.
        macro_rules! put {
            ($bytes:expr) => {{
                let b = $bytes;
                buf[pos..pos + b.len()].copy_from_slice(&b);
                pos += b.len();
            }};
        }

        // Header
        put!([VERSION]);
        put!([LOG_RECORD]);
        put!(total.to_le_bytes());
        put!([level_u8]);
        put!(flags.to_le_bytes());
        put!([0u8]); // _pad
        put!(timestamp.to_le_bytes());

        // Format section
        if flags & FLAG_FORMAT != 0 {
            put!((fmt.as_ptr() as u64).to_le_bytes());
            put!((fmt.len() as u16).to_le_bytes());
        }

        // Source section
        if flags & FLAG_SOURCE != 0 {
            put!((file.as_ptr() as u64).to_le_bytes());
            put!((file.len() as u16).to_le_bytes());
            put!(line.to_le_bytes());
        }

        // Thread section
        if flags & FLAG_THREAD != 0 {
            put!(thread_id.to_le_bytes());
            let name_bytes = thread_name.as_bytes();
            put!((name_bytes.len() as u16).to_le_bytes());
            put!(name_bytes);
        }

        // Count byte
        put!([n_args]);

        // Delegate to the monomorphized closure for tags + payloads.
        write_args(&mut buf[pos..]);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::encode::Loggable;

    /// Test helper: wraps [`assemble`] with a `&[&dyn Loggable]` slice for
    /// convenience.  Computes sizes from the slice and delegates to the
    /// real (monomorphized) `assemble` via a closure.
    #[allow(clippy::too_many_arguments)]
    fn check_assemble(
        scratch: &mut Vec<u8>,
        level: Level,
        timestamp: u64,
        fmt: &'static str,
        file: &'static str,
        line: u32,
        thread_id: u64,
        thread_name: &str,
        args: &[&dyn Loggable],
    ) -> bool {
        if args.len() > u8::MAX as usize {
            return false;
        }
        if fmt.len() > u16::MAX as usize || file.len() > u16::MAX as usize {
            return false;
        }

        let mut args_bytes = 0usize;
        for arg in args {
            args_bytes += arg.encoded_size();
        }
        let thread_name_len = thread_name.len();
        let flags = FLAG_FORMAT | FLAG_SOURCE | FLAG_THREAD;
        let total_size = HEADER_SIZE
            + FORMAT_SECTION_SIZE
            + SOURCE_SECTION_SIZE
            + THREAD_SECTION_BASE_SIZE
            + thread_name_len
            + COUNT_SIZE
            + args.len()
            + args_bytes;
        if total_size > MAX_RECORD_SIZE {
            return false;
        }

        let n_args = args.len() as u8;
        scratch.clear();
        scratch.reserve(total_size);
        assemble(
            scratch.as_mut_ptr(),
            level,
            timestamp,
            flags,
            fmt,
            file,
            line,
            thread_id,
            thread_name,
            n_args,
            total_size,
            |buf| {
                let mut pos = 0usize;
                for arg in args {
                    buf[pos] = arg.type_tag();
                    pos += 1;
                }
                for arg in args {
                    let s = arg.encoded_size();
                    arg.encode(&mut buf[pos..pos + s]);
                    pos += s;
                }
            },
        );
        // SAFETY: `assemble` wrote exactly `total_size` bytes into the
        // Vec's allocation (reserved above); the region is initialized
        // and the Vec's capacity is sufficient.
        unsafe { scratch.set_len(total_size) };
        true
    }

    // Reads a little-endian u16 at `offset`.
    fn read_u16(bytes: &[u8], offset: usize) -> u16 {
        u16::from_le_bytes(bytes[offset..offset + 2].try_into().unwrap())
    }

    // Reads a little-endian u32 at `offset`.
    fn read_u32(bytes: &[u8], offset: usize) -> u32 {
        u32::from_le_bytes(bytes[offset..offset + 4].try_into().unwrap())
    }

    // Reads a little-endian u64 at `offset`.
    fn read_u64(bytes: &[u8], offset: usize) -> u64 {
        u64::from_le_bytes(bytes[offset..offset + 8].try_into().unwrap())
    }

    #[test]
    fn header_fields_are_written() {
        let mut buf = Vec::new();
        let ok = check_assemble(&mut buf, Level::Warn, 0xABCD, "hi", "f.rs", 7, 1, "", &[]);
        assert!(ok);

        assert_eq!(buf[0], VERSION);
        assert_eq!(buf[1], LOG_RECORD);
        assert_eq!(read_u16(&buf, 2) as usize, buf.len());
        assert_eq!(buf[4], Level::Warn.to_u8());
        assert_eq!(read_u16(&buf, 5), FLAG_FORMAT | FLAG_SOURCE | FLAG_THREAD);
        assert_eq!(buf[7], 0);
        assert_eq!(read_u64(&buf, 8), 0xABCD);
    }

    #[test]
    fn format_and_source_sections_reference_the_static_strs() {
        let fmt = "value {}";
        let file = "src/x.rs";
        let mut buf = Vec::new();
        check_assemble(&mut buf, Level::Info, 0, fmt, file, 42, 1, "", &[&1u64]);

        // Format section starts right after the header.
        let fmt_ptr = read_u64(&buf, HEADER_SIZE);
        let fmt_len = read_u16(&buf, HEADER_SIZE + 8);
        assert_eq!(fmt_ptr, fmt.as_ptr() as u64);
        assert_eq!(fmt_len as usize, fmt.len());

        // Source section follows the 10-byte format section.
        let src = HEADER_SIZE + FORMAT_SECTION_SIZE;
        assert_eq!(read_u64(&buf, src), file.as_ptr() as u64);
        assert_eq!(read_u16(&buf, src + 8) as usize, file.len());
        assert_eq!(read_u32(&buf, src + 10), 42);
    }

    #[test]
    fn arguments_are_tag_grouped_then_payload_grouped() {
        let mut buf = Vec::new();
        // Two args: u16 (tag 0x06, 2 bytes) then bool (tag 0x0A, 1 byte).
        check_assemble(
            &mut buf,
            Level::Info,
            0,
            "{} {}",
            "f",
            1,
            1,
            "",
            &[&0x1234u16, &true],
        );

        let args_at =
            HEADER_SIZE + FORMAT_SECTION_SIZE + SOURCE_SECTION_SIZE + THREAD_SECTION_BASE_SIZE;
        assert_eq!(buf[args_at], 2); // count
        assert_eq!(buf[args_at + 1], 0x06); // u16 tag
        assert_eq!(buf[args_at + 2], 0x0A); // bool tag
        // Payloads follow the two tags.
        assert_eq!(read_u16(&buf, args_at + 3), 0x1234);
        assert_eq!(buf[args_at + 5], 1); // bool true
    }

    #[test]
    fn total_size_matches_buffer_length() {
        let mut buf = Vec::new();
        check_assemble(&mut buf, Level::Error, 0, "{}", "f", 1, 1, "", &[&"hello"]);
        assert_eq!(read_u16(&buf, 2) as usize, buf.len());
    }

    #[test]
    fn rejects_more_than_255_arguments() {
        let args: Vec<&dyn Loggable> = (0..256).map(|_| &1u8 as &dyn Loggable).collect();
        let mut buf = Vec::new();
        assert!(!check_assemble(
            &mut buf,
            Level::Info,
            0,
            "x",
            "f",
            1,
            1,
            "",
            &args
        ));
    }

    #[test]
    fn rejects_record_larger_than_u16_total_size() {
        // A string argument just large enough to push total_size past u16::MAX.
        let big = "x".repeat(u16::MAX as usize);
        let mut buf = Vec::new();
        assert!(!check_assemble(
            &mut buf,
            Level::Info,
            0,
            "{}",
            "f",
            1,
            1,
            "",
            &[&big.as_str()]
        ));
    }

    #[test]
    fn flags_control_section_emission() {
        // When FLAG_SOURCE and FLAG_THREAD are not set, their sections
        // must be absent from the encoded record. The count byte should
        // appear immediately after the format section.
        let mut buf = Vec::new();
        let flags = FLAG_FORMAT;
        let total_size = HEADER_SIZE + FORMAT_SECTION_SIZE + COUNT_SIZE;

        buf.reserve(total_size);
        assemble(
            buf.as_mut_ptr(),
            Level::Info,
            0,
            flags,
            "fmt",
            "f.rs",
            1,
            1,
            "main",
            0, // n_args
            total_size,
            |_buf| { /* no args */ },
        );
        // SAFETY: assemble writes exactly total_size bytes.
        unsafe { buf.set_len(total_size) };

        // Flags in header must only have FLAG_FORMAT.
        assert_eq!(read_u16(&buf, 5), FLAG_FORMAT);

        // Count byte must be right after the format section, no source
        // or thread bytes in between.
        let count_at = HEADER_SIZE + FORMAT_SECTION_SIZE;
        assert_eq!(buf[count_at], 0); // n_args = 0
        assert_eq!(buf.len(), count_at + 1);
    }

    #[test]
    fn zero_args_writes_count_zero() {
        let mut buf = Vec::new();
        check_assemble(&mut buf, Level::Info, 0, "static", "f", 1, 1, "", &[]);
        let args_at =
            HEADER_SIZE + FORMAT_SECTION_SIZE + SOURCE_SECTION_SIZE + THREAD_SECTION_BASE_SIZE;
        assert_eq!(buf[args_at], 0);
        assert_eq!(buf.len(), args_at + 1);
    }
}