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