Skip to content

Commit

Permalink
Simplify code
Browse files Browse the repository at this point in the history
  • Loading branch information
GuillaumeGomez committed Jan 10, 2025
1 parent 4206409 commit 4dc727a
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 43 deletions.
6 changes: 3 additions & 3 deletions rinja/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ pub trait Template: fmt::Display + filters::FastWritable {
/// Helper method which allocates a new `String` and renders into it.
#[cfg(feature = "alloc")]
fn render(&self) -> Result<String> {
self.render_with_values(&Values::new())
self.render_with_values(&Values::default())
}

/// Helper method which allocates a new `String` and renders into it with provided [`Values`].
Expand All @@ -125,7 +125,7 @@ pub trait Template: fmt::Display + filters::FastWritable {

/// Renders the template to the given `writer` fmt buffer.
fn render_into<W: fmt::Write + ?Sized>(&self, writer: &mut W) -> Result<()> {
self.render_into_with_values(writer, &Values::new())
self.render_into_with_values(writer, &Values::default())
}

/// Renders the template to the given `writer` fmt buffer with provided [`Values`].
Expand All @@ -138,7 +138,7 @@ pub trait Template: fmt::Display + filters::FastWritable {
/// Renders the template to the given `writer` io buffer.
#[cfg(feature = "std")]
fn write_into<W: io::Write + ?Sized>(&self, writer: &mut W) -> io::Result<()> {
self.write_into_with_values(writer, &Values::new())
self.write_into_with_values(writer, &Values::default())
}

/// Renders the template to the given `writer` io buffer with provided [`Values`].
Expand Down
60 changes: 22 additions & 38 deletions rinja/src/values.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![allow(clippy::new_without_default)]

#[cfg(feature = "alloc")]
use alloc::boxed::Box;
#[cfg(all(not(feature = "std"), feature = "alloc"))]
Expand All @@ -8,30 +10,13 @@ use core::any::Any;
#[cfg(feature = "std")]
use std::collections::HashMap;

// This whole code is to allow the crate to compile if both `alloc` and `std` features
// are disabled. The type will do nothing.
#[cfg(not(any(feature = "std", feature = "alloc")))]
struct HashMap;
#[cfg(not(any(feature = "std", feature = "alloc")))]
impl HashMap {
fn new() -> Self {
Self
}
fn insert(&mut self, _key: String, _value: impl Any) {}
fn get(&self, _key: &str) -> Option<V> {
None
}
}

/// Used to store values of any type at runtime.
///
/// If the `std` feature is enabled, it internally uses the [`HashMap`] type, if the `alloc`
/// feature is enabled, it uses the [`BTreeMap`](alloc::collections::BTreeMap) type, otherwise
/// it uses an empty type and does nothing.
#[cfg(feature = "alloc")]
pub struct Values(HashMap<String, Box<dyn Any>>);
#[cfg(not(feature = "alloc"))]
pub struct Values(HashMap<String, ()>);
#[derive(Default)]
pub struct Values(#[cfg(feature = "alloc")] HashMap<String, Box<dyn Any>>);

/// Returned by [`Values::get`].
#[derive(Debug)]
Expand All @@ -43,40 +28,39 @@ pub enum ValueError {
}

impl Values {
/// Constructor for `Values`.
///
/// For a complete example, take a look at [`Values::get`].
pub fn new() -> Self {
Self(HashMap::new())
}

/// Add a new entry.
///
/// ```
/// let mut v = Values::new();
/// let mut v = Values::default();
///
/// v.add("Hello".into(), 12u8);
/// ```
pub fn add(&mut self, key: impl AsRef<str>, value: impl Any) {
self.0.insert(key.as_ref().into(), Box::new(value));
pub fn add(&mut self, _key: impl AsRef<str>, _value: impl Any) {
#[cfg(feature = "alloc")]
self.0.insert(_key.as_ref().into(), Box::new(_value));
}

/// ```
/// let mut v = Values::new();
/// let mut v = Values::default();
///
/// v.add("Hello".into(), 12u8);
/// assert_eq!(v.get::<u8>("Hell", Err(ValueError::NotPresent)));
/// assert_eq!(v.get::<usize>("Hello", Err(ValueError::WrongType)));
/// assert_eq!(v.get::<u8>("Hello", Ok(12u8)));
/// ```
pub fn get<T: 'static>(&self, key: impl AsRef<str>) -> Result<&T, ValueError> {
let key: &str = key.as_ref();
let Some(value) = self.0.get(key) else {
return Err(ValueError::NotPresent);
};
match value.downcast_ref::<T>() {
Some(v) => Ok(v),
None => Err(ValueError::WrongType),
pub fn get<T: 'static>(&self, _key: impl AsRef<str>) -> Result<&T, ValueError> {
#[cfg(feature = "alloc")]
{
let key: &str = _key.as_ref();
let Some(value) = self.0.get(key) else {
return Err(ValueError::NotPresent);
};
match value.downcast_ref::<T>() {
Some(v) => Ok(v),
None => Err(ValueError::WrongType),
}
}
#[cfg(not(feature = "alloc"))]
Err(ValueError::NotPresent)
}
}
4 changes: 2 additions & 2 deletions testing/tests/values.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ fn test_values() {
)]
struct V;

let mut values = Values::new();
let mut values = Values::default();

values.add("a", 12u32);
assert_eq!(V.render_with_values(&values).unwrap(), "12");
Expand All @@ -28,7 +28,7 @@ fn test_values2() {
)]
struct V;

let mut values = Values::new();
let mut values = Values::default();

values.add("a", "hey");
values.add("b", false);
Expand Down

0 comments on commit 4dc727a

Please sign in to comment.