Skip to content

Commit d4e918a

Browse files
committed
Write line number without allocation
1 parent 5ceaae2 commit d4e918a

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

glib/src/bridged_logging.rs

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -141,19 +141,28 @@ impl GlibLogger {
141141
func: Option<&str>,
142142
message: &str,
143143
) {
144-
let line = line.map(|l| l.to_string());
145-
let line = line.as_deref();
144+
// Write line number into a static array to avoid allocating its string
145+
// represntation. 16 bytes allow 10^15 lines, which should be more than
146+
// sufficient.
147+
let mut line_buffer = [0u8; 16];
148+
let line = {
149+
use std::io::{Cursor, Write};
150+
let mut c = Cursor::new(line_buffer.as_mut_slice());
151+
match line {
152+
Some(lineno) => write!(&mut c, "{lineno}").ok(),
153+
None => write!(&mut c, "<unknown line>").ok(),
154+
};
155+
let pos = c.position() as usize;
156+
&line_buffer[..pos]
157+
};
146158
let glib_level = GlibLogger::level_to_glib(level);
147159
let fields = [
148160
LogField::new(gstr!("PRIORITY"), glib_level.priority().as_bytes()),
149161
LogField::new(
150162
gstr!("CODE_FILE"),
151163
file.unwrap_or("<unknown file>").as_bytes(),
152164
),
153-
LogField::new(
154-
gstr!("CODE_LINE"),
155-
line.unwrap_or("<unknown line>").as_bytes(),
156-
),
165+
LogField::new(gstr!("CODE_LINE"), line),
157166
LogField::new(
158167
gstr!("CODE_FUNC"),
159168
func.unwrap_or("<unknown module path>").as_bytes(),

0 commit comments

Comments
 (0)