summaryrefslogtreecommitdiff
path: root/vendor/log/src/kv
diff options
context:
space:
mode:
authorValentin Popov <valentin@popov.link>2024-01-08 00:21:28 +0300
committerValentin Popov <valentin@popov.link>2024-01-08 00:21:28 +0300
commit1b6a04ca5504955c571d1c97504fb45ea0befee4 (patch)
tree7579f518b23313e8a9748a88ab6173d5e030b227 /vendor/log/src/kv
parent5ecd8cf2cba827454317368b68571df0d13d7842 (diff)
downloadfparkan-1b6a04ca5504955c571d1c97504fb45ea0befee4.tar.xz
fparkan-1b6a04ca5504955c571d1c97504fb45ea0befee4.zip
Initial vendor packages
Signed-off-by: Valentin Popov <valentin@popov.link>
Diffstat (limited to 'vendor/log/src/kv')
-rw-r--r--vendor/log/src/kv/error.rs90
-rw-r--r--vendor/log/src/kv/key.rs157
-rw-r--r--vendor/log/src/kv/mod.rs26
-rw-r--r--vendor/log/src/kv/source.rs776
-rw-r--r--vendor/log/src/kv/value.rs1031
5 files changed, 2080 insertions, 0 deletions
diff --git a/vendor/log/src/kv/error.rs b/vendor/log/src/kv/error.rs
new file mode 100644
index 0000000..c72d323
--- /dev/null
+++ b/vendor/log/src/kv/error.rs
@@ -0,0 +1,90 @@
+use std::fmt;
+
+/// An error encountered while working with structured data.
+#[derive(Debug)]
+pub struct Error {
+ inner: Inner,
+}
+
+#[derive(Debug)]
+enum Inner {
+ #[cfg(feature = "std")]
+ Boxed(std_support::BoxedError),
+ Msg(&'static str),
+ Value(value_bag::Error),
+ Fmt,
+}
+
+impl Error {
+ /// Create an error from a message.
+ pub fn msg(msg: &'static str) -> Self {
+ Error {
+ inner: Inner::Msg(msg),
+ }
+ }
+
+ // Not public so we don't leak the `value_bag` API
+ pub(super) fn from_value(err: value_bag::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 {
+ 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"),
+ }
+ }
+}
+
+impl fmt::Display for Error {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ use self::Inner::*;
+ match &self.inner {
+ #[cfg(feature = "std")]
+ &Boxed(ref err) => err.fmt(f),
+ &Value(ref err) => err.fmt(f),
+ &Msg(ref msg) => msg.fmt(f),
+ &Fmt => fmt::Error.fmt(f),
+ }
+ }
+}
+
+impl From<fmt::Error> for Error {
+ fn from(_: fmt::Error) -> Self {
+ Error { inner: Inner::Fmt }
+ }
+}
+
+#[cfg(feature = "std")]
+mod std_support {
+ use super::*;
+ use std::{error, io};
+
+ pub(super) type BoxedError = Box<dyn error::Error + Send + Sync>;
+
+ impl Error {
+ /// Create an error from a standard error type.
+ pub fn boxed<E>(err: E) -> Self
+ where
+ E: Into<BoxedError>,
+ {
+ Error {
+ inner: Inner::Boxed(err.into()),
+ }
+ }
+ }
+
+ impl error::Error for Error {}
+
+ impl From<io::Error> for Error {
+ fn from(err: io::Error) -> Self {
+ Error::boxed(err)
+ }
+ }
+}
diff --git a/vendor/log/src/kv/key.rs b/vendor/log/src/kv/key.rs
new file mode 100644
index 0000000..4f9a506
--- /dev/null
+++ b/vendor/log/src/kv/key.rs
@@ -0,0 +1,157 @@
+//! Structured keys.
+
+use std::borrow::Borrow;
+use std::fmt;
+
+/// A type that can be converted into a [`Key`](struct.Key.html).
+pub trait ToKey {
+ /// Perform the conversion.
+ fn to_key(&self) -> Key;
+}
+
+impl<'a, T> ToKey for &'a T
+where
+ T: ToKey + ?Sized,
+{
+ fn to_key(&self) -> Key {
+ (**self).to_key()
+ }
+}
+
+impl<'k> ToKey for Key<'k> {
+ fn to_key(&self) -> Key {
+ Key { key: self.key }
+ }
+}
+
+impl ToKey for str {
+ fn to_key(&self) -> Key {
+ Key::from_str(self)
+ }
+}
+
+/// A key in a structured key-value pair.
+// 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)]
+pub struct Key<'k> {
+ key: &'k str,
+}
+
+impl<'k> Key<'k> {
+ /// Get a key from a borrowed string.
+ pub fn from_str(key: &'k str) -> Self {
+ Key { key }
+ }
+
+ /// Get a borrowed string from this key.
+ pub fn as_str(&self) -> &str {
+ self.key
+ }
+
+ /// Try get a string borrowed for the `'k` lifetime from this key.
+ pub fn to_borrowed_str(&self) -> Option<&'k str> {
+ // NOTE: This API leaves room for keys to be owned
+ Some(self.key)
+ }
+}
+
+impl<'k> fmt::Display for Key<'k> {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ self.key.fmt(f)
+ }
+}
+
+impl<'k> AsRef<str> for Key<'k> {
+ fn as_ref(&self) -> &str {
+ self.as_str()
+ }
+}
+
+impl<'k> Borrow<str> for Key<'k> {
+ fn borrow(&self) -> &str {
+ self.as_str()
+ }
+}
+
+impl<'k> From<&'k str> for Key<'k> {
+ fn from(s: &'k str) -> Self {
+ Key::from_str(s)
+ }
+}
+
+#[cfg(feature = "std")]
+mod std_support {
+ use super::*;
+
+ use std::borrow::Cow;
+
+ impl ToKey for String {
+ fn to_key(&self) -> Key {
+ Key::from_str(self)
+ }
+ }
+
+ impl<'a> ToKey for Cow<'a, str> {
+ fn to_key(&self) -> Key {
+ Key::from_str(self)
+ }
+ }
+}
+
+#[cfg(feature = "kv_unstable_sval")]
+mod sval_support {
+ use super::*;
+
+ extern crate sval;
+ extern crate sval_ref;
+
+ use self::sval::Value;
+ use self::sval_ref::ValueRef;
+
+ impl<'a> Value for Key<'a> {
+ fn stream<'sval, S: sval::Stream<'sval> + ?Sized>(
+ &'sval self,
+ stream: &mut S,
+ ) -> sval::Result {
+ self.key.stream(stream)
+ }
+ }
+
+ impl<'a> ValueRef<'a> for Key<'a> {
+ fn stream_ref<S: self::sval::Stream<'a> + ?Sized>(
+ &self,
+ stream: &mut S,
+ ) -> self::sval::Result {
+ self.key.stream(stream)
+ }
+ }
+}
+
+#[cfg(feature = "kv_unstable_serde")]
+mod serde_support {
+ use super::*;
+
+ extern crate serde;
+
+ use self::serde::{Serialize, Serializer};
+
+ impl<'a> Serialize for Key<'a> {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ self.key.serialize(serializer)
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn key_from_string() {
+ assert_eq!("a key", Key::from_str("a key").as_str());
+ }
+}
diff --git a/vendor/log/src/kv/mod.rs b/vendor/log/src/kv/mod.rs
new file mode 100644
index 0000000..5dc6933
--- /dev/null
+++ b/vendor/log/src/kv/mod.rs
@@ -0,0 +1,26 @@
+//! **UNSTABLE:** Structured key-value pairs.
+//!
+//! 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
+//! this module:
+//!
+//! ```toml
+//! [dependencies.log]
+//! features = ["kv_unstable"]
+//! ```
+
+mod error;
+mod key;
+pub mod source;
+
+pub mod value;
+
+pub use self::error::Error;
+pub use self::key::{Key, ToKey};
+pub use self::source::{Source, Visitor};
+
+#[doc(inline)]
+pub use self::value::{ToValue, Value};
diff --git a/vendor/log/src/kv/source.rs b/vendor/log/src/kv/source.rs
new file mode 100644
index 0000000..45fc6dc
--- /dev/null
+++ b/vendor/log/src/kv/source.rs
@@ -0,0 +1,776 @@
+//! Sources for key-value pairs.
+
+#[cfg(feature = "kv_unstable_sval")]
+extern crate sval;
+#[cfg(feature = "kv_unstable_sval")]
+extern crate sval_ref;
+
+#[cfg(feature = "kv_unstable_serde")]
+extern crate serde;
+
+use kv::{Error, Key, ToKey, ToValue, Value};
+use std::fmt;
+
+/// A source of key-value pairs.
+///
+/// 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
+/// in a source.
+pub trait Source {
+ /// Visit key-value pairs.
+ ///
+ /// A source doesn't have to guarantee any ordering or uniqueness of key-value pairs.
+ /// If the given visitor returns an error then the source may early-return with it,
+ /// even if there are more key-value pairs.
+ ///
+ /// # Implementation notes
+ ///
+ /// A source should yield the same key-value pairs to a subsequent visitor unless
+ /// that visitor itself fails.
+ fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error>;
+
+ /// Get the value for a given key.
+ ///
+ /// If the key appears multiple times in the source then which key is returned
+ /// is implementation specific.
+ ///
+ /// # Implementation notes
+ ///
+ /// A source that can provide a more efficient implementation of this method
+ /// should override it.
+ #[cfg(not(test))]
+ fn get<'v>(&'v self, key: Key) -> Option<Value<'v>> {
+ get_default(self, key)
+ }
+
+ #[cfg(test)]
+ fn get<'v>(&'v self, key: Key) -> Option<Value<'v>>;
+
+ /// Count the number of key-value pairs that can be visited.
+ ///
+ /// # Implementation notes
+ ///
+ /// A source that knows the number of key-value pairs 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.
+ #[cfg(not(test))]
+ fn count(&self) -> usize {
+ count_default(self)
+ }
+
+ #[cfg(test)]
+ fn count(&self) -> usize;
+}
+
+/// The default implemention of `Source::get`
+pub(crate) fn get_default<'v>(source: &'v (impl Source + ?Sized), key: Key) -> Option<Value<'v>> {
+ struct Get<'k, 'v> {
+ key: Key<'k>,
+ found: Option<Value<'v>>,
+ }
+
+ impl<'k, 'kvs> Visitor<'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);
+ }
+
+ Ok(())
+ }
+ }
+
+ let mut get = Get { key, found: None };
+
+ let _ = source.visit(&mut get);
+ get.found
+}
+
+/// The default implementation of `Source::count`.
+pub(crate) fn count_default(source: impl Source) -> usize {
+ struct Count(usize);
+
+ impl<'kvs> Visitor<'kvs> for Count {
+ fn visit_pair(&mut self, _: Key<'kvs>, _: Value<'kvs>) -> Result<(), Error> {
+ self.0 += 1;
+
+ Ok(())
+ }
+ }
+
+ let mut count = Count(0);
+ let _ = source.visit(&mut count);
+ count.0
+}
+
+impl<'a, T> Source for &'a T
+where
+ T: Source + ?Sized,
+{
+ fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> {
+ Source::visit(&**self, visitor)
+ }
+
+ fn get<'v>(&'v self, key: Key) -> Option<Value<'v>> {
+ Source::get(&**self, key)
+ }
+
+ fn count(&self) -> usize {
+ Source::count(&**self)
+ }
+}
+
+impl<K, V> Source for (K, V)
+where
+ K: ToKey,
+ V: ToValue,
+{
+ fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> {
+ visitor.visit_pair(self.0.to_key(), self.1.to_value())
+ }
+
+ fn get<'v>(&'v self, key: Key) -> Option<Value<'v>> {
+ if self.0.to_key() == key {
+ Some(self.1.to_value())
+ } else {
+ None
+ }
+ }
+
+ fn count(&self) -> usize {
+ 1
+ }
+}
+
+impl<S> Source for [S]
+where
+ S: Source,
+{
+ fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> {
+ for source in self {
+ source.visit(visitor)?;
+ }
+
+ Ok(())
+ }
+
+ fn get<'v>(&'v self, key: Key) -> Option<Value<'v>> {
+ for source in self {
+ if let Some(found) = source.get(key.clone()) {
+ return Some(found);
+ }
+ }
+
+ None
+ }
+
+ fn count(&self) -> usize {
+ self.len()
+ }
+}
+
+impl<S> Source for Option<S>
+where
+ S: Source,
+{
+ fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> {
+ if let Some(ref source) = *self {
+ source.visit(visitor)?;
+ }
+
+ Ok(())
+ }
+
+ fn get<'v>(&'v self, key: Key) -> Option<Value<'v>> {
+ self.as_ref().and_then(|s| s.get(key))
+ }
+
+ fn count(&self) -> usize {
+ self.as_ref().map(Source::count).unwrap_or(0)
+ }
+}
+
+/// A visitor for the key-value pairs in a [`Source`](trait.Source.html).
+pub trait Visitor<'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
+where
+ T: Visitor<'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> {
+ 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> {
+ 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> {
+ 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> {
+ fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> {
+ self.field(&key);
+ self.field(&value);
+ Ok(())
+ }
+}
+
+#[cfg(feature = "std")]
+mod std_support {
+ use super::*;
+ use std::borrow::Borrow;
+ use std::collections::{BTreeMap, HashMap};
+ use std::hash::{BuildHasher, Hash};
+
+ impl<S> Source for Box<S>
+ where
+ S: Source + ?Sized,
+ {
+ fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> {
+ Source::visit(&**self, visitor)
+ }
+
+ fn get<'v>(&'v self, key: Key) -> Option<Value<'v>> {
+ Source::get(&**self, key)
+ }
+
+ fn count(&self) -> usize {
+ Source::count(&**self)
+ }
+ }
+
+ impl<S> Source for Vec<S>
+ where
+ S: Source,
+ {
+ fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> {
+ Source::visit(&**self, visitor)
+ }
+
+ fn get<'v>(&'v self, key: Key) -> Option<Value<'v>> {
+ Source::get(&**self, key)
+ }
+
+ fn count(&self) -> usize {
+ Source::count(&**self)
+ }
+ }
+
+ impl<'kvs, V> Visitor<'kvs> for Box<V>
+ where
+ V: Visitor<'kvs> + ?Sized,
+ {
+ fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> {
+ (**self).visit_pair(key, value)
+ }
+ }
+
+ impl<K, V, S> Source for HashMap<K, V, S>
+ where
+ K: ToKey + Borrow<str> + Eq + Hash,
+ V: ToValue,
+ S: BuildHasher,
+ {
+ fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> {
+ for (key, value) in self {
+ visitor.visit_pair(key.to_key(), value.to_value())?;
+ }
+ Ok(())
+ }
+
+ fn get<'v>(&'v self, key: Key) -> Option<Value<'v>> {
+ HashMap::get(self, key.as_str()).map(|v| v.to_value())
+ }
+
+ fn count(&self) -> usize {
+ self.len()
+ }
+ }
+
+ impl<K, V> Source for BTreeMap<K, V>
+ where
+ K: ToKey + Borrow<str> + Ord,
+ V: ToValue,
+ {
+ fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> {
+ for (key, value) in self {
+ visitor.visit_pair(key.to_key(), value.to_value())?;
+ }
+ Ok(())
+ }
+
+ fn get<'v>(&'v self, key: Key) -> Option<Value<'v>> {
+ BTreeMap::get(self, key.as_str()).map(|v| v.to_value())
+ }
+
+ fn count(&self) -> usize {
+ self.len()
+ }
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use super::*;
+ use kv::value::tests::Token;
+ use std::collections::{BTreeMap, HashMap};
+
+ #[test]
+ fn count() {
+ assert_eq!(1, Source::count(&Box::new(("a", 1))));
+ assert_eq!(2, Source::count(&vec![("a", 1), ("b", 2)]));
+ }
+
+ #[test]
+ fn get() {
+ let source = vec![("a", 1), ("b", 2), ("a", 1)];
+ assert_eq!(
+ Token::I64(1),
+ Source::get(&source, Key::from_str("a")).unwrap().to_token()
+ );
+
+ let source = Box::new(Option::None::<(&str, i32)>);
+ assert!(Source::get(&source, Key::from_str("a")).is_none());
+ }
+
+ #[test]
+ fn hash_map() {
+ let mut map = HashMap::new();
+ map.insert("a", 1);
+ map.insert("b", 2);
+
+ assert_eq!(2, Source::count(&map));
+ assert_eq!(
+ Token::I64(1),
+ Source::get(&map, Key::from_str("a")).unwrap().to_token()
+ );
+ }
+
+ #[test]
+ fn btree_map() {
+ let mut map = BTreeMap::new();
+ map.insert("a", 1);
+ map.insert("b", 2);
+
+ assert_eq!(2, Source::count(&map));
+ assert_eq!(
+ Token::I64(1),
+ Source::get(&map, Key::from_str("a")).unwrap().to_token()
+ );
+ }
+ }
+}
+
+/// The result of calling `Source::as_map`.
+pub struct AsMap<S>(S);
+
+/// Visit this source as a map.
+pub fn as_map<S>(source: S) -> AsMap<S>
+where
+ S: Source,
+{
+ AsMap(source)
+}
+
+impl<S> Source for AsMap<S>
+where
+ S: Source,
+{
+ fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> {
+ self.0.visit(visitor)
+ }
+
+ fn get<'v>(&'v self, key: Key) -> Option<Value<'v>> {
+ self.0.get(key)
+ }
+
+ fn count(&self) -> usize {
+ self.0.count()
+ }
+}
+
+impl<S> fmt::Debug for AsMap<S>
+where
+ S: Source,
+{
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ let mut f = f.debug_map();
+ self.0.visit(&mut f).map_err(|_| fmt::Error)?;
+ f.finish()
+ }
+}
+
+/// The result of calling `Source::as_list`
+pub struct AsList<S>(S);
+
+/// Visit this source as a list.
+pub fn as_list<S>(source: S) -> AsList<S>
+where
+ S: Source,
+{
+ AsList(source)
+}
+
+impl<S> Source for AsList<S>
+where
+ S: Source,
+{
+ fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> {
+ self.0.visit(visitor)
+ }
+
+ fn get<'v>(&'v self, key: Key) -> Option<Value<'v>> {
+ self.0.get(key)
+ }
+
+ fn count(&self) -> usize {
+ self.0.count()
+ }
+}
+
+impl<S> fmt::Debug for AsList<S>
+where
+ S: Source,
+{
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ let mut f = f.debug_list();
+ self.0.visit(&mut f).map_err(|_| fmt::Error)?;
+ f.finish()
+ }
+}
+
+#[cfg(feature = "kv_unstable_sval")]
+mod sval_support {
+ use super::*;
+
+ impl<S> self::sval::Value for AsMap<S>
+ where
+ S: Source,
+ {
+ fn stream<'sval, SV: self::sval::Stream<'sval> + ?Sized>(
+ &'sval self,
+ stream: &mut SV,
+ ) -> self::sval::Result {
+ struct StreamVisitor<'a, V: ?Sized>(&'a mut V);
+
+ impl<'a, 'kvs, V: self::sval::Stream<'kvs> + ?Sized> Visitor<'kvs> for StreamVisitor<'a, V> {
+ fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> {
+ self.0
+ .map_key_begin()
+ .map_err(|_| Error::msg("failed to stream map key"))?;
+ sval_ref::stream_ref(self.0, key)
+ .map_err(|_| Error::msg("failed to stream map key"))?;
+ self.0
+ .map_key_end()
+ .map_err(|_| Error::msg("failed to stream map key"))?;
+
+ self.0
+ .map_value_begin()
+ .map_err(|_| Error::msg("failed to stream map value"))?;
+ sval_ref::stream_ref(self.0, value)
+ .map_err(|_| Error::msg("failed to stream map value"))?;
+ self.0
+ .map_value_end()
+ .map_err(|_| Error::msg("failed to stream map value"))?;
+
+ Ok(())
+ }
+ }
+
+ stream
+ .map_begin(Some(self.count()))
+ .map_err(|_| self::sval::Error::new())?;
+
+ self.visit(&mut StreamVisitor(stream))
+ .map_err(|_| self::sval::Error::new())?;
+
+ stream.map_end().map_err(|_| self::sval::Error::new())
+ }
+ }
+
+ impl<S> self::sval::Value for AsList<S>
+ where
+ S: Source,
+ {
+ fn stream<'sval, SV: self::sval::Stream<'sval> + ?Sized>(
+ &'sval self,
+ stream: &mut SV,
+ ) -> self::sval::Result {
+ struct StreamVisitor<'a, V: ?Sized>(&'a mut V);
+
+ impl<'a, 'kvs, V: self::sval::Stream<'kvs> + ?Sized> Visitor<'kvs> for StreamVisitor<'a, V> {
+ fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> {
+ self.0
+ .seq_value_begin()
+ .map_err(|_| Error::msg("failed to stream seq value"))?;
+ self::sval_ref::stream_ref(self.0, (key, value))
+ .map_err(|_| Error::msg("failed to stream seq value"))?;
+ self.0
+ .seq_value_end()
+ .map_err(|_| Error::msg("failed to stream seq value"))?;
+
+ Ok(())
+ }
+ }
+
+ stream
+ .seq_begin(Some(self.count()))
+ .map_err(|_| self::sval::Error::new())?;
+
+ self.visit(&mut StreamVisitor(stream))
+ .map_err(|_| self::sval::Error::new())?;
+
+ stream.seq_end().map_err(|_| self::sval::Error::new())
+ }
+ }
+
+ #[cfg(test)]
+ mod tests {
+ extern crate sval_derive;
+
+ use super::*;
+
+ use self::sval_derive::Value;
+
+ use crate::kv::source;
+
+ #[test]
+ fn derive_stream() {
+ #[derive(Value)]
+ pub struct MyRecordAsMap<'a> {
+ msg: &'a str,
+ kvs: source::AsMap<&'a dyn Source>,
+ }
+
+ #[derive(Value)]
+ pub struct MyRecordAsList<'a> {
+ msg: &'a str,
+ kvs: source::AsList<&'a dyn Source>,
+ }
+ }
+ }
+}
+
+#[cfg(feature = "kv_unstable_serde")]
+pub mod as_map {
+ //! `serde` adapters for serializing a `Source` as a map.
+
+ use super::*;
+
+ use self::serde::{Serialize, Serializer};
+
+ /// Serialize a `Source` as a map.
+ pub fn serialize<T, S>(source: &T, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ T: Source,
+ S: Serializer,
+ {
+ as_map(source).serialize(serializer)
+ }
+}
+
+#[cfg(feature = "kv_unstable_serde")]
+pub mod as_list {
+ //! `serde` adapters for serializing a `Source` as a list.
+
+ use super::*;
+
+ use self::serde::{Serialize, Serializer};
+
+ /// Serialize a `Source` as a list.
+ pub fn serialize<T, S>(source: &T, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ T: Source,
+ S: Serializer,
+ {
+ as_list(source).serialize(serializer)
+ }
+}
+
+#[cfg(feature = "kv_unstable_serde")]
+mod serde_support {
+ use super::*;
+
+ use self::serde::ser::{Error as SerError, Serialize, SerializeMap, SerializeSeq, Serializer};
+
+ impl<T> Serialize for AsMap<T>
+ where
+ T: Source,
+ {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ struct SerializerVisitor<'a, S>(&'a mut S);
+
+ impl<'a, 'kvs, S> Visitor<'kvs> for SerializerVisitor<'a, S>
+ where
+ S: SerializeMap,
+ {
+ fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> {
+ self.0
+ .serialize_entry(&key, &value)
+ .map_err(|_| Error::msg("failed to serialize map entry"))?;
+ Ok(())
+ }
+ }
+
+ let mut map = serializer.serialize_map(Some(self.count()))?;
+
+ self.visit(&mut SerializerVisitor(&mut map))
+ .map_err(|_| S::Error::custom("failed to visit key-values"))?;
+
+ map.end()
+ }
+ }
+
+ impl<T> Serialize for AsList<T>
+ where
+ T: Source,
+ {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ struct SerializerVisitor<'a, S>(&'a mut S);
+
+ impl<'a, 'kvs, S> Visitor<'kvs> for SerializerVisitor<'a, S>
+ where
+ S: SerializeSeq,
+ {
+ fn visit_pair(&mut self, key: Key<'kvs>, value: Value<'kvs>) -> Result<(), Error> {
+ self.0
+ .serialize_element(&(key, value))
+ .map_err(|_| Error::msg("failed to serialize seq entry"))?;
+ Ok(())
+ }
+ }
+
+ let mut seq = serializer.serialize_seq(Some(self.count()))?;
+
+ self.visit(&mut SerializerVisitor(&mut seq))
+ .map_err(|_| S::Error::custom("failed to visit seq"))?;
+
+ seq.end()
+ }
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use super::*;
+
+ use self::serde::Serialize;
+
+ use crate::kv::source;
+
+ #[test]
+ fn derive_serialize() {
+ #[derive(Serialize)]
+ pub struct MyRecordAsMap<'a> {
+ msg: &'a str,
+ #[serde(flatten)]
+ #[serde(with = "source::as_map")]
+ kvs: &'a dyn Source,
+ }
+
+ #[derive(Serialize)]
+ pub struct MyRecordAsList<'a> {
+ msg: &'a str,
+ #[serde(flatten)]
+ #[serde(with = "source::as_list")]
+ kvs: &'a dyn Source,
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use kv::value::tests::Token;
+
+ #[test]
+ fn source_is_object_safe() {
+ fn _check(_: &dyn Source) {}
+ }
+
+ #[test]
+ fn visitor_is_object_safe() {
+ fn _check(_: &dyn Visitor) {}
+ }
+
+ #[test]
+ fn count() {
+ struct OnePair {
+ key: &'static str,
+ value: i32,
+ }
+
+ impl Source for OnePair {
+ fn visit<'kvs>(&'kvs self, visitor: &mut dyn Visitor<'kvs>) -> Result<(), Error> {
+ visitor.visit_pair(self.key.to_key(), self.value.to_value())
+ }
+
+ fn get<'v>(&'v self, key: Key) -> Option<Value<'v>> {
+ get_default(self, key)
+ }
+
+ fn count(&self) -> usize {
+ count_default(self)
+ }
+ }
+
+ assert_eq!(1, Source::count(&("a", 1)));
+ assert_eq!(2, Source::count(&[("a", 1), ("b", 2)] as &[_]));
+ assert_eq!(0, Source::count(&Option::None::<(&str, i32)>));
+ assert_eq!(1, Source::count(&OnePair { key: "a", value: 1 }));
+ }
+
+ #[test]
+ fn get() {
+ let source = &[("a", 1), ("b", 2), ("a", 1)] as &[_];
+ assert_eq!(
+ Token::I64(1),
+ Source::get(source, Key::from_str("a")).unwrap().to_token()
+ );
+ assert_eq!(
+ Token::I64(2),
+ Source::get(source, Key::from_str("b")).unwrap().to_token()
+ );
+ assert!(Source::get(&source, Key::from_str("c")).is_none());
+
+ let source = Option::None::<(&str, i32)>;
+ assert!(Source::get(&source, Key::from_str("a")).is_none());
+ }
+
+ #[test]
+ fn as_map() {
+ let _ = crate::kv::source::as_map(("a", 1));
+ let _ = crate::kv::source::as_map(&("a", 1) as &dyn Source);
+ }
+
+ #[test]
+ fn as_list() {
+ let _ = crate::kv::source::as_list(("a", 1));
+ let _ = crate::kv::source::as_list(&("a", 1) as &dyn Source);
+ }
+}
diff --git a/vendor/log/src/kv/value.rs b/vendor/log/src/kv/value.rs
new file mode 100644
index 0000000..9485d48
--- /dev/null
+++ b/vendor/log/src/kv/value.rs
@@ -0,0 +1,1031 @@
+//! Structured values.
+
+use std::fmt;
+
+extern crate value_bag;
+
+#[cfg(feature = "kv_unstable_sval")]
+extern crate sval;
+#[cfg(feature = "kv_unstable_sval")]
+extern crate sval_ref;
+
+#[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(),
+ }
+ }
+}
+
+/// 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.
+///
+/// # 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;
+///
+/// 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());
+/// ```
+///
+/// ```
+/// # use std::fmt::Debug;
+/// use log::kv::ToValue;
+///
+/// let value = (&42i32 as &dyn Debug).to_value();
+///
+/// assert_eq!(None, 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());
+/// ```
+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`.
+ #[cfg(feature = "kv_unstable_sval")]
+ pub fn capture_sval<T>(value: &'v T) -> Self
+ where
+ T: self::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),
+ }
+ }
+
+ /// 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`.
+ #[cfg(feature = "kv_unstable_sval")]
+ pub fn from_sval<T>(value: &'v T) -> Self
+ where
+ T: self::sval::Value,
+ {
+ Value {
+ inner: ValueBag::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),
+ }
+ }
+
+ /// 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 an internal primitive.
+ fn from_value_bag<T>(value: T) -> Self
+ where
+ T: Into<ValueBag<'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)
+ }
+}
+
+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 for Value<'v> {
+ fn stream<'sval, S: self::sval::Stream<'sval> + ?Sized>(
+ &'sval self,
+ stream: &mut S,
+ ) -> self::sval::Result {
+ self::sval::Value::stream(&self.inner, stream)
+ }
+}
+
+#[cfg(feature = "kv_unstable_sval")]
+impl<'v> self::sval_ref::ValueRef<'v> for Value<'v> {
+ fn stream_ref<S: self::sval::Stream<'v> + ?Sized>(&self, stream: &mut S) -> self::sval::Result {
+ self::sval_ref::ValueRef::stream_ref(&self.inner, stream)
+ }
+}
+
+impl ToValue for str {
+ fn to_value(&self) -> Value {
+ Value::from(self)
+ }
+}
+
+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 { std::mem::transmute::<&std::num::NonZeroU128, &u128>(v) })
+ }
+}
+
+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 { std::mem::transmute::<&std::num::NonZeroI128, &i128>(v) })
+ }
+}
+
+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_to_value_nonzero_primitive {
+ ($($into_ty:ident,)*) => {
+ $(
+ impl ToValue for std::num::$into_ty {
+ fn to_value(&self) -> Value {
+ Value::from(self.get())
+ }
+ }
+
+ impl<'v> From<std::num::$into_ty> for Value<'v> {
+ fn from(value: std::num::$into_ty) -> Self {
+ Value::from(value.get())
+ }
+ }
+ )*
+ };
+}
+
+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,];
+
+#[rustfmt::skip]
+impl_to_value_nonzero_primitive![
+ NonZeroUsize, NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64,
+ NonZeroIsize, NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64,
+];
+
+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 convert this value into an error.
+ #[cfg(feature = "kv_unstable_std")]
+ pub fn to_borrowed_error(&self) -> Option<&(dyn std::error::Error + 'static)> {
+ self.inner.to_borrowed_error()
+ }
+
+ /// Try convert this value into a borrowed string.
+ pub fn to_borrowed_str(&self) -> Option<&str> {
+ self.inner.to_borrowed_str()
+ }
+}
+
+#[cfg(feature = "kv_unstable_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()
+ }
+ }
+
+ impl<'v> From<&'v String> for Value<'v> {
+ fn from(v: &'v String) -> Self {
+ Value::from(&**v)
+ }
+ }
+}
+
+/// A visitor for a `Value`.
+pub trait Visit<'v> {
+ /// Visit a `Value`.
+ ///
+ /// This is the only required method on `Visit` 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 unsigned integer.
+ fn visit_u64(&mut self, value: u64) -> Result<(), Error> {
+ self.visit_any(value.into())
+ }
+
+ /// Visit a signed integer.
+ fn visit_i64(&mut self, value: i64) -> Result<(), Error> {
+ self.visit_any(value.into())
+ }
+
+ /// Visit a big unsigned integer.
+ fn visit_u128(&mut self, value: u128) -> Result<(), Error> {
+ self.visit_any((&value).into())
+ }
+
+ /// Visit a big signed integer.
+ fn visit_i128(&mut self, value: i128) -> Result<(), Error> {
+ self.visit_any((&value).into())
+ }
+
+ /// Visit a floating point.
+ fn visit_f64(&mut self, value: f64) -> Result<(), Error> {
+ self.visit_any(value.into())
+ }
+
+ /// Visit a boolean.
+ fn visit_bool(&mut self, value: bool) -> Result<(), Error> {
+ self.visit_any(value.into())
+ }
+
+ /// Visit a string.
+ fn visit_str(&mut self, value: &str) -> Result<(), Error> {
+ self.visit_any(value.into())
+ }
+
+ /// Visit a string.
+ fn visit_borrowed_str(&mut self, value: &'v str) -> Result<(), Error> {
+ self.visit_str(value)
+ }
+
+ /// Visit a Unicode character.
+ fn visit_char(&mut self, value: char) -> Result<(), Error> {
+ let mut b = [0; 4];
+ self.visit_str(&*value.encode_utf8(&mut b))
+ }
+
+ /// Visit an error.
+ #[cfg(feature = "kv_unstable_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")]
+ fn visit_borrowed_error(
+ &mut self,
+ err: &'v (dyn std::error::Error + 'static),
+ ) -> Result<(), Error> {
+ self.visit_any(Value::from_dyn_error(err))
+ }
+}
+
+impl<'a, 'v, T: ?Sized> Visit<'v> for &'a mut T
+where
+ T: Visit<'v>,
+{
+ fn visit_any(&mut self, value: Value) -> Result<(), Error> {
+ (**self).visit_any(value)
+ }
+
+ fn visit_u64(&mut self, value: u64) -> Result<(), Error> {
+ (**self).visit_u64(value)
+ }
+
+ fn visit_i64(&mut self, value: i64) -> Result<(), Error> {
+ (**self).visit_i64(value)
+ }
+
+ fn visit_u128(&mut self, value: u128) -> Result<(), Error> {
+ (**self).visit_u128(value)
+ }
+
+ fn visit_i128(&mut self, value: i128) -> Result<(), Error> {
+ (**self).visit_i128(value)
+ }
+
+ fn visit_f64(&mut self, value: f64) -> Result<(), Error> {
+ (**self).visit_f64(value)
+ }
+
+ fn visit_bool(&mut self, value: bool) -> Result<(), Error> {
+ (**self).visit_bool(value)
+ }
+
+ fn visit_str(&mut self, value: &str) -> Result<(), Error> {
+ (**self).visit_str(value)
+ }
+
+ fn visit_borrowed_str(&mut self, value: &'v str) -> Result<(), Error> {
+ (**self).visit_borrowed_str(value)
+ }
+
+ fn visit_char(&mut self, value: char) -> Result<(), Error> {
+ (**self).visit_char(value)
+ }
+
+ #[cfg(feature = "kv_unstable_std")]
+ fn visit_error(&mut self, err: &(dyn std::error::Error + 'static)) -> Result<(), Error> {
+ (**self).visit_error(err)
+ }
+
+ #[cfg(feature = "kv_unstable_std")]
+ fn visit_borrowed_error(
+ &mut self,
+ err: &'v (dyn std::error::Error + 'static),
+ ) -> Result<(), Error> {
+ (**self).visit_borrowed_error(err)
+ }
+}
+
+#[cfg(test)]
+pub(crate) mod tests {
+ use super::*;
+
+ pub(crate) use super::value_bag::test::TestToken as Token;
+
+ impl<'v> Value<'v> {
+ pub(crate) fn to_token(&self) -> Token {
+ self.inner.to_test_token()
+ }
+ }
+
+ fn unsigned() -> impl Iterator<Item = Value<'static>> {
+ vec![
+ Value::from(8u8),
+ Value::from(16u16),
+ Value::from(32u32),
+ Value::from(64u64),
+ Value::from(1usize),
+ Value::from(std::num::NonZeroU8::new(8).unwrap()),
+ Value::from(std::num::NonZeroU16::new(16).unwrap()),
+ Value::from(std::num::NonZeroU32::new(32).unwrap()),
+ Value::from(std::num::NonZeroU64::new(64).unwrap()),
+ Value::from(std::num::NonZeroUsize::new(1).unwrap()),
+ ]
+ .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),
+ Value::from(std::num::NonZeroI8::new(-8).unwrap()),
+ Value::from(std::num::NonZeroI16::new(-16).unwrap()),
+ Value::from(std::num::NonZeroI32::new(-32).unwrap()),
+ Value::from(std::num::NonZeroI64::new(-64).unwrap()),
+ Value::from(std::num::NonZeroIsize::new(-1).unwrap()),
+ ]
+ .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_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");
+ 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() {
+ 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_str() {
+ for v in str() {
+ assert!(v.to_borrowed_str().is_some());
+
+ #[cfg(feature = "kv_unstable_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 = "kv_unstable_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 = "kv_unstable_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());
+ }
+ }
+
+ #[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 {
+ fn visit_any(&mut self, value: Value) -> Result<(), Error> {
+ unimplemented!("unexpected value: {:?}", value)
+ }
+
+ fn visit_u64(&mut self, value: u64) -> Result<(), Error> {
+ self.0 = Some(value);
+
+ Ok(())
+ }
+ }
+
+ let mut extract = Extract(None);
+ Value::from(42u64).visit(&mut extract).unwrap();
+
+ assert_eq!(Some(42), extract.0);
+ }
+
+ #[test]
+ fn test_visit_borrowed_str() {
+ struct Extract<'v>(Option<&'v str>);
+
+ impl<'v> Visit<'v> for Extract<'v> {
+ fn visit_any(&mut self, value: Value) -> Result<(), Error> {
+ unimplemented!("unexpected value: {:?}", value)
+ }
+
+ fn visit_borrowed_str(&mut self, value: &'v str) -> Result<(), Error> {
+ self.0 = Some(value);
+
+ Ok(())
+ }
+ }
+
+ let mut extract = Extract(None);
+
+ let short_lived = String::from("A short-lived string");
+ Value::from(&*short_lived).visit(&mut extract).unwrap();
+
+ assert_eq!(Some("A short-lived string"), extract.0);
+ }
+}