implement display for Key and Value

This commit is contained in:
Robin Appelman 2020-12-04 16:48:30 +01:00
commit 309f71a041
2 changed files with 38 additions and 1 deletions

View file

@ -1,7 +1,7 @@
[package] [package]
name = "php-literal-parser" name = "php-literal-parser"
description = "parser for php literals" description = "parser for php literals"
version = "0.1.1" version = "0.1.2"
authors = ["Robin Appelman <robin@icewind.nl>"] authors = ["Robin Appelman <robin@icewind.nl>"]
edition = "2018" edition = "2018"
license = "MIT OR Apache-2.0" license = "MIT OR Apache-2.0"

View file

@ -27,6 +27,7 @@ pub use error::{ParseError, SpannedError};
pub use parser::parse; pub use parser::parse;
use std::borrow::Borrow; use std::borrow::Borrow;
use std::collections::HashMap; use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
use std::ops::Index; use std::ops::Index;
@ -134,6 +135,14 @@ impl Value {
_ => None, _ => None,
} }
} }
/// Get the value as &str if it is a string
pub fn as_str(&self) -> Option<&str> {
match self {
Value::String(str) => Some(str.as_str()),
_ => None,
}
}
} }
impl PartialEq<bool> for Value { impl PartialEq<bool> for Value {
@ -211,6 +220,25 @@ impl From<&str> for Value {
} }
} }
impl Display for Value {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Value::Bool(val) => write!(f, "{}", val),
Value::Int(val) => write!(f, "{}", val),
Value::Float(val) => write!(f, "{}", val),
Value::String(val) => write!(f, "{}", val),
Value::Array(val) => {
write!(f, "[\n")?;
for (key, value) in val.iter() {
write!(f, "\t{} => {},", key, value)?;
}
write!(f, "]")
}
Value::Null => write!(f, "null"),
}
}
}
#[derive(Debug, Eq, PartialEq, Clone)] #[derive(Debug, Eq, PartialEq, Clone)]
pub enum Key { pub enum Key {
Int(i64), Int(i64),
@ -318,6 +346,15 @@ impl Index<i64> for Value {
} }
} }
impl Display for Key {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Key::Int(val) => write!(f, "{}", val),
Key::String(val) => write!(f, "{}", val),
}
}
}
#[test] #[test]
fn test_index() { fn test_index() {
use maplit::hashmap; use maplit::hashmap;