Skip to content

Commit

Permalink
Improve readall() convenience function, add readstring()
Browse files Browse the repository at this point in the history
  • Loading branch information
nalimilan committed Feb 6, 2016
1 parent 9725e8d commit 475824b
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
21 changes: 19 additions & 2 deletions src/StringEncodings.jl
Original file line number Diff line number Diff line change
Expand Up @@ -285,8 +285,24 @@ function read(s::StringDecoder, ::Type{UInt8})
eof(s) ? throw(EOFError()) : s.outbuf[s.skip+=1]
end

function readall(filename::AbstractString, encoding::ASCIIString)
open(s -> readall(StringDecoder(s, encoding)), filename)

## 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


Expand Down Expand Up @@ -330,6 +346,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 475824b

Please sign in to comment.