1use anyhow::{Context, Result};
2use bincode::config::standard;
3use bincode::{Decode, Encode, decode_from_slice, encode_to_vec};
4use fs2::FileExt;
5use std::collections::HashMap;
6use std::fs::{self, OpenOptions};
7use std::io::{Read, Seek, SeekFrom, Write};
8use std::path::{Path, PathBuf};
9
10type IndexType = u32;
11
12#[cfg(feature = "macro_debug")]
13const COLORED_PREFIX_BUILD_LOG: &str = "\x1b[32mCLog:\x1b[0m";
14
15#[cfg(feature = "macro_debug")]
16macro_rules! build_log {
17 ($($arg:tt)*) => {
18 eprintln!("{} {}", COLORED_PREFIX_BUILD_LOG, format!($($arg)*));
19 };
20}
21
22const INDEX_DIR_NAME: &str = "cu29_log_index";
24const DB_FILE_NAME: &str = "strings.bin";
25
26#[derive(Encode, Decode, Default)]
27struct InternDb {
28 next_index: IndexType,
29 strings: Vec<String>,
30 string_to_index: HashMap<String, IndexType>,
31}
32
33impl InternDb {
34 fn new() -> Self {
35 Self {
36 next_index: 1, ..Default::default()
38 }
39 }
40}
41
42fn log_index_dir(out_dir: &Path) -> PathBuf {
43 let legacy_root = out_dir.ancestors().nth(3).expect("invalid LOG_INDEX_DIR");
44 let split_layout = legacy_root.ends_with("build")
46 && out_dir.ends_with("out")
47 && out_dir
48 .parent()
49 .and_then(Path::file_name)
50 .and_then(|name| name.to_str())
51 .is_some_and(|name| name.bytes().all(|b| b.is_ascii_hexdigit()));
52 let profile = if split_layout {
53 legacy_root
54 .parent()
55 .expect("missing Cargo profile directory")
56 } else {
57 legacy_root
58 };
59 profile.join(INDEX_DIR_NAME)
60}
61
62pub fn default_log_index_dir() -> PathBuf {
64 let outdir = std::env::var_os("LOG_INDEX_DIR").expect("no LOG_INDEX_DIR system variable set, be sure build.rs sets it, see cu29_log/build.rs for example.");
65 log_index_dir(Path::new(&outdir))
66}
67
68fn database_path(base: &Path) -> PathBuf {
69 match base.extension() {
70 Some(_) => base.to_path_buf(),
71 None => base.join(DB_FILE_NAME),
72 }
73}
74
75pub fn read_interned_strings(index: &Path) -> Result<Vec<String>> {
78 let db_path = database_path(index);
79 let db =
80 load_db_shared(&db_path).context("Could not open the string index. Check the path.")?;
81 Ok(db.strings)
82}
83
84pub fn intern_string(s: &str) -> Option<IndexType> {
85 let base_dir = default_log_index_dir();
86 let db_path = database_path(&base_dir);
87 if let Some(parent) = db_path.parent() {
88 fs::create_dir_all(parent).ok()?;
89 }
90
91 #[cfg(feature = "macro_debug")]
92 log_db_info_once(&db_path);
93
94 let mut file = OpenOptions::new()
95 .read(true)
96 .write(true)
97 .create(true)
98 .truncate(false)
99 .open(&db_path)
100 .ok()?;
101 file.lock_exclusive().ok()?;
102
103 let mut buf = Vec::new();
104 file.read_to_end(&mut buf).ok()?;
105 file.seek(SeekFrom::Start(0)).ok()?;
106
107 let mut db = if buf.is_empty() {
108 InternDb::new()
109 } else {
110 decode_from_slice(&buf, standard()).ok()?.0
111 };
112
113 if let Some(&idx) = db.string_to_index.get(s) {
114 #[cfg(feature = "macro_debug")]
115 {
116 build_log!("#{:0>3} [r] -> {}.", idx, s);
117 }
118 return Some(idx);
119 }
120
121 let idx = db.next_index;
122 let idx_usize = idx as usize;
123 if db.strings.len() <= idx_usize {
124 db.strings.resize(idx_usize + 1, String::new());
125 }
126 db.strings[idx_usize] = s.to_string();
127 db.string_to_index.insert(s.to_string(), idx);
128 db.next_index = db.next_index.checked_add(1)?;
129
130 let encoded = encode_to_vec(&db, standard()).ok()?;
131 file.set_len(0).ok()?;
132 file.write_all(&encoded).ok()?;
133 file.flush().ok()?;
134 let _ = file.unlock();
135
136 #[cfg(feature = "macro_debug")]
137 {
138 build_log!("#{:0>3} [n] -> {}.", idx, s);
139 }
140
141 Some(idx)
142}
143
144#[cfg(feature = "macro_debug")]
145fn log_db_info_once(db_path: &Path) {
146 use std::sync::OnceLock;
147 static ONCE: OnceLock<()> = OnceLock::new();
148 ONCE.get_or_init(|| {
149 build_log!(
150 "=================================================================================="
151 );
152 build_log!("Interned strings are stored in: {:?}", db_path);
153 build_log!(" [r] is reused index and [n] is new index.");
154 build_log!(
155 "=================================================================================="
156 );
157 });
158}
159
160fn load_db_shared(path: &Path) -> std::result::Result<InternDb, anyhow::Error> {
161 let mut file = match OpenOptions::new().read(true).open(path) {
162 Ok(f) => f,
163 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(InternDb::new()),
164 Err(e) => return Err(e).context("Failed to open index file"),
165 };
166 file.lock_shared()
167 .context("Failed to lock index for read")?;
168
169 let mut buf = Vec::new();
170 file.read_to_end(&mut buf)
171 .context("Failed to read index file")?;
172 let _ = file.unlock();
173
174 if buf.is_empty() {
175 return Ok(InternDb::new());
176 }
177
178 let (db, _): (InternDb, _) =
179 decode_from_slice(&buf, standard()).context("Failed to decode index")?;
180 Ok(db)
181}
182
183#[allow(dead_code)]
184pub fn record_callsite(filename: &str, line_number: u32) -> Option<IndexType> {
185 intern_string(format!("{filename}:{line_number}").as_str())
186}
187
188#[cfg(test)]
189mod layout_tests {
190 use super::*;
191
192 #[test]
193 fn log_index_is_shared_at_profile_level() {
194 for profile in ["target/debug", "custom/thumbv8m/release", "target/build"] {
195 let profile = Path::new(profile);
196 for suffix in [
197 "build/my-app-a1b2/out",
198 "build/my-app/a1b2/out",
199 "build/build/a1b2/out",
200 ] {
201 assert_eq!(
202 log_index_dir(&profile.join(suffix)),
203 profile.join(INDEX_DIR_NAME)
204 );
205 }
206 }
207 }
208}