whereat 0.1.5

Lightweight error location tracking with small sizeof and no_std support
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
//! Crate metadata for cross-crate error tracing with repository links.
//!
//! This module provides [`AtCrateInfo`] and [`AtCrateInfoBuilder`] for capturing
//! static metadata about crates, enabling clickable links in error traces.
//!
//! ## Link Format
//!
//! By default, links use GitHub's format: `{repo}/blob/{commit}/{path}{file}#L{line}`
//!
//! For other forges, use `.link_format()`:
//! - **GitLab**: `{repo}/-/blob/{commit}/{path}{file}#L{line}`
//! - **Gitea/Forgejo**: `{repo}/src/commit/{commit}/{path}{file}#L{line}`
//! - **Bitbucket**: `{repo}/src/{commit}/{path}{file}#lines-{line}`

use alloc::boxed::Box;
use alloc::string::String;
use alloc::vec::Vec;

// ============================================================================
// AtCrateInfo - Static metadata about a crate for cross-crate tracing
// ============================================================================

/// Static metadata about a crate, used for generating repository links.
///
/// Create using [`AtCrateInfo::builder()`] for a fluent const-compatible API,
/// or use the [`define_at_crate_info!()`](crate::define_at_crate_info!) macro for automatic capture.
///
/// ## Builder Pattern (Recommended)
///
/// ```rust
/// use whereat::AtCrateInfo;
///
/// static INFO: AtCrateInfo = AtCrateInfo::builder()
///     .name("mylib")
///     .repo(Some("https://github.com/org/repo"))
///     .commit(Some("abc123"))
///     .path(Some("crates/mylib/"))
///     .build();
/// ```
///
/// ## With Custom Metadata
///
/// ```rust
/// use whereat::AtCrateInfo;
///
/// static INFO: AtCrateInfo = AtCrateInfo::builder()
///     .name("mylib")
///     .meta(&[("team", "platform"), ("service", "auth")])
///     .build();
/// ```
/// Default link format for GitHub: `{repo}/blob/{commit}/{path}{file}#L{line}`
#[doc(hidden)]
pub const GITHUB_LINK_FORMAT: &str = "{repo}/blob/{commit}/{path}{file}#L{line}";

/// Link format for GitLab: `{repo}/-/blob/{commit}/{path}{file}#L{line}`
#[doc(hidden)]
pub const GITLAB_LINK_FORMAT: &str = "{repo}/-/blob/{commit}/{path}{file}#L{line}";

/// Link format for Gitea/Forgejo: `{repo}/src/commit/{commit}/{path}{file}#L{line}`
#[doc(hidden)]
pub const GITEA_LINK_FORMAT: &str = "{repo}/src/commit/{commit}/{path}{file}#L{line}";

/// Link format for Bitbucket: `{repo}/src/{commit}/{path}{file}#lines-{line}`
#[doc(hidden)]
pub const BITBUCKET_LINK_FORMAT: &str = "{repo}/src/{commit}/{path}{file}#lines-{line}";

#[derive(Debug, Clone, Copy)]
pub struct AtCrateInfo {
    name: &'static str,
    repo: Option<&'static str>,
    commit: Option<&'static str>,
    crate_path: Option<&'static str>,
    module: &'static str,
    meta: &'static [(&'static str, &'static str)],
    /// Link format string with placeholders: `{repo}`, `{commit}`, `{path}`, `{file}`, `{line}`
    link_format: &'static str,
}

impl AtCrateInfo {
    /// Create a builder for constructing AtCrateInfo with a fluent API.
    ///
    /// All builder methods are `const fn`, so you can use this in static contexts.
    ///
    /// ## Example
    ///
    /// ```rust
    /// use whereat::AtCrateInfo;
    ///
    /// static INFO: AtCrateInfo = AtCrateInfo::builder()
    ///     .name(env!("CARGO_PKG_NAME"))
    ///     .repo(option_env!("CARGO_PKG_REPOSITORY"))
    ///     .build();
    /// ```
    pub const fn builder() -> AtCrateInfoBuilder {
        AtCrateInfoBuilder::new()
    }

