Skip to content

Commit c335745

Browse files
committed
Add readstring() convenience functions
1 parent 9725e8d commit c335745

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

src/StringEncodings.jl

+21
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,26 @@ function readall(filename::AbstractString, encoding::ASCIIString)
290290
end
291291

292292

293+
## Convenience I/O functions
294+
if isdefined(Base, :readstring)
295+
"""
296+
readstring(stream or filename, enc::ASCIIString)
297+
298+
Read the entire contents of an I/O stream or a file in encoding `enc` as a string.
299+
"""
300+
Base.readstring(s::IO, enc::ASCIIString) = readstring(StringDecoder(s, enc))
301+
Base.readstring(filename::AbstractString, enc::ASCIIString) = open(io->readstring(io, enc), filename)
302+
else # Compatibility with Julia 0.4
303+
"""
304+
readall(stream or filename, enc::ASCIIString)
305+
306+
Read the entire contents of an I/O stream or a file in encoding `enc` as a string.
307+
"""
308+
Base.readall(s::IO, enc::ASCIIString) = readall(StringDecoder(s, enc))
309+
Base.readall(filename::AbstractString, enc::ASCIIString) = open(io->readall(io, enc), filename)
310+
end
311+
312+
293313
## Functions to encode/decode strings
294314

295315
encoding_string(::Type{ASCIIString}) = "ASCII"
@@ -330,6 +350,7 @@ function encode(s::AbstractString, enc::ASCIIString)
330350
takebuf_array(b)
331351
end
332352

353+
333354
## Function to list supported encodings
334355
include("encodings.jl")
335356

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)