source: trunk/src/qt3support/tools/q3cstring.cpp@ 324

Last change on this file since 324 was 2, checked in by Dmitry A. Kuminov, 16 years ago

Initially imported qt-all-opensource-src-4.5.1 from Trolltech.

File size: 26.1 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
4** Contact: Qt Software Information ([email protected])
5**
6** This file is part of the Qt3Support module of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial Usage
10** Licensees holding valid Qt Commercial licenses may use this file in
11** accordance with the Qt Commercial License Agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and Nokia.
14**
15** GNU Lesser General Public License Usage
16** Alternatively, this file may be used under the terms of the GNU Lesser
17** General Public License version 2.1 as published by the Free Software
18** Foundation and appearing in the file LICENSE.LGPL included in the
19** packaging of this file. Please review the following information to
20** ensure the GNU Lesser General Public License version 2.1 requirements
21** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
22**
23** In addition, as a special exception, Nokia gives you certain
24** additional rights. These rights are described in the Nokia Qt LGPL
25** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
26** package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you are unsure which license is appropriate for your use, please
37** contact the sales department at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include "q3cstring.h"
43#include "qregexp.h"
44#include "qdatastream.h"
45
46#include <stdio.h>
47#include <stdarg.h>
48#include <stdlib.h>
49#include <ctype.h>
50#include <limits.h>
51
52QT_BEGIN_NAMESPACE
53
54/*****************************************************************************
55 Q3CString member functions
56 *****************************************************************************/
57
58/*!
59 \class Q3CString
60 \reentrant
61 \brief The Q3CString class provides an abstraction of the classic C
62 zero-terminated char array (char *).
63
64 \compat
65
66 Q3CString tries to behave like a more convenient \c{const char *}.
67 The price of doing this is that some algorithms will perform
68 badly. For example, append() is O(length()) since it scans for a
69 null terminator. Although you might use Q3CString for text that is
70 never exposed to the user, for most purposes, and especially for
71 user-visible text, you should use QString. QString provides
72 implicit sharing, Unicode and other internationalization support,
73 and is well optimized.
74
75 Note that for the Q3CString methods that take a \c{const char *}
76 parameter the \c{const char *} must either be 0 (null) or not-null
77 and '\0' (NUL byte) terminated; otherwise the results are
78 undefined.
79
80 A Q3CString that has not been assigned to anything is \e null, i.e.
81 both the length and the data pointer is 0. A Q3CString that
82 references the empty string ("", a single '\0' char) is \e empty.
83 Both null and empty Q3CStrings are legal parameters to the methods.
84 Assigning \c{const char *} 0 to Q3CString produces a null Q3CString.
85
86 The length() function returns the length of the string; resize()
87 resizes the string and truncate() truncates the string. A string
88 can be filled with a character using fill(). Strings can be left
89 or right padded with characters using leftJustify() and
90 rightJustify(). Characters, strings and regular expressions can be
91 searched for using find() and findRev(), and counted using
92 contains().
93
94 Strings and characters can be inserted with insert() and appended
95 with append(). A string can be prepended with prepend().
96 Characters can be removed from the string with remove() and
97 replaced with replace().
98
99 Portions of a string can be extracted using left(), right() and
100 mid(). Whitespace can be removed using stripWhiteSpace() and
101 simplifyWhiteSpace(). Strings can be converted to uppercase or
102 lowercase with upper() and lower() respectively.
103
104 Strings that contain numbers can be converted to numbers with
105 toShort(), toInt(), toLong(), toULong(), toFloat() and toDouble().
106 Numbers can be converted to strings with setNum().
107
108 Many operators are overloaded to work with Q3CStrings. Q3CString
109 also supports some more obscure functions, e.g. sprintf(),
110 setStr() and setExpand().
111
112 \sidebar Note on Character Comparisons
113
114 In Q3CString the notion of uppercase and lowercase and of which
115 character is greater than or less than another character is locale
116 dependent. This affects functions which support a case insensitive
117 option or which compare or lowercase or uppercase their arguments.
118 Case insensitive operations and comparisons will be accurate if
119 both strings contain only ASCII characters. (If \c $LC_CTYPE is
120 set, most Unix systems do "the right thing".) Functions that this
121 affects include contains(), find(), findRev(), \l operator<(), \l
122 operator<=(), \l operator>(), \l operator>=(), lower() and
123 upper().
124
125 This issue does not apply to \l{QString}s since they represent
126 characters using Unicode.
127 \endsidebar
128
129 Performance note: The Q3CString methods for QRegExp searching are
130 implemented by converting the Q3CString to a QString and performing
131 the search on that. This implies a deep copy of the Q3CString data.
132 If you are going to perform many QRegExp searches on a large
133 Q3CString, you will get better performance by converting the
134 Q3CString to a QString yourself, and then searching in the QString.
135*/
136
137/*!
138 \fn Q3CString Q3CString::left(uint len) const
139
140 \internal
141*/
142
143/*!
144 \fn Q3CString Q3CString::right(uint len) const
145
146 \internal
147*/
148
149/*!
150 \fn Q3CString Q3CString::mid(uint index, uint len) const
151
152 \internal
153*/
154
155/*!
156 \fn Q3CString Q3CString::lower() const
157
158 Use QByteArray::toLower() instead.
159*/
160
161/*!
162 \fn Q3CString Q3CString::upper() const
163
164 Use QByteArray::toUpper() instead.
165*/
166
167/*!
168 \fn Q3CString Q3CString::stripWhiteSpace() const
169
170 Use QByteArray::trimmed() instead.
171*/
172
173/*!
174 \fn Q3CString Q3CString::simplifyWhiteSpace() const
175
176 Use QByteArray::simplified() instead.
177*/
178
179/*!
180 \fn Q3CString& Q3CString::insert(uint index, const char *c)
181
182 \internal
183*/
184
185/*!
186 \fn Q3CString& Q3CString::insert(uint index, char c)
187
188 \internal
189*/
190
191/*!
192 \fn Q3CString& Q3CString::prepend(const char *c)
193
194 \internal
195*/
196
197/*!
198 \fn Q3CString& Q3CString::remove(uint index, uint len)
199
200 \internal
201*/
202
203/*!
204 \fn Q3CString& Q3CString::replace(uint index, uint len, const char *c)
205
206 \internal
207*/
208
209/*!
210 \fn Q3CString& Q3CString::replace(char c, const Q3CString &after)
211
212 \internal
213*/
214
215/*!
216 \fn Q3CString& Q3CString::replace(char c, const char *after)
217
218 \internal
219*/
220
221/*!
222 \fn Q3CString& Q3CString::replace(const Q3CString &b, const Q3CString &a)
223
224 \internal
225*/
226
227/*!
228 \fn Q3CString& Q3CString::replace(const char *b, const char *a)
229
230 \internal
231*/
232
233/*!
234 \fn Q3CString& Q3CString::replace(char b, char a)
235
236 \internal
237*/
238
239/*!
240 \fn Q3CString::Q3CString()
241
242 Constructs a null string.
243
244 \sa isNull()
245*/
246
247/*!
248 \fn Q3CString::Q3CString(const QByteArray &ba)
249
250 Constructs a copy of \a ba.
251*/
252
253/*!
254 \fn Q3CString::Q3CString(const Q3CString &s)
255
256 Constructs a shallow copy \a s.
257*/
258
259/*! \fn Q3CString::Q3CString(int size)
260 Constructs a string with room for \a size characters, including
261 the '\0'-terminator. Makes a null string if \a size == 0.
262
263 If \a size \> 0, then the first and last characters in the string
264 are initialized to '\0'. All other characters are uninitialized.
265
266 \sa resize(), isNull()
267*/
268
269/*! \fn Q3CString::Q3CString(const char *str)
270 Constructs a string that is a deep copy of \a str.
271
272 If \a str is 0 a null string is created.
273
274 \sa isNull()
275*/
276
277
278/*! \fn Q3CString::Q3CString(const char *str, uint maxsize)
279
280 Constructs a string that is a deep copy of \a str. The copy will
281 be at most \a maxsize bytes long including the '\0'-terminator.
282
283 Example:
284 \snippet doc/src/snippets/code/src_qt3support_tools_q3cstring.cpp 0
285
286 If \a str contains a 0 byte within the first \a maxsize bytes, the
287 resulting Q3CString will be terminated by this 0. If \a str is 0 a
288 null string is created.
289
290 \sa isNull()
291*/
292
293/*!
294 \fn Q3CString &Q3CString::operator=(const QByteArray &ba)
295
296 Assigns byte array \a ba to this Q3CString.
297*/
298
299/*!
300 \fn Q3CString &Q3CString::operator=(const Q3CString &s)
301
302 Assigns a shallow copy of \a s to this string and returns a
303 reference to this string.
304*/
305
306/*!
307 \fn Q3CString &Q3CString::operator=(const char *str)
308 \overload
309
310 Assigns a deep copy of \a str to this string and returns a
311 reference to this string.
312
313 If \a str is 0 a null string is created.
314
315 \sa isNull()
316*/
317
318/*
319 \fn bool Q3CString::isNull() const
320
321 Returns true if the string is null, i.e. if data() == 0; otherwise
322 returns false. A null string is also an empty string.
323
324 Example:
325 \snippet doc/src/snippets/code/src.qt3support.tools.q3cstring.cpp 1
326
327 \sa isEmpty(), length(), size()
328*/
329
330/*
331 \fn bool Q3CString::isEmpty() const
332
333 Returns true if the string is empty, i.e. if length() == 0;
334 otherwise returns false. An empty string is not always a null
335 string.
336
337 See example in isNull().
338
339 \sa isNull(), length(), size()
340*/
341
342/*
343 \fn uint Q3CString::length() const
344
345 Returns the length of the string, excluding the '\0'-terminator.
346 Equivalent to calling \c strlen(data()).
347
348 Null strings and empty strings have zero length.
349
350 \sa size(), isNull(), isEmpty()
351*/
352
353/*
354 \fn bool Q3CString::truncate(uint pos)
355
356 Truncates the string at position \a pos.
357
358 Equivalent to calling \c resize(pos+1).
359
360 Example:
361 \snippet doc/src/snippets/code/src.qt3support.tools.q3cstring.cpp 2
362
363 \sa resize()
364*/
365
366
367
368/*!
369 Implemented as a call to the native vsprintf() (see the manual for
370 your C library).
371
372 If the string is shorter than 256 characters, this sprintf() calls
373 resize(256) to decrease the chance of memory corruption. The
374 string is resized back to its actual length before sprintf()
375 returns.
376
377 Example:
378 \snippet doc/src/snippets/code/src_qt3support_tools_q3cstring.cpp 3
379
380 \warning All vsprintf() implementations will write past the end of
381 the target string (*this) if the \a format specification and
382 arguments happen to be longer than the target string, and some
383 will also fail if the target string is longer than some arbitrary
384 implementation limit.
385
386 Giving user-supplied arguments to sprintf() is risky: Sooner or
387 later someone will paste a huge line into your application.
388*/
389
390Q3CString &Q3CString::sprintf(const char *format, ...)
391{
392 detach();
393 va_list ap;
394 va_start(ap, format);
395 if (size() < 256)
396 resize(256); // make string big enough
397 qvsnprintf(data(), size(), format, ap);
398 resize(qstrlen(constData()));
399 va_end(ap);
400 return *this;
401}
402
403
404
405/*!
406 \fn Q3CString Q3CString::copy() const
407
408 Returns a deep copy of this string.
409*/
410
411
412/*!
413 Returns a string of length \a width (plus one for the terminating
414 '\0') that contains this string padded with the \a fill character.
415
416 If the length of the string exceeds \a width and \a truncate is
417 false (the default), then the returned string is a copy of the
418 string. If the length of the string exceeds \a width and \a
419 truncate is true, then the returned string is a left(\a width).
420
421 Example:
422 \snippet doc/src/snippets/code/src_qt3support_tools_q3cstring.cpp 4
423
424 \sa rightJustify()
425*/
426
427Q3CString Q3CString::leftJustify(uint width, char fill, bool truncate) const
428{
429 Q3CString result;
430 int len = qstrlen(constData());
431 int padlen = width - len;
432 if (padlen > 0) {
433 result.resize(len+padlen);
434 memcpy(result.data(), constData(), len);
435 memset(result.data()+len, fill, padlen);
436 } else {
437 if (truncate)
438 result = left(width);
439 else
440 result = *this;
441 }
442 return result;
443}
444
445/*!
446 Returns a string of length \a width (plus one for the terminating
447 '\0') that contains zero or more of the \a fill character followed
448 by this string.
449
450 If the length of the string exceeds \a width and \a truncate is
451 false (the default), then the returned string is a copy of the
452 string. If the length of the string exceeds \a width and \a
453 truncate is true, then the returned string is a left(\a width).
454
455 Example:
456 \snippet doc/src/snippets/code/src_qt3support_tools_q3cstring.cpp 5
457
458 \sa leftJustify()
459*/
460
461Q3CString Q3CString::rightJustify(uint width, char fill, bool truncate) const
462{
463 Q3CString result;
464 int len = qstrlen(constData());
465 int padlen = width - len;
466 if (padlen > 0) {
467 result.resize(len+padlen);
468 memset(result.data(), fill, padlen);
469 memcpy(result.data()+padlen, constData(), len);
470 } else {
471 if (truncate)
472 result = left(width);
473 else
474 result = *this;
475 }
476 return result;
477}
478
479/*!
480 Returns the string converted to a \c long value.
481
482 If \a ok is not 0: *\a ok is set to false if the string is not a
483 number, or if it has trailing garbage; otherwise *\a ok is set to
484 true.
485*/
486
487long Q3CString::toLong(bool *ok) const
488{
489 const char *p = constData();
490 long val=0;
491 const long max_mult = 214748364;
492 bool is_ok = false;
493 int neg = 0;
494 if (!p)
495 goto bye;
496 while (isspace((uchar) *p)) // skip leading space
497 p++;
498 if (*p == '-') {
499 p++;
500 neg = 1;
501 } else if (*p == '+') {
502 p++;
503 }
504 if (!isdigit((uchar) *p))
505 goto bye;
506 while (isdigit((uchar) *p)) {
507 if (val > max_mult || (val == max_mult && (*p-'0') > 7+neg))
508 goto bye;
509 val = 10*val + (*p++ - '0');
510 }
511 if (neg)
512 val = -val;
513 while (isspace((uchar) *p)) // skip trailing space
514 p++;
515 if (*p == '\0')
516 is_ok = true;
517bye:
518 if (ok)
519 *ok = is_ok;
520 return is_ok ? val : 0;
521}
522
523/*!
524 Returns the string converted to an \c{unsigned long} value.
525
526 If \a ok is not 0: *\a ok is set to false if the string is not a
527 number, or if it has trailing garbage; otherwise *\a ok is set to
528 true.
529*/
530
531ulong Q3CString::toULong(bool *ok) const
532{
533 const char *p = constData();
534 ulong val=0;
535 const ulong max_mult = 429496729;
536 bool is_ok = false;
537 if (!p)
538 goto bye;
539 while (isspace((uchar) *p)) // skip leading space
540 p++;
541 if (*p == '+')
542 p++;
543 if (!isdigit((uchar) *p))
544 goto bye;
545 while (isdigit((uchar) *p)) {
546 if (val > max_mult || (val == max_mult && (*p-'0') > 5))
547 goto bye;
548 val = 10*val + (*p++ - '0');
549 }
550 while (isspace((uchar) *p)) // skip trailing space
551 p++;
552 if (*p == '\0')
553 is_ok = true;
554bye:
555 if (ok)
556 *ok = is_ok;
557 return is_ok ? val : 0;
558}
559
560/*!
561 Returns the string converted to a \c{short} value.
562
563 If \a ok is not 0: *\a ok is set to false if the string is not a
564 number, is out of range, or if it has trailing garbage; otherwise
565 *\a ok is set to true.
566*/
567
568short Q3CString::toShort(bool *ok) const