From f502412f349c4bf8b388809a3fcdc999c869dffc Mon Sep 17 00:00:00 2001 From: kimikage Date: Mon, 26 Oct 2026 01:39:37 +0900 Subject: [PATCH] Derive the rounding functions from the 2-/3-arg `round` --- src/ColorVectorSpace.jl | 29 +++++++++++++++++++++-------- test/runtests.jl | 2 ++ 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/src/ColorVectorSpace.jl b/src/ColorVectorSpace.jl index 5f4fa55..c83914d 100644 --- a/src/ColorVectorSpace.jl +++ b/src/ColorVectorSpace.jl @@ -10,7 +10,7 @@ using FixedPointNumbers: ShorterThanInt import Base: ==, +, -, *, /, ^, <, ~ import Base: abs, abs2, clamp, convert, copy, div, eps, float, length, mapreduce, - promote_op, promote_rule, zero, trunc, floor, round, ceil, bswap, + promote_op, promote_rule, zero, round, bswap, mod, mod1, rem, atan, hypot, max, min, real, typemin, typemax # More unaryops (mostly math functions) import Base: conj, sin, cos, tan, sinh, cosh, tanh, @@ -176,13 +176,21 @@ Base.reduce_empty(::typeof(Base.add_sum), ::Type{T}) where {T<:MathTypes{Bool}} ## Rounding & mod -for f in (:trunc, :floor, :round, :ceil, :eps, :bswap) - @eval $f(g::Gray{T}) where {T} = Gray{T}($f(gray(g))) -end -eps(::Type{Gray{T}}) where {T} = Gray(eps(T)) - -for f in (:trunc, :floor, :round, :ceil) - @eval $f(::Type{T}, g::Gray) where {T<:Integer} = $f(T, gray(g)) +round(x::Gray{T}, r::RoundingMode) where {T} = Gray{T}(round(gray(x), r)) +round(::Type{Ti}, g::Gray, r::RoundingMode) where {Ti<:Integer} = round(Ti, gray(g), r) +for (m, f) in ((:(:Nearest), :round), + (:(:ToZero), :trunc), + (:(:Up), :ceil), + (:(:Down), :floor)) + @eval begin + if !hasmethod($f, Tuple{Gray}) || which($f, Tuple{Gray}).module !== Base + Base.$f(x::Gray) = round(x, RoundingMode{$m}()) + end + if !hasmethod($f, Tuple{Type{<:Integer}, Gray}) || + which($f, Tuple{Type{<:Integer}, Gray}).module !== Base + Base.$f(::Type{Ti}, x::Gray) where {Ti <: Integer} = round(Ti, x, RoundingMode{$m}()) + end + end end for f in (:mod, :rem, :mod1) @@ -190,6 +198,11 @@ for f in (:mod, :rem, :mod1) @eval $f(x::Gray, m::Real) = Gray($f(gray(x), m)) end +bswap(g::Gray{T}) where {T} = Gray{T}(bswap(gray(g))) + +eps(g::Gray{T}) where {T} = Gray{T}(eps(gray(g))) +eps(::Type{Gray{T}}) where {T} = Gray(eps(T)) + dotc(x::T, y::T) where {T<:Real} = acc(x)*acc(y) dotc(x::Real, y::Real) = dotc(promote(x, y)...) diff --git a/test/runtests.jl b/test/runtests.jl index f6a11a6..38898ef 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -349,6 +349,8 @@ ColorTypes.comp2(c::RGBA32) = alpha(c) @test @eval($op(Int, $g)) === v end end + @test round(Gray(0.4), RoundNearest) === round(Gray(0.4)) + @test round(Int8, Gray(0.4), RoundToZero) === trunc(Int8, Gray(0.4)) @testset "$op" for op in (:mod, :rem, :mod1) for (g1, g2) in ((Gray(0.4), Gray(0.3)), (Gray(N0f8(0.4)), Gray(N0f8(0.3)))) v = @eval $op(gray($g1), gray($g2))