Skip to main content

mago_codex/
lib.rs

1#![allow(clippy::wildcard_imports)]
2#![allow(clippy::exhaustive_enums)]
3#![allow(clippy::float_arithmetic)]
4#![allow(clippy::pub_use)]
5#![allow(clippy::else_if_without_else)]
6#![allow(clippy::match_wildcard_for_single_variants)]
7
8use mago_atom::Atom;
9use mago_atom::atom;
10use mago_span::Span;
11
12pub mod assertion;
13pub mod consts;
14pub mod context;
15pub mod diff;
16pub mod differ;
17pub mod flags;
18pub mod identifier;
19pub mod issue;
20pub mod metadata;
21pub mod misc;
22pub mod populator;
23pub mod reference;
24pub mod scanner;
25pub mod signature;
26pub mod signature_builder;
27pub mod symbol;
28pub mod ttype;
29pub mod visibility;
30
31mod utils;
32
33#[must_use]
34pub fn get_anonymous_class_name(span: Span) -> Atom {
35    use std::io::Write;
36
37    // A 64-byte buffer on the stack. This is ample space for the prefix,
38    // u64 file id, and 2 u32 integers, preventing any chance of a heap allocation.
39    let mut buffer = [0u8; 64];
40
41    // Use a block to limit the scope of the mutable writer
42    // `writer` is a mutable slice that implements `std::io::Write`.
43    let mut writer = &mut buffer[..];
44
45    // SAFETY: We use `unwrap_unchecked` here because we are writing to a fixed-size buffer
46    unsafe {
47        write!(writer, "class@anonymous:{}-{}:{}", span.file_id, span.start.offset, span.end.offset).unwrap_unchecked();
48    };
49
50    // Determine how many bytes were written by checking the length of the original buffer
51    // against what the `writer` had left. This is a common pattern for `io::Write` on slices.
52    let written_len = buffer.iter().position(|&b| b == 0).unwrap_or(buffer.len());
53
54    atom(
55        // SAFETY: We use `unwrap_unchecked` here because we are certain the bytes
56        // up to `written_len` are valid UTF-8.
57        unsafe { std::str::from_utf8(&buffer[..written_len]).unwrap_unchecked() },
58    )
59}