Skip to content

Commit

Permalink
Add readstring() convenience functions
Browse files Browse the repository at this point in the history
  • Loading branch information
nalimilan committed Feb 6, 2016
1 parent 9725e8d commit c335745
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/StringEncodings.jl
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,26 @@ function readall(filename::AbstractString, encoding::ASCIIString)
end


## Convenience I/O functions
if isdefined(Base, :readstring)
"""
readstring(stream or filename, enc::ASCIIString)
Read the entire contents of an I/O stream or a file in encoding `enc` as a string.
"""
Base.readstring(s::IO, enc::ASCIIString) = readstring(StringDecoder(s, enc))
Base.readstring(filename::AbstractString, enc::ASCIIString) = open(io->readstring(io, enc), filename)
else # Compatibility with Julia 0.4
"""
readall(stream or filename, enc::ASCIIString)
Read the entire contents of an I/O stream or a file in encoding `enc` as a string.
"""
Base.readall(s::IO, enc::ASCIIString) = readall(StringDecoder(s, enc))
Base.readall(filename::AbstractString, enc::ASCIIString) = open(io->readall(io, enc), filename)
end


## Functions to encode/decode strings

encoding_string(::Type{ASCIIString}) = "ASCII"
Expand Down Expand Up @@ -330,6 +350,7 @@ function encode(s::AbstractString, enc::ASCIIString)
takebuf_array(b)
end


## Function to list supported encodings
include("encodings.jl")

Expand Down
13 changes: 13 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,19 @@ catch err
"Conversion from nonexistent_encoding to UTF-8 not supported by iconv implementation, check that specified encodings are correct"
end

if !isdefined(Base, :readstring)
readstring = readall
end

mktemp() do path, io
s = "a string \0チャネルパ\0\0トナーの選択 with embedded and trailing nuls\0"
write(io, encode(s, "ISO-2022-JP"))
close(io)

@test readstring(path, "ISO-2022-JP") == s
@test open(io->readstring(io, "ISO-2022-JP"), path) == s
end

encodings_list = encodings()
@test "ASCII" in encodings_list
@test "UTF-8" in encodings_list
Expand Down

0 comments on commit c335745

Please sign in to comment.