Home telegram - write buffer
Post
Cancel

telegram - write buffer

WriteBuffer

class WriteBuffer:MemoryBuffer

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
62
63
64
65
66
67
public var offset = 0

public override init() {
  // default memory with 32 bytes length
    super.init(memory: malloc(32), capacity: 32, length: 0, freeWhenDone: true)
}


// make a read buffer for current memory
// reset self: realloc memory, reset capacity, offset 
public func makeReadBufferAndReset() -> ReadBuffer {
  // free when done
  // means totaly make the memory's ownership to the new ReadBuffer
    let buffer = ReadBuffer(memory: self.memory, length: self.offset, freeWhenDone: true)
    self.memory = malloc(32)
    self.capacity = 32
    self.offset = 0
    return buffer
}

public func readBufferNoCopy() -> ReadBuffer {
  // frewWhenDon: false
  // means: just for read
    return ReadBuffer(memory: self.memory, length: self.offset, freeWhenDone: false)
}

// make data
override public func makeData() -> Data {
    return Data(bytes: self.memory.assumingMemoryBound(to: UInt8.self), count: self.offset)
}

// reset offset to zero position
public func reset() {
    self.offset = 0
}

// copy `data + offset` to `self.memory + self.offset`
public func write(_ data: UnsafeRawPointer, offset: Int = 0, length: Int) {
    if self.offset + length > self.capacity {
        self.capacity = self.offset + length + 256
        if self.length == 0 {
            self.memory = malloc(self.capacity)!
        } else {
            self.memory = realloc(self.memory, self.capacity)
        }
    }
    memcpy(self.memory + self.offset, data + offset, length)
    self.offset += length
    self.length = self.offset
}

// write data to self.memory.advanced(by: offset)
// -[Data copyBytesTo:count:]
public func write(_ data: Data) {
    let length = data.count
    if self.offset + length > self.capacity {
        self.capacity = self.offset + length + 256
        if self.length == 0 {
            self.memory = malloc(self.capacity)!
        } else {
            self.memory = realloc(self.memory, self.capacity)
        }
    }
    data.copyBytes(to: self.memory.advanced(by: offset).assumingMemoryBound(to: UInt8.self), count: length)
    self.offset += length
    self.length = self.offset
}
This post is licensed under CC BY 4.0 by the author.