    /// Crate name (from CARGO_PKG_NAME).
    pub const fn name(&self) -> &'static str {
        self.name
    }

    /// Repository URL (from CARGO_PKG_REPOSITORY).
    pub const fn repo(&self) -> Option<&'static str> {
        self.repo
    }

    /// Git commit hash or tag for generating permalinks.
    pub const fn commit(&self) -> Option<&'static str> {
        self.commit
    }

    /// Path from repository root to crate (e.g., "crates/mylib/").
    pub const fn crate_path(&self) -> Option<&'static str> {
        self.crate_path
    }

    /// Module path where this info was captured.
    pub const fn module(&self) -> &'static str {
        self.module
    }

    /// Custom key-value metadata slice.
    pub const fn meta(&self) -> &'static [(&'static str, &'static str)] {
        self.meta
    }

    /// Link format string for generating repository links.
    ///
    /// Contains placeholders: `{repo}`, `{commit}`, `{path}`, `{file}`, `{line}`
    ///
    /// Default is [`GITHUB_LINK_FORMAT`].
    pub const fn link_format(&self) -> &'static str {
        self.link_format
    }

    /// Look up a custom metadata value by key.
    ///
    /// ## Example
    ///
    /// ```rust
    /// use whereat::AtCrateInfo;
    ///
    /// static INFO: AtCrateInfo = AtCrateInfo::builder()
    ///     .name("mylib")
    ///     .meta(&[("team", "platform")])
    ///     .build();
    ///
    /// assert_eq!(INFO.get_meta("team"), Some("platform"));
    /// assert_eq!(INFO.get_meta("unknown"), None);
    /// ```
    pub const fn get_meta(&self, key: &str) -> Option<&'static str> {
        let mut i = 0;
        while i < self.meta.len() {
            let (k, v) = self.meta[i];
            if const_str_eq(k, key) {
                return Some(v);
            }
            i += 1;
        }
        None
    }
}

/// Const-compatible string equality check.
const fn const_str_eq(a: &str, b: &str) -> bool {
    let a = a.as_bytes();
    let b = b.as_bytes();
    if a.len() != b.len() {
        return false;
    }
    let mut i = 0;
    while i < a.len() {
        if a[i] != b[i] {
            return false;
        }
        i += 1;
    }
    true
}

/// Builder for [`AtCrateInfo`] with a fluent, const-compatible API.
///
/// All methods are `const fn`, enabling use in static/const contexts.
///
/// ## Example
///
/// ```rust
/// use whereat::AtCrateInfo;
///
/// static INFO: AtCrateInfo = AtCrateInfo::builder()
///     .name("mylib")
///     .repo(Some("https://github.com/org/repo"))
///     .commit(option_env!("GIT_COMMIT"))
///     .path(Some("crates/mylib/"))
///     .meta(&[("team", "platform")])
///     .build();
/// ```
#[derive(Debug, Clone, Copy)]
pub struct AtCrateInfoBuilder {
    name: &'static str,
    repo: Option<&'static str>,
    commit: Option<&'static str>,
    crate_path: Option<&'static str>,
    module: &'static str,
    meta: &'static [(&'static str, &'static str)],
    link_format: &'static str,
    link_format_explicit: bool,
}

impl AtCrateInfoBuilder {
    /// Create a new builder with default values.
    pub const fn new() -> Self {
        Self {
            name: "",
            repo: None,
            commit: None,
            crate_path: None,
            module: "",
            meta: &[],
            link_format: GITHUB_LINK_FORMAT,
            link_format_explicit: false,
        }
    }

    /// Set the crate name.
    pub const fn name(mut self, name: &'static str) -> Self {
        self.name = name;
        self
    }

    /// Set the repository URL.
    pub const fn repo(mut self, repo: Option<&'static str>) -> Self {
        self.repo = repo;
        self
    }

    /// Set the git commit hash or version tag.
    pub const fn commit(mut self, commit: Option<&'static str>) -> Self {
        self.commit = commit;
        self
    }

    /// Set the crate path within the repository (for workspace crates).
    pub const fn path(mut self, path: Option<&'static str>) -> Self {
        self.crate_path = path;
        self
    }

    /// Set the module path.
    pub const fn module(mut self, module: &'static str) -> Self {
        self.module = module;
        self
    }

