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

JuliaLang / julia / #37483

pending completion
#37483

push

local

web-flow
Type-assert the value type in getindex(::AbstractDict, key) (#49115)

Closes https://github.com/JuliaCollections/OrderedCollections.jl/issues/101

2 of 2 new or added lines in 1 file covered. (100.0%)

72523 of 82770 relevant lines covered (87.62%)

34287845.75 hits per line

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

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

3
"""
4
    StringIndexError(str, i)
5

6
An error occurred when trying to access `str` at index `i` that is not valid.
7
"""
8
struct StringIndexError <: Exception
9
    string::AbstractString
571✔
10
    index::Integer
11
end
12
@noinline string_index_err(s::AbstractString, i::Integer) =
567✔
13
    throw(StringIndexError(s, Int(i)))
14
function Base.showerror(io::IO, exc::StringIndexError)
4✔
15
    s = exc.string
4✔
16
    print(io, "StringIndexError: ", "invalid index [$(exc.index)]")
4✔
17
    if firstindex(s) <= exc.index <= ncodeunits(s)
4✔
18
        iprev = thisind(s, exc.index)
4✔
19
        inext = nextind(s, iprev)
4✔
20
        escprev = escape_string(s[iprev:iprev])
4✔
21
        if inext <= ncodeunits(s)
4✔
22
            escnext = escape_string(s[inext:inext])
3✔
23
            print(io, ", valid nearby indices [$iprev]=>'$escprev', [$inext]=>'$escnext'")
3✔
24
        else
25
            print(io, ", valid nearby index [$iprev]=>'$escprev'")
1✔
26
        end
27
    end
28
end
29

30
const ByteArray = Union{CodeUnits{UInt8,String}, Vector{UInt8},Vector{Int8}, FastContiguousSubArray{UInt8,1,CodeUnits{UInt8,String}}, FastContiguousSubArray{UInt8,1,Vector{UInt8}}, FastContiguousSubArray{Int8,1,Vector{Int8}}}
31

32
@inline between(b::T, lo::T, hi::T) where {T<:Integer} = (lo ≤ b) & (b ≤ hi)
149,195,609✔
33

34
"""
35
    String <: AbstractString
36

37
The default string type in Julia, used by e.g. string literals.
38

39
`String`s are immutable sequences of `Char`s. A `String` is stored internally as
40
a contiguous byte array, and while they are interpreted as being UTF-8 encoded,
41
they can be composed of any byte sequence. Use [`isvalid`](@ref) to validate
42
that the underlying byte sequence is valid as UTF-8.
43
"""
44
String
45

46
## constructors and conversions ##
47

48
# String constructor docstring from boot.jl, workaround for #16730
49
# and the unavailability of @doc in boot.jl context.
50
"""
51
    String(v::AbstractVector{UInt8})
52

53
Create a new `String` object using the data buffer from byte vector `v`.
54
If `v` is a `Vector{UInt8}` it will be truncated to zero length and future
55
modification of `v` cannot affect the contents of the resulting string.
56
To avoid truncation of `Vector{UInt8}` data, use `String(copy(v))`; for other
57
`AbstractVector` types, `String(v)` already makes a copy.
58

59
When possible, the memory of `v` will be used without copying when the `String`
60
object is created. This is guaranteed to be the case for byte vectors returned
61
by [`take!`](@ref) on a writable [`IOBuffer`](@ref) and by calls to
62
[`read(io, nb)`](@ref). This allows zero-copy conversion of I/O data to strings.
63
In other cases, `Vector{UInt8}` data may be copied, but `v` is truncated anyway
64
to guarantee consistent behavior.
65
"""
66
String(v::AbstractVector{UInt8}) = String(copyto!(StringVector(length(v)), v))
2,475,240✔
67
String(v::Vector{UInt8}) = ccall(:jl_array_to_string, Ref{String}, (Any,), v)
5,601,414✔
68

69
"""
70
    unsafe_string(p::Ptr{UInt8}, [length::Integer])
71

72
Copy a string from the address of a C-style (NUL-terminated) string encoded as UTF-8.
73
(The pointer can be safely freed afterwards.) If `length` is specified
74
(the length of the data in bytes), the string does not have to be NUL-terminated.
75

76
This function is labeled "unsafe" because it will crash if `p` is not
77
a valid memory address to data of the requested length.
78
"""
79
function unsafe_string(p::Union{Ptr{UInt8},Ptr{Int8}}, len::Integer)
1,192✔
80
    p == C_NULL && throw(ArgumentError("cannot convert NULL to string"))
424,908✔
81
    ccall(:jl_pchar_to_string, Ref{String}, (Ptr{UInt8}, Int), p, len)
424,907✔
82
end
83
function unsafe_string(p::Union{Ptr{UInt8},Ptr{Int8}})
10,515✔
84
    p == C_NULL && throw(ArgumentError("cannot convert NULL to string"))
2,969,297✔
85
    ccall(:jl_cstr_to_string, Ref{String}, (Ptr{UInt8},), p)
2,969,296✔
86
end
87

88
# This is @assume_effects :effect_free :nothrow :terminates_globally @ccall jl_alloc_string(n::Csize_t)::Ref{String},
89
# but the macro is not available at this time in bootstrap, so we write it manually.
90
@eval _string_n(n::Integer) = $(Expr(:foreigncall, QuoteNode(:jl_alloc_string), Ref{String}, Expr(:call, Expr(:core, :svec), :Csize_t), 1, QuoteNode((:ccall,0xe)), :(convert(Csize_t, n))))
108,234,845✔
91

92
"""
93
    String(s::AbstractString)
94

95
Create a new `String` from an existing `AbstractString`.
96
"""
97
String(s::AbstractString) = print_to_string(s)
397✔
98
@assume_effects :total String(s::Symbol) = unsafe_string(unsafe_convert(Ptr{UInt8}, s))
561,989✔
99

100
unsafe_wrap(::Type{Vector{UInt8}}, s::String) = ccall(:jl_string_to_array, Ref{Vector{UInt8}}, (Any,), s)
5,989,834✔
101

102
Vector{UInt8}(s::CodeUnits{UInt8,String}) = copyto!(Vector{UInt8}(undef, length(s)), s)
1,123✔
103
Vector{UInt8}(s::String) = Vector{UInt8}(codeunits(s))
1,046✔
104
Array{UInt8}(s::String)  = Vector{UInt8}(codeunits(s))
×
105

106
String(s::CodeUnits{UInt8,String}) = s.s
3✔
107

108
## low-level functions ##
109

110
pointer(s::String) = unsafe_convert(Ptr{UInt8}, s)
366,101,683✔
111
pointer(s::String, i::Integer) = pointer(s) + Int(i)::Int - 1
244,224,878✔
112

113
ncodeunits(s::String) = Core.sizeof(s)
305,070,055✔
114
codeunit(s::String) = UInt8
×
115

116
@assume_effects :foldable @inline function codeunit(s::String, i::Integer)
675,384✔
117
    @boundscheck checkbounds(s, i)
225,870,619✔
118
    b = GC.@preserve s unsafe_load(pointer(s, i))
225,870,619✔
119
    return b
225,870,619✔
120
end
121

122
## comparison ##
123

124
@assume_effects :total _memcmp(a::String, b::String) = @invoke _memcmp(a::Union{Ptr{UInt8},AbstractString},b::Union{Ptr{UInt8},AbstractString})
101,298✔
125

126
_memcmp(a::Union{Ptr{UInt8},AbstractString}, b::Union{Ptr{UInt8},AbstractString}) = _memcmp(a, b, min(sizeof(a), sizeof(b)))
433,031✔
127
function _memcmp(a::Union{Ptr{UInt8},AbstractString}, b::Union{Ptr{UInt8},AbstractString}, len::Int)
297✔
128
    ccall(:memcmp, Cint, (Ptr{UInt8}, Ptr{UInt8}, Csize_t), a, b, len % Csize_t) % Int
932,611✔
129
end
130

131
function cmp(a::String, b::String)
1✔
132
    al, bl = sizeof(a), sizeof(b)
101,298✔
133
    c = _memcmp(a, b)
101,298✔
134
    return c < 0 ? -1 : c > 0 ? +1 : cmp(al,bl)
186,804✔
135
end
136

137
==(a::String, b::String) = a===b
9,897,482✔
138

139
typemin(::Type{String}) = ""
2✔
140
typemin(::String) = typemin(String)
1✔
141

142
## thisind, nextind ##
143

144
@propagate_inbounds thisind(s::String, i::Int) = _thisind_str(s, i)
177,354,574✔
145

146
# s should be String or SubString{String}
147
@inline function _thisind_str(s, i::Int)
×
148
    i == 0 && return 0
89,281,795✔
149
    n = ncodeunits(s)
89,256,336✔
150
    i == n + 1 && return i
89,256,336✔
151
    @boundscheck between(i, 1, n) || throw(BoundsError(s, i))
89,233,894✔
152
    @inbounds b = codeunit(s, i)
89,233,870✔
153
    (b & 0xc0 == 0x80) & (i-1 > 0) || return i
158,399,796✔
154
    @inbounds b = codeunit(s, i-1)
20,067,944✔
155
    between(b, 0b11000000, 0b11110111) && return i-1
20,067,944✔
156
    (b & 0xc0 == 0x80) & (i-2 > 0) || return i
15,660,153✔
157
    @inbounds b = codeunit(s, i-2)
7,170,965✔
158
    between(b, 0b11100000, 0b11110111) && return i-2
7,170,965✔
159
    (b & 0xc0 == 0x80) & (i-3 > 0) || return i
5,906,601✔
160
    @inbounds b = codeunit(s, i-3)
1,027,051✔
161
    between(b, 0b11110000, 0b11110111) && return i-3
1,027,051✔
162
    return i
241,004✔
163
end
164

165
@propagate_inbounds nextind(s::String, i::Int) = _nextind_str(s, i)
13,443,308✔
166

167
# s should be String or SubString{String}
168
@inline function _nextind_str(s, i::Int)
13,957,473✔
169
    i == 0 && return 1
13,957,473✔
170
    n = ncodeunits(s)
13,937,919✔
171
    @boundscheck between(i, 1, n) || throw(BoundsError(s, i))
13,937,931✔
172
    @inbounds l = codeunit(s, i)
13,937,907✔
173
    (l < 0x80) | (0xf8 ≤ l) && return i+1
13,937,907✔
174
    if l < 0xc0
132,027✔
175
        i′ = @inbounds thisind(s, i)
51,357✔
176
        return i′ < i ? @inbounds(nextind(s, i′)) : i+1
30,403✔
177
    end
178
    # first continuation byte
179
    (i += 1) > n && return i
101,624✔
180
    @inbounds b = codeunit(s, i)
101,014✔
181
    b & 0xc0 ≠ 0x80 && return i
101,014✔
182
    ((i += 1) > n) | (l < 0xe0) && return i
93,770✔
183
    # second continuation byte
184
    @inbounds b = codeunit(s, i)
76,293✔
185
    b & 0xc0 ≠ 0x80 && return i
76,293✔
186
    ((i += 1) > n) | (l < 0xf0) && return i
72,660✔
187
    # third continuation byte
188
    @inbounds b = codeunit(s, i)
20,796✔
189
    ifelse(b & 0xc0 ≠ 0x80, i, i+1)
20,796✔
190
end
191

192
## checking UTF-8 & ACSII validity ##
193

194
byte_string_classify(s::Union{String,Vector{UInt8},FastContiguousSubArray{UInt8,1,Vector{UInt8}}}) =
20,311✔
195
    ccall(:u8_isvalid, Int32, (Ptr{UInt8}, Int), s, sizeof(s))
196
    # 0: neither valid ASCII nor UTF-8
197
    # 1: valid ASCII
198
    # 2: valid UTF-8
199

200
isvalid(::Type{String}, s::Union{Vector{UInt8},FastContiguousSubArray{UInt8,1,Vector{UInt8}},String}) = byte_string_classify(s) ≠ 0
20,311✔
201
isvalid(s::String) = isvalid(String, s)
28✔
202

203
is_valid_continuation(c) = c & 0xc0 == 0x80
5✔
204

205
## required core functionality ##
206

207
@inline function iterate(s::String, i::Int=firstindex(s))
61,379✔
208
    (i % UInt) - 1 < ncodeunits(s) || return nothing
24,750,680✔
209
    b = @inbounds codeunit(s, i)
15,434,075✔
210
    u = UInt32(b) << 24
15,434,075✔
211
    between(b, 0x80, 0xf7) || return reinterpret(Char, u), i+1
29,948,930✔
212
    return iterate_continued(s, i, u)
919,220✔
213
end
214

215
function iterate_continued(s::String, i::Int, u::UInt32)
919,220✔
216
    u < 0xc0000000 && (i += 1; @goto ret)
919,294✔
217
    n = ncodeunits(s)
919,146✔
218
    # first continuation byte
219
    (i += 1) > n && @goto ret
919,146✔
220
    @inbounds b = codeunit(s, i)
919,138✔
221
    b & 0xc0 == 0x80 || @goto ret
919,138✔
222
    u |= UInt32(b) << 16
919,077✔
223
    # second continuation byte
224
    ((i += 1) > n) | (u < 0xe0000000) && @goto ret
919,077✔
225
    @inbounds b = codeunit(s, i)
854,205✔
226
    b & 0xc0 == 0x80 || @goto ret
854,207✔
227
    u |= UInt32(b) << 8
854,203✔
228
    # third continuation byte
229
    ((i += 1) > n) | (u < 0xf0000000) && @goto ret
854,203✔
230
    @inbounds b = codeunit(s, i)
273,687✔
231
    b & 0xc0 == 0x80 || @goto ret
273,688✔
232
    u |= UInt32(b); i += 1
547,372✔
233
@label ret
×
234
    return reinterpret(Char, u), i
919,220✔
235
end
236

237
@propagate_inbounds function getindex(s::String, i::Int)
156,002✔
238
    b = codeunit(s, i)
2,517,446✔
239
    u = UInt32(b) << 24
2,517,446✔
240
    between(b, 0x80, 0xf7) || return reinterpret(Char, u)
5,031,189✔
241
    return getindex_continued(s, i, u)
3,703✔
242
end
243

244
function getindex_continued(s::String, i::Int, u::UInt32)
3,703✔
245
    if u < 0xc0000000
3,703✔
246
        # called from `getindex` which checks bounds
247
        @inbounds isvalid(s, i) && @goto ret
4✔
248
        string_index_err(s, i)
1✔
249
    end
250
    n = ncodeunits(s)
3,699✔
251

252
    (i += 1) > n && @goto ret
3,699✔
253
    @inbounds b = codeunit(s, i) # cont byte 1
3,698✔
254
    b & 0xc0 == 0x80 || @goto ret
3,698✔
255
    u |= UInt32(b) << 16
3,697✔
256

257
    ((i += 1) > n) | (u < 0xe0000000) && @goto ret
3,697✔
258
    @inbounds b = codeunit(s, i) # cont byte 2
2,471✔
259
    b & 0xc0 == 0x80 || @goto ret
2,471✔
260
    u |= UInt32(b) << 8
2,471✔
261

262
    ((i += 1) > n) | (u < 0xf0000000) && @goto ret
2,471✔
263
    @inbounds b = codeunit(s, i) # cont byte 3
468✔
264
    b & 0xc0 == 0x80 || @goto ret
468✔
265
    u |= UInt32(b)
468✔
266
@label ret
×
267
    return reinterpret(Char, u)
3,702✔
268
end
269

270
getindex(s::String, r::AbstractUnitRange{<:Integer}) = s[Int(first(r)):Int(last(r))]
4✔
271

272
@inline function getindex(s::String, r::UnitRange{Int})
1,469,208✔
273
    isempty(r) && return ""
960,883✔
274
    i, j = first(r), last(r)
67,602✔
275
    @boundscheck begin
937,047✔
276
        checkbounds(s, r)
937,029✔
277
        @inbounds isvalid(s, i) || string_index_err(s, i)
937,017✔
278
        @inbounds isvalid(s, j) || string_index_err(s, j)
937,018✔
279
    end
280
    j = nextind(s, j) - 1
937,040✔
281
    n = j - i + 1
937,040✔
282
    ss = _string_n(n)
937,040✔
283
    GC.@preserve s ss unsafe_copyto!(pointer(ss), pointer(s, i), n)
937,040✔
284
    return ss
937,040✔
285
end
286

287
# nothrow because we know the start and end indices are valid
288
@assume_effects :nothrow length(s::String) = length_continued(s, 1, ncodeunits(s), ncodeunits(s))
766,822✔
289

290
# effects needed because @inbounds
291
@assume_effects :consistent :effect_free @inline function length(s::String, i::Int, j::Int)
68,251✔
292
    @boundscheck begin
227,627✔
293
        0 < i ≤ ncodeunits(s)+1 || throw(BoundsError(s, i))
227,627✔
294
        0 ≤ j < ncodeunits(s)+1 || throw(BoundsError(s, j))
227,631✔
295
    end
296
    j < i && return 0
227,623✔
297
    @inbounds i, k = thisind(s, i), i
349,148✔
298
    c = j - i + (i == k)
174,574✔
299
    @inbounds length_continued(s, i, j, c)
174,574✔
300
end
301

302
@assume_effects :terminates_locally @inline @propagate_inbounds function length_continued(s::String, i::Int, n::Int, c::Int)
896,965✔
303
    i < n || return c
1,164,356✔
304
    b = codeunit(s, i)
718,436✔
305
    while true
4,142,055✔
306
        while true
45,653,389✔
307
            (i += 1) ≤ n || return c
46,371,054✔
308
            0xc0 ≤ b ≤ 0xf7 && break
44,935,724✔
309
            b = codeunit(s, i)
41,511,334✔
310
        end
41,511,334✔
311
        l = b
3,424,390✔
312
        b = codeunit(s, i) # cont byte 1
3,424,390✔
313
        c -= (x = b & 0xc0 == 0x80)
3,424,390✔
314
        x & (l ≥ 0xe0) || continue
3,424,390✔
315

316
        (i += 1) ≤ n || return c
3,025,146✔
317
        b = codeunit(s, i) # cont byte 2
3,023,684✔
318
        c -= (x = b & 0xc0 == 0x80)
3,023,684✔
319
        x & (l ≥ 0xf0) || continue
5,150,363✔
320

321
        (i += 1) ≤ n || return c
897,045✔
322
        b = codeunit(s, i) # cont byte 3
896,965✔
323
        c -= (b & 0xc0 == 0x80)
896,965✔
324
    end
3,423,619✔
325
end
326

327
## overload methods for efficiency ##
328

329
isvalid(s::String, i::Int) = checkbounds(Bool, s, i) && thisind(s, i) == i
81,714,510✔
330

331
isascii(s::String) = isascii(codeunits(s))
25,782✔
332

333
# don't assume effects for general integers since we cannot know their implementation
334
@assume_effects :foldable function repeat(c::Char, r::BitInteger)
7,977✔
335
    @invoke repeat(c, r::Integer)
14,369✔
336
end
337
"""
338
    repeat(c::AbstractChar, r::Integer) -> String
339

340
Repeat a character `r` times. This can equivalently be accomplished by calling
341
[`c^r`](@ref :^(::Union{AbstractString, AbstractChar}, ::Integer)).
342

343
# Examples
344
```jldoctest
345
julia> repeat('A', 3)
346
"AAA"
347
```
348
"""
349
function repeat(c::AbstractChar, r::Integer)
14,370✔
350
    c = Char(c)
14,370✔
351
    r == 0 && return ""
14,370✔
352
    r < 0 && throw(ArgumentError("can't repeat a character $r times"))
10,123✔
353
    u = bswap(reinterpret(UInt32, c))
10,119✔
354
    n = 4 - (leading_zeros(u | 0xff) >> 3)
10,119✔
355
    s = _string_n(n*r)
10,119✔
356
    p = pointer(s)
10,117✔
357
    GC.@preserve s if n == 1
10,117✔
358
        ccall(:memset, Ptr{Cvoid}, (Ptr{UInt8}, Cint, Csize_t), p, u % UInt8, r)
10,091✔
359
    elseif n == 2
26✔
360
        p16 = reinterpret(Ptr{UInt16}, p)
6✔
361
        for i = 1:r
12✔
362
            unsafe_store!(p16, u % UInt16, i)
20✔
363
        end
20✔
364
    elseif n == 3
20✔
365
        b1 = (u >> 0) % UInt8
16✔
366
        b2 = (u >> 8) % UInt8
16✔
367
        b3 = (u >> 16) % UInt8
16✔
368
        for i = 0:r-1
32✔
369
            unsafe_store!(p, b1, 3i + 1)
45✔
370
            unsafe_store!(p, b2, 3i + 2)
45✔
371
            unsafe_store!(p, b3, 3i + 3)
45✔
372
        end
45✔
373
    elseif n == 4
4✔
374
        p32 = reinterpret(Ptr{UInt32}, p)
4✔
375
        for i = 1:r
8✔
376
            unsafe_store!(p32, u, i)
8✔
377
        end
10,125✔
378
    end
379
    return s
10,117✔
380
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

© 2025 Coveralls, Inc