Skip to content

Commit

Permalink
Removed duplicate Location and Level now that bp3d-debug defines thos…
Browse files Browse the repository at this point in the history
…e types
  • Loading branch information
Yuri6037 committed Jul 20, 2024
1 parent 2464381 commit 741ee11
Show file tree
Hide file tree
Showing 8 changed files with 41 additions and 136 deletions.
1 change: 1 addition & 0 deletions logger/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ categories = []
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
bp3d-debug = "1.0.0-rc.2.0.0"
bp3d-os = { version = "1.0.0-rc.3.0.3", features=["dirs", "time"] }
bp3d-util = { version = "1.0.0", features = ["format"] }
crossbeam-channel = "0.5.2"
Expand Down
2 changes: 1 addition & 1 deletion logger/src/easy_termcolor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use crate::Level;
use bp3d_debug::logger::Level;
use std::fmt::Display;
use termcolor::{Color, ColorSpec};

Expand Down
4 changes: 3 additions & 1 deletion logger/src/handler/stdout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,13 @@
use crate::easy_termcolor::{color, EasyTermColor};
use crate::handler::{Flag, Handler};
use crate::util::write_time;
use crate::{Colors, Level, Location, LogMsg};
use crate::{Colors, LogMsg};
use bp3d_os::time::LocalUtcOffset;
use bp3d_util::format::FixedBufStr;
use std::io::IsTerminal;
use std::mem::MaybeUninit;
use bp3d_debug::logger::Level;
use bp3d_debug::util::Location;
use termcolor::{ColorChoice, ColorSpec, StandardStream};
use time::{OffsetDateTime, UtcOffset};

