Skip to content

Commit

Permalink
Make startswith work with IO objects (#43055)
Browse files Browse the repository at this point in the history
Co-authored-by: Steven G. Johnson <[email protected]>
  • Loading branch information
ArunS-tack and stevengj authored Feb 14, 2023
1 parent 6b85327 commit 1c5b80f
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 1 deletion.
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ New library features
Standard library changes
------------------------

* `startswith` now supports seekable `IO` streams ([#43055])

#### Package Manager

Expand Down
2 changes: 1 addition & 1 deletion base/essentials.jl
Original file line number Diff line number Diff line change
Expand Up @@ -946,7 +946,7 @@ function popfirst! end
peek(stream[, T=UInt8])
Read and return a value of type `T` from a stream without advancing the current position
in the stream.
in the stream. See also [`startswith(stream, char_or_string)`](@ref).
# Examples
Expand Down
19 changes: 19 additions & 0 deletions base/strings/util.jl
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,25 @@ function startswith(a::Union{String, SubString{String}},
end
end

"""
startswith(io::IO, prefix::Union{AbstractString,Base.Chars})
Check if an `IO` object starts with a prefix. See also [`peek`](@ref).
"""
function Base.startswith(io::IO, prefix::Base.Chars)
mark(io)
c = read(io, Char)
reset(io)
return c in prefix
end
function Base.startswith(io::IO, prefix::Union{String,SubString{String}})
mark(io)
s = read(io, ncodeunits(prefix))
reset(io)
return s == codeunits(prefix)
end
Base.startswith(io::IO, prefix::AbstractString) = startswith(io, String(prefix))

function endswith(a::Union{String, SubString{String}},
b::Union{String, SubString{String}})
cub = ncodeunits(b)
Expand Down
6 changes: 6 additions & 0 deletions test/strings/basic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,12 @@ end
@test endswith(y)(y)
@test endswith(z, z)
@test endswith(z)(z)
#40616 startswith for IO objects
let s = "JuliaLang", io = IOBuffer(s)
for prefix in ("Julia", "July", s^2, "Ju", 'J', 'x', ('j','J'))
@test startswith(io, prefix) == startswith(s, prefix)
end
end
end

@testset "SubStrings and Views" begin
Expand Down

0 comments on commit 1c5b80f

Please sign in to comment.