• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

JuliaLang / julia / #38182

15 Aug 2025 03:55AM UTC coverage: 77.87% (-0.4%) from 78.28%
#38182

push

local

web-flow
🤖 [master] Bump the SparseArrays stdlib from 30201ab to bb5ecc0 (#59263)

Stdlib: SparseArrays
URL: https://github.com/JuliaSparse/SparseArrays.jl.git
Stdlib branch: main
Julia branch: master
Old commit: 30201ab
New commit: bb5ecc0
Julia version: 1.13.0-DEV
SparseArrays version: 1.13.0
Bump invoked by: @ViralBShah
Powered by:
[BumpStdlibs.jl](https://github.com/JuliaLang/BumpStdlibs.jl)

Diff:
https://github.com/JuliaSparse/SparseArrays.jl/compare/30201abcb...bb5ecc091

```
$ git log --oneline 30201ab..bb5ecc0
bb5ecc0 fast quadratic form for dense matrix, sparse vectors (#640)
34ece87 Extend 3-arg `dot` to generic `HermOrSym` sparse matrices (#643)
095b685 Exclude unintended complex symmetric sparse matrices from 3-arg `dot` (#642)
8049287 Fix signature for 2-arg matrix-matrix `dot` (#641)
cff971d Make cond(::SparseMatrix, 1 / Inf) discoverable from 2-norm error (#629)
```

Co-authored-by: ViralBShah <744411+ViralBShah@users.noreply.github.com>

48274 of 61993 relevant lines covered (77.87%)

9571166.83 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

47.87
/base/int.jl
1
# This file is a part of Julia. License is MIT: https://julialang.org/license
2

3
## integer arithmetic ##
4

5
# The tuples and types that do not include 128 bit sizes are necessary to handle
6
# certain issues on 32-bit machines, and also to simplify promotion rules, as
7
# they are also used elsewhere where Int128/UInt128 support is separated out,
8
# such as in hashing2.jl
9

10
const BitSigned32_types      = (Int8, Int16, Int32)
11
const BitUnsigned32_types    = (UInt8, UInt16, UInt32)
12
const BitInteger32_types     = (BitSigned32_types..., BitUnsigned32_types...)
13

14
const BitSigned64_types      = (BitSigned32_types..., Int64)
15
const BitUnsigned64_types    = (BitUnsigned32_types..., UInt64)
16
const BitInteger64_types     = (BitSigned64_types..., BitUnsigned64_types...)
17

18
const BitSigned_types        = (BitSigned64_types..., Int128)
19
const BitUnsigned_types      = (BitUnsigned64_types..., UInt128)
20
const BitInteger_types       = (BitSigned_types..., BitUnsigned_types...)
21

22
const BitSignedSmall_types   = Int === Int64 ? ( Int8,  Int16,  Int32) : ( Int8,  Int16)
23
const BitUnsignedSmall_types = Int === Int64 ? (UInt8, UInt16, UInt32) : (UInt8, UInt16)
24
const BitIntegerSmall_types  = (BitSignedSmall_types..., BitUnsignedSmall_types...)
25

26
const BitSigned32      = Union{BitSigned32_types...}
27
const BitUnsigned32    = Union{BitUnsigned32_types...}
28
const BitInteger32     = Union{BitInteger32_types...}
29

30
const BitSigned64      = Union{BitSigned64_types...}
31
const BitUnsigned64    = Union{BitUnsigned64_types...}
32
const BitInteger64     = Union{BitInteger64_types...}
33

34
const BitSigned        = Union{BitSigned_types...}
35
const BitUnsigned      = Union{BitUnsigned_types...}
36
const BitInteger       = Union{BitInteger_types...}
37

38
const BitSignedSmall   = Union{BitSignedSmall_types...}
39
const BitUnsignedSmall = Union{BitUnsignedSmall_types...}
40
const BitIntegerSmall  = Union{BitIntegerSmall_types...}
41

42
const BitSigned64T     = Union{Type{Int8}, Type{Int16}, Type{Int32}, Type{Int64}}
43
const BitUnsigned64T   = Union{Type{UInt8}, Type{UInt16}, Type{UInt32}, Type{UInt64}}
44

45
const BitIntegerType = Union{map(T->Type{T}, BitInteger_types)...}
×
46

47
# >> this use of `unsigned` is defined somewhere else << the docstring should migrate there
48
"""
49
    unsigned(T::Integer)
50

51
Convert an integer bitstype to the unsigned type of the same size.
52
# Examples
53
```jldoctest
54
julia> unsigned(Int16)
55
UInt16
56
julia> unsigned(UInt64)
57
UInt64
58
```
59
""" unsigned
60

61
"""
62
    signed(T::Integer)
63

64
Convert an integer bitstype to the signed type of the same size.
65
# Examples
66
```jldoctest
67
julia> signed(UInt16)
68
Int16
69
julia> signed(UInt64)
70
Int64
71
```
72
"""
73
signed(::Type{Bool}) = Int
×
74
signed(::Type{UInt8}) = Int8
×
75
signed(::Type{UInt16}) = Int16
×
76
signed(::Type{UInt32}) = Int32
×
77
signed(::Type{UInt64}) = Int64
1,930✔
78
signed(::Type{UInt128}) = Int128
×
79
signed(::Type{T}) where {T<:Signed} = T
×
80

81
## integer comparisons ##
82

83
(<)(x::T, y::T) where {T<:BitSigned}  = slt_int(x, y)
2,147,483,647✔
84

85
(-)(x::BitInteger)                    = neg_int(x)
2,147,483,647✔
86
(-)(x::T, y::T) where {T<:BitInteger} = sub_int(x, y)
2,147,483,647✔
87
(+)(x::T, y::T) where {T<:BitInteger} = add_int(x, y)
2,147,483,647✔
88
(*)(x::T, y::T) where {T<:BitInteger} = mul_int(x, y)
2,147,483,647✔
89

90
negate(x) = -x
412,006✔
91
negate(x::Unsigned) = -convert(Signed, x)
22✔
92
#widenegate(x) = -convert(widen(signed(typeof(x))), x)
93

94
inv(x::Integer) = float(one(x)) / float(x)
1,498✔
95
(/)(x::T, y::T) where {T<:Integer} = float(x) / float(y)
6,123✔
96
# skip promotion for system integer types
97
(/)(x::BitInteger, y::BitInteger) = float(x) / float(y)
11,435,711✔
98

99
"""
100
    isodd(x::Number)::Bool
101

102
Return `true` if `x` is an odd integer (that is, an integer not divisible by 2), and `false` otherwise.
103

104
!!! compat "Julia 1.7"
105
    Non-`Integer` arguments require Julia 1.7 or later.
106

107
# Examples
108
```jldoctest
109
julia> isodd(9)
110
true
111

112
julia> isodd(10)
113
false
114
```
115
"""
116
isodd(n::Number) = isreal(n) && isodd(real(n))
3✔
117
isodd(n::Real) = isinteger(n) && !iszero(rem(Integer(n), 2))
54,765,060✔
118

119
"""
120
    iseven(x::Number)::Bool
121

122
Return `true` if `x` is an even integer (that is, an integer divisible by 2), and `false` otherwise.
123

124
!!! compat "Julia 1.7"
125
    Non-`Integer` arguments require Julia 1.7 or later.
126

127
# Examples
128
```jldoctest
129
julia> iseven(9)
130
false
131

132
julia> iseven(10)
133
true
134
```
135
"""
136
iseven(n::Number) = isreal(n) && iseven(real(n))
3✔
137
iseven(n::Real) = isinteger(n) && iszero(rem(Integer(n), 2))
4,885,780✔
138

139
signbit(x::Integer) = x < 0
181,940,579✔
140
signbit(x::Unsigned) = false
×
141

142
isnegative(x::Unsigned) = false
×
143

144
flipsign(x::T, y::T) where {T<:BitSigned} = flipsign_int(x, y)
276,219,369✔
145
flipsign(x::BitSigned, y::BitSigned) = flipsign_int(promote(x, y)...) % typeof(x)
303,700✔
146

147
flipsign(x::Signed, y::Float16) = flipsign(x, bitcast(Int16, y))
×
148
flipsign(x::Signed, y::Float32) = flipsign(x, bitcast(Int32, y))
×
149
flipsign(x::Signed, y::Float64) = flipsign(x, bitcast(Int64, y))
×
150
flipsign(x::Signed, y::Real)    = flipsign(x, -oftype(x, signbit(y)))
32✔
151

152
copysign(x::Signed, y::Signed)  = flipsign(x, x ⊻ y)
659,699✔
153
copysign(x::Signed, y::Float16) = copysign(x, bitcast(Int16, y))
×
154
copysign(x::Signed, y::Float32) = copysign(x, bitcast(Int32, y))
297✔
155
copysign(x::Signed, y::Float64) = copysign(x, bitcast(Int64, y))
651,808✔
156
copysign(x::Signed, y::Real)    = copysign(x, -oftype(x, signbit(y)))
12✔
157

158
"""
159
    abs(x)
160

161
The absolute value of `x`.
162

163
When `abs` is applied to signed integers, overflow may occur,
164
resulting in the return of a negative value. This overflow occurs only
165
when `abs` is applied to the minimum representable value of a signed
166
integer. That is, when `x == typemin(typeof(x))`, `abs(x) == x < 0`,
167
not `-x` as might be expected.
168

169
See also: [`abs2`](@ref), [`unsigned`](@ref), [`sign`](@ref).
170

171
# Examples
172
```jldoctest
173
julia> abs(-3)
174
3
175

176
julia> abs(1 + im)
177
1.4142135623730951
178

179
julia> abs.(Int8[-128 -127 -126 0 126 127])  # overflow at typemin(Int8)
180
1×6 Matrix{Int8}:
181
 -128  127  126  0  126  127
182

183
julia> maximum(abs, [1, -2, 3, -4])
184
4
185
```
186
"""
187
function abs end
188

189
abs(x::Unsigned) = x
97,762,040✔
190
abs(x::Signed) = flipsign(x,x)
146,401,345✔
191

192
~(n::Integer) = -n-1
×
193

194
"""
195
    unsigned(x)
196

197
Convert a number to an unsigned integer. If the argument is signed, it is reinterpreted as
198
unsigned without checking for negative values.
199

200
See also: [`signed`](@ref), [`sign`](@ref), [`signbit`](@ref).
201

202
# Examples
203
```jldoctest
204
julia> unsigned(-2)
205
0xfffffffffffffffe
206

207
julia> unsigned(Int8(2))
208
0x02
209

210
julia> typeof(ans)
211
UInt8
212

213
julia> signed(unsigned(-2))
214
-2
215
```
216
"""
217
unsigned(x) = x % typeof(convert(Unsigned, zero(x)))
97,682,632✔
218
unsigned(x::BitSigned) = reinterpret(typeof(convert(Unsigned, zero(x))), x)
623,519,540✔
219

220
"""
221
    signed(x)
222

223
Convert a number to a signed integer. If the argument is unsigned, it is reinterpreted as
224
signed without checking for overflow.
225

226
See also: [`unsigned`](@ref), [`sign`](@ref), [`signbit`](@ref).
227
"""
228
signed(x) = x % typeof(convert(Signed, zero(x)))
264,144✔
229
signed(x::BitUnsigned) = reinterpret(typeof(convert(Signed, zero(x))), x)
2,072,867✔
230

231
div(x::BitSigned, y::Unsigned) = flipsign(signed(div(unsigned(abs(x)), y)), x)
2,234,615✔
232
div(x::Unsigned, y::BitSigned) = unsigned(flipsign(signed(div(x, unsigned(abs(y)))), y))
62,187,432✔
233

234
rem(x::BitSigned, y::Unsigned) = flipsign(signed(rem(unsigned(abs(x)), y)), x)
40,041✔
235
rem(x::Unsigned, y::BitSigned) = rem(x, unsigned(abs(y)))
66,952,738✔
236

237
function divrem(x::BitSigned, y::Unsigned)
238
    q, r = divrem(unsigned(abs(x)), y)
238✔
239
    flipsign(signed(q), x), flipsign(signed(r), x)
238✔
240
end
241

242
function divrem(x::Unsigned, y::BitSigned)
20✔
243
    q, r = divrem(x, unsigned(abs(y)))
8,294✔
244
    unsigned(flipsign(signed(q), y)), r
8,294✔
245
end
246

247

248
"""
249
    mod(x, y)
250
    rem(x, y, RoundDown)
251

252
The reduction of `x` modulo `y`, or equivalently, the remainder of `x` after floored
253
division by `y`, i.e. `x - y*fld(x,y)` if computed without intermediate rounding.
254

255
The result will have the same sign as `y` if `isfinite(y)`, and magnitude less than `abs(y)` (with some
256
exceptions, see note below).
257

258
!!! note
259

260
    When used with floating point values, the exact result may not be representable by the
261
    type, and so rounding error may occur. In particular, if the exact result is very
262
    close to `y`, then it may be rounded to `y`.
263

264
See also: [`rem`](@ref), [`div`](@ref), [`fld`](@ref), [`mod1`](@ref), [`invmod`](@ref).
265

266
```jldoctest
267
julia> mod(8, 3)
268
2
269

270
julia> mod(9, 3)
271
0
272

273
julia> mod(8.9, 3)
274
2.9000000000000004
275

276
julia> mod(eps(), 3)
277
2.220446049250313e-16
278

279
julia> mod(-eps(), 3)
280
3.0
281

282
julia> mod.(-5:5, 3)'
283
1×11 adjoint(::Vector{Int64}) with eltype Int64:
284
 1  2  0  1  2  0  1  2  0  1  2
285
```
286
"""
287
function mod(x::T, y::T) where T<:Integer
16,778✔
288
    y == -1 && return T(0)   # avoid potential overflow in fld
4,457,223✔
289
    return x - fld(x, y) * y
4,489,938✔
290
end
291
function mod(x::BitSigned, y::Unsigned)
39,700✔
292
    remval = rem(x, y) # correct iff  remval>=0
39,701✔
293
    return unsigned(remval + (remval<zero(remval))*y)
39,701✔
294
end
295
function mod(x::Unsigned, y::Signed)
75✔
296
    remval =  signed(rem(x, y)) #remval>0 so correct iff y>0 or remval==0
405,657✔
297
    return remval + (!iszero(remval) && y<zero(y))*y
405,657✔
298
end
299
mod(x::T, y::T) where {T<:Unsigned} = rem(x, y)
83,472✔
300

301
# Don't promote integers for div/rem/mod since there is no danger of overflow,
302
# while there is a substantial performance penalty to 64-bit promotion.
303
div(x::T, y::T) where {T<:BitSigned64} = checked_sdiv_int(x, y)
122,047,112✔
304
rem(x::T, y::T) where {T<:BitSigned64} = checked_srem_int(x, y)
13,642,429✔
305
div(x::T, y::T) where {T<:BitUnsigned64} = checked_udiv_int(x, y)
294,175,987✔
306
rem(x::T, y::T) where {T<:BitUnsigned64} = checked_urem_int(x, y)
120,199,016✔
307

308
## integer bitwise operations ##
309

310
"""
311
    ~(x)
312

313
Bitwise not.
314

315
See also: [`!`](@ref), [`&`](@ref), [`|`](@ref).
316

317
# Examples
318
```jldoctest
319
julia> ~4
320
-5
321

322
julia> ~10
323
-11
324

325
julia> ~true
326
false
327
```
328
"""
329
(~)(x::BitInteger)             = not_int(x)
225,473,868✔
330

331
"""
332
    x & y
333

334
Bitwise and. Implements [three-valued logic](https://en.wikipedia.org/wiki/Three-valued_logic),
335
returning [`missing`](@ref) if one operand is `missing` and the other is `true`. Add parentheses for
336
function application form: `(&)(x, y)`.
337

338
See also: [`|`](@ref), [`xor`](@ref), [`&&`](@ref).
339

340
# Examples
341
```jldoctest
342
julia> 4 & 10
343
0
344

345
julia> 4 & 12
346
4
347

348
julia> true & missing
349
missing
350

351
julia> false & missing
352
false
353
```
354
"""
355
(&)(x::T, y::T) where {T<:BitInteger} = and_int(x, y)
2,147,483,647✔
356

357
"""
358
    x | y
359

360
Bitwise or. Implements [three-valued logic](https://en.wikipedia.org/wiki/Three-valued_logic),
361
returning [`missing`](@ref) if one operand is `missing` and the other is `false`.
362

363
See also: [`&`](@ref), [`xor`](@ref), [`||`](@ref).
364

365
# Examples
366
```jldoctest
367
julia> 4 | 10
368
14
369

370
julia> 4 | 1
371
5
372

373
julia> true | missing
374
true
375

376
julia> false | missing
377
missing
378
```
379
"""
380
(|)(x::T, y::T) where {T<:BitInteger} = or_int(x, y)
1,523,016,740✔
381
xor(x::T, y::T) where {T<:BitInteger} = xor_int(x, y)
2,147,483,647✔
382

383
"""
384
    bswap(n)
385

386
Reverse the byte order of `n`.
387

388
(See also [`ntoh`](@ref) and [`hton`](@ref) to convert between the current native byte order and big-endian order.)
389

390
# Examples
391
```jldoctest
392
julia> a = bswap(0x10203040)
393
0x40302010
394

395
julia> bswap(a)
396
0x10203040
397

398
julia> string(1, base = 2)
399
"1"
400

401
julia> string(bswap(1), base = 2)
402
"100000000000000000000000000000000000000000000000000000000"
403
```
404
"""
405
bswap(x::Union{Int8, UInt8, Bool}) = x
×
406
bswap(x::Union{Int16, UInt16, Int32, UInt32, Int64, UInt64, Int128, UInt128}) =
354,296,801✔
407
    bswap_int(x)
408

409
"""
410
    count_ones(x::Integer)::Integer
411

412
Number of ones in the binary representation of `x`.
413

414
# Examples
415
```jldoctest
416
julia> count_ones(7)
417
3
418

419
julia> count_ones(Int32(-1))
420
32
421
```
422
"""
423
count_ones(x::BitInteger) = (ctpop_int(x) % Int)::Int
3,356,181✔
424

425
"""
426
    leading_zeros(x::Integer)::Integer
427

428
Number of zeros leading the binary representation of `x`.
429

430
# Examples
431
```jldoctest
432
julia> leading_zeros(Int32(1))
433
31
434
```
435
"""
436
leading_zeros(x::BitInteger) = (ctlz_int(x) % Int)::Int
329,239,210✔
437

438
"""
439
    trailing_zeros(x::Integer)::Integer
440

441
Number of zeros trailing the binary representation of `x`.
442

443
# Examples
444
```jldoctest
445
julia> trailing_zeros(2)
446
1
447
```
448
"""
449
trailing_zeros(x::BitInteger) = (cttz_int(x) % Int)::Int
204,142,586✔
450

451
"""
452
    count_zeros(x::Integer)::Integer
453

454
Number of zeros in the binary representation of `x`.
455

456
# Examples
457
```jldoctest
458
julia> count_zeros(Int32(2 ^ 16 - 1))
459
16
460

461
julia> count_zeros(-1)
462
0
463
```
464
"""
465
count_zeros(x::Integer) = count_ones(~x)
4✔
466

467
"""
468
    leading_ones(x::Integer)::Integer
469

470
Number of ones leading the binary representation of `x`.
471

472
# Examples
473
```jldoctest
474
julia> leading_ones(UInt32(2 ^ 32 - 2))
475
31
476
```
477
"""
478
leading_ones(x::Integer) = leading_zeros(~x)
209,518,124✔
479

480
"""
481
    trailing_ones(x::Integer)::Integer
482

483
Number of ones trailing the binary representation of `x`.
484

485
# Examples
486
```jldoctest
487
julia> trailing_ones(3)
488
2
489
```
490
"""
491
trailing_ones(x::Integer) = trailing_zeros(~x)
55,382✔
492

493
"""
494
    top_set_bit(x::Integer)::Integer
495

496
The number of bits in `x`'s binary representation, excluding leading zeros.
497

498
Equivalently, the position of the most significant set bit in `x`'s binary
499
representation, measured from the least significant side.
500

501
Negative `x` are only supported when `x::BitSigned`.
502

503
See also: [`ndigits0z`](@ref), [`ndigits`](@ref).
504

505
# Examples
506
```jldoctest
507
julia> Base.top_set_bit(4)
508
3
509

510
julia> Base.top_set_bit(0)
511
0
512

513
julia> Base.top_set_bit(-1)
514
64
515
```
516
"""
517
top_set_bit(x::BitInteger) = 8sizeof(x) - leading_zeros(x)
103,501,042✔
518

519
## integer comparisons ##
520

521
(< )(x::T, y::T) where {T<:BitUnsigned} = ult_int(x, y)
2,147,483,647✔
522
(<=)(x::T, y::T) where {T<:BitSigned}   = sle_int(x, y)
2,147,483,647✔
523
(<=)(x::T, y::T) where {T<:BitUnsigned} = ule_int(x, y)
511,640,063✔
524

525
==(x::BitSigned,   y::BitUnsigned) = (x >= 0) & (unsigned(x) == y)
15,404,420✔
526
==(x::BitUnsigned, y::BitSigned  ) = (y >= 0) & (x == unsigned(y))
858,489,677✔
527
<( x::BitSigned,   y::BitUnsigned) = (x <  0) | (unsigned(x) <  y)
49,964,247✔
528
<( x::BitUnsigned, y::BitSigned  ) = (y >= 0) & (x <  unsigned(y))
228,917,887✔
529
<=(x::BitSigned,   y::BitUnsigned) = (x <  0) | (unsigned(x) <= y)
14,123,484✔
530
<=(x::BitUnsigned, y::BitSigned  ) = (y >= 0) & (x <= unsigned(y))
11,447,256✔
531

532
## integer shifts ##
533

534
# unsigned shift counts always shift in the same direction
535
>>(x::BitSigned,   y::BitUnsigned) = ashr_int(x, y)
522,885,891✔
536
>>(x::BitUnsigned, y::BitUnsigned) = lshr_int(x, y)
2,147,483,647✔
537
<<(x::BitInteger,  y::BitUnsigned) = shl_int(x, y)
2,147,483,647✔
538
>>>(x::BitInteger, y::BitUnsigned) = lshr_int(x, y)
465,345,763✔
539
# signed shift counts can shift in either direction
540
# note: this early during bootstrap, `>=` is not yet available
541
# note: we only define Int shift counts here; the generic case is handled later
542
>>(x::BitInteger, y::Int) =
2,147,483,647✔
543
    ifelse(0 <= y, x >> unsigned(y), x << unsigned(-y))
544
<<(x::BitInteger, y::Int) =
1,527,673,469✔
545
    ifelse(0 <= y, x << unsigned(y), x >> unsigned(-y))
546
>>>(x::BitInteger, y::Int) =
261,403,837✔
547
    ifelse(0 <= y, x >>> unsigned(y), x << unsigned(-y))
548

549
for to in BitInteger_types, from in (BitInteger_types..., Bool)
550
    if !(to === from)
551
        if Core.sizeof(to) < Core.sizeof(from)
552
            @eval rem(x::($from), ::Type{$to}) = trunc_int($to, x)
1,435,768,762✔
553
        elseif from === Bool
554
            @eval rem(x::($from), ::Type{$to}) = convert($to, x)
1,595,660,625✔
555
        elseif Core.sizeof(from) < Core.sizeof(to)
556
            if from <: Signed
557
                @eval rem(x::($from), ::Type{$to}) = sext_int($to, x)
260,979,831✔
558
            else
559
                @eval rem(x::($from), ::Type{$to}) = convert($to, x)
1,228,613,779✔
560
            end
561
        else
562
            @eval rem(x::($from), ::Type{$to}) = bitcast($to, x)
2,147,483,647✔
563
        end
564
    end
565
end
566

567
## integer bitwise rotations ##
568

569
"""
570
    bitrotate(x::Base.BitInteger, k::Integer)
571

572
`bitrotate(x, k)` implements bitwise rotation.
573
It returns the value of `x` with its bits rotated left `k` times.
574
A negative value of `k` will rotate to the right instead.
575

576
!!! compat "Julia 1.5"
577
    This function requires Julia 1.5 or later.
578

579
See also: [`<<`](@ref), [`circshift`](@ref), [`BitArray`](@ref).
580

581
```jldoctest
582
julia> bitrotate(UInt8(114), 2)
583
0xc9
584

585
julia> bitstring(bitrotate(0b01110010, 2))
586
"11001001"
587

588
julia> bitstring(bitrotate(0b01110010, -2))
589
"10011100"
590

591
julia> bitstring(bitrotate(0b01110010, 8))
592
"01110010"
593
```
594
"""
595
bitrotate(x::T, k::Integer) where {T <: BitInteger} =
840✔
596
    (x << ((sizeof(T) << 3 - 1) & k)) | (x >>> ((sizeof(T) << 3 - 1) & -k))
597

598
for fname in (:mod, :rem)
599
    @eval @doc """
600
        rem(x::Integer, T::Type{<:Integer})::T
601
        mod(x::Integer, T::Type{<:Integer})::T
602
        %(x::Integer, T::Type{<:Integer})::T
603

604
    Find `y::T` such that `x` ≡ `y` (mod n), where n is the number of integers representable
605
    in `T`, and `y` is an integer in `[typemin(T),typemax(T)]`.
606
    If `T` can represent any integer (e.g. `T == BigInt`), then this operation corresponds to
607
    a conversion to `T`.
608

609
    # Examples
610
    ```jldoctest
611
    julia> x = 129 % Int8
612
    -127
613

614
    julia> typeof(x)
615
    Int8
616

617
    julia> x = 129 % BigInt
618
    129
619

620
    julia> typeof(x)
621
    BigInt
622
    ```
623
    """ $fname(x::Integer, T::Type{<:Integer})
624
end
625

626
rem(x::T, ::Type{T}) where {T<:Integer} = x
2,147,483,647✔
627
rem(x::Signed, ::Type{Unsigned}) = x % unsigned(typeof(x))
2✔
628
rem(x::Unsigned, ::Type{Signed}) = x % signed(typeof(x))
×
629
rem(x::Integer, T::Type{<:Integer}) = convert(T, x)  # `x % T` falls back to `convert`
2✔
630
rem(x::Integer, ::Type{Bool}) = ((x & 1) != 0)
15,610,136✔
631
mod(x::Integer, ::Type{T}) where {T<:Integer} = rem(x, T)
×
632

633
unsafe_trunc(::Type{T}, x::Integer) where {T<:Integer} = rem(x, T)
362,829✔
634

635
## integer construction ##
636

637
"""
638
    @int128_str str
639

640
Parse `str` as an [`Int128`](@ref).
641
Throw an `ArgumentError` if the string is not a valid integer.
642

643
# Examples
644
```jldoctest
645
julia> int128"123456789123"
646
123456789123
647

648
julia> int128"123456789123.4"
649
ERROR: LoadError: ArgumentError: invalid base 10 digit '.' in "123456789123.4"
650
[...]
651
```
652
"""
653
macro int128_str(s::String)
54✔
654
    return parse(Int128, s)
54✔
655
end
656

657
"""
658
    @uint128_str str
659

660
Parse `str` as an [`UInt128`](@ref).
661
Throw an `ArgumentError` if the string is not a valid integer.
662

663
# Examples
664
```
665
julia> uint128"123456789123"
666
0x00000000000000000000001cbe991a83
667

668
julia> uint128"-123456789123"
669
ERROR: LoadError: ArgumentError: invalid base 10 digit '-' in "-123456789123"
670
[...]
671
```
672
"""
673
macro uint128_str(s::String)
80✔
674
    return parse(UInt128, s)
80✔
675
end
676

677
"""
678
    @big_str str
679

680
Parse a string into a [`BigInt`](@ref) or [`BigFloat`](@ref),
681
and throw an `ArgumentError` if the string is not a valid number.
682
For integers `_` is allowed in the string as a separator.
683

684
# Examples
685
```jldoctest
686
julia> big"123_456"
687
123456
688

689
julia> big"7891.5"
690
7891.5
691

692
julia> big"_"
693
ERROR: ArgumentError: invalid number format _ for BigInt or BigFloat
694
[...]
695
```
696

697
!!! warning
698
    Using `@big_str` for constructing [`BigFloat`](@ref) values may not result
699
    in the behavior that might be naively expected: as a macro, `@big_str`
700
    obeys the global precision ([`setprecision`](@ref)) and rounding mode
701
    ([`setrounding`](@ref)) settings as they are at *load time*. Thus, a
702
    function like `() -> precision(big"0.3")` returns a constant whose value
703
    depends on the value of the precision at the point when the function is
704
    defined, **not** at the precision at the time when the function is called.
705
"""
706
macro big_str(s::String)
239✔
707
    message = "invalid number format $s for BigInt or BigFloat"
239✔
708
    throw_error =  :(throw(ArgumentError($message)))
239✔
709
    if '_' in s
239✔
710
        # remove _ in s[2:end-1].
711
        # Do not allow '_' right before or after dot.
712
        bf = IOBuffer(sizehint=ncodeunits(s))
2✔
713
        c = s[1]
2✔
714
        print(bf, c)
2✔
715
        is_prev_underscore = (c == '_')
2✔
716
        is_prev_dot = (c == '.')
2✔
717
        for c in SubString(s, nextind(s, 1), prevind(s, lastindex(s)))
2✔
718
            c != '_' && print(bf, c)
107✔
719
            c == '_' && is_prev_dot && return throw_error
107✔
720
            c == '.' && is_prev_underscore && return throw_error
107✔
721
            is_prev_underscore = (c == '_')
107✔
722
            is_prev_dot = (c == '.')
107✔
723
        end
107✔
724
        print(bf, s[end])
2✔
725
        s = unsafe_takestring!(bf)
2✔
726
    end
727
    n = tryparse(BigInt, s)
239✔
728
    n === nothing || return n
397✔
729
    n = tryparse(BigFloat, s)
81✔
730
    n === nothing || return n
162✔
731
    return throw_error
×
732
end
733

734
## integer promotions ##
735

736
# with different sizes, promote to larger type
737
promote_rule(::Type{Int16}, ::Union{Type{Int8}, Type{UInt8}}) = Int16
×
738
promote_rule(::Type{Int32}, ::Union{Type{Int16}, Type{Int8}, Type{UInt16}, Type{UInt8}}) = Int32
431✔
739
promote_rule(::Type{Int64}, ::Union{Type{Int16}, Type{Int32}, Type{Int8}, Type{UInt16}, Type{UInt32}, Type{UInt8}}) = Int64
1,731,791,686✔
740
promote_rule(::Type{Int128}, ::Union{Type{Int16}, Type{Int32}, Type{Int64}, Type{Int8}, Type{UInt16}, Type{UInt32}, Type{UInt64}, Type{UInt8}}) = Int128
4,501,254✔
741
promote_rule(::Type{UInt16}, ::Union{Type{Int8}, Type{UInt8}}) = UInt16
52,272✔
742
promote_rule(::Type{UInt32}, ::Union{Type{Int16}, Type{Int8}, Type{UInt16}, Type{UInt8}}) = UInt32
478,885,710✔
743
promote_rule(::Type{UInt64}, ::Union{Type{Int16}, Type{Int32}, Type{Int8}, Type{UInt16}, Type{UInt32}, Type{UInt8}}) = UInt64
1,639,164,760✔
744
promote_rule(::Type{UInt128}, ::Union{Type{Int16}, Type{Int32}, Type{Int64}, Type{Int8}, Type{UInt16}, Type{UInt32}, Type{UInt64}, Type{UInt8}}) = UInt128
13,327,407✔
745
# with mixed signedness and same size, Unsigned wins
746
promote_rule(::Type{UInt8},   ::Type{Int8}  ) = UInt8
×
747
promote_rule(::Type{UInt16},  ::Type{Int16} ) = UInt16
×
748
promote_rule(::Type{UInt32},  ::Type{Int32} ) = UInt32
4,027,480✔
749
promote_rule(::Type{UInt64},  ::Type{Int64} ) = UInt64
384,406,307✔
750
promote_rule(::Type{UInt128}, ::Type{Int128}) = UInt128
×
751

752
## traits ##
753

754
"""
755
    typemin(T)
756

757
The lowest value representable by the given (real) numeric DataType `T`.
758

759
See also: [`floatmin`](@ref), [`maxintfloat`](@ref), [`typemax`](@ref), [`eps`](@ref).
760

761
# Examples
762
```jldoctest
763
julia> typemin(Int8)
764
-128
765

766
julia> typemin(UInt32)
767
0x00000000
768

769
julia> typemin(Float16)
770
-Inf16
771

772
julia> typemin(Float32)
773
-Inf32
774

775
julia> floatmin(Float32)  # smallest positive finite Float32 floating point number
776
1.1754944f-38
777

778
julia> nextfloat(-Inf32) == -floatmax(Float32)  # equivalent ways of getting the lowest finite Float32 floating point number
779
true
780
```
781
"""
782
function typemin end
783

784
"""
785
    typemax(T)
786

787
The highest value representable by the given (real) numeric `DataType`.
788

789
See also: [`floatmax`](@ref), [`maxintfloat`](@ref), [`typemin`](@ref), [`eps`](@ref).
790

791
# Examples
792
```jldoctest
793
julia> typemax(Int8)
794
127
795

796
julia> typemax(UInt32)
797
0xffffffff
798

799
julia> typemax(Float64)
800
Inf
801

802
julia> typemax(Float32)
803
Inf32
804

805
julia> floatmax(Float32)  # largest positive finite Float32 floating point number
806
3.4028235f38
807
```
808
"""
809
function typemax end
810

811
typemin(::Type{Int8  }) = Int8(-128)
×
812
typemax(::Type{Int8  }) = Int8(127)
×
813
typemin(::Type{UInt8 }) = UInt8(0)
×
814
typemax(::Type{UInt8 }) = UInt8(255)
×
815
typemin(::Type{Int16 }) = Int16(-32768)
×
816
typemax(::Type{Int16 }) = Int16(32767)
×
817
typemin(::Type{UInt16}) = UInt16(0)
×
818
typemax(::Type{UInt16}) = UInt16(65535)
59,213,620✔
819
typemin(::Type{Int32 }) = Int32(-2147483648)
9,689✔
820
typemax(::Type{Int32 }) = Int32(2147483647)
139,088✔
821
typemin(::Type{UInt32}) = UInt32(0)
×
822
typemax(::Type{UInt32}) = UInt32(4294967295)
1,311✔
823
typemin(::Type{Int64 }) = -9223372036854775808
×
824
typemax(::Type{Int64 }) = 9223372036854775807
×
825
typemin(::Type{UInt64}) = UInt64(0)
611,805✔
826
typemax(::Type{UInt64}) = 0xffffffffffffffff
×
827
@eval typemin(::Type{UInt128}) = $(convert(UInt128, 0))
×
828
@eval typemax(::Type{UInt128}) = $(bitcast(UInt128, convert(Int128, -1)))
×
829
@eval typemin(::Type{Int128} ) = $(convert(Int128, 1) << 127)
×
830
@eval typemax(::Type{Int128} ) = $(bitcast(Int128, typemax(UInt128) >> 1))
×
831

832

833
widen(::Type{Int8}) = Int16
×
834
widen(::Type{Int16}) = Int32
×
835
widen(::Type{Int32}) = Int64
×
836
widen(::Type{Int64}) = Int128
417✔
837
widen(::Type{UInt8}) = UInt16
×
838
widen(::Type{UInt16}) = UInt32
×
839
widen(::Type{UInt32}) = UInt64
9✔
840
widen(::Type{UInt64}) = UInt128
26,008,817✔
841

842
# a few special cases,
843
# Int64*UInt64 => Int128
844
# |x|<=2^(k-1), |y|<=2^k-1   =>   |x*y|<=2^(2k-1)-1
845
widemul(x::Signed,y::Unsigned) = widen(x) * signed(widen(y))
440✔
846
widemul(x::Unsigned,y::Signed) = signed(widen(x)) * widen(y)
460✔
847
# multiplication by Bool doesn't require widening
848
widemul(x::Bool,y::Bool) = x * y
×
849
widemul(x::Bool,y::Number) = x * y
×
850
widemul(x::Number,y::Bool) = x * y
×
851

852

853
## wide multiplication, Int128 multiply and divide ##
854

855
if Core.sizeof(Int) == 4
856
    function widemul(u::Int64, v::Int64)
×
857
        local u0::UInt64, v0::UInt64, w0::UInt64
×
858
        local u1::Int64, v1::Int64, w1::UInt64, w2::Int64, t::UInt64
×
859

860
        u0 = u & 0xffffffff; u1 = u >> 32
×
861
        v0 = v & 0xffffffff; v1 = v >> 32
×
862
        w0 = u0 * v0
×
863
        t = reinterpret(UInt64, u1) * v0 + (w0 >>> 32)
×
864
        w2 = reinterpret(Int64, t) >> 32
×
865
        w1 = u0 * reinterpret(UInt64, v1) + (t & 0xffffffff)
×
866
        hi = u1 * v1 + w2 + (reinterpret(Int64, w1) >> 32)
×
867
        lo = w0 & 0xffffffff + (w1 << 32)
×
868
        return Int128(hi) << 64 + Int128(lo)
×
869
    end
870

871
    function widemul(u::UInt64, v::UInt64)
×
872
        local u0::UInt64, v0::UInt64, w0::UInt64
×
873
        local u1::UInt64, v1::UInt64, w1::UInt64, w2::UInt64, t::UInt64
×
874

875
        u0 = u & 0xffffffff; u1 = u >>> 32
×
876
        v0 = v & 0xffffffff; v1 = v >>> 32
×
877
        w0 = u0 * v0
×
878
        t = u1 * v0 + (w0 >>> 32)
×
879
        w2 = t >>> 32
×
880
        w1 = u0 * v1 + (t & 0xffffffff)
×
881
        hi = u1 * v1 + w2 + (w1 >>> 32)
×
882
        lo = w0 & 0xffffffff + (w1 << 32)
×
883
        return UInt128(hi) << 64 + UInt128(lo)
×
884
    end
885

886
    function *(u::Int128, v::Int128)
×
887
        u0 = u % UInt64; u1 = Int64(u >> 64)
×
888
        v0 = v % UInt64; v1 = Int64(v >> 64)
×
889
        lolo = widemul(u0, v0)
×
890
        lohi = widemul(reinterpret(Int64, u0), v1)
×
891
        hilo = widemul(u1, reinterpret(Int64, v0))
×
892
        t = reinterpret(UInt128, hilo) + (lolo >>> 64)
×
893
        w1 = reinterpret(UInt128, lohi) + (t & 0xffffffffffffffff)
×
894
        return Int128(lolo & 0xffffffffffffffff) + reinterpret(Int128, w1) << 64
×
895
    end
896

897
    function *(u::UInt128, v::UInt128)
×
898
        u0 = u % UInt64; u1 = UInt64(u>>>64)
×
899
        v0 = v % UInt64; v1 = UInt64(v>>>64)
×
900
        lolo = widemul(u0, v0)
×
901
        lohi = widemul(u0, v1)
×
902
        hilo = widemul(u1, v0)
×
903
        t = hilo + (lolo >>> 64)
×
904
        w1 = lohi + (t & 0xffffffffffffffff)
×
905
        return (lolo & 0xffffffffffffffff) + UInt128(w1) << 64
×
906
    end
907

908
    function _setbit(x::UInt128, i)
×
909
        # faster version of `return x | (UInt128(1) << i)`
910
        j = i >> 5
×
911
        y = UInt128(one(UInt32) << (i & 0x1f))
×
912
        if j == 0
×
913
            return x | y
×
914
        elseif j == 1
×
915
            return x | (y << 32)
×
916
        elseif j == 2
×
917
            return x | (y << 64)
×
918
        elseif j == 3
×
919
            return x | (y << 96)
×
920
        end
921
        return x
×
922
    end
923

924
    function divrem(x::UInt128, y::UInt128)
×
925
        iszero(y) && throw(DivideError())
×
926
        if (x >> 64) % UInt64 == 0
×
927
            if (y >> 64) % UInt64 == 0
×
928
                # fast path: upper 64 bits are zero, so we can fallback to UInt64 division
929
                q64, x64 = divrem(x % UInt64, y % UInt64)
×
930
                return UInt128(q64), UInt128(x64)
×
931
            else
932
                # this implies y>x, so
933
                return zero(UInt128), x
×
934
            end
935
        end
936
        n = leading_zeros(y) - leading_zeros(x)
×
937
        q = zero(UInt128)
×
938
        ys = y << n
×
939
        while n >= 0
×
940
            # ys == y * 2^n
941
            if ys <= x
×
942
                x -= ys
×
943
                q = _setbit(q, n)
×
944
                if (x >> 64) % UInt64 == 0
×
945
                    # exit early, similar to above fast path
946
                    if (y >> 64) % UInt64 == 0
×
947
                        q64, x64 = divrem(x % UInt64, y % UInt64)
×
948
                        q |= q64
×
949
                        x = UInt128(x64)
×
950
                    end
951
                    return q, x
×
952
                end
953
            end
954
            ys >>>= 1
×
955
            n -= 1
×
956
        end
×
957
        return q, x
×
958
    end
959

960
    function div(x::Int128, y::Int128)
×
961
        (x == typemin(Int128)) & (y == -1) && throw(DivideError())
×
962
        return Int128(div(BigInt(x), BigInt(y)))::Int128
×
963
    end
964
    div(x::UInt128, y::UInt128) = divrem(x, y)[1]
×
965

966
    function rem(x::Int128, y::Int128)
×
967
        return Int128(rem(BigInt(x), BigInt(y)))::Int128
×
968
    end
969

970
    function rem(x::UInt128, y::UInt128)
×
971
        iszero(y) && throw(DivideError())
×
972
        if (x >> 64) % UInt64 == 0
×
973
            if (y >> 64) % UInt64 == 0
×
974
                # fast path: upper 64 bits are zero, so we can fallback to UInt64 division
975
                return UInt128(rem(x % UInt64, y % UInt64))
×
976
            else
977
                # this implies y>x, so
978
                return x
×
979
            end
980
        end
981
        n = leading_zeros(y) - leading_zeros(x)
×
982
        ys = y << n
×
983
        while n >= 0
×
984
            # ys == y * 2^n
985
            if ys <= x
×
986
                x -= ys
×
987
                if (x >> 64) % UInt64 == 0
×
988
                    # exit early, similar to above fast path
989
                    if (y >> 64) % UInt64 == 0
×
990
                        x = UInt128(rem(x % UInt64, y % UInt64))
×
991
                    end
992
                    return x
×
993
                end
994
            end
995
            ys >>>= 1
×
996
            n -= 1
×
997
        end
×
998
        return x
×
999
    end
1000

1001
    function mod(x::Int128, y::Int128)
×
1002
        return Int128(mod(BigInt(x), BigInt(y)))::Int128
×
1003
    end
1004
else
1005
    *(x::T, y::T) where {T<:Union{Int128,UInt128}}  = mul_int(x, y)
39,658,417✔
1006

1007
    div(x::Int128,  y::Int128)  = checked_sdiv_int(x, y)
1,025,436✔
1008
    div(x::UInt128, y::UInt128) = checked_udiv_int(x, y)
150,951✔
1009

1010
    rem(x::Int128,  y::Int128)  = checked_srem_int(x, y)
2,917✔
1011
    rem(x::UInt128, y::UInt128) = checked_urem_int(x, y)
3,990✔
1012
end
1013

1014
# issue #15489: since integer ops are unchecked, they shouldn't check promotion
1015
for op in (:+, :-, :*, :&, :|, :xor)
1016
    @eval function $op(a::Integer, b::Integer)
105,529✔
1017
        T = promote_typeof(a, b)
1,258,645,080✔
1018
        aT, bT = a % T, b % T
2,147,483,647✔
1019
        not_sametype((a, b), (aT, bT))
1,256,022,531✔
1020
        return $op(aT, bT)
2,147,483,647✔
1021
    end
1022
end
1023

1024
const _mask1_uint128 = (UInt128(0x5555555555555555) << 64) | UInt128(0x5555555555555555)
1025
const _mask2_uint128 = (UInt128(0x3333333333333333) << 64) | UInt128(0x3333333333333333)
1026
const _mask4_uint128 = (UInt128(0x0f0f0f0f0f0f0f0f) << 64) | UInt128(0x0f0f0f0f0f0f0f0f)
1027

1028
"""
1029
    bitreverse(x)
1030

1031
Reverse the order of bits in integer `x`. `x` must have a fixed bit width,
1032
e.g. be an `Int16` or `Int32`.
1033

1034
!!! compat "Julia 1.5"
1035
    This function requires Julia 1.5 or later.
1036

1037
# Examples
1038
```jldoctest
1039
julia> bitreverse(0x8080808080808080)
1040
0x0101010101010101
1041

1042
julia> reverse(bitstring(0xa06e)) == bitstring(bitreverse(0xa06e))
1043
true
1044
```
1045
"""
1046
function bitreverse(x::BitInteger)
×
1047
    # TODO: consider using llvm.bitreverse intrinsic
1048
    z = unsigned(x)
×
1049
    mask1 = _mask1_uint128 % typeof(z)
×
1050
    mask2 = _mask2_uint128 % typeof(z)
×
1051
    mask4 = _mask4_uint128 % typeof(z)
×
1052
    z = ((z & mask1) << 1) | ((z >> 1) & mask1)
×
1053
    z = ((z & mask2) << 2) | ((z >> 2) & mask2)
×
1054
    z = ((z & mask4) << 4) | ((z >> 4) & mask4)
×
1055
    return bswap(z) % typeof(x)
×
1056
end
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc