From 7e2df67fee340d2b32c80830b87eb8032e2c5f39 Mon Sep 17 00:00:00 2001
From: Martin Berg Alstad <emberal+github@pm.me>
Date: Sat, 31 Aug 2024 17:49:27 +0200
Subject: [PATCH] Comments.

Coverage to Makefile.toml.

Added branch to map! to allow for instantiating with default values.
---
 .env                                  |  1 -
 Makefile.toml                         |  4 +++
 crates/tests/tests/test_containers.rs |  8 +++--
 src/axum/router.rs                    |  4 +++
 src/diesel/mod.rs                     |  3 ++
 src/io/file.rs                        |  5 +++
 src/nom/combinators.rs                | 23 +++++++++++++
 src/time/common.rs                    |  2 ++
 src/vector/distinct.rs                |  2 ++
 src/vector/map.rs                     | 47 +++++++++++++++++++++++++++
 10 files changed, 95 insertions(+), 4 deletions(-)
 delete mode 100644 .env

diff --git a/.env b/.env
deleted file mode 100644
index 0d36dd0..0000000
--- a/.env
+++ /dev/null
@@ -1 +0,0 @@
-DATABASE_URL="postgres://postgres:postgres@localhost:32768/postgres"
\ No newline at end of file
diff --git a/Makefile.toml b/Makefile.toml
index 925969b..0e2175a 100644
--- a/Makefile.toml
+++ b/Makefile.toml
@@ -9,3 +9,7 @@ args = ["fmt", "--all"]
 [tasks.test]
 command = "cargo"
 args = ["test", "--all-features"]
+
+[tasks.coverage]
+command = "cargo"
+args = ["llvm-cov", "--all-features"]
diff --git a/crates/tests/tests/test_containers.rs b/crates/tests/tests/test_containers.rs
index c24d4f8..10f295c 100644
--- a/crates/tests/tests/test_containers.rs
+++ b/crates/tests/tests/test_containers.rs
@@ -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> {
diff --git a/src/axum/router.rs b/src/axum/router.rs
index fc80a4d..a48f284 100644
--- a/src/axum/router.rs
+++ b/src/axum/router.rs
@@ -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),* $(,)?) => {
diff --git a/src/diesel/mod.rs b/src/diesel/mod.rs
index c9e2bb1..d117bc2 100644
--- a/src/diesel/mod.rs
+++ b/src/diesel/mod.rs
@@ -1 +1,4 @@
 pub mod pool;
+
+/// Re-export diesel::result::Error as DieselError
+pub type DieselError = diesel::result::Error;
diff --git a/src/io/file.rs b/src/io/file.rs
index 9730e54..b45d7b5 100644
--- a/src/io/file.rs
+++ b/src/io/file.rs
@@ -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>,
diff --git a/src/nom/combinators.rs b/src/nom/combinators.rs
index a5c8dbf..ca011b8 100644
--- a/src/nom/combinators.rs
+++ b/src/nom/combinators.rs
@@ -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>,
diff --git a/src/time/common.rs b/src/time/common.rs
index 072e128..b6182e9 100644
--- a/src/time/common.rs
+++ b/src/time/common.rs
@@ -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 {
diff --git a/src/vector/distinct.rs b/src/vector/distinct.rs
index 700ffc1..15c4bfc 100644
--- a/src/vector/distinct.rs
+++ b/src/vector/distinct.rs
@@ -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);
 }
 
diff --git a/src/vector/map.rs b/src/vector/map.rs
index b0cd573..0fa4cc6 100644
--- a/src/vector/map.rs
+++ b/src/vector/map.rs
@@ -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);
+    }
 }