Expand Down
2 changes: 1 addition & 1 deletion logger/src/internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ impl Logger {
/// This function calls the [raw_log](Self::raw_log) function only when this logger is enabled.
#[inline]
pub fn log(&self, msg: &LogMsg) {
if self.filter() >= msg.level().as_level_filter() {
if self.filter() >= msg.level().into() {
self.raw_log(msg);
}
}
Expand Down
61 changes: 11 additions & 50 deletions logger/src/level.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use std::fmt::{Display, Formatter};
use bp3d_debug::logger::Level;

/// An enum representing the available verbosity levels of the logger.
#[repr(u8)]
Expand Down Expand Up @@ -88,61 +88,22 @@ impl LevelFilter {
}
}

/// An enum representing the available verbosity levels for a message.
#[repr(u8)]
#[derive(Clone, PartialEq, Copy, Ord, PartialOrd, Eq, Debug, Hash)]
pub enum Level {
/// The "trace" level.
///
/// Designates very low priority, often extremely verbose, information.
Trace = 1,

/// The "debug" level.
///
/// Designates lower priority information.
Debug = 2,

/// The "info" level.
///
/// Designates useful information.
Info = 3,

/// The "warn" level.
///
/// Designates hazardous situations.
Warn = 4,

/// The "error" level.
///
/// Designates very serious errors.
// This way these line up with the discriminants for LevelFilter below
// This works because Rust treats field-less enums the same way as C does:
// https://doc.rust-lang.org/reference/items/enumerations.html#custom-discriminant-values-for-field-less-enumerations
Error = 5,
}

static LOG_LEVEL_NAMES: [&str; 6] = ["OFF", "TRACE", "DEBUG", "INFO", "WARNING", "ERROR"];

impl Level {
/// Returns the string representation of the `Level`.
///
/// This returns the same string as the `fmt::Display` implementation.
pub fn as_str(&self) -> &'static str {
LOG_LEVEL_NAMES[*self as usize]
}

/// Returns the [LevelFilter](LevelFilter) representation of this log [Level](Level).
impl From<&Level> for LevelFilter {
#[allow(clippy::missing_transmute_annotations)]
pub fn as_level_filter(&self) -> LevelFilter {
fn from(value: &Level) -> Self {
// SAFETY: This is safe because both Level and LevelFilter are u8 values and Level shares
// the same variants as LevelFilter (with the exception that LevelFilter has one more
// variant at 0).
unsafe { std::mem::transmute(*self) }
unsafe { std::mem::transmute(*value) }
}
}

impl Display for Level {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
impl From<Level> for LevelFilter {
#[allow(clippy::missing_transmute_annotations)]
fn from(value: Level) -> Self {
// SAFETY: This is safe because both Level and LevelFilter are u8 values and Level shares
// the same variants as LevelFilter (with the exception that LevelFilter has one more
// variant at 0).
unsafe { std::mem::transmute(value) }
}
}
6 changes: 4 additions & 2 deletions logger/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,10 @@ use std::path::PathBuf;

pub use builder::*;
pub use internal::Logger;
pub use level::{Level, LevelFilter};
pub use log_msg::{Location, LogMsg};
pub use level::LevelFilter;
pub use log_msg::LogMsg;
pub use bp3d_debug::logger::Level;
pub use bp3d_debug::util::Location;

/// The log buffer type.
pub type LogBuffer = Receiver<LogMsg>;
Expand Down
73 changes: 17 additions & 56 deletions logger/src/log_msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use crate::util::extract_target_module;
use crate::Level;
use std::fmt::{Error, Write};
use std::mem::MaybeUninit;
use bp3d_debug::logger::Level;
use bp3d_debug::util::Location;
use time::OffsetDateTime;

// Size of the control fields of the log message structure:
Expand All @@ -39,55 +39,6 @@ const LOG_CONTROL_SIZE: usize = 40 + 16 + 4 + 1 + 3;
const LOG_MSG_SIZE: usize = LOG_BUFFER_SIZE - LOG_CONTROL_SIZE;
const LOG_BUFFER_SIZE: usize = 1024;

/// The context of a log message.
#[derive(Clone, Copy)]
pub struct Location {
module_path: &'static str,
file: &'static str,
line: u32,
}

impl Location {
/// Creates a new instance of a log message location.
///
/// This function is const to let the caller store location structures in statics.
///
/// # Arguments
///
/// * `module_path`: the module path obtained from the [module_path](module_path) macro.
/// * `file`: the source file obtained from the [file](file) macro.
/// * `line`: the line number in the source file obtained from the [line](line) macro.
///
/// returns: Metadata
pub const fn new(module_path: &'static str, file: &'static str, line: u32) -> Self {
Self {
module_path,
file,
line,
}
}

/// The module path which issued this log message.
pub fn module_path(&self) -> &'static str {
self.module_path
}

/// The source file which issued this log message.
pub fn file(&self) -> &'static str {
self.file
}

/// The line in the source file which issued this log message.
pub fn line(&self) -> u32 {
self.line
}

/// Extracts the target name and the module name from the module path.
pub fn get_target_module(&self) -> (&'static str, &'static str) {
extract_target_module(self.module_path)
}
}

/// A log message.
///
/// This structure uses a large 1K buffer which stores the entire log message to improve
Expand All @@ -99,8 +50,10 @@ impl Location {
/// # Examples
///
/// ```
/// use bp3d_logger::{Level, Location, LogMsg};
/// use bp3d_logger::LogMsg;
/// use std::fmt::Write;
/// use bp3d_debug::logger::Level;
/// use bp3d_debug::util::Location;
/// let mut msg = LogMsg::new(Location::new("test", "file.c", 1), Level::Info);
/// let _ = write!(msg, "This is a formatted message {}", 42);
/// assert_eq!(msg.msg(), "This is a formatted message 42");
Expand Down Expand Up @@ -128,7 +81,9 @@ impl LogMsg {
/// # Examples
///
/// ```
/// use bp3d_logger::{Level, Location, LogMsg};
/// use bp3d_debug::logger::Level;
/// use bp3d_debug::util::Location;
/// use bp3d_logger::LogMsg;
/// let msg = LogMsg::new(Location::new("test", "file.c", 1), Level::Info);
/// assert_eq!(msg.location().module_path(), "test");
/// assert_eq!(msg.level(), Level::Info);
Expand All @@ -149,8 +104,10 @@ impl LogMsg {
/// # Examples
///
/// ```
/// use bp3d_debug::logger::Level;
/// use bp3d_debug::util::Location;
/// use time::macros::datetime;
/// use bp3d_logger::{Level, Location, LogMsg};
/// use bp3d_logger::LogMsg;
/// let msg = LogMsg::with_time(Location::new("test", "file.c", 1), datetime!(1999-1-1 0:0 UTC), Level::Info);
/// assert_eq!(msg.location().module_path(), "test");
/// assert_eq!(msg.level(), Level::Info);
Expand All @@ -170,7 +127,9 @@ impl LogMsg {
/// # Examples
///
/// ```
/// use bp3d_logger::{Level, Location, LogMsg};
/// use bp3d_debug::logger::Level;
/// use bp3d_debug::util::Location;
/// use bp3d_logger::LogMsg;
/// let mut msg = LogMsg::from_msg(Location::new("test", "file.c", 1), Level::Info, "this is a test");
/// msg.clear();
/// assert_eq!(msg.msg(), "");
Expand Down Expand Up @@ -208,7 +167,9 @@ impl LogMsg {
/// # Examples
///
/// ```
/// use bp3d_logger::{LogMsg, Level, Location};
/// use bp3d_debug::logger::Level;
/// use bp3d_debug::util::Location;
/// use bp3d_logger::LogMsg;
/// let mut msg = LogMsg::from_msg(Location::new("test", "file.c", 1), Level::Info, "this is a test");
/// assert_eq!(msg.location().module_path(), "test");
/// assert_eq!(msg.level(), Level::Info);
Expand Down
28 changes: 3 additions & 25 deletions logger/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,22 +33,6 @@ use std::fmt::Write;
use time::macros::format_description;
use time::OffsetDateTime;

/// Extracts the target name and the module path (without the target name) from a full module path string.
///
/// # Arguments
///
/// * `base_string`: a full module path string (ex: bp3d_logger::util::extract_target_module).
///
/// returns: (&str, &str)
pub fn extract_target_module(base_string: &str) -> (&str, &str) {
let target = base_string
.find("::")
.map(|v| &base_string[..v])
.unwrap_or(base_string);
let module = base_string.find("::").map(|v| &base_string[(v + 2)..]);
(target, module.unwrap_or("main"))
}

/// Write time information into the given [Write](Write).
///
/// # Arguments
Expand All @@ -66,18 +50,12 @@ pub fn write_time(msg: &mut impl Write, time: OffsetDateTime) {
let _ = msg.write_str(")");
}

/// Generate a [Location](crate::Location) structure.
#[macro_export]
macro_rules! location {
() => {
$crate::Location::new(module_path!(), file!(), line!())
};
}

#[cfg(test)]
mod tests {
use bp3d_debug::logger::Level;
use bp3d_debug::util::Location;
use crate::util::write_time;
use crate::{Level, Location, LogMsg};
use crate::LogMsg;
use bp3d_os::time::LocalOffsetDateTime;
use time::OffsetDateTime;

Expand Down

0 comments on commit 741ee11

Please sign in to comment.