Dataset Viewer
Auto-converted to Parquet Duplicate
repo
stringclasses
1 value
pull_number
int64
70
619
instance_id
stringlengths
17
18
issue_numbers
sequencelengths
1
1
base_commit
stringlengths
40
40
patch
stringlengths
341
89.2k
test_patch
stringlengths
548
5.67k
problem_statement
stringlengths
67
4.82k
hints_text
stringlengths
0
4.86k
created_at
stringlengths
20
20
version
stringclasses
2 values
environment_setup_commit
stringclasses
2 values
rust-lang/log
619
rust-lang__log-619
[ "601" ]
06c306fa8f4d41a722f8759f03effd4185eee3ee
diff --git a/Cargo.toml b/Cargo.toml index c0ea52a77..72fcdb0e4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,8 +20,8 @@ edition = "2021" features = ["std", "serde", "kv_std", "kv_sval", "kv_serde"] [[test]] -name = "filters" -path = "tests/filters.rs" +name = "integration" +path = "tests/integration.rs" harness = false [[test]]
diff --git a/tests/filters.rs b/tests/integration.rs similarity index 56% rename from tests/filters.rs rename to tests/integration.rs index 3e0810d07..7bf456e02 100644 --- a/tests/filters.rs +++ b/tests/integration.rs @@ -12,7 +12,8 @@ fn set_boxed_logger(logger: Box<dyn Log>) -> Result<(), log::SetLoggerError> { } struct State { - last_log: Mutex<Option<Level>>, + last_log_level: Mutex<Option<Level>>, + last_log_location: Mutex<Option<u32>>, } struct Logger(Arc<State>); @@ -23,11 +24,11 @@ impl Log for Logger { } fn log(&self, record: &Record) { - *self.0.last_log.lock().unwrap() = Some(record.level()); + *self.0.last_log_level.lock().unwrap() = Some(record.level()); + *self.0.last_log_location.lock().unwrap() = record.line(); } fn flush(&self) {} } - #[cfg_attr(lib_build, test)] fn main() { // These tests don't really make sense when static @@ -48,21 +49,25 @@ fn main() { )))] { let me = Arc::new(State { - last_log: Mutex::new(None), + last_log_level: Mutex::new(None), + last_log_location: Mutex::new(None), }); let a = me.clone(); set_boxed_logger(Box::new(Logger(me))).unwrap(); - test(&a, LevelFilter::Off); - test(&a, LevelFilter::Error); - test(&a, LevelFilter::Warn); - test(&a, LevelFilter::Info); - test(&a, LevelFilter::Debug); - test(&a, LevelFilter::Trace); + test_filter(&a, LevelFilter::Off); + test_filter(&a, LevelFilter::Error); + test_filter(&a, LevelFilter::Warn); + test_filter(&a, LevelFilter::Info); + test_filter(&a, LevelFilter::Debug); + test_filter(&a, LevelFilter::Trace); + + test_line_numbers(&a); } } -fn test(a: &State, filter: LevelFilter) { +fn test_filter(a: &State, filter: LevelFilter) { + // tests to ensure logs with a level beneath 'max_level' are filtered out log::set_max_level(filter); error!(""); last(a, t(Level::Error, filter)); @@ -82,9 +87,22 @@ fn test(a: &State, filter: LevelFilter) { None } } + fn last(state: &State, expected: Option<Level>) { + let lvl = state.last_log_level.lock().unwrap().take(); + assert_eq!(lvl, expected); + } } -fn last(state: &State, expected: Option<Level>) { - let lvl = state.last_log.lock().unwrap().take(); - assert_eq!(lvl, expected); +fn test_line_numbers(state: &State) { + log::set_max_level(LevelFilter::Trace); + + info!(""); // ensure check_line function follows log macro + check_log_location(&state); + + #[track_caller] + fn check_log_location(state: &State) { + let location = std::panic::Location::caller().line(); // get function calling location + let line_number = state.last_log_location.lock().unwrap().take().unwrap(); // get location of most recent log + assert_eq!(line_number, location - 1); + } } diff --git a/tests/src/lib.rs b/tests/src/lib.rs index 73f0753ca..a791a0c87 100644 --- a/tests/src/lib.rs +++ b/tests/src/lib.rs @@ -6,8 +6,8 @@ #![allow(dead_code)] #[cfg(test)] -#[path = "../filters.rs"] -mod filters; +#[path = "../integration.rs"] +mod integration; #[cfg(test)] #[path = "../macros.rs"]
Add tests that check the line numbers We currently don't have any.
Im pretty new to contributing, but I would love to contribute to this repo. Would this be a good issue to start with? > Im pretty new to contributing, but I would love to contribute to this repo. Would this be a good issue to start with? Hey @DIvkov575 sorry for the delayed response, I've been traveling. I think it will be a good first issue. I think the easiest way to get started is to look at `tests/filters.rs`for inspiration. If you have a any questions or you get stuck somewhere feel free to ask!
2024-03-16T14:49:52Z
0.4
06c306fa8f4d41a722f8759f03effd4185eee3ee
rust-lang/log
613
rust-lang__log-613
[ "584" ]
7cb6a01dff9157f3f3dca36aa0152f144023ff60
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 3fc335e73..3c263a434 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -44,10 +44,10 @@ jobs: - run: cargo test --verbose --all-features - run: cargo test --verbose --features serde - run: cargo test --verbose --features std - - run: cargo test --verbose --features kv_unstable - - run: cargo test --verbose --features kv_unstable_sval - - run: cargo test --verbose --features kv_unstable_serde - - run: cargo test --verbose --features "kv_unstable kv_unstable_std kv_unstable_sval kv_unstable_serde" + - run: cargo test --verbose --features kv + - run: cargo test --verbose --features kv_sval + - run: cargo test --verbose --features kv_serde + - run: cargo test --verbose --features "kv kv_std kv_sval kv_serde" - run: cargo run --verbose --manifest-path test_max_level_features/Cargo.toml - run: cargo run --verbose --manifest-path test_max_level_features/Cargo.toml --release @@ -103,12 +103,12 @@ jobs: run: | rustup update nightly --no-self-update rustup default nightly - - run: cargo build --verbose -Z avoid-dev-deps --features kv_unstable - - run: cargo build --verbose -Z avoid-dev-deps --features "kv_unstable std" - - run: cargo build --verbose -Z avoid-dev-deps --features "kv_unstable kv_unstable_sval" - - run: cargo build --verbose -Z avoid-dev-deps --features "kv_unstable kv_unstable_serde" - - run: cargo build --verbose -Z avoid-dev-deps --features "kv_unstable kv_unstable_std" - - run: cargo build --verbose -Z avoid-dev-deps --features "kv_unstable kv_unstable_sval kv_unstable_serde" + - run: cargo build --verbose -Z avoid-dev-deps --features kv + - run: cargo build --verbose -Z avoid-dev-deps --features "kv std" + - run: cargo build --verbose -Z avoid-dev-deps --features "kv kv_sval" + - run: cargo build --verbose -Z avoid-dev-deps --features "kv kv_serde" + - run: cargo build --verbose -Z avoid-dev-deps --features "kv kv_std" + - run: cargo build --verbose -Z avoid-dev-deps --features "kv kv_sval kv_serde" minimalv: name: Minimal versions @@ -119,12 +119,12 @@ jobs: run: | rustup update nightly --no-self-update rustup default nightly - - run: cargo build --verbose -Z minimal-versions --features kv_unstable - - run: cargo build --verbose -Z minimal-versions --features "kv_unstable std" - - run: cargo build --verbose -Z minimal-versions --features "kv_unstable kv_unstable_sval" - - run: cargo build --verbose -Z minimal-versions --features "kv_unstable kv_unstable_serde" - - run: cargo build --verbose -Z minimal-versions --features "kv_unstable kv_unstable_std" - - run: cargo build --verbose -Z minimal-versions --features "kv_unstable kv_unstable_sval kv_unstable_serde" + - run: cargo build --verbose -Z minimal-versions --features kv + - run: cargo build --verbose -Z minimal-versions --features "kv std" + - run: cargo build --verbose -Z minimal-versions --features "kv kv_sval" + - run: cargo build --verbose -Z minimal-versions --features "kv kv_serde" + - run: cargo build --verbose -Z minimal-versions --features "kv kv_std" + - run: cargo build --verbose -Z minimal-versions --features "kv kv_sval kv_serde" msrv: name: MSRV @@ -135,7 +135,9 @@ jobs: run: | rustup update 1.60.0 --no-self-update rustup default 1.60.0 - - run: cargo test --verbose --manifest-path tests/Cargo.toml + - run: | + cargo test --verbose --manifest-path tests/Cargo.toml + cargo test --verbose --manifest-path tests/Cargo.toml --features kv embedded: name: Embedded diff --git a/Cargo.toml b/Cargo.toml index 89012be02..cf64b43e7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,7 +17,7 @@ rust-version = "1.60.0" edition = "2021" [package.metadata.docs.rs] -features = ["std", "serde", "kv_unstable_std", "kv_unstable_sval", "kv_unstable_serde"] +features = ["std", "serde", "kv_std", "kv_sval", "kv_serde"] [[test]] name = "filters" @@ -46,25 +46,31 @@ release_max_level_trace = [] std = [] -# requires the latest stable -# this will have a tighter MSRV before stabilization -kv_unstable = ["value-bag"] -kv_unstable_sval = ["kv_unstable", "value-bag/sval", "sval", "sval_ref"] -kv_unstable_std = ["std", "kv_unstable", "value-bag/error"] -kv_unstable_serde = ["kv_unstable_std", "value-bag/serde", "serde"] +kv = [] +kv_sval = ["kv", "value-bag/sval", "sval", "sval_ref"] +kv_std = ["std", "kv", "value-bag/error"] +kv_serde = ["kv_std", "value-bag/serde", "serde"] + +# Deprecated: use `kv_*` instead +# These `*_unstable` features will be removed in a future release +kv_unstable = ["kv", "value-bag"] +kv_unstable_sval = ["kv_sval", "kv_unstable"] +kv_unstable_std = ["kv_std", "kv_unstable"] +kv_unstable_serde = ["kv_serde", "kv_unstable_std"] [dependencies] serde = { version = "1.0", optional = true, default-features = false } sval = { version = "2.1", optional = true, default-features = false } sval_ref = { version = "2.1", optional = true, default-features = false } -value-bag = { version = "1.4", optional = true, default-features = false } +value-bag = { version = "1.7", optional = true, default-features = false, features = ["inline-i128"] } [dev-dependencies] serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" serde_test = "1.0" sval = { version = "2.1" } sval_derive = { version = "2.1" } -value-bag = { version = "1.4", features = ["test"] } +value-bag = { version = "1.7", features = ["test"] } # NOTE: log doesn't actually depent on this crate. However our dependencies, # serde and sval, dependent on version 1.0 of the crate, which has problem fixed diff --git a/README.md b/README.md index d41414473..d6a08f558 100644 --- a/README.md +++ b/README.md @@ -100,23 +100,28 @@ The executable itself may use the `log` crate to log as well. ## Structured logging -If you enable the `kv_unstable` feature, you can associate structured data with your log records: +If you enable the `kv` feature, you can associate structured data with your log records: ```rust -use log::{info, trace, warn, as_serde, as_error}; +use log::{info, trace, warn}; pub fn shave_the_yak(yak: &mut Yak) { - trace!(target = "yak_events", yak = as_serde!(yak); "Commencing yak shaving"); + // `yak:serde` will capture `yak` using its `serde::Serialize` impl + // + // You could also use `:?` for `Debug`, or `:%` for `Display`. For a + // full list, see the `log` crate documentation + trace!(target = "yak_events", yak:serde; "Commencing yak shaving"); loop { match find_a_razor() { Ok(razor) => { - info!(razor = razor; "Razor located"); + info!(razor; "Razor located"); yak.shave(razor); break; } - Err(err) => { - warn!(err = as_error!(err); "Unable to locate a razor, retrying"); + Err(e) => { + // `e:err` will capture `e` using its `std::error::Error` impl + warn!(e:err; "Unable to locate a razor, retrying"); } } } diff --git a/benches/value.rs b/benches/value.rs index e43be50f7..3d0f18bfe 100644 --- a/benches/value.rs +++ b/benches/value.rs @@ -1,4 +1,4 @@ -#![cfg(feature = "kv_unstable")] +#![cfg(feature = "kv")] #![feature(test)] use log::kv::Value; diff --git a/src/__private_api.rs b/src/__private_api.rs index 92bd15656..fd0a5a762 100644 --- a/src/__private_api.rs +++ b/src/__private_api.rs @@ -5,31 +5,28 @@ use crate::{Level, Metadata, Record}; use std::fmt::Arguments; pub use std::{file, format_args, line, module_path, stringify}; -#[cfg(feature = "kv_unstable")] -pub type Value<'a> = dyn crate::kv::value::ToValue + 'a; - -#[cfg(not(feature = "kv_unstable"))] -pub type Value<'a> = str; +#[cfg(not(feature = "kv"))] +pub type Value<'a> = &'a str; mod sealed { /// Types for the `kv` argument. pub trait KVs<'a> { - fn into_kvs(self) -> Option<&'a [(&'a str, &'a super::Value<'a>)]>; + fn into_kvs(self) -> Option<&'a [(&'a str, super::Value<'a>)]>; } } // Types for the `kv` argument. -impl<'a> KVs<'a> for &'a [(&'a str, &'a Value<'a>)] { +impl<'a> KVs<'a> for &'a [(&'a str, Value<'a>)] { #[inline] - fn into_kvs(self) -> Option<&'a [(&'a str, &'a Value<'a>)]> { + fn into_kvs(self) -> Option<&'a [(&'a str, Value<'a>)]> { Some(self) } } impl<'a> KVs<'a> for () { #[inline] - fn into_kvs(self) -> Option<&'a [(&'a str, &'a Value<'a>)]> { + fn into_kvs(self) -> Option<&'a [(&'a str, Value<'a>)]> { None } } @@ -41,13 +38,11 @@ fn log_impl( level: Level, &(target, module_path, file): &(&str, &'static str, &'static str), line: u32, - kvs: Option<&[(&str, &Value)]>, + kvs: Option<&[(&str, Value)]>, ) { - #[cfg(not(feature = "kv_unstable"))] + #[cfg(not(feature = "kv"))] if kvs.is_some() { - panic!( - "key-value support is experimental and must be enabled using the `kv_unstable` feature" - ) + panic!("key-value support is experimental and must be enabled using the `kv` feature") } let mut builder = Record::builder(); @@ -60,7 +55,7 @@ fn log_impl( .file_static(Some(file)) .line(Some(line)); - #[cfg(feature = "kv_unstable")] + #[cfg(feature = "kv")] builder.key_values(&kvs); crate::logger().log(&builder.build()); @@ -87,3 +82,44 @@ pub fn log<'a, K>( pub fn enabled(level: Level, target: &str) -> bool { crate::logger().enabled(&Metadata::builder().level(level).target(target).build()) } + +#[cfg(feature = "kv")] +mod kv_support { + use crate::kv; + + pub type Value<'a> = kv::Value<'a>; + + // NOTE: Many functions here accept a double reference &&V + // This is so V itself can be ?Sized, while still letting us + // erase it to some dyn Trait (because &T is sized) + + pub fn capture_to_value<'a, V: kv::ToValue + ?Sized>(v: &'a &'a V) -> Value<'a> { + v.to_value() + } + + pub fn capture_debug<'a, V: core::fmt::Debug + ?Sized>(v: &'a &'a V) -> Value<'a> { + Value::from_debug(v) + } + + pub fn capture_display<'a, V: core::fmt::Display + ?Sized>(v: &'a &'a V) -> Value<'a> { + Value::from_display(v) + } + + #[cfg(feature = "kv_std")] + pub fn capture_error<'a>(v: &'a (dyn std::error::Error + 'static)) -> Value<'a> { + Value::from_dyn_error(v) + } + + #[cfg(feature = "kv_sval")] + pub fn capture_sval<'a, V: sval::Value + ?Sized>(v: &'a &'a V) -> Value<'a> { + Value::from_sval(v) + } + + #[cfg(feature = "kv_serde")] + pub fn capture_serde<'a, V: serde::Serialize + ?Sized>(v: &'a &'a V) -> Value<'a> { + Value::from_serde(v) + } +} + +#[cfg(feature = "kv")] +pub use self::kv_support::*; diff --git a/src/kv/error.rs b/src/kv/error.rs index 9643a47f2..7efa5af36 100644 --- a/src/kv/error.rs +++ b/src/kv/error.rs @@ -11,7 +11,8 @@ enum Inner { #[cfg(feature = "std")] Boxed(std_support::BoxedError), Msg(&'static str), - Value(value_bag::Error), + #[cfg(feature = "value-bag")] + Value(crate::kv::value::inner::Error), Fmt, } @@ -23,21 +24,23 @@ impl Error { } } - // Not public so we don't leak the `value_bag` API - pub(super) fn from_value(err: value_bag::Error) -> Self { + // Not public so we don't leak the `crate::kv::value::inner` API + #[cfg(feature = "value-bag")] + pub(super) fn from_value(err: crate::kv::value::inner::Error) -> Self { Error { inner: Inner::Value(err), } } - // Not public so we don't leak the `value_bag` API - pub(super) fn into_value(self) -> value_bag::Error { + // Not public so we don't leak the `crate::kv::value::inner` API + #[cfg(feature = "value-bag")] + pub(super) fn into_value(self) -> crate::kv::value::inner::Error { match self.inner { Inner::Value(err) => err, - #[cfg(feature = "kv_unstable_std")] - _ => value_bag::Error::boxed(self), - #[cfg(not(feature = "kv_unstable_std"))] - _ => value_bag::Error::msg("error inspecting a value"), + #[cfg(feature = "kv_std")] + _ => crate::kv::value::inner::Error::boxed(self), + #[cfg(not(feature = "kv_std"))] + _ => crate::kv::value::inner::Error::msg("error inspecting a value"), } } } @@ -48,6 +51,7 @@ impl fmt::Display for Error { match &self.inner { #[cfg(feature = "std")] Boxed(err) => err.fmt(f), + #[cfg(feature = "value-bag")] Value(err) => err.fmt(f), Msg(msg) => msg.fmt(f), Fmt => fmt::Error.fmt(f), diff --git a/src/kv/key.rs b/src/kv/key.rs index 858ec493a..9a64b956f 100644 --- a/src/kv/key.rs +++ b/src/kv/key.rs @@ -30,7 +30,7 @@ impl ToKey for str { } } -/// A key in a structured key-value pair. +/// A key in a key-value. // These impls must only be based on the as_str() representation of the key // If a new field (such as an optional index) is added to the key they must not affect comparison #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] @@ -93,7 +93,7 @@ mod std_support { } } -#[cfg(feature = "kv_unstable_sval")] +#[cfg(feature = "kv_sval")] mod sval_support { use super::*; @@ -116,7 +116,7 @@ mod sval_support { } } -#[cfg(feature = "kv_unstable_serde")] +#[cfg(feature = "kv_serde")] mod serde_support { use super::*; diff --git a/src/kv/mod.rs b/src/kv/mod.rs index 5dc69337c..1ccb82514 100644 --- a/src/kv/mod.rs +++ b/src/kv/mod.rs @@ -1,26 +1,265 @@ -//! **UNSTABLE:** Structured key-value pairs. +//! Structured logging. //! -//! This module is unstable and breaking changes may be made -//! at any time. See [the tracking issue](https://github.com/rust-lang-nursery/log/issues/328) -//! for more details. -//! -//! Add the `kv_unstable` feature to your `Cargo.toml` to enable +//! Add the `kv` feature to your `Cargo.toml` to enable //! this module: //! //! ```toml //! [dependencies.log] -//! features = ["kv_unstable"] +//! features = ["kv"] +//! ``` +//! +//! # Structured logging in `log` +//! +//! Structured logging enhances traditional text-based log records with user-defined +//! attributes. Structured logs can be analyzed using a variety of data processing +//! techniques, without needing to find and parse attributes from unstructured text first. +//! +//! In `log`, user-defined attributes are part of a [`Source`] on the log record. +//! Each attribute is a key-value; a pair of [`Key`] and [`Value`]. Keys are strings +//! and values are a datum of any type that can be formatted or serialized. Simple types +//! like strings, booleans, and numbers are supported, as well as arbitrarily complex +//! structures involving nested objects and sequences. +//! +//! ## Adding key-values to log records +//! +//! Key-values appear before the message format in the `log!` macros: +//! +//! ``` +//! # use log::info; +//! info!(a = 1; "Something of interest"); +//! ``` +//! +//! Key-values support the same shorthand identifer syntax as `format_args`: +//! +//! ``` +//! # use log::info; +//! let a = 1; +//! +//! info!(a; "Something of interest"); +//! ``` +//! +//! Values are capturing using the [`ToValue`] trait by default. To capture a value +//! using a different trait implementation, use a modifier after its key. Here's how +//! the same example can capture `a` using its `Debug` implementation instead: +//! +//! ``` +//! # use log::info; +//! info!(a:? = 1; "Something of interest"); +//! ``` +//! +//! The following capturing modifiers are supported: +//! +//! - `:?` will capture the value using `Debug`. +//! - `:debug` will capture the value using `Debug`. +//! - `:%` will capture the value using `Display`. +//! - `:display` will capture the value using `Display`. +//! - `:err` will capture the value using `std::error::Error` (requires the `kv_std` feature). +//! - `:sval` will capture the value using `sval::Value` (requires the `kv_sval` feature). +//! - `:serde` will capture the value using `serde::Serialize` (requires the `kv_serde` feature). +//! +//! ## Working with key-values on log records +//! +//! Use the [`Record::key_values`](../struct.Record.html#method.key_values) method to access key-values. +//! +//! Individual values can be pulled from the source by their key: +//! +//! ``` +//! # fn main() -> Result<(), log::kv::Error> { +//! use log::kv::{Source, Key, Value}; +//! # let record = log::Record::builder().key_values(&[("a", 1)]).build(); +//! +//! // info!(a = 1; "Something of interest"); +//! +//! let a: Value = record.key_values().get(Key::from("a")).unwrap(); +//! assert_eq!(1, a.to_i64().unwrap()); +//! # Ok(()) +//! # } +//! ``` +//! +//! All key-values can also be enumerated using a [`VisitSource`]: +//! +//! ``` +//! # fn main() -> Result<(), log::kv::Error> { +//! use std::collections::BTreeMap; +//! +//! use log::kv::{self, Source, Key, Value, VisitSource}; +//! +//! struct Collect<'kvs>(BTreeMap<Key<'kvs>, Value<'kvs>>); +//! +//! impl<'kvs> VisitSource<'kvs> for Collect<'kvs> { +//! fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), kv::Error> { +//! self.0.insert(key, value); +//! +//! Ok(()) +//! } +//! } +//! +//! let mut visitor = Collect(BTreeMap::new()); +//! +//! # let record = log::Record::builder().key_values(&[("a", 1), ("b", 2), ("c", 3)]).build(); +//! // info!(a = 1, b = 2, c = 3; "Something of interest"); +//! +//! record.key_values().visit(&mut visitor)?; +//! +//! let collected = visitor.0; +//! +//! assert_eq!( +//! vec!["a", "b", "c"], +//! collected +//! .keys() +//! .map(|k| k.as_str()) +//! .collect::<Vec<_>>(), +//! ); +//! # Ok(()) +//! # } +//! ``` +//! +//! [`Value`]s have methods for conversions to common types: +//! +//! ``` +//! # fn main() -> Result<(), log::kv::Error> { +//! use log::kv::{Source, Key}; +//! # let record = log::Record::builder().key_values(&[("a", 1)]).build(); +//! +//! // info!(a = 1; "Something of interest"); +//! +//! let a = record.key_values().get(Key::from("a")).unwrap(); +//! +//! assert_eq!(1, a.to_i64().unwrap()); +//! # Ok(()) +//! # } +//! ``` +//! +//! Values also have their own [`VisitValue`] type. Value visitors are a lightweight +//! API for working with primitives types: +//! +//! ``` +//! # fn main() -> Result<(), log::kv::Error> { +//! use log::kv::{self, Source, Key, VisitValue}; +//! # let record = log::Record::builder().key_values(&[("a", 1)]).build(); +//! +//! struct IsNumeric(bool); +//! +//! impl<'kvs> VisitValue<'kvs> for IsNumeric { +//! fn visit_any(&mut self, _value: kv::Value) -> Result<(), kv::Error> { +//! self.0 = false; +//! Ok(()) +//! } +//! +//! fn visit_u64(&mut self, _value: u64) -> Result<(), kv::Error> { +//! self.0 = true; +//! Ok(()) +//! } +//! +//! fn visit_i64(&mut self, _value: i64) -> Result<(), kv::Error> { +//! self.0 = true; +//! Ok(()) +//! } +//! +//! fn visit_u128(&mut self, _value: u128) -> Result<(), kv::Error> { +//! self.0 = true; +//! Ok(()) +//! } +//! +//! fn visit_i128(&mut self, _value: i128) -> Result<(), kv::Error> { +//! self.0 = true; +//! Ok(()) +//! } +//! +//! fn visit_f64(&mut self, _value: f64) -> Result<(), kv::Error> { +//! self.0 = true; +//! Ok(()) +//! } +//! } +//! +//! // info!(a = 1; "Something of interest"); +//! +//! let a = record.key_values().get(Key::from("a")).unwrap(); +//! +//! let mut visitor = IsNumeric(false); +//! +//! a.visit(&mut visitor)?; +//! +//! let is_numeric = visitor.0; +//! +//! assert!(is_numeric); +//! # Ok(()) +//! # } +//! ``` +//! +//! To serialize a value to a format like JSON, you can also use either `serde` or `sval`: +//! +//! ``` +//! # fn main() -> Result<(), Box<dyn std::error::Error>> { +//! # #[cfg(feature = "serde")] +//! # { +//! # use log::kv::Key; +//! #[derive(serde::Serialize)] +//! struct Data { +//! a: i32, b: bool, +//! c: &'static str, +//! } +//! +//! let data = Data { a: 1, b: true, c: "Some data" }; +//! +//! # let source = [("a", log::kv::Value::from_serde(&data))]; +//! # let record = log::Record::builder().key_values(&source).build(); +//! // info!(a = data; "Something of interest"); +//! +//! let a = record.key_values().get(Key::from("a")).unwrap(); +//! +//! assert_eq!("{\"a\":1,\"b\":true,\"c\":\"Some data\"}", serde_json::to_string(&a)?); +//! # } +//! # Ok(()) +//! # } +//! ``` +//! +//! The choice of serialization framework depends on the needs of the consumer. +//! If you're in a no-std environment, you can use `sval`. In other cases, you can use `serde`. +//! Log producers and log consumers don't need to agree on the serialization framework. +//! A value can be captured using its `serde::Serialize` implementation and still be serialized +//! through `sval` without losing any structure or data. +//! +//! Values can also always be formatted using the standard `Debug` and `Display` +//! traits: +//! +//! ``` +//! # use log::kv::Key; +//! # #[derive(Debug)] +//! struct Data { +//! a: i32, +//! b: bool, +//! c: &'static str, +//! } +//! +//! let data = Data { a: 1, b: true, c: "Some data" }; +//! +//! # let source = [("a", log::kv::Value::from_debug(&data))]; +//! # let record = log::Record::builder().key_values(&source).build(); +//! // info!(a = data; "Something of interest"); +//! +//! let a = record.key_values().get(Key::from("a")).unwrap(); +//! +//! assert_eq!("Data { a: 1, b: true, c: \"Some data\" }", format!("{a:?}")); //! ``` mod error; mod key; -pub mod source; -pub mod value; +#[cfg(not(feature = "kv_unstable"))] +mod source; +#[cfg(not(feature = "kv_unstable"))] +mod value; pub use self::error::Error; pub use self::key::{Key, ToKey}; -pub use self::source::{Source, Visitor}; +pub use self::source::{Source, VisitSource}; +pub use self::value::{ToValue, Value, VisitValue}; + +#[cfg(feature = "kv_unstable")] +pub mod source; +#[cfg(feature = "kv_unstable")] +pub mod value; -#[doc(inline)] -pub use self::value::{ToValue, Value}; +#[cfg(feature = "kv_unstable")] +pub use self::source::Visitor; diff --git a/src/kv/source.rs b/src/kv/source.rs index 9c56f8b76..0ca267ce3 100644 --- a/src/kv/source.rs +++ b/src/kv/source.rs @@ -1,25 +1,65 @@ -//! Sources for key-value pairs. +//! Sources for key-values. +//! +//! This module defines the [`Source`] type and supporting APIs for +//! working with collections of key-values. use crate::kv::{Error, Key, ToKey, ToValue, Value}; use std::fmt; -/// A source of key-value pairs. +/// A source of key-values. /// /// The source may be a single pair, a set of pairs, or a filter over a set of pairs. -/// Use the [`Visitor`](trait.Visitor.html) trait to inspect the structured data +/// Use the [`VisitSource`](trait.VisitSource.html) trait to inspect the structured data /// in a source. +/// +/// A source is like an iterator over its key-values, except with a push-based API +/// instead of a pull-based one. +/// +/// # Examples +/// +/// Enumerating the key-values in a source: +/// +/// ``` +/// # fn main() -> Result<(), log::kv::Error> { +/// use log::kv::{self, Source, Key, Value, VisitSource}; +/// +/// // A `VisitSource` that prints all key-values +/// // VisitSources are fed the key-value pairs of each key-values +/// struct Printer; +/// +/// impl<'kvs> VisitSource<'kvs> for Printer { +/// fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), kv::Error> { +/// println!("{key}: {value}"); +/// +/// Ok(()) +/// } +/// } +/// +/// // A source with 3 key-values +/// // Common collection types implement the `Source` trait +/// let source = &[ +/// ("a", 1), +/// ("b", 2), +/// ("c", 3), +/// ]; +/// +/// // Pass an instance of the `VisitSource` to a `Source` to visit it +/// source.visit(&mut Printer)?; +/// # Ok(()) +/// # } +/// ``` pub trait Source { - /// Visit key-value pairs. + /// Visit key-values. /// - /// A source doesn't have to guarantee any ordering or uniqueness of key-value pairs. + /// A source doesn't have to guarantee any ordering or uniqueness of key-values. /// If the given visitor returns an error then the source may early-return with it, - /// even if there are more key-value pairs. + /// even if there are more key-values. /// /// # Implementation notes /// - /// A source should yield the same key-value pairs to a subsequent visitor unless + /// A source should yield the same key-values to a subsequent visitor unless /// that visitor itself fails. - fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error>; + fn visit<'kvs>(&'kvs self, visitor: &mut dyn VisitSource<'kvs>) -> Result<(), Error>; /// Get the value for a given key. /// @@ -34,15 +74,14 @@ pub trait Source { get_default(self, key) } - /// Count the number of key-value pairs that can be visited. + /// Count the number of key-values that can be visited. /// /// # Implementation notes /// - /// A source that knows the number of key-value pairs upfront may provide a more + /// A source that knows the number of key-values upfront may provide a more /// efficient implementation. /// - /// A subsequent call to `visit` should yield the same number of key-value pairs - /// to the visitor, unless that visitor fails part way through. + /// A subsequent call to `visit` should yield the same number of key-values. fn count(&self) -> usize { count_default(self) } @@ -55,7 +94,7 @@ fn get_default<'v>(source: &'v (impl Source + ?Sized), key: Key) -> Option<Value found: Option<Value<'v>>, } - impl<'k, 'kvs> Visitor<'kvs> for Get<'k, 'kvs> { + impl<'k, 'kvs> VisitSource<'kvs> for Get<'k, 'kvs> { fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> { if self.key == key { self.found = Some(value); @@ -75,7 +114,7 @@ fn get_default<'v>(source: &'v (impl Source + ?Sized), key: Key) -> Option<Value fn count_default(source: impl Source) -> usize { struct Count(usize); - impl<'kvs> Visitor<'kvs> for Count { + impl<'kvs> VisitSource<'kvs> for Count { fn visit_pair(&mut self, _: Key<'kvs>, _: Value<'kvs>) -> Result<(), Error> { self.0 += 1; @@ -92,7 +131,7 @@ impl<'a, T> Source for &'a T where T: Source + ?Sized, { - fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { + fn visit<'kvs>(&'kvs self, visitor: &mut dyn VisitSource<'kvs>) -> Result<(), Error> { Source::visit(&**self, visitor) } @@ -110,7 +149,7 @@ where K: ToKey, V: ToValue, { - fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { + fn visit<'kvs>(&'kvs self, visitor: &mut dyn VisitSource<'kvs>) -> Result<(), Error> { visitor.visit_pair(self.0.to_key(), self.1.to_value()) } @@ -131,7 +170,7 @@ impl<S> Source for [S] where S: Source, { - fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { + fn visit<'kvs>(&'kvs self, visitor: &mut dyn VisitSource<'kvs>) -> Result<(), Error> { for source in self { source.visit(visitor)?; } @@ -154,11 +193,28 @@ where } } +impl<const N: usize, S> Source for [S; N] +where + S: Source, +{ + fn visit<'kvs>(&'kvs self, visitor: &mut dyn VisitSource<'kvs>) -> Result<(), Error> { + Source::visit(self as &[_], visitor) + } + + fn get(&self, key: Key) -> Option<Value<'_>> { + Source::get(self as &[_], key) + } + + fn count(&self) -> usize { + Source::count(self as &[_]) + } +} + impl<S> Source for Option<S> where S: Source, { - fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { + fn visit<'kvs>(&'kvs self, visitor: &mut dyn VisitSource<'kvs>) -> Result<(), Error> { if let Some(source) = self { source.visit(visitor)?; } @@ -176,42 +232,42 @@ where } /// A visitor for the key-value pairs in a [`Source`](trait.Source.html). -pub trait Visitor<'kvs> { +pub trait VisitSource<'kvs> { /// Visit a key-value pair. fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error>; } -impl<'a, 'kvs, T> Visitor<'kvs> for &'a mut T +impl<'a, 'kvs, T> VisitSource<'kvs> for &'a mut T where - T: Visitor<'kvs> + ?Sized, + T: VisitSource<'kvs> + ?Sized, { fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> { (**self).visit_pair(key, value) } } -impl<'a, 'b: 'a, 'kvs> Visitor<'kvs> for fmt::DebugMap<'a, 'b> { +impl<'a, 'b: 'a, 'kvs> VisitSource<'kvs> for fmt::DebugMap<'a, 'b> { fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> { self.entry(&key, &value); Ok(()) } } -impl<'a, 'b: 'a, 'kvs> Visitor<'kvs> for fmt::DebugList<'a, 'b> { +impl<'a, 'b: 'a, 'kvs> VisitSource<'kvs> for fmt::DebugList<'a, 'b> { fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> { self.entry(&(key, value)); Ok(()) } } -impl<'a, 'b: 'a, 'kvs> Visitor<'kvs> for fmt::DebugSet<'a, 'b> { +impl<'a, 'b: 'a, 'kvs> VisitSource<'kvs> for fmt::DebugSet<'a, 'b> { fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> { self.entry(&(key, value)); Ok(()) } } -impl<'a, 'b: 'a, 'kvs> Visitor<'kvs> for fmt::DebugTuple<'a, 'b> { +impl<'a, 'b: 'a, 'kvs> VisitSource<'kvs> for fmt::DebugTuple<'a, 'b> { fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> { self.field(&key); self.field(&value); @@ -232,7 +288,7 @@ mod std_support { where S: Source + ?Sized, { - fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { + fn visit<'kvs>(&'kvs self, visitor: &mut dyn VisitSource<'kvs>) -> Result<(), Error> { Source::visit(&**self, visitor) } @@ -249,7 +305,7 @@ mod std_support { where S: Source + ?Sized, { - fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { + fn visit<'kvs>(&'kvs self, visitor: &mut dyn VisitSource<'kvs>) -> Result<(), Error> { Source::visit(&**self, visitor) } @@ -266,7 +322,7 @@ mod std_support { where S: Source + ?Sized, { - fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { + fn visit<'kvs>(&'kvs self, visitor: &mut dyn VisitSource<'kvs>) -> Result<(), Error> { Source::visit(&**self, visitor) } @@ -283,7 +339,7 @@ mod std_support { where S: Source, { - fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { + fn visit<'kvs>(&'kvs self, visitor: &mut dyn VisitSource<'kvs>) -> Result<(), Error> { Source::visit(&**self, visitor) } @@ -296,9 +352,9 @@ mod std_support { } } - impl<'kvs, V> Visitor<'kvs> for Box<V> + impl<'kvs, V> VisitSource<'kvs> for Box<V> where - V: Visitor<'kvs> + ?Sized, + V: VisitSource<'kvs> + ?Sized, { fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> { (**self).visit_pair(key, value) @@ -311,7 +367,7 @@ mod std_support { V: ToValue, S: BuildHasher, { - fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { + fn visit<'kvs>(&'kvs self, visitor: &mut dyn VisitSource<'kvs>) -> Result<(), Error> { for (key, value) in self { visitor.visit_pair(key.to_key(), value.to_value())?; } @@ -332,7 +388,7 @@ mod std_support { K: ToKey + Borrow<str> + Ord, V: ToValue, { - fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { + fn visit<'kvs>(&'kvs self, visitor: &mut dyn VisitSource<'kvs>) -> Result<(), Error> { for (key, value) in self { visitor.visit_pair(key.to_key(), value.to_value())?; } @@ -352,7 +408,7 @@ mod std_support { mod tests { use std::collections::{BTreeMap, HashMap}; - use crate::kv::value::tests::Token; + use crate::kv::value; use super::*; @@ -366,7 +422,7 @@ mod std_support { fn get() { let source = vec![("a", 1), ("b", 2), ("a", 1)]; assert_eq!( - Token::I64(1), + value::inner::Token::I64(1), Source::get(&source, Key::from_str("a")).unwrap().to_token() ); @@ -382,7 +438,7 @@ mod std_support { assert_eq!(2, Source::count(&map)); assert_eq!( - Token::I64(1), + value::inner::Token::I64(1), Source::get(&map, Key::from_str("a")).unwrap().to_token() ); } @@ -395,16 +451,20 @@ mod std_support { assert_eq!(2, Source::count(&map)); assert_eq!( - Token::I64(1), + value::inner::Token::I64(1), Source::get(&map, Key::from_str("a")).unwrap().to_token() ); } } } +// NOTE: Deprecated; but aliases can't carry this attribute +#[cfg(feature = "kv_unstable")] +pub use VisitSource as Visitor; + #[cfg(test)] mod tests { - use crate::kv::value::tests::Token; + use crate::kv::value; use super::*; @@ -415,7 +475,7 @@ mod tests { #[test] fn visitor_is_object_safe() { - fn _check(_: &dyn Visitor) {} + fn _check(_: &dyn VisitSource) {} } #[test] @@ -426,7 +486,7 @@ mod tests { } impl Source for OnePair { - fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> { + fn visit<'kvs>(&'kvs self, visitor: &mut dyn VisitSource<'kvs>) -> Result<(), Error> { visitor.visit_pair(self.key.to_key(), self.value.to_value()) } } @@ -441,11 +501,11 @@ mod tests { fn get() { let source = &[("a", 1), ("b", 2), ("a", 1)] as &[_]; assert_eq!( - Token::I64(1), + value::inner::Token::I64(1), Source::get(source, Key::from_str("a")).unwrap().to_token() ); assert_eq!( - Token::I64(2), + value::inner::Token::I64(2), Source::get(source, Key::from_str("b")).unwrap().to_token() ); assert!(Source::get(&source, Key::from_str("c")).is_none()); diff --git a/src/kv/value.rs b/src/kv/value.rs index 1c39bef0a..1511dd02e 100644 --- a/src/kv/value.rs +++ b/src/kv/value.rs @@ -1,11 +1,12 @@ //! Structured values. +//! +//! This module defines the [`Value`] type and supporting APIs for +//! capturing and serializing them. use std::fmt; pub use crate::kv::Error; -use value_bag::ValueBag; - /// A type that can be converted into a [`Value`](struct.Value.html). pub trait ToValue { /// Perform the conversion. @@ -29,77 +30,21 @@ impl<'v> ToValue for Value<'v> { } } -/// Get a value from a type implementing `std::fmt::Debug`. -#[macro_export] -macro_rules! as_debug { - ($capture:expr) => { - $crate::kv::Value::from_debug(&$capture) - }; -} - -/// Get a value from a type implementing `std::fmt::Display`. -#[macro_export] -macro_rules! as_display { - ($capture:expr) => { - $crate::kv::Value::from_display(&$capture) - }; -} - -/// Get a value from an error. -#[cfg(feature = "kv_unstable_std")] -#[macro_export] -macro_rules! as_error { - ($capture:expr) => { - $crate::kv::Value::from_dyn_error(&$capture) - }; -} - -#[cfg(feature = "kv_unstable_serde")] -/// Get a value from a type implementing `serde::Serialize`. -#[macro_export] -macro_rules! as_serde { - ($capture:expr) => { - $crate::kv::Value::from_serde(&$capture) - }; -} - -/// Get a value from a type implementing `sval::Value`. -#[cfg(feature = "kv_unstable_sval")] -#[macro_export] -macro_rules! as_sval { - ($capture:expr) => { - $crate::kv::Value::from_sval(&$capture) - }; -} - -/// A value in a structured key-value pair. +/// A value in a key-value. +/// +/// Values are an anonymous bag containing some structured datum. /// /// # Capturing values /// /// There are a few ways to capture a value: /// -/// - Using the `Value::capture_*` methods. /// - Using the `Value::from_*` methods. /// - Using the `ToValue` trait. /// - Using the standard `From` trait. /// -/// ## Using the `Value::capture_*` methods -/// -/// `Value` offers a few constructor methods that capture values of different kinds. -/// These methods require a `T: 'static` to support downcasting. -/// -/// ``` -/// use log::kv::Value; -/// -/// let value = Value::capture_debug(&42i32); -/// -/// assert_eq!(Some(42), value.to_i64()); -/// ``` -/// /// ## Using the `Value::from_*` methods /// /// `Value` offers a few constructor methods that capture values of different kinds. -/// These methods don't require `T: 'static`, but can't support downcasting. /// /// ``` /// use log::kv::Value; @@ -133,19 +78,45 @@ macro_rules! as_sval { /// assert_eq!(Some(42), value.to_i64()); /// ``` /// +/// # Data model +/// +/// Values can hold one of a number of types: +/// +/// - **Null:** The absence of any other meaningful value. Note that +/// `Some(Value::null())` is not the same as `None`. The former is +/// `null` while the latter is `undefined`. This is important to be +/// able to tell the difference between a key-value that was logged, +/// but its value was empty (`Some(Value::null())`) and a key-value +/// that was never logged at all (`None`). +/// - **Strings:** `str`, `char`. +/// - **Booleans:** `bool`. +/// - **Integers:** `u8`-`u128`, `i8`-`i128`, `NonZero*`. +/// - **Floating point numbers:** `f32`-`f64`. +/// - **Errors:** `dyn (Error + 'static)`. +/// - **`serde`:** Any type in `serde`'s data model. +/// - **`sval`:** Any type in `sval`'s data model. +/// /// # Serialization /// -/// `Value` provides a number of ways to be serialized. +/// Values provide a number of ways to be serialized. /// /// For basic types the [`Value::visit`] method can be used to extract the /// underlying typed value. However this is limited in the amount of types -/// supported (see the [`Visit`] trait methods). +/// supported (see the [`VisitValue`] trait methods). /// /// For more complex types one of the following traits can be used: -/// * [`sval::Value`], requires the `kv_unstable_sval` feature. -/// * [`serde::Serialize`], requires the `kv_unstable_serde` feature. +/// * `sval::Value`, requires the `kv_sval` feature. +/// * `serde::Serialize`, requires the `kv_serde` feature. +/// +/// You don't need a visitor to serialize values through `serde` or `sval`. +/// +/// A value can always be serialized using any supported framework, regardless +/// of how it was captured. If, for example, a value was captured using its +/// `Display` implementation, it will serialize through `serde` as a string. If it was +/// captured as a struct using `serde`, it will also serialize as a struct +/// through `sval`, or can be formatted using a `Debug`-compatible representation. pub struct Value<'v> { - inner: ValueBag<'v>, + inner: inner::Inner<'v>, } impl<'v> Value<'v> { @@ -157,66 +128,13 @@ impl<'v> Value<'v> { value.to_value() } - /// Get a value from a type implementing `std::fmt::Debug`. - pub fn capture_debug<T>(value: &'v T) -> Self - where - T: fmt::Debug + 'static, - { - Value { - inner: ValueBag::capture_debug(value), - } - } - - /// Get a value from a type implementing `std::fmt::Display`. - pub fn capture_display<T>(value: &'v T) -> Self - where - T: fmt::Display + 'static, - { - Value { - inner: ValueBag::capture_display(value), - } - } - - /// Get a value from an error. - #[cfg(feature = "kv_unstable_std")] - pub fn capture_error<T>(err: &'v T) -> Self - where - T: std::error::Error + 'static, - { - Value { - inner: ValueBag::capture_error(err), - } - } - - #[cfg(feature = "kv_unstable_serde")] - /// Get a value from a type implementing `serde::Serialize`. - pub fn capture_serde<T>(value: &'v T) -> Self - where - T: serde::Serialize + 'static, - { - Value { - inner: ValueBag::capture_serde1(value), - } - } - - /// Get a value from a type implementing `sval::Value`. - #[cfg(feature = "kv_unstable_sval")] - pub fn capture_sval<T>(value: &'v T) -> Self - where - T: sval::Value + 'static, - { - Value { - inner: ValueBag::capture_sval2(value), - } - } - /// Get a value from a type implementing `std::fmt::Debug`. pub fn from_debug<T>(value: &'v T) -> Self where T: fmt::Debug, { Value { - inner: ValueBag::from_debug(value), + inner: inner::Inner::from_debug(value), } } @@ -226,144 +144,77 @@ impl<'v> Value<'v> { T: fmt::Display, { Value { - inner: ValueBag::from_display(value), + inner: inner::Inner::from_display(value), } } /// Get a value from a type implementing `serde::Serialize`. - #[cfg(feature = "kv_unstable_serde")] + #[cfg(feature = "kv_serde")] pub fn from_serde<T>(value: &'v T) -> Self where T: serde::Serialize, { Value { - inner: ValueBag::from_serde1(value), + inner: inner::Inner::from_serde1(value), } } /// Get a value from a type implementing `sval::Value`. - #[cfg(feature = "kv_unstable_sval")] + #[cfg(feature = "kv_sval")] pub fn from_sval<T>(value: &'v T) -> Self where T: sval::Value, { Value { - inner: ValueBag::from_sval2(value), + inner: inner::Inner::from_sval2(value), } } /// Get a value from a dynamic `std::fmt::Debug`. pub fn from_dyn_debug(value: &'v dyn fmt::Debug) -> Self { Value { - inner: ValueBag::from_dyn_debug(value), + inner: inner::Inner::from_dyn_debug(value), } } /// Get a value from a dynamic `std::fmt::Display`. pub fn from_dyn_display(value: &'v dyn fmt::Display) -> Self { Value { - inner: ValueBag::from_dyn_display(value), + inner: inner::Inner::from_dyn_display(value), } } /// Get a value from a dynamic error. - #[cfg(feature = "kv_unstable_std")] + #[cfg(feature = "kv_std")] pub fn from_dyn_error(err: &'v (dyn std::error::Error + 'static)) -> Self { Value { - inner: ValueBag::from_dyn_error(err), + inner: inner::Inner::from_dyn_error(err), + } + } + + /// Get a `null` value. + pub fn null() -> Self { + Value { + inner: inner::Inner::empty(), } } /// Get a value from an internal primitive. - fn from_value_bag<T>(value: T) -> Self + fn from_inner<T>(value: T) -> Self where - T: Into<ValueBag<'v>>, + T: Into<inner::Inner<'v>>, { Value { inner: value.into(), } } - /// Check whether this value can be downcast to `T`. - pub fn is<T: 'static>(&self) -> bool { - self.inner.is::<T>() - } - - /// Try downcast this value to `T`. - pub fn downcast_ref<T: 'static>(&self) -> Option<&T> { - self.inner.downcast_ref::<T>() - } - /// Inspect this value using a simple visitor. - pub fn visit(&self, visitor: impl Visit<'v>) -> Result<(), Error> { - struct Visitor<V>(V); - - impl<'v, V> value_bag::visit::Visit<'v> for Visitor<V> - where - V: Visit<'v>, - { - fn visit_any(&mut self, value: ValueBag) -> Result<(), value_bag::Error> { - self.0 - .visit_any(Value { inner: value }) - .map_err(Error::into_value) - } - - fn visit_u64(&mut self, value: u64) -> Result<(), value_bag::Error> { - self.0.visit_u64(value).map_err(Error::into_value) - } - - fn visit_i64(&mut self, value: i64) -> Result<(), value_bag::Error> { - self.0.visit_i64(value).map_err(Error::into_value) - } - - fn visit_u128(&mut self, value: u128) -> Result<(), value_bag::Error> { - self.0.visit_u128(value).map_err(Error::into_value) - } - - fn visit_i128(&mut self, value: i128) -> Result<(), value_bag::Error> { - self.0.visit_i128(value).map_err(Error::into_value) - } - - fn visit_f64(&mut self, value: f64) -> Result<(), value_bag::Error> { - self.0.visit_f64(value).map_err(Error::into_value) - } - - fn visit_bool(&mut self, value: bool) -> Result<(), value_bag::Error> { - self.0.visit_bool(value).map_err(Error::into_value) - } - - fn visit_str(&mut self, value: &str) -> Result<(), value_bag::Error> { - self.0.visit_str(value).map_err(Error::into_value) - } - - fn visit_borrowed_str(&mut self, value: &'v str) -> Result<(), value_bag::Error> { - self.0.visit_borrowed_str(value).map_err(Error::into_value) - } - - fn visit_char(&mut self, value: char) -> Result<(), value_bag::Error> { - self.0.visit_char(value).map_err(Error::into_value) - } - - #[cfg(feature = "kv_unstable_std")] - fn visit_error( - &mut self, - err: &(dyn std::error::Error + 'static), - ) -> Result<(), value_bag::Error> { - self.0.visit_error(err).map_err(Error::into_value) - } - - #[cfg(feature = "kv_unstable_std")] - fn visit_borrowed_error( - &mut self, - err: &'v (dyn std::error::Error + 'static), - ) -> Result<(), value_bag::Error> { - self.0.visit_borrowed_error(err).map_err(Error::into_value) - } - } - - self.inner - .visit(&mut Visitor(visitor)) - .map_err(Error::from_value) + /// + /// When the `kv_serde` or `kv_sval` features are enabled, you can also + /// serialize a value using its `Serialize` or `Value` implementation. + pub fn visit(&self, visitor: impl VisitValue<'v>) -> Result<(), Error> { + inner::visit(&self.inner, visitor) } } @@ -379,7 +230,7 @@ impl<'v> fmt::Display for Value<'v> { } } -#[cfg(feature = "kv_unstable_serde")] +#[cfg(feature = "kv_serde")] impl<'v> serde::Serialize for Value<'v> { fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error> where @@ -389,14 +240,14 @@ impl<'v> serde::Serialize for Value<'v> { } } -#[cfg(feature = "kv_unstable_sval")] +#[cfg(feature = "kv_sval")] impl<'v> sval::Value for Value<'v> { fn stream<'sval, S: sval::Stream<'sval> + ?Sized>(&'sval self, stream: &mut S) -> sval::Result { sval::Value::stream(&self.inner, stream) } } -#[cfg(feature = "kv_unstable_sval")] +#[cfg(feature = "kv_sval")] impl<'v> sval_ref::ValueRef<'v> for Value<'v> { fn stream_ref<S: sval::Stream<'v> + ?Sized>(&self, stream: &mut S) -> sval::Result { sval_ref::ValueRef::stream_ref(&self.inner, stream) @@ -409,65 +260,15 @@ impl ToValue for str { } } -impl ToValue for u128 { - fn to_value(&self) -> Value { - Value::from(self) - } -} - -impl ToValue for i128 { - fn to_value(&self) -> Value { - Value::from(self) - } -} - -impl ToValue for std::num::NonZeroU128 { - fn to_value(&self) -> Value { - Value::from(self) - } -} - -impl ToValue for std::num::NonZeroI128 { - fn to_value(&self) -> Value { - Value::from(self) - } -} - impl<'v> From<&'v str> for Value<'v> { fn from(value: &'v str) -> Self { - Value::from_value_bag(value) - } -} - -impl<'v> From<&'v u128> for Value<'v> { - fn from(value: &'v u128) -> Self { - Value::from_value_bag(value) - } -} - -impl<'v> From<&'v i128> for Value<'v> { - fn from(value: &'v i128) -> Self { - Value::from_value_bag(value) - } -} - -impl<'v> From<&'v std::num::NonZeroU128> for Value<'v> { - fn from(v: &'v std::num::NonZeroU128) -> Value<'v> { - // SAFETY: `NonZeroU128` and `u128` have the same ABI - Value::from_value_bag(unsafe { &*(v as *const std::num::NonZeroU128 as *const u128) }) - } -} - -impl<'v> From<&'v std::num::NonZeroI128> for Value<'v> { - fn from(v: &'v std::num::NonZeroI128) -> Value<'v> { - // SAFETY: `NonZeroI128` and `i128` have the same ABI - Value::from_value_bag(unsafe { &*(v as *const std::num::NonZeroI128 as *const i128) }) + Value::from_inner(value) } } impl ToValue for () { fn to_value(&self) -> Value { - Value::from_value_bag(()) + Value::from_inner(()) } } @@ -478,7 +279,7 @@ where fn to_value(&self) -> Value { match *self { Some(ref value) => value.to_value(), - None => Value::from_value_bag(()), + None => Value::from_inner(()), } } } @@ -494,7 +295,13 @@ macro_rules! impl_to_value_primitive { impl<'v> From<$into_ty> for Value<'v> { fn from(value: $into_ty) -> Self { - Value::from_value_bag(value) + Value::from_inner(value) + } + } + + impl<'v> From<&'v $into_ty> for Value<'v> { + fn from(value: &'v $into_ty) -> Self { + Value::from_inner(*value) } } )* @@ -515,6 +322,12 @@ macro_rules! impl_to_value_nonzero_primitive { Value::from(value.get()) } } + + impl<'v> From<&'v std::num::$into_ty> for Value<'v> { + fn from(value: &'v std::num::$into_ty) -> Self { + Value::from(value.get()) + } + } )* }; } @@ -532,12 +345,14 @@ macro_rules! impl_value_to_primitive { } } -impl_to_value_primitive![usize, u8, u16, u32, u64, isize, i8, i16, i32, i64, f32, f64, char, bool,]; +impl_to_value_primitive![ + usize, u8, u16, u32, u64, u128, isize, i8, i16, i32, i64, i128, f32, f64, char, bool, +]; #[rustfmt::skip] impl_to_value_nonzero_primitive![ - NonZeroUsize, NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, - NonZeroIsize, NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, + NonZeroUsize, NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, + NonZeroIsize, NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, ]; impl_value_to_primitive![ @@ -559,7 +374,7 @@ impl_value_to_primitive![ impl<'v> Value<'v> { /// Try convert this value into an error. - #[cfg(feature = "kv_unstable_std")] + #[cfg(feature = "kv_std")] pub fn to_borrowed_error(&self) -> Option<&(dyn std::error::Error + 'static)> { self.inner.to_borrowed_error() } @@ -570,7 +385,7 @@ impl<'v> Value<'v> { } } -#[cfg(feature = "kv_unstable_std")] +#[cfg(feature = "kv_std")] mod std_support { use std::borrow::Cow; use std::rc::Rc; @@ -631,20 +446,32 @@ mod std_support { } } -/// A visitor for a `Value`. +/// A visitor for a [`Value`]. /// -/// Also see [`Value`'s documentation on seralization]. +/// Also see [`Value`'s documentation on seralization]. Value visitors are a simple alternative +/// to a more fully-featured serialization framework like `serde` or `sval`. A value visitor +/// can differentiate primitive types through methods like [`VisitValue::visit_bool`] and +/// [`VisitValue::visit_str`], but more complex types like maps and sequences +/// will fallthrough to [`VisitValue::visit_any`]. +/// +/// If you're trying to serialize a value to a format like JSON, you can use either `serde` +/// or `sval` directly with the value. You don't need a visitor. /// /// [`Value`'s documentation on seralization]: Value#serialization -pub trait Visit<'v> { +pub trait VisitValue<'v> { /// Visit a `Value`. /// - /// This is the only required method on `Visit` and acts as a fallback for any + /// This is the only required method on `VisitValue` and acts as a fallback for any /// more specific methods that aren't overridden. /// The `Value` may be formatted using its `fmt::Debug` or `fmt::Display` implementation, /// or serialized using its `sval::Value` or `serde::Serialize` implementation. fn visit_any(&mut self, value: Value) -> Result<(), Error>; + /// Visit an empty value. + fn visit_null(&mut self) -> Result<(), Error> { + self.visit_any(Value::null()) + } + /// Visit an unsigned integer. fn visit_u64(&mut self, value: u64) -> Result<(), Error> { self.visit_any(value.into()) @@ -657,12 +484,12 @@ pub trait Visit<'v> { /// Visit a big unsigned integer. fn visit_u128(&mut self, value: u128) -> Result<(), Error> { - self.visit_any((&value).into()) + self.visit_any((value).into()) } /// Visit a big signed integer. fn visit_i128(&mut self, value: i128) -> Result<(), Error> { - self.visit_any((&value).into()) + self.visit_any((value).into()) } /// Visit a floating point. @@ -692,13 +519,13 @@ pub trait Visit<'v> { } /// Visit an error. - #[cfg(feature = "kv_unstable_std")] + #[cfg(feature = "kv_std")] fn visit_error(&mut self, err: &(dyn std::error::Error + 'static)) -> Result<(), Error> { self.visit_any(Value::from_dyn_error(err)) } /// Visit an error. - #[cfg(feature = "kv_unstable_std")] + #[cfg(feature = "kv_std")] fn visit_borrowed_error( &mut self, err: &'v (dyn std::error::Error + 'static), @@ -707,14 +534,18 @@ pub trait Visit<'v> { } } -impl<'a, 'v, T: ?Sized> Visit<'v> for &'a mut T +impl<'a, 'v, T: ?Sized> VisitValue<'v> for &'a mut T where - T: Visit<'v>, + T: VisitValue<'v>, { fn visit_any(&mut self, value: Value) -> Result<(), Error> { (**self).visit_any(value) } + fn visit_null(&mut self) -> Result<(), Error> { + (**self).visit_null() + } + fn visit_u64(&mut self, value: u64) -> Result<(), Error> { (**self).visit_u64(value) } @@ -751,12 +582,12 @@ where (**self).visit_char(value) } - #[cfg(feature = "kv_unstable_std")] + #[cfg(feature = "kv_std")] fn visit_error(&mut self, err: &(dyn std::error::Error + 'static)) -> Result<(), Error> { (**self).visit_error(err) } - #[cfg(feature = "kv_unstable_std")] + #[cfg(feature = "kv_std")] fn visit_borrowed_error( &mut self, err: &'v (dyn std::error::Error + 'static), @@ -765,13 +596,586 @@ where } } +#[cfg(feature = "value-bag")] +pub(in crate::kv) mod inner { + /** + An implementation of `Value` based on a library called `value_bag`. + + `value_bag` was written specifically for use in `log`'s value, but was split out when it outgrew + the codebase here. It's a general-purpose type-erasure library that handles mapping between + more fully-featured serialization frameworks. + */ + use super::*; + + pub use value_bag::ValueBag as Inner; + + pub use value_bag::Error; + + #[cfg(test)] + pub use value_bag::test::TestToken as Token; + + pub fn visit<'v>( + inner: &Inner<'v>, + visitor: impl VisitValue<'v>, + ) -> Result<(), crate::kv::Error> { + struct InnerVisitValue<V>(V); + + impl<'v, V> value_bag::visit::Visit<'v> for InnerVisitValue<V> + where + V: VisitValue<'v>, + { + fn visit_any(&mut self, value: value_bag::ValueBag) -> Result<(), Error> { + self.0 + .visit_any(Value { inner: value }) + .map_err(crate::kv::Error::into_value) + } + + fn visit_empty(&mut self) -> Result<(), Error> { + self.0.visit_null().map_err(crate::kv::Error::into_value) + } + + fn visit_u64(&mut self, value: u64) -> Result<(), Error> { + self.0 + .visit_u64(value) + .map_err(crate::kv::Error::into_value) + } + + fn visit_i64(&mut self, value: i64) -> Result<(), Error> { + self.0 + .visit_i64(value) + .map_err(crate::kv::Error::into_value) + } + + fn visit_u128(&mut self, value: u128) -> Result<(), Error> { + self.0 + .visit_u128(value) + .map_err(crate::kv::Error::into_value) + } + + fn visit_i128(&mut self, value: i128) -> Result<(), Error> { + self.0 + .visit_i128(value) + .map_err(crate::kv::Error::into_value) + } + + fn visit_f64(&mut self, value: f64) -> Result<(), Error> { + self.0 + .visit_f64(value) + .map_err(crate::kv::Error::into_value) + } + + fn visit_bool(&mut self, value: bool) -> Result<(), Error> { + self.0 + .visit_bool(value) + .map_err(crate::kv::Error::into_value) + } + + fn visit_str(&mut self, value: &str) -> Result<(), Error> { + self.0 + .visit_str(value) + .map_err(crate::kv::Error::into_value) + } + + fn visit_borrowed_str(&mut self, value: &'v str) -> Result<(), Error> { + self.0 + .visit_borrowed_str(value) + .map_err(crate::kv::Error::into_value) + } + + fn visit_char(&mut self, value: char) -> Result<(), Error> { + self.0 + .visit_char(value) + .map_err(crate::kv::Error::into_value) + } + + #[cfg(feature = "kv_std")] + fn visit_error( + &mut self, + err: &(dyn std::error::Error + 'static), + ) -> Result<(), Error> { + self.0 + .visit_error(err) + .map_err(crate::kv::Error::into_value) + } + + #[cfg(feature = "kv_std")] + fn visit_borrowed_error( + &mut self, + err: &'v (dyn std::error::Error + 'static), + ) -> Result<(), Error> { + self.0 + .visit_borrowed_error(err) + .map_err(crate::kv::Error::into_value) + } + } + + inner + .visit(&mut InnerVisitValue(visitor)) + .map_err(crate::kv::Error::from_value) + } +} + +#[cfg(not(feature = "value-bag"))] +pub(in crate::kv) mod inner { + /** + This is a dependency-free implementation of `Value` when there's no serialization frameworks involved. + In these simple cases a more fully featured solution like `value_bag` isn't needed, so we avoid pulling it in. + + There are a few things here that need to remain consistent with the `value_bag`-based implementation: + + 1. Conversions should always produce the same results. If a conversion here returns `Some`, then + the same `value_bag`-based conversion must also. Of particular note here are floats to ints; they're + based on the standard library's `TryInto` conversions, which need to be convert to `i32` or `u32`, + and then to `f64`. + 2. VisitValues should always be called in the same way. If a particular type of value calls `visit_i64`, + then the same `value_bag`-based visitor must also. + */ + use super::*; + + #[derive(Clone)] + pub enum Inner<'v> { + None, + Bool(bool), + Str(&'v str), + Char(char), + I64(i64), + U64(u64), + F64(f64), + I128(i128), + U128(u128), + Debug(&'v dyn fmt::Debug), + Display(&'v dyn fmt::Display), + } + + impl<'v> From<()> for Inner<'v> { + fn from(_: ()) -> Self { + Inner::None + } + } + + impl<'v> From<bool> for Inner<'v> { + fn from(v: bool) -> Self { + Inner::Bool(v) + } + } + + impl<'v> From<char> for Inner<'v> { + fn from(v: char) -> Self { + Inner::Char(v) + } + } + + impl<'v> From<f32> for Inner<'v> { + fn from(v: f32) -> Self { + Inner::F64(v as f64) + } + } + + impl<'v> From<f64> for Inner<'v> { + fn from(v: f64) -> Self { + Inner::F64(v) + } + } + + impl<'v> From<i8> for Inner<'v> { + fn from(v: i8) -> Self { + Inner::I64(v as i64) + } + } + + impl<'v> From<i16> for Inner<'v> { + fn from(v: i16) -> Self { + Inner::I64(v as i64) + } + } + + impl<'v> From<i32> for Inner<'v> { + fn from(v: i32) -> Self { + Inner::I64(v as i64) + } + } + + impl<'v> From<i64> for Inner<'v> { + fn from(v: i64) -> Self { + Inner::I64(v as i64) + } + } + + impl<'v> From<isize> for Inner<'v> { + fn from(v: isize) -> Self { + Inner::I64(v as i64) + } + } + + impl<'v> From<u8> for Inner<'v> { + fn from(v: u8) -> Self { + Inner::U64(v as u64) + } + } + + impl<'v> From<u16> for Inner<'v> { + fn from(v: u16) -> Self { + Inner::U64(v as u64) + } + } + + impl<'v> From<u32> for Inner<'v> { + fn from(v: u32) -> Self { + Inner::U64(v as u64) + } + } + + impl<'v> From<u64> for Inner<'v> { + fn from(v: u64) -> Self { + Inner::U64(v as u64) + } + } + + impl<'v> From<usize> for Inner<'v> { + fn from(v: usize) -> Self { + Inner::U64(v as u64) + } + } + + impl<'v> From<i128> for Inner<'v> { + fn from(v: i128) -> Self { + Inner::I128(v) + } + } + + impl<'v> From<u128> for Inner<'v> { + fn from(v: u128) -> Self { + Inner::U128(v) + } + } + + impl<'v> From<&'v str> for Inner<'v> { + fn from(v: &'v str) -> Self { + Inner::Str(v) + } + } + + impl<'v> fmt::Debug for Inner<'v> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Inner::None => fmt::Debug::fmt(&None::<()>, f), + Inner::Bool(v) => fmt::Debug::fmt(v, f), + Inner::Str(v) => fmt::Debug::fmt(v, f), + Inner::Char(v) => fmt::Debug::fmt(v, f), + Inner::I64(v) => fmt::Debug::fmt(v, f), + Inner::U64(v) => fmt::Debug::fmt(v, f), + Inner::F64(v) => fmt::Debug::fmt(v, f), + Inner::I128(v) => fmt::Debug::fmt(v, f), + Inner::U128(v) => fmt::Debug::fmt(v, f), + Inner::Debug(v) => fmt::Debug::fmt(v, f), + Inner::Display(v) => fmt::Display::fmt(v, f), + } + } + } + + impl<'v> fmt::Display for Inner<'v> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Inner::None => fmt::Debug::fmt(&None::<()>, f), + Inner::Bool(v) => fmt::Display::fmt(v, f), + Inner::Str(v) => fmt::Display::fmt(v, f), + Inner::Char(v) => fmt::Display::fmt(v, f), + Inner::I64(v) => fmt::Display::fmt(v, f), + Inner::U64(v) => fmt::Display::fmt(v, f), + Inner::F64(v) => fmt::Display::fmt(v, f), + Inner::I128(v) => fmt::Display::fmt(v, f), + Inner::U128(v) => fmt::Display::fmt(v, f), + Inner::Debug(v) => fmt::Debug::fmt(v, f), + Inner::Display(v) => fmt::Display::fmt(v, f), + } + } + } + + impl<'v> Inner<'v> { + pub fn from_debug<T: fmt::Debug>(value: &'v T) -> Self { + Inner::Debug(value) + } + + pub fn from_display<T: fmt::Display>(value: &'v T) -> Self { + Inner::Display(value) + } + + pub fn from_dyn_debug(value: &'v dyn fmt::Debug) -> Self { + Inner::Debug(value) + } + + pub fn from_dyn_display(value: &'v dyn fmt::Display) -> Self { + Inner::Display(value) + } + + pub fn empty() -> Self { + Inner::None + } + + pub fn to_bool(&self) -> Option<bool> { + match self { + Inner::Bool(v) => Some(*v), + _ => None, + } + } + + pub fn to_char(&self) -> Option<char> { + match self { + Inner::Char(v) => Some(*v), + _ => None, + } + } + + pub fn to_f64(&self) -> Option<f64> { + match self { + Inner::F64(v) => Some(*v), + Inner::I64(v) => { + let v: i32 = (*v).try_into().ok()?; + v.try_into().ok() + } + Inner::U64(v) => { + let v: u32 = (*v).try_into().ok()?; + v.try_into().ok() + } + Inner::I128(v) => { + let v: i32 = (*v).try_into().ok()?; + v.try_into().ok() + } + Inner::U128(v) => { + let v: u32 = (*v).try_into().ok()?; + v.try_into().ok() + } + _ => None, + } + } + + pub fn to_i64(&self) -> Option<i64> { + match self { + Inner::I64(v) => Some(*v), + Inner::U64(v) => (*v).try_into().ok(), + Inner::I128(v) => (*v).try_into().ok(), + Inner::U128(v) => (*v).try_into().ok(), + _ => None, + } + } + + pub fn to_u64(&self) -> Option<u64> { + match self { + Inner::U64(v) => Some(*v), + Inner::I64(v) => (*v).try_into().ok(), + Inner::I128(v) => (*v).try_into().ok(), + Inner::U128(v) => (*v).try_into().ok(), + _ => None, + } + } + + pub fn to_u128(&self) -> Option<u128> { + match self { + Inner::U128(v) => Some(*v), + Inner::I64(v) => (*v).try_into().ok(), + Inner::U64(v) => (*v).try_into().ok(), + Inner::I128(v) => (*v).try_into().ok(), + _ => None, + } + } + + pub fn to_i128(&self) -> Option<i128> { + match self { + Inner::I128(v) => Some(*v), + Inner::I64(v) => (*v).try_into().ok(), + Inner::U64(v) => (*v).try_into().ok(), + Inner::U128(v) => (*v).try_into().ok(), + _ => None, + } + } + + pub fn to_borrowed_str(&self) -> Option<&'v str> { + match self { + Inner::Str(v) => Some(v), + _ => None, + } + } + + #[cfg(test)] + pub fn to_test_token(&self) -> Token { + match self { + Inner::None => Token::None, + Inner::Bool(v) => Token::Bool(*v), + Inner::Str(v) => Token::Str(*v), + Inner::Char(v) => Token::Char(*v), + Inner::I64(v) => Token::I64(*v), + Inner::U64(v) => Token::U64(*v), + Inner::F64(v) => Token::F64(*v), + Inner::I128(_) => unimplemented!(), + Inner::U128(_) => unimplemented!(), + Inner::Debug(_) => unimplemented!(), + Inner::Display(_) => unimplemented!(), + } + } + } + + #[cfg(test)] + #[derive(Debug, PartialEq)] + pub enum Token<'v> { + None, + Bool(bool), + Char(char), + Str(&'v str), + F64(f64), + I64(i64), + U64(u64), + } + + pub fn visit<'v>( + inner: &Inner<'v>, + mut visitor: impl VisitValue<'v>, + ) -> Result<(), crate::kv::Error> { + match inner { + Inner::None => visitor.visit_null(), + Inner::Bool(v) => visitor.visit_bool(*v), + Inner::Str(v) => visitor.visit_borrowed_str(*v), + Inner::Char(v) => visitor.visit_char(*v), + Inner::I64(v) => visitor.visit_i64(*v), + Inner::U64(v) => visitor.visit_u64(*v), + Inner::F64(v) => visitor.visit_f64(*v), + Inner::I128(v) => visitor.visit_i128(*v), + Inner::U128(v) => visitor.visit_u128(*v), + Inner::Debug(v) => visitor.visit_any(Value::from_dyn_debug(*v)), + Inner::Display(v) => visitor.visit_any(Value::from_dyn_display(*v)), + } + } +} + +impl<'v> Value<'v> { + /// Get a value from a type implementing `std::fmt::Debug`. + #[cfg(feature = "kv_unstable")] + #[deprecated(note = "use `from_debug` instead")] + pub fn capture_debug<T>(value: &'v T) -> Self + where + T: fmt::Debug + 'static, + { + Value::from_debug(value) + } + + /// Get a value from a type implementing `std::fmt::Display`. + #[cfg(feature = "kv_unstable")] + #[deprecated(note = "use `from_display` instead")] + pub fn capture_display<T>(value: &'v T) -> Self + where + T: fmt::Display + 'static, + { + Value::from_display(value) + } + + /// Get a value from an error. + #[cfg(feature = "kv_unstable_std")] + #[deprecated(note = "use `from_dyn_error` instead")] + pub fn capture_error<T>(err: &'v T) -> Self + where + T: std::error::Error + 'static, + { + Value::from_dyn_error(err) + } + + /// Get a value from a type implementing `serde::Serialize`. + #[cfg(feature = "kv_unstable_serde")] + #[deprecated(note = "use `from_serde` instead")] + pub fn capture_serde<T>(value: &'v T) -> Self + where + T: serde::Serialize + 'static, + { + Value::from_serde(value) + } + + /// Get a value from a type implementing `sval::Value`. + #[cfg(feature = "kv_unstable_sval")] + #[deprecated(note = "use `from_sval` instead")] + pub fn capture_sval<T>(value: &'v T) -> Self + where + T: sval::Value + 'static, + { + Value::from_sval(value) + } + + /// Check whether this value can be downcast to `T`. + #[cfg(feature = "kv_unstable")] + #[deprecated( + note = "downcasting has been removed; log an issue at https://github.com/rust-lang/log/issues if this is something you rely on" + )] + pub fn is<T: 'static>(&self) -> bool { + false + } + + /// Try downcast this value to `T`. + #[cfg(feature = "kv_unstable")] + #[deprecated( + note = "downcasting has been removed; log an issue at https://github.com/rust-lang/log/issues if this is something you rely on" + )] + pub fn downcast_ref<T: 'static>(&self) -> Option<&T> { + None + } +} + +// NOTE: Deprecated; but aliases can't carry this attribute +#[cfg(feature = "kv_unstable")] +pub use VisitValue as Visit; + +/// Get a value from a type implementing `std::fmt::Debug`. +#[cfg(feature = "kv_unstable")] +#[deprecated(note = "use the `key:? = value` macro syntax instead")] +#[macro_export] +macro_rules! as_debug { + ($capture:expr) => { + $crate::kv::Value::from_debug(&$capture) + }; +} + +/// Get a value from a type implementing `std::fmt::Display`. +#[cfg(feature = "kv_unstable")] +#[deprecated(note = "use the `key:% = value` macro syntax instead")] +#[macro_export] +macro_rules! as_display { + ($capture:expr) => { + $crate::kv::Value::from_display(&$capture) + }; +} + +/// Get a value from an error. +#[cfg(feature = "kv_unstable_std")] +#[deprecated(note = "use the `key:err = value` macro syntax instead")] +#[macro_export] +macro_rules! as_error { + ($capture:expr) => { + $crate::kv::Value::from_dyn_error(&$capture) + }; +} + +#[cfg(feature = "kv_unstable_serde")] +#[deprecated(note = "use the `key:serde = value` macro syntax instead")] +/// Get a value from a type implementing `serde::Serialize`. +#[macro_export] +macro_rules! as_serde { + ($capture:expr) => { + $crate::kv::Value::from_serde(&$capture) + }; +} + +/// Get a value from a type implementing `sval::Value`. +#[cfg(feature = "kv_unstable_sval")] +#[deprecated(note = "use the `key:sval = value` macro syntax instead")] +#[macro_export] +macro_rules! as_sval { + ($capture:expr) => { + $crate::kv::Value::from_sval(&$capture) + }; +} + #[cfg(test)] pub(crate) mod tests { use super::*; - pub(crate) use value_bag::test::TestToken as Token; impl<'v> Value<'v> { - pub(crate) fn to_token(&self) -> Token { + pub(crate) fn to_token(&self) -> inner::Token { self.inner.to_test_token() } } @@ -824,40 +1228,6 @@ pub(crate) mod tests { vec![Value::from('a'), Value::from('⛰')].into_iter() } - #[test] - fn test_capture_fmt() { - assert_eq!(Some(42u64), Value::capture_display(&42).to_u64()); - assert_eq!(Some(42u64), Value::capture_debug(&42).to_u64()); - - assert!(Value::from_display(&42).to_u64().is_none()); - assert!(Value::from_debug(&42).to_u64().is_none()); - } - - #[cfg(feature = "kv_unstable_std")] - #[test] - fn test_capture_error() { - let err = std::io::Error::from(std::io::ErrorKind::Other); - - assert!(Value::capture_error(&err).to_borrowed_error().is_some()); - assert!(Value::from_dyn_error(&err).to_borrowed_error().is_some()); - } - - #[cfg(feature = "kv_unstable_serde")] - #[test] - fn test_capture_serde() { - assert_eq!(Some(42u64), Value::capture_serde(&42).to_u64()); - - assert_eq!(Some(42u64), Value::from_serde(&42).to_u64()); - } - - #[cfg(feature = "kv_unstable_sval")] - #[test] - fn test_capture_sval() { - assert_eq!(Some(42u64), Value::capture_sval(&42).to_u64()); - - assert_eq!(Some(42u64), Value::from_sval(&42).to_u64()); - } - #[test] fn test_to_value_display() { assert_eq!(42u64.to_value().to_string(), "42"); @@ -873,18 +1243,18 @@ pub(crate) mod tests { #[test] fn test_to_value_structured() { - assert_eq!(42u64.to_value().to_token(), Token::U64(42)); - assert_eq!(42i64.to_value().to_token(), Token::I64(42)); - assert_eq!(42.01f64.to_value().to_token(), Token::F64(42.01)); - assert_eq!(true.to_value().to_token(), Token::Bool(true)); - assert_eq!('a'.to_value().to_token(), Token::Char('a')); + assert_eq!(42u64.to_value().to_token(), inner::Token::U64(42)); + assert_eq!(42i64.to_value().to_token(), inner::Token::I64(42)); + assert_eq!(42.01f64.to_value().to_token(), inner::Token::F64(42.01)); + assert_eq!(true.to_value().to_token(), inner::Token::Bool(true)); + assert_eq!('a'.to_value().to_token(), inner::Token::Char('a')); assert_eq!( "a loong string".to_value().to_token(), - Token::Str("a loong string".into()) + inner::Token::Str("a loong string".into()) ); - assert_eq!(Some(true).to_value().to_token(), Token::Bool(true)); - assert_eq!(().to_value().to_token(), Token::None); - assert_eq!(None::<bool>.to_value().to_token(), Token::None); + assert_eq!(Some(true).to_value().to_token(), inner::Token::Bool(true)); + assert_eq!(().to_value().to_token(), inner::Token::None); + assert_eq!(None::<bool>.to_value().to_token(), inner::Token::None); } #[test] @@ -909,12 +1279,22 @@ pub(crate) mod tests { } } + #[test] + fn test_to_float() { + // Only integers from i32::MIN..=u32::MAX can be converted into floats + assert!(Value::from(i32::MIN).to_f64().is_some()); + assert!(Value::from(u32::MAX).to_f64().is_some()); + + assert!(Value::from((i32::MIN as i64) - 1).to_f64().is_none()); + assert!(Value::from((u32::MAX as u64) + 1).to_f64().is_none()); + } + #[test] fn test_to_cow_str() { for v in str() { assert!(v.to_borrowed_str().is_some()); - #[cfg(feature = "kv_unstable_std")] + #[cfg(feature = "kv_std")] assert!(v.to_cow_str().is_some()); } @@ -923,13 +1303,13 @@ pub(crate) mod tests { assert!(v.to_borrowed_str().is_some()); - #[cfg(feature = "kv_unstable_std")] + #[cfg(feature = "kv_std")] assert!(v.to_cow_str().is_some()); for v in unsigned().chain(signed()).chain(float()).chain(bool()) { assert!(v.to_borrowed_str().is_none()); - #[cfg(feature = "kv_unstable_std")] + #[cfg(feature = "kv_std")] assert!(v.to_cow_str().is_none()); } } @@ -966,22 +1346,11 @@ pub(crate) mod tests { } } - #[test] - fn test_downcast_ref() { - #[derive(Debug)] - struct Foo(u64); - - let v = Value::capture_debug(&Foo(42)); - - assert!(v.is::<Foo>()); - assert_eq!(42u64, v.downcast_ref::<Foo>().expect("invalid downcast").0); - } - #[test] fn test_visit_integer() { struct Extract(Option<u64>); - impl<'v> Visit<'v> for Extract { + impl<'v> VisitValue<'v> for Extract { fn visit_any(&mut self, value: Value) -> Result<(), Error> { unimplemented!("unexpected value: {value:?}") } @@ -1003,7 +1372,7 @@ pub(crate) mod tests { fn test_visit_borrowed_str() { struct Extract<'v>(Option<&'v str>); - impl<'v> Visit<'v> for Extract<'v> { + impl<'v> VisitValue<'v> for Extract<'v> { fn visit_any(&mut self, value: Value) -> Result<(), Error> { unimplemented!("unexpected value: {value:?}") } diff --git a/src/lib.rs b/src/lib.rs index 6a3a8ca98..505d24961 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -88,7 +88,7 @@ //! //! ## Structured logging //! -//! If you enable the `kv_unstable` feature you can associate structured values +//! If you enable the `kv` feature you can associate structured values //! with your log records. If we take the example from before, we can include //! some additional context besides what's in the formatted message: //! @@ -97,31 +97,33 @@ //! # #[derive(Debug, Serialize)] pub struct Yak(String); //! # impl Yak { fn shave(&mut self, _: u32) {} } //! # fn find_a_razor() -> Result<u32, std::io::Error> { Ok(1) } -//! # #[cfg(feature = "kv_unstable_serde")] +//! # #[cfg(feature = "kv_serde")] //! # fn main() { -//! use log::{info, warn, as_serde, as_error}; +//! use log::{info, warn}; //! //! pub fn shave_the_yak(yak: &mut Yak) { -//! info!(target: "yak_events", yak = as_serde!(yak); "Commencing yak shaving"); +//! info!(target: "yak_events", yak:serde; "Commencing yak shaving"); //! //! loop { //! match find_a_razor() { //! Ok(razor) => { -//! info!(razor = razor; "Razor located"); +//! info!(razor; "Razor located"); //! yak.shave(razor); //! break; //! } -//! Err(err) => { -//! warn!(err = as_error!(err); "Unable to locate a razor, retrying"); +//! Err(e) => { +//! warn!(e:err; "Unable to locate a razor, retrying"); //! } //! } //! } //! } //! # } -//! # #[cfg(not(feature = "kv_unstable_serde"))] +//! # #[cfg(not(feature = "kv_serde"))] //! # fn main() {} //! ``` //! +//! See the [`kv`] module documentation for more details. +//! //! # Available logging implementations //! //! In order to produce log output executables have to use @@ -353,7 +355,7 @@ use std::{cmp, fmt, mem}; mod macros; mod serde; -#[cfg(feature = "kv_unstable")] +#[cfg(feature = "kv")] pub mod kv; #[cfg(target_has_atomic = "ptr")] @@ -721,7 +723,7 @@ pub struct Record<'a> { module_path: Option<MaybeStaticStr<'a>>, file: Option<MaybeStaticStr<'a>>, line: Option<u32>, - #[cfg(feature = "kv_unstable")] + #[cfg(feature = "kv")] key_values: KeyValues<'a>, } @@ -729,11 +731,11 @@ pub struct Record<'a> { // `#[derive(Debug)]` on `Record`. It also // provides a useful `Debug` implementation for // the underlying `Source`. -#[cfg(feature = "kv_unstable")] +#[cfg(feature = "kv")] #[derive(Clone)] struct KeyValues<'a>(&'a dyn kv::Source); -#[cfg(feature = "kv_unstable")] +#[cfg(feature = "kv")] impl<'a> fmt::Debug for KeyValues<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut visitor = f.debug_map(); @@ -810,14 +812,14 @@ impl<'a> Record<'a> { } /// The structured key-value pairs associated with the message. - #[cfg(feature = "kv_unstable")] + #[cfg(feature = "kv")] #[inline] pub fn key_values(&self) -> &dyn kv::Source { self.key_values.0 } /// Create a new [`RecordBuilder`](struct.RecordBuilder.html) based on this record. - #[cfg(feature = "kv_unstable")] + #[cfg(feature = "kv")] #[inline] pub fn to_builder(&self) -> RecordBuilder { RecordBuilder { @@ -902,7 +904,7 @@ impl<'a> RecordBuilder<'a> { module_path: None, file: None, line: None, - #[cfg(feature = "kv_unstable")] + #[cfg(feature = "kv")] key_values: KeyValues(&None::<(kv::Key, kv::Value)>), }, } @@ -972,7 +974,7 @@ impl<'a> RecordBuilder<'a> { } /// Set [`key_values`](struct.Record.html#method.key_values) - #[cfg(feature = "kv_unstable")] + #[cfg(feature = "kv")] #[inline] pub fn key_values(&mut self, kvs: &'a dyn kv::Source) -> &mut RecordBuilder<'a> { self.record.key_values = KeyValues(kvs); @@ -1755,16 +1757,16 @@ mod tests { } #[test] - #[cfg(feature = "kv_unstable")] + #[cfg(feature = "kv")] fn test_record_key_values_builder() { use super::Record; - use crate::kv::{self, Visitor}; + use crate::kv::{self, VisitSource}; - struct TestVisitor { + struct TestVisitSource { seen_pairs: usize, } - impl<'kvs> Visitor<'kvs> for TestVisitor { + impl<'kvs> VisitSource<'kvs> for TestVisitSource { fn visit_pair( &mut self, _: kv::Key<'kvs>, @@ -1778,7 +1780,7 @@ mod tests { let kvs: &[(&str, i32)] = &[("a", 1), ("b", 2)]; let record_test = Record::builder().key_values(&kvs).build(); - let mut visitor = TestVisitor { seen_pairs: 0 }; + let mut visitor = TestVisitSource { seen_pairs: 0 }; record_test.key_values().visit(&mut visitor).unwrap(); @@ -1786,7 +1788,7 @@ mod tests { } #[test] - #[cfg(feature = "kv_unstable")] + #[cfg(feature = "kv")] fn test_record_key_values_get_coerce() { use super::Record; diff --git a/src/macros.rs b/src/macros.rs index 44945f0d9..48a7447ef 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -29,8 +29,8 @@ /// ``` #[macro_export] macro_rules! log { - // log!(target: "my_target", Level::Info, key1 = 42, key2 = true; "a {} event", "log"); - (target: $target:expr, $lvl:expr, $($key:tt = $value:expr),+; $($arg:tt)+) => ({ + // log!(target: "my_target", Level::Info, key1:? = 42, key2 = true; "a {} event", "log"); + (target: $target:expr, $lvl:expr, $($key:tt $(:$capture:tt)? $(= $value:expr)?),+; $($arg:tt)+) => ({ let lvl = $lvl; if lvl <= $crate::STATIC_MAX_LEVEL && lvl <= $crate::max_level() { $crate::__private_api::log::<&_>( @@ -38,7 +38,7 @@ macro_rules! log { lvl, &($target, $crate::__private_api::module_path!(), $crate::__private_api::file!()), $crate::__private_api::line!(), - &[$(($crate::__log_key!($key), &$value)),+] + &[$(($crate::__log_key!($key), $crate::__log_value!($key $(:$capture)* = $($value)*))),+] ); } }); @@ -226,8 +226,12 @@ macro_rules! log_enabled { }; } +// These macros use a pattern of #[cfg]s to produce nicer error +// messages when log features aren't available + #[doc(hidden)] #[macro_export] +#[cfg(feature = "kv")] macro_rules! __log_key { // key1 = 42 ($($args:ident)*) => { @@ -238,3 +242,128 @@ macro_rules! __log_key { $($args)* }; } + +#[doc(hidden)] +#[macro_export] +#[cfg(not(feature = "kv"))] +macro_rules! __log_key { + ($($args:tt)*) => { + compile_error!("key value support requires the `kv` feature of `log`") + }; +} + +#[doc(hidden)] +#[macro_export] +#[cfg(feature = "kv")] +macro_rules! __log_value { + // Entrypoint + ($key:tt = $args:expr) => { + $crate::__log_value!(($args):value) + }; + ($key:tt :$capture:tt = $args:expr) => { + $crate::__log_value!(($args):$capture) + }; + ($key:ident =) => { + $crate::__log_value!(($key):value) + }; + ($key:ident :$capture:tt =) => { + $crate::__log_value!(($key):$capture) + }; + // ToValue + (($args:expr):value) => { + $crate::__private_api::capture_to_value(&&$args) + }; + // Debug + (($args:expr):?) => { + $crate::__private_api::capture_debug(&&$args) + }; + (($args:expr):debug) => { + $crate::__private_api::capture_debug(&&$args) + }; + // Display + (($args:expr):%) => { + $crate::__private_api::capture_display(&&$args) + }; + (($args:expr):display) => { + $crate::__private_api::capture_display(&&$args) + }; + //Error + (($args:expr):err) => { + $crate::__log_value_error!($args) + }; + // sval::Value + (($args:expr):sval) => { + $crate::__log_value_sval!($args) + }; + // serde::Serialize + (($args:expr):serde) => { + $crate::__log_value_serde!($args) + }; +} + +#[doc(hidden)] +#[macro_export] +#[cfg(not(feature = "kv"))] +macro_rules! __log_value { + ($($args:tt)*) => { + compile_error!("key value support requires the `kv` feature of `log`") + }; +} + +#[doc(hidden)] +#[macro_export] +#[cfg(feature = "kv_sval")] +macro_rules! __log_value_sval { + ($args:expr) => { + $crate::__private_api::capture_sval(&&$args) + }; +} + +#[doc(hidden)] +#[macro_export] +#[cfg(not(feature = "kv_sval"))] +macro_rules! __log_value_sval { + ($args:expr) => { + compile_error!("capturing values as `sval::Value` requites the `kv_sval` feature of `log`") + }; +} + +#[doc(hidden)] +#[macro_export] +#[cfg(feature = "kv_serde")] +macro_rules! __log_value_serde { + ($args:expr) => { + $crate::__private_api::capture_serde(&&$args) + }; +} + +#[doc(hidden)] +#[macro_export] +#[cfg(not(feature = "kv_serde"))] +macro_rules! __log_value_serde { + ($args:expr) => { + compile_error!( + "capturing values as `serde::Serialize` requites the `kv_serde` feature of `log`" + ) + }; +} + +#[doc(hidden)] +#[macro_export] +#[cfg(feature = "kv_std")] +macro_rules! __log_value_error { + ($args:expr) => { + $crate::__private_api::capture_error(&$args) + }; +} + +#[doc(hidden)] +#[macro_export] +#[cfg(not(feature = "kv_std"))] +macro_rules! __log_value_error { + ($args:expr) => { + compile_error!( + "capturing values as `std::error::Error` requites the `kv_std` feature of `log`" + ) + }; +}
diff --git a/tests/Cargo.toml b/tests/Cargo.toml index 88f37b5d4..8754bb16a 100644 --- a/tests/Cargo.toml +++ b/tests/Cargo.toml @@ -7,6 +7,10 @@ build = "src/build.rs" [features] std = ["log/std"] +kv = ["log/kv"] +kv_std = ["log/kv_std"] +kv_sval = ["log/kv_sval"] +kv_serde = ["log/kv_serde"] [dependencies.log] path = ".." diff --git a/tests/macros.rs b/tests/macros.rs index 3afcf88da..20da6ac44 100644 --- a/tests/macros.rs +++ b/tests/macros.rs @@ -107,7 +107,7 @@ fn expr() { } #[test] -#[cfg(feature = "kv_unstable")] +#[cfg(feature = "kv")] fn kv_no_args() { for lvl in log::Level::iter() { log!(target: "my_target", lvl, cat_1 = "chashu", cat_2 = "nori", cat_count = 2; "hello"); @@ -121,7 +121,7 @@ fn kv_no_args() { } #[test] -#[cfg(feature = "kv_unstable")] +#[cfg(feature = "kv")] fn kv_expr_args() { for lvl in log::Level::iter() { log!(target: "my_target", lvl, cat_math = { let mut x = 0; x += 1; x + 1 }; "hello"); @@ -136,7 +136,7 @@ fn kv_expr_args() { } #[test] -#[cfg(feature = "kv_unstable")] +#[cfg(feature = "kv")] fn kv_anonymous_args() { for lvl in log::Level::iter() { log!(target: "my_target", lvl, cat_1 = "chashu", cat_2 = "nori", cat_count = 2; "hello {}", "world"); @@ -151,7 +151,7 @@ fn kv_anonymous_args() { } #[test] -#[cfg(feature = "kv_unstable")] +#[cfg(feature = "kv")] fn kv_named_args() { for lvl in log::Level::iter() { log!(target: "my_target", lvl, cat_1 = "chashu", cat_2 = "nori", cat_count = 2; "hello {world}", world = "world"); @@ -166,7 +166,16 @@ fn kv_named_args() { } #[test] -#[cfg(feature = "kv_unstable")] +#[cfg(feature = "kv")] +fn kv_ident() { + let cat_1 = "chashu"; + let cat_2 = "nori"; + + all_log_macros!(cat_1, cat_2:%, cat_count = 2; "hello {world}", world = "world"); +} + +#[test] +#[cfg(feature = "kv")] fn kv_expr_context() { match "chashu" { cat_1 => { @@ -196,14 +205,14 @@ fn implicit_named_args() { all_log_macros!(target: "my_target", "hello {world}"); all_log_macros!(target: "my_target", "hello {world}",); - #[cfg(feature = "kv_unstable")] + #[cfg(feature = "kv")] all_log_macros!(target = "my_target"; "hello {world}"); - #[cfg(feature = "kv_unstable")] + #[cfg(feature = "kv")] all_log_macros!(target = "my_target"; "hello {world}",); } #[test] -#[cfg(feature = "kv_unstable")] +#[cfg(feature = "kv")] fn kv_implicit_named_args() { let world = "world"; @@ -219,7 +228,7 @@ fn kv_implicit_named_args() { } #[test] -#[cfg(feature = "kv_unstable")] +#[cfg(feature = "kv")] fn kv_string_keys() { for lvl in log::Level::iter() { log!(target: "my_target", lvl, "also dogs" = "Fílos", "key/that-can't/be/an/ident" = "hi"; "hello {world}", world = "world"); @@ -229,7 +238,7 @@ fn kv_string_keys() { } #[test] -#[cfg(feature = "kv_unstable")] +#[cfg(feature = "kv")] fn kv_common_value_types() { all_log_macros!( u8 = 42u8, @@ -250,6 +259,53 @@ fn kv_common_value_types() { ); } +#[test] +#[cfg(feature = "kv")] +fn kv_debug() { + all_log_macros!( + a:? = 42, + b:debug = 42; + "hello world" + ); +} + +#[test] +#[cfg(feature = "kv")] +fn kv_display() { + all_log_macros!( + a:% = 42, + b:display = 42; + "hello world" + ); +} + +#[test] +#[cfg(feature = "kv_std")] +fn kv_error() { + all_log_macros!( + a:err = std::io::Error::new(std::io::ErrorKind::Other, "an error"); + "hello world" + ); +} + +#[test] +#[cfg(feature = "kv_sval")] +fn kv_sval() { + all_log_macros!( + a:sval = 42; + "hello world" + ); +} + +#[test] +#[cfg(feature = "kv_serde")] +fn kv_serde() { + all_log_macros!( + a:serde = 42; + "hello world" + ); +} + /// Some and None (from Option) are used in the macros. #[derive(Debug)] enum Type {
Review of key-value feature Discussion for https://github.com/rust-lang/log/issues/328.
Thanks for all the time you've spent digging through this so far @Thomasdezeeuw! I think we're getting towards something that feels appropriate for the `log` crate without losing capability. Just checking back in on this, is the main blocker we've got deciding whether to default to capturing using `ToValue` and supporting some `tracing`-like syntax for changing it? > Just checking back in on this, is the main blocker we've got deciding whether to default to capturing using `ToValue` and supporting some `tracing`-like syntax for changing it? Yes, I think those are the two main things from this pr. I'm doing some work on this now; removing the `Value::capture_*` and downcasting methods, and improving the overall documentation for the `kv` module. It looks like we already default to using `ToValue` for key-values, so nothing needs to change there. That just leaves some nicer macro support for tweaking how values are captured. Are you happy with that plan @Thomasdezeeuw?
2024-01-26T08:08:39Z
0.4
06c306fa8f4d41a722f8759f03effd4185eee3ee
rust-lang/log
495
rust-lang__log-495
[ "494" ]
bc181df9fbb1ad40abcae41ae2dd53b3652b50bc
diff --git a/src/macros.rs b/src/macros.rs index ec2f4200c..a4fe6803b 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -37,7 +37,7 @@ macro_rules! log { __log_format_args!($($arg)+), lvl, &($target, __log_module_path!(), __log_file!(), __log_line!()), - Some(&[$((__log_key!($key), &$value)),+]) + std::option::Option::Some(&[$((__log_key!($key), &$value)),+]) ); } }); @@ -50,7 +50,7 @@ macro_rules! log { __log_format_args!($($arg)+), lvl, &($target, __log_module_path!(), __log_file!(), __log_line!()), - None, + std::option::Option::None, ); } });
diff --git a/tests/macros.rs b/tests/macros.rs index 7b2483ceb..fcd8556a3 100644 --- a/tests/macros.rs +++ b/tests/macros.rs @@ -215,3 +215,16 @@ fn kv_string_keys() { all_log_macros!(target: "my_target", "also dogs" = "Fílos", "key/that-can't/be/an/ident" = "hi"; "hello {world}", world = "world"); } + +/// Some and None (from Option) are used in the macros. +#[derive(Debug)] +enum Type { + Some, + None, +} + +#[test] +fn regression_issue_494() { + use Type::*; + all_log_macros!("some message: {:?}, {:?}", None, Some); +}
regression: enum variant named None fails to compile in 0.4.15 I have written some poker software where it makes sense (at least to me!) to have a `None` variant. When I upgraded to log 0.4.15, my code stopped compiling. Here's a short illustration: ``` #[derive(Debug)] pub enum Limit { None, } pub struct M { limit: Limit, } impl M { fn bring_in_based_min_raise(&self) { use Limit::*; log::warn!("self.limit should not be: {:?}", self.limit); } } fn main() { println!("Hello, world!"); } ``` ``` error[E0308]: mismatched types --> src/main.rs:13:9 | 13 | log::warn!("self.limit should not be: {:?}", self.limit); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected enum `Option`, found enum `Limit` | = note: expected enum `Option<&[(&str, &str)]>` found enum `Limit` ``` I've [temporarily pinned to log 0.4.14](https://github.com/ctm/mb2-doc/issues/933), which works fine.
It looks like this `None` (and the `Some` above it) needs to be fully qualified: https://github.com/rust-lang/log/blob/master/src/macros.rs#L53 @sfackler can you make a pr or want me to do it? I can make one later today, but go for it if you have the time earlier.
2022-03-22T13:01:36Z
0.4
06c306fa8f4d41a722f8759f03effd4185eee3ee
rust-lang/log
470
rust-lang__log-470
[ "381" ]
525336f364fb80b63d910e783884b14be71814c5
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index d90d48baa..855a2d965 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -37,6 +37,8 @@ jobs: rustup update ${{ matrix.rust }} --no-self-update rustup default ${{ matrix.rust }} - run: cargo test --verbose + - run: cargo test --verbose --no-default-features + - run: cargo test --verbose --all-features - run: cargo test --verbose --features serde - run: cargo test --verbose --features std - run: cargo test --verbose --features kv_unstable
diff --git a/tests/filters.rs b/tests/filters.rs index de6bd189f..f37751c24 100644 --- a/tests/filters.rs +++ b/tests/filters.rs @@ -1,3 +1,5 @@ +#![allow(dead_code, unused_imports)] + #[cfg(not(lib_build))] #[macro_use] extern crate log; @@ -32,18 +34,36 @@ impl Log for Logger { #[cfg_attr(lib_build, test)] fn main() { - let me = Arc::new(State { - last_log: Mutex::new(None), - }); - let a = me.clone(); - set_boxed_logger(Box::new(Logger(me))).unwrap(); + // These tests don't really make sense when static + // max level filtering is applied + #[cfg(not(any( + feature = "max_level_off", + feature = "max_level_error", + feature = "max_level_warn", + feature = "max_level_info", + feature = "max_level_debug", + feature = "max_level_trace", + feature = "max_level_off", + feature = "max_level_error", + feature = "max_level_warn", + feature = "max_level_info", + feature = "max_level_debug", + feature = "max_level_trace", + )))] + { + let me = Arc::new(State { + last_log: Mutex::new(None), + }); + let a = me.clone(); + set_boxed_logger(Box::new(Logger(me))).unwrap(); - test(&a, LevelFilter::Off); - test(&a, LevelFilter::Error); - test(&a, LevelFilter::Warn); - test(&a, LevelFilter::Info); - test(&a, LevelFilter::Debug); - test(&a, LevelFilter::Trace); + test(&a, LevelFilter::Off); + test(&a, LevelFilter::Error); + test(&a, LevelFilter::Warn); + test(&a, LevelFilter::Info); + test(&a, LevelFilter::Debug); + test(&a, LevelFilter::Trace); + } } fn test(a: &State, filter: LevelFilter) {
`cargo test --all-features` fails from git master, if i run `cargo test --all-features`, i see: ``` Finished dev [unoptimized + debuginfo] target(s) in 0.01s Running target/debug/deps/log-7d6eb7ffa43b7118 running 45 tests test kv::key::tests::key_from_string ... ok test kv::source::std_support::tests::btree_map ... ok test kv::source::std_support::tests::get ... ok test kv::source::std_support::tests::count ... ok test kv::source::tests::count ... ok test kv::source::std_support::tests::hash_map ... ok test kv::source::tests::source_is_object_safe ... ok test kv::source::tests::get ... ok test kv::source::tests::visitor_is_object_safe ... ok test kv::value::fill::tests::fill_cast ... ok test kv::value::fill::tests::fill_value_borrowed ... ok test kv::value::fill::tests::fill_value_owned ... ok test kv::value::impls::tests::test_to_value_display ... ok test kv::value::internal::cast::std_support::tests::primitive_cast ... ok test kv::value::internal::fmt::tests::fmt_cast ... ok test kv::value::internal::cast::tests::primitive_cast ... ok test kv::value::internal::sval::tests::sval_cast ... ok test kv::value::internal::sval::tests::test_from_sval ... ok test kv::value::internal::sval::tests::test_sval_structured ... ok test serde::tests::test_level_case_insensitive ... ok test serde::tests::test_level_de_error ... ok test kv::value::impls::tests::test_to_value_structured ... ok test serde::tests::test_level_filter_case_insensitive ... ok test serde::tests::test_level_filter_de_bytes ... ok test serde::tests::test_level_de_bytes ... ok test serde::tests::test_level_filter_de_error ... ok test serde::tests::test_level_ser_de ... ok test tests::test_cross_eq ... ok test tests::test_error_trait ... ok test tests::test_level_from_str ... ok test tests::test_level_show ... ok test tests::test_levelfilter_from_str ... ok test tests::test_levelfilter_show ... ok test tests::test_metadata_builder ... ok test serde::tests::test_level_filter_ser_de ... ok test tests::test_metadata_convenience_builder ... ok test tests::test_record_builder ... ok test tests::test_record_complete_builder ... ok test tests::test_record_convenience_builder ... ok test tests::test_record_key_values_builder ... ok test tests::test_to_level ... ok test tests::test_record_key_values_get_coerce ... ok test tests::test_to_level_filter ... ok test tests::test_cross_cmp ... ok test kv::value::fill::tests::fill_multiple_times_panics ... ok test result: ok. 45 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out Running target/debug/deps/filters-8e7b236d082cd8bd thread 'main' panicked at 'assertion failed: `(left == right)` left: `None`, right: `Some(Error)`', tests/filters.rs:71:5 stack backtrace: 0: 0x556fd8283524 - <std::sys_common::backtrace::_print::DisplayBacktrace as core::fmt::Display>::fmt::h6001c6574450335d 1: 0x556fd829461d - core::fmt::write::h1371734f6a7c7bc2 2: 0x556fd8282845 - std::io::Write::write_fmt::h5ee928f19b08369c 3: 0x556fd827c84e - std::panicking::default_hook::{{closure}}::h6b521085a6513c53 4: 0x556fd827c560 - std::panicking::default_hook::h3e3fe9b536fd99f6 5: 0x556fd827ceeb - std::panicking::rust_panic_with_hook::h3d899269d6b7f8f7 6: 0x556fd827ca8e - std::panicking::continue_panic_fmt::h22635bd1aa2db87e 7: 0x556fd827c9cf - std::panicking::begin_panic_fmt::h4934e76a4a1dca0f 8: 0x556fd827797b - filters::last::h6ea39f99f73e96a2 at tests/filters.rs:71 9: 0x556fd82771c8 - filters::test::h018f9be09c67b83d at tests/filters.rs:50 10: 0x556fd8276ee5 - filters::main::h5cb267d978caf4dd at tests/filters.rs:40 11: 0x556fd82742e0 - std::rt::lang_start::{{closure}}::h99add10a92b1f5d8 at /usr/src/rustc-1.40.0/src/libstd/rt.rs:61 12: 0x556fd827c913 - std::panicking::try::do_call::h405fa073712ab5d5 13: 0x556fd8283eea - __rust_maybe_catch_panic 14: 0x556fd827fd39 - std::rt::lang_start_internal::he63ceb3eba03dd55 15: 0x556fd82742b9 - std::rt::lang_start::h2e31d45daa3b065e at /usr/src/rustc-1.40.0/src/libstd/rt.rs:61 16: 0x556fd82779ca - main 17: 0x7fb00fb9dbbb - __libc_start_main 18: 0x556fd82741aa - _start 19: 0x0 - <unknown> error: test failed, to rerun pass '--test filters' ``` This is also a problem at tags 0.4.8 and 0.4.9. (i confess i don't really understand what it means exactly) It's likely to cause problems for [the debian package for this crate](https://tracker.debian.org/pkg/rust-log) as well, since we typically try to run `cargo test --all-features`.
Ah, unfortunately `log`'s features are set up in such a way that running with `--all-features` doesn't really make sense (it uses features to set minimum levels at compile-time). It's unfortunate for tests to fail though since `--all-features` should be a perfectly legitimate flag so we should do something about the filters tests so they don't run unless the feature set makes sense to them.
2021-11-15T06:58:10Z
0.4
06c306fa8f4d41a722f8759f03effd4185eee3ee
rust-lang/log
423
rust-lang__log-423
[ "408" ]
cb0b8c4f93758531ef3eada40da2642e9ed0d616
diff --git a/Cargo.toml b/Cargo.toml index 69fe79d25..299937c3e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,7 +16,7 @@ exclude = ["rfcs/**/*", "/.travis.yml", "/appveyor.yml"] build = "build.rs" [package.metadata.docs.rs] -features = ["std", "serde", "kv_unstable_sval"] +features = ["std", "serde", "kv_unstable_std", "kv_unstable_sval", "kv_unstable_serde"] [[test]] name = "filters" @@ -45,14 +45,17 @@ std = [] # requires the latest stable # this will have a tighter MSRV before stabilization -kv_unstable = [] -kv_unstable_sval = ["kv_unstable", "sval/fmt"] +kv_unstable = ["value-bag"] +kv_unstable_sval = ["kv_unstable", "value-bag/sval", "sval"] +kv_unstable_std = ["std", "kv_unstable", "value-bag/error"] +kv_unstable_serde = ["kv_unstable_std", "value-bag/serde", "serde"] [dependencies] cfg-if = "1.0" serde = { version = "1.0", optional = true, default-features = false } -sval = { version = "0.5.2", optional = true, default-features = false } +sval = { version = "1.0.0-alpha.4", optional = true, default-features = false } +value-bag = { version = "1.0.0-alpha.5", optional = true, default-features = false } [dev-dependencies] serde_test = "1.0" -sval = { version = "0.5.2", features = ["test"] } +value-bag = { version = "1.0.0-alpha.5", features = ["test"] } diff --git a/build.rs b/build.rs index bb2462d06..2b17e0be9 100644 --- a/build.rs +++ b/build.rs @@ -4,10 +4,6 @@ use std::env; use std::str; -#[cfg(feature = "kv_unstable")] -#[path = "src/kv/value/internal/cast/primitive.rs"] -mod primitive; - fn main() { let target = match rustc_target() { Some(target) => target, @@ -22,11 +18,6 @@ fn main() { println!("cargo:rustc-cfg=has_atomics"); } - // Generate sorted type id lookup - #[cfg(feature = "kv_unstable")] - primitive::generate(); - - println!("cargo:rustc-cfg=srcbuild"); println!("cargo:rerun-if-changed=build.rs"); } diff --git a/src/kv/source.rs b/src/kv/source.rs index 86b016033..cb5efc066 100644 --- a/src/kv/source.rs +++ b/src/kv/source.rs @@ -323,7 +323,7 @@ mod std_support { #[cfg(test)] mod tests { use super::*; - use kv::value::test::Token; + use kv::value::tests::Token; use std::collections::{BTreeMap, HashMap}; #[test] @@ -375,7 +375,7 @@ mod std_support { #[cfg(test)] mod tests { use super::*; - use kv::value::test::Token; + use kv::value::tests::Token; #[test] fn source_is_object_safe() { diff --git a/src/kv/value.rs b/src/kv/value.rs new file mode 100644 index 000000000..561ea8641 --- /dev/null +++ b/src/kv/value.rs @@ -0,0 +1,659 @@ +//! Structured values. + +use std::fmt; + +extern crate value_bag; + +#[cfg(feature = "kv_unstable_sval")] +extern crate sval; + +#[cfg(feature = "kv_unstable_serde")] +extern crate serde; + +use self::value_bag::ValueBag; + +pub use kv::Error; + +/// A type that can be converted into a [`Value`](struct.Value.html). +pub trait ToValue { + /// Perform the conversion. + fn to_value(&self) -> Value; +} + +impl<'a, T> ToValue for &'a T +where + T: ToValue + ?Sized, +{ + fn to_value(&self) -> Value { + (**self).to_value() + } +} + +impl<'v> ToValue for Value<'v> { + fn to_value(&self) -> Value { + Value { + inner: self.inner.clone(), + } + } +} + +/// A value in a structured key-value pair. +/// +/// # Capturing values +/// +/// There are a few ways to capture a value: +/// +/// - Using the `Value::capture_*` methods. +/// - Using the `Value::from_*` methods. +/// - Using the `ToValue` trait. +/// - Using the standard `From` trait. +/// +/// ## Using the `Value::capture_*` methods +/// +/// `Value` offers a few constructor methods that capture values of different kinds. +/// These methods require a `T: 'static` to support downcasting. +/// +/// ``` +/// use log::kv::Value; +/// +/// let value = Value::capture_debug(&42i32); +/// +/// assert_eq!(Some(42), value.to_i32()); +/// ``` +/// +/// ## Using the `Value::from_*` methods +/// +/// `Value` offers a few constructor methods that capture values of different kinds. +/// These methods don't require `T: 'static`, but can't support downcasting. +/// +/// ``` +/// use log::kv::Value; +/// +/// let value = Value::from_debug(&42i32); +/// +/// assert_eq!(None, value.to_i32()); +/// ``` +/// +/// ## Using the `ToValue` trait +/// +/// The `ToValue` trait can be used to capture values generically. +/// It's the bound used by `Source`. +/// +/// ``` +/// # use log::kv::ToValue; +/// let value = 42i32.to_value(); +/// +/// assert_eq!(Some(42), value.to_i32()); +/// ``` +/// +/// ``` +/// # use std::fmt::Debug; +/// use log::kv::ToValue; +/// +/// let value = (&42i32 as &dyn Debug).to_value(); +/// +/// assert_eq!(None, value.to_i32()); +/// ``` +/// +/// ## Using the standard `From` trait +/// +/// Standard types that implement `ToValue` also implement `From`. +/// +/// ``` +/// use log::kv::Value; +/// +/// let value = Value::from(42i32); +/// +/// assert_eq!(Some(42), value.to_i32()); +/// ``` +pub struct Value<'v> { + inner: ValueBag<'v>, +} + +impl<'v> Value<'v> { + /// Get a value from a type implementing `ToValue`. + pub fn from_any<T>(value: &'v T) -> Self + where + T: ToValue, + { + value.to_value() + } + + /// Get a value from a type implementing `std::fmt::Debug`. + pub fn capture_debug<T>(value: &'v T) -> Self + where + T: fmt::Debug + 'static, + { + Value { + inner: ValueBag::capture_debug(value), + } + } + + /// Get a value from a type implementing `std::fmt::Display`. + pub fn capture_display<T>(value: &'v T) -> Self + where + T: fmt::Display + 'static, + { + Value { + inner: ValueBag::capture_display(value), + } + } + + /// Get a value from an error. + #[cfg(feature = "kv_unstable_std")] + pub fn capture_error<T>(err: &'v T) -> Self + where + T: std::error::Error + 'static, + { + Value { + inner: ValueBag::capture_error(err), + } + } + + #[cfg(feature = "kv_unstable_serde")] + /// Get a value from a type implementing `serde::Serialize`. + pub fn capture_serde<T>(value: &'v T) -> Self + where + T: self::serde::Serialize + 'static, + { + Value { + inner: ValueBag::capture_serde1(value), + } + } + + /// Get a value from a type implementing `sval::value::Value`. + #[cfg(feature = "kv_unstable_sval")] + pub fn capture_sval<T>(value: &'v T) -> Self + where + T: self::sval::value::Value + 'static, + { + Value { + inner: ValueBag::capture_sval1(value), + } + } + + /// Get a value from a type implementing `std::fmt::Debug`. + pub fn from_debug<T>(value: &'v T) -> Self + where + T: fmt::Debug, + { + Value { + inner: ValueBag::from_debug(value), + } + } + + /// Get a value from a type implementing `std::fmt::Display`. + pub fn from_display<T>(value: &'v T) -> Self + where + T: fmt::Display, + { + Value { + inner: ValueBag::from_display(value), + } + } + + /// Get a value from a type implementing `serde::Serialize`. + #[cfg(feature = "kv_unstable_serde")] + pub fn from_serde<T>(value: &'v T) -> Self + where + T: self::serde::Serialize, + { + Value { + inner: ValueBag::from_serde1(value), + } + } + + /// Get a value from a type implementing `sval::value::Value`. + #[cfg(feature = "kv_unstable_sval")] + pub fn from_sval<T>(value: &'v T) -> Self + where + T: self::sval::value::Value, + { + Value { + inner: ValueBag::from_sval1(value), + } + } + + /// Get a value from a dynamic `std::fmt::Debug`. + pub fn from_dyn_debug(value: &'v dyn fmt::Debug) -> Self { + Value { + inner: ValueBag::from_dyn_debug(value), + } + } + + /// Get a value from a dynamic `std::fmt::Display`. + pub fn from_dyn_display(value: &'v dyn fmt::Display) -> Self { + Value { + inner: ValueBag::from_dyn_display(value), + } + } + + /// Get a value from a dynamic error. + #[cfg(feature = "kv_unstable_std")] + pub fn from_dyn_error(err: &'v (dyn std::error::Error + 'static)) -> Self { + Value { + inner: ValueBag::from_dyn_error(err), + } + } + + /// Get a value from a type implementing `sval::value::Value`. + #[cfg(feature = "kv_unstable_sval")] + pub fn from_dyn_sval(value: &'v dyn self::sval::value::Value) -> Self { + Value { + inner: ValueBag::from_dyn_sval1(value), + } + } + + /// Get a value from an internal primitive. + fn from_value_bag<T>(value: T) -> Self + where + T: Into<ValueBag<'v>>, + { + Value { + inner: value.into(), + } + } +} + +impl<'v> fmt::Debug for Value<'v> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(&self.inner, f) + } +} + +impl<'v> fmt::Display for Value<'v> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&self.inner, f) + } +} + +impl ToValue for dyn fmt::Debug { + fn to_value(&self) -> Value { + Value::from_dyn_debug(self) + } +} + +impl ToValue for dyn fmt::Display { + fn to_value(&self) -> Value { + Value::from_dyn_display(self) + } +} + +#[cfg(feature = "kv_unstable_std")] +impl ToValue for dyn std::error::Error + 'static { + fn to_value(&self) -> Value { + Value::from_dyn_error(self) + } +} + +#[cfg(feature = "kv_unstable_serde")] +impl<'v> self::serde::Serialize for Value<'v> { + fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error> + where + S: self::serde::Serializer, + { + self.inner.serialize(s) + } +} + +#[cfg(feature = "kv_unstable_sval")] +impl<'v> self::sval::value::Value for Value<'v> { + fn stream(&self, stream: &mut self::sval::value::Stream) -> self::sval::value::Result { + self::sval::value::Value::stream(&self.inner, stream) + } +} + +#[cfg(feature = "kv_unstable_sval")] +impl ToValue for dyn self::sval::value::Value { + fn to_value(&self) -> Value { + Value::from_dyn_sval(self) + } +} + +impl ToValue for str { + fn to_value(&self) -> Value { + Value::from(self) + } +} + +impl<'v> From<&'v str> for Value<'v> { + fn from(value: &'v str) -> Self { + Value::from_value_bag(value) + } +} + +impl ToValue for () { + fn to_value(&self) -> Value { + Value::from_value_bag(()) + } +} + +impl<T> ToValue for Option<T> +where + T: ToValue, +{ + fn to_value(&self) -> Value { + match *self { + Some(ref value) => value.to_value(), + None => Value::from_value_bag(()), + } + } +} + +macro_rules! impl_to_value_primitive { + ($($into_ty:ty,)*) => { + $( + impl ToValue for $into_ty { + fn to_value(&self) -> Value { + Value::from(*self) + } + } + + impl<'v> From<$into_ty> for Value<'v> { + fn from(value: $into_ty) -> Self { + Value::from_value_bag(value) + } + } + )* + }; +} + +macro_rules! impl_value_to_primitive { + ($(#[doc = $doc:tt] $into_name:ident -> $into_ty:ty,)*) => { + impl<'v> Value<'v> { + $( + #[doc = $doc] + pub fn $into_name(&self) -> Option<$into_ty> { + self.inner.$into_name() + } + )* + } + } +} + +impl_to_value_primitive![usize, u8, u16, u32, u64, isize, i8, i16, i32, i64, f32, f64, char, bool,]; + +impl_value_to_primitive![ + #[doc = "Try convert this value into a `usize`."] + to_usize -> usize, + #[doc = "Try convert this value into a `u8`."] + to_u8 -> u8, + #[doc = "Try convert this value into a `u16`."] + to_u16 -> u16, + #[doc = "Try convert this value into a `u32`."] + to_u32 -> u32, + #[doc = "Try convert this value into a `u64`."] + to_u64 -> u64, + #[doc = "Try convert this value into a `isize`."] + to_isize -> isize, + #[doc = "Try convert this value into a `i8`."] + to_i8 -> i8, + #[doc = "Try convert this value into a `i16`."] + to_i16 -> i16, + #[doc = "Try convert this value into a `i32`."] + to_i32 -> i32, + #[doc = "Try convert this value into a `i64`."] + to_i64 -> i64, + #[doc = "Try convert this value into a `f32`."] + to_f32 -> f32, + #[doc = "Try convert this value into a `f64`."] + to_f64 -> f64, + #[doc = "Try convert this value into a `char`."] + to_char -> char, + #[doc = "Try convert this value into a `bool`."] + to_bool -> bool, +]; + +impl<'v> Value<'v> { + /// Try convert this value into an error. + #[cfg(feature = "kv_unstable_std")] + pub fn to_error(&self) -> Option<&(dyn std::error::Error + 'static)> { + self.inner.to_error() + } + + /// Try convert this value into a borrowed string. + pub fn to_borrowed_str(&self) -> Option<&str> { + self.inner.to_borrowed_str() + } +} + +#[cfg(feature = "std")] +mod std_support { + use super::*; + + use std::borrow::Cow; + + impl<T> ToValue for Box<T> + where + T: ToValue + ?Sized, + { + fn to_value(&self) -> Value { + (**self).to_value() + } + } + + impl ToValue for String { + fn to_value(&self) -> Value { + Value::from(&**self) + } + } + + impl<'v> ToValue for Cow<'v, str> { + fn to_value(&self) -> Value { + Value::from(&**self) + } + } + + impl<'v> Value<'v> { + /// Try convert this value into a string. + pub fn to_str(&self) -> Option<Cow<str>> { + self.inner.to_str() + } + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + + pub(crate) use super::value_bag::test::Token; + + impl<'v> Value<'v> { + pub(crate) fn to_token(&self) -> Token { + self.inner.to_token() + } + } + + fn unsigned() -> impl Iterator<Item = Value<'static>> { + vec![ + Value::from(8u8), + Value::from(16u16), + Value::from(32u32), + Value::from(64u64), + Value::from(1usize), + ] + .into_iter() + } + + fn signed() -> impl Iterator<Item = Value<'static>> { + vec![ + Value::from(-8i8), + Value::from(-16i16), + Value::from(-32i32), + Value::from(-64i64), + Value::from(-1isize), + ] + .into_iter() + } + + fn float() -> impl Iterator<Item = Value<'static>> { + vec![Value::from(32.32f32), Value::from(64.64f64)].into_iter() + } + + fn bool() -> impl Iterator<Item = Value<'static>> { + vec![Value::from(true), Value::from(false)].into_iter() + } + + fn str() -> impl Iterator<Item = Value<'static>> { + vec![Value::from("a string"), Value::from("a loong string")].into_iter() + } + + fn char() -> impl Iterator<Item = Value<'static>> { + vec![Value::from('a'), Value::from('⛰')].into_iter() + } + + #[test] + fn test_capture_fmt() { + assert_eq!(Some(42u64), Value::capture_display(&42).to_u64()); + assert_eq!(Some(42u64), Value::capture_debug(&42).to_u64()); + + assert!(Value::from_display(&42).to_u64().is_none()); + assert!(Value::from_debug(&42).to_u64().is_none()); + } + + #[cfg(feature = "kv_unstable_std")] + #[test] + fn test_capture_error() { + let err = std::io::Error::from(std::io::ErrorKind::Other); + + assert!(Value::capture_error(&err).to_error().is_some()); + assert!(Value::from_dyn_error(&err).to_error().is_some()); + } + + #[cfg(feature = "kv_unstable_serde")] + #[test] + fn test_capture_serde() { + assert_eq!(Some(42u64), Value::capture_serde(&42).to_u64()); + + assert_eq!(Some(42u64), Value::from_serde(&42).to_u64()); + } + + #[cfg(feature = "kv_unstable_sval")] + #[test] + fn test_capture_sval() { + assert_eq!(Some(42u64), Value::capture_sval(&42).to_u64()); + + assert_eq!(Some(42u64), Value::from_sval(&42).to_u64()); + } + + #[test] + fn test_to_value_display() { + assert_eq!(42u64.to_value().to_string(), "42"); + assert_eq!(42i64.to_value().to_string(), "42"); + assert_eq!(42.01f64.to_value().to_string(), "42.01"); + assert_eq!(true.to_value().to_string(), "true"); + assert_eq!('a'.to_value().to_string(), "a"); + assert_eq!("a loong string".to_value().to_string(), "a loong string"); + assert_eq!(Some(true).to_value().to_string(), "true"); + assert_eq!(().to_value().to_string(), "None"); + assert_eq!(Option::None::<bool>.to_value().to_string(), "None"); + } + + #[test] + fn test_to_value_structured() { + assert_eq!(42u64.to_value().to_token(), Token::U64(42)); + assert_eq!(42i64.to_value().to_token(), Token::I64(42)); + assert_eq!(42.01f64.to_value().to_token(), Token::F64(42.01)); + assert_eq!(true.to_value().to_token(), Token::Bool(true)); + assert_eq!('a'.to_value().to_token(), Token::Char('a')); + assert_eq!( + "a loong string".to_value().to_token(), + Token::Str("a loong string".into()) + ); + assert_eq!(Some(true).to_value().to_token(), Token::Bool(true)); + assert_eq!(().to_value().to_token(), Token::None); + assert_eq!(Option::None::<bool>.to_value().to_token(), Token::None); + } + + #[test] + fn test_to_number() { + for v in unsigned().chain(signed()).chain(float()) { + assert!(v.to_u8().is_some()); + assert!(v.to_u16().is_some()); + assert!(v.to_u32().is_some()); + assert!(v.to_u64().is_some()); + assert!(v.to_usize().is_some()); + + assert!(v.to_i8().is_some()); + assert!(v.to_i16().is_some()); + assert!(v.to_i32().is_some()); + assert!(v.to_i64().is_some()); + assert!(v.to_isize().is_some()); + + assert!(v.to_f32().is_some()); + assert!(v.to_f64().is_some()); + } + + for v in bool().chain(str()).chain(char()) { + assert!(v.to_u8().is_none()); + assert!(v.to_u16().is_none()); + assert!(v.to_u32().is_none()); + assert!(v.to_u64().is_none()); + + assert!(v.to_i8().is_none()); + assert!(v.to_i16().is_none()); + assert!(v.to_i32().is_none()); + assert!(v.to_i64().is_none()); + + assert!(v.to_f32().is_none()); + assert!(v.to_f64().is_none()); + } + } + + #[test] + fn test_to_str() { + for v in str() { + assert!(v.to_borrowed_str().is_some()); + + #[cfg(feature = "std")] + assert!(v.to_str().is_some()); + } + + let short_lived = String::from("short lived"); + let v = Value::from(&*short_lived); + + assert!(v.to_borrowed_str().is_some()); + + #[cfg(feature = "std")] + assert!(v.to_str().is_some()); + + for v in unsigned().chain(signed()).chain(float()).chain(bool()) { + assert!(v.to_borrowed_str().is_none()); + + #[cfg(feature = "std")] + assert!(v.to_str().is_none()); + } + } + + #[test] + fn test_to_bool() { + for v in bool() { + assert!(v.to_bool().is_some()); + } + + for v in unsigned() + .chain(signed()) + .chain(float()) + .chain(str()) + .chain(char()) + { + assert!(v.to_bool().is_none()); + } + } + + #[test] + fn test_to_char() { + for v in char() { + assert!(v.to_char().is_some()); + } + + for v in unsigned() + .chain(signed()) + .chain(float()) + .chain(str()) + .chain(bool()) + { + assert!(v.to_char().is_none()); + } + } +} diff --git a/src/kv/value/fill.rs b/src/kv/value/fill.rs deleted file mode 100644 index f34ba31d5..000000000 --- a/src/kv/value/fill.rs +++ /dev/null @@ -1,164 +0,0 @@ -//! Lazy value initialization. - -use std::fmt; - -use super::internal::{Inner, Visitor}; -use super::{Error, Value}; - -impl<'v> Value<'v> { - /// Get a value from a fillable slot. - pub fn from_fill<T>(value: &'v T) -> Self - where - T: Fill, - { - Value { - inner: Inner::Fill(value), - } - } -} - -/// A type that requires extra work to convert into a [`Value`](struct.Value.html). -/// -/// This trait is a more advanced initialization API than [`ToValue`](trait.ToValue.html). -/// It's intended for erased values coming from other logging frameworks that may need -/// to perform extra work to determine the concrete type to use. -pub trait Fill { - /// Fill a value. - fn fill(&self, slot: &mut Slot) -> Result<(), Error>; -} - -impl<'a, T> Fill for &'a T -where - T: Fill + ?Sized, -{ - fn fill(&self, slot: &mut Slot) -> Result<(), Error> { - (**self).fill(slot) - } -} - -/// A value slot to fill using the [`Fill`](trait.Fill.html) trait. -pub struct Slot<'s, 'f> { - filled: bool, - visitor: &'s mut dyn Visitor<'f>, -} - -impl<'s, 'f> fmt::Debug for Slot<'s, 'f> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("Slot").finish() - } -} - -impl<'s, 'f> Slot<'s, 'f> { - pub(super) fn new(visitor: &'s mut dyn Visitor<'f>) -> Self { - Slot { - visitor, - filled: false, - } - } - - pub(super) fn fill<F>(&mut self, f: F) -> Result<(), Error> - where - F: FnOnce(&mut dyn Visitor<'f>) -> Result<(), Error>, - { - assert!(!self.filled, "the slot has already been filled"); - self.filled = true; - - f(self.visitor) - } - - /// Fill the slot with a value. - /// - /// The given value doesn't need to satisfy any particular lifetime constraints. - /// - /// # Panics - /// - /// Calling more than a single `fill` method on this slot will panic. - pub fn fill_any<T>(&mut self, value: T) -> Result<(), Error> - where - T: Into<Value<'f>>, - { - self.fill(|visitor| value.into().inner.visit(visitor)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn fill_value_borrowed() { - struct TestFill; - - impl Fill for TestFill { - fn fill(&self, slot: &mut Slot) -> Result<(), Error> { - let dbg: &dyn fmt::Debug = &1; - - slot.fill_debug(&dbg) - } - } - - assert_eq!("1", Value::from_fill(&TestFill).to_string()); - } - - #[test] - fn fill_value_owned() { - struct TestFill; - - impl Fill for TestFill { - fn fill(&self, slot: &mut Slot) -> Result<(), Error> { - slot.fill_any("a string") - } - } - } - - #[test] - #[should_panic] - fn fill_multiple_times_panics() { - struct BadFill; - - impl Fill for BadFill { - fn fill(&self, slot: &mut Slot) -> Result<(), Error> { - slot.fill_any(42)?; - slot.fill_any(6789)?; - - Ok(()) - } - } - - let _ = Value::from_fill(&BadFill).to_string(); - } - - #[test] - fn fill_cast() { - struct TestFill; - - impl Fill for TestFill { - fn fill(&self, slot: &mut Slot) -> Result<(), Error> { - slot.fill_any("a string") - } - } - - assert_eq!( - "a string", - Value::from_fill(&TestFill) - .to_borrowed_str() - .expect("invalid value") - ); - } - - #[test] - fn fill_debug() { - struct TestFill; - - impl Fill for TestFill { - fn fill(&self, slot: &mut Slot) -> Result<(), Error> { - slot.fill_any(42u64) - } - } - - assert_eq!( - format!("{:04?}", 42u64), - format!("{:04?}", Value::from_fill(&TestFill)), - ) - } -} diff --git a/src/kv/value/impls.rs b/src/kv/value/impls.rs deleted file mode 100644 index 506128bf2..000000000 --- a/src/kv/value/impls.rs +++ /dev/null @@ -1,141 +0,0 @@ -//! Converting standard types into `Value`s. -//! -//! This module provides `ToValue` implementations for commonly -//! logged types from the standard library. - -use std::fmt; - -use super::{Primitive, ToValue, Value}; - -impl<'v> ToValue for &'v str { - fn to_value(&self) -> Value { - Value::from(*self) - } -} - -impl<'v> From<&'v str> for Value<'v> { - fn from(value: &'v str) -> Self { - Value::from_primitive(value) - } -} - -impl<'v> ToValue for fmt::Arguments<'v> { - fn to_value(&self) -> Value { - Value::from(*self) - } -} - -impl<'v> From<fmt::Arguments<'v>> for Value<'v> { - fn from(value: fmt::Arguments<'v>) -> Self { - Value::from_primitive(value) - } -} - -impl ToValue for () { - fn to_value(&self) -> Value { - Value::from_primitive(Primitive::None) - } -} - -impl<T> ToValue for Option<T> -where - T: ToValue, -{ - fn to_value(&self) -> Value { - match *self { - Some(ref value) => value.to_value(), - None => Value::from_primitive(Primitive::None), - } - } -} - -macro_rules! impl_to_value_primitive { - ($($into_ty:ty,)*) => { - $( - impl ToValue for $into_ty { - fn to_value(&self) -> Value { - Value::from(*self) - } - } - - impl<'v> From<$into_ty> for Value<'v> { - fn from(value: $into_ty) -> Self { - Value::from_primitive(value) - } - } - )* - }; -} - -impl_to_value_primitive![usize, u8, u16, u32, u64, isize, i8, i16, i32, i64, f32, f64, char, bool,]; - -#[cfg(feature = "std")] -mod std_support { - use super::*; - - use std::borrow::Cow; - - impl<T> ToValue for Box<T> - where - T: ToValue + ?Sized, - { - fn to_value(&self) -> Value { - (**self).to_value() - } - } - - impl ToValue for String { - fn to_value(&self) -> Value { - Value::from_primitive(Primitive::Str(&*self)) - } - } - - impl<'v> ToValue for Cow<'v, str> { - fn to_value(&self) -> Value { - Value::from_primitive(Primitive::Str(&*self)) - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use kv::value::test::Token; - - #[test] - fn test_to_value_display() { - assert_eq!(42u64.to_value().to_string(), "42"); - assert_eq!(42i64.to_value().to_string(), "42"); - assert_eq!(42.01f64.to_value().to_string(), "42.01"); - assert_eq!(true.to_value().to_string(), "true"); - assert_eq!('a'.to_value().to_string(), "a"); - assert_eq!( - format_args!("a {}", "value").to_value().to_string(), - "a value" - ); - assert_eq!("a loong string".to_value().to_string(), "a loong string"); - assert_eq!(Some(true).to_value().to_string(), "true"); - assert_eq!(().to_value().to_string(), "None"); - assert_eq!(Option::None::<bool>.to_value().to_string(), "None"); - } - - #[test] - fn test_to_value_structured() { - assert_eq!(42u64.to_value().to_token(), Token::U64(42)); - assert_eq!(42i64.to_value().to_token(), Token::I64(42)); - assert_eq!(42.01f64.to_value().to_token(), Token::F64(42.01)); - assert_eq!(true.to_value().to_token(), Token::Bool(true)); - assert_eq!('a'.to_value().to_token(), Token::Char('a')); - assert_eq!( - format_args!("a {}", "value").to_value().to_token(), - Token::Str("a value".into()) - ); - assert_eq!( - "a loong string".to_value().to_token(), - Token::Str("a loong string".into()) - ); - assert_eq!(Some(true).to_value().to_token(), Token::Bool(true)); - assert_eq!(().to_value().to_token(), Token::None); - assert_eq!(Option::None::<bool>.to_value().to_token(), Token::None); - } -} diff --git a/src/kv/value/internal/cast/mod.rs b/src/kv/value/internal/cast/mod.rs deleted file mode 100644 index ec6a22379..000000000 --- a/src/kv/value/internal/cast/mod.rs +++ /dev/null @@ -1,425 +0,0 @@ -//! Coerce a `Value` into some concrete types. -//! -//! These operations are cheap when the captured value is a simple primitive, -//! but may end up executing arbitrary caller code if the value is complex. -//! They will also attempt to downcast erased types into a primitive where possible. - -use std::fmt; - -use super::{Inner, Primitive, Visitor}; -use crate::kv::value::{Error, Value}; - -mod primitive; - -/// Attempt to capture a primitive from some generic value. -/// -/// If the value is a primitive type, then cast it here, avoiding needing to erase its value -/// This makes `Value`s produced by `Value::from_*` more useful -pub(super) fn try_from_primitive<'v, T: 'static>(value: &'v T) -> Option<Value<'v>> { - primitive::from_any(value).map(|primitive| Value { - inner: Inner::Primitive(primitive), - }) -} - -impl<'v> Value<'v> { - /// Try get a `usize` from this value. - /// - /// This method is cheap for primitive types, but may call arbitrary - /// serialization implementations for complex ones. - pub fn to_usize(&self) -> Option<usize> { - self.inner - .cast() - .into_primitive() - .into_u64() - .map(|v| v as usize) - } - - /// Try get a `u8` from this value. - /// - /// This method is cheap for primitive types, but may call arbitrary - /// serialization implementations for complex ones. - pub fn to_u8(&self) -> Option<u8> { - self.inner - .cast() - .into_primitive() - .into_u64() - .map(|v| v as u8) - } - - /// Try get a `u16` from this value. - /// - /// This method is cheap for primitive types, but may call arbitrary - /// serialization implementations for complex ones. - pub fn to_u16(&self) -> Option<u16> { - self.inner - .cast() - .into_primitive() - .into_u64() - .map(|v| v as u16) - } - - /// Try get a `u32` from this value. - /// - /// This method is cheap for primitive types, but may call arbitrary - /// serialization implementations for complex ones. - pub fn to_u32(&self) -> Option<u32> { - self.inner - .cast() - .into_primitive() - .into_u64() - .map(|v| v as u32) - } - - /// Try get a `u64` from this value. - /// - /// This method is cheap for primitive types, but may call arbitrary - /// serialization implementations for complex ones. - pub fn to_u64(&self) -> Option<u64> { - self.inner.cast().into_primitive().into_u64() - } - - /// Try get a `isize` from this value. - /// - /// This method is cheap for primitive types, but may call arbitrary - /// serialization implementations for complex ones. - pub fn to_isize(&self) -> Option<isize> { - self.inner - .cast() - .into_primitive() - .into_i64() - .map(|v| v as isize) - } - - /// Try get a `i8` from this value. - /// - /// This method is cheap for primitive types, but may call arbitrary - /// serialization implementations for complex ones. - pub fn to_i8(&self) -> Option<i8> { - self.inner - .cast() - .into_primitive() - .into_i64() - .map(|v| v as i8) - } - - /// Try get a `i16` from this value. - /// - /// This method is cheap for primitive types, but may call arbitrary - /// serialization implementations for complex ones. - pub fn to_i16(&self) -> Option<i16> { - self.inner - .cast() - .into_primitive() - .into_i64() - .map(|v| v as i16) - } - - /// Try get a `i32` from this value. - /// - /// This method is cheap for primitive types, but may call arbitrary - /// serialization implementations for complex ones. - pub fn to_i32(&self) -> Option<i32> { - self.inner - .cast() - .into_primitive() - .into_i64() - .map(|v| v as i32) - } - - /// Try get a `i64` from this value. - /// - /// This method is cheap for primitive types, but may call arbitrary - /// serialization implementations for complex ones. - pub fn to_i64(&self) -> Option<i64> { - self.inner.cast().into_primitive().into_i64() - } - - /// Try get a `f32` from this value. - /// - /// This method is cheap for primitive types, but may call arbitrary - /// serialization implementations for complex ones. - pub fn to_f32(&self) -> Option<f32> { - self.inner - .cast() - .into_primitive() - .into_f64() - .map(|v| v as f32) - } - - /// Try get a `f64` from this value. - /// - /// This method is cheap for primitive types, but may call arbitrary - /// serialization implementations for complex ones. - pub fn to_f64(&self) -> Option<f64> { - self.inner.cast().into_primitive().into_f64() - } - - /// Try get a `bool` from this value. - /// - /// This method is cheap for primitive types, but may call arbitrary - /// serialization implementations for complex ones. - pub fn to_bool(&self) -> Option<bool> { - self.inner.cast().into_primitive().into_bool() - } - - /// Try get a `char` from this value. - /// - /// This method is cheap for primitive types, but may call arbitrary - /// serialization implementations for complex ones. - pub fn to_char(&self) -> Option<char> { - self.inner.cast().into_primitive().into_char() - } - - /// Try get a `str` from this value. - /// - /// This method is cheap for primitive types. It won't allocate an owned - /// `String` if the value is a complex type. - pub fn to_borrowed_str(&self) -> Option<&str> { - self.inner.cast().into_primitive().into_borrowed_str() - } -} - -impl<'v> Inner<'v> { - /// Cast the inner value to another type. - fn cast(self) -> Cast<'v> { - struct CastVisitor<'v>(Cast<'v>); - - impl<'v> Visitor<'v> for CastVisitor<'v> { - fn debug(&mut self, _: &dyn fmt::Debug) -> Result<(), Error> { - Ok(()) - } - - fn u64(&mut self, v: u64) -> Result<(), Error> { - self.0 = Cast::Primitive(Primitive::Unsigned(v)); - Ok(()) - } - - fn i64(&mut self, v: i64) -> Result<(), Error> { - self.0 = Cast::Primitive(Primitive::Signed(v)); - Ok(()) - } - - fn f64(&mut self, v: f64) -> Result<(), Error> { - self.0 = Cast::Primitive(Primitive::Float(v)); - Ok(()) - } - - fn bool(&mut self, v: bool) -> Result<(), Error> { - self.0 = Cast::Primitive(Primitive::Bool(v)); - Ok(()) - } - - fn char(&mut self, v: char) -> Result<(), Error> { - self.0 = Cast::Primitive(Primitive::Char(v)); - Ok(()) - } - - #[cfg(feature = "std")] - fn str(&mut self, s: &str) -> Result<(), Error> { - self.0 = Cast::String(s.to_owned()); - Ok(()) - } - - #[cfg(not(feature = "std"))] - fn str(&mut self, _: &str) -> Result<(), Error> { - Ok(()) - } - - fn borrowed_str(&mut self, v: &'v str) -> Result<(), Error> { - self.0 = Cast::Primitive(Primitive::Str(v)); - Ok(()) - } - - fn none(&mut self) -> Result<(), Error> { - self.0 = Cast::Primitive(Primitive::None); - Ok(()) - } - - #[cfg(feature = "kv_unstable_sval")] - fn sval(&mut self, v: &dyn super::sval::Value) -> Result<(), Error> { - self.0 = super::sval::cast(v); - Ok(()) - } - } - - if let Inner::Primitive(value) = self { - Cast::Primitive(value) - } else { - // If the erased value isn't a primitive then we visit it - let mut cast = CastVisitor(Cast::Primitive(Primitive::None)); - let _ = self.visit(&mut cast); - cast.0 - } - } -} - -pub(super) enum Cast<'v> { - Primitive(Primitive<'v>), - #[cfg(feature = "std")] - String(String), -} - -impl<'v> Cast<'v> { - fn into_primitive(self) -> Primitive<'v> { - match self { - Cast::Primitive(value) => value, - #[cfg(feature = "std")] - _ => Primitive::None, - } - } -} - -impl<'v> Primitive<'v> { - fn into_borrowed_str(self) -> Option<&'v str> { - if let Primitive::Str(value) = self { - Some(value) - } else { - None - } - } - - fn into_u64(self) -> Option<u64> { - match self { - Primitive::Unsigned(value) => Some(value), - Primitive::Signed(value) => Some(value as u64), - Primitive::Float(value) => Some(value as u64), - _ => None, - } - } - - fn into_i64(self) -> Option<i64> { - match self { - Primitive::Signed(value) => Some(value), - Primitive::Unsigned(value) => Some(value as i64), - Primitive::Float(value) => Some(value as i64), - _ => None, - } - } - - fn into_f64(self) -> Option<f64> { - match self { - Primitive::Float(value) => Some(value), - Primitive::Unsigned(value) => Some(value as f64), - Primitive::Signed(value) => Some(value as f64), - _ => None, - } - } - - fn into_char(self) -> Option<char> { - if let Primitive::Char(value) = self { - Some(value) - } else { - None - } - } - - fn into_bool(self) -> Option<bool> { - if let Primitive::Bool(value) = self { - Some(value) - } else { - None - } - } -} - -#[cfg(feature = "std")] -mod std_support { - use super::*; - - use std::borrow::Cow; - - impl<'v> Value<'v> { - /// Try get a `usize` from this value. - /// - /// This method is cheap for primitive types, but may call arbitrary - /// serialization implementations for complex ones. If the serialization - /// implementation produces a short lived string it will be allocated. - pub fn to_str(&self) -> Option<Cow<str>> { - self.inner.cast().into_str() - } - } - - impl<'v> Cast<'v> { - pub(super) fn into_str(self) -> Option<Cow<'v, str>> { - match self { - Cast::Primitive(Primitive::Str(value)) => Some(value.into()), - Cast::String(value) => Some(value.into()), - _ => None, - } - } - } - - #[cfg(test)] - mod tests { - use crate::kv::ToValue; - - #[test] - fn primitive_cast() { - assert_eq!( - "a string", - "a string" - .to_owned() - .to_value() - .to_borrowed_str() - .expect("invalid value") - ); - assert_eq!( - "a string", - &*"a string".to_value().to_str().expect("invalid value") - ); - assert_eq!( - "a string", - &*"a string" - .to_owned() - .to_value() - .to_str() - .expect("invalid value") - ); - } - } -} - -#[cfg(test)] -mod tests { - use crate::kv::ToValue; - - #[test] - fn primitive_cast() { - assert_eq!( - "a string", - "a string" - .to_value() - .to_borrowed_str() - .expect("invalid value") - ); - assert_eq!( - "a string", - Some("a string") - .to_value() - .to_borrowed_str() - .expect("invalid value") - ); - - assert_eq!(1u8, 1u64.to_value().to_u8().expect("invalid value")); - assert_eq!(1u16, 1u64.to_value().to_u16().expect("invalid value")); - assert_eq!(1u32, 1u64.to_value().to_u32().expect("invalid value")); - assert_eq!(1u64, 1u64.to_value().to_u64().expect("invalid value")); - assert_eq!(1usize, 1u64.to_value().to_usize().expect("invalid value")); - - assert_eq!(-1i8, -1i64.to_value().to_i8().expect("invalid value")); - assert_eq!(-1i16, -1i64.to_value().to_i16().expect("invalid value")); - assert_eq!(-1i32, -1i64.to_value().to_i32().expect("invalid value")); - assert_eq!(-1i64, -1i64.to_value().to_i64().expect("invalid value")); - assert_eq!(-1isize, -1i64.to_value().to_isize().expect("invalid value")); - - assert!(1f32.to_value().to_f32().is_some(), "invalid value"); - assert!(1f64.to_value().to_f64().is_some(), "invalid value"); - - assert_eq!(1u32, 1i64.to_value().to_u32().expect("invalid value")); - assert_eq!(1i32, 1u64.to_value().to_i32().expect("invalid value")); - assert!(1f32.to_value().to_i32().is_some(), "invalid value"); - - assert_eq!('a', 'a'.to_value().to_char().expect("invalid value")); - assert_eq!(true, true.to_value().to_bool().expect("invalid value")); - } -} diff --git a/src/kv/value/internal/cast/primitive.rs b/src/kv/value/internal/cast/primitive.rs deleted file mode 100644 index c306e66f6..000000000 --- a/src/kv/value/internal/cast/primitive.rs +++ /dev/null @@ -1,120 +0,0 @@ -/* -This module generates code to try efficiently convert some arbitrary `T: 'static` into -a `Primitive`. It's used by both the `build.rs` script and by the source itself. There -are currently two implementations here: - -- When the compiler version is less than `1.46.0` we check type ids at runtime. This -means generating a pre-sorted list of type ids at compile time using the `build.rs` -and matching them at runtime. -- When the compiler version is at least `1.46.0` we use const evaluation to check type ids -at compile time. There's no generated code from `build.rs` involved. - -In the future when `min_specialization` is stabilized we could use it instead and avoid needing -the `'static` bound altogether. -*/ - -// Use a build-time generated set of type ids to match a type with a conversion fn -#[cfg(srcbuild)] -pub(super) fn from_any<'v>( - value: &'v (dyn std::any::Any + 'static), -) -> Option<crate::kv::value::internal::Primitive<'v>> { - // The set of type ids that map to primitives are generated at build-time - // by the contents of `sorted_type_ids.expr`. These type ids are pre-sorted - // so that they can be searched efficiently. See the `sorted_type_ids.expr.rs` - // file for the set of types that appear in this list - let type_ids = include!(concat!(env!("OUT_DIR"), "/into_primitive.rs")); - - if let Ok(i) = type_ids.binary_search_by_key(&value.type_id(), |&(k, _)| k) { - Some((type_ids[i].1)(value)) - } else { - None - } -} - -// When the `src_build` config is not set then we're in the build script -#[cfg(not(srcbuild))] -#[allow(dead_code)] -pub fn generate() { - use std::path::Path; - use std::{env, fs}; - - macro_rules! type_ids { - ($($ty:ty,)*) => { - [ - $( - ( - std::any::TypeId::of::<$ty>(), - stringify!( - ( - std::any::TypeId::of::<$ty>(), - (|value| unsafe { - debug_assert_eq!(value.type_id(), std::any::TypeId::of::<$ty>()); - - // SAFETY: We verify the value is $ty before casting - let value = *(value as *const dyn std::any::Any as *const $ty); - crate::kv::value::internal::Primitive::from(value) - }) as for<'a> fn(&'a (dyn std::any::Any + 'static)) -> crate::kv::value::internal::Primitive<'a> - ) - ) - ), - )* - $( - ( - std::any::TypeId::of::<Option<$ty>>(), - stringify!( - ( - std::any::TypeId::of::<Option<$ty>>(), - (|value| unsafe { - debug_assert_eq!(value.type_id(), std::any::TypeId::of::<Option<$ty>>()); - - // SAFETY: We verify the value is Option<$ty> before casting - let value = *(value as *const dyn std::any::Any as *const Option<$ty>); - if let Some(value) = value { - crate::kv::value::internal::Primitive::from(value) - } else { - crate::kv::value::internal::Primitive::None - } - }) as for<'a> fn(&'a (dyn std::any::Any + 'static)) -> crate::kv::value::internal::Primitive<'a> - ) - ) - ), - )* - ] - }; - } - - // NOTE: The types here *must* match the ones used above when `const_type_id` is available - let mut type_ids = type_ids![ - usize, - u8, - u16, - u32, - u64, - isize, - i8, - i16, - i32, - i64, - f32, - f64, - char, - bool, - &'static str, - ]; - - type_ids.sort_by_key(|&(k, _)| k); - - let mut ordered_type_ids_expr = String::new(); - - ordered_type_ids_expr.push('['); - - for (_, v) in &type_ids { - ordered_type_ids_expr.push_str(v); - ordered_type_ids_expr.push(','); - } - - ordered_type_ids_expr.push(']'); - - let path = Path::new(&env::var_os("OUT_DIR").unwrap()).join("into_primitive.rs"); - fs::write(path, ordered_type_ids_expr).unwrap(); -} diff --git a/src/kv/value/internal/fmt.rs b/src/kv/value/internal/fmt.rs deleted file mode 100644 index bde703c20..000000000 --- a/src/kv/value/internal/fmt.rs +++ /dev/null @@ -1,315 +0,0 @@ -//! Integration between `Value` and `std::fmt`. -//! -//! This module allows any `Value` to implement the `fmt::Debug` and `fmt::Display` traits, -//! and for any `fmt::Debug` or `fmt::Display` to be captured as a `Value`. - -use std::fmt; - -use super::{cast, Inner, Visitor}; -use crate::kv; -use crate::kv::value::{Error, Slot, ToValue}; - -impl<'v> kv::Value<'v> { - /// Get a value from a debuggable type. - /// - /// This method will attempt to capture the given value as a well-known primitive - /// before resorting to using its `Debug` implementation. - pub fn capture_debug<T>(value: &'v T) -> Self - where - T: fmt::Debug + 'static, - { - cast::try_from_primitive(value).unwrap_or(kv::Value { - inner: Inner::Debug(value), - }) - } - - /// Get a value from a debuggable type. - pub fn from_debug<T>(value: &'v T) -> Self - where - T: fmt::Debug, - { - kv::Value { - inner: Inner::Debug(value), - } - } - - /// Get a value from a displayable type. - /// - /// This method will attempt to capture the given value as a well-known primitive - /// before resorting to using its `Display` implementation. - pub fn capture_display<T>(value: &'v T) -> Self - where - T: fmt::Display + 'static, - { - cast::try_from_primitive(value).unwrap_or(kv::Value { - inner: Inner::Display(value), - }) - } - - /// Get a value from a displayable type. - pub fn from_display<T>(value: &'v T) -> Self - where - T: fmt::Display, - { - kv::Value { - inner: Inner::Display(value), - } - } -} - -impl<'s, 'f> Slot<'s, 'f> { - /// Fill the slot with a debuggable value. - /// - /// The given value doesn't need to satisfy any particular lifetime constraints. - /// - /// # Panics - /// - /// Calling more than a single `fill` method on this slot will panic. - pub fn fill_debug<T>(&mut self, value: T) -> Result<(), Error> - where - T: fmt::Debug, - { - self.fill(|visitor| visitor.debug(&value)) - } - - /// Fill the slot with a displayable value. - /// - /// The given value doesn't need to satisfy any particular lifetime constraints. - /// - /// # Panics - /// - /// Calling more than a single `fill` method on this slot will panic. - pub fn fill_display<T>(&mut self, value: T) -> Result<(), Error> - where - T: fmt::Display, - { - self.fill(|visitor| visitor.display(&value)) - } -} - -pub(in kv::value) use self::fmt::{Arguments, Debug, Display}; - -impl<'v> fmt::Debug for kv::Value<'v> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - struct DebugVisitor<'a, 'b: 'a>(&'a mut fmt::Formatter<'b>); - - impl<'a, 'b: 'a, 'v> Visitor<'v> for DebugVisitor<'a, 'b> { - fn debug(&mut self, v: &dyn fmt::Debug) -> Result<(), Error> { - fmt::Debug::fmt(v, self.0)?; - - Ok(()) - } - - fn display(&mut self, v: &dyn fmt::Display) -> Result<(), Error> { - fmt::Display::fmt(v, self.0)?; - - Ok(()) - } - - fn u64(&mut self, v: u64) -> Result<(), Error> { - fmt::Debug::fmt(&v, self.0)?; - - Ok(()) - } - - fn i64(&mut self, v: i64) -> Result<(), Error> { - fmt::Debug::fmt(&v, self.0)?; - - Ok(()) - } - - fn f64(&mut self, v: f64) -> Result<(), Error> { - fmt::Debug::fmt(&v, self.0)?; - - Ok(()) - } - - fn bool(&mut self, v: bool) -> Result<(), Error> { - fmt::Debug::fmt(&v, self.0)?; - - Ok(()) - } - - fn char(&mut self, v: char) -> Result<(), Error> { - fmt::Debug::fmt(&v, self.0)?; - - Ok(()) - } - - fn str(&mut self, v: &str) -> Result<(), Error> { - fmt::Debug::fmt(&v, self.0)?; - - Ok(()) - } - - fn none(&mut self) -> Result<(), Error> { - self.debug(&format_args!("None")) - } - - #[cfg(feature = "kv_unstable_sval")] - fn sval(&mut self, v: &dyn super::sval::Value) -> Result<(), Error> { - super::sval::fmt(self.0, v) - } - } - - self.visit(&mut DebugVisitor(f)).map_err(|_| fmt::Error)?; - - Ok(()) - } -} - -impl<'v> fmt::Display for kv::Value<'v> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - struct DisplayVisitor<'a, 'b: 'a>(&'a mut fmt::Formatter<'b>); - - impl<'a, 'b: 'a, 'v> Visitor<'v> for DisplayVisitor<'a, 'b> { - fn debug(&mut self, v: &dyn fmt::Debug) -> Result<(), Error> { - fmt::Debug::fmt(v, self.0)?; - - Ok(()) - } - - fn display(&mut self, v: &dyn fmt::Display) -> Result<(), Error> { - fmt::Display::fmt(v, self.0)?; - - Ok(()) - } - - fn u64(&mut self, v: u64) -> Result<(), Error> { - fmt::Display::fmt(&v, self.0)?; - - Ok(()) - } - - fn i64(&mut self, v: i64) -> Result<(), Error> { - fmt::Display::fmt(&v, self.0)?; - - Ok(()) - } - - fn f64(&mut self, v: f64) -> Result<(), Error> { - fmt::Display::fmt(&v, self.0)?; - - Ok(()) - } - - fn bool(&mut self, v: bool) -> Result<(), Error> { - fmt::Display::fmt(&v, self.0)?; - - Ok(()) - } - - fn char(&mut self, v: char) -> Result<(), Error> { - fmt::Display::fmt(&v, self.0)?; - - Ok(()) - } - - fn str(&mut self, v: &str) -> Result<(), Error> { - fmt::Display::fmt(&v, self.0)?; - - Ok(()) - } - - fn none(&mut self) -> Result<(), Error> { - self.debug(&format_args!("None")) - } - - #[cfg(feature = "kv_unstable_sval")] - fn sval(&mut self, v: &dyn super::sval::Value) -> Result<(), Error> { - super::sval::fmt(self.0, v) - } - } - - self.visit(&mut DisplayVisitor(f)).map_err(|_| fmt::Error)?; - - Ok(()) - } -} - -impl<'v> ToValue for dyn fmt::Debug + 'v { - fn to_value(&self) -> kv::Value { - kv::Value::from(self) - } -} - -impl<'v> ToValue for dyn fmt::Display + 'v { - fn to_value(&self) -> kv::Value { - kv::Value::from(self) - } -} - -impl<'v> From<&'v (dyn fmt::Debug)> for kv::Value<'v> { - fn from(value: &'v (dyn fmt::Debug)) -> kv::Value<'v> { - kv::Value { - inner: Inner::Debug(value), - } - } -} - -impl<'v> From<&'v (dyn fmt::Display)> for kv::Value<'v> { - fn from(value: &'v (dyn fmt::Display)) -> kv::Value<'v> { - kv::Value { - inner: Inner::Display(value), - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use kv::value::test::Token; - - use crate::kv::value::ToValue; - - #[test] - fn fmt_capture() { - assert_eq!(kv::Value::capture_debug(&1u16).to_token(), Token::U64(1)); - assert_eq!(kv::Value::capture_display(&1u16).to_token(), Token::U64(1)); - - assert_eq!( - kv::Value::capture_debug(&Some(1u16)).to_token(), - Token::U64(1) - ); - } - - #[test] - fn fmt_cast() { - assert_eq!( - 42u32, - kv::Value::capture_debug(&42u64) - .to_u32() - .expect("invalid value") - ); - - assert_eq!( - "a string", - kv::Value::capture_display(&"a string") - .to_borrowed_str() - .expect("invalid value") - ); - } - - #[test] - fn fmt_debug() { - assert_eq!( - format!("{:?}", "a string"), - format!("{:?}", "a string".to_value()), - ); - - assert_eq!( - format!("{:04?}", 42u64), - format!("{:04?}", 42u64.to_value()), - ); - } - - #[test] - fn fmt_display() { - assert_eq!( - format!("{}", "a string"), - format!("{}", "a string".to_value()), - ); - - assert_eq!(format!("{:04}", 42u64), format!("{:04}", 42u64.to_value()),); - } -} diff --git a/src/kv/value/internal/mod.rs b/src/kv/value/internal/mod.rs deleted file mode 100644 index 4acbe683c..000000000 --- a/src/kv/value/internal/mod.rs +++ /dev/null @@ -1,210 +0,0 @@ -//! The internal `Value` serialization API. -//! -//! This implementation isn't intended to be public. It may need to change -//! for optimizations or to support new external serialization frameworks. - -use super::{Error, Fill, Slot}; - -pub(super) mod cast; -pub(super) mod fmt; -#[cfg(feature = "kv_unstable_sval")] -pub(super) mod sval; - -/// A container for a structured value for a specific kind of visitor. -#[derive(Clone, Copy)] -pub(super) enum Inner<'v> { - /// A simple primitive value that can be copied without allocating. - Primitive(Primitive<'v>), - /// A value that can be filled. - Fill(&'v (dyn Fill)), - /// A debuggable value. - Debug(&'v (dyn fmt::Debug)), - /// A displayable value. - Display(&'v (dyn fmt::Display)), - - #[cfg(feature = "kv_unstable_sval")] - /// A structured value from `sval`. - Sval(&'v (dyn sval::Value)), -} - -impl<'v> Inner<'v> { - pub(super) fn visit(self, visitor: &mut dyn Visitor<'v>) -> Result<(), Error> { - match self { - Inner::Primitive(value) => value.visit(visitor), - - Inner::Debug(value) => visitor.debug(value), - Inner::Display(value) => visitor.display(value), - - Inner::Fill(value) => value.fill(&mut Slot::new(visitor)), - - #[cfg(feature = "kv_unstable_sval")] - Inner::Sval(value) => visitor.sval(value), - } - } -} - -/// The internal serialization contract. -pub(super) trait Visitor<'v> { - fn debug(&mut self, v: &dyn fmt::Debug) -> Result<(), Error>; - fn display(&mut self, v: &dyn fmt::Display) -> Result<(), Error> { - self.debug(&format_args!("{}", v)) - } - - fn u64(&mut self, v: u64) -> Result<(), Error>; - fn i64(&mut self, v: i64) -> Result<(), Error>; - fn f64(&mut self, v: f64) -> Result<(), Error>; - fn bool(&mut self, v: bool) -> Result<(), Error>; - fn char(&mut self, v: char) -> Result<(), Error>; - - fn str(&mut self, v: &str) -> Result<(), Error>; - fn borrowed_str(&mut self, v: &'v str) -> Result<(), Error> { - self.str(v) - } - - fn none(&mut self) -> Result<(), Error>; - - #[cfg(feature = "kv_unstable_sval")] - fn sval(&mut self, v: &dyn sval::Value) -> Result<(), Error>; -} - -/// A captured primitive value. -/// -/// These values are common and cheap to copy around. -#[derive(Clone, Copy)] -pub(super) enum Primitive<'v> { - Signed(i64), - Unsigned(u64), - Float(f64), - Bool(bool), - Char(char), - Str(&'v str), - Fmt(fmt::Arguments<'v>), - None, -} - -impl<'v> Primitive<'v> { - fn visit(self, visitor: &mut dyn Visitor<'v>) -> Result<(), Error> { - match self { - Primitive::Signed(value) => visitor.i64(value), - Primitive::Unsigned(value) => visitor.u64(value), - Primitive::Float(value) => visitor.f64(value), - Primitive::Bool(value) => visitor.bool(value), - Primitive::Char(value) => visitor.char(value), - Primitive::Str(value) => visitor.borrowed_str(value), - Primitive::Fmt(value) => visitor.debug(&value), - Primitive::None => visitor.none(), - } - } -} - -impl<'v> From<u8> for Primitive<'v> { - #[inline] - fn from(v: u8) -> Self { - Primitive::Unsigned(v as u64) - } -} - -impl<'v> From<u16> for Primitive<'v> { - #[inline] - fn from(v: u16) -> Self { - Primitive::Unsigned(v as u64) - } -} - -impl<'v> From<u32> for Primitive<'v> { - #[inline] - fn from(v: u32) -> Self { - Primitive::Unsigned(v as u64) - } -} - -impl<'v> From<u64> for Primitive<'v> { - #[inline] - fn from(v: u64) -> Self { - Primitive::Unsigned(v) - } -} - -impl<'v> From<usize> for Primitive<'v> { - #[inline] - fn from(v: usize) -> Self { - Primitive::Unsigned(v as u64) - } -} - -impl<'v> From<i8> for Primitive<'v> { - #[inline] - fn from(v: i8) -> Self { - Primitive::Signed(v as i64) - } -} - -impl<'v> From<i16> for Primitive<'v> { - #[inline] - fn from(v: i16) -> Self { - Primitive::Signed(v as i64) - } -} - -impl<'v> From<i32> for Primitive<'v> { - #[inline] - fn from(v: i32) -> Self { - Primitive::Signed(v as i64) - } -} - -impl<'v> From<i64> for Primitive<'v> { - #[inline] - fn from(v: i64) -> Self { - Primitive::Signed(v) - } -} - -impl<'v> From<isize> for Primitive<'v> { - #[inline] - fn from(v: isize) -> Self { - Primitive::Signed(v as i64) - } -} - -impl<'v> From<f32> for Primitive<'v> { - #[inline] - fn from(v: f32) -> Self { - Primitive::Float(v as f64) - } -} - -impl<'v> From<f64> for Primitive<'v> { - #[inline] - fn from(v: f64) -> Self { - Primitive::Float(v) - } -} - -impl<'v> From<bool> for Primitive<'v> { - #[inline] - fn from(v: bool) -> Self { - Primitive::Bool(v) - } -} - -impl<'v> From<char> for Primitive<'v> { - #[inline] - fn from(v: char) -> Self { - Primitive::Char(v) - } -} - -impl<'v> From<&'v str> for Primitive<'v> { - #[inline] - fn from(v: &'v str) -> Self { - Primitive::Str(v) - } -} - -impl<'v> From<fmt::Arguments<'v>> for Primitive<'v> { - #[inline] - fn from(v: fmt::Arguments<'v>) -> Self { - Primitive::Fmt(v) - } -} diff --git a/src/kv/value/internal/sval.rs b/src/kv/value/internal/sval.rs deleted file mode 100644 index 252efd152..000000000 --- a/src/kv/value/internal/sval.rs +++ /dev/null @@ -1,252 +0,0 @@ -//! Integration between `Value` and `sval`. -//! -//! This module allows any `Value` to implement the `sval::Value` trait, -//! and for any `sval::Value` to be captured as a `Value`. - -extern crate sval; - -use std::fmt; - -use super::cast::{self, Cast}; -use super::{Inner, Primitive, Visitor}; -use crate::kv; -use crate::kv::value::{Error, Slot, ToValue}; - -impl<'v> kv::Value<'v> { - /// Get a value from a structured type. - /// - /// This method will attempt to capture the given value as a well-known primitive - /// before resorting to using its `Value` implementation. - pub fn capture_sval<T>(value: &'v T) -> Self - where - T: sval::Value + 'static, - { - cast::try_from_primitive(value).unwrap_or(kv::Value { - inner: Inner::Sval(value), - }) - } - - /// Get a value from a structured type. - pub fn from_sval<T>(value: &'v T) -> Self - where - T: sval::Value, - { - kv::Value { - inner: Inner::Sval(value), - } - } -} - -impl<'s, 'f> Slot<'s, 'f> { - /// Fill the slot with a structured value. - /// - /// The given value doesn't need to satisfy any particular lifetime constraints. - /// - /// # Panics - /// - /// Calling more than a single `fill` method on this slot will panic. - pub fn fill_sval<T>(&mut self, value: T) -> Result<(), Error> - where - T: sval::Value, - { - self.fill(|visitor| visitor.sval(&value)) - } -} - -impl<'v> sval::Value for kv::Value<'v> { - fn stream(&self, s: &mut sval::value::Stream) -> sval::value::Result { - struct SvalVisitor<'a, 'b: 'a>(&'a mut sval::value::Stream<'b>); - - impl<'a, 'b: 'a, 'v> Visitor<'v> for SvalVisitor<'a, 'b> { - fn debug(&mut self, v: &dyn fmt::Debug) -> Result<(), Error> { - self.0 - .fmt(format_args!("{:?}", v)) - .map_err(Error::from_sval) - } - - fn u64(&mut self, v: u64) -> Result<(), Error> { - self.0.u64(v).map_err(Error::from_sval) - } - - fn i64(&mut self, v: i64) -> Result<(), Error> { - self.0.i64(v).map_err(Error::from_sval) - } - - fn f64(&mut self, v: f64) -> Result<(), Error> { - self.0.f64(v).map_err(Error::from_sval) - } - - fn bool(&mut self, v: bool) -> Result<(), Error> { - self.0.bool(v).map_err(Error::from_sval) - } - - fn char(&mut self, v: char) -> Result<(), Error> { - self.0.char(v).map_err(Error::from_sval) - } - - fn str(&mut self, v: &str) -> Result<(), Error> { - self.0.str(v).map_err(Error::from_sval) - } - - fn none(&mut self) -> Result<(), Error> { - self.0.none().map_err(Error::from_sval) - } - - fn sval(&mut self, v: &dyn sval::Value) -> Result<(), Error> { - self.0.any(v).map_err(Error::from_sval) - } - } - - self.visit(&mut SvalVisitor(s)).map_err(Error::into_sval)?; - - Ok(()) - } -} - -impl<'v> ToValue for dyn sval::Value + 'v { - fn to_value(&self) -> kv::Value { - kv::Value::from(self) - } -} - -impl<'v> From<&'v (dyn sval::Value)> for kv::Value<'v> { - fn from(value: &'v (dyn sval::Value)) -> kv::Value<'v> { - kv::Value { - inner: Inner::Sval(value), - } - } -} - -pub(in kv::value) use self::sval::Value; - -pub(super) fn fmt(f: &mut fmt::Formatter, v: &dyn sval::Value) -> Result<(), Error> { - sval::fmt::debug(f, v)?; - Ok(()) -} - -pub(super) fn cast<'v>(v: &dyn sval::Value) -> Cast<'v> { - struct CastStream<'v>(Cast<'v>); - - impl<'v> sval::Stream for CastStream<'v> { - fn u64(&mut self, v: u64) -> sval::stream::Result { - self.0 = Cast::Primitive(Primitive::Unsigned(v)); - Ok(()) - } - - fn i64(&mut self, v: i64) -> sval::stream::Result { - self.0 = Cast::Primitive(Primitive::Signed(v)); - Ok(()) - } - - fn f64(&mut self, v: f64) -> sval::stream::Result { - self.0 = Cast::Primitive(Primitive::Float(v)); - Ok(()) - } - - fn char(&mut self, v: char) -> sval::stream::Result { - self.0 = Cast::Primitive(Primitive::Char(v)); - Ok(()) - } - - fn bool(&mut self, v: bool) -> sval::stream::Result { - self.0 = Cast::Primitive(Primitive::Bool(v)); - Ok(()) - } - - #[cfg(feature = "std")] - fn str(&mut self, s: &str) -> sval::stream::Result { - self.0 = Cast::String(s.into()); - Ok(()) - } - } - - let mut cast = CastStream(Cast::Primitive(Primitive::None)); - let _ = sval::stream(&mut cast, v); - - cast.0 -} - -impl Error { - fn from_sval(_: sval::value::Error) -> Self { - Error::msg("`sval` serialization failed") - } - - fn into_sval(self) -> sval::value::Error { - sval::value::Error::msg("`sval` serialization failed") - } -} - -#[cfg(test)] -mod tests { - use super::*; - use kv::value::test::Token; - - #[test] - fn sval_capture() { - assert_eq!(kv::Value::capture_sval(&42u64).to_token(), Token::U64(42)); - } - - #[test] - fn sval_cast() { - assert_eq!( - 42u32, - kv::Value::capture_sval(&42u64) - .to_u32() - .expect("invalid value") - ); - - assert_eq!( - "a string", - kv::Value::capture_sval(&"a string") - .to_borrowed_str() - .expect("invalid value") - ); - - #[cfg(feature = "std")] - assert_eq!( - "a string", - kv::Value::capture_sval(&"a string") - .to_str() - .expect("invalid value") - ); - } - - #[test] - fn sval_structured() { - let value = kv::Value::from(42u64); - let expected = vec![sval::test::Token::Unsigned(42)]; - - assert_eq!(sval::test::tokens(value), expected); - } - - #[test] - fn sval_debug() { - struct TestSval; - - impl sval::Value for TestSval { - fn stream(&self, stream: &mut sval::value::Stream) -> sval::value::Result { - stream.u64(42) - } - } - - assert_eq!( - format!("{:04?}", 42u64), - format!("{:04?}", kv::Value::from_sval(&TestSval)), - ); - } - - #[cfg(feature = "std")] - mod std_support { - use super::*; - - #[test] - fn sval_cast() { - assert_eq!( - "a string", - kv::Value::capture_sval(&"a string".to_owned()) - .to_str() - .expect("invalid value") - ); - } - } -} diff --git a/src/kv/value/mod.rs b/src/kv/value/mod.rs deleted file mode 100644 index 8d8282624..000000000 --- a/src/kv/value/mod.rs +++ /dev/null @@ -1,180 +0,0 @@ -//! Structured values. - -mod fill; -mod impls; -mod internal; - -#[cfg(test)] -pub(in kv) mod test; - -pub use self::fill::{Fill, Slot}; -pub use kv::Error; - -use self::internal::{Inner, Primitive, Visitor}; - -/// A type that can be converted into a [`Value`](struct.Value.html). -pub trait ToValue { - /// Perform the conversion. - fn to_value(&self) -> Value; -} - -impl<'a, T> ToValue for &'a T -where - T: ToValue + ?Sized, -{ - fn to_value(&self) -> Value { - (**self).to_value() - } -} - -impl<'v> ToValue for Value<'v> { - fn to_value(&self) -> Value { - Value { inner: self.inner } - } -} - -/// A value in a structured key-value pair. -/// -/// # Capturing values -/// -/// There are a few ways to capture a value: -/// -/// - Using the `Value::capture_*` methods. -/// - Using the `Value::from_*` methods. -/// - Using the `ToValue` trait. -/// - Using the standard `From` trait. -/// - Using the `Fill` API. -/// -/// ## Using the `Value::capture_*` methods -/// -/// `Value` offers a few constructor methods that capture values of different kinds. -/// These methods require a `T: 'static` to support downcasting. -/// -/// ``` -/// use log::kv::Value; -/// -/// let value = Value::capture_debug(&42i32); -/// -/// assert_eq!(Some(42), value.to_i32()); -/// ``` -/// -/// ## Using the `Value::from_*` methods -/// -/// `Value` offers a few constructor methods that capture values of different kinds. -/// These methods don't require `T: 'static`, but can't support downcasting. -/// -/// ``` -/// use log::kv::Value; -/// -/// let value = Value::from_debug(&42i32); -/// -/// assert_eq!(None, value.to_i32()); -/// ``` -/// -/// ## Using the `ToValue` trait -/// -/// The `ToValue` trait can be used to capture values generically. -/// It's the bound used by `Source`. -/// -/// ``` -/// # use log::kv::ToValue; -/// let value = 42i32.to_value(); -/// -/// assert_eq!(Some(42), value.to_i32()); -/// ``` -/// -/// ``` -/// # use std::fmt::Debug; -/// use log::kv::ToValue; -/// -/// let value = (&42i32 as &dyn Debug).to_value(); -/// -/// assert_eq!(None, value.to_i32()); -/// ``` -/// -/// ## Using the standard `From` trait -/// -/// Standard types that implement `ToValue` also implement `From`. -/// -/// ``` -/// use log::kv::Value; -/// -/// let value = Value::from(42i32); -/// -/// assert_eq!(Some(42), value.to_i32()); -/// ``` -/// -/// ``` -/// # use std::fmt::Debug; -/// use log::kv::Value; -/// -/// let value = Value::from(&42i32 as &dyn Debug); -/// -/// assert_eq!(None, value.to_i32()); -/// ``` -/// -/// ## Using the `Fill` API -/// -/// The `Fill` trait is a way to bridge APIs that may not be directly -/// compatible with other constructor methods. -/// -/// ``` -/// use log::kv::value::{Value, Slot, Fill, Error}; -/// -/// struct FillSigned; -/// -/// impl Fill for FillSigned { -/// fn fill(&self, slot: &mut Slot) -> Result<(), Error> { -/// slot.fill_any(42i32) -/// } -/// } -/// -/// let value = Value::from_fill(&FillSigned); -/// -/// assert_eq!(Some(42), value.to_i32()); -/// ``` -/// -/// ``` -/// # use std::fmt::Debug; -/// use log::kv::value::{Value, Slot, Fill, Error}; -/// -/// struct FillDebug; -/// -/// impl Fill for FillDebug { -/// fn fill(&self, slot: &mut Slot) -> Result<(), Error> { -/// slot.fill_debug(&42i32 as &dyn Debug) -/// } -/// } -/// -/// let value = Value::from_fill(&FillDebug); -/// -/// assert_eq!(None, value.to_i32()); -/// ``` -pub struct Value<'v> { - inner: Inner<'v>, -} - -impl<'v> Value<'v> { - /// Get a value from a type implementing `ToValue`. - pub fn from_any<T>(value: &'v T) -> Self - where - T: ToValue, - { - value.to_value() - } - - /// Get a value from an internal primitive. - fn from_primitive<T>(value: T) -> Self - where - T: Into<Primitive<'v>>, - { - Value { - inner: Inner::Primitive(value.into()), - } - } - - /// Visit the value using an internal visitor. - fn visit<'a>(&'a self, visitor: &mut dyn Visitor<'a>) -> Result<(), Error> { - self.inner.visit(visitor) - } -}
diff --git a/src/kv/value/test.rs b/src/kv/value/test.rs deleted file mode 100644 index ab5f8075e..000000000 --- a/src/kv/value/test.rs +++ /dev/null @@ -1,81 +0,0 @@ -// Test support for inspecting Values - -use std::fmt; -use std::str; - -use super::internal; -use super::{Error, Value}; - -#[derive(Debug, PartialEq)] -pub(in kv) enum Token { - U64(u64), - I64(i64), - F64(f64), - Char(char), - Bool(bool), - Str(String), - None, - - #[cfg(feature = "kv_unstable_sval")] - Sval, -} - -#[cfg(test)] -impl<'v> Value<'v> { - pub(in kv) fn to_token(&self) -> Token { - struct TestVisitor(Option<Token>); - - impl<'v> internal::Visitor<'v> for TestVisitor { - fn debug(&mut self, v: &dyn fmt::Debug) -> Result<(), Error> { - self.0 = Some(Token::Str(format!("{:?}", v))); - Ok(()) - } - - fn u64(&mut self, v: u64) -> Result<(), Error> { - self.0 = Some(Token::U64(v)); - Ok(()) - } - - fn i64(&mut self, v: i64) -> Result<(), Error> { - self.0 = Some(Token::I64(v)); - Ok(()) - } - - fn f64(&mut self, v: f64) -> Result<(), Error> { - self.0 = Some(Token::F64(v)); - Ok(()) - } - - fn bool(&mut self, v: bool) -> Result<(), Error> { - self.0 = Some(Token::Bool(v)); - Ok(()) - } - - fn char(&mut self, v: char) -> Result<(), Error> { - self.0 = Some(Token::Char(v)); - Ok(()) - } - - fn str(&mut self, v: &str) -> Result<(), Error> { - self.0 = Some(Token::Str(v.into())); - Ok(()) - } - - fn none(&mut self) -> Result<(), Error> { - self.0 = Some(Token::None); - Ok(()) - } - - #[cfg(feature = "kv_unstable_sval")] - fn sval(&mut self, _: &dyn internal::sval::Value) -> Result<(), Error> { - self.0 = Some(Token::Sval); - Ok(()) - } - } - - let mut visitor = TestVisitor(None); - self.visit(&mut visitor).unwrap(); - - visitor.0.unwrap() - } -}
Support converting Errors into Values There are some design decisions to make around `dyn Error` vs `dyn Error + 'static`, but I've been looking at providing a proper downcasting API too.
2020-11-11T03:25:19Z
0.4
06c306fa8f4d41a722f8759f03effd4185eee3ee
rust-lang/log
370
rust-lang__log-370
[ "369" ]
87fc152d40f06623e109ead03cba0431da0e7f73
"diff --git a/src/macros.rs b/src/macros.rs\nindex 23378fc5e..f628664b7 100644\n--- a/src/macros.rs\(...TRUNCATED)
"diff --git a/tests/macros.rs b/tests/macros.rs\nindex f41c52ed3..34c89811f 100644\n--- a/tests/macr(...TRUNCATED)
"0.4.9 release seems to break tokio (which depends on log)\nYou can see an example of this here: htt(...TRUNCATED)
"I am receiving similar errors trying to install cargo-make.\r\n\r\n```\r\n Compiling cargo-make v(...TRUNCATED)
2019-12-16T00:11:28Z
0.4
06c306fa8f4d41a722f8759f03effd4185eee3ee
rust-lang/log
245
rust-lang__log-245
[ "243" ]
1e12cfa3b3ba2a1f1ed80588fd9ebfc3ba46065d
"diff --git a/src/lib.rs b/src/lib.rs\nindex feea3d326..50423604a 100644\n--- a/src/lib.rs\n+++ b/sr(...TRUNCATED)
"diff --git a/tests/filters.rs b/tests/filters.rs\nindex d28fa004e..84449ccfe 100644\n--- a/tests/fi(...TRUNCATED)
"Possibly removing closures from `set_*_logger` functions?\nAre the closures still needed any more? (...TRUNCATED)
"The closure-based indirection is there to make sure the active logger is the only thing that can me(...TRUNCATED)
2017-12-06T04:54:16Z
0.3
1e12cfa3b3ba2a1f1ed80588fd9ebfc3ba46065d
rust-lang/log
224
rust-lang__log-224
[ "145" ]
8af5f3c688461a166a5097c395a5deb6c99a70ed
"diff --git a/.travis.yml b/.travis.yml\nindex 226c591c8..6bc0aa9ed 100644\n--- a/.travis.yml\n+++ b(...TRUNCATED)
"diff --git a/env/tests/regexp_filter.rs b/env/tests/regexp_filter.rs\ndeleted file mode 100644\nind(...TRUNCATED)
"Remove env_logger from this repository\nLet's find a suitable maintainer and move it out of the `lo(...TRUNCATED)
"Hey @alexcrichton, I've started to work on this split at [sebasmagri/env_logger](https://github.com(...TRUNCATED)
2017-09-17T05:41:09Z
0.3
1e12cfa3b3ba2a1f1ed80588fd9ebfc3ba46065d
rust-lang/log
217
rust-lang__log-217
[ "148" ]
25e349c7389ab63a9f5303a9a6183aa9d723b0a0
"diff --git a/.travis.yml b/.travis.yml\nindex 1b82ecd3a..479981582 100644\n--- a/.travis.yml\n+++ b(...TRUNCATED)
"diff --git a/log-test/Cargo.toml b/log-test/Cargo.toml\nnew file mode 100644\nindex 000000000..82ea(...TRUNCATED)
"Ensure 0.3 works with the next major release\nWe'll want to publish a version of 0.3 that works as (...TRUNCATED)
"If it's alright and no one else has started, I can start working on a shared backend crate for this(...TRUNCATED)
2017-08-13T23:43:25Z
0.3
1e12cfa3b3ba2a1f1ed80588fd9ebfc3ba46065d
rust-lang/log
208
rust-lang__log-208
[ "204" ]
8af5f3c688461a166a5097c395a5deb6c99a70ed
"diff --git a/src/lib.rs b/src/lib.rs\nindex 50479f619..e31451324 100644\n--- a/src/lib.rs\n+++ b/sr(...TRUNCATED)
"diff --git a/tests/filters.rs b/tests/filters.rs\nindex 5fc55b2d4..4b4d09050 100644\n--- a/tests/fi(...TRUNCATED)
"Rename set_logger_raw to try_set_logger_raw\nWith respect to the changes made in #187, it makes sen(...TRUNCATED)
"The rationale to change `set_logger` to panic-on-error was that most libraries would transitively c(...TRUNCATED)
2017-07-16T17:18:17Z
0.3
1e12cfa3b3ba2a1f1ed80588fd9ebfc3ba46065d
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
1