insta/content/mod.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
//! This module implements a generic `Content` type that can hold
//! runtime typed data.
//!
//! It's modelled after serde's data format but it's in fact possible to use
//! this independently of serde. The `yaml` and `json` support implemented
//! here works without serde. Only `yaml` has an implemented parser but since
//! YAML is a superset of JSON insta instead currently parses JSON via the
//! YAML implementation.
pub mod json;
#[cfg(feature = "serde")]
mod serialization;
pub mod yaml;
#[cfg(feature = "serde")]
pub use serialization::*;
use std::fmt;
/// An internal error type for content related errors.
#[derive(Debug)]
pub enum Error {
FailedParsingYaml,
UnexpectedDataType,
#[cfg(feature = "_cargo_insta_internal")]
MissingField,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::FailedParsingYaml => f.write_str("Failed parsing the provided YAML text"),
Self::UnexpectedDataType => {
f.write_str("The present data type wasn't what was expected")
}
#[cfg(feature = "_cargo_insta_internal")]
Self::MissingField => f.write_str("A required field was missing"),
}
}
}
impl std::error::Error for Error {}
/// Represents variable typed content.
///
/// This is used for the serialization system to represent values
/// before the actual snapshots are written and is also exposed to
/// dynamic redaction functions.
///
/// Some enum variants are intentionally not exposed to user code.
/// It's generally recommended to construct content objects by
/// using the [`From`](std::convert::From) trait and by using the
/// accessor methods to assert on it.
///
/// While matching on the content is possible in theory it is
/// recommended against. The reason for this is that the content
/// enum holds variants that can "wrap" values where it's not
/// expected. For instance if a field holds an `Option<String>`
/// you cannot use pattern matching to extract the string as it
/// will be contained in an internal `Some` variant that is not
/// exposed. On the other hand the `as_str` method will
/// automatically resolve such internal wrappers.
///
/// If you do need to pattern match you should use the
/// `resolve_inner` method to resolve such internal wrappers.
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub enum Content {
Bool(bool),
U8(u8),
U16(u16),
U32(u32),
U64(u64),
U128(u128),
I8(i8),
I16(i16),
I32(i32),
I64(i64),
I128(i128),
F32(f32),
F64(f64),
Char(char),
String(String),
Bytes(Vec<u8>),
#[doc(hidden)]
None,
#[doc(hidden)]
Some(Box<Content>),
#[doc(hidden)]
Unit,
#[doc(hidden)]
UnitStruct(&'static str),
#[doc(hidden)]
UnitVariant(&'static str, u32, &'static str),
#[doc(hidden)]
NewtypeStruct(&'static str, Box<Content>),
#[doc(hidden)]
NewtypeVariant(&'static str, u32, &'static str, Box<Content>),
Seq(Vec<Content>),
#[doc(hidden)]
Tuple(Vec<Content>),
#[doc(hidden)]
TupleStruct(&'static str, Vec<Content>),
#[doc(hidden)]
TupleVariant(&'static str, u32, &'static str, Vec<Content>),
Map(Vec<(Content, Content)>),
#[doc(hidden)]
Struct(&'static str, Vec<(&'static str, Content)>),
#[doc(hidden)]
StructVariant(
&'static str,
u32,
&'static str,
Vec<(&'static str, Content)>,
),
}
macro_rules! impl_from {
($ty:ty, $newty:ident) => {
impl From<$ty> for Content {
fn from(value: $ty) -> Content {
Content::$newty(value)
}
}
};
}
impl_from!(bool, Bool);
impl_from!(u8, U8);
impl_from!(u16, U16);
impl_from!(u32, U32);
impl_from!(u64, U64);
impl_from!(u128, U128);
impl_from!(i8, I8);
impl_from!(i16, I16);
impl_from!(i32, I32);
impl_from!(i64, I64);
impl_from!(i128, I128);
impl_from!(f32, F32);
impl_from!(f64, F64);
impl_from!(char, Char);
impl_from!(String, String);
impl_from!(Vec<u8>, Bytes);
impl From<()> for Content {
fn from(_value: ()) -> Content {
Content::Unit
}
}
impl<'a> From<&'a str> for Content {
fn from(value: &'a str) -> Content {
Content::String(value.to_string())
}
}
impl<'a> From<&'a [u8]> for Content {
fn from(value: &'a [u8]) -> Content {
Content::Bytes(value.to_vec())
}
}
impl Content {
/// This resolves the innermost content in a chain of
/// wrapped content.
///
/// For instance if you encounter an `Option<Option<String>>`
/// field the content will be wrapped twice in an internal
/// option wrapper. If you need to pattern match you will
/// need in some situations to first resolve the inner value
/// before such matching can take place as there is no exposed
/// way to match on these wrappers.
///
/// This method does not need to be called for the `as_`
/// methods which resolve automatically.
pub fn resolve_inner(&self) -> &Content {
match *self {
Content::Some(ref v)
| Content::NewtypeStruct(_, ref v)
| Content::NewtypeVariant(_, _, _, ref v) => v.resolve_inner(),
ref other => other,
}
}
/// Mutable version of [`resolve_inner`](Self::resolve_inner).
pub fn resolve_inner_mut(&mut self) -> &mut Content {
match *self {
Content::Some(ref mut v)
| Content::NewtypeStruct(_, ref mut v)
| Content::NewtypeVariant(_, _, _, ref mut v) => v.resolve_inner_mut(),
ref mut other => other,
}
}
/// Returns the value as string
pub fn as_str(&self) -> Option<&str> {
match self.resolve_inner() {
Content::String(ref s) => Some(s.as_str()),
_ => None,
}
}
/// Returns the value as bytes
pub fn as_bytes(&self) -> Option<&[u8]> {
match self.resolve_inner() {
Content::Bytes(ref b) => Some(b),
_ => None,
}
}
/// Returns the value as slice of content values.
pub fn as_slice(&self) -> Option<&[Content]> {
match self.resolve_inner() {
Content::Seq(ref v) | Content::Tuple(ref v) | Content::TupleVariant(_, _, _, ref v) => {
Some(&v[..])
}
_ => None,
}
}
/// Returns true if the value is nil.
pub fn is_nil(&self) -> bool {
matches!(self.resolve_inner(), Content::None | Content::Unit)
}
/// Returns the value as bool
pub fn as_bool(&self) -> Option<bool> {
match *self.resolve_inner() {
Content::Bool(val) => Some(val),
_ => None,
}
}
/// Returns the value as u64
pub fn as_u64(&self) -> Option<u64> {
match *self.resolve_inner() {
Content::U8(v) => Some(u64::from(v)),
Content::U16(v) => Some(u64::from(v)),
Content::U32(v) => Some(u64::from(v)),
Content::U64(v) => Some(v),
Content::U128(v) => {
let rv = v as u64;
if rv as u128 == v {
Some(rv)
} else {
None
}
}
Content::I8(v) if v >= 0 => Some(v as u64),
Content::I16(v) if v >= 0 => Some(v as u64),
Content::I32(v) if v >= 0 => Some(v as u64),
Content::I64(v) if v >= 0 => Some(v as u64),
Content::I128(v) => {
let rv = v as u64;
if rv as i128 == v {
Some(rv)
} else {
None
}
}
_ => None,
}
}
/// Returns the value as u128
pub fn as_u128(&self) -> Option<u128> {
match *self.resolve_inner() {
Content::U128(v) => Some(v),
Content::I128(v) if v >= 0 => Some(v as u128),
_ => self.as_u64().map(u128::from),
}
}
/// Returns the value as i64
pub fn as_i64(&self) -> Option<i64> {
match *self.resolve_inner() {
Content::U8(v) => Some(i64::from(v)),
Content::U16(v) => Some(i64::from(v)),
Content::U32(v) => Some(i64::from(v)),
Content::U64(v) => {
let rv = v as i64;
if rv as u64 == v {
Some(rv)
} else {
None
}
}
Content::U128(v) => {
let rv = v as i64;
if rv as u128 == v {
Some(rv)
} else {
None
}
}
Content::I8(v) => Some(i64::from(v)),
Content::I16(v) => Some(i64::from(v)),
Content::I32(v) => Some(i64::from(v)),
Content::I64(v) => Some(v),
Content::I128(v) => {
let rv = v as i64;
if rv as i128 == v {
Some(rv)
} else {
None
}
}
_ => None,
}
}
/// Returns the value as i128
pub fn as_i128(&self) -> Option<i128> {
match *self.resolve_inner() {
Content::U128(v) => {
let rv = v as i128;
if rv as u128 == v {
Some(rv)
} else {
None
}
}
Content::I128(v) => Some(v),
_ => self.as_i64().map(i128::from),
}
}
/// Returns the value as f64
pub fn as_f64(&self) -> Option<f64> {
match *self.resolve_inner() {
Content::F32(v) => Some(f64::from(v)),
Content::F64(v) => Some(v),
_ => None,
}
}
/// Recursively walks the content structure mutably.
///
/// The callback is invoked for every content in the tree.
pub fn walk<F: FnMut(&mut Content) -> bool>(&mut self, visit: &mut F) {
if !visit(self) {
return;
}
match *self {
Content::Some(ref mut inner) => {
Self::walk(&mut *inner, visit);
}
Content::NewtypeStruct(_, ref mut inner) => {
Self::walk(&mut *inner, visit);
}
Content::NewtypeVariant(_, _, _, ref mut inner) => {
Self::walk(&mut *inner, visit);
}
Content::Seq(ref mut vec) => {
for inner in vec.iter_mut() {
Self::walk(inner, visit);
}
}
Content::Map(ref mut vec) => {
for inner in vec.iter_mut() {
Self::walk(&mut inner.0, visit);
Self::walk(&mut inner.1, visit);
}
}
Content::Struct(_, ref mut vec) => {
for inner in vec.iter_mut() {
Self::walk(&mut inner.1, visit);
}
}
Content::StructVariant(_, _, _, ref mut vec) => {
for inner in vec.iter_mut() {
Self::walk(&mut inner.1, visit);
}
}
Content::Tuple(ref mut vec) => {
for inner in vec.iter_mut() {
Self::walk(inner, visit);
}
}
Content::TupleStruct(_, ref mut vec) => {
for inner in vec.iter_mut() {
Self::walk(inner, visit);
}
}
Content::TupleVariant(_, _, _, ref mut vec) => {
for inner in vec.iter_mut() {
Self::walk(inner, visit);
}
}
_ => {}
}
}
}