-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
iostring.jl
61 lines (54 loc) · 1.59 KB
/
iostring.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
## work with Vector{Uint8} via I/O primitives ##
# Stateful string
type IOString <: IO
data::Vector{Uint8}
ptr::Int
IOString(data::Vector{Uint8}) = new(data, 1)
# TODO: should be copy on write if given a string
IOString(str::String) = IOString(str.data)
IOString() = IOString(Uint8[])
end
function read{T}(from::IOString, a::Array{T})
if isa(T, BitsKind)
nb = numel(a)*sizeof(T)
if length(from.data) - from.ptr + 1 < nb
throw(EOFError())
end
from.ptr += nb
return reshape(reinterpret(T, from.data[from.ptr-nb:from.ptr-1]), size(a))
else
error("Read from IOString only supports bits types or arrays of bits types; got $T.")
end
end
function read(from::IOString, ::Type{Uint8})
if from.ptr > length(from.data)
throw(EOFError())
end
from.ptr += 1
return from.data[from.ptr-1]
end
skip(io::IOString, n::Integer) = io.ptr += n
seek(io::IOString, n::Integer) = io.ptr = n+1
function write{T}(to::IOString, a::Array{T})
if isa(T, BitsKind)
nb = numel(a)*sizeof(T)
nshort = to.ptr + nb - length(to.data) - 1
if nshort > 0
grow(to.data, nshort)
end
to.data[to.ptr:to.ptr+nb-1] = reinterpret(Uint8, a, (sizeof(T)*numel(a),))
to.ptr += nb
else
error("Write to IOString only supports bits types or arrays of bits types; got $T.")
end
nb
end
function write(to::IOString, a::Uint8)
if to.ptr + 1 > length(to.data)
push(to.data, a)
else
to.data[to.ptr] = a
end
to.ptr += 1
sizeof(Uint8)
end