Base architecture.
[brdnet.git] / MemStream.pas
blob3c8bb854ab6358e62cba0a08f7e38aed3562682e
1 unit MemStream;
3 INTERFACE
4 uses SysUtils;
5 type tMemoryStream=object
6 length: LongWord;
7 size: LongWord;
8 data: pointer;
9 position: pointer;
10 procedure Seek(absolute:LongWord);
11 procedure Skip(cnt:Word);
12 procedure Read(var buf; cnt:Word);
13 function ReadByte:byte;
14 function ReadWord(cnt:byte): LongWord; experimental;
15 procedure Rewind;
16 procedure Append;
17 function Tell:LongWord;
18 procedure Write(var buf; cnt:word);
19 procedure WriteByte(v:byte);
20 procedure WriteWord(v:LongWord; cnt:byte); experimental;
21 procedure Init(ibuf:pointer; ilen,isize:LongWord);
22 end;
24 type eInvalidMemStreamAccess=class(Exception)
25 {no details jet}
26 end;
28 IMPLEMENTATION
30 procedure tMemoryStream.Seek(absolute:LongWord);
31 begin
32 if absolute>=size then raise eInvalidMemStreamAccess.Create('Seek out of bounds');
33 position:=data+absolute;
34 end;
36 procedure tMemoryStream.Skip(cnt:Word);
37 begin
38 if cnt>=size then raise eInvalidMemStreamAccess.Create('Seek out of bounds');
39 position:=position+cnt;
40 end;
42 procedure tMemoryStream.Read(var buf; cnt:Word);
43 begin
44 if (position+cnt)>=(data+length) then raise eInvalidMemStreamAccess.Create('Read out of bounds');
45 Move(position^,buf,cnt);
46 position:=position+cnt;
47 end;
49 function tMemoryStream.ReadByte:byte;
50 begin Read(result, 1); end;
52 function tMemoryStream.ReadWord(cnt:byte): LongWord;
53 {$IFDEF ENDIAN_LITTLE}
54 var tm:packed array [0..3] of byte;
55 var i:byte;
56 begin
57 if (position+cnt)>=(data+length) then raise eInvalidMemStreamAccess.Create('Read out of bounds');
58 for i:=cnt-1 downto 0 do begin
59 tm[i]:=byte((position)^);
60 inc(position);
61 end;
62 {$ELSE}
63 begin
64 Read(tm[4-cnt],cnt);
65 {$ENDIF}
66 ReadWord:=LongWord(pointer(@tm)^);
67 end;
69 procedure tMemoryStream.Rewind;
70 begin position:=data; end;
71 procedure tMemoryStream.Append;
72 begin position:=data+length; end;
73 function tMemoryStream.Tell:LongWord;
74 begin Tell:=position-data; end;
75 procedure tMemoryStream.Write(var buf; cnt:word);
76 begin
77 if (position+cnt)>=(data+size) then raise eInvalidMemStreamAccess.Create('Write out of bounds');
78 Move(buf,position^,cnt);
79 length:=position-data;
80 end;
81 procedure tMemoryStream.WriteByte(v:byte);
82 begin Write(v,1); end;
84 procedure tMemoryStream.WriteWord(v:LongWord; cnt:byte);
85 var tm:packed array [0..3] of byte absolute v;
86 var i:byte;
87 begin
88 {$IFDEF ENDIAN_LITTLE}
89 if (position+cnt)>=(data+size) then raise eInvalidMemStreamAccess.Create('Write out of bounds');
90 for i:=cnt-1 to 0 do begin
91 byte(position^):=tm[i];
92 inc(position);
93 end;
94 {$ELSE}
95 Write(tm[4-cnt],cnt);
96 {$ENDIF}
97 length:=position-data;
98 end;
100 procedure tMemoryStream.Init(ibuf:pointer; ilen,isize:LongWord);
101 begin
102 data:=ibuf;
103 length:=ilen;
104 size:=isize;
105 end;
107 END.