IdBuffer.pas 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  1. {
  2. $Project$
  3. $Workfile$
  4. $Revision$
  5. $DateUTC$
  6. $Id$
  7. This file is part of the Indy (Internet Direct) project, and is offered
  8. under the dual-licensing agreement described on the Indy website.
  9. (http://www.indyproject.org/)
  10. Copyright:
  11. (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
  12. }
  13. {
  14. $Log$
  15. }
  16. {
  17. Rev 1.47 1/24/2005 7:35:54 PM JPMugaas
  18. Fixed CopyTIdIPV6Address.
  19. Rev 1.46 1/17/2005 7:28:44 PM JPMugaas
  20. Added Index parameter to several functions so you can use TIdBuffer in a
  21. random access manner instead of in a sequential manner. This is good for
  22. some fixed-packet or data types.
  23. Added functions for reading and writing various types to TIdBuffer which use
  24. Byte Order functions. This should facilitate a lot of development as this
  25. gets used more.
  26. Rev 1.45 27.08.2004 21:58:18 Andreas Hausladen
  27. Speed optimization ("const" for string parameters)
  28. Rev 1.44 2004.07.03 19:41:34 czhower
  29. UTF8, SaveToStream
  30. Rev 1.43 6/11/2004 8:48:12 AM DSiders
  31. Added "Do not Localize" comments.
  32. Rev 1.42 6/9/04 7:46:26 PM RLebeau
  33. Updated ExtractToBytes() to allocate the output buffer only if the buffer
  34. length is smaller than the requested number of bytes.
  35. Rev 1.41 5/29/04 10:44:58 PM RLebeau
  36. Updated ExtractToBytes() to allocate the output buffer regardless of the
  37. AAppend parameter
  38. Added empty string return value to Extract() when AByteCount <= 0
  39. Rev 1.40 2004.05.20 11:39:06 AM czhower
  40. IdStreamVCL
  41. Rev 1.39 2004.05.10 1:19:18 PM czhower
  42. Removed unneeded code.
  43. Rev 1.38 5/3/2004 12:57:00 PM BGooijen
  44. Fixes for 0-based
  45. Rev 1.37 2004.05.03 11:15:42 AM czhower
  46. Changed Find to IndexOf and made 0 based to be consistent.
  47. Rev 1.36 2004.05.01 4:26:52 PM czhower
  48. Added PeekByte
  49. Rev 1.35 2004.04.16 11:30:26 PM czhower
  50. Size fix to IdBuffer, optimizations, and memory leaks
  51. Rev 1.34 2004.04.08 7:06:44 PM czhower
  52. Peek support.
  53. Rev 1.33 2004.04.08 3:56:24 PM czhower
  54. Fixed bug with Intercept byte count. Also removed Bytes from Buffer.
  55. Rev 1.32 2004.04.08 2:03:34 AM czhower
  56. Fixes to Bytes.
  57. Rev 1.31 2004.04.07 3:59:44 PM czhower
  58. Bug fix for WriteDirect.
  59. Rev 1.30 2004.04.07 3:46:30 PM czhower
  60. Compile fix.
  61. Rev 1.29 4/7/2004 1:02:14 PM BGooijen
  62. when extract* is called with -1 or no parameters all data it extracted
  63. Rev 1.28 2004.03.29 9:58:38 PM czhower
  64. Is now buffered. Now takes 2/3rds the time as before.
  65. Rev 1.27 23/03/2004 18:33:44 CCostelloe
  66. Bug fix: ReadLn returns a previously-read line if FBytes also accessed
  67. in-between (causes MoveHeadToStartIfNecessary to be called)
  68. Rev 1.26 18/03/2004 20:24:26 CCostelloe
  69. Speed improvement by adding FHeadIndex: 10 MB base64 decode reduced from 10
  70. hours to 62 seconds.
  71. Rev 1.25 2004.03.03 11:55:02 AM czhower
  72. IdStream change
  73. Rev 1.24 3/1/04 7:33:12 PM RLebeau
  74. Updated Remove() to call the OnBytesRemoved event handler.
  75. Rev 1.23 2004.02.03 4:17:14 PM czhower
  76. For unit name changes.
  77. Rev 1.22 1/11/2004 5:48:48 PM BGooijen
  78. Added AApend parameter to ExtractToBytes
  79. Rev 1.21 1/7/2004 8:36:32 PM BGooijen
  80. Arguments were in wrong order
  81. Rev 1.20 22/11/2003 10:35:04 PM GGrieve
  82. Reverse copy direction in TIdBuffer.ExtractToStream
  83. Rev 1.19 2003.10.24 10:44:54 AM czhower
  84. IdStream implementation, bug fixes.
  85. Rev 1.18 10/15/2003 1:03:40 PM DSiders
  86. Created resource strings for TIdBuffer.Find exceptions.
  87. Rev 1.17 2003.10.14 1:27:06 PM czhower
  88. Uupdates + Intercept support
  89. Rev 1.16 2003.10.11 5:47:00 PM czhower
  90. -VCL fixes for servers
  91. -Chain suport for servers (Super core)
  92. -Scheduler upgrades
  93. -Full yarn support
  94. Rev 1.15 10/5/2003 10:24:20 PM BGooijen
  95. Changed WriteBytes(var ...) to WriteBytes(const ...)
  96. Rev 1.14 10/3/2003 10:46:38 PM BGooijen
  97. Fixed Range Check Exception, and fixed ExtractToStream
  98. Rev 1.13 2003.10.02 8:29:12 PM czhower
  99. Changed names of byte conversion routines to be more readily understood and
  100. not to conflict with already in use ones.
  101. Rev 1.12 2003.10.02 12:44:58 PM czhower
  102. Comment added
  103. Rev 1.11 10/2/2003 5:23:14 PM GGrieve
  104. make Bytes a public property
  105. Rev 1.10 10/2/2003 5:00:38 PM GGrieve
  106. Fix bug in find - can't find last char
  107. Rev 1.9 2003.10.02 10:37:00 AM czhower
  108. Comments
  109. Rev 1.8 10/2/2003 3:54:06 PM GGrieve
  110. Finish cleaning up - no $IFDEFs but still optimal on both win32 and DontNet
  111. Rev 1.7 10/1/2003 10:58:38 PM BGooijen
  112. Removed unused var
  113. Rev 1.6 10/1/2003 8:15:58 PM BGooijen
  114. Fixed Range Check Error on D7
  115. Rev 1.5 10/1/2003 8:02:22 PM BGooijen
  116. Removed some ifdefs and improved code
  117. Rev 1.4 10/1/2003 10:49:02 PM GGrieve
  118. Rework buffer for Octane Compability
  119. Rev 1.3 2003.10.01 2:30:44 PM czhower
  120. .Net
  121. Rev 1.2 2003.10.01 1:37:32 AM czhower
  122. .Net
  123. Rev 1.1 2003.10.01 1:12:32 AM czhower
  124. .Net
  125. Rev 1.0 2003.09.30 10:33:56 PM czhower
  126. Readd after accidental delete.
  127. Rev 1.14 2003.09.30 10:33:16 PM czhower
  128. Updates
  129. Rev 1.13 2003.07.16 5:05:06 PM czhower
  130. Phase 1 of IdBuffer changes for compat.
  131. Rev 1.12 6/29/2003 10:56:22 PM BGooijen
  132. Removed .Memory from the buffer, and added some extra methods
  133. Rev 1.11 2003.06.25 4:29:06 PM czhower
  134. Free --> FreeAndNil
  135. Rev 1.10 2003.01.17 2:18:36 PM czhower
  136. Rev 1.9 12-14-2002 22:08:24 BGooijen
  137. Changed FMemory to FMemory.Memory in some places
  138. Rev 1.8 12-14-2002 22:02:34 BGooijen
  139. changed Memory to FMemory in some places, to remove some issues
  140. Rev 1.7 12/11/2002 04:27:02 AM JPMugaas
  141. Fixed compiler warning.
  142. Rev 1.6 12/11/2002 03:53:44 AM JPMugaas
  143. Merged the buffer classes.
  144. Rev 1.5 2002.12.07 12:26:18 AM czhower
  145. Rev 1.4 12-6-2002 20:34:06 BGooijen
  146. Now compiles on Delphi 5
  147. Rev 1.3 6/12/2002 11:00:14 AM SGrobety
  148. Rev 1.2 12/5/2002 02:55:44 PM JPMugaas
  149. Added AddStream method for reading a stream into the buffer class.
  150. Rev 1.1 23.11.2002 12:59:48 JBerg
  151. fixed packbuffer
  152. Rev 1.0 11/13/2002 08:38:32 AM JPMugaas
  153. }
  154. unit IdBuffer;
  155. {$I IdCompilerDefines.inc}
  156. {
  157. .Net forces us to perform copies from strings to Bytes so that it can do the
  158. proper unicode and other conversions.
  159. IdBuffer is for storing data we cannot deal with right now and we do not know
  160. the size. It must be optimized for adding to the end, and extracting from the
  161. beginning. First pass we are just making it work, later using bubbling we will
  162. optimize it for such tasks.
  163. The copy is a separate issue and we considered several options. For .net we will
  164. always have to copy data to send or to receive to translate it to binary. For
  165. example if we have a string it must be converted to bytes. This conversion
  166. requires a copy. All strings are Unicode and must be converted to single
  167. bytes by a convertor. This is not limited to strings.
  168. In VCL previously all strings were AnsiString so we used a pointer and just
  169. accessed the memory directly from the string. This avoided the overhead of a
  170. copy.
  171. We have come up with several ideas on how to allow the copy on .net, while
  172. avoiding the copy on VCL to keep the performance benefit. However we must do
  173. it in a single source manner and in a manner that does not impact the code
  174. negatively.
  175. For now for VCL we also do a copy. This has the advantage that Byte arrays are
  176. reference counted and automaticaly handled by Delphi. For example:
  177. WriteBytes(StringToBytes(s));
  178. The array returned by this function will automatically be freed by Delphi.
  179. There are other options that are nearly as transparent but have the additional
  180. overhead of requiring class creation. These classes can be used to copy for .net
  181. and proxy on VCL. It all works very nice and has low memory overhead. The
  182. objects can then be freed by default in methods that accept them.
  183. However after analysis, copy on VCL may not be that bad after all. The copy
  184. only really impacts strings. The overhead to copy strings is minimal and only
  185. used in commands etc. The big transfers come from files, streams, or other.
  186. Such transfers have to be mapped into memory in VCL anyways, and if we map
  187. directly into the byte array instead of the previous classes peformance should
  188. be fine.
  189. In short - copy under VCL should be acceptable if we watch for bottlenecks and
  190. fix them appropriately without having to creat proxy classes. The only problem
  191. remains for transmitting large memory blocks. But if this is done against a
  192. fixed copy buffer the performance hit will be neglible and it is not a common
  193. task to transmit large memory blocks.
  194. For such transfers from streams, etc the user can declare a persistent array
  195. of bytes that is not freed between each call to WriteBytes.
  196. -Kudzu
  197. }
  198. interface
  199. uses
  200. Classes,
  201. IdException,
  202. IdGlobal,
  203. SysUtils;
  204. type
  205. EIdNotEnoughDataInBuffer = class(EIdException);
  206. EIdTooMuchDataInBuffer = class(EIdException); // only 2GB is allowed -
  207. TIdBufferBytesRemoved = procedure(ASender: TObject; ABytes: Integer) of object;
  208. // TIdBuffer is used as an internal buffer to isolate Indy from pointers and
  209. // memory allocations. It also allows optimizations to be kept in a single place.
  210. //
  211. // TIdBuffer is primarily used as a read/write buffer for the communication layer.
  212. TIdBuffer = class(TObject)
  213. private
  214. function GetAsString: string;
  215. protected
  216. FBytes: TIdBytes;
  217. FByteEncoding: IIdTextEncoding;
  218. FGrowthFactor: Integer;
  219. FHeadIndex: Integer;
  220. FOnBytesRemoved: TIdBufferBytesRemoved;
  221. FSize: Integer;
  222. //
  223. procedure CheckAdd(AByteCount : Integer; const AIndex : Integer);
  224. procedure CheckByteCount(var VByteCount : Integer; const AIndex : Integer);
  225. function GetCapacity: Integer;
  226. procedure SetCapacity(AValue: Integer);
  227. public
  228. procedure Clear;
  229. constructor Create; overload;
  230. constructor Create(AOnBytesRemoved: TIdBufferBytesRemoved); overload;
  231. constructor Create(AGrowthFactor: Integer); overload;
  232. constructor Create(const ABytes : TIdBytes; const ALength : Integer = -1); overload;
  233. procedure CompactHead(ACanShrink: Boolean = True);
  234. destructor Destroy; override;
  235. {
  236. Most of these now have an AIndex parameter. If that is less than 0,
  237. we are accessing data sequentially. That means, read the data from the HeadIndex
  238. and "remove" the data you read.
  239. If AIndex is 0 or greater, the HeadIndex is disregarded and no deletion is done.
  240. You are just reading from a particular location in a random access manner.
  241. }
  242. // will extract number of bytes and decode as specified
  243. function ExtractToString(AByteCount: Integer = -1; AByteEncoding: IIdTextEncoding = nil): string;
  244. // all 3 extract routines append to existing data, if any
  245. procedure ExtractToStream(const AStream: TStream; AByteCount: Integer = -1; const AIndex: Integer = -1);
  246. procedure ExtractToIdBuffer(ABuffer: TIdBuffer; AByteCount: Integer = -1; const AIndex : Integer = -1);
  247. procedure ExtractToBytes(var VBytes: TIdBytes; AByteCount: Integer = -1;
  248. AAppend: Boolean = True; AIndex : Integer = -1);
  249. function ExtractToUInt8(const AIndex : Integer): UInt8;
  250. function ExtractToUInt16(const AIndex : Integer; AConvert: Boolean = True): UInt16;
  251. function ExtractToUInt32(const AIndex : Integer; AConvert: Boolean = True): UInt32;
  252. function ExtractToUInt64(const AIndex : Integer; AConvert: Boolean = True): UInt64;
  253. procedure ExtractToIPv6(const AIndex : Integer; var VAddress: TIdIPv6Address);
  254. function IndexOf(const AByte: Byte; AStartPos: Integer = 0): Integer; overload;
  255. function IndexOf(const ABytes: TIdBytes; AStartPos: Integer = 0): Integer; overload;
  256. function IndexOf(const AString: string; AStartPos: Integer = 0; AByteEncoding: IIdTextEncoding = nil): Integer; overload;
  257. function PeekByte(AIndex: Integer): Byte;
  258. procedure Remove(AByteCount: Integer);
  259. procedure SaveToStream(const AStream: TStream);
  260. { Most of these now have an ADestIndex parameter. If that is less than 0,
  261. we are writing data sequentially.
  262. If ADestIndex is 0 or greater, you are setting bytes in a particular
  263. location in a random access manner.
  264. }
  265. // Write
  266. procedure Write(const AString: string; AByteEncoding: IIdTextEncoding = nil; const ADestIndex: Integer = -1); overload;
  267. procedure Write(const ABytes: TIdBytes; const ADestIndex: Integer = -1); overload;
  268. procedure Write(const ABytes: TIdBytes; const ALength, AOffset : Integer; const ADestIndex: Integer = -1); overload;
  269. procedure Write(AStream: TStream; AByteCount: Integer = 0); overload;
  270. procedure Write(const AValue: UInt64; const ADestIndex: Integer = -1; AConvert: Boolean = True); overload;
  271. procedure Write(const AValue: UInt32; const ADestIndex: Integer = -1; AConvert: Boolean = True); overload;
  272. procedure Write(const AValue: UInt16; const ADestIndex: Integer = -1; AConvert: Boolean = True); overload;
  273. procedure Write(const AValue: UInt8; const ADestIndex: Integer = -1); overload;
  274. procedure Write(const AValue: TIdIPv6Address; const ADestIndex: Integer = -1); overload;
  275. //
  276. //Kudzu: I have removed the Bytes property. Do not add it back - it allowed "internal" access
  277. // which caused compacting or internal knowledge. Access via Extract or other such methods
  278. // instead. Bytes could also be easily confused with FBytes internally and cause issues.
  279. //
  280. // Bytes also allowed direct acces without removing which could cause concurrency issues if
  281. // the reference was kept.
  282. //
  283. property Capacity: Integer read GetCapacity write SetCapacity;
  284. property Encoding: IIdTextEncoding read FByteEncoding write FByteEncoding;
  285. property GrowthFactor: Integer read FGrowthFactor write FGrowthFactor;
  286. property Size: Integer read FSize;
  287. //useful for testing. returns buffer as string without extraction.
  288. property AsString: string read GetAsString;
  289. end;
  290. implementation
  291. uses
  292. IdResourceStringsCore,
  293. IdStack; //needed for byte order functions
  294. procedure TIdBuffer.CheckAdd(AByteCount : Integer; const AIndex : Integer);
  295. begin
  296. if (MaxInt - AByteCount) < (Size + AIndex) then begin
  297. raise EIdTooMuchDataInBuffer.Create(RSTooMuchDataInBuffer);
  298. end;
  299. end;
  300. procedure TIdBuffer.CheckByteCount(var VByteCount : Integer; const AIndex : Integer);
  301. begin
  302. if VByteCount = -1 then begin
  303. VByteCount := Size+AIndex;
  304. end
  305. else if VByteCount > (Size+AIndex) then begin
  306. raise EIdNotEnoughDataInBuffer.CreateFmt(RSNotEnoughDataInBuffer, [VByteCount, Size]); {do not localize}
  307. end;
  308. end;
  309. procedure TIdBuffer.Clear;
  310. begin
  311. SetLength(FBytes, 0);
  312. FHeadIndex := 0;
  313. FSize := 0;
  314. end;
  315. constructor TIdBuffer.Create(AGrowthFactor: Integer);
  316. begin
  317. Create;
  318. FGrowthFactor := AGrowthFactor;
  319. end;
  320. constructor TIdBuffer.Create(AOnBytesRemoved: TIdBufferBytesRemoved);
  321. begin
  322. Create;
  323. FOnBytesRemoved := AOnBytesRemoved;
  324. end;
  325. constructor TIdBuffer.Create(const ABytes: TIdBytes; const ALength: Integer);
  326. begin
  327. Create;
  328. if ALength < 0 then
  329. begin
  330. FBytes := ABytes;
  331. FSize := Length(ABytes);
  332. end else
  333. begin
  334. SetLength(FBytes, ALength);
  335. if ALength > 0 then
  336. begin
  337. CopyTIdBytes(ABytes, 0, FBytes, 0, ALength);
  338. FSize := ALength;
  339. end;
  340. end;
  341. end;
  342. destructor TIdBuffer.Destroy;
  343. begin
  344. Clear;
  345. inherited Destroy;
  346. //do only at the last moment
  347. TIdStack.DecUsage;
  348. end;
  349. function TIdBuffer.ExtractToString(AByteCount: Integer = -1; AByteEncoding: IIdTextEncoding = nil): string;
  350. var
  351. LBytes: TIdBytes;
  352. begin
  353. if AByteCount < 0 then begin
  354. AByteCount := Size;
  355. end;
  356. if AByteCount > 0 then
  357. begin
  358. if AByteEncoding = nil then begin
  359. AByteEncoding := FByteEncoding;
  360. EnsureEncoding(AByteEncoding);
  361. end;
  362. // TODO: convert directly from FBytes without allocating a local TIdBytes anymore...
  363. {
  364. CheckByteCount(AByteCount, 0);
  365. try
  366. Result := BytesToString(FBytes, FHeadIndex, AByteCount, AByteEncoding);
  367. finally
  368. Remove(AByteCount);
  369. end;
  370. }
  371. ExtractToBytes(LBytes, AByteCount);
  372. Result := BytesToString(LBytes, AByteEncoding);
  373. end else begin
  374. Result := '';
  375. end;
  376. end;
  377. procedure TIdBuffer.ExtractToBytes(var VBytes: TIdBytes; AByteCount: Integer = -1;
  378. AAppend: Boolean = True; AIndex : Integer = -1);
  379. var
  380. LOldSize: Integer;
  381. LIndex : Integer;
  382. begin
  383. if AByteCount < 0 then begin
  384. AByteCount := Size;
  385. end;
  386. LIndex := IndyMax(AIndex, 0);
  387. if AByteCount > 0 then begin
  388. CheckByteCount(AByteCount, LIndex);
  389. if AAppend then begin
  390. LOldSize := Length(VBytes);
  391. SetLength(VBytes, LOldSize + AByteCount);
  392. end else begin
  393. LOldSize := 0;
  394. if Length(VBytes) < AByteCount then begin
  395. SetLength(VBytes, AByteCount);
  396. end;
  397. end;
  398. if AIndex < 0 then
  399. begin
  400. CopyTIdBytes(FBytes, FHeadIndex, VBytes, LOldSize, AByteCount);
  401. Remove(AByteCount);
  402. end else
  403. begin
  404. CopyTIdBytes(FBytes, AIndex, VBytes, LOldSize, AByteCount);
  405. end;
  406. end;
  407. end;
  408. procedure TIdBuffer.ExtractToIdBuffer(ABuffer: TIdBuffer; AByteCount: Integer = -1;
  409. const AIndex: Integer = -1);
  410. var
  411. LBytes: TIdBytes;
  412. begin
  413. if AByteCount < 0 then begin
  414. AByteCount := Size;
  415. end;
  416. //TODO: Optimize this routine to directly copy from one to the other
  417. ExtractToBytes(LBytes, AByteCount, True, AIndex);
  418. ABuffer.Write(LBytes);
  419. end;
  420. procedure TIdBuffer.ExtractToStream(const AStream: TStream; AByteCount: Integer = -1;
  421. const AIndex: Integer = -1);
  422. var
  423. LBytes : TIdBytes;
  424. begin
  425. if AByteCount < 0 then begin
  426. AByteCount := Size;
  427. end;
  428. if AIndex < 0 then
  429. begin
  430. // TODO: remove CompactHead() here and pass FHeadIndex to AStream.WriteBuffer():
  431. {
  432. CheckByteCount(AByteCount, FHeadIndex);
  433. AStream.WriteBuffer(FBytes[FHeadIndex], AByteCount);
  434. Remove(AByteCount);
  435. }
  436. CompactHead;
  437. CheckByteCount(AByteCount, 0);
  438. AStream.WriteBuffer(PByte(FBytes)^, AByteCount);
  439. Remove(AByteCount);
  440. end else
  441. begin
  442. CheckByteCount(AByteCount, AIndex);
  443. // TODO: remove CopyTIdBytes() here and pass FBytes and AIndex to AStream.WriteBuffer():
  444. //AStream.WriteBuffer(FBytes[AIndex], AByteCount);
  445. SetLength(LBytes, AByteCount);
  446. CopyTIdBytes(FBytes, AIndex, LBytes, 0, AByteCount);
  447. AStream.WriteBuffer(PByte(LBytes)^, AByteCount);
  448. end;
  449. end;
  450. procedure TIdBuffer.Remove(AByteCount: Integer);
  451. begin
  452. if AByteCount >= Size then begin
  453. Clear;
  454. end else begin
  455. Inc(FHeadIndex, AByteCount);
  456. Dec(FSize, AByteCount);
  457. if FHeadIndex > GrowthFactor then begin
  458. CompactHead;
  459. end;
  460. end;
  461. if Assigned(FOnBytesRemoved) then begin
  462. FOnBytesRemoved(Self, AByteCount);
  463. end;
  464. end;
  465. procedure TIdBuffer.CompactHead(ACanShrink: Boolean = True);
  466. begin
  467. // Only try to compact if needed.
  468. if FHeadIndex > 0 then begin
  469. CopyTIdBytes(FBytes, FHeadIndex, FBytes, 0, Size);
  470. FHeadIndex := 0;
  471. if ACanShrink and ((Capacity - Size - FHeadIndex) > GrowthFactor) then begin
  472. SetLength(FBytes, FHeadIndex + Size + GrowthFactor);
  473. end;
  474. end;
  475. end;
  476. procedure TIdBuffer.Write(const ABytes: TIdBytes; const ADestIndex: Integer = -1);
  477. {$IFDEF USE_CLASSINLINE}inline;{$ENDIF}
  478. begin
  479. Write(ABytes, Length(ABytes), 0, ADestIndex);
  480. end;
  481. procedure TIdBuffer.Write(AStream: TStream; AByteCount: Integer);
  482. var
  483. LToAdd: Integer;
  484. LLength: Integer;
  485. begin
  486. // TODO: handle sizes > 2GB...
  487. if AByteCount < 0 then begin
  488. // Copy remaining
  489. LToAdd := AStream.Size - AStream.Position;
  490. end else if AByteCount = 0 then begin
  491. // Copy all
  492. AStream.Position := 0;
  493. LToAdd := AStream.Size;
  494. end else begin
  495. LToAdd := IndyMin(AByteCount, AStream.Size - AStream.Position);
  496. end;
  497. //Assert(LToAdd <= MaxInt);
  498. if LToAdd > 0 then begin
  499. LLength := Size;
  500. CheckAdd(LToAdd, 0);
  501. CompactHead;
  502. SetLength(FBytes, LLength + LToAdd);
  503. AStream.ReadBuffer(FBytes[LLength], LToAdd);
  504. Inc(FSize, LToAdd);
  505. end;
  506. end;
  507. function TIdBuffer.IndexOf(const AString: string; AStartPos: Integer = 0;
  508. AByteEncoding: IIdTextEncoding = nil): Integer;
  509. begin
  510. if AByteEncoding = nil then begin
  511. AByteEncoding := FByteEncoding;
  512. end;
  513. Result := IndexOf(ToBytes(AString, AByteEncoding), AStartPos);
  514. end;
  515. function TIdBuffer.IndexOf(const ABytes: TIdBytes; AStartPos: Integer = 0): Integer;
  516. var
  517. i, j, LEnd, BytesLen: Integer;
  518. LFound: Boolean;
  519. begin
  520. Result := -1;
  521. // Dont search if it empty
  522. if Size > 0 then begin
  523. BytesLen := Length(ABytes);
  524. if BytesLen = 0 then begin
  525. raise EIdException.Create(RSBufferMissingTerminator); // TODO: create a new Exception class for this
  526. end;
  527. if (AStartPos < 0) or (AStartPos >= Size) then begin
  528. raise EIdException.Create(RSBufferInvalidStartPos); // TODO: create a new Exception class for this
  529. end;
  530. LEnd := FHeadIndex + Size;
  531. for i := FHeadIndex + AStartPos to LEnd - BytesLen do begin
  532. LFound := True;
  533. for j := 0 to BytesLen - 1 do begin
  534. if (i + j) >= LEnd then begin
  535. Break;
  536. end;
  537. if FBytes[i + j] <> ABytes[j] then begin
  538. LFound := False;
  539. Break;
  540. end;
  541. end;
  542. if LFound then begin
  543. Result := i - FHeadIndex;
  544. Break;
  545. end;
  546. end;
  547. end;
  548. end;
  549. function TIdBuffer.IndexOf(const AByte: Byte; AStartPos: Integer = 0): Integer;
  550. var
  551. i: Integer;
  552. begin
  553. Result := -1;
  554. // Dont search if it empty
  555. if Size > 0 then begin
  556. if (AStartPos < 0) or (AStartPos >= Size) then begin
  557. raise EIdException.Create(RSBufferInvalidStartPos); // TODO: create a new Exception class for this
  558. end;
  559. for i := (FHeadIndex + AStartPos) to (FHeadIndex + Size - 1) do begin
  560. if FBytes[i] = AByte then begin
  561. Result := i - FHeadIndex;
  562. Break;
  563. end;
  564. end;
  565. end;
  566. end;
  567. procedure TIdBuffer.Write(const AString: string; AByteEncoding: IIdTextEncoding = nil;
  568. const ADestIndex : Integer = -1);
  569. begin
  570. if AByteEncoding = nil then begin
  571. AByteEncoding := FByteEncoding;
  572. end;
  573. Write(ToBytes(AString, AByteEncoding), ADestIndex);
  574. end;
  575. function TIdBuffer.GetCapacity: Integer;
  576. begin
  577. Result := Length(FBytes);
  578. end;
  579. procedure TIdBuffer.SetCapacity(AValue: Integer);
  580. begin
  581. if AValue < Size then begin
  582. raise EIdException.Create('Capacity cannot be smaller than Size'); {do not localize} // TODO: add a resource string, and create a new Exception class for this
  583. end;
  584. CompactHead;
  585. SetLength(FBytes, AValue);
  586. end;
  587. constructor TIdBuffer.Create;
  588. begin
  589. inherited Create;
  590. FGrowthFactor := 2048;
  591. Clear;
  592. TIdStack.IncUsage;
  593. end;
  594. function TIdBuffer.PeekByte(AIndex: Integer): Byte;
  595. begin
  596. if Size = 0 then begin
  597. raise EIdException.Create('No bytes in buffer.'); {do not localize} // TODO: add a resource string, and create a new Exception class for this
  598. end;
  599. if (AIndex < 0) or (AIndex >= Size) then begin
  600. raise EIdException.Create('Index out of bounds.'); {do not localize} // TODO: add a resource string, and create a new Exception class for this
  601. end;
  602. Result := FBytes[FHeadIndex + AIndex];
  603. end;
  604. procedure TIdBuffer.SaveToStream(const AStream: TStream);
  605. begin
  606. // TODO: remove CompactHead here and pass FBytes to AStream.WriteBuffer():
  607. //AStream.WriteBuffer(FBytes[FHeadIndex], Size);
  608. CompactHead(False);
  609. AStream.WriteBuffer(PByte(FBytes)^, Size);
  610. end;
  611. procedure TIdBuffer.ExtractToIPv6(const AIndex: Integer; var VAddress: TIdIPv6Address);
  612. var
  613. LIndex : Integer;
  614. begin
  615. if AIndex < 0 then begin
  616. LIndex := FHeadIndex;
  617. end else begin
  618. LIndex := AIndex;
  619. end;
  620. BytesToIPv6(FBytes, VAddress, LIndex);
  621. VAddress := GStack.NetworkToHost(VAddress);
  622. if AIndex < 0 then begin
  623. Remove(16);
  624. end;
  625. end;
  626. function TIdBuffer.ExtractToUInt64(const AIndex: Integer; AConvert: Boolean = True): UInt64;
  627. var
  628. LIndex : Integer;
  629. begin
  630. if AIndex < 0 then begin
  631. LIndex := FHeadIndex;
  632. end else begin
  633. LIndex := AIndex;
  634. end;
  635. Result := BytesToUInt64(FBytes, LIndex);
  636. if AIndex < 0 then begin
  637. Remove(8);
  638. end;
  639. if AConvert then begin
  640. Result := GStack.NetworkToHost(Result);
  641. end;
  642. end;
  643. function TIdBuffer.ExtractToUInt32(const AIndex: Integer; AConvert: Boolean = True): UInt32;
  644. var
  645. LIndex : Integer;
  646. begin
  647. if AIndex < 0 then begin
  648. LIndex := FHeadIndex;
  649. end else begin
  650. LIndex := AIndex;
  651. end;
  652. Result := BytesToUInt32(FBytes, LIndex);
  653. if AIndex < 0 then begin
  654. Remove(4);
  655. end;
  656. if AConvert then begin
  657. Result := GStack.NetworkToHost(Result);
  658. end;
  659. end;
  660. function TIdBuffer.ExtractToUInt16(const AIndex: Integer; AConvert: Boolean = True): UInt16;
  661. var
  662. LIndex : Integer;
  663. begin
  664. if AIndex < 0 then begin
  665. LIndex := FHeadIndex;
  666. end else begin
  667. LIndex := AIndex;
  668. end;
  669. Result := BytesToUInt16(FBytes, LIndex);
  670. if AIndex < 0 then begin
  671. Remove(2);
  672. end;
  673. if AConvert then begin
  674. Result := GStack.NetworkToHost(Result);
  675. end;
  676. end;
  677. function TIdBuffer.ExtractToUInt8(const AIndex: Integer): UInt8;
  678. var
  679. LIndex : Integer;
  680. begin
  681. if AIndex < 0 then begin
  682. LIndex := FHeadIndex;
  683. end else begin
  684. LIndex := AIndex;
  685. end;
  686. Result := FBytes[LIndex];
  687. if AIndex < 0 then begin
  688. Remove(1);
  689. end;
  690. end;
  691. procedure TIdBuffer.Write(const AValue: UInt16; const ADestIndex: Integer; AConvert: Boolean = True);
  692. var
  693. LVal : UInt16;
  694. LIndex : Integer;
  695. begin
  696. if ADestIndex < 0 then
  697. begin
  698. LIndex := FHeadIndex + Size;
  699. SetLength(FBytes, LIndex+2);
  700. end else
  701. begin
  702. LIndex := ADestIndex;
  703. end;
  704. LVal := AValue;
  705. if AConvert then begin
  706. LVal := GStack.HostToNetwork(LVal);
  707. end;
  708. CopyTIdUInt16(LVal, FBytes, LIndex);
  709. if LIndex >= FSize then begin
  710. FSize := LIndex+2;
  711. end;
  712. end;
  713. procedure TIdBuffer.Write(const AValue: UInt8; const ADestIndex: Integer);
  714. var
  715. LIndex : Integer;
  716. begin
  717. if ADestIndex < 0 then
  718. begin
  719. LIndex := FHeadIndex + Size;
  720. SetLength(FBytes, LIndex+1);
  721. end else
  722. begin
  723. LIndex := ADestIndex;
  724. end;
  725. FBytes[LIndex] := AValue;
  726. if LIndex >= FSize then begin
  727. FSize := LIndex+1;
  728. end;
  729. end;
  730. procedure TIdBuffer.Write(const AValue: TIdIPv6Address; const ADestIndex: Integer);
  731. var
  732. LVal : TIdIPv6Address;
  733. LIndex : Integer;
  734. begin
  735. if ADestIndex < 0 then
  736. begin
  737. LIndex := FHeadIndex + Size;
  738. SetLength(FBytes, LIndex + 16);
  739. end else
  740. begin
  741. LIndex := ADestIndex;
  742. end;
  743. LVal := GStack.HostToNetwork(AValue);
  744. CopyTIdIPV6Address(LVal, FBytes, LIndex);
  745. if LIndex >= FSize then begin
  746. FSize := LIndex+16;
  747. end;
  748. end;
  749. procedure TIdBuffer.Write(const AValue: UInt64; const ADestIndex: Integer; AConvert: Boolean = True);
  750. var
  751. LVal: UInt64;
  752. LIndex: Integer;
  753. begin
  754. if ADestIndex < 0 then
  755. begin
  756. LIndex := FHeadIndex + Size;
  757. SetLength(FBytes, LIndex + 8);
  758. end else
  759. begin
  760. LIndex := ADestIndex;
  761. end;
  762. LVal := AValue;
  763. if AConvert then begin
  764. LVal := GStack.HostToNetwork(LVal);
  765. end;
  766. CopyTIdUInt64(LVal, FBytes, LIndex);
  767. if LIndex >= FSize then begin
  768. FSize := LIndex + 8;
  769. end;
  770. end;
  771. procedure TIdBuffer.Write(const AValue: UInt32; const ADestIndex: Integer; AConvert: Boolean = True);
  772. var
  773. LVal : UInt32;
  774. LIndex : Integer;
  775. begin
  776. if ADestIndex < 0 then
  777. begin
  778. LIndex := FHeadIndex + Size;
  779. SetLength(FBytes, LIndex + 4);
  780. end else
  781. begin
  782. LIndex := ADestIndex;
  783. end;
  784. LVal := AValue;
  785. if AConvert then begin
  786. LVal := GStack.HostToNetwork(LVal);
  787. end;
  788. CopyTIdUInt32(LVal, FBytes, LIndex);
  789. if LIndex >= FSize then begin
  790. FSize := LIndex+4;
  791. end;
  792. end;
  793. procedure TIdBuffer.Write(const ABytes: TIdBytes; const ALength, AOffset : Integer;
  794. const ADestIndex: Integer = -1);
  795. var
  796. LByteLength: Integer;
  797. LIndex : Integer;
  798. begin
  799. LByteLength := IndyLength(ABytes, ALength, AOffset);
  800. if LByteLength = 0 then begin
  801. Exit;
  802. end;
  803. LIndex := IndyMax(ADestIndex, 0);
  804. CheckAdd(LByteLength, LIndex);
  805. if Size = 0 then begin
  806. FHeadIndex := 0;
  807. if ADestIndex < 0 then
  808. begin
  809. FBytes := ToBytes(ABytes, LByteLength, AOffset);
  810. FSize := LByteLength;
  811. end else
  812. begin
  813. FSize := ADestIndex + LByteLength;
  814. SetLength(FBytes, FSize);
  815. CopyTIdBytes(ABytes, AOffset, FBytes, ADestIndex, LByteLength);
  816. end;
  817. end
  818. else if ADestIndex < 0 then
  819. begin
  820. CompactHead(False);
  821. if (Capacity - Size - FHeadIndex) < LByteLength then begin
  822. SetLength(FBytes, Size + LByteLength + GrowthFactor);
  823. end;
  824. CopyTIdBytes(ABytes, AOffset, FBytes, FHeadIndex + Size, LByteLength);
  825. Inc(FSize, LByteLength);
  826. end else
  827. begin
  828. CopyTIdBytes(ABytes, AOffset, FBytes, LIndex, LByteLength);
  829. if LIndex >= FSize then begin
  830. FSize := LIndex + LByteLength;
  831. end;
  832. end;
  833. end;
  834. function TIdBuffer.GetAsString: string;
  835. begin
  836. Result := BytesToString(FBytes, FByteEncoding);
  837. end;
  838. end.