//! Structured values. //! //! This module defines the [`Value`] type and supporting APIs for //! capturing and serializing them.
use std::fmt;
pubusecrate::kv::Error;
/// A type that can be converted into a [`Value`](struct.Value.html). pubtrait ToValue { /// Perform the conversion. fn to_value(&self) -> Value<'_>;
}
impl<T> ToValue for &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 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::from_*` methods. /// - Using the `ToValue` trait. /// - Using the standard `From` trait. /// /// ## Using the `Value::from_*` methods /// /// `Value` offers a few constructor methods that capture values of different kinds. /// /// ``` /// use log::kv::Value; /// /// let value = Value::from_debug(&42i32); /// /// assert_eq!(None, value.to_i64()); /// ``` /// /// ## 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_i64()); /// ``` /// /// ## 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_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 /// /// 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 [`VisitValue`] trait methods). /// /// For more complex types one of the following traits can be used: /// * `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. #[derive(Clone)] pubstruct Value<'v> {
inner: inner::Inner<'v>,
}
impl<'v> Value<'v> { /// Get a value from a type implementing `ToValue`. pubfn from_any<T>(value: &'v T) -> Self where
T: ToValue,
{
value.to_value()
}
/// Get a value from a type implementing `std::fmt::Debug`. pubfn from_debug<T>(value: &'v T) -> Self where
T: fmt::Debug,
{
Value {
inner: inner::Inner::from_debug(value),
}
}
/// Get a value from a type implementing `std::fmt::Display`. pubfn from_display<T>(value: &'v T) -> Self where
T: fmt::Display,
{
Value {
inner: inner::Inner::from_display(value),
}
}
/// Get a value from a type implementing `serde::Serialize`. #[cfg(feature = "kv_serde")] pubfn from_serde<T>(value: &'v T) -> Self where
T: serde_core::Serialize,
{
Value {
inner: inner::Inner::from_serde1(value),
}
}
/// Get a value from a type implementing `sval::Value`. #[cfg(feature = "kv_sval")] pubfn from_sval<T>(value: &'v T) -> Self where
T: sval::Value,
{
Value {
inner: inner::Inner::from_sval2(value),
}
}
/// Get a value from a dynamic `std::fmt::Debug`. pubfn from_dyn_debug(value: &'v dyn fmt::Debug) -> Self {
Value {
inner: inner::Inner::from_dyn_debug(value),
}
}
/// Get a value from a dynamic `std::fmt::Display`. pubfn from_dyn_display(value: &'v dyn fmt::Display) -> Self {
Value {
inner: inner::Inner::from_dyn_display(value),
}
}
/// Get a value from a dynamic error. #[cfg(feature = "kv_std")] pubfn from_dyn_error(err: &'v (dyn std::error::Error + 'static)) -> Self {
Value {
inner: inner::Inner::from_dyn_error(err),
}
}
/// Get a `null` value. pubfn null() -> Self {
Value {
inner: inner::Inner::empty(),
}
}
/// Get a value from an internal primitive. fn from_inner<T>(value: T) -> Self where
T: Into<inner::Inner<'v>>,
{
Value {
inner: value.into(),
}
}
/// Inspect this value using a simple visitor. /// /// When the `kv_serde` or `kv_sval` features are enabled, you can also /// serialize a value using its `Serialize` or `Value` implementation. pubfn visit(&self, visitor: impl VisitValue<'v>) -> Result<(), Error> {
inner::visit(&self.inner, visitor)
}
}
impl_value_to_primitive![ #[doc = "Try convert this value into a `u64`."]
to_u64 -> u64, #[doc = "Try convert this value into a `i64`."]
to_i64 -> i64, #[doc = "Try convert this value into a `u128`."]
to_u128 -> u128, #[doc = "Try convert this value into a `i128`."]
to_i128 -> i128, #[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 to convert this value into an error. #[cfg(feature = "kv_std")] pubfn to_borrowed_error(&self) -> Option<&(>dyn std::error::Error + 'static)> { self.inner.to_borrowed_error()
}
/// Try to convert this value into a borrowed string. pubfn to_borrowed_str(&self) -> Option<&'v str> { self.inner.to_borrowed_str()
}
}
#[cfg(feature = "kv_std")] mod std_support { use std::borrow::Cow; use std::rc::Rc; use std::sync::Arc;
/// A visitor for a [`Value`]. /// /// Also see [`Value`'s documentation on serialization]. 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 serialization]: Value#serialization pubtrait VisitValue<'v> { /// Visit a `Value`. /// /// 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(&mutself, value: Value) -> Result<(), Error>;
impl<'v> Value<'v> { /// Get a value from a type implementing `std::fmt::Debug`. #[cfg(feature = "kv_unstable")] #[deprecated(note = "use `from_debug` instead")] pubfn 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")] pubfn 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")] pubfn 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")] pubfn capture_serde<T>(value: &'v T) -> Self where
T: serde_core::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")] pubfn 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"
)] pubfn 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"
)] pubfn downcast_ref<T: 'static>(&self) -> Option<&T> {
None
}
}
// NOTE: Deprecated; but aliases can't carry this attribute #[cfg(feature = "kv_unstable")] pubuse 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)
};
}
#[test] fn test_to_number() { for v in unsigned() {
assert!(v.to_u64().is_some());
assert!(v.to_i64().is_some());
}
for v in signed() {
assert!(v.to_i64().is_some());
}
for v in unsigned().chain(signed()).chain(float()) {
assert!(v.to_f64().is_some());
}
for v in bool().chain(str()).chain(char()) {
assert!(v.to_u64().is_none());
assert!(v.to_i64().is_none());
assert!(v.to_f64().is_none());
}
}
#[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());
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.