Skip to content

Commit

Permalink
[WIP] 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 93899ba
Show file tree
Hide file tree
Showing 14 changed files with 127 additions and 119 deletions.
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
61 changes: 17 additions & 44 deletions spdlog/src/formatter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,27 +84,32 @@ 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 {
#[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 +125,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
}
}
48 changes: 22 additions & 26 deletions spdlog/src/formatter/pattern_formatter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ pub mod __pattern;
#[cfg(feature = "runtime-pattern")]
mod runtime;

use std::{fmt::Write, ops::Range, sync::Arc};
use std::{fmt::Write, sync::Arc};

use dyn_clone::*;
#[cfg(feature = "runtime-pattern")]
pub use runtime::*;

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

Expand Down Expand Up @@ -369,36 +369,31 @@ impl<P> Formatter for PatternFormatter<P>
where
P: 'static + Clone + Pattern,
{
fn format(&self, record: &Record, dest: &mut StringBuf) -> crate::Result<FmtExtraInfo> {
let mut ctx = PatternContext::new(FmtExtraInfoBuilder::default());
fn format(
&self,
record: &Record,
dest: &mut StringBuf,
ctx: &mut FormatterContext,
) -> crate::Result<()> {
let mut ctx = PatternContext::new(ctx);
self.pattern.format(record, dest, &mut ctx)?;
Ok(ctx.fmt_info_builder.build())
Ok(())
}
}

/// Provides context for patterns.
///
/// There is nothing to set up here at the moment, reserved for future use.
#[derive(Clone, Debug)]
pub struct PatternContext {
fmt_info_builder: FmtExtraInfoBuilder,
#[derive(Debug)]
pub struct PatternContext<'a> {
fmt_ctx: &'a mut FormatterContext,
}

impl PatternContext {
impl<'a> PatternContext<'a> {
/// Creates a new `PatternContext` object.
#[must_use]
fn new(fmt_info_builder: FmtExtraInfoBuilder) -> Self {
Self { fmt_info_builder }
}

/// Sets the style range of the log message written by the patterns.
///
/// This function is reserved for use by the style range pattern. Other
/// built-in patterns should not use this function. User-defined
/// patterns cannot use this function due to type privacy.
fn set_style_range(&mut self, style_range: Range<usize>) {
let builder = std::mem::take(&mut self.fmt_info_builder);
self.fmt_info_builder = builder.style_range(style_range);
fn new(fmt_ctx: &'a mut FormatterContext) -> Self {
Self { fmt_ctx }
}
}

Expand Down Expand Up @@ -1196,6 +1191,8 @@ tuple_pattern! {

#[cfg(test)]
pub mod tests {
use std::ops::Range;

use super::*;
use crate::{Level, SourceLocation};

Expand All @@ -1217,15 +1214,14 @@ pub mod tests {
{
let record = get_mock_record();
let mut output = StringBuf::new();
let mut ctx = PatternContext::new(FmtExtraInfoBuilder::default());
let mut fmt_ctx = FormatterContext::new();
let mut pat_ctx = PatternContext::new(&mut fmt_ctx);

let format_result = pattern.format(&record, &mut output, &mut ctx);
let format_result = pattern.format(&record, &mut output, &mut pat_ctx);
assert!(format_result.is_ok());

assert_eq!(output.as_str(), formatted.as_ref());

let fmt_info = ctx.fmt_info_builder.build();
assert_eq!(fmt_info.style_range(), style_range);
assert_eq!(fmt_ctx.style_range(), style_range);
}

#[test]
Expand Down
15 changes: 8 additions & 7 deletions spdlog/src/formatter/pattern_formatter/pattern/full.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,14 @@ impl Pattern for Full {
dest: &mut StringBuf,
ctx: &mut PatternContext,
) -> crate::Result<()> {
let extra_info = self.full_formatter.format(record, dest)?;
if let Some(style_range) = extra_info.style_range {
// Before we support multiple style ranges, if there is already a style range
// set, we don't override it.
if ctx.fmt_info_builder.info.style_range.is_none() {
ctx.set_style_range(style_range)
}
let saved_style_range = ctx.fmt_ctx.style_range.clone();

self.full_formatter.format(record, dest, ctx.fmt_ctx)?;

// TODO: Before we support multiple style ranges, if there is already a style
// range set, we don't override it.
if let Some(saved_style_range) = saved_style_range {
ctx.fmt_ctx.set_style_range(Some(saved_style_range));
}
Ok(())
}
Expand Down
Loading

0 comments on commit 93899ba

Please sign in to comment.