Skip to content

Commit 231b8c4

Browse files
committed
add indexing methods for Memory
1 parent edde03a commit 231b8c4

File tree

3 files changed

+52
-0
lines changed

3 files changed

+52
-0
lines changed

docs/src/index.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,3 +255,7 @@ TranscodingStreams.finalize
255255
TranscodingStreams.startproc
256256
TranscodingStreams.process
257257
```
258+
259+
```@docs
260+
TranscodingStreams.Memory
261+
```

src/memory.jl

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
# Memory
22
# ======
33

4+
"""
5+
A contiguous memory.
6+
7+
This type works like a `Vector` method.
8+
"""
49
struct Memory
510
ptr::Ptr{UInt8}
611
size::UInt
@@ -9,3 +14,23 @@ end
914
function Base.length(mem::Memory)
1015
return mem.size
1116
end
17+
18+
function Base.endof(mem::Memory)
19+
return Int(mem.size)
20+
end
21+
22+
function Base.checkbounds(mem::Memory, i::Integer)
23+
if !(1 i endof(mem))
24+
throw(BoundsError(mem, i))
25+
end
26+
end
27+
28+
function Base.getindex(mem::Memory, i::Integer)
29+
@boundscheck checkbounds(mem, i)
30+
return unsafe_load(mem.ptr, i)
31+
end
32+
33+
function Base.setindex!(mem::Memory, val::UInt8, i::Integer)
34+
@boundscheck checkbounds(mem, i)
35+
return unsafe_store!(mem.ptr, val, i)
36+
end

test/runtests.jl

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,29 @@ using TranscodingStreams
22
using TranscodingStreams.CodecIdentity
33
using Base.Test
44

5+
@testset "Memory" begin
6+
data = b"foobar"
7+
mem = TranscodingStreams.Memory(pointer(data), sizeof(data))
8+
@test mem isa TranscodingStreams.Memory
9+
@test mem.ptr === pointer(data)
10+
@test mem.size === length(mem) === UInt(sizeof(data))
11+
@test endof(mem) === 6
12+
@test mem[1] === UInt8('f')
13+
@test mem[2] === UInt8('o')
14+
@test mem[3] === UInt8('o')
15+
@test mem[4] === UInt8('b')
16+
@test mem[5] === UInt8('a')
17+
@test mem[6] === UInt8('r')
18+
@test_throws BoundsError mem[7]
19+
@test_throws BoundsError mem[0]
20+
mem[1] = UInt8('z')
21+
@test mem[1] === UInt8('z')
22+
mem[3] = UInt8('!')
23+
@test mem[3] === UInt8('!')
24+
@test_throws BoundsError mem[7] = 0x00
25+
@test_throws BoundsError mem[0] = 0x00
26+
end
27+
528
@testset "Identity Codec" begin
629
source = IOBuffer("")
730
stream = TranscodingStream(Identity(), source)

0 commit comments

Comments
 (0)