-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuDangoStringBuilder.pas
More file actions
74 lines (64 loc) · 1.51 KB
/
uDangoStringBuilder.pas
File metadata and controls
74 lines (64 loc) · 1.51 KB
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
unit uDangoStringBuilder;
interface
uses
SysUtils;
type
TStringBuilder = class
private
FBuffer: array of Char;
FLength: Integer;
procedure EnsureCapacity(MinCapacity: Integer);
public
constructor Create(InitialCapacity: Integer = 16);
function Append(const S: string): TStringBuilder;
function AppendChar(C: Char): TStringBuilder;
function ToString: string;
end;
implementation
constructor TStringBuilder.Create(InitialCapacity: Integer);
begin
inherited Create;
if InitialCapacity < 1 then
raise Exception.Create('InitialCapacity must be greater 0');
SetLength(FBuffer, InitialCapacity);
FLength := 0;
end;
procedure TStringBuilder.EnsureCapacity(MinCapacity: Integer);
var
NewCapacity: Integer;
begin
if MinCapacity > Length(FBuffer) then
begin
NewCapacity := Length(FBuffer) * 2;
if NewCapacity < MinCapacity then
NewCapacity := MinCapacity;
SetLength(FBuffer, NewCapacity);
end;
end;
function TStringBuilder.Append(const S: string): TStringBuilder;
var
L: Integer;
begin
L := Length(S);
if L = 0 then
Exit;
EnsureCapacity(FLength + L);
Move(S[1], FBuffer[FLength], L * SizeOf(Char));
Inc(FLength, L);
Result := Self;
end;
function TStringBuilder.AppendChar(C: Char): TStringBuilder;
begin
EnsureCapacity(FLength + 1);
FBuffer[FLength] := C;
Inc(FLength);
Result := Self;
end;
function TStringBuilder.ToString: string;
begin
if FLength = 0 then
Result := ''
else
SetString(Result, PChar(@FBuffer[0]), FLength);
end;
end.