Home telegram - memory buffer
Post
Cancel

telegram - memory buffer

MemoryBuffer

private let emptyMemory = malloc(1)!

class MemoryBuffer:Equatable,CustomStringConvertible

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
68
69
public internal(set) var memory: UnsafeMutableRawPointer
var capacity: Int
public internal(set) var length: Int
var freeWhenDone: Bool

public init(copyOf buffer: MemoryBuffer) {
  // malloc
    self.memory = malloc(buffer.length)
  // copy
    memcpy(self.memory, buffer.memory, buffer.length)
    self.capacity = buffer.length
    self.length = buffer.length
  // default free when down
    self.freeWhenDone = true
}

public init(memory: UnsafeMutableRawPointer, capacity: Int, length: Int, freeWhenDone: Bool) {
    self.memory = memory
    self.capacity = capacity
    self.length = length
    self.freeWhenDone = freeWhenDone
}

public init(data: Data) {
    if data.count == 0 {
        self.memory = emptyMemory
        self.capacity = 0
        self.length = 0
        self.freeWhenDone = false
    } else {
      // malloc
        self.memory = malloc(data.count)!
      // copy [data copyBytesTo:count:]
        data.copyBytes(to: self.memory.assumingMemoryBound(to: UInt8.self), count: data.count)
        self.capacity = data.count
        self.length = data.count
        self.freeWhenDone = true
    }
}

public init() {
  // empty memory with 1 byte
    self.memory = emptyMemory
    self.capacity = 0
    self.length = 0
    self.freeWhenDone = false
}

// make data
public func makeData() -> Data {
    if self.length == 0 {
        return Data()
    } else {
//      [Data initBytes:count:]
        return Data(bytes: self.memory, count: self.length)
    }
}

// description
public var description: String {
    let hexString = NSMutableString()
    let bytes = self.memory.assumingMemoryBound(to: UInt8.self)
    for i in 0 ..< self.length {
      // dump every byte in hex representation
        hexString.appendFormat("%02x", UInt(bytes[i]))
    }
    
    return hexString as String
}
This post is licensed under CC BY 4.0 by the author.