Debian Codegraph @

generic/tclStringObj.c

raw
1 /*
2 * tclStringObj.c --
3 *
4 * This file contains functions that implement string operations on Tcl
5 * objects. Some string operations work with UTF-8 encoding forms.
6 * Functions that require knowledge of the width of each character,
7 * such as indexing, operate on fixed width encoding forms such as UTF-16.
8 *
9 * Conceptually, a string is a sequence of Unicode code points. Internally
10 * it may be stored in an encoding form such as a modified version of
11 * UTF-8 or UTF-16.
12 *
13 * The String object is optimized for the case where each UTF char
14 * in a string is only one byte. In this case, we store the value of
15 * numChars, but we don't store the fixed form encoding (unless
16 * Tcl_GetUnicode is explicitly called).
17 *
18 * The String object type stores one or both formats. The default
19 * behavior is to store UTF-8. Once UTF-16/UTF32 is calculated, it is
20 * stored in the internal rep for future access (without an additional
21 * O(n) cost).
22 *
23 * To allow many appends to be done to an object without constantly
24 * reallocating space, we allocate double the space and use the
25 * internal representation to keep track of how much space is used vs.
26 * allocated.
27 *
28 * Copyright (c) 1995-1997 Sun Microsystems, Inc.
29 * Copyright (c) 1999 Scriptics Corporation.
30 *
31 * See the file "license.terms" for information on usage and redistribution of
32 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
33 */
34
35 #include "tclInt.h"
36 #include "tommath.h"
37 #include "tclStringRep.h"
38 /*
39 * Prototypes for functions defined later in this file:
40 */
41
42 static void AppendPrintfToObjVA(Tcl_Obj *objPtr,
43 const char *format, va_list argList);
44 static void AppendUnicodeToUnicodeRep(Tcl_Obj *objPtr,
45 const Tcl_UniChar *unicode, int appendNumChars);
46 static void AppendUnicodeToUtfRep(Tcl_Obj *objPtr,
47 const Tcl_UniChar *unicode, int numChars);
48 static void AppendUtfToUnicodeRep(Tcl_Obj *objPtr,
49 const char *bytes, int numBytes);
50 static void AppendUtfToUtfRep(Tcl_Obj *objPtr,
51 const char *bytes, int numBytes);
52 static void DupStringInternalRep(Tcl_Obj *objPtr,
53 Tcl_Obj *copyPtr);
54 static int ExtendStringRepWithUnicode(Tcl_Obj *objPtr,
55 const Tcl_UniChar *unicode, int numChars);
56 static void ExtendUnicodeRepWithString(Tcl_Obj *objPtr,
57 const char *bytes, int numBytes,
58 int numAppendChars);
59 static void FillUnicodeRep(Tcl_Obj *objPtr);
60 static void FreeStringInternalRep(Tcl_Obj *objPtr);
61 static void GrowStringBuffer(Tcl_Obj *objPtr, int needed, int flag);
62 static void GrowUnicodeBuffer(Tcl_Obj *objPtr, int needed);
63 static int SetStringFromAny(Tcl_Interp *interp, Tcl_Obj *objPtr);
64 static void SetUnicodeObj(Tcl_Obj *objPtr,
65 const Tcl_UniChar *unicode, int numChars);
66 static int UnicodeLength(const Tcl_UniChar *unicode);
67 static void UpdateStringOfString(Tcl_Obj *objPtr);
68
69 /*
70 * The structure below defines the string Tcl object type by means of
71 * functions that can be invoked by generic object code.
72 */
73
74 const Tcl_ObjType tclStringType = {
75 "string", /* name */
76 FreeStringInternalRep, /* freeIntRepPro */
77 DupStringInternalRep, /* dupIntRepProc */
78 UpdateStringOfString, /* updateStringProc */
79 SetStringFromAny /* setFromAnyProc */
80 };
81
82 /*
83 * TCL STRING GROWTH ALGORITHM
84 *
85 * When growing strings (during an append, for example), the following growth
86 * algorithm is used:
87 *
88 * Attempt to allocate 2 * (originalLength + appendLength)
89 * On failure:
90 * attempt to allocate originalLength + 2*appendLength + TCL_MIN_GROWTH
91 *
92 * This algorithm allows very good performance, as it rapidly increases the
93 * memory allocated for a given string, which minimizes the number of
94 * reallocations that must be performed. However, using only the doubling
95 * algorithm can lead to a significant waste of memory. In particular, it may
96 * fail even when there is sufficient memory available to complete the append
97 * request (but there is not 2*totalLength memory available). So when the
98 * doubling fails (because there is not enough memory available), the
99 * algorithm requests a smaller amount of memory, which is still enough to
100 * cover the request, but which hopefully will be less than the total
101 * available memory.
102 *
103 * The addition of TCL_MIN_GROWTH allows for efficient handling of very
104 * small appends. Without this extra slush factor, a sequence of several small
105 * appends would cause several memory allocations. As long as
106 * TCL_MIN_GROWTH is a reasonable size, we can avoid that behavior.
107 *
108 * The growth algorithm can be tuned by adjusting the following parameters:
109 *
110 * TCL_MIN_GROWTH Additional space, in bytes, to allocate when
111 * the double allocation has failed. Default is
112 * 1024 (1 kilobyte). See tclInt.h.
113 */
114
115 #ifndef TCL_MIN_UNICHAR_GROWTH
116 #define TCL_MIN_UNICHAR_GROWTH TCL_MIN_GROWTH/sizeof(Tcl_UniChar)
117 #endif
118
119 static void
120 GrowStringBuffer(
121 Tcl_Obj *objPtr,
122 int needed, /* Not including terminating nul */
123 int flag) /* If 0, try to overallocate */
124 {
125 /*
126 * Preconditions:
127 * objPtr->typePtr == &tclStringType
128 * needed > stringPtr->allocated
129 * flag || objPtr->bytes != NULL
130 */
131
132 String *stringPtr = GET_STRING(objPtr);
133 char *ptr = NULL;
134 int attempt;
135
136 if (objPtr->bytes == tclEmptyStringRep) {
137 objPtr->bytes = NULL;
138 }
139 if (flag == 0 || stringPtr->allocated > 0) {
140 if (needed <= INT_MAX / 2) {
141 attempt = 2 * needed;
142 ptr = (char *)attemptckrealloc(objPtr->bytes, attempt + 1U);
143 }
144 if (ptr == NULL) {
145 /*
146 * Take care computing the amount of modest growth to avoid
147 * overflow into invalid argument values for attempt.
148 */
149
150 unsigned int limit = INT_MAX - needed;
151 unsigned int extra = needed - objPtr->length + TCL_MIN_GROWTH;
152 int growth = (int) ((extra > limit) ? limit : extra);
153
154 attempt = needed + growth;
155 ptr = (char *)attemptckrealloc(objPtr->bytes, attempt + 1U);
156 }
157 }
158 if (ptr == NULL) {
159 /*
160 * First allocation - just big enough; or last chance fallback.
161 */
162
163 attempt = needed;
164 ptr = (char *)ckrealloc(objPtr->bytes, attempt + 1U);
165 }
166 objPtr->bytes = ptr;
167 stringPtr->allocated = attempt;
168 }
169
170 static void
171 GrowUnicodeBuffer(
172 Tcl_Obj *objPtr,
173 int needed)
174 {
175 /*
176 * Preconditions:
177 * objPtr->typePtr == &tclStringType
178 * needed > stringPtr->maxChars
179 * needed < STRING_MAXCHARS
180 */
181
182 String *ptr = NULL, *stringPtr = GET_STRING(objPtr);
183 int capacity;
184
185 if (stringPtr->maxChars > 0) {
186 /*
187 * Subsequent appends - apply the growth algorithm.
188 */
189
190 if (needed <= STRING_MAXCHARS / 2) {
191 capacity = 2 * needed;
192 ptr = stringAttemptRealloc(stringPtr, capacity);
193 }
194 if (ptr == NULL) {
195 /*
196 * Take care computing the amount of modest growth to avoid
197 * overflow into invalid argument values for capacity.
198 */
199
200 unsigned int limit = STRING_MAXCHARS - needed;
201 unsigned int extra = needed - stringPtr->numChars
202 + TCL_MIN_UNICHAR_GROWTH;
203 int growth = (int) ((extra > limit) ? limit : extra);
204
205 capacity = needed + growth;
206 ptr = stringAttemptRealloc(stringPtr, capacity);
207 }
208 }
209 if (ptr == NULL) {
210 /*
211 * First allocation - just big enough; or last chance fallback.
212 */
213
214 capacity = needed;
215 ptr = stringRealloc(stringPtr, capacity);
216 }
217 stringPtr = ptr;
218 stringPtr->maxChars = capacity;
219 SET_STRING(objPtr, stringPtr);
220 }
221
222 /*
223 *----------------------------------------------------------------------
224 *
225 * Tcl_NewStringObj --
226 *
227 * This function is normally called when not debugging: i.e., when
228 * TCL_MEM_DEBUG is not defined. It creates a new string object and
229 * initializes it from the byte pointer and length arguments.
230 *
231 * When TCL_MEM_DEBUG is defined, this function just returns the result
232 * of calling the debugging version Tcl_DbNewStringObj.
233 *
234 * Results:
235 * A newly created string object is returned that has ref count zero.
236 *
237 * Side effects:
238 * The new object's internal string representation will be set to a copy
239 * of the length bytes starting at "bytes". If "length" is -1, use
240 * bytes up to the first NUL byte; i.e., assume "bytes" points to a
241 * C-style NUL-terminated string. The object's type is set to NULL. An
242 * extra NUL is added to the end of the new object's byte array.
243 *
244 *----------------------------------------------------------------------
245 */
246
247 #ifdef TCL_MEM_DEBUG
248 #undef Tcl_NewStringObj
249 Tcl_Obj *
250 Tcl_NewStringObj(
251 const char *bytes, /* Points to the first of the length bytes
252 * used to initialize the new object. */
253 int length) /* The number of bytes to copy from "bytes"
254 * when initializing the new object. If
255 * -1, use bytes up to the first NUL
256 * byte. */
257 {
258 return Tcl_DbNewStringObj(bytes, length, "unknown", 0);
259 }
260
261 /* Redefine the macro */
262 #define Tcl_NewStringObj(bytes, len) \
263 Tcl_DbNewStringObj(bytes, len, __FILE__, __LINE__)
264 #else /* if not TCL_MEM_DEBUG */
265 Tcl_Obj *
266 Tcl_NewStringObj(
267 const char *bytes, /* Points to the first of the length bytes
268 * used to initialize the new object. */
269 int length) /* The number of bytes to copy from "bytes"
270 * when initializing the new object. If -1,
271 * use bytes up to the first NUL byte. */
272 {
273 Tcl_Obj *objPtr;
274
275 if (length < 0) {
276 length = (bytes? strlen(bytes) : 0);
277 }
278 TclNewStringObj(objPtr, bytes, length);
279 return objPtr;
280 }
281 #endif /* TCL_MEM_DEBUG */
282
283 /*
284 *----------------------------------------------------------------------
285 *
286 * Tcl_DbNewStringObj --
287 *
288 * This function is normally called when debugging: i.e., when
289 * TCL_MEM_DEBUG is defined. It creates new string objects. It is the
290 * same as the Tcl_NewStringObj function above except that it calls
291 * Tcl_DbCkalloc directly with the file name and line number from its
292 * caller. This simplifies debugging since then the [memory active]
293 * command will report the correct file name and line number when
294 * reporting objects that haven't been freed.
295 *
296 * When TCL_MEM_DEBUG is not defined, this function just returns the
297 * result of calling Tcl_NewStringObj.
298 *
299 * Results:
300 * A newly created string object is returned that has ref count zero.
301 *
302 * Side effects:
303 * The new object's internal string representation will be set to a copy
304 * of the length bytes starting at "bytes". If "length" is -1, use
305 * bytes up to the first NUL byte; i.e., assume "bytes" points to a
306 * C-style NUL-terminated string. The object's type is set to NULL. An
307 * extra NUL is added to the end of the new object's byte array.
308 *
309 *----------------------------------------------------------------------
310 */
311
312 #ifdef TCL_MEM_DEBUG
313 Tcl_Obj *
314 Tcl_DbNewStringObj(
315 const char *bytes, /* Points to the first of the length bytes
316 * used to initialize the new object. */
317 int length, /* The number of bytes to copy from "bytes"
318 * when initializing the new object. If -1,
319 * use bytes up to the first NUL byte. */
320 const char *file, /* The name of the source file calling this
321 * function; used for debugging. */
322 int line) /* Line number in the source file; used for
323 * debugging. */
324 {
325 Tcl_Obj *objPtr;
326
327 if (length < 0) {
328 length = (bytes? strlen(bytes) : 0);
329 }
330 TclDbNewObj(objPtr, file, line);
331 TclInitStringRep(objPtr, bytes, length);
332 return objPtr;
333 }
334 #else /* if not TCL_MEM_DEBUG */
335 Tcl_Obj *
336 Tcl_DbNewStringObj(
337 const char *bytes, /* Points to the first of the length bytes
338 * used to initialize the new object. */
339 int length, /* The number of bytes to copy from "bytes"
340 * when initializing the new object. If -1,
341 * use bytes up to the first NUL byte. */
342 const char *file, /* The name of the source file calling this
343 * function; used for debugging. */
344 int line) /* Line number in the source file; used for
345 * debugging. */
346 {
347 return Tcl_NewStringObj(bytes, length);
348 }
349 #endif /* TCL_MEM_DEBUG */
350
351 /*
352 *---------------------------------------------------------------------------
353 *
354 * Tcl_NewUnicodeObj --
355 *
356 * This function is creates a new String object and initializes it from
357 * the given Unicode String. If the Utf String is the same size as the
358 * Unicode string, don't duplicate the data.
359 *
360 * Results:
361 * The newly created object is returned. This object will have no initial
362 * string representation. The returned object has a ref count of 0.
363 *
364 * Side effects:
365 * Memory allocated for new object and copy of Unicode argument.
366 *
367 *---------------------------------------------------------------------------
368 */
369
370 Tcl_Obj *
371 Tcl_NewUnicodeObj(
372 const Tcl_UniChar *unicode, /* The unicode string used to initialize the
373 * new object. */
374 int numChars) /* Number of characters in the unicode
375 * string. */
376 {
377 Tcl_Obj *objPtr;
378
379 TclNewObj(objPtr);
380 SetUnicodeObj(objPtr, unicode, numChars);
381 return objPtr;
382 }
383
384 /*
385 *----------------------------------------------------------------------
386 *
387 * Tcl_GetCharLength --
388 *
389 * Get the length of the Unicode string from the Tcl object.
390 *
391 * Results:
392 * Pointer to Unicode string representing the Unicode object.
393 *
394 * Side effects:
395 * Frees old internal rep. Allocates memory for new "String" internal
396 * rep.
397 *
398 *----------------------------------------------------------------------
399 */
400
401 int
402 Tcl_GetCharLength(
403 Tcl_Obj *objPtr) /* The String object to get the num chars
404 * of. */
405 {
406 String *stringPtr;
407 int numChars;
408
409 /*
410 * Quick, no-shimmer return for short string reps.
411 */
412
413 if ((objPtr->bytes) && (objPtr->length < 2)) {
414 /* 0 bytes -> 0 chars; 1 byte -> 1 char */
415 return objPtr->length;
416 }
417
418 /*
419 * Optimize the case where we're really dealing with a bytearray object;
420 * we don't need to convert to a string to perform the get-length operation.
421 *
422 * NOTE that we do not need the ByteArray to be "pure". A ByteArray value
423 * with a string rep cannot be trusted to represent the same value as the
424 * string rep, but it *can* be trusted to have the same character length
425 * as the string rep, which is all this routine cares about.
426 */
427
428 if (objPtr->typePtr == &tclByteArrayType) {
429 int length;
430
431 (void) Tcl_GetByteArrayFromObj(objPtr, &length);
432 return length;
433 }
434
435 /*
436 * OK, need to work with the object as a string.
437 */
438
439 SetStringFromAny(NULL, objPtr);
440 stringPtr = GET_STRING(objPtr);
441 numChars = stringPtr->numChars;
442
443 /*
444 * If numChars is unknown, compute it.
445 */
446
447 if (numChars == -1) {
448 TclNumUtfChars(numChars, objPtr->bytes, objPtr->length);
449 stringPtr->numChars = numChars;
450
451 }
452 return numChars;
453 }
454
455 /*
456 *----------------------------------------------------------------------
457 *
458 * TclCheckEmptyString --
459 *
460 * Determine whether the string value of an object is or would be the
461 * empty string, without generating a string representation.
462 *
463 * Results:
464 * Returns 1 if empty, 0 if not, and -1 if unknown.
465 *
466 * Side effects:
467 * None.
468 *
469 *----------------------------------------------------------------------
470 */
471 int
472 TclCheckEmptyString(
473 Tcl_Obj *objPtr)
474 {
475 int length = -1;
476
477 if (objPtr->bytes == tclEmptyStringRep) {
478 return TCL_EMPTYSTRING_YES;
479 }
480
481 if (TclIsPureList(objPtr)) {
482 TclListObjLength(NULL, objPtr, &length);
483 return length == 0;
484 }
485
486 if (TclIsPureDict(objPtr)) {
487 Tcl_DictObjSize(NULL, objPtr, &length);
488 return length == 0;
489 }
490
491 if (objPtr->bytes == NULL) {
492 return TCL_EMPTYSTRING_UNKNOWN;
493 }
494 return objPtr->length == 0;
495 }
496
497 /*
498 *----------------------------------------------------------------------
499 *
500 * Tcl_GetUniChar/TclGetUCS4 --
501 *
502 * Get the index'th Unicode character from the String object. If index
503 * is out of range, the result = 0xFFFD (Tcl_GetUniChar) resp. -1 (TclGetUCS4)
504 *
505 * Results:
506 * Returns the index'th Unicode character in the Object.
507 *
508 * Side effects:
509 * Fills unichar with the index'th Unicode character.
510 *
511 *----------------------------------------------------------------------
512 */
513
514 Tcl_UniChar
515 Tcl_GetUniChar(
516 Tcl_Obj *objPtr, /* The object to get the Unicode charater
517 * from. */
518 int index) /* Get the index'th Unicode character. */
519 {
520 String *stringPtr;
521
522 if (index < 0) {
523 return 0xFFFD;
524 }
525
526 /*
527 * Optimize the case where we're really dealing with a ByteArray object
528 * we don't need to convert to a string to perform the indexing operation.
529 */
530
531 if (TclIsPureByteArray(objPtr)) {
532 int length;
533 unsigned char *bytes = Tcl_GetByteArrayFromObj(objPtr, &length);
534 if (index >= length) {
535 return 0xFFFD;
536 }
537
538 return bytes[index];
539 }
540
541 /*
542 * OK, need to work with the object as a string.
543 */
544
545 SetStringFromAny(NULL, objPtr);
546 stringPtr = GET_STRING(objPtr);
547
548 if (stringPtr->hasUnicode == 0) {
549 /*
550 * If numChars is unknown, compute it.
551 */
552
553 if (stringPtr->numChars == -1) {
554 TclNumUtfChars(stringPtr->numChars, objPtr->bytes, objPtr->length);
555 }
556 if (index >= stringPtr->numChars) {
557 return 0xFFFD;
558 }
559 if (stringPtr->numChars == objPtr->length) {
560 return (unsigned char) objPtr->bytes[index];
561 }
562 FillUnicodeRep(objPtr);
563 stringPtr = GET_STRING(objPtr);
564 }
565
566 if (index >= stringPtr->numChars) {
567 return 0xFFFD;
568 }
569 return stringPtr->unicode[index];
570 }
571
572 #if TCL_UTF_MAX == 4
573 int
574 TclGetUCS4(
575 Tcl_Obj *objPtr, /* The object to get the Unicode character
576 * from. */
577 int index) /* Get the index'th Unicode character. */
578 {
579 String *stringPtr;
580 int ch;
581
582 if (index < 0) {
583 return -1;
584 }
585
586 /*
587 * Optimize the case where we're really dealing with a ByteArray object
588 * we don't need to convert to a string to perform the indexing operation.
589 */
590
591 if (TclIsPureByteArray(objPtr)) {
592 int length;
593 unsigned char *bytes = Tcl_GetByteArrayFromObj(objPtr, &length);
594 if (index >= length) {
595 return -1;
596 }
597
598 return bytes[index];
599 }
600
601 /*
602 * OK, need to work with the object as a string.
603 */
604
605 SetStringFromAny(NULL, objPtr);
606 stringPtr = GET_STRING(objPtr);
607
608 if (stringPtr->hasUnicode == 0) {
609 /*
610 * If numChars is unknown, compute it.
611 */
612
613 if (stringPtr->numChars == -1) {
614 TclNumUtfChars(stringPtr->numChars, objPtr->bytes, objPtr->length);
615 }
616 if (index >= stringPtr->numChars) {
617 return -1;
618 }
619 if (stringPtr->numChars == objPtr->length) {
620 return (unsigned char) objPtr->bytes[index];
621 }
622 FillUnicodeRep(objPtr);
623 stringPtr = GET_STRING(objPtr);
624 }
625
626 if (index >= stringPtr->numChars) {
627 return -1;
628 }
629 ch = stringPtr->unicode[index];
630 #if TCL_UTF_MAX <= 4
631 /* See: bug [11ae2be95dac9417] */
632 if ((ch & 0xF800) == 0xD800) {
633 if (ch & 0x400) {
634 if ((index > 0)
635 && ((stringPtr->unicode[index-1] & 0xFC00) == 0xD800)) {
636 ch = -1; /* low surrogate preceded by high surrogate */
637 }
638 } else if ((++index < stringPtr->numChars)
639 && ((stringPtr->unicode[index] & 0xFC00) == 0xDC00)) {
640 /* high surrogate followed by low surrogate */
641 ch = (((ch & 0x3FF) << 10) |
642 (stringPtr->unicode[index] & 0x3FF)) + 0x10000;
643 }
644 }
645 #endif
646 return ch;
647 }
648 #endif
649
650 /*
651 *----------------------------------------------------------------------
652 *
653 * Tcl_GetUnicode --
654 *
655 * Get the Unicode form of the String object. If the object is not
656 * already a String object, it will be converted to one. If the String
657 * object does not have a Unicode rep, then one is created from the UTF
658 * string format.
659 *
660 * Results:
661 * Returns a pointer to the object's internal Unicode string.
662 *
663 * Side effects:
664 * Converts the object to have the String internal rep.
665 *
666 *----------------------------------------------------------------------
667 */
668
669 Tcl_UniChar *
670 Tcl_GetUnicode(
671 Tcl_Obj *objPtr) /* The object to find the Unicode string
672 * for. */
673 {
674 return Tcl_GetUnicodeFromObj(objPtr, NULL);
675 }
676
677 /*
678 *----------------------------------------------------------------------
679 *
680 * Tcl_GetUnicodeFromObj --
681 *
682 * Get the Unicode form of the String object with length. If the object
683 * is not already a String object, it will be converted to one. If the
684 * String object does not have a Unicode rep, then one is create from the
685 * UTF string format.
686 *
687 * Results:
688 * Returns a pointer to the object's internal Unicode string.
689 *
690 * Side effects:
691 * Converts the object to have the String internal rep.
692 *
693 *----------------------------------------------------------------------
694 */
695
696 Tcl_UniChar *
697 Tcl_GetUnicodeFromObj(
698 Tcl_Obj *objPtr, /* The object to find the Unicode string
699 * for. */
700 int *lengthPtr) /* If non-NULL, the location where the string
701 * rep's Tcl_UniChar length should be stored. If
702 * NULL, no length is stored. */
703 {
704 String *stringPtr;
705
706 SetStringFromAny(NULL, objPtr);
707 stringPtr = GET_STRING(objPtr);
708
709 if (stringPtr->hasUnicode == 0) {
710 FillUnicodeRep(objPtr);
711 stringPtr = GET_STRING(objPtr);
712 }
713
714 if (lengthPtr != NULL) {
715 *lengthPtr = stringPtr->numChars;
716 }
717 return stringPtr->unicode;
718 }
719
720 /*
721 *----------------------------------------------------------------------
722 *
723 * Tcl_GetRange --
724 *
725 * Create a Tcl Object that contains the chars between first and last of
726 * the object indicated by "objPtr". If the object is not already a
727 * String object, convert it to one. If first is -1, the
728 * returned string start at the beginning of objPtr. If last is
729 * -1, the returned string ends at the end of objPtr.
730 *
731 * Results:
732 * Returns a new Tcl Object of the String type.
733 *
734 * Side effects:
735 * Changes the internal rep of "objPtr" to the String type.
736 *
737 *----------------------------------------------------------------------
738 */
739
740 Tcl_Obj *
741 Tcl_GetRange(
742 Tcl_Obj *objPtr, /* The Tcl object to find the range of. */
743 int first, /* First index of the range. */
744 int last) /* Last index of the range. */
745 {
746 Tcl_Obj *newObjPtr; /* The Tcl object to find the range of. */
747 String *stringPtr;
748 int length;
749
750 if (first < 0) {
751 first = 0;
752 }
753
754 /*
755 * Optimize the case where we're really dealing with a bytearray object
756 * we don't need to convert to a string to perform the substring operation.
757 */
758
759 if (TclIsPureByteArray(objPtr)) {
760 unsigned char *bytes = Tcl_GetByteArrayFromObj(objPtr, &length);
761
762 if (last < 0 || last >= length) {
763 last = length - 1;
764 }
765 if (last < first) {
766 TclNewObj(newObjPtr);
767 return newObjPtr;
768 }
769 return Tcl_NewByteArrayObj(bytes + first, last - first + 1);
770 }
771
772 /*
773 * OK, need to work with the object as a string.
774 */
775
776 SetStringFromAny(NULL, objPtr);
777 stringPtr = GET_STRING(objPtr);
778
779 if (stringPtr->hasUnicode == 0) {
780 /*
781 * If numChars is unknown, compute it.
782 */
783
784 if (stringPtr->numChars == -1) {
785 TclNumUtfChars(stringPtr->numChars, objPtr->bytes, objPtr->length);
786 }
787 if (stringPtr->numChars == objPtr->length) {
788 if (last < 0 || last >= stringPtr->numChars) {
789 last = stringPtr->numChars - 1;
790 }
791 if (last < first) {
792 TclNewObj(newObjPtr);
793 return newObjPtr;
794 }
795 newObjPtr = Tcl_NewStringObj(objPtr->bytes + first, last - first + 1);
796
797 /*
798 * Since we know the char length of the result, store it.
799 */
800
801 SetStringFromAny(NULL, newObjPtr);
802 stringPtr = GET_STRING(newObjPtr);
803 stringPtr->numChars = newObjPtr->length;
804 return newObjPtr;
805 }
806 FillUnicodeRep(objPtr);
807 stringPtr = GET_STRING(objPtr);
808 }
809 if (last < 0 || last >= stringPtr->numChars) {
810 last = stringPtr->numChars - 1;
811 }
812 if (last < first) {
813 TclNewObj(newObjPtr);
814 return newObjPtr;
815 }
816 #if TCL_UTF_MAX == 4
817 /* See: bug [11ae2be95dac9417] */
818 if ((first > 0) && ((stringPtr->unicode[first] & 0xFC00) == 0xDC00)
819 && ((stringPtr->unicode[first-1] & 0xFC00) == 0xD800)) {
820 ++first;
821 }
822 if ((last + 1 < stringPtr->numChars)
823 && ((stringPtr->unicode[last+1] & 0xFC00) == 0xDC00)
824 && ((stringPtr->unicode[last] & 0xFC00) == 0xD800)) {
825 ++last;
826 }
827 #endif
828 return Tcl_NewUnicodeObj(stringPtr->unicode + first, last - first + 1);
829 }
830
831 /*
832 *----------------------------------------------------------------------
833 *
834 * Tcl_SetStringObj --
835 *
836 * Modify an object to hold a string that is a copy of the bytes
837 * indicated by the byte pointer and length arguments.
838 *
839 * Results:
840 * None.
841 *
842 * Side effects:
843 * The object's string representation will be set to a copy of the
844 * "length" bytes starting at "bytes". If "length" is -1, use bytes
845 * up to the first NUL byte; i.e., assume "bytes" points to a C-style
846 * NUL-terminated string. The object's old string and internal
847 * representations are freed and the object's type is set NULL.
848 *
849 *----------------------------------------------------------------------
850 */
851
852 void
853 Tcl_SetStringObj(
854 Tcl_Obj *objPtr, /* Object whose internal rep to init. */
855 const char *bytes, /* Points to the first of the length bytes
856 * used to initialize the object. */
857 int length) /* The number of bytes to copy from "bytes"
858 * when initializing the object. If -1,
859 * use bytes up to the first NUL byte.*/
860 {
861 if (Tcl_IsShared(objPtr)) {
862 Tcl_Panic("%s called with shared object", "Tcl_SetStringObj");
863 }
864
865 /*
866 * Set the type to NULL and free any internal rep for the old type.
867 */
868
869 TclFreeIntRep(objPtr);
870
871 /*
872 * Free any old string rep, then set the string rep to a copy of the
873 * length bytes starting at "bytes".
874 */
875
876 TclInvalidateStringRep(objPtr);
877 if (length < 0) {
878 length = (bytes? strlen(bytes) : 0);
879 }
880 TclInitStringRep(objPtr, bytes, length);
881 }
882
883 /*
884 *----------------------------------------------------------------------
885 *
886 * Tcl_SetObjLength --
887 *
888 * Changes the length of the string representation of objPtr.
889 *
890 * Results:
891 * None.
892 *
893 * Side effects:
894 * If the size of objPtr's string representation is greater than length, a
895 * new terminating null byte is stored in objPtr->bytes at length, and
896 * bytes at positions past length have no meaning. If the length of the
897 * string representation is greater than length, the storage space is
898 * reallocated to length+1.
899 *
900 * The object's internal representation is changed to &tclStringType.
901 *
902 *----------------------------------------------------------------------
903 */
904
905 void
906 Tcl_SetObjLength(
907 Tcl_Obj *objPtr, /* Pointer to object. This object must not
908 * currently be shared. */
909 int length) /* Number of bytes desired for string
910 * representation of object, not including
911 * terminating null byte. */
912 {
913 String *stringPtr;
914
915 if (length < 0) {
916 Tcl_Panic("Tcl_SetObjLength: negative length requested: "
917 "%d (integer overflow?)", length);
918 }
919 if (Tcl_IsShared(objPtr)) {
920 Tcl_Panic("%s called with shared object", "Tcl_SetObjLength");
921 }
922
923 if (objPtr->bytes && objPtr->length == length) {
924 return;
925 }
926
927 SetStringFromAny(NULL, objPtr);
928 stringPtr = GET_STRING(objPtr);
929
930 if (objPtr->bytes != NULL) {
931 /*
932 * Change length of an existing string rep.
933 */
934 if (length > stringPtr->allocated) {
935 /*
936 * Need to enlarge the buffer.
937 */
938 if (objPtr->bytes == tclEmptyStringRep) {
939 objPtr->bytes = (char *)ckalloc((unsigned int)length + 1U);
940 } else {
941 objPtr->bytes = (char *)ckrealloc(objPtr->bytes, (unsigned int)length + 1U);
942 }
943 stringPtr->allocated = length;
944 }
945
946 objPtr->length = length;
947 objPtr->bytes[length] = 0;
948
949 /*
950 * Invalidate the Unicode data.
951 */
952
953 stringPtr->numChars = -1;
954 stringPtr->hasUnicode = 0;
955 } else {
956 /*
957 * Changing length of pure unicode string.
958 */
959
960 stringCheckLimits(length);
961 if (length > stringPtr->maxChars) {
962 stringPtr = stringRealloc(stringPtr, length);
963 SET_STRING(objPtr, stringPtr);
964 stringPtr->maxChars = length;
965 }
966
967 /*
968 * Mark the new end of the Unicode string
969 */
970
971 stringPtr->numChars = length;
972 stringPtr->unicode[length] = 0;
973 stringPtr->hasUnicode = 1;
974
975 /*
976 * Can only get here when objPtr->bytes == NULL. No need to invalidate
977 * the string rep.
978 */
979 }
980 }
981
982 /*
983 *----------------------------------------------------------------------
984 *
985 * Tcl_AttemptSetObjLength --
986 *
987 * This function changes the length of the string representation of an
988 * object. It uses the attempt* (non-panic'ing) memory allocators.
989 *
990 * Results:
991 * 1 if the requested memory was allocated, 0 otherwise.
992 *
993 * Side effects:
994 * If the size of objPtr's string representation is greater than length,
995 * then it is reduced to length and a new terminating null byte is stored
996 * in the strength. If the length of the string representation is greater
997 * than length, the storage space is reallocated to the given length; a
998 * null byte is stored at the end, but other bytes past the end of the
999 * original string representation are undefined. The object's internal
1000 * representation is changed to "expendable string".
1001 *
1002 *----------------------------------------------------------------------
1003 */
1004
1005 int
1006 Tcl_AttemptSetObjLength(
1007 Tcl_Obj *objPtr, /* Pointer to object. This object must not
1008 * currently be shared. */
1009 int length) /* Number of bytes desired for string
1010 * representation of object, not including
1011 * terminating null byte. */
1012 {
1013 String *stringPtr;
1014
1015 if (length < 0) {
1016 /* Negative lengths => most likely integer overflow */
1017 return 0;
1018 }
1019
1020 if (Tcl_IsShared(objPtr)) {
1021 Tcl_Panic("%s called with shared object", "Tcl_AttemptSetObjLength");
1022 }
1023 if (objPtr->bytes && objPtr->length == length) {
1024 return 1;
1025 }
1026
1027 SetStringFromAny(NULL, objPtr);
1028 stringPtr = GET_STRING(objPtr);
1029
1030 if (objPtr->bytes != NULL) {
1031 /*
1032 * Change length of an existing string rep.
1033 */
1034 if (length > stringPtr->allocated) {
1035 /*
1036 * Need to enlarge the buffer.
1037 */
1038
1039 char *newBytes;
1040
1041 if (objPtr->bytes == tclEmptyStringRep) {
1042 newBytes = (char *)attemptckalloc((unsigned int)length + 1U);
1043 } else {
1044 newBytes = (char *)attemptckrealloc(objPtr->bytes, (unsigned int)length + 1U);
1045 }
1046 if (newBytes == NULL) {
1047 return 0;
1048 }
1049 objPtr->bytes = newBytes;
1050 stringPtr->allocated = length;
1051 }
1052
1053 objPtr->length = length;
1054 objPtr->bytes[length] = 0;
1055
1056 /*
1057 * Invalidate the Unicode data.
1058 */
1059
1060 stringPtr->numChars = -1;
1061 stringPtr->hasUnicode = 0;
1062 } else {
1063 /*
1064 * Changing length of pure Unicode string.
1065 */
1066
1067 if (length > STRING_MAXCHARS) {
1068 return 0;
1069 }
1070 if (length > stringPtr->maxChars) {
1071 stringPtr = stringAttemptRealloc(stringPtr, length);
1072 if (stringPtr == NULL) {
1073 return 0;
1074 }
1075 SET_STRING(objPtr, stringPtr);
1076 stringPtr->maxChars = length;
1077 }
1078
1079 /*
1080 * Mark the new end of the Unicode string.
1081 */
1082
1083 stringPtr->unicode[length] = 0;
1084 stringPtr->numChars = length;
1085 stringPtr->hasUnicode = 1;
1086
1087 /*
1088 * Can only get here when objPtr->bytes == NULL. No need to invalidate
1089 * the string rep.
1090 */
1091 }
1092 return 1;
1093 }
1094
1095 /*
1096 *---------------------------------------------------------------------------
1097 *
1098 * Tcl_SetUnicodeObj --
1099 *
1100 * Modify an object to hold the Unicode string indicated by "unicode".
1101 *
1102 * Results:
1103 * None.
1104 *
1105 * Side effects:
1106 * Memory allocated for new "String" internal rep.
1107 *
1108 *---------------------------------------------------------------------------
1109 */
1110
1111 void
1112 Tcl_SetUnicodeObj(
1113 Tcl_Obj *objPtr, /* The object to set the string of. */
1114 const Tcl_UniChar *unicode, /* The Unicode string used to initialize the
1115 * object. */
1116 int numChars) /* Number of characters in the Unicode
1117 * string. */
1118 {
1119 if (Tcl_IsShared(objPtr)) {
1120 Tcl_Panic("%s called with shared object", "Tcl_SetUnicodeObj");
1121 }
1122 TclFreeIntRep(objPtr);
1123 SetUnicodeObj(objPtr, unicode, numChars);
1124 }
1125
1126 static int
1127 UnicodeLength(
1128 const Tcl_UniChar *unicode)
1129 {
1130 int numChars = 0;
1131
1132 if (unicode) {
1133 while ((numChars >= 0) && (unicode[numChars] != 0)) {
1134 numChars++;
1135 }
1136 }
1137 stringCheckLimits(numChars);
1138 return numChars;
1139 }
1140
1141 static void
1142 SetUnicodeObj(
1143 Tcl_Obj *objPtr, /* The object to set the string of. */
1144 const Tcl_UniChar *unicode, /* The Unicode string used to initialize the
1145 * object. */
1146 int numChars) /* Number of characters in the Unicode
1147 * string. */
1148 {
1149 String *stringPtr;
1150
1151 if (numChars < 0) {
1152 numChars = UnicodeLength(unicode);
1153 }
1154
1155 /*
1156 * Allocate enough space for the String structure + Unicode string.
1157 */
1158
1159 stringCheckLimits(numChars);
1160 stringPtr = stringAlloc(numChars);
1161 SET_STRING(objPtr, stringPtr);
1162 objPtr->typePtr = &tclStringType;
1163
1164 stringPtr->maxChars = numChars;
1165 memcpy(stringPtr->unicode, unicode, numChars * sizeof(Tcl_UniChar));
1166 stringPtr->unicode[numChars] = 0;
1167 stringPtr->numChars = numChars;
1168 stringPtr->hasUnicode = 1;
1169
1170 TclInvalidateStringRep(objPtr);
1171 stringPtr->allocated = 0;
1172 }
1173
1174 /*
1175 *----------------------------------------------------------------------
1176 *
1177 * Tcl_AppendLimitedToObj --
1178 *
1179 * This function appends a limited number of bytes from a sequence of
1180 * bytes to an object, marking any limitation with an ellipsis.
1181 *
1182 * Results:
1183 * None.
1184 *
1185 * Side effects:
1186 * The bytes at *bytes are appended to the string representation of
1187 * objPtr.
1188 *
1189 *----------------------------------------------------------------------
1190 */
1191
1192 void
1193 Tcl_AppendLimitedToObj(
1194 Tcl_Obj *objPtr, /* Points to the object to append to. */
1195 const char *bytes, /* Points to the bytes to append to the
1196 * object. */
1197 int length, /* The number of bytes available to be
1198 * appended from "bytes". If -1, then
1199 * all bytes up to a NUL byte are available. */
1200 int limit, /* The maximum number of bytes to append to
1201 * the object. */
1202 const char *ellipsis) /* Ellipsis marker string, appended to the
1203 * object to indicate not all available bytes
1204 * at "bytes" were appended. */
1205 {
1206 String *stringPtr;
1207 int toCopy = 0;
1208 int eLen = 0;
1209
1210 if (length < 0) {
1211 length = (bytes ? strlen(bytes) : 0);
1212 }
1213 if (length == 0) {
1214 return;
1215 }
1216 if (limit <= 0) {
1217 return;
1218 }
1219
1220 if (length <= limit) {
1221 toCopy = length;
1222 } else {
1223 if (ellipsis == NULL) {
1224 ellipsis = "...";
1225 }
1226 eLen = strlen(ellipsis);
1227 while (eLen > limit) {
1228 eLen = TclUtfPrev(ellipsis+eLen, ellipsis) - ellipsis;
1229 }
1230
1231 toCopy = TclUtfPrev(bytes+limit+1-eLen, bytes) - bytes;
1232 }
1233
1234 /*
1235 * If objPtr has a valid Unicode rep, then append the Unicode conversion
1236 * of "bytes" to the objPtr's Unicode rep, otherwise append "bytes" to
1237 * objPtr's string rep.
1238 */
1239
1240 if (Tcl_IsShared(objPtr)) {
1241 Tcl_Panic("%s called with shared object", "Tcl_AppendLimitedToObj");
1242 }
1243
1244 SetStringFromAny(NULL, objPtr);
1245 stringPtr = GET_STRING(objPtr);
1246
1247 if (stringPtr->hasUnicode && stringPtr->numChars > 0) {
1248 AppendUtfToUnicodeRep(objPtr, bytes, toCopy);
1249 } else {
1250 AppendUtfToUtfRep(objPtr, bytes, toCopy);
1251 }
1252
1253 if (length <= limit) {
1254 return;
1255 }
1256
1257 stringPtr = GET_STRING(objPtr);
1258 if (stringPtr->hasUnicode && (stringPtr->numChars > 0)) {
1259 AppendUtfToUnicodeRep(objPtr, ellipsis, eLen);
1260 } else {
1261 AppendUtfToUtfRep(objPtr, ellipsis, eLen);
1262 }
1263 }
1264
1265 /*
1266 *----------------------------------------------------------------------
1267 *
1268 * Tcl_AppendToObj --
1269 *
1270 * This function appends a sequence of bytes to an object.
1271 *
1272 * Results:
1273 * None.
1274 *
1275 * Side effects:
1276 * The bytes at *bytes are appended to the string representation of
1277 * objPtr.
1278 *
1279 *----------------------------------------------------------------------
1280 */
1281
1282 void
1283 Tcl_AppendToObj(
1284 Tcl_Obj *objPtr, /* Points to the object to append to. */
1285 const char *bytes, /* Points to the bytes to append to the
1286 * object. */
1287 int length) /* The number of bytes to append from "bytes".
1288 * If < 0, then append all bytes up to NUL
1289 * byte. */
1290 {
1291 Tcl_AppendLimitedToObj(objPtr, bytes, length, INT_MAX, NULL);
1292 }
1293
1294 /*
1295 *----------------------------------------------------------------------
1296 *
1297 * Tcl_AppendUnicodeToObj --
1298 *
1299 * This function appends a Unicode string to an object in the most
1300 * efficient manner possible. Length must be >= 0.
1301 *
1302 * Results:
1303 * None.
1304 *
1305 * Side effects:
1306 * Invalidates the string rep and creates a new Unicode string.
1307 *
1308 *----------------------------------------------------------------------
1309 */
1310
1311 void
1312 Tcl_AppendUnicodeToObj(
1313 Tcl_Obj *objPtr, /* Points to the object to append to. */
1314 const Tcl_UniChar *unicode, /* The Unicode string to append to the
1315 * object. */
1316 int length) /* Number of chars in unicode. */
1317 {
1318 String *stringPtr;
1319
1320 if (Tcl_IsShared(objPtr)) {
1321 Tcl_Panic("%s called with shared object", "Tcl_AppendUnicodeToObj");
1322 }
1323
1324 if (length == 0) {
1325 return;
1326 }
1327
1328 SetStringFromAny(NULL, objPtr);
1329 stringPtr = GET_STRING(objPtr);
1330
1331 /*
1332 * If objPtr has a valid Unicode rep, then append unicode to the
1333 * objPtr's Unicode rep, otherwise the UTF conversion of unicode to
1334 * objPtr's string rep.
1335 */
1336
1337 if (stringPtr->hasUnicode) {
1338 AppendUnicodeToUnicodeRep(objPtr, unicode, length);
1339 } else {
1340 AppendUnicodeToUtfRep(objPtr, unicode, length);
1341 }
1342 }
1343
1344 /*
1345 *----------------------------------------------------------------------
1346 *
1347 * Tcl_AppendObjToObj --
1348 *
1349 * This function appends the string rep of one object to another.
1350 * "objPtr" cannot be a shared object.
1351 *
1352 * Results:
1353 * None.
1354 *
1355 * Side effects:
1356 * The string rep of appendObjPtr is appended to the string
1357 * representation of objPtr.
1358 * IMPORTANT: This routine does not and MUST NOT shimmer appendObjPtr.
1359 * Callers are counting on that.
1360 *
1361 *----------------------------------------------------------------------
1362 */
1363
1364 void
1365 Tcl_AppendObjToObj(
1366 Tcl_Obj *objPtr, /* Points to the object to append to. */
1367 Tcl_Obj *appendObjPtr) /* Object to append. */
1368 {
1369 String *stringPtr;
1370 int length, numChars, appendNumChars = -1;
1371 const char *bytes;
1372
1373 /*
1374 * Special case: second object is standard-empty is fast case. We know
1375 * that appending nothing to anything leaves that starting anything...
1376 */
1377
1378 if (appendObjPtr->bytes == tclEmptyStringRep) {
1379 return;
1380 }
1381
1382 /*
1383 * Handle append of one ByteArray object to another as a special case.
1384 * Note that we only do this when the objects don't have string reps; if
1385 * it did, then appending the byte arrays together could well lose
1386 * information; this is a special-case optimization only.
1387 */
1388
1389 if ((TclIsPureByteArray(objPtr) || objPtr->bytes == tclEmptyStringRep)
1390 && TclIsPureByteArray(appendObjPtr)) {
1391 /*
1392 * One might expect the code here to be
1393 *
1394 * bytes = Tcl_GetByteArrayFromObj(appendObjPtr, &length);
1395 * TclAppendBytesToByteArray(objPtr, bytes, length);
1396 *
1397 * and essentially all of the time that would be fine. However, it
1398 * would run into trouble in the case where objPtr and appendObjPtr
1399 * point to the same thing. That may never be a good idea. It seems to
1400 * violate Copy On Write, and we don't have any tests for the
1401 * situation, since making any Tcl commands that call
1402 * Tcl_AppendObjToObj() do that appears impossible (They honor Copy On
1403 * Write!). For the sake of extensions that go off into that realm,
1404 * though, here's a more complex approach that can handle all the
1405 * cases.
1406 *
1407 * First, get the lengths.
1408 */
1409
1410 int lengthSrc;
1411
1412 (void) Tcl_GetByteArrayFromObj(objPtr, &length);
1413 (void) Tcl_GetByteArrayFromObj(appendObjPtr, &lengthSrc);
1414
1415 /*
1416 * Grow buffer enough for the append.
1417 */
1418
1419 TclAppendBytesToByteArray(objPtr, NULL, lengthSrc);
1420
1421 /*
1422 * Reset objPtr back to the original value.
1423 */
1424
1425 Tcl_SetByteArrayLength(objPtr, length);
1426
1427 /*
1428 * Now do the append knowing that buffer growth cannot cause any
1429 * trouble.
1430 */
1431
1432 TclAppendBytesToByteArray(objPtr,
1433 Tcl_GetByteArrayFromObj(appendObjPtr, NULL), lengthSrc);
1434 return;
1435 }
1436
1437 /*
1438 * Must append as strings.
1439 */
1440
1441 SetStringFromAny(NULL, objPtr);
1442 stringPtr = GET_STRING(objPtr);
1443
1444 /*
1445 * If objPtr has a valid Unicode rep, then get a Unicode string from
1446 * appendObjPtr and append it.
1447 */
1448
1449 if (stringPtr->hasUnicode) {
1450 /*
1451 * If appendObjPtr is not of the "String" type, don't convert it.
1452 */
1453
1454 if (appendObjPtr->typePtr == &tclStringType) {
1455 Tcl_UniChar *unicode =
1456 Tcl_GetUnicodeFromObj(appendObjPtr, &numChars);
1457
1458 AppendUnicodeToUnicodeRep(objPtr, unicode, numChars);
1459 } else {
1460 bytes = TclGetStringFromObj(appendObjPtr, &length);
1461 AppendUtfToUnicodeRep(objPtr, bytes, length);
1462 }
1463 return;
1464 }
1465
1466 /*
1467 * Append to objPtr's UTF string rep. If we know the number of characters
1468 * in both objects before appending, then set the combined number of
1469 * characters in the final (appended-to) object.
1470 */
1471
1472 bytes = TclGetStringFromObj(appendObjPtr, &length);
1473
1474 numChars = stringPtr->numChars;
1475 if ((numChars >= 0) && (appendObjPtr->typePtr == &tclStringType)) {
1476 String *appendStringPtr = GET_STRING(appendObjPtr);
1477
1478 appendNumChars = appendStringPtr->numChars;
1479 }
1480
1481 AppendUtfToUtfRep(objPtr, bytes, length);
1482
1483 if ((numChars >= 0) && (appendNumChars >= 0)) {
1484 stringPtr->numChars = numChars + appendNumChars;
1485 }
1486 }
1487
1488 /*
1489 *----------------------------------------------------------------------
1490 *
1491 * AppendUnicodeToUnicodeRep --
1492 *
1493 * Appends the contents of unicode to the Unicode rep of
1494 * objPtr, which must already have a valid Unicode rep.
1495 *
1496 * Results:
1497 * None.
1498 *
1499 * Side effects:
1500 * objPtr's internal rep is reallocated.
1501 *
1502 *----------------------------------------------------------------------
1503 */
1504
1505 static void
1506 AppendUnicodeToUnicodeRep(
1507 Tcl_Obj *objPtr, /* Points to the object to append to. */
1508 const Tcl_UniChar *unicode, /* String to append. */
1509 int appendNumChars) /* Number of chars of "unicode" to append. */
1510 {
1511 String *stringPtr;
1512 int numChars;
1513
1514 if (appendNumChars < 0) {
1515 appendNumChars = UnicodeLength(unicode);
1516 }
1517 if (appendNumChars == 0) {
1518 return;
1519 }
1520
1521 SetStringFromAny(NULL, objPtr);
1522 stringPtr = GET_STRING(objPtr);
1523
1524 /*
1525 * If not enough space has been allocated for the Unicode rep, reallocate
1526 * the internal rep object with additional space. First try to double the
1527 * required allocation; if that fails, try a more modest increase. See the
1528 * "TCL STRING GROWTH ALGORITHM" comment at the top of this file for an
1529 * explanation of this growth algorithm.
1530 */
1531
1532 numChars = stringPtr->numChars + appendNumChars;
1533 stringCheckLimits(numChars);
1534
1535 if (numChars > stringPtr->maxChars) {
1536 int offset = -1;
1537
1538 /*
1539 * Protect against case where Unicode points into the existing
1540 * stringPtr->unicode array. Force it to follow any relocations due to
1541 * the reallocs below.
1542 */
1543
1544 if (unicode && unicode >= stringPtr->unicode
1545 && unicode <= stringPtr->unicode + stringPtr->maxChars) {
1546 offset = unicode - stringPtr->unicode;
1547 }
1548
1549 GrowUnicodeBuffer(objPtr, numChars);
1550 stringPtr = GET_STRING(objPtr);
1551
1552 /*
1553 * Relocate Unicode if needed; see above.
1554 */
1555
1556 if (offset >= 0) {
1557 unicode = stringPtr->unicode + offset;
1558 }
1559 }
1560
1561 /*
1562 * Copy the new string onto the end of the old string, then add the
1563 * trailing null.
1564 */
1565
1566 if (unicode) {
1567 memmove(stringPtr->unicode + stringPtr->numChars, unicode,
1568 appendNumChars * sizeof(Tcl_UniChar));
1569 }
1570 stringPtr->unicode[numChars] = 0;
1571 stringPtr->numChars = numChars;
1572 stringPtr->allocated = 0;
1573
1574 TclInvalidateStringRep(objPtr);
1575 }
1576
1577 /*
1578 *----------------------------------------------------------------------
1579 *
1580 * AppendUnicodeToUtfRep --
1581 *
1582 * This function converts the contents of "unicode" to UTF and appends
1583 * the UTF to the string rep of "objPtr".
1584 *
1585 * Results:
1586 * None.
1587 *
1588 * Side effects:
1589 * objPtr's internal rep is reallocated.
1590 *
1591 *----------------------------------------------------------------------
1592 */
1593
1594 static void
1595 AppendUnicodeToUtfRep(
1596 Tcl_Obj *objPtr, /* Points to the object to append to. */
1597 const Tcl_UniChar *unicode, /* String to convert to UTF. */
1598 int numChars) /* Number of chars of Unicode to convert. */
1599 {
1600 String *stringPtr = GET_STRING(objPtr);
1601
1602 numChars = ExtendStringRepWithUnicode(objPtr, unicode, numChars);
1603
1604 if (stringPtr->numChars != -1) {
1605 stringPtr->numChars += numChars;
1606 }
1607 }
1608
1609 /*
1610 *----------------------------------------------------------------------
1611 *
1612 * AppendUtfToUnicodeRep --
1613 *
1614 * This function converts the contents of "bytes" to Unicode and appends
1615 * the Unicode to the Unicode rep of "objPtr". objPtr must already have a
1616 * valid Unicode rep. numBytes must be non-negative.
1617 *
1618 * Results:
1619 * None.
1620 *
1621 * Side effects:
1622 * objPtr's internal rep is reallocated and string rep is cleaned.
1623 *
1624 *----------------------------------------------------------------------
1625 */
1626
1627 static void
1628 AppendUtfToUnicodeRep(
1629 Tcl_Obj *objPtr, /* Points to the object to append to. */
1630 const char *bytes, /* String to convert to Unicode. */
1631 int numBytes) /* Number of bytes of "bytes" to convert. */
1632 {
1633 String *stringPtr;
1634
1635 if (numBytes == 0) {
1636 return;
1637 }
1638
1639 ExtendUnicodeRepWithString(objPtr, bytes, numBytes, -1);
1640 TclInvalidateStringRep(objPtr);
1641 stringPtr = GET_STRING(objPtr);
1642 stringPtr->allocated = 0;
1643 }
1644
1645 /*
1646 *----------------------------------------------------------------------
1647 *
1648 * AppendUtfToUtfRep --
1649 *
1650 * This function appends "numBytes" bytes of "bytes" to the UTF string
1651 * rep of "objPtr". objPtr must already have a valid String rep.
1652 * numBytes must be non-negative.
1653 *
1654 * Results:
1655 * None.
1656 *
1657 * Side effects:
1658 * objPtr's string rep is reallocated (by TCL STRING GROWTH ALGORITHM).
1659 *
1660 *----------------------------------------------------------------------
1661 */
1662
1663 static void
1664 AppendUtfToUtfRep(
1665 Tcl_Obj *objPtr, /* Points to the object to append to. */
1666 const char *bytes, /* String to append. */
1667 int numBytes) /* Number of bytes of "bytes" to append. */
1668 {
1669 String *stringPtr;
1670 int newLength, oldLength;
1671
1672 if (numBytes == 0) {
1673 return;
1674 }
1675
1676 /*
1677 * Copy the new string onto the end of the old string, then add the
1678 * trailing null.
1679 */
1680
1681 if (objPtr->bytes == NULL) {
1682 objPtr->length = 0;
1683 }
1684 oldLength = objPtr->length;
1685 if (numBytes > INT_MAX - oldLength) {
1686 Tcl_Panic("max size for a Tcl value (%d bytes) exceeded", INT_MAX);
1687 }
1688 newLength = numBytes + oldLength;
1689
1690 stringPtr = GET_STRING(objPtr);
1691 if (newLength > stringPtr->allocated) {
1692 int offset = -1;
1693
1694 /*
1695 * Protect against case where unicode points into the existing
1696 * stringPtr->unicode array. Force it to follow any relocations due to
1697 * the reallocs below.
1698 */
1699
1700 if (bytes && objPtr->bytes && (bytes >= objPtr->bytes)
1701 && (bytes <= objPtr->bytes + objPtr->length)) {
1702 offset = bytes - objPtr->bytes;
1703 }
1704
1705 /*
1706 * TODO: consider passing flag=1: no overalloc on first append. This
1707 * would make test stringObj-8.1 fail.
1708 */
1709
1710 GrowStringBuffer(objPtr, newLength, 0);
1711
1712 /*
1713 * Relocate bytes if needed; see above.
1714 */
1715
1716 if (offset >= 0) {
1717 bytes = objPtr->bytes + offset;
1718 }
1719 }
1720
1721 /*
1722 * Invalidate the unicode data.
1723 */
1724
1725 stringPtr->numChars = -1;
1726 stringPtr->hasUnicode = 0;
1727
1728 if (bytes) {
1729 memmove(objPtr->bytes + oldLength, bytes, numBytes);
1730 }
1731 objPtr->bytes[newLength] = 0;
1732 objPtr->length = newLength;
1733 }
1734
1735 /*
1736 *----------------------------------------------------------------------
1737 *
1738 * TclAppendUtfToUtf --
1739 *
1740 * This function appends "numBytes" bytes of "bytes" to the UTF string
1741 * rep of "objPtr" (objPtr's internal rep converted to string on demand).
1742 * numBytes must be non-negative.
1743 *
1744 * Results:
1745 * None.
1746 *
1747 * Side effects:
1748 * objPtr's string rep is reallocated (by TCL STRING GROWTH ALGORITHM).
1749 *
1750 *----------------------------------------------------------------------
1751 */
1752
1753 void
1754 TclAppendUtfToUtf(
1755 Tcl_Obj *objPtr, /* Points to the object to append to. */
1756 const char *bytes, /* String to append (or NULL to enlarge buffer). */
1757 int numBytes) /* Number of bytes of "bytes" to append. */
1758 {
1759 if (Tcl_IsShared(objPtr)) {
1760 Tcl_Panic("%s called with shared object", "TclAppendUtfToUtf");
1761 }
1762
1763 SetStringFromAny(NULL, objPtr);
1764
1765 AppendUtfToUtfRep(objPtr, bytes, numBytes);
1766 }
1767
1768 /*
1769 *----------------------------------------------------------------------
1770 *
1771 * Tcl_AppendStringsToObjVA --
1772 *
1773 * This function appends one or more null-terminated strings to an
1774 * object.
1775 *
1776 * Results:
1777 * None.
1778 *
1779 * Side effects:
1780 * The contents of all the string arguments are appended to the string
1781 * representation of objPtr.
1782 *
1783 *----------------------------------------------------------------------
1784 */
1785
1786 void
1787 Tcl_AppendStringsToObjVA(
1788 Tcl_Obj *objPtr, /* Points to the object to append to. */
1789 va_list argList) /* Variable argument list. */
1790 {
1791 if (Tcl_IsShared(objPtr)) {
1792 Tcl_Panic("%s called with shared object", "Tcl_AppendStringsToObj");
1793 }
1794
1795 while (1) {
1796 const char *bytes = va_arg(argList, char *);
1797
1798 if (bytes == NULL) {
1799 break;
1800 }
1801 Tcl_AppendToObj(objPtr, bytes, -1);
1802 }
1803 }
1804
1805 /*
1806 *----------------------------------------------------------------------
1807 *
1808 * Tcl_AppendStringsToObj --
1809 *
1810 * This function appends one or more null-terminated strings to an
1811 * object.
1812 *
1813 * Results:
1814 * None.
1815 *
1816 * Side effects:
1817 * The contents of all the string arguments are appended to the string
1818 * representation of objPtr.
1819 *
1820 *----------------------------------------------------------------------
1821 */
1822
1823 void
1824 Tcl_AppendStringsToObj(
1825 Tcl_Obj *objPtr,
1826 ...)
1827 {
1828 va_list argList;
1829
1830 va_start(argList, objPtr);
1831 Tcl_AppendStringsToObjVA(objPtr, argList);
1832 va_end(argList);
1833 }
1834
1835 /*
1836 *----------------------------------------------------------------------
1837 *
1838 * Tcl_AppendFormatToObj --
1839 *
1840 * This function appends a list of Tcl_Obj's to a Tcl_Obj according to
1841 * the formatting instructions embedded in the format string. The
1842 * formatting instructions are inspired by sprintf(). Returns TCL_OK when
1843 * successful. If there's an error in the arguments, TCL_ERROR is
1844 * returned, and an error message is written to the interp, if non-NULL.
1845 *
1846 * Results:
1847 * A standard Tcl result.
1848 *
1849 * Side effects:
1850 * None.
1851 *
1852 *----------------------------------------------------------------------
1853 */
1854
1855 int
1856 Tcl_AppendFormatToObj(
1857 Tcl_Interp *interp,
1858 Tcl_Obj *appendObj,
1859 const char *format,
1860 int objc,
1861 Tcl_Obj *const objv[])
1862 {
1863 const char *span = format, *msg, *errCode;
1864 int gotXpg = 0, gotSequential = 0;
1865 int objIndex = 0, originalLength, limit, numBytes = 0;
1866 Tcl_UniChar ch = 0;
1867 static const char *mixedXPG =
1868 "cannot mix \"%\" and \"%n$\" conversion specifiers";
1869 static const char *const badIndex[2] = {
1870 "not enough arguments for all format specifiers",
1871 "\"%n$\" argument index out of range"
1872 };
1873 static const char *overflow = "max size for a Tcl value exceeded";
1874
1875 if (Tcl_IsShared(appendObj)) {
1876 Tcl_Panic("%s called with shared object", "Tcl_AppendFormatToObj");
1877 }
1878 (void)TclGetStringFromObj(appendObj, &originalLength);
1879 limit = INT_MAX - originalLength;
1880
1881 /*
1882 * Format string is NUL-terminated.
1883 */
1884
1885 while (*format != '\0') {
1886 char *end;
1887 int gotMinus = 0, gotHash = 0, gotZero = 0, gotSpace = 0, gotPlus = 0;
1888 int gotPrecision, sawFlag, useShort = 0, useBig = 0;
1889 int width, precision;
1890 #ifndef TCL_WIDE_INT_IS_LONG
1891 int useWide = 0;
1892 #endif
1893 int newXpg, allocSegment = 0;
1894 int numChars, segmentLimit, segmentNumBytes;
1895 Tcl_Obj *segment;
1896 int step = TclUtfToUniChar(format, &ch);
1897
1898 format += step;
1899 if (ch != '%') {
1900 numBytes += step;
1901 continue;
1902 }
1903 if (numBytes) {
1904 if (numBytes > limit) {
1905 msg = overflow;
1906 errCode = "OVERFLOW";
1907 goto errorMsg;
1908 }
1909 Tcl_AppendToObj(appendObj, span, numBytes);
1910 limit -= numBytes;
1911 numBytes = 0;
1912 }
1913
1914 /*
1915 * Saw a % : process the format specifier.
1916 *
1917 * Step 0. Handle special case of escaped format marker (i.e., %%).
1918 */
1919
1920 step = TclUtfToUniChar(format, &ch);
1921 if (ch == '%') {
1922 span = format;
1923 numBytes = step;
1924 format += step;
1925 continue;
1926 }
1927
1928 /*
1929 * Step 1. XPG3 position specifier
1930 */
1931
1932 newXpg = 0;
1933 if (isdigit(UCHAR(ch))) {
1934 int position = strtoul(format, &end, 10);
1935
1936 if (*end == '$') {
1937 newXpg = 1;
1938 objIndex = position - 1;
1939 format = end + 1;
1940 step = TclUtfToUniChar(format, &ch);
1941 }
1942 }
1943 if (newXpg) {
1944 if (gotSequential) {
1945 msg = mixedXPG;
1946 errCode = "MIXEDSPECTYPES";
1947 goto errorMsg;
1948 }
1949 gotXpg = 1;
1950 } else {
1951 if (gotXpg) {
1952 msg = mixedXPG;
1953 errCode = "MIXEDSPECTYPES";
1954 goto errorMsg;
1955 }
1956 gotSequential = 1;
1957 }
1958 if ((objIndex < 0) || (objIndex >= objc)) {
1959 msg = badIndex[gotXpg];
1960 errCode = gotXpg ? "INDEXRANGE" : "FIELDVARMISMATCH";
1961 goto errorMsg;
1962 }
1963
1964 /*
1965 * Step 2. Set of flags.
1966 */
1967
1968 sawFlag = 1;
1969 do {
1970 switch (ch) {
1971 case '-':
1972 gotMinus = 1;
1973 break;
1974 case '#':
1975 gotHash = 1;
1976 break;
1977 case '0':
1978 gotZero = 1;
1979 break;
1980 case ' ':
1981 gotSpace = 1;
1982 break;
1983 case '+':
1984 gotPlus = 1;
1985 break;
1986 default:
1987 sawFlag = 0;
1988 }
1989 if (sawFlag) {
1990 format += step;
1991 step = TclUtfToUniChar(format, &ch);
1992 }
1993 } while (sawFlag);
1994
1995 /*
1996 * Step 3. Minimum field width.
1997 */
1998
1999 width = 0;
2000 if (isdigit(UCHAR(ch))) {
2001 width = strtoul(format, &end, 10);
2002 if (width < 0) {
2003 msg = overflow;
2004 errCode = "OVERFLOW";
2005 goto errorMsg;
2006 }
2007 format = end;
2008 step = TclUtfToUniChar(format, &ch);
2009 } else if (ch == '*') {
2010 if (objIndex >= objc - 1) {
2011 msg = badIndex[gotXpg];
2012 errCode = gotXpg ? "INDEXRANGE" : "FIELDVARMISMATCH";
2013 goto errorMsg;
2014 }
2015 if (TclGetIntFromObj(interp, objv[objIndex], &width) != TCL_OK) {
2016 goto error;
2017 }
2018 if (width < 0) {
2019 width = -width;
2020 gotMinus = 1;
2021 }
2022 objIndex++;
2023 format += step;
2024 step = TclUtfToUniChar(format, &ch);
2025 }
2026 if (width > limit) {
2027 msg = overflow;
2028 errCode = "OVERFLOW";
2029 goto errorMsg;
2030 }
2031
2032 /*
2033 * Step 4. Precision.
2034 */
2035
2036 gotPrecision = precision = 0;
2037 if (ch == '.') {
2038 gotPrecision = 1;
2039 format += step;
2040 step = TclUtfToUniChar(format, &ch);
2041 }
2042 if (isdigit(UCHAR(ch))) {
2043 precision = strtoul(format, &end, 10);
2044 format = end;
2045 step = TclUtfToUniChar(format, &ch);
2046 } else if (ch == '*') {
2047 if (objIndex >= objc - 1) {
2048 msg = badIndex[gotXpg];
2049 errCode = gotXpg ? "INDEXRANGE" : "FIELDVARMISMATCH";
2050 goto errorMsg;
2051 }
2052 if (TclGetIntFromObj(interp, objv[objIndex], &precision)
2053 != TCL_OK) {
2054 goto error;
2055 }
2056
2057 /*
2058 * TODO: Check this truncation logic.
2059 */
2060
2061 if (precision < 0) {
2062 precision = 0;
2063 }
2064 objIndex++;
2065 format += step;
2066 step = TclUtfToUniChar(format, &ch);
2067 }
2068
2069 /*
2070 * Step 5. Length modifier.
2071 */
2072
2073 if (ch == 'h') {
2074 useShort = 1;
2075 format += step;
2076 step = TclUtfToUniChar(format, &ch);
2077 } else if (ch == 'l') {
2078 format += step;
2079 step = TclUtfToUniChar(format, &ch);
2080 if (ch == 'l') {
2081 useBig = 1;
2082 format += step;
2083 step = TclUtfToUniChar(format, &ch);
2084 #ifndef TCL_WIDE_INT_IS_LONG
2085 } else {
2086 useWide = 1;
2087 #endif
2088 }
2089 }
2090
2091 format += step;
2092 span = format;
2093
2094 /*
2095 * Step 6. The actual conversion character.
2096 */
2097
2098 segment = objv[objIndex];
2099 numChars = -1;
2100 if (ch == 'i') {
2101 ch = 'd';
2102 }
2103 switch (ch) {
2104 case '\0':
2105 msg = "format string ended in middle of field specifier";
2106 errCode = "INCOMPLETE";
2107 goto errorMsg;
2108 case 's':
2109 if (gotPrecision) {
2110 numChars = Tcl_GetCharLength(segment);
2111 if (precision < numChars) {
2112 if (precision < 1) {
2113 TclNewObj(segment);
2114 } else {
2115 segment = Tcl_GetRange(segment, 0, precision - 1);
2116 }
2117 numChars = precision;
2118 Tcl_IncrRefCount(segment);
2119 allocSegment = 1;
2120 }
2121 }
2122 break;
2123 case 'c': {
2124 char buf[4] = "";
2125 int code, length;
2126
2127 if (TclGetIntFromObj(interp, segment, &code) != TCL_OK) {
2128 goto error;
2129 }
2130 length = Tcl_UniCharToUtf(code, buf);
2131 #if TCL_UTF_MAX > 3
2132 if ((code >= 0xD800) && (length < 3)) {
2133 /* Special case for handling high surrogates. */
2134 length += Tcl_UniCharToUtf(-1, buf + length);
2135 }
2136 #endif
2137 segment = Tcl_NewStringObj(buf, length);
2138 Tcl_IncrRefCount(segment);
2139 allocSegment = 1;
2140 break;
2141 }
2142
2143 case 'u':
2144 if (useBig) {
2145 msg = "unsigned bignum format is invalid";
2146 errCode = "BADUNSIGNED";
2147 goto errorMsg;
2148 }
2149 /* FALLTHRU */
2150 case 'd':
2151 case 'o':
2152 case 'x':
2153 case 'X':
2154 case 'b': {
2155 short s = 0; /* Silence compiler warning; only defined and
2156 * used when useShort is true. */
2157 long l;
2158 Tcl_WideInt w;
2159 mp_int big;
2160 int toAppend, isNegative = 0;
2161
2162 if (useBig) {
2163 if (Tcl_GetBignumFromObj(interp, segment, &big) != TCL_OK) {
2164 goto error;
2165 }
2166 isNegative = mp_isneg(&big);
2167 #ifndef TCL_WIDE_INT_IS_LONG
2168 } else if (useWide) {
2169 if (Tcl_GetWideIntFromObj(NULL, segment, &w) != TCL_OK) {
2170 Tcl_Obj *objPtr;
2171
2172 if (Tcl_GetBignumFromObj(interp,segment,&big) != TCL_OK) {
2173 goto error;
2174 }
2175 mp_mod_2d(&big, CHAR_BIT*sizeof(Tcl_WideInt), &big);
2176 objPtr = Tcl_NewBignumObj(&big);
2177 Tcl_IncrRefCount(objPtr);
2178 Tcl_GetWideIntFromObj(NULL, objPtr, &w);
2179 Tcl_DecrRefCount(objPtr);
2180 }
2181 isNegative = (w < 0);
2182 #endif
2183 } else if (TclGetLongFromObj(NULL, segment, &l) != TCL_OK) {
2184 if (Tcl_GetWideIntFromObj(NULL, segment, &w) != TCL_OK) {
2185 Tcl_Obj *objPtr;
2186
2187 if (Tcl_GetBignumFromObj(interp,segment,&big) != TCL_OK) {
2188 goto error;
2189 }
2190 mp_mod_2d(&big, CHAR_BIT * sizeof(long), &big);
2191 objPtr = Tcl_NewBignumObj(&big);
2192 Tcl_IncrRefCount(objPtr);
2193 TclGetLongFromObj(NULL, objPtr, &l);
2194 Tcl_DecrRefCount(objPtr);
2195 } else {
2196 l = Tcl_WideAsLong(w);
2197 }
2198 if (useShort) {
2199 s = (short) l;
2200 isNegative = (s < (short) 0);
2201 } else {
2202 isNegative = (l < (long) 0);
2203 }
2204 } else if (useShort) {
2205 s = (short) l;
2206 isNegative = (s < (short) 0);
2207 } else {
2208 isNegative = (l < (long) 0);
2209 }
2210
2211 TclNewObj(segment);
2212 allocSegment = 1;
2213 segmentLimit = INT_MAX;
2214 Tcl_IncrRefCount(segment);
2215
2216 if ((isNegative || gotPlus || gotSpace) && (useBig || ch=='d')) {
2217 Tcl_AppendToObj(segment,
2218 (isNegative ? "-" : gotPlus ? "+" : " "), 1);
2219 segmentLimit -= 1;
2220 }
2221
2222 if (gotHash) {
2223 switch (ch) {
2224 case 'o':
2225 Tcl_AppendToObj(segment, "0", 1);
2226 segmentLimit -= 1;
2227 precision--;
2228 break;
2229 case 'X':
2230 Tcl_AppendToObj(segment, "0X", 2);
2231 segmentLimit -= 2;
2232 break;
2233 case 'x':
2234 Tcl_AppendToObj(segment, "0x", 2);
2235 segmentLimit -= 2;
2236 break;
2237 case 'b':
2238 Tcl_AppendToObj(segment, "0b", 2);
2239 segmentLimit -= 2;
2240 break;
2241 }
2242 }
2243
2244 switch (ch) {
2245 case 'd': {
2246 int length;
2247 Tcl_Obj *pure;
2248 const char *bytes;
2249
2250 if (useShort) {
2251 TclNewIntObj(pure, s);
2252 #ifndef TCL_WIDE_INT_IS_LONG
2253 } else if (useWide) {
2254 pure = Tcl_NewWideIntObj(w);
2255 #endif
2256 } else if (useBig) {
2257 pure = Tcl_NewBignumObj(&big);
2258 } else {
2259 pure = Tcl_NewLongObj(l);
2260 }
2261 Tcl_IncrRefCount(pure);
2262 bytes = TclGetStringFromObj(pure, &length);
2263
2264 /*
2265 * Already did the sign above.
2266 */
2267
2268 if (*bytes == '-') {
2269 length--;
2270 bytes++;
2271 }
2272 toAppend = length;
2273
2274 /*
2275 * Canonical decimal string reps for integers are composed
2276 * entirely of one-byte encoded characters, so "length" is the
2277 * number of chars.
2278 */
2279
2280 if (gotPrecision) {
2281 if (length < precision) {
2282 segmentLimit -= precision - length;
2283 }
2284 while (length < precision) {
2285 Tcl_AppendToObj(segment, "0", 1);
2286 length++;
2287 }
2288 gotZero = 0;
2289 }
2290 if (gotZero) {
2291 length += Tcl_GetCharLength(segment);
2292 if (length < width) {
2293 segmentLimit -= width - length;
2294 }
2295 while (length < width) {
2296 Tcl_AppendToObj(segment, "0", 1);
2297 length++;
2298 }
2299 }
2300 if (toAppend > segmentLimit) {
2301 msg = overflow;
2302 errCode = "OVERFLOW";
2303 goto errorMsg;
2304 }
2305 Tcl_AppendToObj(segment, bytes, toAppend);
2306 Tcl_DecrRefCount(pure);
2307 break;
2308 }
2309
2310 case 'u':
2311 case 'o':
2312 case 'x':
2313 case 'X':
2314 case 'b': {
2315 Tcl_WideUInt bits = 0;
2316 Tcl_WideInt numDigits = 0;
2317 int numBits = 4, base = 16, index = 0, shift = 0;
2318 int length;
2319 Tcl_Obj *pure;
2320 char *bytes;
2321
2322 if (ch == 'u') {
2323 base = 10;
2324 } else if (ch == 'o') {
2325 base = 8;
2326 numBits = 3;
2327 } else if (ch == 'b') {
2328 base = 2;
2329 numBits = 1;
2330 }
2331 if (useShort) {
2332 unsigned short us = (unsigned short) s;
2333
2334 bits = (Tcl_WideUInt)us;
2335 while (us) {
2336 numDigits++;
2337 us /= base;
2338 }
2339 #ifndef TCL_WIDE_INT_IS_LONG
2340 } else if (useWide) {
2341 Tcl_WideUInt uw = (Tcl_WideUInt)w;
2342
2343 bits = uw;
2344 while (uw) {
2345 numDigits++;
2346 uw /= base;
2347 }
2348 #endif
2349 } else if (useBig && !mp_iszero(&big)) {
2350 int leftover = (big.used * MP_DIGIT_BIT) % numBits;
2351 mp_digit mask = (~(mp_digit)0) << (MP_DIGIT_BIT-leftover);
2352
2353 numDigits = 1 +
2354 (((Tcl_WideInt)big.used * MP_DIGIT_BIT) / numBits);
2355 while ((mask & big.dp[big.used-1]) == 0) {
2356 numDigits--;
2357 mask >>= numBits;
2358 }
2359 if (numDigits > INT_MAX) {
2360 msg = overflow;
2361 errCode = "OVERFLOW";
2362 goto errorMsg;
2363 }
2364 } else if (!useBig) {
2365 unsigned long ul = (unsigned long) l;
2366
2367 bits = (Tcl_WideUInt)ul;
2368 while (ul) {
2369 numDigits++;
2370 ul /= base;
2371 }
2372 }
2373
2374 /*
2375 * Need to be sure zero becomes "0", not "".
2376 */
2377
2378 if ((numDigits == 0) && !((ch == 'o') && gotHash)) {
2379 numDigits = 1;
2380 }
2381 TclNewObj(pure);
2382 Tcl_SetObjLength(pure, (int)numDigits);
2383 bytes = TclGetString(pure);
2384 toAppend = length = numDigits;
2385 while (numDigits--) {
2386 int digitOffset;
2387
2388 if (useBig && !mp_iszero(&big)) {
2389 if (index < big.used && (size_t) shift <
2390 CHAR_BIT*sizeof(Tcl_WideUInt) - MP_DIGIT_BIT) {
2391 bits |= ((Tcl_WideUInt)big.dp[index++]) << shift;
2392 shift += MP_DIGIT_BIT;
2393 }
2394 shift -= numBits;
2395 }
2396 digitOffset = bits % base;
2397 if (digitOffset > 9) {
2398 if (ch == 'X') {
2399 bytes[numDigits] = 'A' + digitOffset - 10;
2400 } else {
2401 bytes[numDigits] = 'a' + digitOffset - 10;
2402 }
2403 } else {
2404 bytes[numDigits] = '0' + digitOffset;
2405 }
2406 bits /= base;
2407 }
2408 if (useBig) {
2409 mp_clear(&big);
2410 }
2411 if (gotPrecision) {
2412 if (length < precision) {
2413 segmentLimit -= precision - length;
2414 }
2415 while (length < precision) {
2416 Tcl_AppendToObj(segment, "0", 1);
2417 length++;
2418 }
2419 gotZero = 0;
2420 }
2421 if (gotZero) {
2422 length += Tcl_GetCharLength(segment);
2423 if (length < width) {
2424 segmentLimit -= width - length;
2425 }
2426 while (length < width) {
2427 Tcl_AppendToObj(segment, "0", 1);
2428 length++;
2429 }
2430 }
2431 if (toAppend > segmentLimit) {
2432 msg = overflow;
2433 errCode = "OVERFLOW";
2434 goto errorMsg;
2435 }
2436 Tcl_AppendObjToObj(segment, pure);
2437 Tcl_DecrRefCount(pure);
2438 break;
2439 }
2440
2441 }
2442 break;
2443 }
2444
2445 case 'e':
2446 case 'E':
2447 case 'f':
2448 case 'g':
2449 case 'G': {
2450 #define MAX_FLOAT_SIZE 320
2451 char spec[2*TCL_INTEGER_SPACE + 9], *p = spec;
2452 double d;
2453 int length = MAX_FLOAT_SIZE;
2454 char *bytes;
2455
2456 if (Tcl_GetDoubleFromObj(interp, segment, &d) != TCL_OK) {
2457 /* TODO: Figure out ACCEPT_NAN here */
2458 goto error;
2459 }
2460 *p++ = '%';
2461 if (gotMinus) {
2462 *p++ = '-';
2463 }
2464 if (gotHash) {
2465 *p++ = '#';
2466 }
2467 if (gotZero) {
2468 *p++ = '0';
2469 }
2470 if (gotSpace) {
2471 *p++ = ' ';
2472 }
2473 if (gotPlus) {
2474 *p++ = '+';
2475 }
2476 if (width) {
2477 p += snprintf(p, TCL_INTEGER_SPACE, "%d", width);
2478 if (width > length) {
2479 length = width;
2480 }
2481 }
2482 if (gotPrecision) {
2483 *p++ = '.';
2484 p += snprintf(p, TCL_INTEGER_SPACE, "%d", precision);
2485 if (precision > INT_MAX - length) {
2486 msg = overflow;
2487 errCode = "OVERFLOW";
2488 goto errorMsg;
2489 }
2490 length += precision;
2491 }
2492
2493 /*
2494 * Don't pass length modifiers!
2495 */
2496
2497 *p++ = (char) ch;
2498 *p = '\0';
2499
2500 TclNewObj(segment);
2501 allocSegment = 1;
2502 if (!Tcl_AttemptSetObjLength(segment, length)) {
2503 msg = overflow;
2504 errCode = "OVERFLOW";
2505 goto errorMsg;
2506 }
2507 bytes = TclGetString(segment);
2508 if (!Tcl_AttemptSetObjLength(segment, snprintf(bytes, segment->length, spec, d))) {
2509 msg = overflow;
2510 errCode = "OVERFLOW";
2511 goto errorMsg;
2512 }
2513 break;
2514 }
2515 default:
2516 if (interp != NULL) {
2517 Tcl_SetObjResult(interp,
2518 Tcl_ObjPrintf("bad field specifier \"%c\"", ch));
2519 Tcl_SetErrorCode(interp, "TCL", "FORMAT", "BADTYPE", (char *)NULL);
2520 }
2521 goto error;
2522 }
2523
2524 if (width>0 && numChars<0) {
2525 numChars = Tcl_GetCharLength(segment);
2526 }
2527 if (!gotMinus && width>0) {
2528 if (numChars < width) {
2529 limit -= width - numChars;
2530 }
2531 while (numChars < width) {
2532 Tcl_AppendToObj(appendObj, (gotZero ? "0" : " "), 1);
2533 numChars++;
2534 }
2535 }
2536
2537 (void)TclGetStringFromObj(segment, &segmentNumBytes);
2538 if (segmentNumBytes > limit) {
2539 if (allocSegment) {
2540 Tcl_DecrRefCount(segment);
2541 }
2542 msg = overflow;
2543 errCode = "OVERFLOW";
2544 goto errorMsg;
2545 }
2546 Tcl_AppendObjToObj(appendObj, segment);
2547 limit -= segmentNumBytes;
2548 if (allocSegment) {
2549 Tcl_DecrRefCount(segment);
2550 }
2551 if (width > 0) {
2552 if (numChars < width) {
2553 limit -= width-numChars;
2554 }
2555 while (numChars < width) {
2556 Tcl_AppendToObj(appendObj, (gotZero ? "0" : " "), 1);
2557 numChars++;
2558 }
2559 }
2560
2561 objIndex += gotSequential;
2562 }
2563 if (numBytes) {
2564 if (numBytes > limit) {
2565 msg = overflow;
2566 errCode = "OVERFLOW";
2567 goto errorMsg;
2568 }
2569 Tcl_AppendToObj(appendObj, span, numBytes);
2570 limit -= numBytes;
2571 numBytes = 0;
2572 }
2573
2574 return TCL_OK;
2575
2576 errorMsg:
2577 if (interp != NULL) {
2578 Tcl_SetObjResult(interp, Tcl_NewStringObj(msg, -1));
2579 Tcl_SetErrorCode(interp, "TCL", "FORMAT", errCode, (char *)NULL);
2580 }
2581 error:
2582 Tcl_SetObjLength(appendObj, originalLength);
2583 return TCL_ERROR;
2584 }
2585
2586 /*
2587 *---------------------------------------------------------------------------
2588 *
2589 * Tcl_Format --
2590 *
2591 * Results:
2592 * A refcount zero Tcl_Obj.
2593 *
2594 * Side effects:
2595 * None.
2596 *
2597 *---------------------------------------------------------------------------
2598 */
2599
2600 Tcl_Obj *
2601 Tcl_Format(
2602 Tcl_Interp *interp,
2603 const char *format,
2604 int objc,
2605 Tcl_Obj *const objv[])
2606 {
2607 int result;
2608 Tcl_Obj *objPtr;
2609
2610 TclNewObj(objPtr);
2611 result = Tcl_AppendFormatToObj(interp, objPtr, format, objc, objv);
2612 if (result != TCL_OK) {
2613 Tcl_DecrRefCount(objPtr);
2614 return NULL;
2615 }
2616 return objPtr;
2617 }
2618
2619 /*
2620 *---------------------------------------------------------------------------
2621 *
2622 * AppendPrintfToObjVA --
2623 *
2624 * Results:
2625 *
2626 * Side effects:
2627 *
2628 *---------------------------------------------------------------------------
2629 */
2630
2631 static Tcl_Obj *
2632 NewLongObj(
2633 char c,
2634 long value)
2635 {
2636 if ((value < 0) && strchr("puoxX", c)) {
2637 #ifdef TCL_WIDE_INT_IS_LONG
2638 mp_int bignumValue;
2639 mp_init_u64(&bignumValue, (unsigned long)value);
2640 return Tcl_NewBignumObj(&bignumValue);
2641 #else
2642 return Tcl_NewWideIntObj((unsigned long)value);
2643 #endif
2644 }
2645 return Tcl_NewLongObj(value);
2646 }
2647
2648 static void
2649 AppendPrintfToObjVA(
2650 Tcl_Obj *objPtr,
2651 const char *format,
2652 va_list argList)
2653 {
2654 int code;
2655 int objc;
2656 Tcl_Obj **objv, *list;
2657 const char *p;
2658
2659 TclNewObj(list);
2660 p = format;
2661 Tcl_IncrRefCount(list);
2662 while (*p != '\0') {
2663 int size = 0, seekingConversion = 1, gotPrecision = 0;
2664 int lastNum = -1;
2665
2666 if (*p++ != '%') {
2667 continue;
2668 }
2669 if (*p == '%') {
2670 p++;
2671 continue;
2672 }
2673 do {
2674 switch (*p) {
2675 case '\0':
2676 seekingConversion = 0;
2677 break;
2678 case 's': {
2679 const char *q, *end, *bytes = va_arg(argList, char *);
2680 seekingConversion = 0;
2681
2682 /*
2683 * The buffer to copy characters from starts at bytes and ends
2684 * at either the first NUL byte, or after lastNum bytes, when
2685 * caller has indicated a limit.
2686 */
2687
2688 end = bytes;
2689 while ((!gotPrecision || lastNum--) && (*end != '\0')) {
2690 end++;
2691 }
2692
2693 /*
2694 * Within that buffer, we trim both ends if needed so that we
2695 * copy only whole characters, and avoid copying any partial
2696 * multi-byte characters.
2697 */
2698
2699 q = TclUtfPrev(end, bytes);
2700 if (!Tcl_UtfCharComplete(q, end - q)) {
2701 end = q;
2702 }
2703
2704 q = bytes + TCL_UTF_MAX;
2705 while ((bytes < end) && (bytes < q)
2706 && ((*bytes & 0xC0) == 0x80)) {
2707 bytes++;
2708 }
2709
2710 Tcl_ListObjAppendElement(NULL, list,
2711 Tcl_NewStringObj(bytes , end - bytes));
2712
2713 break;
2714 }
2715 case 'c':
2716 case 'i':
2717 case 'u':
2718 case 'd':
2719 case 'o':
2720 case 'x':
2721 case 'X':
2722 seekingConversion = 0;
2723 switch (size) {
2724 case -1:
2725 case 0:
2726 Tcl_ListObjAppendElement(NULL, list, Tcl_NewIntObj(
2727 va_arg(argList, int)));
2728 break;
2729 case 1:
2730 Tcl_ListObjAppendElement(NULL, list, NewLongObj(*p,
2731 va_arg(argList, long)));
2732 break;
2733 }
2734 break;
2735 case 'e':
2736 case 'E':
2737 case 'f':
2738 case 'g':
2739 case 'G':
2740 Tcl_ListObjAppendElement(NULL, list, Tcl_NewDoubleObj(
2741 va_arg(argList, double)));
2742 seekingConversion = 0;
2743 break;
2744 case '*':
2745 lastNum = va_arg(argList, int);
2746 Tcl_ListObjAppendElement(NULL, list, Tcl_NewIntObj(lastNum));
2747 p++;
2748 break;
2749 case '0': case '1': case '2': case '3': case '4':
2750 case '5': case '6': case '7': case '8': case '9': {
2751 char *end;
2752
2753 lastNum = strtoul(p, &end, 10);
2754 p = end;
2755 break;
2756 }
2757 case '.':
2758 gotPrecision = 1;
2759 p++;
2760 break;
2761 /* TODO: support for wide (and bignum?) arguments */
2762 case 'l':
2763 size = 1;
2764 p++;
2765 break;
2766 case 'h':
2767 size = -1;
2768 /* FALLTHRU */
2769 default:
2770 p++;
2771 }
2772 } while (seekingConversion);
2773 }
2774 TclListObjGetElements(NULL, list, &objc, &objv);
2775 code = Tcl_AppendFormatToObj(NULL, objPtr, format, objc, objv);
2776 if (code != TCL_OK) {
2777 Tcl_AppendPrintfToObj(objPtr,
2778 "Unable to format \"%s\" with supplied arguments: %s",
2779 format, TclGetString(list));
2780 }
2781 Tcl_DecrRefCount(list);
2782 }
2783
2784 /*
2785 *---------------------------------------------------------------------------
2786 *
2787 * Tcl_AppendPrintfToObj --
2788 *
2789 * Results:
2790 * A standard Tcl result.
2791 *
2792 * Side effects:
2793 * None.
2794 *
2795 *---------------------------------------------------------------------------
2796 */
2797
2798 void
2799 Tcl_AppendPrintfToObj(
2800 Tcl_Obj *objPtr,
2801 const char *format,
2802 ...)
2803 {
2804 va_list argList;
2805
2806 va_start(argList, format);
2807 AppendPrintfToObjVA(objPtr, format, argList);
2808 va_end(argList);
2809 }
2810
2811 /*
2812 *---------------------------------------------------------------------------
2813 *
2814 * Tcl_ObjPrintf --
2815 *
2816 * Results:
2817 * A refcount zero Tcl_Obj.
2818 *
2819 * Side effects:
2820 * None.
2821 *
2822 *---------------------------------------------------------------------------
2823 */
2824
2825 Tcl_Obj *
2826 Tcl_ObjPrintf(
2827 const char *format,
2828 ...)
2829 {
2830 va_list argList;
2831 Tcl_Obj *objPtr;
2832
2833 TclNewObj(objPtr);
2834 va_start(argList, format);
2835 AppendPrintfToObjVA(objPtr, format, argList);
2836 va_end(argList);
2837 return objPtr;
2838 }
2839
2840 /*
2841 *---------------------------------------------------------------------------
2842 *
2843 * TclGetStringStorage --
2844 *
2845 * Returns the string storage space of a Tcl_Obj.
2846 *
2847 * Results:
2848 * The pointer value objPtr->bytes is returned and the number of bytes
2849 * allocated there is written to *sizePtr (if known).
2850 *
2851 * Side effects:
2852 * May set objPtr->bytes.
2853 *
2854 *---------------------------------------------------------------------------
2855 */
2856
2857 char *
2858 TclGetStringStorage(
2859 Tcl_Obj *objPtr,
2860 unsigned int *sizePtr)
2861 {
2862 String *stringPtr;
2863
2864 if (objPtr->typePtr != &tclStringType || objPtr->bytes == NULL) {
2865 return TclGetStringFromObj(objPtr, (int *)sizePtr);
2866 }
2867
2868 stringPtr = GET_STRING(objPtr);
2869 *sizePtr = stringPtr->allocated;
2870 return objPtr->bytes;
2871 }
2872 /*
2873 *---------------------------------------------------------------------------
2874 *
2875 * TclStringReverse --
2876 *
2877 * Implements the [string reverse] operation.
2878 *
2879 * Results:
2880 * A Tcl value which is the [string reverse] of the argument supplied.
2881 * When sharing rules permit and the caller requests, the returned value
2882 * might be the argument with modifications done in place.
2883 *
2884 * Side effects:
2885 * May allocate a new Tcl_Obj.
2886 *
2887 *---------------------------------------------------------------------------
2888 */
2889
2890 static void
2891 ReverseBytes(
2892 unsigned char *to, /* Copy bytes into here... */
2893 unsigned char *from, /* ...from here... */
2894 int count) /* Until this many are copied, */
2895 /* reversing as you go. */
2896 {
2897 unsigned char *src = from + count;
2898
2899 if (to == from) {
2900 /* Reversing in place */
2901 while (--src > to) {
2902 unsigned char c = *src;
2903
2904 *src = *to;
2905 *to++ = c;
2906 }
2907 } else {
2908 while (--src >= from) {
2909 *to++ = *src;
2910 }
2911 }
2912 }
2913
2914 Tcl_Obj *
2915 TclStringReverse(
2916 Tcl_Obj *objPtr)
2917 {
2918 String *stringPtr;
2919 Tcl_UniChar ch = 0;
2920 #if TCL_UTF_MAX <= 4
2921 int needFlip = 0;
2922 #endif
2923
2924 if (TclIsPureByteArray(objPtr)) {
2925 int numBytes;
2926 unsigned char *from = Tcl_GetByteArrayFromObj(objPtr, &numBytes);
2927
2928 if (Tcl_IsShared(objPtr)) {
2929 objPtr = Tcl_NewByteArrayObj(NULL, numBytes);
2930 }
2931 ReverseBytes(Tcl_GetByteArrayFromObj(objPtr, NULL), from, numBytes);
2932 return objPtr;
2933 }
2934
2935 SetStringFromAny(NULL, objPtr);
2936 stringPtr = GET_STRING(objPtr);
2937
2938 if (stringPtr->hasUnicode) {
2939 Tcl_UniChar *from = Tcl_GetUnicode(objPtr);
2940 Tcl_UniChar *src = from + stringPtr->numChars;
2941 Tcl_UniChar *to;
2942
2943 if (Tcl_IsShared(objPtr)) {
2944 /*
2945 * Create a non-empty, pure Unicode value, so we can coax
2946 * Tcl_SetObjLength into growing the Unicode rep buffer.
2947 */
2948
2949 objPtr = Tcl_NewUnicodeObj(&ch, 1);
2950 Tcl_SetObjLength(objPtr, stringPtr->numChars);
2951 to = Tcl_GetUnicode(objPtr);
2952 while (--src >= from) {
2953 #if TCL_UTF_MAX <= 4
2954 ch = *src;
2955 if ((ch & 0xF800) == 0xD800) {
2956 needFlip = 1;
2957 }
2958 *to++ = ch;
2959 #else
2960 *to++ = *src;
2961 #endif
2962 }
2963 } else {
2964 /*
2965 * Reversing in place.
2966 */
2967
2968 #if TCL_UTF_MAX <= 4
2969 to = src;
2970 #endif
2971 while (--src > from) {
2972 ch = *src;
2973 #if TCL_UTF_MAX <= 4
2974 if ((ch & 0xF800) == 0xD800) {
2975 needFlip = 1;
2976 }
2977 #endif
2978 *src = *from;
2979 *from++ = ch;
2980 }
2981 }
2982 #if TCL_UTF_MAX <= 4
2983 if (needFlip) {
2984 /*
2985 * Flip back surrogate pairs.
2986 */
2987
2988 from = to - stringPtr->numChars;
2989 while (--to >= from) {
2990 ch = *to;
2991 if ((ch & 0xFC00) == 0xD800) {
2992 if ((to-1 >= from) && ((to[-1] & 0xFC00) == 0xDC00)) {
2993 to[0] = to[-1];
2994 to[-1] = ch;
2995 --to;
2996 }
2997 }
2998 }
2999 }
3000 #endif
3001 }
3002
3003 if (objPtr->bytes) {
3004 int numChars = stringPtr->numChars;
3005 int numBytes = objPtr->length;
3006 char *to, *from = objPtr->bytes;
3007
3008 if (Tcl_IsShared(objPtr)) {
3009 TclNewObj(objPtr);
3010 Tcl_SetObjLength(objPtr, numBytes);
3011 }
3012 to = objPtr->bytes;
3013
3014 if (numChars < numBytes) {
3015 /*
3016 * Either numChars == -1 and we don't know how many chars are
3017 * represented by objPtr->bytes and we need Pass 1 just in case,
3018 * or numChars >= 0 and we know we have fewer chars than bytes, so
3019 * we know there's a multibyte character needing Pass 1.
3020 *
3021 * Pass 1. Reverse the bytes of each multi-byte character.
3022 */
3023
3024 int bytesLeft = numBytes;
3025 int chw;
3026
3027 while (bytesLeft) {
3028 /*
3029 * NOTE: We know that the from buffer is NUL-terminated. It's
3030 * part of the contract for objPtr->bytes values. Thus, we can
3031 * skip calling Tcl_UtfCharComplete() here.
3032 */
3033
3034 int bytesInChar = TclUtfToUCS4(from, &chw);
3035
3036 ReverseBytes((unsigned char *)to, (unsigned char *)from,
3037 bytesInChar);
3038 to += bytesInChar;
3039 from += bytesInChar;
3040 bytesLeft -= bytesInChar;
3041 }
3042
3043 from = to = objPtr->bytes;
3044 }
3045 /* Pass 2. Reverse all the bytes. */
3046 ReverseBytes((unsigned char *)to, (unsigned char *)from, numBytes);
3047 }
3048
3049 return objPtr;
3050 }
3051
3052 /*
3053 *---------------------------------------------------------------------------
3054 *
3055 * FillUnicodeRep --
3056 *
3057 * Populate the Unicode internal rep with the Unicode form of its string
3058 * rep. The object must already have a "String" internal rep.
3059 *
3060 * Results:
3061 * None.
3062 *
3063 * Side effects:
3064 * Reallocates the String internal rep.
3065 *
3066 *---------------------------------------------------------------------------
3067 */
3068
3069 static void
3070 FillUnicodeRep(
3071 Tcl_Obj *objPtr) /* The object in which to fill the unicode
3072 * rep. */
3073 {
3074 String *stringPtr = GET_STRING(objPtr);
3075
3076 ExtendUnicodeRepWithString(objPtr, objPtr->bytes, objPtr->length,
3077 stringPtr->numChars);
3078 }
3079
3080 static void
3081 ExtendUnicodeRepWithString(
3082 Tcl_Obj *objPtr,
3083 const char *bytes,
3084 int numBytes,
3085 int numAppendChars)
3086 {
3087 String *stringPtr = GET_STRING(objPtr);
3088 int needed, numOrigChars = 0;
3089 Tcl_UniChar *dst, unichar = 0;
3090
3091 if (stringPtr->hasUnicode) {
3092 numOrigChars = stringPtr->numChars;
3093 }
3094 if (numAppendChars == -1) {
3095 TclNumUtfChars(numAppendChars, bytes, numBytes);
3096 }
3097 needed = numOrigChars + numAppendChars;
3098 stringCheckLimits(needed);
3099
3100 if (needed > stringPtr->maxChars) {
3101 GrowUnicodeBuffer(objPtr, needed);
3102 stringPtr = GET_STRING(objPtr);
3103 }
3104
3105 stringPtr->hasUnicode = 1;
3106 if (bytes) {
3107 stringPtr->numChars = needed;
3108 } else {
3109 numAppendChars = 0;
3110 }
3111 for (dst = stringPtr->unicode + numOrigChars; numAppendChars-- > 0; dst++) {
3112 bytes += TclUtfToUniChar(bytes, &unichar);
3113 *dst = unichar;
3114 }
3115 *dst = 0;
3116 }
3117
3118 /*
3119 *----------------------------------------------------------------------
3120 *
3121 * DupStringInternalRep --
3122 *
3123 * Initialize the internal representation of a new Tcl_Obj to a copy of
3124 * the internal representation of an existing string object.
3125 *
3126 * Results:
3127 * None.
3128 *
3129 * Side effects:
3130 * copyPtr's internal rep is set to a copy of srcPtr's internal
3131 * representation.
3132 *
3133 *----------------------------------------------------------------------
3134 */
3135
3136 static void
3137 DupStringInternalRep(
3138 Tcl_Obj *srcPtr, /* Object with internal rep to copy. Must have
3139 * an internal rep of type "String". */
3140 Tcl_Obj *copyPtr) /* Object with internal rep to set. Must not
3141 * currently have an internal rep.*/
3142 {
3143 String *srcStringPtr = GET_STRING(srcPtr);
3144 String *copyStringPtr = NULL;
3145
3146 if (srcStringPtr->numChars == -1) {
3147 /*
3148 * The String struct in the source value holds zero useful data. Don't
3149 * bother copying it. Don't even bother allocating space in which to
3150 * copy it. Just let the copy be untyped.
3151 */
3152 return;
3153 }
3154
3155 if (srcStringPtr->hasUnicode) {
3156 int copyMaxChars;
3157
3158 if (srcStringPtr->maxChars / 2 >= srcStringPtr->numChars) {
3159 copyMaxChars = 2 * srcStringPtr->numChars;
3160 } else {
3161 copyMaxChars = srcStringPtr->maxChars;
3162 }
3163 copyStringPtr = stringAttemptAlloc(copyMaxChars);
3164 if (copyStringPtr == NULL) {
3165 copyMaxChars = srcStringPtr->numChars;
3166 copyStringPtr = stringAlloc(copyMaxChars);
3167 }
3168 copyStringPtr->maxChars = copyMaxChars;
3169 memcpy(copyStringPtr->unicode, srcStringPtr->unicode,
3170 srcStringPtr->numChars * sizeof(Tcl_UniChar));
3171 copyStringPtr->unicode[srcStringPtr->numChars] = 0;
3172 } else {
3173 copyStringPtr = stringAlloc(0);
3174 copyStringPtr->maxChars = 0;
3175 copyStringPtr->unicode[0] = 0;
3176 }
3177 copyStringPtr->hasUnicode = srcStringPtr->hasUnicode;
3178 copyStringPtr->numChars = srcStringPtr->numChars;
3179
3180 /*
3181 * Tricky point: the string value was copied by generic object management
3182 * code, so it doesn't contain any extra bytes that might exist in the
3183 * source object.
3184 */
3185
3186 copyStringPtr->allocated = copyPtr->bytes ? copyPtr->length : 0;
3187
3188 SET_STRING(copyPtr, copyStringPtr);
3189 copyPtr->typePtr = &tclStringType;
3190 }
3191
3192 /*
3193 *----------------------------------------------------------------------
3194 *
3195 * SetStringFromAny --
3196 *
3197 * Create an internal representation of type "String" for an object.
3198 *
3199 * Results:
3200 * This operation always succeeds and returns TCL_OK.
3201 *
3202 * Side effects:
3203 * Any old internal representation for objPtr is freed and the internal
3204 * representation is set to &tclStringType.
3205 *
3206 *----------------------------------------------------------------------
3207 */
3208
3209 static int
3210 SetStringFromAny(
3211 Tcl_Interp *interp, /* Used for error reporting if not NULL. */
3212 Tcl_Obj *objPtr) /* The object to convert. */
3213 {
3214 if (objPtr->typePtr != &tclStringType) {
3215 String *stringPtr = stringAlloc(0);
3216
3217 /*
3218 * Convert whatever we have into an untyped value. Just A String.
3219 */
3220
3221 (void) TclGetString(objPtr);
3222 TclFreeIntRep(objPtr);
3223
3224 /*
3225 * Create a basic String internalrep that just points to the UTF-8 string
3226 * already in place at objPtr->bytes.
3227 */
3228
3229 stringPtr->numChars = -1;
3230 stringPtr->allocated = objPtr->length;
3231 stringPtr->maxChars = 0;
3232 stringPtr->hasUnicode = 0;
3233 SET_STRING(objPtr, stringPtr);
3234 objPtr->typePtr = &tclStringType;
3235 }
3236 return TCL_OK;
3237 }
3238
3239 /*
3240 *----------------------------------------------------------------------
3241 *
3242 * UpdateStringOfString --
3243 *
3244 * Update the string representation for an object whose internal
3245 * representation is "String".
3246 *
3247 * Results:
3248 * None.
3249 *
3250 * Side effects:
3251 * The object's string may be set by converting its Unicode representation
3252 * to UTF format.
3253 *
3254 *----------------------------------------------------------------------
3255 */
3256
3257 static void
3258 UpdateStringOfString(
3259 Tcl_Obj *objPtr) /* Object with string rep to update. */
3260 {
3261 String *stringPtr = GET_STRING(objPtr);
3262
3263 /*
3264 * This routine is only called when we need to generate the
3265 * string rep objPtr->bytes because it does not exist -- it is NULL.
3266 * In that circumstance, any lingering claim about the size of
3267 * memory pointed to by that NULL pointer is clearly bogus, and
3268 * needs a reset.
3269 */
3270
3271 stringPtr->allocated = 0;
3272
3273 if (stringPtr->numChars == 0) {
3274 TclInitStringRep(objPtr, tclEmptyStringRep, 0);
3275 } else {
3276 (void) ExtendStringRepWithUnicode(objPtr, stringPtr->unicode,
3277 stringPtr->numChars);
3278 }
3279 }
3280
3281 static int
3282 ExtendStringRepWithUnicode(
3283 Tcl_Obj *objPtr,
3284 const Tcl_UniChar *unicode,
3285 int numChars)
3286 {
3287 /*
3288 * Precondition: this is the "string" Tcl_ObjType.
3289 */
3290
3291 int i, origLength, size = 0;
3292 char *dst, buf[4] = "";
3293 String *stringPtr = GET_STRING(objPtr);
3294
3295 if (numChars < 0) {
3296 numChars = UnicodeLength(unicode);
3297 }
3298
3299 if (numChars == 0) {
3300 return 0;
3301 }
3302
3303 if (objPtr->bytes == NULL) {
3304 objPtr->length = 0;
3305 }
3306 size = origLength = objPtr->length;
3307
3308 /*
3309 * Quick cheap check in case we have more than enough room.
3310 */
3311
3312 if (numChars <= (INT_MAX - size)/TCL_UTF_MAX
3313 && stringPtr->allocated >= size + numChars * TCL_UTF_MAX) {
3314 goto copyBytes;
3315 }
3316
3317 for (i = 0; i < numChars && size >= 0; i++) {
3318 size += (unsigned int)Tcl_UniCharToUtf((int) unicode[i], buf);
3319 }
3320 if (size < 0) {
3321 Tcl_Panic("max size for a Tcl value (%d bytes) exceeded", INT_MAX);
3322 }
3323
3324 /*
3325 * Grow space if needed.
3326 */
3327
3328 if (size > stringPtr->allocated) {
3329 GrowStringBuffer(objPtr, size, 1);
3330 }
3331
3332 copyBytes:
3333 dst = objPtr->bytes + origLength;
3334 for (i = 0; i < numChars; i++) {
3335 dst += Tcl_UniCharToUtf(unicode[i], dst);
3336 }
3337 *dst = '\0';
3338 objPtr->length = dst - objPtr->bytes;
3339 return numChars;
3340 }
3341
3342 /*
3343 *----------------------------------------------------------------------
3344 *
3345 * FreeStringInternalRep --
3346 *
3347 * Deallocate the storage associated with a String data object's internal
3348 * representation.
3349 *
3350 * Results:
3351 * None.
3352 *
3353 * Side effects:
3354 * Frees memory.
3355 *
3356 *----------------------------------------------------------------------
3357 */
3358
3359 static void
3360 FreeStringInternalRep(
3361 Tcl_Obj *objPtr) /* Object with internal rep to free. */
3362 {
3363 ckfree(GET_STRING(objPtr));
3364 objPtr->typePtr = NULL;
3365 }
3366
3367 /*
3368 * Local Variables:
3369 * mode: c
3370 * c-basic-offset: 4
3371 * fill-column: 78
3372 * End:
3373 */