Skip to content

Commit

Permalink
Refactor internal utilities
Browse files Browse the repository at this point in the history
  • Loading branch information
MilesCranmer committed Oct 28, 2023
1 parent f8b6e98 commit 3bb9452
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 14 deletions.
1 change: 1 addition & 0 deletions src/DynamicQuantities.jl
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export ustrip, dimension
export ulength, umass, utime, ucurrent, utemperature, uluminosity, uamount
export uparse, @u_str, sym_uparse, @us_str, uexpand, uconvert

include("internal_utils.jl")
include("fixed_rational.jl")
include("types.jl")
include("utils.jl")
Expand Down
25 changes: 25 additions & 0 deletions src/internal_utils.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""
This file contains utility functions that are not specific to the
library, but are used throughout.
"""

@generated function fieldnames_equal(::Type{T1}, ::Type{T2}) where {T1,T2}
# Needs to be a generated function as might not be inlined
return Base.fieldnames(T1) == Base.fieldnames(T2)
end

const SUPERSCRIPT_MAPPING = ('', '¹', '²', '³', '', '', '', '', '', '')
const INTCHARS = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')

function to_superscript(s::AbstractString)
chars = map(replace(s, "//" => "")) do c
if c INTCHARS
SUPERSCRIPT_MAPPING[parse(Int, c)+1]
elseif c == '-'
''
else
c
end
end
return join(chars)
end
2 changes: 1 addition & 1 deletion src/types.jl
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ end
(::Type{D})(; kws...) where {R,D<:AbstractDimensions{R}} = constructor_of(D)(R; kws...)
(::Type{D})(; kws...) where {D<:AbstractDimensions} = D(DEFAULT_DIM_BASE_TYPE; kws...)
function (::Type{D})(d::D2) where {R,D<:AbstractDimensions{R},D2<:AbstractDimensions}
issetequal(static_fieldnames(D), static_fieldnames(D2)) ||
fieldnames_equal(D, D2) ||
error("Cannot create a dimensions of `$(D)` from `$(D2)`. Please write a custom method for construction.")
D((getproperty(d, k) for k in static_fieldnames(D))...)
end
Expand Down
13 changes: 0 additions & 13 deletions src/utils.jl
Original file line number Diff line number Diff line change
Expand Up @@ -162,19 +162,6 @@ end

string_rational(x) = isinteger(x) ? string(round(Int, x)) : string(x)
pretty_print_exponent(io::IO, x) = print(io, to_superscript(string_rational(x)))
const SUPERSCRIPT_MAPPING = ('', '¹', '²', '³', '', '', '', '', '', '')
const INTCHARS = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
to_superscript(s::AbstractString) = join(
map(replace(s, "//" => "")) do c
if c INTCHARS
SUPERSCRIPT_MAPPING[parse(Int, c)+1]
elseif c == '-'
''
else
c
end
end
)

tryrationalize(::Type{R}, x::R) where {R} = x
tryrationalize(::Type{R}, x::Union{Rational,Integer}) where {R} = convert(R, x)
Expand Down

0 comments on commit 3bb9452

Please sign in to comment.