From c0d891c1da8c3ead702cbeb1743c52e2c5b87d68 Mon Sep 17 00:00:00 2001
From: Marco Matthies <71844+marcom@users.noreply.github.com>
Date: Tue, 20 Aug 2024 21:31:12 +0200
Subject: [PATCH] Make bounds function type-stable

---
 src/core/utils.jl | 12 ++++--------
 test/io_tests.jl  | 12 ++++++++++++
 2 files changed, 16 insertions(+), 8 deletions(-)

diff --git a/src/core/utils.jl b/src/core/utils.jl
index 25d1b1d..067c966 100644
--- a/src/core/utils.jl
+++ b/src/core/utils.jl
@@ -164,14 +164,10 @@ end
 A utility function to make sure that a number is within a given set of bounds.
 Returns `max`/`min` if `x` is greater/less than this.
 """
-function bounds(x::Number; max::Number=Inf, min::Number=0)
-    if unit(x) != NoUnits
-        max = max*unit(x)
-        min = min*unit(x)
-    end
-    x > max ? max :
-        x < min ? min :
-        x
+function bounds(x::T; max::T=typemax(T), min::T=zero(T)) where {T<:Union{Real,Unitful.AbstractQuantity}}
+    x > max && return max
+    x < min && return min
+    return x
 end
 
 """
diff --git a/test/io_tests.jl b/test/io_tests.jl
index deebec3..17b18eb 100644
--- a/test/io_tests.jl
+++ b/test/io_tests.jl
@@ -122,7 +122,19 @@ end
     @test length(AnnualDate(heute):birthday) == 14
     # bounds
     @test Ps.bounds(3) == 3
+    @test Ps.bounds(3.0) == 3.0
     @test Ps.bounds(-3) == 0
+    @test Ps.bounds(-3.0) == 0.0
     @test Ps.bounds(20, max=10) == 10
+    @test Ps.bounds(20.0, max=10.0) == 10.0
     @test Ps.bounds(-3, min=-10) == -3
+    @test Ps.bounds(-3.0, min=-10.0) == -3.0
+    @test Ps.bounds(3u"m") == 3u"m"
+    @test Ps.bounds(3.0u"m") == 3.0u"m"
+    @test Ps.bounds(-3u"m") == 0u"m"
+    @test Ps.bounds(-3.0u"m") == 0.0u"m"
+    @test Ps.bounds(20u"m", max=10u"m") == 10u"m"
+    @test Ps.bounds(20.0u"m", max=10.0u"m") == 10.0u"m"
+    @test Ps.bounds(-3u"m", min=-10u"m") == -3u"m"
+    @test Ps.bounds(-3.0u"m", min=-10.0u"m") == -3.0u"m"
 end
-- 
GitLab