6f14d4921dbe67a95ffd1d04f3f3d06a81cd15eb
[sdk] / extras / types / DynamicString.ec
1 #include <stdarg.h>
2
3 extern int isblank(int c);
4
5 class DynamicString : Array<char>
6 {
7    minAllocSize = 1024;
8
9    DynamicString()
10    {
11       Add('\0');
12    }
13
14    property String
15    {
16       set
17       {
18          DynamicString s { };
19          if(value)
20          {
21             int len = strlen(value) + 1;
22             s.size = len;
23             memcpy(s.array, value, len);
24          }
25          return s;
26       }
27       get { return array; }
28    }
29
30    void concat(String s)
31    {
32       int len = strlen(s);
33       if(len)
34       {
35          int pos = size-1;
36          if(pos == -1) { Add('\0'); pos = 0; }
37          size += len;
38          memcpy(&(this[pos]), s, len+1);
39       }
40    }
41
42    void concatf(char * format, ...)
43    {
44       // TODO: improve this to vsprinf directly in the Array<char> instead of calling concat
45       char string[MAX_F_STRING];
46       va_list args;
47       va_start(args, format);
48       vsnprintf(string, sizeof(string), format, args);
49       string[sizeof(string)-1] = 0;
50       va_end(args);
51       concat(string);
52    }
53
54    void concatx(typed_object object, ...)
55    {
56       // TODO: improve this to work directly on the Array<char> instead of calling PrintStdArgsToBuffer
57       char string[MAX_F_STRING];
58       va_list args;
59       int len;
60       va_start(args, object);
61       len = PrintStdArgsToBuffer(string, sizeof(string), object, args);
62       concat(string);
63       va_end(args);
64    }
65
66    void copySingleBlankReplTrim(String s, char replace, bool trim)
67    {
68       privateCommonCopyLenSingleBlankReplTrim(s, replace, trim, strlen(s));
69    }
70
71    void copyLenSingleBlankReplTrim(String s, char replace, bool trim, int copyLen)
72    {
73       privateCommonCopyLenSingleBlankReplTrim(s, replace, trim, Min(strlen(s), copyLen));
74    }
75
76    void privateCommonCopyLenSingleBlankReplTrim(String s, char replace, bool trim, int len)
77    {
78       int c, d;
79       bool wasBlank = trim;
80       size = len + 1;
81       for(c = d = 0; c < len; c++)
82       {
83          if(isblank(s[c]))
84          {
85             if(!wasBlank)
86             {
87                wasBlank = true;
88                /*array*/this[d++] = replace ? replace : s[c];
89             }
90          }
91          else
92          {
93             /*array*/this[d++] = s[c];
94             if(wasBlank)
95                wasBlank = false;
96          }
97       }
98       if(!trim || (len && !isblank(/*array*/this[d])))
99          d++;
100       /*array*/this[d] = '\0';
101       size = d + 1;
102    }
103 }