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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
--[[
Public functions:
CreateStream(data_or_nil)
A stream object, has the methods:
stream:WriteString(string) :: nil
stream:WriteInt(num,bytes) :: nil
stream:ReadString() :: string
stream:ReadInt(bytes) :: number
stream:ToString() :: string
]]
local ss = {}
local function WriteString(self,string)
local buflen = #self.buf
for i = 1,#string do
self.buf[buflen + i] = string.byte(string,i)
end
self.buf[#self.buf + 1] = 0
end
local function WriteInt(self,num,bytes)
local buflen = #self.buf
local byte = 255
for i = 1,bytes do
--[[
pack[i] = (num & byte) >> (i-1)*8
byte = 255 << i*8
]]
self.buf[buflen + i] = bit.rshift(bit.band(num,byte),(i - 1) * 8)
byte = bit.lshift(255,i * 8)
end
end
local function ReadInt(self,len)
local tbl = {}
for i = 1, len do
tbl[i] = self.buf[i]
end
for i = 1, #self.buf do
self.buf[i] = self.buf[i + len]
end
local byte = 1
local num = 0
for i = 1, #tbl do
num = num + (tbl[i] * byte)
byte = 2 ^ (i * 8)
end
return num
end
local function ReadString(self)
local str = {}
local strlen = 1
while self.buf[strlen] ~= 0 do
str[#str + 1] = string.char(self.buf[strlen])
strlen = strlen + 1
end
for i = 1,strlen do
self.buf[i] = self.buf[i + strlen]
end
return table.concat(str)
end
local function ToString(self)
return table.concat(self.buf)
end
function ss.CreateStream(str)
local ns = {}
ns.buf = {}
if str ~= nil then
for i = 1, #str do
ns[i] = str[i]
end
end
ns.ReadString = ReadString
ns.ReadInt = ReadInt
ns.WriteString = WriteString
ns.WriteInt = WriteInt
ns.ToString = ToString
return ns
end
return ss
|