@@ -226,6 +226,80 @@ function unsafe_read(s::IO, p::Ptr{UInt8}, n::UInt)
226
226
nothing
227
227
end
228
228
229
+ function peek (s:: IO )
230
+ mark (s)
231
+ try read (s, UInt8)
232
+ finally
233
+ reset (s)
234
+ end
235
+ end
236
+
237
+ # Generic `open` methods
238
+
239
+ """
240
+ open_flags(; keywords...) -> NamedTuple
241
+
242
+ Compute the `read`, `write`, `create`, `truncate`, `append` flag value for
243
+ a given set of keyword arguments to [`open`](@ref) a [`NamedTuple`](@ref).
244
+ """
245
+ function open_flags (;
246
+ read :: Union{Bool,Nothing} = nothing ,
247
+ write :: Union{Bool,Nothing} = nothing ,
248
+ create :: Union{Bool,Nothing} = nothing ,
249
+ truncate :: Union{Bool,Nothing} = nothing ,
250
+ append :: Union{Bool,Nothing} = nothing ,
251
+ )
252
+ if write === true && read != = true && append != = true
253
+ create === nothing && (create = true )
254
+ truncate === nothing && (truncate = true )
255
+ end
256
+
257
+ if truncate === true || append === true
258
+ write === nothing && (write = true )
259
+ create === nothing && (create = true )
260
+ end
261
+
262
+ write === nothing && (write = false )
263
+ read === nothing && (read = ! write)
264
+ create === nothing && (create = false )
265
+ truncate === nothing && (truncate = false )
266
+ append === nothing && (append = false )
267
+
268
+ return (
269
+ read = read,
270
+ write = write,
271
+ create = create,
272
+ truncate = truncate,
273
+ append = append,
274
+ )
275
+ end
276
+
277
+ """
278
+ open(f::Function, args...; kwargs....)
279
+
280
+ Apply the function `f` to the result of `open(args...; kwargs...)` and close the resulting file
281
+ descriptor upon completion.
282
+
283
+ # Examples
284
+ ```jldoctest
285
+ julia> open("myfile.txt", "w") do io
286
+ write(io, "Hello world!")
287
+ end;
288
+
289
+ julia> open(f->read(f, String), "myfile.txt")
290
+ "Hello world!"
291
+
292
+ julia> rm("myfile.txt")
293
+ ```
294
+ """
295
+ function open (f:: Function , args... ; kwargs... )
296
+ io = open (args... ; kwargs... )
297
+ try
298
+ f (io)
299
+ finally
300
+ close (io)
301
+ end
302
+ end
229
303
230
304
# Generic wrappers around other IO objects
231
305
abstract type AbstractPipe <: IO end
0 commit comments