Skip to content

Commit

Permalink
Replace FmtExtraInfo with FormatterContext
Browse files Browse the repository at this point in the history
  • Loading branch information
SpriteOvO committed Aug 16, 2024
1 parent b5dc872 commit 4654472
Show file tree
Hide file tree
Showing 17 changed files with 150 additions and 130 deletions.
14 changes: 9 additions & 5 deletions spdlog/examples/04_format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ fn impl_manually() {
use std::fmt::Write;

use spdlog::{
formatter::{FmtExtraInfo, Formatter},
formatter::{Formatter, FormatterContext},
prelude::*,
Record, StringBuf,
};
Expand All @@ -43,7 +43,12 @@ fn impl_manually() {
struct MyFormatter;

impl Formatter for MyFormatter {
fn format(&self, record: &Record, dest: &mut StringBuf) -> spdlog::Result<FmtExtraInfo> {
fn format(
&self,
record: &Record,
dest: &mut StringBuf,
ctx: &mut FormatterContext,
) -> spdlog::Result<()> {
let style_range_begin = dest.len();

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

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

Ok(FmtExtraInfo::builder()
.style_range(style_range_begin..style_range_end)
.build())
ctx.set_style_range(Some(style_range_begin..style_range_end));
Ok(())
}
}

Expand Down
7 changes: 5 additions & 2 deletions spdlog/examples/05_sink.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::sync::Arc;

use atomic::{Atomic, Ordering};
use spdlog::{
formatter::{Formatter, FullFormatter},
formatter::{Formatter, FormatterContext, FullFormatter},
prelude::*,
sink::Sink,
ErrorHandler, Record, StringBuf,
Expand Down Expand Up @@ -34,7 +34,10 @@ impl CollectVecSink {
impl Sink for CollectVecSink {
fn log(&self, record: &Record) -> spdlog::Result<()> {
let mut string_buf = StringBuf::new();
self.formatter.read().format(record, &mut string_buf)?;
let mut ctx = FormatterContext::new();
self.formatter
.read()
.format(record, &mut string_buf, &mut ctx)?;
self.collected.lock().push(string_buf.to_string());
Ok(())
}
Expand Down
27 changes: 18 additions & 9 deletions spdlog/src/formatter/full_formatter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::fmt::{self, Write};
use cfg_if::cfg_if;

use crate::{
formatter::{FmtExtraInfo, Formatter, LOCAL_TIME_CACHER},
formatter::{Formatter, FormatterContext, LOCAL_TIME_CACHER},
Error, Record, StringBuf, __EOL,
};

Expand Down Expand Up @@ -54,7 +54,8 @@ impl FullFormatter {
&self,
record: &Record,
dest: &mut StringBuf,
) -> Result<FmtExtraInfo, fmt::Error> {
ctx: &mut FormatterContext,
) -> Result<(), fmt::Error> {
cfg_if! {
if #[cfg(not(feature = "flexible-string"))] {
dest.reserve(crate::string_buf::RESERVE_SIZE);
Expand Down Expand Up @@ -98,15 +99,20 @@ impl FullFormatter {
dest.write_str(__EOL)?;
}

Ok(FmtExtraInfo {
style_range: Some(style_range_begin..style_range_end),
})
ctx.set_style_range(Some(style_range_begin..style_range_end));
Ok(())
}
}

impl Formatter for FullFormatter {
fn format(&self, record: &Record, dest: &mut StringBuf) -> crate::Result<FmtExtraInfo> {
self.format_impl(record, dest).map_err(Error::FormatRecord)
fn format(
&self,
record: &Record,
dest: &mut StringBuf,
ctx: &mut FormatterContext,
) -> crate::Result<()> {
self.format_impl(record, dest, ctx)
.map_err(Error::FormatRecord)
}
}

Expand All @@ -127,7 +133,10 @@ mod tests {
fn format() {
let record = Record::new(Level::Warn, "test log content");
let mut buf = StringBuf::new();
let extra_info = FullFormatter::new().format(&record, &mut buf).unwrap();
let mut ctx = FormatterContext::new();
FullFormatter::new()
.format(&record, &mut buf, &mut ctx)
.unwrap();

let local_time: DateTime<Local> = record.time().into();
assert_eq!(
Expand All @@ -138,6 +147,6 @@ mod tests {
),
buf
);
assert_eq!(Some(27..31), extra_info.style_range());
assert_eq!(Some(27..31), ctx.style_range());
}
}
20 changes: 13 additions & 7 deletions spdlog/src/formatter/journald_formatter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::fmt::{self, Write};
use cfg_if::cfg_if;

use crate::{
formatter::{FmtExtraInfo, Formatter},
formatter::{Formatter, FormatterContext},
Error, Record, StringBuf, __EOL,
};

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

Ok(FmtExtraInfo {
style_range: Some(style_range_begin..style_range_end),
})
ctx.set_style_range(Some(style_range_begin..style_range_end));
Ok(())
}
}

impl Formatter for JournaldFormatter {
fn format(&self, record: &Record, dest: &mut StringBuf) -> crate::Result<FmtExtraInfo> {
self.format_impl(record, dest).map_err(Error::FormatRecord)
fn format(
&self,
record: &Record,
dest: &mut StringBuf,
ctx: &mut FormatterContext,
) -> crate::Result<()> {
self.format_impl(record, dest, ctx)
.map_err(Error::FormatRecord)
}
}

Expand Down
31 changes: 20 additions & 11 deletions spdlog/src/formatter/json_formatter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use cfg_if::cfg_if;
use serde::{ser::SerializeStruct, Serialize};

use crate::{
formatter::{FmtExtraInfo, Formatter},
formatter::{Formatter, FormatterContext},
Error, Record, StringBuf, __EOL,
};

Expand Down Expand Up @@ -146,7 +146,8 @@ impl JsonFormatter {
&self,
record: &Record,
dest: &mut StringBuf,
) -> Result<FmtExtraInfo, JsonFormatterError> {
_ctx: &mut FormatterContext,
) -> Result<(), JsonFormatterError> {
cfg_if! {
if #[cfg(not(feature = "flexible-string"))] {
dest.reserve(crate::string_buf::RESERVE_SIZE);
Expand All @@ -163,13 +164,18 @@ impl JsonFormatter {

dest.write_str(__EOL)?;

Ok(FmtExtraInfo { style_range: None })
Ok(())
}
}

impl Formatter for JsonFormatter {
fn format(&self, record: &Record, dest: &mut StringBuf) -> crate::Result<FmtExtraInfo> {
self.format_impl(record, dest).map_err(Into::into)
fn format(
&self,
record: &Record,
dest: &mut StringBuf,
ctx: &mut FormatterContext,
) -> crate::Result<()> {
self.format_impl(record, dest, ctx).map_err(Into::into)
}
}

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

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

assert_eq!(extra_info.style_range, None);
assert_eq!(ctx.style_range(), None);
assert_eq!(
dest.to_string(),
format!(
Expand All @@ -215,11 +222,12 @@ mod tests {
let record = Record::builder(Level::Info, "payload")
.logger_name("my-component")
.build();
let extra_info = formatter.format(&record, &mut dest).unwrap();
let mut ctx = FormatterContext::new();
formatter.format(&record, &mut dest, &mut ctx).unwrap();

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

assert_eq!(extra_info.style_range, None);
assert_eq!(ctx.style_range(), None);
assert_eq!(
dest.to_string(),
format!(
Expand All @@ -239,11 +247,12 @@ mod tests {
let record = Record::builder(Level::Info, "payload")
.source_location(Some(SourceLocation::__new("module", "file.rs", 1, 2)))
.build();
let extra_info = formatter.format(&record, &mut dest).unwrap();
let mut ctx = FormatterContext::new();
formatter.format(&record, &mut dest, &mut ctx).unwrap();

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

assert_eq!(extra_info.style_range, None);
assert_eq!(ctx.style_range(), None);
assert_eq!(
dest.to_string(),
format!(
Expand Down
62 changes: 18 additions & 44 deletions spdlog/src/formatter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,27 +84,33 @@ use crate::{Record, Result, StringBuf};
/// [./examples]: https://github.com/SpriteOvO/spdlog-rs/tree/main/spdlog/examples
pub trait Formatter: Send + Sync + DynClone {
/// Formats a log record.
fn format(&self, record: &Record, dest: &mut StringBuf) -> Result<FmtExtraInfo>;
fn format(
&self,
record: &Record,
dest: &mut StringBuf,
ctx: &mut FormatterContext,
) -> Result<()>;
}
clone_trait_object!(Formatter);

/// Extra information for formatted text.
#[derive(Clone, Eq, PartialEq, Hash, Debug, Default)]
pub struct FmtExtraInfo {
/// Provides context for formatters.
#[derive(Debug, Default)]
pub struct FormatterContext {
style_range: Option<Range<usize>>,
}

impl FmtExtraInfo {
/// Constructs a `FmtExtraInfo`.
impl FormatterContext {
/// Constructs a `FormatterContext`.
#[must_use]
pub fn new() -> FmtExtraInfo {
FmtExtraInfo::default()
pub fn new() -> Self {
Self { style_range: None }
}

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

/// A style range (in bytes) of the formatted text.
Expand All @@ -120,35 +126,3 @@ impl FmtExtraInfo {
self.style_range.clone() // This clone is cheap
}
}

#[allow(missing_docs)]
#[derive(Clone, Eq, PartialEq, Hash, Debug, Default)]
pub struct FmtExtraInfoBuilder {
info: FmtExtraInfo,
}

impl FmtExtraInfoBuilder {
/// Constructs a `FmtExtraInfoBuilder`.
///
/// The default value of [`FmtExtraInfo`] is the same as
/// [`FmtExtraInfo::new`].
#[must_use]
pub fn new() -> Self {
Self::default()
}

/// Sets style range (in bytes) of the formatted text.
///
/// Users must ensure that indexes are correctly UTF-8 boundary.
#[must_use]
pub fn style_range(mut self, range: Range<usize>) -> Self {
self.info.style_range = Some(range);
self
}

/// Builds a [`FmtExtraInfo`].
#[must_use]
pub fn build(self) -> FmtExtraInfo {
self.info
}
}
Loading

0 comments on commit 4654472

Please sign in to comment.