    /// Set custom key-value metadata.
    ///
    /// ## Example
    ///
    /// ```rust
    /// use whereat::AtCrateInfo;
    ///
    /// static INFO: AtCrateInfo = AtCrateInfo::builder()
    ///     .name("mylib")
    ///     .meta(&[
    ///         ("team", "platform"),
    ///         ("service", "auth"),
    ///         ("oncall", "platform-oncall@example.com"),
    ///     ])
    ///     .build();
    /// ```
    pub const fn meta(mut self, meta: &'static [(&'static str, &'static str)]) -> Self {
        self.meta = meta;
        self
    }

    /// Set the link format for repository URLs.
    ///
    /// The format string can contain these placeholders:
    /// - `{repo}` - Repository URL (trailing slash stripped)
    /// - `{commit}` - Git commit hash or tag
    /// - `{path}` - Crate path within repo (e.g., `crates/mylib/`)
    /// - `{file}` - Source file path (e.g., `src/lib.rs`)
    /// - `{line}` - Line number
    ///
    /// ## Predefined formats
    ///
    /// - [`GITHUB_LINK_FORMAT`] (default)
    /// - [`GITLAB_LINK_FORMAT`]
    /// - [`GITEA_LINK_FORMAT`]
    /// - [`BITBUCKET_LINK_FORMAT`]
    ///
    /// ## Example
    ///
    /// ```rust
    /// use whereat::{AtCrateInfo, GITLAB_LINK_FORMAT};
    ///
    /// static INFO: AtCrateInfo = AtCrateInfo::builder()
    ///     .name("mylib")
    ///     .repo(Some("https://gitlab.com/org/repo"))
    ///     .link_format(GITLAB_LINK_FORMAT)
    ///     .build();
    /// ```
    pub const fn link_format(mut self, format: &'static str) -> Self {
        self.link_format = format;
        self.link_format_explicit = true;
        self
    }

    /// Build the final AtCrateInfo.
    ///
    /// If no link format was explicitly set via [`link_format()`](Self::link_format)
    /// or [`link_format_auto()`](Self::link_format_auto), auto-detects the format
    /// from the repository URL (GitHub, GitLab, Gitea/Forgejo, Bitbucket).
    pub const fn build(self) -> AtCrateInfo {
        let link_format = if self.link_format_explicit {
            self.link_format
        } else {
            match self.repo {
                Some(url) => detect_link_format(url),
                None => self.link_format,
            }
        };
        AtCrateInfo {
            name: self.name,
            repo: self.repo,
            commit: self.commit,
            crate_path: self.crate_path,
            module: self.module,
            meta: self.meta,
            link_format,
        }
    }

    // ========================================================================
    // Runtime (owned) variants - these leak strings for 'static lifetime
    // ========================================================================

    /// Set the crate name from an owned string (leaks memory for static lifetime).
    ///
    /// Use for runtime configuration with `OnceLock`.
    #[inline]
    pub fn name_owned(mut self, name: String) -> Self {
        self.name = Box::leak(name.into_boxed_str());
        self
    }

    /// Set the repository URL from an owned string (leaks memory for static lifetime).
    #[inline]
    pub fn repo_owned(mut self, repo: Option<String>) -> Self {
        self.repo = repo.map(|s| {
            let leaked: &'static str = Box::leak(s.into_boxed_str());
            leaked
        });
        self
    }

    /// Set the commit hash from an owned string (leaks memory for static lifetime).
    #[inline]
    pub fn commit_owned(mut self, commit: Option<String>) -> Self {
        self.commit = commit.map(|s| {
            let leaked: &'static str = Box::leak(s.into_boxed_str());
            leaked
        });
        self
    }

    /// Set the crate path from an owned string (leaks memory for static lifetime).
    #[inline]
    pub fn path_owned(mut self, path: Option<String>) -> Self {
        self.crate_path = path.map(|s| {
            let leaked: &'static str = Box::leak(s.into_boxed_str());
            leaked
        });
        self
    }

    /// Set the module path from an owned string (leaks memory for static lifetime).
    #[inline]
    pub fn module_owned(mut self, module: String) -> Self {
        self.module = Box::leak(module.into_boxed_str());
        self
    }

