Debian Codegraph @

pTk/mTk/tclGeneric/tclBinary.c

raw symbols SCIP
1 /*
2 * tclBinary.c --
3 *
4 * This file contains the implementation of the "binary" Tcl built-in
5 * command and the Tcl binary data object.
6 *
7 * Copyright (c) 1997 by Sun Microsystems, Inc.
8 * Copyright (c) 1998-1999 by Scriptics Corporation.
9 *
10 * See the file "license.terms" for information on usage and redistribution
11 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
12 *
13 * RCS: @(#) $Id: tclBinary.c,v 1.13 2003/02/21 21:54:11 dkf Exp $
14 */
15
16 #include "tclInt.h"
17 #include "tclPort.h"
18 #include <math.h>
19
20 /*
21 * The following constants are used by GetFormatSpec to indicate various
22 * special conditions in the parsing of a format specifier.
23 */
24
25 #define BINARY_ALL -1 /* Use all elements in the argument. */
26 #define BINARY_NOCOUNT -2 /* No count was specified in format. */
27
28 /*
29 * The following defines the maximum number of different (integer)
30 * numbers placed in the object cache by 'binary scan' before it bails
31 * out and switches back to Plan A (creating a new object for each
32 * value.) Theoretically, it would be possible to keep the cache
33 * about for the values that are already in it, but that makes the
34 * code slower in practise when overflow happens, and makes little
35 * odds the rest of the time (as measured on my machine.) It is also
36 * slower (on the sample I tried at least) to grow the cache to hold
37 * all items we might want to put in it; presumably the extra cost of
38 * managing the memory for the enlarged table outweighs the benefit
39 * from allocating fewer objects. This is probably because as the
40 * number of objects increases, the likelihood of reuse of any
41 * particular one drops, and there is very little gain from larger
42 * maximum cache sizes (the value below is chosen to allow caching to
43 * work in full with conversion of bytes.) - DKF
44 */
45
46 #define BINARY_SCAN_MAX_CACHE 260
47
48 /*
49 * Prototypes for local procedures defined in this file:
50 */
51
52 static void DupByteArrayInternalRep _ANSI_ARGS_((Tcl_Obj *srcPtr,
53 Tcl_Obj *copyPtr));
54 static int FormatNumber _ANSI_ARGS_((Tcl_Interp *interp, int type,
55 Tcl_Obj *src, unsigned char **cursorPtr));
56 static void FreeByteArrayInternalRep _ANSI_ARGS_((Tcl_Obj *objPtr));
57 static int GetFormatSpec _ANSI_ARGS_((char **formatPtr,
58 char *cmdPtr, int *countPtr));
59 static Tcl_Obj * ScanNumber _ANSI_ARGS_((unsigned char *buffer,
60 int type, Tcl_HashTable **numberCachePtr));
61 static int SetByteArrayFromAny _ANSI_ARGS_((Tcl_Interp *interp,
62 Tcl_Obj *objPtr));
63 static void UpdateStringOfByteArray _ANSI_ARGS_((Tcl_Obj *listPtr));
64
65
66 /*
67 * The following object type represents an array of bytes. An array of
68 * bytes is not equivalent to an internationalized string. Conceptually, a
69 * string is an array of 16-bit quantities organized as a sequence of properly
70 * formed UTF-8 characters, while a ByteArray is an array of 8-bit quantities.
71 * Accessor functions are provided to convert a ByteArray to a String or a
72 * String to a ByteArray. Two or more consecutive bytes in an array of bytes
73 * may look like a single UTF-8 character if the array is casually treated as
74 * a string. But obtaining the String from a ByteArray is guaranteed to
75 * produced properly formed UTF-8 sequences so that there is a one-to-one
76 * map between bytes and characters.
77 *
78 * Converting a ByteArray to a String proceeds by casting each byte in the
79 * array to a 16-bit quantity, treating that number as a Unicode character,
80 * and storing the UTF-8 version of that Unicode character in the String.
81 * For ByteArrays consisting entirely of values 1..127, the corresponding
82 * String representation is the same as the ByteArray representation.
83 *
84 * Converting a String to a ByteArray proceeds by getting the Unicode
85 * representation of each character in the String, casting it to a
86 * byte by truncating the upper 8 bits, and then storing the byte in the
87 * ByteArray. Converting from ByteArray to String and back to ByteArray
88 * is not lossy, but converting an arbitrary String to a ByteArray may be.
89 */
90
91 Tcl_ObjType tclByteArrayType = {
92 "bytearray",
93 FreeByteArrayInternalRep,
94 DupByteArrayInternalRep,
95 UpdateStringOfByteArray,
96 SetByteArrayFromAny
97 };
98
99 /*
100 * The following structure is the internal rep for a ByteArray object.
101 * Keeps track of how much memory has been used and how much has been
102 * allocated for the byte array to enable growing and shrinking of the
103 * ByteArray object with fewer mallocs.
104 */
105
106 typedef struct ByteArray {
107 int used; /* The number of bytes used in the byte
108 * array. */
109 int allocated; /* The amount of space actually allocated
110 * minus 1 byte. */
111 unsigned char bytes[4]; /* The array of bytes. The actual size of
112 * this field depends on the 'allocated' field
113 * above. */
114 } ByteArray;
115
116 #define BYTEARRAY_SIZE(len) \
117 ((unsigned) (sizeof(ByteArray) - 4 + (len)))
118 #define GET_BYTEARRAY(objPtr) \
119 ((ByteArray *) (objPtr)->internalRep.otherValuePtr)
120 #define SET_BYTEARRAY(objPtr, baPtr) \
121 (objPtr)->internalRep.otherValuePtr = (VOID *) (baPtr)
122
123
124 /*
125 *---------------------------------------------------------------------------
126 *
127 * Tcl_NewByteArrayObj --
128 *
129 * This procedure is creates a new ByteArray object and initializes
130 * it from the given array of bytes.
131 *
132 * Results:
133 * The newly create object is returned. This object will have no
134 * initial string representation. The returned object has a ref count
135 * of 0.
136 *
137 * Side effects:
138 * Memory allocated for new object and copy of byte array argument.
139 *
140 *---------------------------------------------------------------------------
141 */
142
143 #ifdef TCL_MEM_DEBUG
144 #undef Tcl_NewByteArrayObj
145
146
147 Tcl_Obj *
148 Tcl_NewByteArrayObj(bytes, length)
149 CONST unsigned char *bytes; /* The array of bytes used to initialize
150 * the new object. */
151 int length; /* Length of the array of bytes, which must
152 * be >= 0. */
153 {
154 return Tcl_DbNewByteArrayObj(bytes, length, "unknown", 0);
155 }
156
157 #else /* if not TCL_MEM_DEBUG */
158
159 Tcl_Obj *
160 Tcl_NewByteArrayObj(bytes, length)
161 CONST unsigned char *bytes; /* The array of bytes used to initialize
162 * the new object. */
163 int length; /* Length of the array of bytes, which must
164 * be >= 0. */
165 {
166 Tcl_Obj *objPtr;
167
168 TclNewObj(objPtr);
169 Tcl_SetByteArrayObj(objPtr, bytes, length);
170 return objPtr;
171 }
172 #endif /* TCL_MEM_DEBUG */
173
174 /*
175 *---------------------------------------------------------------------------
176 *
177 * Tcl_DbNewByteArrayObj --
178 *
179 * This procedure is normally called when debugging: i.e., when
180 * TCL_MEM_DEBUG is defined. It is the same as the Tcl_NewByteArrayObj
181 * above except that it calls Tcl_DbCkalloc directly with the file name
182 * and line number from its caller. This simplifies debugging since then
183 * the [memory active] command will report the correct file name and line
184 * number when reporting objects that haven't been freed.
185 *
186 * When TCL_MEM_DEBUG is not defined, this procedure just returns the
187 * result of calling Tcl_NewByteArrayObj.
188 *
189 * Results:
190 * The newly create object is returned. This object will have no
191 * initial string representation. The returned object has a ref count
192 * of 0.
193 *
194 * Side effects:
195 * Memory allocated for new object and copy of byte array argument.
196 *
197 *---------------------------------------------------------------------------
198 */
199
200 #ifdef TCL_MEM_DEBUG
201
202 Tcl_Obj *
203 Tcl_DbNewByteArrayObj(bytes, length, file, line)
204 CONST unsigned char *bytes; /* The array of bytes used to initialize
205 * the new object. */
206 int length; /* Length of the array of bytes, which must
207 * be >= 0. */
208 CONST char *file; /* The name of the source file calling this
209 * procedure; used for debugging. */
210 int line; /* Line number in the source file; used
211 * for debugging. */
212 {
213 Tcl_Obj *objPtr;
214
215 TclDbNewObj(objPtr, file, line);
216 Tcl_SetByteArrayObj(objPtr, bytes, length);
217 return objPtr;
218 }
219
220 #else /* if not TCL_MEM_DEBUG */
221
222 Tcl_Obj *
223 Tcl_DbNewByteArrayObj(bytes, length, file, line)
224 CONST unsigned char *bytes; /* The array of bytes used to initialize
225 * the new object. */
226 int length; /* Length of the array of bytes, which must
227 * be >= 0. */
228 CONST char *file; /* The name of the source file calling this
229 * procedure; used for debugging. */
230 int line; /* Line number in the source file; used
231 * for debugging. */
232 {
233 return Tcl_NewByteArrayObj(bytes, length);
234 }
235 #endif /* TCL_MEM_DEBUG */
236
237 /*
238 *---------------------------------------------------------------------------
239 *
240 * Tcl_SetByteArrayObj --
241 *
242 * Modify an object to be a ByteArray object and to have the specified
243 * array of bytes as its value.
244 *
245 * Results:
246 * None.
247 *
248 * Side effects:
249 * The object's old string rep and internal rep is freed.
250 * Memory allocated for copy of byte array argument.
251 *
252 *----------------------------------------------------------------------
253 */
254
255 void
256 Tcl_SetByteArrayObj(objPtr, bytes, length)
257 Tcl_Obj *objPtr; /* Object to initialize as a ByteArray. */
258 CONST unsigned char *bytes; /* The array of bytes to use as the new
259 * value. */
260 int length; /* Length of the array of bytes, which must
261 * be >= 0. */
262 {
263 Tcl_ObjType *typePtr;
264 ByteArray *byteArrayPtr;
265
266 if (Tcl_IsShared(objPtr)) {
267 panic("Tcl_SetByteArrayObj called with shared object");
268 }
269 typePtr = objPtr->typePtr;
270 if ((typePtr != NULL) && (typePtr->freeIntRepProc != NULL)) {
271 (*typePtr->freeIntRepProc)(objPtr);
272 }
273 Tcl_InvalidateStringRep(objPtr);
274
275 byteArrayPtr = (ByteArray *) ckalloc(BYTEARRAY_SIZE(length));
276 byteArrayPtr->used = length;
277 byteArrayPtr->allocated = length;
278 memcpy((VOID *) byteArrayPtr->bytes, (VOID *) bytes, (size_t) length);
279
280 objPtr->typePtr = &tclByteArrayType;
281 SET_BYTEARRAY(objPtr, byteArrayPtr);
282 }
283
284 /*
285 *----------------------------------------------------------------------
286 *
287 * Tcl_GetByteArrayFromObj --
288 *
289 * Attempt to get the array of bytes from the Tcl object. If the
290 * object is not already a ByteArray object, an attempt will be
291 * made to convert it to one.
292 *
293 * Results:
294 * Pointer to array of bytes representing the ByteArray object.
295 *
296 * Side effects:
297 * Frees old internal rep. Allocates memory for new internal rep.
298 *
299 *----------------------------------------------------------------------
300 */
301
302 unsigned char *
303 Tcl_GetByteArrayFromObj(objPtr, lengthPtr)
304 Tcl_Obj *objPtr; /* The ByteArray object. */
305 int *lengthPtr; /* If non-NULL, filled with length of the
306 * array of bytes in the ByteArray object. */
307 {
308 ByteArray *baPtr;
309
310 SetByteArrayFromAny(NULL, objPtr);
311 baPtr = GET_BYTEARRAY(objPtr);
312
313 if (lengthPtr != NULL) {
314 *lengthPtr = baPtr->used;
315 }
316 return (unsigned char *) baPtr->bytes;
317 }
318
319 /*
320 *----------------------------------------------------------------------
321 *
322 * Tcl_SetByteArrayLength --
323 *
324 * This procedure changes the length of the byte array for this
325 * object. Once the caller has set the length of the array, it
326 * is acceptable to directly modify the bytes in the array up until
327 * Tcl_GetStringFromObj() has been called on this object.
328 *
329 * Results:
330 * The new byte array of the specified length.
331 *
332 * Side effects:
333 * Allocates enough memory for an array of bytes of the requested
334 * size. When growing the array, the old array is copied to the
335 * new array; new bytes are undefined. When shrinking, the
336 * old array is truncated to the specified length.
337 *
338 *---------------------------------------------------------------------------
339 */
340
341 unsigned char *
342 Tcl_SetByteArrayLength(objPtr, length)
343 Tcl_Obj *objPtr; /* The ByteArray object. */
344 int length; /* New length for internal byte array. */
345 {
346 ByteArray *byteArrayPtr, *newByteArrayPtr;
347
348 if (Tcl_IsShared(objPtr)) {
349 panic("Tcl_SetObjLength called with shared object");
350 }
351 if (objPtr->typePtr != &tclByteArrayType) {
352 SetByteArrayFromAny(NULL, objPtr);
353 }
354
355 byteArrayPtr = GET_BYTEARRAY(objPtr);
356 if (length > byteArrayPtr->allocated) {
357 newByteArrayPtr = (ByteArray *) ckalloc(BYTEARRAY_SIZE(length));
358 newByteArrayPtr->used = length;
359 newByteArrayPtr->allocated = length;
360 memcpy((VOID *) newByteArrayPtr->bytes,
361 (VOID *) byteArrayPtr->bytes, (size_t) byteArrayPtr->used);
362 ckfree((char *) byteArrayPtr);
363 byteArrayPtr = newByteArrayPtr;
364 SET_BYTEARRAY(objPtr, byteArrayPtr);
365 }
366 Tcl_InvalidateStringRep(objPtr);
367 byteArrayPtr->used = length;
368 return byteArrayPtr->bytes;
369 }
370
371 /*
372 *---------------------------------------------------------------------------
373 *
374 * SetByteArrayFromAny --
375 *
376 * Generate the ByteArray internal rep from the string rep.
377 *
378 * Results:
379 * The return value is always TCL_OK.
380 *
381 * Side effects:
382 * A ByteArray object is stored as the internal rep of objPtr.
383 *
384 *---------------------------------------------------------------------------
385 */
386
387 static int
388 SetByteArrayFromAny(interp, objPtr)
389 Tcl_Interp *interp; /* Not used. */
390 Tcl_Obj *objPtr; /* The object to convert to type ByteArray. */
391 {
392 Tcl_ObjType *typePtr;
393 int length;
394 char *src, *srcEnd;
395 unsigned char *dst;
396 ByteArray *byteArrayPtr;
397 Tcl_UniChar ch;
398
399 typePtr = objPtr->typePtr;
400 if (typePtr != &tclByteArrayType) {
401 src = Tcl_GetStringFromObj(objPtr, &length);
402 srcEnd = src + length;
403
404 byteArrayPtr = (ByteArray *) ckalloc(BYTEARRAY_SIZE(length));
405 for (dst = byteArrayPtr->bytes; src < srcEnd; ) {
406 src += Tcl_UtfToUniChar(src, &ch);
407 *dst++ = (unsigned char) ch;
408 }
409
410 byteArrayPtr->used = dst - byteArrayPtr->bytes;
411 byteArrayPtr->allocated = length;
412
413 if ((typePtr != NULL) && (typePtr->freeIntRepProc) != NULL) {
414 (*typePtr->freeIntRepProc)(objPtr);
415 }
416 objPtr->typePtr = &tclByteArrayType;
417 SET_BYTEARRAY(objPtr, byteArrayPtr);
418 }
419 return TCL_OK;
420 }
421
422 /*
423 *----------------------------------------------------------------------
424 *
425 * FreeByteArrayInternalRep --
426 *
427 * Deallocate the storage associated with a ByteArray data object's
428 * internal representation.
429 *
430 * Results:
431 * None.
432 *
433 * Side effects:
434 * Frees memory.
435 *
436 *----------------------------------------------------------------------
437 */
438
439 static void
440 FreeByteArrayInternalRep(objPtr)
441 Tcl_Obj *objPtr; /* Object with internal rep to free. */
442 {
443 ckfree((char *) GET_BYTEARRAY(objPtr));
444 }
445
446 /*
447 *---------------------------------------------------------------------------
448 *
449 * DupByteArrayInternalRep --
450 *
451 * Initialize the internal representation of a ByteArray Tcl_Obj
452 * to a copy of the internal representation of an existing ByteArray
453 * object.
454 *
455 * Results:
456 * None.
457 *
458 * Side effects:
459 * Allocates memory.
460 *
461 *---------------------------------------------------------------------------
462 */
463
464 static void
465 DupByteArrayInternalRep(srcPtr, copyPtr)
466 Tcl_Obj *srcPtr; /* Object with internal rep to copy. */
467 Tcl_Obj *copyPtr; /* Object with internal rep to set. */
468 {
469 int length;
470 ByteArray *srcArrayPtr, *copyArrayPtr;
471
472 srcArrayPtr = GET_BYTEARRAY(srcPtr);
473 length = srcArrayPtr->used;
474
475 copyArrayPtr = (ByteArray *) ckalloc(BYTEARRAY_SIZE(length));
476 copyArrayPtr->used = length;
477 copyArrayPtr->allocated = length;
478 memcpy((VOID *) copyArrayPtr->bytes, (VOID *) srcArrayPtr->bytes,
479 (size_t) length);
480 SET_BYTEARRAY(copyPtr, copyArrayPtr);
481
482 copyPtr->typePtr = &tclByteArrayType;
483 }
484
485 /*
486 *---------------------------------------------------------------------------
487 *
488 * UpdateStringOfByteArray --
489 *
490 * Update the string representation for a ByteArray data object.
491 * Note: This procedure does not invalidate an existing old string rep
492 * so storage will be lost if this has not already been done.
493 *
494 * Results:
495 * None.
496 *
497 * Side effects:
498 * The object's string is set to a valid string that results from
499 * the ByteArray-to-string conversion.
500 *
501 * The object becomes a string object -- the internal rep is
502 * discarded and the typePtr becomes NULL.
503 *
504 *---------------------------------------------------------------------------
505 */
506
507 static void
508 UpdateStringOfByteArray(objPtr)
509 Tcl_Obj *objPtr; /* ByteArray object whose string rep to
510 * update. */
511 {
512 int i, length, size;
513 unsigned char *src;
514 char *dst;
515 ByteArray *byteArrayPtr;
516
517 byteArrayPtr = GET_BYTEARRAY(objPtr);
518 src = byteArrayPtr->bytes;
519 length = byteArrayPtr->used;
520
521 /*
522 * How much space will string rep need?
523 */
524
525 size = length;
526 for (i = 0; i < length; i++) {
527 if ((src[i] == 0) || (src[i] > 127)) {
528 size++;
529 }
530 }
531
532 dst = (char *) ckalloc((unsigned) (size + 1));
533 objPtr->bytes = dst;
534 objPtr->length = size;
535
536 if (size == length) {
537 memcpy((VOID *) dst, (VOID *) src, (size_t) size);
538 dst[size] = '\0';
539 } else {
540 for (i = 0; i < length; i++) {
541 dst += Tcl_UniCharToUtf(src[i], dst);
542 }
543 *dst = '\0';
544 }
545 }
546
547 /*
548 *----------------------------------------------------------------------
549 *
550 * Tcl_BinaryObjCmd --
551 *
552 * This procedure implements the "binary" Tcl command.
553 *
554 * Results:
555 * A standard Tcl result.
556 *
557 * Side effects:
558 * See the user documentation.
559 *
560 *----------------------------------------------------------------------
561 */
562
563 int
564 Tcl_BinaryObjCmd(dummy, interp, objc, objv)
565 ClientData dummy; /* Not used. */
566 Tcl_Interp *interp; /* Current interpreter. */
567 int objc; /* Number of arguments. */
568 Tcl_Obj *CONST objv[]; /* Argument objects. */
569 {
570 int arg; /* Index of next argument to consume. */
571 int value = 0; /* Current integer value to be packed.
572 * Initialized to avoid compiler warning. */
573 char cmd; /* Current format character. */
574 int count; /* Count associated with current format
575 * character. */
576 char *format; /* Pointer to current position in format
577 * string. */
578 Tcl_Obj *resultPtr; /* Object holding result buffer. */
579 unsigned char *buffer; /* Start of result buffer. */
580 unsigned char *cursor; /* Current position within result buffer. */
581 unsigned char *maxPos; /* Greatest position within result buffer that
582 * cursor has visited.*/
583 char *errorString, *errorValue, *str;
584 int offset, size, length, index;
585 static CONST char *options[] = {
586 "format", "scan", NULL
587 };
588 enum options {
589 BINARY_FORMAT, BINARY_SCAN
590 };
591
592 if (objc < 2) {
593 Tcl_WrongNumArgs(interp, 1, objv, "option ?arg arg ...?");
594 return TCL_ERROR;
595 }
596
597 if (Tcl_GetIndexFromObj(interp, objv[1], options, "option", 0,
598 &index) != TCL_OK) {
599 return TCL_ERROR;
600 }
601
602 switch ((enum options) index) {
603 case BINARY_FORMAT: {
604 if (objc < 3) {
605 Tcl_WrongNumArgs(interp, 2, objv, "formatString ?arg arg ...?");
606 return TCL_ERROR;
607 }
608
609 /*
610 * To avoid copying the data, we format the string in two passes.
611 * The first pass computes the size of the output buffer. The
612 * second pass places the formatted data into the buffer.
613 */
614
615 format = Tcl_GetString(objv[2]);
616 arg = 3;
617 offset = 0;
618 length = 0;
619 while (*format != '\0') {
620 str = format;
621 if (!GetFormatSpec(&format, &cmd, &count)) {
622 break;
623 }
624 switch (cmd) {
625 case 'a':
626 case 'A':
627 case 'b':
628 case 'B':
629 case 'h':
630 case 'H': {
631 /*
632 * For string-type specifiers, the count corresponds
633 * to the number of bytes in a single argument.
634 */
635
636 if (arg >= objc) {
637 goto badIndex;
638 }
639 if (count == BINARY_ALL) {
640 Tcl_GetByteArrayFromObj(objv[arg], &count);
641 } else if (count == BINARY_NOCOUNT) {
642 count = 1;
643 }
644 arg++;
645 if (cmd == 'a' || cmd == 'A') {
646 offset += count;
647 } else if (cmd == 'b' || cmd == 'B') {
648 offset += (count + 7) / 8;
649 } else {
650 offset += (count + 1) / 2;
651 }
652 break;
653 }
654 case 'c': {
655 size = 1;
656 goto doNumbers;
657 }
658 case 's':
659 case 'S': {
660 size = 2;
661 goto doNumbers;
662 }
663 case 'i':
664 case 'I': {
665 size = 4;
666 goto doNumbers;
667 }
668 case 'w':
669 case 'W': {
670 size = 8;
671 goto doNumbers;
672 }
673 case 'f': {
674 size = sizeof(float);
675 goto doNumbers;
676 }
677 case 'd': {
678 size = sizeof(double);
679
680 doNumbers:
681 if (arg >= objc) {
682 goto badIndex;
683 }
684
685 /*
686 * For number-type specifiers, the count corresponds
687 * to the number of elements in the list stored in
688 * a single argument. If no count is specified, then
689 * the argument is taken as a single non-list value.
690 */
691
692 if (count == BINARY_NOCOUNT) {
693 arg++;
694 count = 1;
695 } else {
696 int listc;
697 Tcl_Obj **listv;
698 if (Tcl_ListObjGetElements(interp, objv[arg++],
699 &listc, &listv) != TCL_OK) {
700 return TCL_ERROR;
701 }
702 if (count == BINARY_ALL) {
703 count = listc;
704 } else if (count > listc) {
705 Tcl_AppendResult(interp,
706 "number of elements in list does not match count",
707 (char *) NULL);
708 return TCL_ERROR;
709 }
710 }
711 offset += count*size;
712 break;
713 }
714 case 'x': {
715 if (count == BINARY_ALL) {
716 Tcl_AppendResult(interp,
717 "cannot use \"*\" in format string with \"x\"",
718 (char *) NULL);
719 return TCL_ERROR;
720 } else if (count == BINARY_NOCOUNT) {
721 count = 1;
722 }
723 offset += count;
724 break;
725 }
726 case 'X': {
727 if (count == BINARY_NOCOUNT) {
728 count = 1;
729 }
730 if ((count > offset) || (count == BINARY_ALL)) {
731 count = offset;
732 }
733 if (offset > length) {
734 length = offset;
735 }
736 offset -= count;
737 break;
738 }
739 case '@': {
740 if (offset > length) {
741 length = offset;
742 }
743 if (count == BINARY_ALL) {
744 offset = length;
745 } else if (count == BINARY_NOCOUNT) {
746 goto badCount;
747 } else {
748 offset = count;
749 }
750 break;
751 }
752 default: {
753 errorString = str;
754 goto badfield;
755 }
756 }
757 }
758 if (offset > length) {
759 length = offset;
760 }
761 if (length == 0) {
762 return TCL_OK;
763 }
764
765 /*
766 * Prepare the result object by preallocating the caclulated
767 * number of bytes and filling with nulls.
768 */
769
770 resultPtr = Tcl_GetObjResult(interp);
771 buffer = Tcl_SetByteArrayLength(resultPtr, length);
772 memset((VOID *) buffer, 0, (size_t) length);
773
774 /*
775 * Pack the data into the result object. Note that we can skip
776 * the error checking during this pass, since we have already
777 * parsed the string once.
778 */
779
780 arg = 3;
781 format = Tcl_GetString(objv[2]);
782 cursor = buffer;
783 maxPos = cursor;
784 while (*format != 0) {
785 if (!GetFormatSpec(&format, &cmd, &count)) {
786 break;
787 }
788 if ((count == 0) && (cmd != '@')) {
789 arg++;
790 continue;
791 }
792 switch (cmd) {
793 case 'a':
794 case 'A': {
795 char pad = (char) (cmd == 'a' ? '\0' : ' ');
796 unsigned char *bytes;
797
798 bytes = Tcl_GetByteArrayFromObj(objv[arg++], &length);
799
800 if (count == BINARY_ALL) {
801 count = length;
802 } else if (count == BINARY_NOCOUNT) {
803 count = 1;
804 }
805 if (length >= count) {
806 memcpy((VOID *) cursor, (VOID *) bytes,
807 (size_t) count);
808 } else {
809 memcpy((VOID *) cursor, (VOID *) bytes,
810 (size_t) length);
811 memset((VOID *) (cursor + length), pad,
812 (size_t) (count - length));
813 }
814 cursor += count;
815 break;
816 }
817 case 'b':
818 case 'B': {
819 unsigned char *last;
820
821 str = Tcl_GetStringFromObj(objv[arg++], &length);
822 if (count == BINARY_ALL) {
823 count = length;
824 } else if (count == BINARY_NOCOUNT) {
825 count = 1;
826 }
827 last = cursor + ((count + 7) / 8);
828 if (count > length) {
829 count = length;
830 }
831 value = 0;
832 errorString = "binary";
833 if (cmd == 'B') {
834 for (offset = 0; offset < count; offset++) {
835 value <<= 1;
836 if (str[offset] == '1') {
837 value |= 1;
838 } else if (str[offset] != '0') {
839 errorValue = str;
840 goto badValue;
841 }
842 if (((offset + 1) % 8) == 0) {
843 *cursor++ = (unsigned char) value;
844 value = 0;
845 }
846 }
847 } else {
848 for (offset = 0; offset < count; offset++) {
849 value >>= 1;
850 if (str[offset] == '1') {
851 value |= 128;
852 } else if (str[offset] != '0') {
853 errorValue = str;
854 goto badValue;
855 }
856 if (!((offset + 1) % 8)) {
857 *cursor++ = (unsigned char) value;
858 value = 0;
859 }
860 }
861 }
862 if ((offset % 8) != 0) {
863 if (cmd == 'B') {
864 value <<= 8 - (offset % 8);
865 } else {
866 value >>= 8 - (offset % 8);
867 }
868 *cursor++ = (unsigned char) value;
869 }
870 while (cursor < last) {
871 *cursor++ = '\0';
872 }
873 break;
874 }
875 case 'h':
876 case 'H': {
877 unsigned char *last;
878 int c;
879
880 str = Tcl_GetStringFromObj(objv[arg++], &length);
881 if (count == BINARY_ALL) {
882 count = length;
883 } else if (count == BINARY_NOCOUNT) {
884 count = 1;
885 }
886 last = cursor + ((count + 1) / 2);
887 if (count > length) {
888 count = length;
889 }
890 value = 0;
891 errorString = "hexadecimal";
892 if (cmd == 'H') {
893 for (offset = 0; offset < count; offset++) {
894 value <<= 4;
895 if (!isxdigit(UCHAR(str[offset]))) { /* INTL: digit */
896 errorValue = str;
897 goto badValue;
898 }
899 c = str[offset] - '0';
900 if (c > 9) {
901 c += ('0' - 'A') + 10;
902 }
903 if (c > 16) {
904 c += ('A' - 'a');
905 }
906 value |= (c & 0xf);
907 if (offset % 2) {
908 *cursor++ = (char) value;
909 value = 0;
910 }
911 }
912 } else {
913 for (offset = 0; offset < count; offset++) {
914 value >>= 4;
915
916 if (!isxdigit(UCHAR(str[offset]))) { /* INTL: digit */
917 errorValue = str;
918 goto badValue;
919 }
920 c = str[offset] - '0';
921 if (c > 9) {
922 c += ('0' - 'A') + 10;
923 }
924 if (c > 16) {
925 c += ('A' - 'a');
926 }
927 value |= ((c << 4) & 0xf0);
928 if (offset % 2) {
929 *cursor++ = (unsigned char)(value & 0xff);
930 value = 0;
931 }
932 }
933 }
934 if (offset % 2) {
935 if (cmd == 'H') {
936 value <<= 4;
937 } else {
938 value >>= 4;
939 }
940 *cursor++ = (unsigned char) value;
941 }
942
943 while (cursor < last) {
944 *cursor++ = '\0';
945 }
946 break;
947 }
948 case 'c':
949 case 's':
950 case 'S':
951 case 'i':
952 case 'I':
953 case 'w':
954 case 'W':
955 case 'd':
956 case 'f': {
957 int listc, i;
958 Tcl_Obj **listv;
959
960 if (count == BINARY_NOCOUNT) {
961 /*
962 * Note that we are casting away the const-ness of
963 * objv, but this is safe since we aren't going to
964 * modify the array.
965 */
966
967 listv = (Tcl_Obj**)(objv + arg);
968 listc = 1;
969 count = 1;
970 } else {
971 Tcl_ListObjGetElements(interp, objv[arg],
972 &listc, &listv);
973 if (count == BINARY_ALL) {
974 count = listc;
975 }
976 }
977 arg++;
978 for (i = 0; i < count; i++) {
979 if (FormatNumber(interp, cmd, listv[i], &cursor)
980 != TCL_OK) {
981 return TCL_ERROR;
982 }
983 }
984 break;
985 }
986 case 'x': {
987 if (count == BINARY_NOCOUNT) {
988 count = 1;
989 }
990 memset(cursor, 0, (size_t) count);
991 cursor += count;
992 break;
993 }
994 case 'X': {
995 if (cursor > maxPos) {
996 maxPos = cursor;
997 }
998 if (count == BINARY_NOCOUNT) {
999 count = 1;
1000 }
1001 if ((count == BINARY_ALL)
1002 || (count > (cursor - buffer))) {
1003 cursor = buffer;
1004 } else {
1005 cursor -= count;
1006 }
1007 break;
1008 }
1009 case '@': {
1010 if (cursor > maxPos) {
1011 maxPos = cursor;
1012 }
1013 if (count == BINARY_ALL) {
1014 cursor = maxPos;
1015 } else {
1016 cursor = buffer + count;
1017 }
1018 break;
1019 }
1020 }
1021 }
1022 break;
1023 }
1024 case BINARY_SCAN: {
1025 int i;
1026 Tcl_Obj *valuePtr, *elementPtr;
1027 Tcl_HashTable numberCacheHash;
1028 Tcl_HashTable *numberCachePtr;
1029
1030 if (objc < 4) {
1031 Tcl_WrongNumArgs(interp, 2, objv,
1032 "value formatString ?varName varName ...?");
1033 return TCL_ERROR;
1034 }
1035 numberCachePtr = &numberCacheHash;
1036 Tcl_InitHashTable(numberCachePtr, TCL_ONE_WORD_KEYS);
1037 buffer = Tcl_GetByteArrayFromObj(objv[2], &length);
1038 format = Tcl_GetString(objv[3]);
1039 cursor = buffer;
1040 arg = 4;
1041 offset = 0;
1042 while (*format != '\0') {
1043 str = format;
1044 if (!GetFormatSpec(&format, &cmd, &count)) {
1045 goto done;
1046 }
1047 switch (cmd) {
1048 case 'a':
1049 case 'A': {
1050 unsigned char *src;
1051
1052 if (arg >= objc) {
1053 if (numberCachePtr != NULL) {
1054 Tcl_DeleteHashTable(numberCachePtr);
1055 }
1056 goto badIndex;
1057 }
1058 if (count == BINARY_ALL) {
1059 count = length - offset;
1060 } else {
1061 if (count == BINARY_NOCOUNT) {
1062 count = 1;
1063 }
1064 if (count > (length - offset)) {
1065 goto done;
1066 }
1067 }
1068
1069 src = buffer + offset;
1070 size = count;
1071
1072 /*
1073 * Trim trailing nulls and spaces, if necessary.
1074 */
1075
1076 if (cmd == 'A') {
1077 while (size > 0) {
1078 if (src[size-1] != '\0' && src[size-1] != ' ') {
1079 break;
1080 }
1081 size--;
1082 }
1083 }
1084 valuePtr = Tcl_NewByteArrayObj(src, size);
1085 resultPtr = Tcl_ObjSetVar2(interp, objv[arg],
1086 NULL, valuePtr, TCL_LEAVE_ERR_MSG);
1087 arg++;
1088 if (resultPtr == NULL) {
1089 if (numberCachePtr != NULL) {
1090 Tcl_DeleteHashTable(numberCachePtr);
1091 }
1092 Tcl_DecrRefCount(valuePtr); /* unneeded */
1093 return TCL_ERROR;
1094 }
1095 offset += count;
1096 break;
1097 }
1098 case 'b':
1099 case 'B': {
1100 unsigned char *src;
1101 char *dest;
1102
1103 if (arg >= objc) {
1104 if (numberCachePtr != NULL) {
1105 Tcl_DeleteHashTable(numberCachePtr);
1106 }
1107 goto badIndex;
1108 }
1109 if (count == BINARY_ALL) {
1110 count = (length - offset) * 8;
1111 } else {
1112 if (count == BINARY_NOCOUNT) {
1113 count = 1;
1114 }
1115 if (count > (length - offset) * 8) {
1116 goto done;
1117 }
1118 }
1119 src = buffer + offset;
1120 valuePtr = Tcl_NewObj();
1121 Tcl_SetObjLength(valuePtr, count);
1122 dest = Tcl_GetString(valuePtr);
1123
1124 if (cmd == 'b') {
1125 for (i = 0; i < count; i++) {
1126 if (i % 8) {
1127 value >>= 1;
1128 } else {
1129 value = *src++;
1130 }
1131 *dest++ = (char) ((value & 1) ? '1' : '0');
1132 }
1133 } else {
1134 for (i = 0; i < count; i++) {
1135 if (i % 8) {
1136 value <<= 1;
1137 } else {
1138 value = *src++;
1139 }
1140 *dest++ = (char) ((value & 0x80) ? '1' : '0');
1141 }
1142 }
1143
1144 resultPtr = Tcl_ObjSetVar2(interp, objv[arg],
1145 NULL, valuePtr, TCL_LEAVE_ERR_MSG);
1146 arg++;
1147 if (resultPtr == NULL) {
1148 if (numberCachePtr != NULL) {
1149 Tcl_DeleteHashTable(numberCachePtr);
1150 }
1151 Tcl_DecrRefCount(valuePtr); /* unneeded */
1152 return TCL_ERROR;
1153 }
1154 offset += (count + 7 ) / 8;
1155 break;
1156 }
1157 case 'h':
1158 case 'H': {
1159 char *dest;
1160 unsigned char *src;
1161 int i;
1162 static char hexdigit[] = "0123456789abcdef";
1163
1164 if (arg >= objc) {
1165 if (numberCachePtr != NULL) {
1166 Tcl_DeleteHashTable(numberCachePtr);
1167 }
1168 goto badIndex;
1169 }
1170 if (count == BINARY_ALL) {
1171 count = (length - offset)*2;
1172 } else {
1173 if (count == BINARY_NOCOUNT) {
1174 count = 1;
1175 }
1176 if (count > (length - offset)*2) {
1177 goto done;
1178 }
1179 }
1180 src = buffer + offset;
1181 valuePtr = Tcl_NewObj();
1182 Tcl_SetObjLength(valuePtr, count);
1183 dest = Tcl_GetString(valuePtr);
1184
1185 if (cmd == 'h') {
1186 for (i = 0; i < count; i++) {
1187 if (i % 2) {
1188 value >>= 4;
1189 } else {
1190 value = *src++;
1191 }
1192 *dest++ = hexdigit[value & 0xf];
1193 }
1194 } else {
1195 for (i = 0; i < count; i++) {
1196 if (i % 2) {
1197 value <<= 4;
1198 } else {
1199 value = *src++;
1200 }
1201 *dest++ = hexdigit[(value >> 4) & 0xf];
1202 }
1203 }
1204
1205 resultPtr = Tcl_ObjSetVar2(interp, objv[arg],
1206 NULL, valuePtr, TCL_LEAVE_ERR_MSG);
1207 arg++;
1208 if (resultPtr == NULL) {
1209 if (numberCachePtr != NULL) {
1210 Tcl_DeleteHashTable(numberCachePtr);
1211 }
1212 Tcl_DecrRefCount(valuePtr); /* unneeded */
1213 return TCL_ERROR;
1214 }
1215 offset += (count + 1) / 2;
1216 break;
1217 }
1218 case 'c': {
1219 size = 1;
1220 goto scanNumber;
1221 }
1222 case 's':
1223 case 'S': {
1224 size = 2;
1225 goto scanNumber;
1226 }
1227 case 'i':
1228 case 'I': {
1229 size = 4;
1230 goto scanNumber;
1231 }
1232 case 'w':
1233 case 'W': {
1234 size = 8;
1235 goto scanNumber;
1236 }
1237 case 'f': {
1238 size = sizeof(float);
1239 goto scanNumber;
1240 }
1241 case 'd': {
1242 unsigned char *src;
1243
1244 size = sizeof(double);
1245 /* fall through */
1246
1247 scanNumber:
1248 if (arg >= objc) {
1249 if (numberCachePtr != NULL) {
1250 Tcl_DeleteHashTable(numberCachePtr);
1251 }
1252 goto badIndex;
1253 }
1254 if (count == BINARY_NOCOUNT) {
1255 if ((length - offset) < size) {
1256 goto done;
1257 }
1258 valuePtr = ScanNumber(buffer+offset, cmd,
1259 &numberCachePtr);
1260 offset += size;
1261 } else {
1262 if (count == BINARY_ALL) {
1263 count = (length - offset) / size;
1264 }
1265 if ((length - offset) < (count * size)) {
1266 goto done;
1267 }
1268 valuePtr = Tcl_NewObj();
1269 src = buffer+offset;
1270 for (i = 0; i < count; i++) {
1271 elementPtr = ScanNumber(src, cmd,
1272 &numberCachePtr);
1273 src += size;
1274 Tcl_ListObjAppendElement(NULL, valuePtr,
1275 elementPtr);
1276 }
1277 offset += count*size;
1278 }
1279
1280 resultPtr = Tcl_ObjSetVar2(interp, objv[arg],
1281 NULL, valuePtr, TCL_LEAVE_ERR_MSG);
1282 arg++;
1283 if (resultPtr == NULL) {
1284 if (numberCachePtr != NULL) {
1285 Tcl_DeleteHashTable(numberCachePtr);
1286 }
1287 Tcl_DecrRefCount(valuePtr); /* unneeded */
1288 return TCL_ERROR;
1289 }
1290 break;
1291 }
1292 case 'x': {
1293 if (count == BINARY_NOCOUNT) {
1294 count = 1;
1295 }
1296 if ((count == BINARY_ALL)
1297 || (count > (length - offset))) {
1298 offset = length;
1299 } else {
1300 offset += count;
1301 }
1302 break;
1303 }
1304 case 'X': {
1305 if (count == BINARY_NOCOUNT) {
1306 count = 1;
1307 }
1308 if ((count == BINARY_ALL) || (count > offset)) {
1309 offset = 0;
1310 } else {
1311 offset -= count;
1312 }
1313 break;
1314 }
1315 case '@': {
1316 if (count == BINARY_NOCOUNT) {
1317 if (numberCachePtr != NULL) {
1318 Tcl_DeleteHashTable(numberCachePtr);
1319 }
1320 goto badCount;
1321 }
1322 if ((count == BINARY_ALL) || (count > length)) {
1323 offset = length;
1324 } else {
1325 offset = count;
1326 }
1327 break;
1328 }
1329 default: {
1330 if (numberCachePtr != NULL) {
1331 Tcl_DeleteHashTable(numberCachePtr);
1332 }
1333 errorString = str;
1334 goto badfield;
1335 }
1336 }
1337 }
1338
1339 /*
1340 * Set the result to the last position of the cursor.
1341 */
1342
1343 done:
1344 Tcl_ResetResult(interp);
1345 Tcl_SetLongObj(Tcl_GetObjResult(interp), arg - 4);
1346 if (numberCachePtr != NULL) {
1347 Tcl_DeleteHashTable(numberCachePtr);
1348 }
1349 break;
1350 }
1351 }
1352 return TCL_OK;
1353
1354 badValue:
1355 Tcl_ResetResult(interp);
1356 Tcl_AppendStringsToObj(Tcl_GetObjResult(interp), "expected ", errorString,
1357 " string but got \"", errorValue, "\" instead", NULL);
1358 return TCL_ERROR;
1359
1360 badCount:
1361 errorString = "missing count for \"@\" field specifier";
1362 goto error;
1363
1364 badIndex:
1365 errorString = "not enough arguments for all format specifiers";
1366 goto error;
1367
1368 badfield: {
1369 Tcl_UniChar ch;
1370 char buf[TCL_UTF_MAX + 1];
1371
1372 Tcl_UtfToUniChar(errorString, &ch);
1373 buf[Tcl_UniCharToUtf(ch, buf)] = '\0';
1374 Tcl_AppendResult(interp, "bad field specifier \"", buf, "\"", NULL);
1375 return TCL_ERROR;
1376 }
1377
1378 error:
1379 Tcl_AppendResult(interp, errorString, NULL);
1380 return TCL_ERROR;
1381 }
1382
1383 /*
1384 *----------------------------------------------------------------------
1385 *
1386 * GetFormatSpec --
1387 *
1388 * This function parses the format strings used in the binary
1389 * format and scan commands.
1390 *
1391 * Results:
1392 * Moves the formatPtr to the start of the next command. Returns
1393 * the current command character and count in cmdPtr and countPtr.
1394 * The count is set to BINARY_ALL if the count character was '*'
1395 * or BINARY_NOCOUNT if no count was specified. Returns 1 on
1396 * success, or 0 if the string did not have a format specifier.
1397 *
1398 * Side effects:
1399 * None.
1400 *
1401 *----------------------------------------------------------------------
1402 */
1403
1404 static int
1405 GetFormatSpec(formatPtr, cmdPtr, countPtr)
1406 char **formatPtr; /* Pointer to format string. */
1407 char *cmdPtr; /* Pointer to location of command char. */
1408 int *countPtr; /* Pointer to repeat count value. */
1409 {
1410 /*
1411 * Skip any leading blanks.
1412 */
1413
1414 while (**formatPtr == ' ') {
1415 (*formatPtr)++;
1416 }
1417
1418 /*
1419 * The string was empty, except for whitespace, so fail.
1420 */
1421
1422 if (!(**formatPtr)) {
1423 return 0;
1424 }
1425
1426 /*
1427 * Extract the command character and any trailing digits or '*'.
1428 */
1429
1430 *cmdPtr = **formatPtr;
1431 (*formatPtr)++;
1432 if (**formatPtr == '*') {
1433 (*formatPtr)++;
1434 (*countPtr) = BINARY_ALL;
1435 } else if (isdigit(UCHAR(**formatPtr))) { /* INTL: digit */
1436 (*countPtr) = strtoul(*formatPtr, formatPtr, 10);
1437 } else {
1438 (*countPtr) = BINARY_NOCOUNT;
1439 }
1440 return 1;
1441 }
1442
1443 /*
1444 *----------------------------------------------------------------------
1445 *
1446 * FormatNumber --
1447 *
1448 * This routine is called by Tcl_BinaryObjCmd to format a number
1449 * into a location pointed at by cursor.
1450 *
1451 * Results:
1452 * A standard Tcl result.
1453 *
1454 * Side effects:
1455 * Moves the cursor to the next location to be written into.
1456 *
1457 *----------------------------------------------------------------------
1458 */
1459
1460 static int
1461 FormatNumber(interp, type, src, cursorPtr)
1462 Tcl_Interp *interp; /* Current interpreter, used to report
1463 * errors. */
1464 int type; /* Type of number to format. */
1465 Tcl_Obj *src; /* Number to format. */
1466 unsigned char **cursorPtr; /* Pointer to index into destination buffer. */
1467 {
1468 long value;
1469 double dvalue;
1470 Tcl_WideInt wvalue;
1471
1472 switch (type) {
1473 case 'd':
1474 case 'f':
1475 /*
1476 * For floating point types, we need to copy the data using
1477 * memcpy to avoid alignment issues.
1478 */
1479
1480 if (Tcl_GetDoubleFromObj(interp, src, &dvalue) != TCL_OK) {
1481 return TCL_ERROR;
1482 }
1483 if (type == 'd') {
1484 memcpy((VOID *) *cursorPtr, (VOID *) &dvalue, sizeof(double));
1485 *cursorPtr += sizeof(double);
1486 } else {
1487 float fvalue;
1488
1489 /*
1490 * Because some compilers will generate floating point exceptions
1491 * on an overflow cast (e.g. Borland), we restrict the values
1492 * to the valid range for float.
1493 */
1494
1495 if (fabs(dvalue) > (double)FLT_MAX) {
1496 fvalue = (dvalue >= 0.0) ? FLT_MAX : -FLT_MAX;
1497 } else {
1498 fvalue = (float) dvalue;
1499 }
1500 memcpy((VOID *) *cursorPtr, (VOID *) &fvalue, sizeof(float));
1501 *cursorPtr += sizeof(float);
1502 }
1503 return TCL_OK;
1504
1505 /*
1506 * Next cases separate from other integer cases because we
1507 * need a different API to get a wide.
1508 */
1509 case 'w':
1510 case 'W':
1511 if (Tcl_GetWideIntFromObj(interp, src, &wvalue) != TCL_OK) {
1512 return TCL_ERROR;
1513 }
1514 if (type == 'w') {
1515 *(*cursorPtr)++ = (unsigned char) wvalue;
1516 *(*cursorPtr)++ = (unsigned char) (wvalue >> 8);
1517 *(*cursorPtr)++ = (unsigned char) (wvalue >> 16);
1518 *(*cursorPtr)++ = (unsigned char) (wvalue >> 24);
1519 *(*cursorPtr)++ = (unsigned char) (wvalue >> 32);
1520 *(*cursorPtr)++ = (unsigned char) (wvalue >> 40);
1521 *(*cursorPtr)++ = (unsigned char) (wvalue >> 48);
1522 *(*cursorPtr)++ = (unsigned char) (wvalue >> 56);
1523 } else {
1524 *(*cursorPtr)++ = (unsigned char) (wvalue >> 56);
1525 *(*cursorPtr)++ = (unsigned char) (wvalue >> 48);
1526 *(*cursorPtr)++ = (unsigned char) (wvalue >> 40);
1527 *(*cursorPtr)++ = (unsigned char) (wvalue >> 32);
1528 *(*cursorPtr)++ = (unsigned char) (wvalue >> 24);
1529 *(*cursorPtr)++ = (unsigned char) (wvalue >> 16);
1530 *(*cursorPtr)++ = (unsigned char) (wvalue >> 8);
1531 *(*cursorPtr)++ = (unsigned char) wvalue;
1532 }
1533 return TCL_OK;
1534 default:
1535 if (Tcl_GetLongFromObj(interp, src, &value) != TCL_OK) {
1536 return TCL_ERROR;
1537 }
1538 if (type == 'c') {
1539 *(*cursorPtr)++ = (unsigned char) value;
1540 } else if (type == 's') {
1541 *(*cursorPtr)++ = (unsigned char) value;
1542 *(*cursorPtr)++ = (unsigned char) (value >> 8);
1543 } else if (type == 'S') {
1544 *(*cursorPtr)++ = (unsigned char) (value >> 8);
1545 *(*cursorPtr)++ = (unsigned char) value;
1546 } else if (type == 'i') {
1547 *(*cursorPtr)++ = (unsigned char) value;
1548 *(*cursorPtr)++ = (unsigned char) (value >> 8);
1549 *(*cursorPtr)++ = (unsigned char) (value >> 16);
1550 *(*cursorPtr)++ = (unsigned char) (value >> 24);
1551 } else if (type == 'I') {
1552 *(*cursorPtr)++ = (unsigned char) (value >> 24);
1553 *(*cursorPtr)++ = (unsigned char) (value >> 16);
1554 *(*cursorPtr)++ = (unsigned char) (value >> 8);
1555 *(*cursorPtr)++ = (unsigned char) value;
1556 }
1557 return TCL_OK;
1558 }
1559 }
1560
1561 /*
1562 *----------------------------------------------------------------------
1563 *
1564 * ScanNumber --
1565 *
1566 * This routine is called by Tcl_BinaryObjCmd to scan a number
1567 * out of a buffer.
1568 *
1569 * Results:
1570 * Returns a newly created object containing the scanned number.
1571 * This object has a ref count of zero.
1572 *
1573 * Side effects:
1574 * Might reuse an object in the number cache, place a new object
1575 * in the cache, or delete the cache and set the reference to
1576 * it (itself passed in by reference) to NULL.
1577 *
1578 *----------------------------------------------------------------------
1579 */
1580
1581 static Tcl_Obj *
1582 ScanNumber(buffer, type, numberCachePtrPtr)
1583 unsigned char *buffer; /* Buffer to scan number from. */
1584 int type; /* Format character from "binary scan" */
1585 Tcl_HashTable **numberCachePtrPtr;
1586 /* Place to look for cache of scanned
1587 * value objects, or NULL if too many
1588 * different numbers have been scanned. */
1589 {
1590 long value;
1591 Tcl_WideUInt uwvalue;
1592
1593 /*
1594 * We cannot rely on the compiler to properly sign extend integer values
1595 * when we cast from smaller values to larger values because we don't know
1596 * the exact size of the integer types. So, we have to handle sign
1597 * extension explicitly by checking the high bit and padding with 1's as
1598 * needed.
1599 */
1600
1601 switch (type) {
1602 case 'c':
1603 /*
1604 * Characters need special handling. We want to produce a
1605 * signed result, but on some platforms (such as AIX) chars
1606 * are unsigned. To deal with this, check for a value that
1607 * should be negative but isn't.
1608 */
1609
1610 value = buffer[0];
1611 if (value & 0x80) {
1612 value |= -0x100;
1613 }
1614 goto returnNumericObject;
1615
1616 case 's':
1617 value = (long) (buffer[0] + (buffer[1] << 8));
1618 goto shortValue;
1619 case 'S':
1620 value = (long) (buffer[1] + (buffer[0] << 8));
1621 shortValue:
1622 if (value & 0x8000) {
1623 value |= -0x10000;
1624 }
1625 goto returnNumericObject;
1626
1627 case 'i':
1628 value = (long) (buffer[0]
1629 + (buffer[1] << 8)
1630 + (buffer[2] << 16)
1631 + (buffer[3] << 24));
1632 goto intValue;
1633 case 'I':
1634 value = (long) (buffer[3]
1635 + (buffer[2] << 8)
1636 + (buffer[1] << 16)
1637 + (buffer[0] << 24));
1638 intValue:
1639 /*
1640 * Check to see if the value was sign extended properly on
1641 * systems where an int is more than 32-bits.
1642 */
1643
1644 if ((value & (((unsigned int)1)<<31)) && (value > 0)) {
1645 value -= (((unsigned int)1)<<31);
1646 value -= (((unsigned int)1)<<31);
1647 }
1648 returnNumericObject:
1649 if (*numberCachePtrPtr == NULL) {
1650 return Tcl_NewLongObj(value);
1651 } else {
1652 register Tcl_HashTable *tablePtr = *numberCachePtrPtr;
1653 register Tcl_HashEntry *hPtr;
1654 int isNew;
1655
1656 hPtr = Tcl_CreateHashEntry(tablePtr, (char *)value, &isNew);
1657 if (!isNew) {
1658 return (Tcl_Obj *) Tcl_GetHashValue(hPtr);
1659 }
1660 if (tablePtr->numEntries > BINARY_SCAN_MAX_CACHE) {
1661 /*
1662 * We've overflowed the cache! Someone's parsing
1663 * a LOT of varied binary data in a single call!
1664 * Bail out by switching back to the old behaviour
1665 * for the rest of the scan.
1666 *
1667 * Note that anyone just using the 'c' conversion
1668 * (for bytes) cannot trigger this.
1669 */
1670 Tcl_DeleteHashTable(tablePtr);
1671 *numberCachePtrPtr = NULL;
1672 return Tcl_NewLongObj(value);
1673 } else {
1674 register Tcl_Obj *objPtr = Tcl_NewLongObj(value);
1675 /* Don't need to fiddle with refcount... */
1676 Tcl_SetHashValue(hPtr, (ClientData) objPtr);
1677 return objPtr;
1678 }
1679 }
1680 case 'w':
1681 uwvalue = ((Tcl_WideUInt) buffer[0])
1682 | (((Tcl_WideUInt) buffer[1]) << 8)
1683 | (((Tcl_WideUInt) buffer[2]) << 16)
1684 | (((Tcl_WideUInt) buffer[3]) << 24)
1685 | (((Tcl_WideUInt) buffer[4]) << 32)
1686 | (((Tcl_WideUInt) buffer[5]) << 40)
1687 | (((Tcl_WideUInt) buffer[6]) << 48)
1688 | (((Tcl_WideUInt) buffer[7]) << 56);
1689 return Tcl_NewWideIntObj((Tcl_WideInt) uwvalue);
1690 case 'W':
1691 uwvalue = ((Tcl_WideUInt) buffer[7])
1692 | (((Tcl_WideUInt) buffer[6]) << 8)
1693 | (((Tcl_WideUInt) buffer[5]) << 16)
1694 | (((Tcl_WideUInt) buffer[4]) << 24)
1695 | (((Tcl_WideUInt) buffer[3]) << 32)
1696 | (((Tcl_WideUInt) buffer[2]) << 40)
1697 | (((Tcl_WideUInt) buffer[1]) << 48)
1698 | (((Tcl_WideUInt) buffer[0]) << 56);
1699 return Tcl_NewWideIntObj((Tcl_WideInt) uwvalue);
1700 case 'f': {
1701 float fvalue;
1702 memcpy((VOID *) &fvalue, (VOID *) buffer, sizeof(float));
1703 return Tcl_NewDoubleObj(fvalue);
1704 }
1705 case 'd': {
1706 double dvalue;
1707 memcpy((VOID *) &dvalue, (VOID *) buffer, sizeof(double));
1708 return Tcl_NewDoubleObj(dvalue);
1709 }
1710 }
1711 return NULL;
1712 }