Comments.

Coverage to Makefile.toml.

Added branch to map! to allow for instantiating with default values.
This commit is contained in:
Martin Berg Alstad 2024-08-31 17:49:27 +02:00
parent 8fb89e0459
commit 7e2df67fee
10 changed files with 95 additions and 4 deletions

1
.env
View File

@ -1 +0,0 @@
DATABASE_URL="postgres://postgres:postgres@localhost:32768/postgres"

View File

@ -9,3 +9,7 @@ args = ["fmt", "--all"]
[tasks.test]
command = "cargo"
args = ["test", "--all-features"]
[tasks.coverage]
command = "cargo"
args = ["llvm-cov", "--all-features"]

View File

@ -3,13 +3,15 @@ use diesel_async::pooled_connection::deadpool::{BuildError, PoolError};
use diesel_async::AsyncPgConnection;
use diesel_async_migrations::EmbeddedMigrations;
use lib::diesel::pool::{create_pool_from_url, PgPool};
use lib::diesel::DieselError;
use testcontainers_modules::postgres::Postgres;
use testcontainers_modules::testcontainers::runners::AsyncRunner;
use testcontainers_modules::testcontainers::{ContainerAsync, TestcontainersError};
/// When the TestContainer is dropped, the container will be removed.
/// # Panics
/// If destructed and the container field is dropped, the container will be removed, and using the pool will cause panic.
/// # Errors
/// If destructed and the container field is dropped, the container will be stopped
/// and all connections from the pool will result in DatabaseError.
#[derive(Constructor)]
pub struct TestContainer {
pub container: ContainerAsync<Postgres>,
@ -21,7 +23,7 @@ pub enum ContainerError {
TestContainers(TestcontainersError),
BuildError(BuildError),
PoolError(PoolError),
DieselError(diesel::result::Error),
DieselError(DieselError),
}
pub async fn create_test_containers_pool<'a>() -> Result<TestContainer, ContainerError> {

View File

@ -77,6 +77,10 @@ macro_rules! routes {
}
/// Merges the given routers into a single router.
/// # Examples
/// ```
/// let _: axum::Router<()> = lib::join_routes![axum::Router::new(), axum::Router::new()];
/// ```
#[macro_export]
macro_rules! join_routes {
($($route:expr),* $(,)?) => {

View File

@ -1 +1,4 @@
pub mod pool;
/// Re-export diesel::result::Error as DieselError
pub type DieselError = diesel::result::Error;

View File

@ -1,5 +1,10 @@
use {std::io::Error, tokio::fs::File, tokio_util::io::ReaderStream};
/// Loads a file from the file system and returns a stream of bytes.
/// # Arguments
/// * `file_path` - The path to the file to load.
/// # Returns
/// A stream of bytes from the file if the file is found. Otherwise, an error is returned.
pub async fn load_file<Path>(file_path: Path) -> Result<ReaderStream<File>, Error>
where
Path: AsRef<std::path::Path>,

View File

@ -47,6 +47,29 @@ where
take_while_m_n(n, n, predicate)
}
/// Parse the inner parser and then the end of the input.
/// Very useful for ensuring that the entire input is consumed.
/// - Parameters
/// - `inner`: The parser to run
/// - Returns: A parser that runs the inner parser and then the end of the input
/// # Example
/// ```
/// use nom::bytes::complete::{tag};
/// use lib::nom::combinators::exhausted;
///
/// let input = "test";
/// let (remaining, result) = exhausted(tag("test"))(input).unwrap();
/// assert_eq!(remaining, "");
/// assert_eq!(result, "test");
/// ```
/// - Fails if the input is not exhausted
/// ```
/// use nom::bytes::complete::{tag};
/// use lib::nom::combinators::exhausted;
///
/// let input = "test";
/// assert!(exhausted(tag("tes"))(input).is_err());
/// ```
pub fn exhausted<'a, Parser, R>(inner: Parser) -> impl FnMut(&'a str) -> IResult<&'a str, R>
where
Parser: FnMut(&'a str) -> IResult<&'a str, R>,

View File

@ -1,6 +1,8 @@
use chrono::NaiveDateTime;
use derive_more::{Constructor, From};
/// Represents a date-time interval using naive date-time.
/// All date-times are expected to be in UTC.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Constructor, From)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DateTimeInterval {

View File

@ -1,4 +1,6 @@
/// Modify self to contain only distinct elements.
pub trait Distinct {
/// Modify self to contain only distinct elements.
fn distinct(&mut self);
}

View File

@ -1,6 +1,38 @@
/// Create a `HashMap` with the given key-value pairs.
/// There are three ways to use this macro:
/// 1. `map!()`: Create an empty `HashMap`.
/// 2. `map!(usize; 1, 2)`: Create a `HashMap` with the keys `1` and `2` with the default value of `usize`.
/// 3. `map!("one" => 1, "two" => 2)`: Create a `HashMap` with the keys `"one"` and `"two"` with the values `1` and `2` respectively.
/// # Examples
/// ```
/// use std::collections::HashMap;
///
/// let empty_map: HashMap<usize, usize> = lib::map!();
/// assert_eq!(empty_map.len(), 0);
///
/// let map: HashMap<&str, usize> = lib::map!("one" => 1, "two" => 2);
/// assert_eq!(map.len(), 2);
/// assert_eq!(map.get("one"), Some(&1));
/// assert_eq!(map.get("two"), Some(&2));
///
/// let map: HashMap<usize, usize> = lib::map!(usize; 1, 2);
/// assert_eq!(map.len(), 2);
/// assert_eq!(map.get(&1), Some(&0));
/// assert_eq!(map.get(&2), Some(&0));
/// ```
#[macro_export]
macro_rules! map {
() => { std::collections::HashMap::new() };
($default:ty; $($key:expr),* $(,)?) => {
{
#[allow(unused_mut)]
let mut temp_map = std::collections::HashMap::new();
$(
temp_map.insert($key, <$default>::default());
)*
temp_map
}
};
($($k:expr => $v:expr),* $(,)?) => {
{
let mut temp_map = std::collections::HashMap::new();
@ -33,4 +65,19 @@ mod tests {
assert_eq!(map.get("two"), Some(&2));
assert_eq!(map.get("three"), Some(&3));
}
#[test]
fn test_map_only_keys() {
let map: HashMap<usize, usize> = map!(usize; 1, 2, 3);
assert_eq!(map.len(), 3);
assert_eq!(map.get(&1), Some(&0));
assert_eq!(map.get(&2), Some(&0));
assert_eq!(map.get(&3), Some(&0));
}
#[test]
fn test_map_only_keys_0_keys() {
let map: HashMap<usize, usize> = map!(usize;);
assert_eq!(map.len(), 0);
}
}