    /// Set custom metadata from owned strings (leaks memory for static lifetime).
    ///
    /// ## Example
    ///
    /// ```rust
    /// use std::sync::OnceLock;
    /// use whereat::AtCrateInfo;
    ///
    /// static CRATE_INFO: OnceLock<AtCrateInfo> = OnceLock::new();
    ///
    /// fn init_crate_info(instance_id: String) {
    ///     CRATE_INFO.get_or_init(|| {
    ///         AtCrateInfo::builder()
    ///             .name("mylib")
    ///             .module("mylib")
    ///             .meta_owned(vec![
    ///                 ("instance".into(), instance_id),
    ///             ])
    ///             .build()
    ///     });
    /// }
    /// ```
    #[inline]
    pub fn meta_owned(mut self, entries: Vec<(String, String)>) -> Self {
        let leaked: &'static [(&'static str, &'static str)] = Box::leak(
            entries
                .into_iter()
                .map(|(k, v)| {
                    let k: &'static str = Box::leak(k.into_boxed_str());
                    let v: &'static str = Box::leak(v.into_boxed_str());
                    (k, v)
                })
                .collect::<Vec<_>>()
                .into_boxed_slice(),
        );
        self.meta = leaked;
        self
    }

    /// Set the link format from an owned string (leaks memory for static lifetime).
    #[inline]
    pub fn link_format_owned(mut self, format: String) -> Self {
        self.link_format = Box::leak(format.into_boxed_str());
        self.link_format_explicit = true;
        self
    }

    /// Auto-detect the link format based on the repository URL.
    ///
    /// This inspects the repo URL set via `.repo()` or `.repo_owned()` and selects
    /// the appropriate format:
    /// - URLs containing `github.com` → [`GITHUB_LINK_FORMAT`]
    /// - URLs containing `gitlab.com` or `gitlab.` → [`GITLAB_LINK_FORMAT`]
    /// - URLs containing `gitea.` or `forgejo.` or `codeberg.org` → [`GITEA_LINK_FORMAT`]
    /// - URLs containing `bitbucket.org` → [`BITBUCKET_LINK_FORMAT`]
    /// - Unknown hosts → [`GITHUB_LINK_FORMAT`] (default)
    ///
    /// ## Example
    ///
    /// ```rust
    /// use whereat::AtCrateInfo;
    ///
    /// // Auto-detects GitLab format from URL
    /// let info = AtCrateInfo::builder()
    ///     .name("mylib")
    ///     .repo(Some("https://gitlab.com/org/repo"))
    ///     .link_format_auto()
    ///     .build();
    /// ```
    #[inline]
    pub const fn link_format_auto(mut self) -> Self {
        self.link_format = match self.repo {
            Some(url) => detect_link_format(url),
            None => GITHUB_LINK_FORMAT,
        };
        self.link_format_explicit = true;
        self
    }
}

/// Case-insensitive const substring search.
const fn contains_ci(haystack: &[u8], needle: &[u8]) -> bool {
    if needle.len() > haystack.len() {
        return false;
    }
    let mut i = 0;
    while i <= haystack.len() - needle.len() {
        let mut j = 0;
        while j < needle.len() {
            let h = if haystack[i + j] >= b'A' && haystack[i + j] <= b'Z' {
                haystack[i + j] + 32
            } else {
                haystack[i + j]
            };
            if h != needle[j] {
                break;
            }
            j += 1;
        }
        if j == needle.len() {
            return true;
        }
        i += 1;
    }
    false
}

/// Detect the appropriate link format based on repository URL.
///
/// Case-insensitive, const-compatible. Used by both `link_format_auto()` and
/// `define_at_crate_info!()` (via the builder's `build()` method).
const fn detect_link_format(repo_url: &str) -> &'static str {
    let url = repo_url.as_bytes();

    if contains_ci(url, b"github.com") || contains_ci(url, b"github.") {
        GITHUB_LINK_FORMAT
    } else if contains_ci(url, b"gitlab.com") || contains_ci(url, b"gitlab.") {
        GITLAB_LINK_FORMAT
    } else if contains_ci(url, b"gitea.")
        || contains_ci(url, b"forgejo.")
        || contains_ci(url, b"codeberg.org")
    {
        GITEA_LINK_FORMAT
    } else if contains_ci(url, b"bitbucket.org") || contains_ci(url, b"bitbucket.") {
        BITBUCKET_LINK_FORMAT
    } else {
        GITHUB_LINK_FORMAT
    }
}

impl Default for AtCrateInfoBuilder {
    fn default() -> Self {
        Self::new()
    }
}