1.0.5.54: fix thinko in src/code/array.lisp
[sbcl.git] / src / code / array.lisp
1 ;;;; functions to implement arrays
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!IMPL")
13
14 #!-sb-fluid
15 (declaim (inline fill-pointer array-has-fill-pointer-p adjustable-array-p
16                  array-displacement))
17 \f
18 ;;;; miscellaneous accessor functions
19
20 ;;; These functions are only needed by the interpreter, 'cause the
21 ;;; compiler inlines them.
22 (macrolet ((def (name)
23              `(progn
24                 (defun ,name (array)
25                   (,name array))
26                 (defun (setf ,name) (value array)
27                   (setf (,name array) value)))))
28   (def %array-fill-pointer)
29   (def %array-fill-pointer-p)
30   (def %array-available-elements)
31   (def %array-data-vector)
32   (def %array-displacement)
33   (def %array-displaced-p))
34
35 (defun %array-rank (array)
36   (%array-rank array))
37
38 (defun %array-dimension (array axis)
39   (%array-dimension array axis))
40
41 (defun %set-array-dimension (array axis value)
42   (%set-array-dimension array axis value))
43
44 (defun %check-bound (array bound index)
45   (declare (type index bound)
46            (fixnum index))
47   (%check-bound array bound index))
48
49 (defun %with-array-data (array start end)
50   (%with-array-data-macro array start end :fail-inline? t))
51
52 (defun %data-vector-and-index (array index)
53   (if (array-header-p array)
54       (multiple-value-bind (vector index)
55           (%with-array-data array index nil)
56         (values vector index))
57       (values array index)))
58
59 (defun simple-vector-compare-and-swap (vector index old new)
60   #!+(or x86 x86-64)
61   (%simple-vector-compare-and-swap vector
62                                    (%check-bound vector (length vector) index)
63                                    old
64                                    new)
65   #!-(or x86 x86-64)
66   (let ((n-old (svref vector index)))
67     (when (eq old n-old)
68       (setf (svref vector index) new))
69     n-old))
70
71 ;;; It'd waste space to expand copies of error handling in every
72 ;;; inline %WITH-ARRAY-DATA, so we have them call this function
73 ;;; instead. This is just a wrapper which is known never to return.
74 (defun failed-%with-array-data (array start end)
75   (declare (notinline %with-array-data))
76   (%with-array-data array start end)
77   (bug "called FAILED-%WITH-ARRAY-DATA with valid array parameters?"))
78 \f
79 ;;;; MAKE-ARRAY
80 (eval-when (:compile-toplevel :execute)
81   (sb!xc:defmacro pick-vector-type (type &rest specs)
82     `(cond ,@(mapcar (lambda (spec)
83                        `(,(if (eq (car spec) t)
84                               t
85                               `(subtypep ,type ',(car spec)))
86                          ,@(cdr spec)))
87                      specs))))
88
89 ;;; These functions are used in the implementation of MAKE-ARRAY for
90 ;;; complex arrays. There are lots of transforms to simplify
91 ;;; MAKE-ARRAY for various easy cases, but not for all reasonable
92 ;;; cases, so e.g. as of sbcl-0.6.6 we still make full calls to
93 ;;; MAKE-ARRAY for any non-simple array. Thus, there's some value to
94 ;;; making this somewhat efficient, at least not doing full calls to
95 ;;; SUBTYPEP in the easy cases.
96 (defun %vector-widetag-and-n-bits (type)
97   (case type
98     ;; Pick off some easy common cases.
99     ;;
100     ;; (Perhaps we should make a much more exhaustive table of easy
101     ;; common cases here. Or perhaps the effort would be better spent
102     ;; on smarter compiler transforms which do the calculation once
103     ;; and for all in any reasonable user programs.)
104     ((t)
105      (values #.sb!vm:simple-vector-widetag #.sb!vm:n-word-bits))
106     ((base-char standard-char #!-sb-unicode character)
107      (values #.sb!vm:simple-base-string-widetag #.sb!vm:n-byte-bits))
108     #!+sb-unicode
109     ((character)
110      (values #.sb!vm:simple-character-string-widetag #.sb!vm:n-word-bits))
111     ((bit)
112      (values #.sb!vm:simple-bit-vector-widetag 1))
113     ;; OK, we have to wade into SUBTYPEPing after all.
114     (t
115      #.`(pick-vector-type type
116          ,@(map 'list
117                 (lambda (saetp)
118                   `(,(sb!vm:saetp-specifier saetp)
119                     (values ,(sb!vm:saetp-typecode saetp)
120                             ,(sb!vm:saetp-n-bits saetp))))
121                 sb!vm:*specialized-array-element-type-properties*)))))
122
123 (defun %complex-vector-widetag (type)
124   (case type
125     ;; Pick off some easy common cases.
126     ((t)
127      #.sb!vm:complex-vector-widetag)
128     ((base-char #!-sb-unicode character)
129      #.sb!vm:complex-base-string-widetag)
130     #!+sb-unicode
131     ((character)
132      #.sb!vm:complex-character-string-widetag)
133     ((nil)
134      #.sb!vm:complex-vector-nil-widetag)
135     ((bit)
136      #.sb!vm:complex-bit-vector-widetag)
137     ;; OK, we have to wade into SUBTYPEPing after all.
138     (t
139      (pick-vector-type type
140        (nil #.sb!vm:complex-vector-nil-widetag)
141        #!-sb-unicode
142        (character #.sb!vm:complex-base-string-widetag)
143        #!+sb-unicode
144        (base-char #.sb!vm:complex-base-string-widetag)
145        #!+sb-unicode
146        (character #.sb!vm:complex-character-string-widetag)
147        (bit #.sb!vm:complex-bit-vector-widetag)
148        (t #.sb!vm:complex-vector-widetag)))))
149
150 (defun make-array (dimensions &key
151                               (element-type t)
152                               (initial-element nil initial-element-p)
153                               (initial-contents nil initial-contents-p)
154                               adjustable fill-pointer
155                               displaced-to displaced-index-offset)
156   (let* ((dimensions (if (listp dimensions) dimensions (list dimensions)))
157          (array-rank (length (the list dimensions)))
158          (simple (and (null fill-pointer)
159                       (not adjustable)
160                       (null displaced-to))))
161     (declare (fixnum array-rank))
162     (when (and displaced-index-offset (null displaced-to))
163       (error "can't specify :DISPLACED-INDEX-OFFSET without :DISPLACED-TO"))
164     (when (and displaced-to
165                (arrayp displaced-to)
166                (not (equal (array-element-type displaced-to)
167                            (upgraded-array-element-type element-type))))
168       (error "Array element type of :DISPLACED-TO array does not match specified element type"))
169     (if (and simple (= array-rank 1))
170         ;; it's a (SIMPLE-ARRAY * (*))
171         (multiple-value-bind (type n-bits)
172             (%vector-widetag-and-n-bits element-type)
173           (declare (type (unsigned-byte 8) type)
174                    (type (integer 0 256) n-bits))
175           (let* ((length (car dimensions))
176                  (array (allocate-vector
177                          type
178                          length
179                          (ceiling
180                           (* (if (or (= type sb!vm:simple-base-string-widetag)
181                                      #!+sb-unicode
182                                      (= type
183                                         sb!vm:simple-character-string-widetag))
184                                  (1+ length)
185                                  length)
186                              n-bits)
187                           sb!vm:n-word-bits))))
188             (declare (type index length))
189             (when initial-element-p
190               (fill array initial-element))
191             (when initial-contents-p
192               (when initial-element-p
193                 (error "can't specify both :INITIAL-ELEMENT and ~
194                        :INITIAL-CONTENTS"))
195               (unless (= length (length initial-contents))
196                 (error "There are ~W elements in the :INITIAL-CONTENTS, but ~
197                        the vector length is ~W."
198                        (length initial-contents)
199                        length))
200               (replace array initial-contents))
201             array))
202         ;; it's either a complex array or a multidimensional array.
203         (let* ((total-size (reduce #'* dimensions))
204                (data (or displaced-to
205                          (data-vector-from-inits
206                           dimensions total-size element-type
207                           initial-contents initial-contents-p
208                           initial-element initial-element-p)))
209                (array (make-array-header
210                        (cond ((= array-rank 1)
211                               (%complex-vector-widetag element-type))
212                              (simple sb!vm:simple-array-widetag)
213                              (t sb!vm:complex-array-widetag))
214                        array-rank)))
215           (cond (fill-pointer
216                  (unless (= array-rank 1)
217                    (error "Only vectors can have fill pointers."))
218                  (let ((length (car dimensions)))
219                    (declare (fixnum length))
220                    (setf (%array-fill-pointer array)
221                      (cond ((eq fill-pointer t)
222                             length)
223                            (t
224                             (unless (and (fixnump fill-pointer)
225                                          (>= fill-pointer 0)
226                                          (<= fill-pointer length))
227                               ;; FIXME: should be TYPE-ERROR?
228                               (error "invalid fill-pointer ~W"
229                                      fill-pointer))
230                             fill-pointer))))
231                  (setf (%array-fill-pointer-p array) t))
232                 (t
233                  (setf (%array-fill-pointer array) total-size)
234                  (setf (%array-fill-pointer-p array) nil)))
235           (setf (%array-available-elements array) total-size)
236           (setf (%array-data-vector array) data)
237           (cond (displaced-to
238                  (when (or initial-element-p initial-contents-p)
239                    (error "Neither :INITIAL-ELEMENT nor :INITIAL-CONTENTS ~
240                    can be specified along with :DISPLACED-TO"))
241                  (let ((offset (or displaced-index-offset 0)))
242                    (when (> (+ offset total-size)
243                             (array-total-size displaced-to))
244                      (error "~S doesn't have enough elements." displaced-to))
245                    (setf (%array-displacement array) offset)
246                    (setf (%array-displaced-p array) t)))
247                 (t
248                  (setf (%array-displaced-p array) nil)))
249           (let ((axis 0))
250             (dolist (dim dimensions)
251               (setf (%array-dimension array axis) dim)
252               (incf axis)))
253           array))))
254
255 (defun make-static-vector (length &key
256                            (element-type '(unsigned-byte 8))
257                            (initial-contents nil initial-contents-p)
258                            (initial-element nil initial-element-p))
259   "Allocate vector of LENGTH elements in static space. Only allocation
260 of specialized arrays is supported."
261   ;; STEP 1: check inputs fully
262   ;;
263   ;; This way of doing explicit checks before the vector is allocated
264   ;; is expensive, but probably worth the trouble as once we've allocated
265   ;; the vector we have no way to get rid of it anymore...
266   (when (eq t (upgraded-array-element-type element-type))
267     (error "Static arrays of type ~S not supported."
268            element-type))
269   (when initial-contents-p
270     (when initial-element-p
271       (error "can't specify both :INITIAL-ELEMENT and :INITIAL-CONTENTS"))
272     (unless (= length (length initial-contents))
273       (error "There are ~W elements in the :INITIAL-CONTENTS, but the ~
274               vector length is ~W."
275              (length initial-contents)
276              length))
277     (unless (every (lambda (x) (typep x element-type)) initial-contents)
278       (error ":INITIAL-CONTENTS contains elements not of type ~S."
279              element-type)))
280   (when initial-element-p
281     (unless (typep initial-element element-type)
282       (error ":INITIAL-ELEMENT ~S is not of type ~S."
283              initial-element element-type)))
284   ;; STEP 2
285   ;;
286   ;; Allocate and possibly initialize the vector.
287   (multiple-value-bind (type n-bits)
288       (sb!impl::%vector-widetag-and-n-bits element-type)
289     (let ((vector
290            (allocate-static-vector type length
291                                    (ceiling (* length n-bits)
292                                             sb!vm:n-word-bits))))
293       (cond (initial-element-p
294              (fill vector initial-element))
295             (initial-contents-p
296              (replace vector initial-contents))
297             (t
298              vector)))))
299
300 ;;; DATA-VECTOR-FROM-INITS returns a simple vector that has the
301 ;;; specified array characteristics. Dimensions is only used to pass
302 ;;; to FILL-DATA-VECTOR for error checking on the structure of
303 ;;; initial-contents.
304 (defun data-vector-from-inits (dimensions total-size element-type
305                                initial-contents initial-contents-p
306                                initial-element initial-element-p)
307   (when (and initial-contents-p initial-element-p)
308     (error "cannot supply both :INITIAL-CONTENTS and :INITIAL-ELEMENT to
309             either MAKE-ARRAY or ADJUST-ARRAY."))
310   (let ((data (if initial-element-p
311                   (make-array total-size
312                               :element-type element-type
313                               :initial-element initial-element)
314                   (make-array total-size
315                               :element-type element-type))))
316     (cond (initial-element-p
317            (unless (simple-vector-p data)
318              (unless (typep initial-element element-type)
319                (error "~S cannot be used to initialize an array of type ~S."
320                       initial-element element-type))
321              (fill (the vector data) initial-element)))
322           (initial-contents-p
323            (fill-data-vector data dimensions initial-contents)))
324     data))
325
326 (defun vector (&rest objects)
327   #!+sb-doc
328   "Construct a SIMPLE-VECTOR from the given objects."
329   (coerce (the list objects) 'simple-vector))
330 \f
331
332 ;;;; accessor/setter functions
333
334 ;;; Dispatch to an optimized routine the data vector accessors for
335 ;;; each different specialized vector type. Do dispatching by looking
336 ;;; up the widetag in the array rather than with the typecases, which
337 ;;; as of 1.0.5 compiles to a naive sequence of linear TYPEPs. Also
338 ;;; provide separate versions where bounds checking has been moved
339 ;;; from the callee to the caller, since it's much cheaper to do once
340 ;;; the type information is available. Finally, for each of these
341 ;;; routines also provide a slow path, taken for arrays that are not
342 ;;; vectors or not simple.
343 (macrolet ((%define (table-name extra-params)
344              `(funcall
345                (the function
346                  (let ((tag 0)
347                        (offset
348                         #.(ecase sb!c:*backend-byte-order*
349                             (:little-endian
350                              (- sb!vm:other-pointer-lowtag))
351                             (:big-endian
352                              (- (1- sb!vm:n-word-bytes) sb!vm:other-pointer-lowtag)))))
353                    ;; WIDETAG-OF needs extra code to handle
354                    ;; LIST and FUNCTION lowtags. We're only
355                    ;; dispatching on other pointers, so let's
356                    ;; do the lowtag extraction manually.
357                    (when (sb!vm::%other-pointer-p array)
358                      (setf tag
359                            (sb!sys:sap-ref-8 (int-sap (get-lisp-obj-address array))
360                                              offset)))
361                    ;; SYMBOL-GLOBAL-VALUE is a performance hack
362                    ;; for threaded builds.
363                    (svref (sb!vm::symbol-global-value ',table-name) tag)))
364                array index ,@extra-params))
365            (define (accessor-name slow-accessor-name table-name extra-params
366                                   check-bounds)
367                `(progn
368                  (defvar ,table-name)
369                  (defun ,accessor-name (array index ,@extra-params)
370                    (declare (optimize speed
371                                       ;; (SAFETY 0) is ok. All calls to
372                                       ;; these functions are generated by
373                                       ;; the compiler, so argument count
374                                       ;; checking isn't needed. Type checking
375                                       ;; is done implicitly via the widetag
376                                       ;; dispatch.
377                                       (safety 0)))
378                    (%define ,table-name ,extra-params))
379                  (defun ,slow-accessor-name (array index ,@extra-params)
380                    (declare (optimize speed (safety 0)))
381                    (if (not (%array-displaced-p array))
382                        ;; The reasonably quick path of non-displaced complex
383                        ;; arrays.
384                        (let ((array (%array-data-vector array)))
385                          (%define ,table-name ,extra-params))
386                        ;; The real slow path.
387                        (with-array-data
388                            ((vector array)
389                             (index (locally
390                                        (declare (optimize (speed 1) (safety 1)))
391                                      (,@check-bounds index)))
392                             (end)
393                             :force-inline t)
394                          (declare (ignore end))
395                          (,accessor-name vector index ,@extra-params)))))))
396   (define hairy-data-vector-ref slow-hairy-data-vector-ref
397     *data-vector-reffers* nil (progn))
398   (define hairy-data-vector-set slow-hairy-data-vector-set
399     *data-vector-setters* (new-value) (progn))
400   (define hairy-data-vector-ref/check-bounds
401       slow-hairy-data-vector-ref/check-bounds
402     *data-vector-reffers/check-bounds* nil
403     (%check-bound array (array-dimension array 0)))
404   (define hairy-data-vector-set/check-bounds
405       slow-hairy-data-vector-set/check-bounds
406     *data-vector-setters/check-bounds* (new-value)
407     (%check-bound array (array-dimension array 0))))
408
409 (defun hairy-ref-error (array index &optional new-value)
410   (declare (ignore index new-value))
411   (error 'type-error
412          :datum array
413          :expected-type 'vector))
414
415 ;;; Populate the dispatch tables.
416 (macrolet ((define-reffer (saetp check-form)
417              (let* ((type (sb!vm:saetp-specifier saetp))
418                     (atype `(simple-array ,type (*))))
419                `(named-lambda optimized-data-vector-ref (vector index)
420                   (declare (optimize speed (safety 0)))
421                   (data-vector-ref (the ,atype vector)
422                                    (locally
423                                        (declare (optimize (safety 1)))
424                                      (the index
425                                        (,@check-form index)))))))
426            (define-setter (saetp check-form)
427              (let* ((type (sb!vm:saetp-specifier saetp))
428                     (atype `(simple-array ,type (*))))
429                `(named-lambda optimized-data-vector-set (vector index new-value)
430                   (declare (optimize speed (safety 0)))
431                   (data-vector-set (the ,atype vector)
432                                    (locally
433                                        (declare (optimize (safety 1)))
434                                      (the index
435                                        (,@check-form index)))
436                                    (locally
437                                        ;; SPEED 1 needed to avoid the compiler
438                                        ;; from downgrading the type check to
439                                        ;; a cheaper one.
440                                        (declare (optimize (speed 1)
441                                                           (safety 1)))
442                                      (the ,type new-value)))
443                   ;; For specialized arrays, the return from
444                   ;; data-vector-set would have to be reboxed to be a
445                   ;; (Lisp) return value; instead, we use the
446                   ;; already-boxed value as the return.
447                   new-value)))
448            (define-reffers (symbol deffer check-form slow-path)
449              `(progn
450                 (setf ,symbol (make-array sb!vm::widetag-mask
451                                           :initial-element #'hairy-ref-error))
452                 ,@(loop for widetag in '(sb!vm:complex-vector-widetag
453                                          sb!vm:complex-vector-nil-widetag
454                                          sb!vm:complex-bit-vector-widetag
455                                          #!+sb-unicode sb!vm:complex-character-string-widetag
456                                          sb!vm:complex-base-string-widetag
457                                          sb!vm:simple-array-widetag
458                                          sb!vm:complex-array-widetag)
459                         collect `(setf (svref ,symbol ,widetag) ,slow-path))
460                 ,@(loop for saetp across sb!vm:*specialized-array-element-type-properties*
461                         for widetag = (sb!vm:saetp-typecode saetp)
462                         collect `(setf (svref ,symbol ,widetag)
463                                        (,deffer ,saetp ,check-form))))))
464   (defun !hairy-data-vector-reffer-init ()
465     (define-reffers *data-vector-reffers* define-reffer
466       (progn)
467       #'slow-hairy-data-vector-ref)
468     (define-reffers *data-vector-setters* define-setter
469       (progn)
470       #'slow-hairy-data-vector-set)
471     (define-reffers *data-vector-reffers/check-bounds* define-reffer
472       (%check-bound vector (length vector))
473       #'slow-hairy-data-vector-ref/check-bounds)
474     (define-reffers *data-vector-setters/check-bounds* define-setter
475       (%check-bound vector (length vector))
476       #'slow-hairy-data-vector-set/check-bounds)))
477
478 ;;; (Ordinary DATA-VECTOR-REF usage compiles into a vop, but
479 ;;; DATA-VECTOR-REF is also FOLDABLE, and this ordinary function
480 ;;; definition is needed for the compiler to use in constant folding.)
481 (defun data-vector-ref (array index)
482   (hairy-data-vector-ref array index))
483
484 ;;; SUBSCRIPTS has a dynamic-extent list structure and is destroyed
485 (defun %array-row-major-index (array subscripts
486                                      &optional (invalid-index-error-p t))
487   (declare (array array)
488            (list subscripts))
489   (let ((rank (array-rank array)))
490     (unless (= rank (length subscripts))
491       (error "wrong number of subscripts, ~W, for array of rank ~W"
492              (length subscripts) rank))
493     (if (array-header-p array)
494         (do ((subs (nreverse subscripts) (cdr subs))
495              (axis (1- (array-rank array)) (1- axis))
496              (chunk-size 1)
497              (result 0))
498             ((null subs) result)
499           (declare (list subs) (fixnum axis chunk-size result))
500           (let ((index (car subs))
501                 (dim (%array-dimension array axis)))
502             (declare (fixnum dim))
503             (unless (and (fixnump index) (< -1 index dim))
504               (if invalid-index-error-p
505                   (error 'simple-type-error
506                          :format-control "invalid index ~W~[~;~:; on axis ~:*~W~] in ~S"
507                          :format-arguments (list index axis array)
508                          :datum index
509                          :expected-type `(integer 0 (,dim)))
510                   (return-from %array-row-major-index nil)))
511             (incf result (* chunk-size (the fixnum index)))
512             (setf chunk-size (* chunk-size dim))))
513         (let ((index (first subscripts))
514               (length (length (the (simple-array * (*)) array))))
515           (unless (and (fixnump index) (< -1 index length))
516             (if invalid-index-error-p
517                 ;; FIXME: perhaps this should share a format-string
518                 ;; with INVALID-ARRAY-INDEX-ERROR or
519                 ;; INDEX-TOO-LARGE-ERROR?
520                 (error 'simple-type-error
521                        :format-control "invalid index ~W in ~S"
522                        :format-arguments (list index array)
523                        :datum index
524                        :expected-type `(integer 0 (,length)))
525                 (return-from %array-row-major-index nil)))
526           index))))
527
528 (defun array-in-bounds-p (array &rest subscripts)
529   #!+sb-doc
530   "Return T if the SUBSCIPTS are in bounds for the ARRAY, NIL otherwise."
531   (if (%array-row-major-index array subscripts nil)
532       t))
533
534 (defun array-row-major-index (array &rest subscripts)
535   (declare (dynamic-extent subscripts))
536   (%array-row-major-index array subscripts))
537
538 (defun aref (array &rest subscripts)
539   #!+sb-doc
540   "Return the element of the ARRAY specified by the SUBSCRIPTS."
541   (declare (dynamic-extent subscripts))
542   (row-major-aref array (%array-row-major-index array subscripts)))
543
544 (defun %aset (array &rest stuff)
545   (declare (dynamic-extent stuff))
546   (let ((subscripts (butlast stuff))
547         (new-value (car (last stuff))))
548     (setf (row-major-aref array (%array-row-major-index array subscripts))
549           new-value)))
550
551 ;;; FIXME: What's supposed to happen with functions
552 ;;; like AREF when we (DEFUN (SETF FOO) ..) when
553 ;;; DEFSETF FOO is also defined? It seems as though the logical
554 ;;; thing to do would be to nuke the macro definition for (SETF FOO)
555 ;;; and replace it with the (SETF FOO) function, issuing a warning,
556 ;;; just as for ordinary functions
557 ;;;  * (LISP-IMPLEMENTATION-VERSION)
558 ;;;  "18a+ release x86-linux 2.4.7 6 November 1998 cvs"
559 ;;;  * (DEFMACRO ZOO (X) `(+ ,X ,X))
560 ;;;  ZOO
561 ;;;  * (DEFUN ZOO (X) (* 3 X))
562 ;;;  Warning: ZOO previously defined as a macro.
563 ;;;  ZOO
564 ;;; But that doesn't seem to be what happens in CMU CL.
565 ;;;
566 ;;; KLUDGE: this is probably because ANSI, in its wisdom (CLHS
567 ;;; 5.1.2.5) requires implementations to support
568 ;;;   (SETF (APPLY #'AREF ...) ...)
569 ;;; [and also #'BIT and #'SBIT].  Yes, this is terrifying, and it's
570 ;;; also terrifying that this sequence of definitions causes it to
571 ;;; work.
572 ;;;
573 ;;; Also, it would be nice to make DESCRIBE FOO tell whether a symbol
574 ;;; has a setf expansion and/or a setf function defined.
575
576 #!-sb-fluid (declaim (inline (setf aref)))
577 (defun (setf aref) (new-value array &rest subscripts)
578   (declare (dynamic-extent subscripts))
579   (declare (type array array))
580   (setf (row-major-aref array (%array-row-major-index array subscripts))
581         new-value))
582
583 (defun row-major-aref (array index)
584   #!+sb-doc
585   "Return the element of array corressponding to the row-major index. This is
586    SETF'able."
587   (declare (optimize (safety 1)))
588   (row-major-aref array index))
589
590 (defun %set-row-major-aref (array index new-value)
591   (declare (optimize (safety 1)))
592   (setf (row-major-aref array index) new-value))
593
594 (defun svref (simple-vector index)
595   #!+sb-doc
596   "Return the INDEX'th element of the given Simple-Vector."
597   (declare (optimize (safety 1)))
598   (aref simple-vector index))
599
600 (defun %svset (simple-vector index new)
601   (declare (optimize (safety 1)))
602   (setf (aref simple-vector index) new))
603
604 (defun bit (bit-array &rest subscripts)
605   #!+sb-doc
606   "Return the bit from the BIT-ARRAY at the specified SUBSCRIPTS."
607   (declare (type (array bit) bit-array) (optimize (safety 1)))
608   (row-major-aref bit-array (%array-row-major-index bit-array subscripts)))
609
610 (defun %bitset (bit-array &rest stuff)
611   (declare (type (array bit) bit-array) (optimize (safety 1)))
612   (let ((subscripts (butlast stuff))
613         (new-value (car (last stuff))))
614     (setf (row-major-aref bit-array
615                           (%array-row-major-index bit-array subscripts))
616           new-value)))
617
618 #!-sb-fluid (declaim (inline (setf bit)))
619 (defun (setf bit) (new-value bit-array &rest subscripts)
620   (declare (type (array bit) bit-array) (optimize (safety 1)))
621   (setf (row-major-aref bit-array
622                         (%array-row-major-index bit-array subscripts))
623         new-value))
624
625 (defun sbit (simple-bit-array &rest subscripts)
626   #!+sb-doc
627   "Return the bit from SIMPLE-BIT-ARRAY at the specified SUBSCRIPTS."
628   (declare (type (simple-array bit) simple-bit-array) (optimize (safety 1)))
629   (row-major-aref simple-bit-array
630                   (%array-row-major-index simple-bit-array subscripts)))
631
632 ;;; KLUDGE: Not all these things (%SET-ROW-MAJOR-AREF, %SET-FILL-POINTER,
633 ;;; %SET-FDEFINITION, %SCHARSET, %SBITSET..) seem to deserve separate names.
634 ;;; Could we just DEFUN (SETF SBIT) etc. and get rid of the non-ANSI names?
635 ;;; -- WHN 19990911
636 (defun %sbitset (simple-bit-array &rest stuff)
637   (declare (type (simple-array bit) simple-bit-array) (optimize (safety 1)))
638   (let ((subscripts (butlast stuff))
639         (new-value (car (last stuff))))
640     (setf (row-major-aref simple-bit-array
641                           (%array-row-major-index simple-bit-array subscripts))
642           new-value)))
643
644 #!-sb-fluid (declaim (inline (setf sbit)))
645 (defun (setf sbit) (new-value bit-array &rest subscripts)
646   (declare (type (simple-array bit) bit-array) (optimize (safety 1)))
647   (setf (row-major-aref bit-array
648                         (%array-row-major-index bit-array subscripts))
649         new-value))
650 \f
651 ;;;; miscellaneous array properties
652
653 (defun array-element-type (array)
654   #!+sb-doc
655   "Return the type of the elements of the array"
656   (let ((widetag (widetag-of array)))
657     (macrolet ((pick-element-type (&rest stuff)
658                  `(cond ,@(mapcar (lambda (stuff)
659                                     (cons
660                                      (let ((item (car stuff)))
661                                        (cond ((eq item t)
662                                               t)
663                                              ((listp item)
664                                               (cons 'or
665                                                     (mapcar (lambda (x)
666                                                               `(= widetag ,x))
667                                                             item)))
668                                              (t
669                                               `(= widetag ,item))))
670                                      (cdr stuff)))
671                                   stuff))))
672       #.`(pick-element-type
673           ,@(map 'list
674                  (lambda (saetp)
675                    `(,(if (sb!vm:saetp-complex-typecode saetp)
676                           (list (sb!vm:saetp-typecode saetp)
677                                 (sb!vm:saetp-complex-typecode saetp))
678                           (sb!vm:saetp-typecode saetp))
679                      ',(sb!vm:saetp-specifier saetp)))
680                  sb!vm:*specialized-array-element-type-properties*)
681           ((sb!vm:simple-array-widetag
682             sb!vm:complex-vector-widetag
683             sb!vm:complex-array-widetag)
684            (with-array-data ((array array) (start) (end))
685              (declare (ignore start end))
686              (array-element-type array)))
687           (t
688            (error 'type-error :datum array :expected-type 'array))))))
689
690 (defun array-rank (array)
691   #!+sb-doc
692   "Return the number of dimensions of ARRAY."
693   (if (array-header-p array)
694       (%array-rank array)
695       1))
696
697 (defun array-dimension (array axis-number)
698   #!+sb-doc
699   "Return the length of dimension AXIS-NUMBER of ARRAY."
700   (declare (array array) (type index axis-number))
701   (cond ((not (array-header-p array))
702          (unless (= axis-number 0)
703            (error "Vector axis is not zero: ~S" axis-number))
704          (length (the (simple-array * (*)) array)))
705         ((>= axis-number (%array-rank array))
706          (error "Axis number ~W is too big; ~S only has ~D dimension~:P."
707                 axis-number array (%array-rank array)))
708         (t
709          ;; ANSI sayeth (ADJUST-ARRAY dictionary entry):
710          ;;
711          ;;   "If A is displaced to B, the consequences are
712          ;;   unspecified if B is adjusted in such a way that it no
713          ;;   longer has enough elements to satisfy A.
714          ;;
715          ;; In situations where this matters we should be doing a
716          ;; bounds-check, which in turn uses ARRAY-DIMENSION -- so
717          ;; this seems like a good place to signal an error.
718          (multiple-value-bind (target offset) (array-displacement array)
719            (when (and target
720                       (> (array-total-size array)
721                          (- (array-total-size target) offset)))
722                (error 'displaced-to-array-too-small-error
723                       :format-control "~@<The displaced-to array is too small. ~S ~
724                                       elements after offset required, ~S available.~:@>"
725                       :format-arguments (list (array-total-size array)
726                                               (- (array-total-size target) offset))))
727            (%array-dimension array axis-number)))))
728
729 (defun array-dimensions (array)
730   #!+sb-doc
731   "Return a list whose elements are the dimensions of the array"
732   (declare (array array))
733   (if (array-header-p array)
734       (do ((results nil (cons (array-dimension array index) results))
735            (index (1- (array-rank array)) (1- index)))
736           ((minusp index) results))
737       (list (array-dimension array 0))))
738
739 (defun array-total-size (array)
740   #!+sb-doc
741   "Return the total number of elements in the Array."
742   (declare (array array))
743   (if (array-header-p array)
744       (%array-available-elements array)
745       (length (the vector array))))
746
747 (defun array-displacement (array)
748   #!+sb-doc
749   "Return the values of :DISPLACED-TO and :DISPLACED-INDEX-offset
750    options to MAKE-ARRAY, or NIL and 0 if not a displaced array."
751   (declare (type array array))
752   (if (and (array-header-p array) ; if unsimple and
753            (%array-displaced-p array)) ; displaced
754       (values (%array-data-vector array) (%array-displacement array))
755       (values nil 0)))
756
757 (defun adjustable-array-p (array)
758   #!+sb-doc
759   "Return T if (ADJUST-ARRAY ARRAY...) would return an array identical
760    to the argument, this happens for complex arrays."
761   (declare (array array))
762   ;; Note that this appears not to be a fundamental limitation.
763   ;; non-vector SIMPLE-ARRAYs are in fact capable of being adjusted,
764   ;; but in practice we test using ADJUSTABLE-ARRAY-P in ADJUST-ARRAY.
765   ;; -- CSR, 2004-03-01.
766   (not (typep array 'simple-array)))
767 \f
768 ;;;; fill pointer frobbing stuff
769
770 (defun array-has-fill-pointer-p (array)
771   #!+sb-doc
772   "Return T if the given ARRAY has a fill pointer, or NIL otherwise."
773   (declare (array array))
774   (and (array-header-p array) (%array-fill-pointer-p array)))
775
776 (defun fill-pointer (vector)
777   #!+sb-doc
778   "Return the FILL-POINTER of the given VECTOR."
779   (declare (vector vector))
780   (if (and (array-header-p vector) (%array-fill-pointer-p vector))
781       (%array-fill-pointer vector)
782       (error 'simple-type-error
783              :datum vector
784              :expected-type '(and vector (satisfies array-has-fill-pointer-p))
785              :format-control "~S is not an array with a fill pointer."
786              :format-arguments (list vector))))
787
788 (defun %set-fill-pointer (vector new)
789   (declare (vector vector) (fixnum new))
790   (if (and (array-header-p vector) (%array-fill-pointer-p vector))
791       (if (> new (%array-available-elements vector))
792         (error
793          "The new fill pointer, ~S, is larger than the length of the vector."
794          new)
795         (setf (%array-fill-pointer vector) new))
796       (error 'simple-type-error
797              :datum vector
798              :expected-type '(and vector (satisfies array-has-fill-pointer-p))
799              :format-control "~S is not an array with a fill pointer."
800              :format-arguments (list vector))))
801
802 ;;; FIXME: It'd probably make sense to use a MACROLET to share the
803 ;;; guts of VECTOR-PUSH between VECTOR-PUSH-EXTEND. Such a macro
804 ;;; should probably be based on the VECTOR-PUSH-EXTEND code (which is
805 ;;; new ca. sbcl-0.7.0) rather than the VECTOR-PUSH code (which dates
806 ;;; back to CMU CL).
807 (defun vector-push (new-el array)
808   #!+sb-doc
809   "Attempt to set the element of ARRAY designated by its fill pointer
810    to NEW-EL, and increment the fill pointer by one. If the fill pointer is
811    too large, NIL is returned, otherwise the index of the pushed element is
812    returned."
813   (declare (vector array))
814   (let ((fill-pointer (fill-pointer array)))
815     (declare (fixnum fill-pointer))
816     (cond ((= fill-pointer (%array-available-elements array))
817            nil)
818           (t
819            (setf (aref array fill-pointer) new-el)
820            (setf (%array-fill-pointer array) (1+ fill-pointer))
821            fill-pointer))))
822
823 (defun vector-push-extend (new-element
824                            vector
825                            &optional
826                            (extension (1+ (length vector))))
827   (declare (vector vector) (fixnum extension))
828   (let ((fill-pointer (fill-pointer vector)))
829     (declare (fixnum fill-pointer))
830     (when (= fill-pointer (%array-available-elements vector))
831       (adjust-array vector (+ fill-pointer extension)))
832     ;; disable bounds checking
833     (locally (declare (optimize (safety 0)))
834       (setf (aref vector fill-pointer) new-element))
835     (setf (%array-fill-pointer vector) (1+ fill-pointer))
836     fill-pointer))
837
838 (defun vector-pop (array)
839   #!+sb-doc
840   "Decrease the fill pointer by 1 and return the element pointed to by the
841   new fill pointer."
842   (declare (vector array))
843   (let ((fill-pointer (fill-pointer array)))
844     (declare (fixnum fill-pointer))
845     (if (zerop fill-pointer)
846         (error "There is nothing left to pop.")
847         ;; disable bounds checking (and any fixnum test)
848         (locally (declare (optimize (safety 0)))
849           (aref array
850                 (setf (%array-fill-pointer array)
851                       (1- fill-pointer)))))))
852
853 \f
854 ;;;; ADJUST-ARRAY
855
856 (defun adjust-array (array dimensions &key
857                            (element-type (array-element-type array))
858                            (initial-element nil initial-element-p)
859                            (initial-contents nil initial-contents-p)
860                            fill-pointer
861                            displaced-to displaced-index-offset)
862   #!+sb-doc
863   "Adjust ARRAY's dimensions to the given DIMENSIONS and stuff."
864   (let ((dimensions (if (listp dimensions) dimensions (list dimensions))))
865     (cond ((/= (the fixnum (length (the list dimensions)))
866                (the fixnum (array-rank array)))
867            (error "The number of dimensions not equal to rank of array."))
868           ((not (subtypep element-type (array-element-type array)))
869            (error "The new element type, ~S, is incompatible with old type."
870                   element-type))
871           ((and fill-pointer (not (array-has-fill-pointer-p array)))
872            (error 'type-error
873                   :datum array
874                   :expected-type '(satisfies array-has-fill-pointer-p))))
875     (let ((array-rank (length (the list dimensions))))
876       (declare (fixnum array-rank))
877       (unless (= array-rank 1)
878         (when fill-pointer
879           (error "Only vectors can have fill pointers.")))
880       (cond (initial-contents-p
881              ;; array former contents replaced by INITIAL-CONTENTS
882              (if (or initial-element-p displaced-to)
883                  (error "INITIAL-CONTENTS may not be specified with ~
884                          the :INITIAL-ELEMENT or :DISPLACED-TO option."))
885              (let* ((array-size (apply #'* dimensions))
886                     (array-data (data-vector-from-inits
887                                  dimensions array-size element-type
888                                  initial-contents initial-contents-p
889                                  initial-element initial-element-p)))
890                (if (adjustable-array-p array)
891                    (set-array-header array array-data array-size
892                                  (get-new-fill-pointer array array-size
893                                                        fill-pointer)
894                                  0 dimensions nil)
895                    (if (array-header-p array)
896                        ;; simple multidimensional or single dimensional array
897                        (make-array dimensions
898                                    :element-type element-type
899                                    :initial-contents initial-contents)
900                        array-data))))
901             (displaced-to
902              ;; We already established that no INITIAL-CONTENTS was supplied.
903              (when initial-element
904                (error "The :INITIAL-ELEMENT option may not be specified ~
905                        with :DISPLACED-TO."))
906              (unless (subtypep element-type (array-element-type displaced-to))
907                (error "can't displace an array of type ~S into another of ~
908                        type ~S"
909                       element-type (array-element-type displaced-to)))
910              (let ((displacement (or displaced-index-offset 0))
911                    (array-size (apply #'* dimensions)))
912                (declare (fixnum displacement array-size))
913                (if (< (the fixnum (array-total-size displaced-to))
914                       (the fixnum (+ displacement array-size)))
915                    (error "The :DISPLACED-TO array is too small."))
916                (if (adjustable-array-p array)
917                    ;; None of the original contents appear in adjusted array.
918                    (set-array-header array displaced-to array-size
919                                      (get-new-fill-pointer array array-size
920                                                            fill-pointer)
921                                      displacement dimensions t)
922                    ;; simple multidimensional or single dimensional array
923                    (make-array dimensions
924                                :element-type element-type
925                                :displaced-to displaced-to
926                                :displaced-index-offset
927                                displaced-index-offset))))
928             ((= array-rank 1)
929              (let ((old-length (array-total-size array))
930                    (new-length (car dimensions))
931                    new-data)
932                (declare (fixnum old-length new-length))
933                (with-array-data ((old-data array) (old-start)
934                                  (old-end old-length))
935                  (cond ((or (and (array-header-p array)
936                                  (%array-displaced-p array))
937                             (< old-length new-length))
938                         (setf new-data
939                               (data-vector-from-inits
940                                dimensions new-length element-type
941                                initial-contents initial-contents-p
942                                initial-element initial-element-p))
943                         (replace new-data old-data
944                                  :start2 old-start :end2 old-end))
945                        (t (setf new-data
946                                 (shrink-vector old-data new-length))))
947                  (if (adjustable-array-p array)
948                      (set-array-header array new-data new-length
949                                        (get-new-fill-pointer array new-length
950                                                              fill-pointer)
951                                        0 dimensions nil)
952                      new-data))))
953             (t
954              (let ((old-length (%array-available-elements array))
955                    (new-length (apply #'* dimensions)))
956                (declare (fixnum old-length new-length))
957                (with-array-data ((old-data array) (old-start)
958                                  (old-end old-length))
959                  (declare (ignore old-end))
960                  (let ((new-data (if (or (and (array-header-p array)
961                                               (%array-displaced-p array))
962                                          (> new-length old-length))
963                                      (data-vector-from-inits
964                                       dimensions new-length
965                                       element-type () nil
966                                       initial-element initial-element-p)
967                                      old-data)))
968                    (if (or (zerop old-length) (zerop new-length))
969                        (when initial-element-p (fill new-data initial-element))
970                        (zap-array-data old-data (array-dimensions array)
971                                        old-start
972                                        new-data dimensions new-length
973                                        element-type initial-element
974                                        initial-element-p))
975                    (if (adjustable-array-p array)
976                        (set-array-header array new-data new-length
977                                          new-length 0 dimensions nil)
978                        (let ((new-array
979                               (make-array-header
980                                sb!vm:simple-array-widetag array-rank)))
981                          (set-array-header new-array new-data new-length
982                                            new-length 0 dimensions nil)))))))))))
983
984
985 (defun get-new-fill-pointer (old-array new-array-size fill-pointer)
986   (cond ((not fill-pointer)
987          (when (array-has-fill-pointer-p old-array)
988            (when (> (%array-fill-pointer old-array) new-array-size)
989              (error "cannot ADJUST-ARRAY an array (~S) to a size (~S) that is ~
990                      smaller than its fill pointer (~S)"
991                     old-array new-array-size (fill-pointer old-array)))
992            (%array-fill-pointer old-array)))
993         ((not (array-has-fill-pointer-p old-array))
994          (error "cannot supply a non-NIL value (~S) for :FILL-POINTER ~
995                  in ADJUST-ARRAY unless the array (~S) was originally ~
996                  created with a fill pointer"
997                 fill-pointer
998                 old-array))
999         ((numberp fill-pointer)
1000          (when (> fill-pointer new-array-size)
1001            (error "can't supply a value for :FILL-POINTER (~S) that is larger ~
1002                    than the new length of the vector (~S)"
1003                   fill-pointer new-array-size))
1004          fill-pointer)
1005         ((eq fill-pointer t)
1006          new-array-size)
1007         (t
1008          (error "bogus value for :FILL-POINTER in ADJUST-ARRAY: ~S"
1009                 fill-pointer))))
1010
1011 ;;; Destructively alter VECTOR, changing its length to NEW-LENGTH,
1012 ;;; which must be less than or equal to its current length. This can
1013 ;;; be called on vectors without a fill pointer but it is extremely
1014 ;;; dangerous to do so: shrinking the size of an object (as viewed by
1015 ;;; the gc) makes bounds checking unreliable in the face of interrupts
1016 ;;; or multi-threading. Call it only on provably local vectors.
1017 (defun %shrink-vector (vector new-length)
1018   (declare (vector vector))
1019   (unless (array-header-p vector)
1020     (macrolet ((frob (name &rest things)
1021                  `(etypecase ,name
1022                     ((simple-array nil (*)) (error 'nil-array-accessed-error))
1023                     ,@(mapcar (lambda (thing)
1024                                 (destructuring-bind (type-spec fill-value)
1025                                     thing
1026                                   `(,type-spec
1027                                     (fill (truly-the ,type-spec ,name)
1028                                           ,fill-value
1029                                           :start new-length))))
1030                               things))))
1031       ;; Set the 'tail' of the vector to the appropriate type of zero,
1032       ;; "because in some cases we'll scavenge larger areas in one go,
1033       ;; like groups of pages that had triggered the write barrier, or
1034       ;; the whole static space" according to jsnell.
1035       #.`(frob vector
1036           ,@(map 'list
1037                  (lambda (saetp)
1038                    `((simple-array ,(sb!vm:saetp-specifier saetp) (*))
1039                      ,(if (or (eq (sb!vm:saetp-specifier saetp) 'character)
1040                               #!+sb-unicode
1041                               (eq (sb!vm:saetp-specifier saetp) 'base-char))
1042                           *default-init-char-form*
1043                           (sb!vm:saetp-initial-element-default saetp))))
1044                  (remove-if-not
1045                   #'sb!vm:saetp-specifier
1046                   sb!vm:*specialized-array-element-type-properties*)))))
1047   ;; Only arrays have fill-pointers, but vectors have their length
1048   ;; parameter in the same place.
1049   (setf (%array-fill-pointer vector) new-length)
1050   vector)
1051
1052 (defun shrink-vector (vector new-length)
1053   (declare (vector vector))
1054   (cond
1055     ((eq (length vector) new-length)
1056      vector)
1057     ((array-has-fill-pointer-p vector)
1058      (setf (%array-fill-pointer vector) new-length)
1059      vector)
1060     (t (subseq vector 0 new-length))))
1061
1062 ;;; Fill in array header with the provided information, and return the array.
1063 (defun set-array-header (array data length fill-pointer displacement dimensions
1064                          &optional displacedp)
1065   (setf (%array-data-vector array) data)
1066   (setf (%array-available-elements array) length)
1067   (cond (fill-pointer
1068          (setf (%array-fill-pointer array) fill-pointer)
1069          (setf (%array-fill-pointer-p array) t))
1070         (t
1071          (setf (%array-fill-pointer array) length)
1072          (setf (%array-fill-pointer-p array) nil)))
1073   (setf (%array-displacement array) displacement)
1074   (if (listp dimensions)
1075       (dotimes (axis (array-rank array))
1076         (declare (type index axis))
1077         (setf (%array-dimension array axis) (pop dimensions)))
1078       (setf (%array-dimension array 0) dimensions))
1079   (setf (%array-displaced-p array) displacedp)
1080   array)
1081 \f
1082 ;;;; ZAP-ARRAY-DATA for ADJUST-ARRAY
1083
1084 ;;; a temporary to be used when OLD-DATA and NEW-DATA are EQ.
1085 ;;; KLUDGE: Boy, DYNAMIC-EXTENT would be nice. This is rebound
1086 ;;; to length zero array in each new thread.
1087 ;;;
1088 ;;; DX is probably a bad idea, because a with a big array it would
1089 ;;; be fairly easy to blow the stack.
1090 (defvar *zap-array-data-temp* (vector))
1091 (declaim (simple-vector *zap-array-data-temp*))
1092
1093 (defun zap-array-data-temp (length initial-element initial-element-p)
1094   (declare (fixnum length))
1095   (let ((tmp *zap-array-data-temp*))
1096     (declare (simple-vector tmp))
1097     (cond ((> length (length tmp))
1098            (setf *zap-array-data-temp*
1099                  (if initial-element-p
1100                      (make-array length :initial-element initial-element)
1101                      (make-array length))))
1102           (initial-element-p
1103            (fill tmp initial-element :end length))
1104           (t
1105            tmp))))
1106
1107 ;;; This does the grinding work for ADJUST-ARRAY. It zaps the data
1108 ;;; from the OLD-DATA in an arrangement specified by the OLD-DIMS to
1109 ;;; the NEW-DATA in an arrangement specified by the NEW-DIMS. OFFSET
1110 ;;; is a displaced offset to be added to computed indices of OLD-DATA.
1111 (defun zap-array-data (old-data old-dims offset new-data new-dims new-length
1112                        element-type initial-element initial-element-p)
1113   (declare (list old-dims new-dims))
1114   ;; OLD-DIMS comes from array-dimensions, which returns a fresh list
1115   ;; at least in SBCL.
1116   ;; NEW-DIMS comes from the user.
1117   (setf old-dims (nreverse old-dims)
1118         new-dims (reverse new-dims))
1119   (cond ((eq old-data new-data)
1120          ;; NEW-LENGTH, ELEMENT-TYPE, INITIAL-ELEMENT, and
1121          ;; INITIAL-ELEMENT-P are used when OLD-DATA and NEW-DATA are
1122          ;; EQ; in this case, a temporary must be used and filled
1123          ;; appropriately. specified initial-element.
1124          (when initial-element-p
1125            ;; FIXME: transforming this TYPEP to someting a bit faster
1126            ;; would be a win...
1127            (unless (typep initial-element element-type)
1128              (error "~S can't be used to initialize an array of type ~S."
1129                     initial-element element-type)))
1130          (without-interrupts
1131            ;; Need to disable interrupts while using the temp-vector.
1132            ;; An interrupt handler that also happened to call
1133            ;; ADJUST-ARRAY could otherwise stomp on our data here.
1134            (let ((temp (zap-array-data-temp new-length
1135                                             initial-element initial-element-p)))
1136              (declare (simple-vector temp))
1137              (zap-array-data-aux old-data old-dims offset temp new-dims)
1138              (dotimes (i new-length)
1139                (setf (aref new-data i) (aref temp i)
1140                      ;; zero out any garbage right away
1141                      (aref temp i) 0)))))
1142         (t
1143          ;; When OLD-DATA and NEW-DATA are not EQ, NEW-DATA has
1144          ;; already been filled with any
1145          (zap-array-data-aux old-data old-dims offset new-data new-dims))))
1146
1147 (defun zap-array-data-aux (old-data old-dims offset new-data new-dims)
1148   (declare (fixnum offset))
1149   (let ((limits (mapcar (lambda (x y)
1150                           (declare (fixnum x y))
1151                           (1- (the fixnum (min x y))))
1152                         old-dims new-dims)))
1153     (macrolet ((bump-index-list (index limits)
1154                  `(do ((subscripts ,index (cdr subscripts))
1155                        (limits ,limits (cdr limits)))
1156                       ((null subscripts) :eof)
1157                     (cond ((< (the fixnum (car subscripts))
1158                               (the fixnum (car limits)))
1159                            (rplaca subscripts
1160                                    (1+ (the fixnum (car subscripts))))
1161                            (return ,index))
1162                           (t (rplaca subscripts 0))))))
1163       (do ((index (make-list (length old-dims) :initial-element 0)
1164                   (bump-index-list index limits)))
1165           ((eq index :eof))
1166         (setf (aref new-data (row-major-index-from-dims index new-dims))
1167               (aref old-data
1168                     (+ (the fixnum (row-major-index-from-dims index old-dims))
1169                        offset)))))))
1170
1171 ;;; Figure out the row-major-order index of an array reference from a
1172 ;;; list of subscripts and a list of dimensions. This is for internal
1173 ;;; calls only, and the subscripts and dim-list variables are assumed
1174 ;;; to be reversed from what the user supplied.
1175 (defun row-major-index-from-dims (rev-subscripts rev-dim-list)
1176   (do ((rev-subscripts rev-subscripts (cdr rev-subscripts))
1177        (rev-dim-list rev-dim-list (cdr rev-dim-list))
1178        (chunk-size 1)
1179        (result 0))
1180       ((null rev-dim-list) result)
1181     (declare (fixnum chunk-size result))
1182     (setq result (+ result
1183                     (the fixnum (* (the fixnum (car rev-subscripts))
1184                                    chunk-size))))
1185     (setq chunk-size (* chunk-size (the fixnum (car rev-dim-list))))))
1186 \f
1187 ;;;; some bit stuff
1188
1189 (defun bit-array-same-dimensions-p (array1 array2)
1190   (declare (type (array bit) array1 array2))
1191   (and (= (array-rank array1)
1192           (array-rank array2))
1193        (dotimes (index (array-rank array1) t)
1194          (when (/= (array-dimension array1 index)
1195                    (array-dimension array2 index))
1196            (return nil)))))
1197
1198 (defun pick-result-array (result-bit-array bit-array-1)
1199   (case result-bit-array
1200     ((t) bit-array-1)
1201     ((nil) (make-array (array-dimensions bit-array-1)
1202                        :element-type 'bit
1203                        :initial-element 0))
1204     (t
1205      (unless (bit-array-same-dimensions-p bit-array-1
1206                                           result-bit-array)
1207        (error "~S and ~S don't have the same dimensions."
1208               bit-array-1 result-bit-array))
1209      result-bit-array)))
1210
1211 (defmacro def-bit-array-op (name function)
1212   `(defun ,name (bit-array-1 bit-array-2 &optional result-bit-array)
1213      #!+sb-doc
1214      ,(format nil
1215               "Perform a bit-wise ~A on the elements of BIT-ARRAY-1 and ~
1216                BIT-ARRAY-2,~%  putting the results in RESULT-BIT-ARRAY. ~
1217                If RESULT-BIT-ARRAY is T,~%  BIT-ARRAY-1 is used. If ~
1218                RESULT-BIT-ARRAY is NIL or omitted, a new array is~%  created. ~
1219                All the arrays must have the same rank and dimensions."
1220               (symbol-name function))
1221      (declare (type (array bit) bit-array-1 bit-array-2)
1222               (type (or (array bit) (member t nil)) result-bit-array))
1223      (unless (bit-array-same-dimensions-p bit-array-1 bit-array-2)
1224        (error "~S and ~S don't have the same dimensions."
1225               bit-array-1 bit-array-2))
1226      (let ((result-bit-array (pick-result-array result-bit-array bit-array-1)))
1227        (if (and (simple-bit-vector-p bit-array-1)
1228                 (simple-bit-vector-p bit-array-2)
1229                 (simple-bit-vector-p result-bit-array))
1230            (locally (declare (optimize (speed 3) (safety 0)))
1231              (,name bit-array-1 bit-array-2 result-bit-array))
1232            (with-array-data ((data1 bit-array-1) (start1) (end1))
1233              (declare (ignore end1))
1234              (with-array-data ((data2 bit-array-2) (start2) (end2))
1235                (declare (ignore end2))
1236                (with-array-data ((data3 result-bit-array) (start3) (end3))
1237                  (do ((index-1 start1 (1+ index-1))
1238                       (index-2 start2 (1+ index-2))
1239                       (index-3 start3 (1+ index-3)))
1240                      ((>= index-3 end3) result-bit-array)
1241                    (declare (type index index-1 index-2 index-3))
1242                    (setf (sbit data3 index-3)
1243                          (logand (,function (sbit data1 index-1)
1244                                             (sbit data2 index-2))
1245                                  1))))))))))
1246
1247 (def-bit-array-op bit-and logand)
1248 (def-bit-array-op bit-ior logior)
1249 (def-bit-array-op bit-xor logxor)
1250 (def-bit-array-op bit-eqv logeqv)
1251 (def-bit-array-op bit-nand lognand)
1252 (def-bit-array-op bit-nor lognor)
1253 (def-bit-array-op bit-andc1 logandc1)
1254 (def-bit-array-op bit-andc2 logandc2)
1255 (def-bit-array-op bit-orc1 logorc1)
1256 (def-bit-array-op bit-orc2 logorc2)
1257
1258 (defun bit-not (bit-array &optional result-bit-array)
1259   #!+sb-doc
1260   "Performs a bit-wise logical NOT on the elements of BIT-ARRAY,
1261   putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
1262   BIT-ARRAY is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
1263   created. Both arrays must have the same rank and dimensions."
1264   (declare (type (array bit) bit-array)
1265            (type (or (array bit) (member t nil)) result-bit-array))
1266   (let ((result-bit-array (pick-result-array result-bit-array bit-array)))
1267     (if (and (simple-bit-vector-p bit-array)
1268              (simple-bit-vector-p result-bit-array))
1269         (locally (declare (optimize (speed 3) (safety 0)))
1270           (bit-not bit-array result-bit-array))
1271         (with-array-data ((src bit-array) (src-start) (src-end))
1272           (declare (ignore src-end))
1273           (with-array-data ((dst result-bit-array) (dst-start) (dst-end))
1274             (do ((src-index src-start (1+ src-index))
1275                  (dst-index dst-start (1+ dst-index)))
1276                 ((>= dst-index dst-end) result-bit-array)
1277               (declare (type index src-index dst-index))
1278               (setf (sbit dst dst-index)
1279                     (logxor (sbit src src-index) 1))))))))