Skip to content

Commit 475824b

Browse files
committedFeb 6, 2016
Improve readall() convenience function, add readstring()
1 parent 9725e8d commit 475824b

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed
 

Diff for: ‎src/StringEncodings.jl

+19-2
Original file line numberDiff line numberDiff line change
@@ -285,8 +285,24 @@ function read(s::StringDecoder, ::Type{UInt8})
285285
eof(s) ? throw(EOFError()) : s.outbuf[s.skip+=1]
286286
end
287287

288-
function readall(filename::AbstractString, encoding::ASCIIString)
289-
open(s -> readall(StringDecoder(s, encoding)), filename)
288+
289+
## Convenience I/O functions
290+
if isdefined(Base, :readstring)
291+
"""
292+
readstring(stream or filename, enc::ASCIIString)
293+
294+
Read the entire contents of an I/O stream or a file in encoding `enc` as a string.
295+
"""
296+
Base.readstring(s::IO, enc::ASCIIString) = readstring(StringDecoder(s, enc))
297+
Base.readstring(filename::AbstractString, enc::ASCIIString) = open(io->readstring(io, enc), filename)
298+
else # Compatibility with Julia 0.4
299+
"""
300+
readall(stream or filename, enc::ASCIIString)
301+
302+
Read the entire contents of an I/O stream or a file in encoding `enc` as a string.
303+
"""
304+
Base.readall(s::IO, enc::ASCIIString) = readall(StringDecoder(s, enc))
305+
Base.readall(filename::AbstractString, enc::ASCIIString) = open(io->readall(io, enc), filename)
290306
end
291307

292308

@@ -330,6 +346,7 @@ function encode(s::AbstractString, enc::ASCIIString)
330346
takebuf_array(b)
331347
end
332348

349+
333350
## Function to list supported encodings
334351
include("encodings.jl")
335352

Diff for: ‎test/runtests.jl

+13
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,19 @@ catch err
127127
"Conversion from nonexistent_encoding to UTF-8 not supported by iconv implementation, check that specified encodings are correct"
128128
end
129129

130+
if !isdefined(Base, :readstring)
131+
readstring = readall
132+
end
133+
134+
mktemp() do path, io
135+
s = "a string \0チャネルパ\0\0トナーの選択 with embedded and trailing nuls\0"
136+
write(io, encode(s, "ISO-2022-JP"))
137+
close(io)
138+
139+
@test readstring(path, "ISO-2022-JP") == s
140+
@test open(io->readstring(io, "ISO-2022-JP"), path) == s
141+
end
142+
130143
encodings_list = encodings()
131144
@test "ASCII" in encodings_list
132145
@test "UTF-8" in encodings_list

0 commit comments

Comments
 (0)
Please sign in to comment.