-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcformat.jl
More file actions
327 lines (303 loc) · 11.1 KB
/
cformat.jl
File metadata and controls
327 lines (303 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
formatters = Dict{ ASCIIStr, Function }()
cfmt( fmt::ASCIIStr, x::Union{<:AbstractString,<:Real,<:Rational,<:Char} ) = m_eval(Expr(:call, generate_formatter( fmt ), x))
function cfmt( fmt_str::ASCIIStr, x::Number )
#remove width information
new_fmt_str = replace(fmt_str, r"(%(\d+\$)?[\-\+#0' ]*)(\d+)?"=>s"\1")
s = fmt_Number(x, x->m_eval(Expr(:call, generate_formatter( new_fmt_str ), AbstractFloat(x))))
# extract width information
m = match(r"%(\d+\$)?[\-\+#0' ]*(\d+)?", fmt_str)
width = m[2] == nothing ? 0 : parse(Int, m[2])
fmt(s, width, occursin("-", fmt_str) ? :left : :right)
end
function checkfmt(fmt)
test = PF.parse( fmt )
(length( test ) == 1 && typeof( test[1] ) <: Tuple) ||
error( "Only one AND undecorated format string is allowed")
end
function generate_formatter( fmt::ASCIIStr )
global formatters
haskey( formatters, fmt ) && return formatters[fmt]
if !occursin("'", fmt)
checkfmt(fmt)
formatter = @eval(x->@sprintf( $fmt, x ))
return (formatters[ fmt ] = x->Base.invokelatest(formatter, x))
end
conversion = fmt[end]
conversion in "sduifF" ||
error( string("thousand separator not defined for ", conversion, " conversion") )
fmtactual = replace( fmt, "'" => ""; count=1 )
checkfmt( fmtactual )
formatter =
if !(conversion in "sfF")
@eval(x->checkcommas(@sprintf( $fmtactual, x )))
elseif endswith( fmtactual, 's')
@eval((x::Real)->((eltype(x) <: Rational)
? addcommasrat(@sprintf( $fmtactual, x ))
: addcommasreal(@sprintf( $fmtactual, x ))))
else
@eval((x::Real)->addcommasreal(@sprintf( $fmtactual, x )))
end
return (formatters[ fmt ] = x->Base.invokelatest(formatter, x))
end
function addcommasreal(s)
len = length(s)
dpos = findfirst( isequal('.'), s )
dpos !== nothing && return addcommas(s, len, dpos-1)
# find the rightmost digit
for i in len:-1:1
isdigit( s[i] ) && return addcommas(s, len, i)
end
s
end
# commas are added to only the numerator
addcommasrat(s) = addcommas(s, length(s), findfirst( isequal('/'), s )-1)
function checkcommas(s)
len = length(s)
for i in len:-1:1
isdigit( s[i] ) && return addcommas(s, len, i)
end
s
end
function addcommas(s::T, len, lst) where {T<:AbstractString}
lst < 4 && return s
beg = 1
while beg < len
isdigit(s[beg]) && break
beg += 1
end
dig = lst - beg + 1
dig < 4 && return s
commas = div(dig - 1, 3)
sv = Base.StringVector(len + commas)
for i = 1:beg-1; sv[i] = s[i]; end
cnt = dig - commas*3
pos = beg - 1
for i = beg:lst-3
sv[pos += 1] = s[i]
(cnt -= 1) == 0 && (cnt = 3; sv[pos += 1] = ',')
end
for i = lst-2:len; sv[i+commas] = s[i]; end
T(sv)
end
addcommas(s) = (l = length(s); addcommas(s, l, l))
function generate_format_string(;
width::Int=-1,
precision::Int= -1,
leftjustified::Bool=false,
zeropadding::Bool=false,
commas::Bool=false,
signed::Bool=false,
positivespace::Bool=false,
alternative::Bool=false,
conversion::ASCIIStr="f" #aAdecEfFiosxX
)
s = ['%'%UInt8]
commas &&
push!(s, '\'')
alternative && in( conversion[1], "aAeEfFoxX" ) &&
push!(s, '#')
zeropadding && !leftjustified && width != -1 &&
push!(s, '0')
if signed
push!(s, '+')
elseif positivespace
push!(s, ' ')
end
if width != -1
leftjustified && push!(s, '-')
append!(s, _codeunits(string( width )))
end
precision != -1 &&
append!(s, _codeunits(string( '.', precision )))
String(append!(s, _codeunits(conversion)))
end
function format(x::T; kwargs...) where T<:Number
s = fmt_Number(x, x->format(AbstractFloat(x); kwargs..., width=-1))
fmt(s, get(kwargs, :width, 0), get(kwargs, :leftjustified, false) ? :left : :right)
end
function format( x::T;
width::Int=-1,
precision::Int= -1,
leftjustified::Bool=false,
zeropadding::Bool=false, # when right-justified, use 0 instead of space to fill
commas::Bool=false,
signed::Bool=false, # +/- prefix
positivespace::Bool=false,
stripzeros::Bool=(precision== -1),
parens::Bool=false, # use (1.00) instead of -1.00. Used in finance
alternative::Bool=false, # usually for hex
mixedfraction::Bool=false,
mixedfractionsep::UTF8Str="_",
fractionsep::UTF8Str="/", # num / den
fractionwidth::Int = 0,
tryden::Int = 0, # if 2 or higher,
# try to use this denominator, without losing precision
suffix::UTF8Str="", # useful for units/%
autoscale::Symbol=:none, # :metric, :binary or :finance
conversion::ASCIIStr=""
) where {T<:Real}
checkwidth = commas
if conversion == ""
if T <: AbstractFloat || T <: Rational && precision != -1
actualconv = "f"
elseif T <: Unsigned
actualconv = "x"
elseif T <: Integer
actualconv = "d"
else
conversion = "s"
actualconv = "s"
end
else
actualconv = conversion
end
signed && commas && error( "You cannot use signed (+/-) AND commas at the same time")
T <: Rational && conversion == "s" && (stripzeros = false)
if ( T <: AbstractFloat && actualconv == "f" || T <: Integer ) && autoscale != :none
actualconv = "f"
if autoscale == :metric
scales = [
(1e24, "Y" ),
(1e21, "Z" ),
(1e18, "E" ),
(1e15, "P" ),
(1e12, "T" ),
(1e9, "G"),
(1e6, "M"),
(1e3, "k") ]
if abs(x) > 1
for (mag, sym) in scales
if abs(x) >= mag
x /= mag
suffix = string(sym, suffix)
break
end
end
elseif T <: AbstractFloat
smallscales = [
( 1e-12, "p" ),
( 1e-9, "n" ),
( 1e-6, "μ" ),
( 1e-3, "m" ) ]
for (mag,sym) in smallscales
if abs(x) < mag*10
x /= mag
suffix = string(sym, suffix)
break
end
end
end
else
if autoscale == :binary
scales = [
(1024.0 ^8, "Yi" ),
(1024.0 ^7, "Zi" ),
(1024.0 ^6, "Ei" ),
(1024.0 ^5, "Pi" ),
(1024.0 ^4, "Ti" ),
(1024.0 ^3, "Gi"),
(1024.0 ^2, "Mi"),
(1024.0, "Ki")
]
else # :finance
scales = [
(1e12, "t" ),
(1e9, "b"),
(1e6, "m"),
(1e3, "k") ]
end
for (mag, sym) in scales
if abs(x) >= mag
x /= mag
suffix = string(sym, suffix)
break
end
end
end
end
nonneg = x >= 0
fractional = 0
if T <: Rational && mixedfraction
actualconv = "d"
actualx = trunc( Int, x )
fractional = abs(x) - abs(actualx)
else
actualx = (parens && !in( actualconv[1], "xX" )) ? abs(x) : x
end
s = cfmt( generate_format_string( width=width,
precision=precision,
leftjustified=leftjustified,
zeropadding=zeropadding,
commas=commas,
signed=signed,
positivespace=positivespace,
alternative=alternative,
conversion=actualconv
),
actualx)
if T <:Rational && conversion == "s"
if mixedfraction && fractional != 0
num = fractional.num
den = fractional.den
if tryden >= 2 && mod( tryden, den ) == 0
num *= div(tryden,den)
den = tryden
end
fs = string( num, fractionsep, den)
length(fs) < fractionwidth &&
(fs = string(repeat( "0", fractionwidth - length(fs) ), fs))
s = (actualx != 0
? string(rstrip(s), mixedfractionsep, fs)
: (nonneg ? fs : string('-', fs)))
checkwidth = true
elseif !mixedfraction
s = replace( s, "//" => fractionsep )
checkwidth = true
end
elseif stripzeros && in( actualconv[1], "fFeEs" )
dpos = findfirst( isequal('.'), s )
dpos === nothing && (dpos = length(s))
if actualconv[1] in "eEs"
epos = findfirst(isequal(actualconv[1] == 'E' ? 'E' : 'e'), s)
rpos = (epos === nothing) ? length( s ) : (epos-1)
else
rpos = length(s)
end
# rpos at this point is the rightmost possible char to start
# stripping
stripfrom = rpos+1
for i = rpos:-1:dpos+1
if s[i] == '0'
stripfrom = i
elseif s[i] ==' '
continue
else
break
end
end
if stripfrom <= rpos
# everything after decimal is 0, so strip the decimal too
s = string(s[1:stripfrom-1-(stripfrom == dpos+1)], s[rpos+1:end])
checkwidth = true
end
end
s = string(s, suffix)
if parens && !in( actualconv[1], "xX" )
# if zero or positive, we still need 1 white space on the right
s = nonneg ? string(' ', strip(s), ' ') : string('(', strip(s), ')')
checkwidth = true
end
if checkwidth && width != -1
if (len = length(s) - width) > 0
s = replace( s, " " => ""; count=len )
if (len = length(s) - width) > 0
endswith(s, " ") && (s = reverse(replace(reverse(s), " " => ""; count=len)))
(len = length(s) - width) > 0 && (s = replace( s, "," => ""; count=len ))
end
elseif len < 0
# Todo: should use lpad or rpad here, can be more efficient
s = leftjustified ? string(s, repeat( " ", -len )) : string(repeat( " ", -len), s)
end
end
s
end