Skip to content

Commit 6f10ca2

Browse files
add various @propagate_inbounds annotations
also: avoid second bounds check in `get` with default
1 parent 1f0c6fa commit 6f10ca2

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

base/strings/basic.jl

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ I.e. the value returned by `codeunit(s, i)` is of the type returned by
8181
8282
See also: [`ncodeunits`](@ref), [`checkbounds`](@ref)
8383
"""
84-
codeunit(s::AbstractString, i::Integer) = typeof(i) === Int ?
84+
@propagate_inbounds codeunit(s::AbstractString, i::Integer) = typeof(i) === Int ?
8585
throw(MethodError(codeunit, Tuple{typeof(s),Int})) : codeunit(s, Int(i))
8686

8787
"""
@@ -119,7 +119,7 @@ Stacktrace:
119119
[...]
120120
```
121121
"""
122-
isvalid(s::AbstractString, i::Integer) = typeof(i) === Int ?
122+
@propagate_inbounds isvalid(s::AbstractString, i::Integer) = typeof(i) === Int ?
123123
throw(MethodError(isvalid, Tuple{typeof(s),Int})) : isvalid(s, Int(i))
124124

125125
"""
@@ -134,7 +134,7 @@ a Unicode index error is raised.
134134
See also: [`getindex`](@ref), [`start`](@ref), [`done`](@ref),
135135
[`checkbounds`](@ref)
136136
"""
137-
next(s::AbstractString, i::Integer) = typeof(i) === Int ?
137+
@propagate_inbounds next(s::AbstractString, i::Integer) = typeof(i) === Int ?
138138
throw(MethodError(next, Tuple{typeof(s),Int})) : next(s, Int(i))
139139

140140
## basic generic definitions ##
@@ -148,13 +148,21 @@ endof(s::AbstractString) = thisind(s, ncodeunits(s))
148148
getindex(s::AbstractString, i::Integer) = next(s, i)[1]
149149
getindex(s::AbstractString, i::Colon) = s
150150
# TODO: handle other ranges with stride ±1 specially?
151+
# TODO: add more @propagate_inbounds annotations?
151152
getindex(s::AbstractString, r::UnitRange{<:Integer}) = SubString(s, r)
152153
getindex(s::AbstractString, v::AbstractVector{<:Integer}) =
153154
sprint(length(v), io->(for i in v; write(io, s[i]) end))
154155
getindex(s::AbstractString, v::AbstractVector{Bool}) =
155156
throw(ArgumentError("logical indexing not supported for strings"))
156157

157-
get(s::AbstractString, i::Integer, default) = checkbounds(Bool, s, i) ? s[i] : default
158+
function get(s::AbstractString, i::Integer, default)
159+
# TODO: use ternary once @inbounds is expression-like
160+
if checkbounds(Bool, s, i)
161+
@inbounds return s[i]
162+
else
163+
return default
164+
end
165+
end
158166

159167
## bounds checking ##
160168

0 commit comments

Comments
 (0)