Skip to content

Commit b0f810f

Browse files
committed
Refactor FmtExtraInfo with FormatterContext
1 parent b5dc872 commit b0f810f

File tree

18 files changed

+159
-135
lines changed

18 files changed

+159
-135
lines changed

spdlog/benches/spdlog-rs/pattern.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use paste::paste;
88
#[cfg(feature = "serde_json")]
99
use spdlog::formatter::JsonFormatter;
1010
use spdlog::{
11-
formatter::{pattern, Formatter, FullFormatter, Pattern, PatternFormatter},
11+
formatter::{pattern, Formatter, FormatterContext, FullFormatter, Pattern, PatternFormatter},
1212
prelude::*,
1313
sink::Sink,
1414
Record, StringBuf,
@@ -22,17 +22,18 @@ include!(concat!(
2222
));
2323
use test_utils::*;
2424

25-
#[derive(Clone)]
2625
struct BenchSink<F> {
2726
formatter: F,
2827
buffer: RefCell<StringBuf>,
28+
ctx: RefCell<FormatterContext>,
2929
}
3030

3131
impl<F: Formatter> BenchSink<F> {
3232
fn new(formatter: F) -> Self {
3333
Self {
3434
formatter,
3535
buffer: RefCell::new(StringBuf::with_capacity(512)),
36+
ctx: RefCell::new(FormatterContext::new()),
3637
}
3738
}
3839
}
@@ -43,8 +44,11 @@ unsafe impl<F> Sync for BenchSink<F> {}
4344

4445
impl<F: Formatter> Sink for BenchSink<F> {
4546
fn log(&self, record: &Record) -> spdlog::Result<()> {
46-
self.formatter
47-
.format(record, &mut self.buffer.borrow_mut())?;
47+
self.formatter.format(
48+
record,
49+
&mut self.buffer.borrow_mut(),
50+
&mut self.ctx.borrow_mut(),
51+
)?;
4852
Ok(())
4953
}
5054

spdlog/examples/04_format.rs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ fn impl_manually() {
3434
use std::fmt::Write;
3535

3636
use spdlog::{
37-
formatter::{FmtExtraInfo, Formatter},
37+
formatter::{Formatter, FormatterContext},
3838
prelude::*,
3939
Record, StringBuf,
4040
};
@@ -43,7 +43,12 @@ fn impl_manually() {
4343
struct MyFormatter;
4444

4545
impl Formatter for MyFormatter {
46-
fn format(&self, record: &Record, dest: &mut StringBuf) -> spdlog::Result<FmtExtraInfo> {
46+
fn format(
47+
&self,
48+
record: &Record,
49+
dest: &mut StringBuf,
50+
ctx: &mut FormatterContext,
51+
) -> spdlog::Result<()> {
4752
let style_range_begin = dest.len();
4853

4954
dest.write_str(&record.level().as_str().to_ascii_uppercase())
@@ -53,9 +58,8 @@ fn impl_manually() {
5358

5459
writeln!(dest, " {}", record.payload()).map_err(spdlog::Error::FormatRecord)?;
5560

56-
Ok(FmtExtraInfo::builder()
57-
.style_range(style_range_begin..style_range_end)
58-
.build())
61+
ctx.set_style_range(Some(style_range_begin..style_range_end));
62+
Ok(())
5963
}
6064
}
6165

spdlog/examples/05_sink.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use std::sync::Arc;
22

33
use atomic::{Atomic, Ordering};
44
use spdlog::{
5-
formatter::{Formatter, FullFormatter},
5+
formatter::{Formatter, FormatterContext, FullFormatter},
66
prelude::*,
77
sink::Sink,
88
ErrorHandler, Record, StringBuf,
@@ -34,7 +34,10 @@ impl CollectVecSink {
3434
impl Sink for CollectVecSink {
3535
fn log(&self, record: &Record) -> spdlog::Result<()> {
3636
let mut string_buf = StringBuf::new();
37-
self.formatter.read().format(record, &mut string_buf)?;
37+
let mut ctx = FormatterContext::new();
38+
self.formatter
39+
.read()
40+
.format(record, &mut string_buf, &mut ctx)?;
3841
self.collected.lock().push(string_buf.to_string());
3942
Ok(())
4043
}

spdlog/src/formatter/full_formatter.rs

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use std::fmt::{self, Write};
55
use cfg_if::cfg_if;
66

77
use crate::{
8-
formatter::{FmtExtraInfo, Formatter, LOCAL_TIME_CACHER},
8+
formatter::{Formatter, FormatterContext, LOCAL_TIME_CACHER},
99
Error, Record, StringBuf, __EOL,
1010
};
1111

@@ -54,7 +54,8 @@ impl FullFormatter {
5454
&self,
5555
record: &Record,
5656
dest: &mut StringBuf,
57-
) -> Result<FmtExtraInfo, fmt::Error> {
57+
ctx: &mut FormatterContext,
58+
) -> Result<(), fmt::Error> {
5859
cfg_if! {
5960
if #[cfg(not(feature = "flexible-string"))] {
6061
dest.reserve(crate::string_buf::RESERVE_SIZE);
@@ -98,15 +99,20 @@ impl FullFormatter {
9899
dest.write_str(__EOL)?;
99100
}
100101

101-
Ok(FmtExtraInfo {
102-
style_range: Some(style_range_begin..style_range_end),
103-
})
102+
ctx.set_style_range(Some(style_range_begin..style_range_end));
103+
Ok(())
104104
}
105105
}
106106

107107
impl Formatter for FullFormatter {
108-
fn format(&self, record: &Record, dest: &mut StringBuf) -> crate::Result<FmtExtraInfo> {
109-
self.format_impl(record, dest).map_err(Error::FormatRecord)
108+
fn format(
109+
&self,
110+
record: &Record,
111+
dest: &mut StringBuf,
112+
ctx: &mut FormatterContext,
113+
) -> crate::Result<()> {
114+
self.format_impl(record, dest, ctx)
115+
.map_err(Error::FormatRecord)
110116
}
111117
}
112118

@@ -127,7 +133,10 @@ mod tests {
127133
fn format() {
128134
let record = Record::new(Level::Warn, "test log content");
129135
let mut buf = StringBuf::new();
130-
let extra_info = FullFormatter::new().format(&record, &mut buf).unwrap();
136+
let mut ctx = FormatterContext::new();
137+
FullFormatter::new()
138+
.format(&record, &mut buf, &mut ctx)
139+
.unwrap();
131140

132141
let local_time: DateTime<Local> = record.time().into();
133142
assert_eq!(
@@ -138,6 +147,6 @@ mod tests {
138147
),
139148
buf
140149
);
141-
assert_eq!(Some(27..31), extra_info.style_range());
150+
assert_eq!(Some(27..31), ctx.style_range());
142151
}
143152
}

spdlog/src/formatter/journald_formatter.rs

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use std::fmt::{self, Write};
88
use cfg_if::cfg_if;
99

1010
use crate::{
11-
formatter::{FmtExtraInfo, Formatter},
11+
formatter::{Formatter, FormatterContext},
1212
Error, Record, StringBuf, __EOL,
1313
};
1414

@@ -25,7 +25,8 @@ impl JournaldFormatter {
2525
&self,
2626
record: &Record,
2727
dest: &mut StringBuf,
28-
) -> Result<FmtExtraInfo, fmt::Error> {
28+
ctx: &mut FormatterContext,
29+
) -> Result<(), fmt::Error> {
2930
cfg_if! {
3031
if #[cfg(not(feature = "flexible-string"))] {
3132
dest.reserve(crate::string_buf::RESERVE_SIZE);
@@ -49,15 +50,20 @@ impl JournaldFormatter {
4950
dest.write_str(record.payload())?;
5051
dest.write_str(__EOL)?;
5152

52-
Ok(FmtExtraInfo {
53-
style_range: Some(style_range_begin..style_range_end),
54-
})
53+
ctx.set_style_range(Some(style_range_begin..style_range_end));
54+
Ok(())
5555
}
5656
}
5757

5858
impl Formatter for JournaldFormatter {
59-
fn format(&self, record: &Record, dest: &mut StringBuf) -> crate::Result<FmtExtraInfo> {
60-
self.format_impl(record, dest).map_err(Error::FormatRecord)
59+
fn format(
60+
&self,
61+
record: &Record,
62+
dest: &mut StringBuf,
63+
ctx: &mut FormatterContext,
64+
) -> crate::Result<()> {
65+
self.format_impl(record, dest, ctx)
66+
.map_err(Error::FormatRecord)
6167
}
6268
}
6369

spdlog/src/formatter/json_formatter.rs

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use cfg_if::cfg_if;
88
use serde::{ser::SerializeStruct, Serialize};
99

1010
use crate::{
11-
formatter::{FmtExtraInfo, Formatter},
11+
formatter::{Formatter, FormatterContext},
1212
Error, Record, StringBuf, __EOL,
1313
};
1414

@@ -146,7 +146,8 @@ impl JsonFormatter {
146146
&self,
147147
record: &Record,
148148
dest: &mut StringBuf,
149-
) -> Result<FmtExtraInfo, JsonFormatterError> {
149+
_ctx: &mut FormatterContext,
150+
) -> Result<(), JsonFormatterError> {
150151
cfg_if! {
151152
if #[cfg(not(feature = "flexible-string"))] {
152153
dest.reserve(crate::string_buf::RESERVE_SIZE);
@@ -163,13 +164,18 @@ impl JsonFormatter {
163164

164165
dest.write_str(__EOL)?;
165166

166-
Ok(FmtExtraInfo { style_range: None })
167+
Ok(())
167168
}
168169
}
169170

170171
impl Formatter for JsonFormatter {
171-
fn format(&self, record: &Record, dest: &mut StringBuf) -> crate::Result<FmtExtraInfo> {
172-
self.format_impl(record, dest).map_err(Into::into)
172+
fn format(
173+
&self,
174+
record: &Record,
175+
dest: &mut StringBuf,
176+
ctx: &mut FormatterContext,
177+
) -> crate::Result<()> {
178+
self.format_impl(record, dest, ctx).map_err(Into::into)
173179
}
174180
}
175181

@@ -191,11 +197,12 @@ mod tests {
191197
let mut dest = StringBuf::new();
192198
let formatter = JsonFormatter::new();
193199
let record = Record::builder(Level::Info, "payload").build();
194-
let extra_info = formatter.format(&record, &mut dest).unwrap();
200+
let mut ctx = FormatterContext::new();
201+
formatter.format(&record, &mut dest, &mut ctx).unwrap();
195202

196203
let local_time: DateTime<Local> = record.time().into();
197204

198-
assert_eq!(extra_info.style_range, None);
205+
assert_eq!(ctx.style_range(), None);
199206
assert_eq!(
200207
dest.to_string(),
201208
format!(
@@ -215,11 +222,12 @@ mod tests {
215222
let record = Record::builder(Level::Info, "payload")
216223
.logger_name("my-component")
217224
.build();
218-
let extra_info = formatter.format(&record, &mut dest).unwrap();
225+
let mut ctx = FormatterContext::new();
226+
formatter.format(&record, &mut dest, &mut ctx).unwrap();
219227

220228
let local_time: DateTime<Local> = record.time().into();
221229

222-
assert_eq!(extra_info.style_range, None);
230+
assert_eq!(ctx.style_range(), None);
223231
assert_eq!(
224232
dest.to_string(),
225233
format!(
@@ -239,11 +247,12 @@ mod tests {
239247
let record = Record::builder(Level::Info, "payload")
240248
.source_location(Some(SourceLocation::__new("module", "file.rs", 1, 2)))
241249
.build();
242-
let extra_info = formatter.format(&record, &mut dest).unwrap();
250+
let mut ctx = FormatterContext::new();
251+
formatter.format(&record, &mut dest, &mut ctx).unwrap();
243252

244253
let local_time: DateTime<Local> = record.time().into();
245254

246-
assert_eq!(extra_info.style_range, None);
255+
assert_eq!(ctx.style_range(), None);
247256
assert_eq!(
248257
dest.to_string(),
249258
format!(

spdlog/src/formatter/mod.rs

Lines changed: 18 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -84,27 +84,33 @@ use crate::{Record, Result, StringBuf};
8484
/// [./examples]: https://github.com/SpriteOvO/spdlog-rs/tree/main/spdlog/examples
8585
pub trait Formatter: Send + Sync + DynClone {
8686
/// Formats a log record.
87-
fn format(&self, record: &Record, dest: &mut StringBuf) -> Result<FmtExtraInfo>;
87+
fn format(
88+
&self,
89+
record: &Record,
90+
dest: &mut StringBuf,
91+
ctx: &mut FormatterContext,
92+
) -> Result<()>;
8893
}
8994
clone_trait_object!(Formatter);
9095

91-
/// Extra information for formatted text.
92-
#[derive(Clone, Eq, PartialEq, Hash, Debug, Default)]
93-
pub struct FmtExtraInfo {
96+
/// Provides context for formatters.
97+
#[derive(Debug, Default)]
98+
pub struct FormatterContext {
9499
style_range: Option<Range<usize>>,
95100
}
96101

97-
impl FmtExtraInfo {
98-
/// Constructs a `FmtExtraInfo`.
102+
impl FormatterContext {
103+
/// Constructs a `FormatterContext`.
99104
#[must_use]
100-
pub fn new() -> FmtExtraInfo {
101-
FmtExtraInfo::default()
105+
pub fn new() -> Self {
106+
Self { style_range: None }
102107
}
103108

104-
/// Gets a [`FmtExtraInfoBuilder`].
105-
#[must_use]
106-
pub fn builder() -> FmtExtraInfoBuilder {
107-
FmtExtraInfoBuilder::new()
109+
/// Sets style range (in bytes) of the formatted text.
110+
///
111+
/// Users must ensure that indexes are correctly UTF-8 boundary.
112+
pub fn set_style_range(&mut self, range: Option<Range<usize>>) {
113+
self.style_range = range;
108114
}
109115

110116
/// A style range (in bytes) of the formatted text.
@@ -120,35 +126,3 @@ impl FmtExtraInfo {
120126
self.style_range.clone() // This clone is cheap
121127
}
122128
}
123-
124-
#[allow(missing_docs)]
125-
#[derive(Clone, Eq, PartialEq, Hash, Debug, Default)]
126-
pub struct FmtExtraInfoBuilder {
127-
info: FmtExtraInfo,
128-
}
129-
130-
impl FmtExtraInfoBuilder {
131-
/// Constructs a `FmtExtraInfoBuilder`.
132-
///
133-
/// The default value of [`FmtExtraInfo`] is the same as
134-
/// [`FmtExtraInfo::new`].
135-
#[must_use]
136-
pub fn new() -> Self {
137-
Self::default()
138-
}
139-
140-
/// Sets style range (in bytes) of the formatted text.
141-
///
142-
/// Users must ensure that indexes are correctly UTF-8 boundary.
143-
#[must_use]
144-
pub fn style_range(mut self, range: Range<usize>) -> Self {
145-
self.info.style_range = Some(range);
146-
self
147-
}
148-
149-
/// Builds a [`FmtExtraInfo`].
150-
#[must_use]
151-
pub fn build(self) -> FmtExtraInfo {
152-
self.info
153-
}
154-
}

0 commit comments

Comments
 (0)