Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make startswith work with IO objects #43055

Merged
merged 9 commits into from
Feb 14, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions base/strings/util.jl
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,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.
stevengj marked this conversation as resolved.
Show resolved Hide resolved
"""
function Base.startswith(io::IO, prefix::Base.Chars)
mark(io)
Copy link
Member

@stevengj stevengj Feb 13, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems worth it to optimize the common case of an ASCII char, especially since a stream may conceivably support peek but not mark/reset.

Suggested change
mark(io)
prefix isa AbstractChar && prefix '\x7f' && return peek(io) == prefix % UInt8
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
3 changes: 3 additions & 0 deletions test/strings/basic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,9 @@ end
@test endswith(y)(y)
@test endswith(z, z)
@test endswith(z)(z)
#40616 startswith for IO objects
io = IOBuffer("JuliaLang")
@test startswith(io, "Julia")
ArunS-tack marked this conversation as resolved.
Show resolved Hide resolved
end

@testset "SubStrings and Views" begin
Expand Down