0.pre7.38:
[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-frob (name)
23              `(progn
24                 (defun ,name (array)
25                   (,name array))
26                 (defun (setf ,name) (value array)
27                   (setf (,name array) value)))))
28   (def-frob %array-fill-pointer)
29   (def-frob %array-fill-pointer-p)
30   (def-frob %array-available-elements)
31   (def-frob %array-data-vector)
32   (def-frob %array-displacement)
33   (def-frob %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 ;;; It'd waste space to expand copies of error handling in every
53 ;;; inline %WITH-ARRAY-DATA, so we have them call this function
54 ;;; instead. This is just a wrapper which is known never to return.
55 (defun failed-%with-array-data (array start end)
56   (declare (notinline %with-array-data))
57   (%with-array-data array start end)
58   (error "internal error: shouldn't be here with valid parameters"))
59 \f
60 ;;;; MAKE-ARRAY
61
62 (eval-when (:compile-toplevel :execute)
63   (sb!xc:defmacro pick-type (type &rest specs)
64     `(cond ,@(mapcar #'(lambda (spec)
65                          `(,(if (eq (car spec) t)
66                               t
67                               `(subtypep ,type ',(car spec)))
68                            ,@(cdr spec)))
69                      specs))))
70
71 ;;; These functions are used in the implementation of MAKE-ARRAY for
72 ;;; complex arrays. There are lots of transforms to simplify
73 ;;; MAKE-ARRAY for various easy cases, but not for all reasonable
74 ;;; cases, so e.g. as of sbcl-0.6.6 we still make full calls to
75 ;;; MAKE-ARRAY for any non-simple array. Thus, there's some value to
76 ;;; making this somewhat efficient, at least not doing full calls to
77 ;;; SUBTYPEP in the easy cases.
78 (defun %vector-type-code (type)
79   (case type
80     ;; Pick off some easy common cases.
81     ;;
82     ;; (Perhaps we should make a much more exhaustive table of easy
83     ;; common cases here. Or perhaps the effort would be better spent
84     ;; on smarter compiler transforms which do the calculation once
85     ;; and for all in any reasonable user programs.)
86     ((t)
87      (values #.sb!vm:simple-vector-type #.sb!vm:word-bits))
88     ((character base-char)
89      (values #.sb!vm:simple-string-type #.sb!vm:byte-bits))
90     ((bit)
91      (values #.sb!vm:simple-bit-vector-type 1))
92     ;; OK, we have to wade into SUBTYPEPing after all.
93     (t
94      (pick-type type
95        (base-char (values #.sb!vm:simple-string-type #.sb!vm:byte-bits))
96        (bit (values #.sb!vm:simple-bit-vector-type 1))
97        ((unsigned-byte 2)
98         (values #.sb!vm:simple-array-unsigned-byte-2-type 2))
99        ((unsigned-byte 4)
100         (values #.sb!vm:simple-array-unsigned-byte-4-type 4))
101        ((unsigned-byte 8)
102         (values #.sb!vm:simple-array-unsigned-byte-8-type 8))
103        ((unsigned-byte 16)
104         (values #.sb!vm:simple-array-unsigned-byte-16-type 16))
105        ((unsigned-byte 32)
106         (values #.sb!vm:simple-array-unsigned-byte-32-type 32))
107        ((signed-byte 8)
108         (values #.sb!vm:simple-array-signed-byte-8-type 8))
109        ((signed-byte 16)
110         (values #.sb!vm:simple-array-signed-byte-16-type 16))
111        ((signed-byte 30)
112         (values #.sb!vm:simple-array-signed-byte-30-type 32))
113        ((signed-byte 32)
114         (values #.sb!vm:simple-array-signed-byte-32-type 32))
115        (single-float (values #.sb!vm:simple-array-single-float-type 32))
116        (double-float (values #.sb!vm:simple-array-double-float-type 64))
117        #!+long-float
118        (long-float
119         (values #.sb!vm:simple-array-long-float-type #!+x86 96 #!+sparc 128))
120        ((complex single-float)
121         (values #.sb!vm:simple-array-complex-single-float-type 64))
122        ((complex double-float)
123         (values #.sb!vm:simple-array-complex-double-float-type 128))
124        #!+long-float
125        ((complex long-float)
126         (values #.sb!vm:simple-array-complex-long-float-type
127                 #!+x86 192
128                 #!+sparc 256))
129        (t (values #.sb!vm:simple-vector-type #.sb!vm:word-bits))))))
130 (defun %complex-vector-type-code (type)
131   (case type
132     ;; Pick off some easy common cases.
133     ((t)
134      #.sb!vm:complex-vector-type)
135     ((character base-char)
136      #.sb!vm:complex-string-type) 
137     ((bit)
138      #.sb!vm:complex-bit-vector-type)
139     ;; OK, we have to wade into SUBTYPEPing after all.
140     (t
141      (pick-type type
142        (base-char #.sb!vm:complex-string-type)
143        (bit #.sb!vm:complex-bit-vector-type)
144        (t #.sb!vm:complex-vector-type)))))
145
146 (defun make-array (dimensions &key
147                               (element-type t)
148                               (initial-element nil initial-element-p)
149                               initial-contents adjustable fill-pointer
150                               displaced-to displaced-index-offset)
151   (let* ((dimensions (if (listp dimensions) dimensions (list dimensions)))
152          (array-rank (length (the list dimensions)))
153          (simple (and (null fill-pointer)
154                       (not adjustable)
155                       (null displaced-to))))
156     (declare (fixnum array-rank))
157     (when (and displaced-index-offset (null displaced-to))
158       (error "can't specify :DISPLACED-INDEX-OFFSET without :DISPLACED-TO"))
159     (if (and simple (= array-rank 1))
160         ;; Its a (simple-array * (*))
161         (multiple-value-bind (type bits) (%vector-type-code element-type)
162           (declare (type (unsigned-byte 8) type)
163                    (type (integer 1 256) bits))
164           (let* ((length (car dimensions))
165                  (array (allocate-vector
166                          type
167                          length
168                          (ceiling (* (if (= type sb!vm:simple-string-type)
169                                          (1+ length)
170                                          length)
171                                      bits)
172                                   sb!vm:word-bits))))
173             (declare (type index length))
174             (when initial-element-p
175               (fill array initial-element))
176             (when initial-contents
177               (when initial-element
178                 (error "can't specify both :INITIAL-ELEMENT and ~
179                 :INITIAL-CONTENTS"))
180               (unless (= length (length initial-contents))
181                 (error "There are ~D elements in the :INITIAL-CONTENTS, but ~
182                        the vector length is ~D."
183                        (length initial-contents)
184                        length))
185               (replace array initial-contents))
186             array))
187         ;; It's either a complex array or a multidimensional array.
188         (let* ((total-size (reduce #'* dimensions))
189                (data (or displaced-to
190                          (data-vector-from-inits
191                           dimensions total-size element-type
192                           initial-contents initial-element initial-element-p)))
193                (array (make-array-header
194                        (cond ((= array-rank 1)
195                               (%complex-vector-type-code element-type))
196                              (simple sb!vm:simple-array-type)
197                              (t sb!vm:complex-array-type))
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                                     (error "invalid fill-pointer ~D"
212                                            fill-pointer))
213                             fill-pointer))))
214                  (setf (%array-fill-pointer-p array) t))
215                 (t
216                  (setf (%array-fill-pointer array) total-size)
217                  (setf (%array-fill-pointer-p array) nil)))
218           (setf (%array-available-elements array) total-size)
219           (setf (%array-data-vector array) data)
220           (cond (displaced-to
221                  (when (or initial-element-p initial-contents)
222                    (error "Neither :INITIAL-ELEMENT nor :INITIAL-CONTENTS ~
223                    can be specified along with :DISPLACED-TO"))
224                  (let ((offset (or displaced-index-offset 0)))
225                    (when (> (+ offset total-size)
226                             (array-total-size displaced-to))
227                      (error "~S doesn't have enough elements." displaced-to))
228                    (setf (%array-displacement array) offset)
229                    (setf (%array-displaced-p array) t)))
230                 (t
231                  (setf (%array-displaced-p array) nil)))
232           (let ((axis 0))
233             (dolist (dim dimensions)
234               (setf (%array-dimension array axis) dim)
235               (incf axis)))
236           array))))
237         
238 ;;; DATA-VECTOR-FROM-INITS returns a simple vector that has the
239 ;;; specified array characteristics. Dimensions is only used to pass
240 ;;; to FILL-DATA-VECTOR for error checking on the structure of
241 ;;; initial-contents.
242 (defun data-vector-from-inits (dimensions total-size element-type
243                                initial-contents initial-element
244                                initial-element-p)
245   (when (and initial-contents initial-element-p)
246     (error "cannot supply both :INITIAL-CONTENTS and :INITIAL-ELEMENT to
247             either MAKE-ARRAY or ADJUST-ARRAY."))
248   (let ((data (if initial-element-p
249                   (make-array total-size
250                               :element-type element-type
251                               :initial-element initial-element)
252                   (make-array total-size
253                               :element-type element-type))))
254     (cond (initial-element-p
255            (unless (simple-vector-p data)
256              (unless (typep initial-element element-type)
257                (error "~S cannot be used to initialize an array of type ~S."
258                       initial-element element-type))
259              (fill (the vector data) initial-element)))
260           (initial-contents
261            (fill-data-vector data dimensions initial-contents)))
262     data))
263
264 (defun fill-data-vector (vector dimensions initial-contents)
265   (let ((index 0))
266     (labels ((frob (axis dims contents)
267                (cond ((null dims)
268                       (setf (aref vector index) contents)
269                       (incf index))
270                      (t
271                       (unless (typep contents 'sequence)
272                         (error "malformed :INITIAL-CONTENTS: ~S is not a ~
273                                 sequence, but ~D more layer~:P needed."
274                                contents
275                                (- (length dimensions) axis)))
276                       (unless (= (length contents) (car dims))
277                         (error "malformed :INITIAL-CONTENTS: Dimension of ~
278                                 axis ~D is ~D, but ~S is ~D long."
279                                axis (car dims) contents (length contents)))
280                       (if (listp contents)
281                           (dolist (content contents)
282                             (frob (1+ axis) (cdr dims) content))
283                           (dotimes (i (length contents))
284                             (frob (1+ axis) (cdr dims) (aref contents i))))))))
285       (frob 0 dimensions initial-contents))))
286
287 (defun vector (&rest objects)
288   #!+sb-doc
289   "Construct a SIMPLE-VECTOR from the given objects."
290   (coerce (the list objects) 'simple-vector))
291 \f
292 ;;;; accessor/setter functions
293
294 (eval-when (:compile-toplevel :execute)
295   (defparameter *specialized-array-element-types*
296     '(t
297       character
298       bit
299       (unsigned-byte 2)
300       (unsigned-byte 4)
301       (unsigned-byte 8)
302       (unsigned-byte 16)
303       (unsigned-byte 32)
304       (signed-byte 8)
305       (signed-byte 16)
306       (signed-byte 30)
307       (signed-byte 32)
308       single-float
309       double-float
310       #!+long-float long-float
311       (complex single-float)
312       (complex double-float)
313       #!+long-float (complex long-float))))
314     
315 (defun hairy-data-vector-ref (array index)
316   (with-array-data ((vector array) (index index) (end))
317     (declare (ignore end) (optimize (safety 3)))
318     (etypecase vector .
319                #.(mapcar (lambda (type)
320                            (let ((atype `(simple-array ,type (*))))
321                              `(,atype
322                                (data-vector-ref (the ,atype vector)
323                                                 index))))
324                          *specialized-array-element-types*))))
325
326 (defun hairy-data-vector-set (array index new-value)
327   (with-array-data ((vector array) (index index) (end))
328     (declare (ignore end) (optimize (safety 3)))
329     (etypecase vector .
330                #.(mapcar (lambda (type)
331                            (let ((atype `(simple-array ,type (*))))
332                              `(,atype
333                                (data-vector-set (the ,atype vector)
334                                                 index
335                                                 (the ,type
336                                                   new-value)))))
337                          *specialized-array-element-types*))))
338
339 (defun %array-row-major-index (array subscripts
340                                      &optional (invalid-index-error-p t))
341   (declare (array array)
342            (list subscripts))
343   (let ((rank (array-rank array)))
344     (unless (= rank (length subscripts))
345       (error "wrong number of subscripts, ~D, for array of rank ~D"
346              (length subscripts) rank))
347     (if (array-header-p array)
348         (do ((subs (nreverse subscripts) (cdr subs))
349              (axis (1- (array-rank array)) (1- axis))
350              (chunk-size 1)
351              (result 0))
352             ((null subs) result)
353           (declare (list subs) (fixnum axis chunk-size result))
354           (let ((index (car subs))
355                 (dim (%array-dimension array axis)))
356             (declare (fixnum index dim))
357             (unless (< -1 index dim)
358               (if invalid-index-error-p
359                   (error "invalid index ~D~[~;~:; on axis ~:*~D~] in ~S"
360                          index axis array)
361                   (return-from %array-row-major-index nil)))
362             (incf result (* chunk-size index))
363             (setf chunk-size (* chunk-size dim))))
364         (let ((index (first subscripts)))
365           (unless (< -1 index (length (the (simple-array * (*)) array)))
366             (if invalid-index-error-p
367                 (error "invalid index ~D in ~S" index array)
368                 (return-from %array-row-major-index nil)))
369           index))))
370
371 (defun array-in-bounds-p (array &rest subscripts)
372   #!+sb-doc
373   "Returns T if the Subscipts are in bounds for the Array, Nil otherwise."
374   (if (%array-row-major-index array subscripts nil)
375       t))
376
377 (defun array-row-major-index (array &rest subscripts)
378   (%array-row-major-index array subscripts))
379
380 (defun aref (array &rest subscripts)
381   #!+sb-doc
382   "Returns the element of the Array specified by the Subscripts."
383   (row-major-aref array (%array-row-major-index array subscripts)))
384
385 (defun %aset (array &rest stuff)
386   (let ((subscripts (butlast stuff))
387         (new-value (car (last stuff))))
388     (setf (row-major-aref array (%array-row-major-index array subscripts))
389           new-value)))
390
391 ;;; FIXME: What's supposed to happen with functions
392 ;;; like AREF when we (DEFUN (SETF FOO) ..) when
393 ;;; DEFSETF FOO is also defined? It seems as though the logical
394 ;;; thing to do would be to nuke the macro definition for (SETF FOO)
395 ;;; and replace it with the (SETF FOO) function, issuing a warning,
396 ;;; just as for ordinary functions
397 ;;;  * (LISP-IMPLEMENTATION-VERSION)
398 ;;;  "18a+ release x86-linux 2.4.7 6 November 1998 cvs"
399 ;;;  * (DEFMACRO ZOO (X) `(+ ,X ,X))
400 ;;;  ZOO
401 ;;;  * (DEFUN ZOO (X) (* 3 X))
402 ;;;  Warning: ZOO previously defined as a macro.
403 ;;;  ZOO
404 ;;; But that doesn't seem to be what happens in CMU CL.
405 ;;;
406 ;;; Also, it would be nice to make DESCRIBE FOO tell whether a symbol
407 ;;; has a setf expansion and/or a setf function defined.
408
409 #!-sb-fluid (declaim (inline (setf aref)))
410 (defun (setf aref) (new-value array &rest subscripts)
411   (declare (type array array))
412   (setf (row-major-aref array (%array-row-major-index array subscripts))
413         new-value))
414
415 (defun row-major-aref (array index)
416   #!+sb-doc
417   "Returns the element of array corressponding to the row-major index. This is
418    SETF'able."
419   (declare (optimize (safety 1)))
420   (row-major-aref array index))
421
422 (defun %set-row-major-aref (array index new-value)
423   (declare (optimize (safety 1)))
424   (setf (row-major-aref array index) new-value))
425
426 (defun svref (simple-vector index)
427   #!+sb-doc
428   "Returns the Index'th element of the given Simple-Vector."
429   (declare (optimize (safety 1)))
430   (aref simple-vector index))
431
432 (defun %svset (simple-vector index new)
433   (declare (optimize (safety 1)))
434   (setf (aref simple-vector index) new))
435
436 (defun bit (bit-array &rest subscripts)
437   #!+sb-doc
438   "Returns the bit from the Bit-Array at the specified Subscripts."
439   (declare (type (array bit) bit-array) (optimize (safety 1)))
440   (row-major-aref bit-array (%array-row-major-index bit-array subscripts)))
441
442 (defun %bitset (bit-array &rest stuff)
443   (declare (type (array bit) bit-array) (optimize (safety 1)))
444   (let ((subscripts (butlast stuff))
445         (new-value (car (last stuff))))
446     (setf (row-major-aref bit-array
447                           (%array-row-major-index bit-array subscripts))
448           new-value)))
449
450 #!-sb-fluid (declaim (inline (setf bit)))
451 (defun (setf bit) (new-value bit-array &rest subscripts)
452   (declare (type (array bit) bit-array) (optimize (safety 1)))
453   (setf (row-major-aref bit-array
454                         (%array-row-major-index bit-array subscripts))
455         new-value))
456
457 (defun sbit (simple-bit-array &rest subscripts)
458   #!+sb-doc
459   "Returns the bit from the Simple-Bit-Array at the specified Subscripts."
460   (declare (type (simple-array bit) simple-bit-array) (optimize (safety 1)))
461   (row-major-aref simple-bit-array
462                   (%array-row-major-index simple-bit-array subscripts)))
463
464 ;;; KLUDGE: Not all these things (%SET-ROW-MAJOR-AREF, %SET-FILL-POINTER,
465 ;;; %SET-FDEFINITION, %SCHARSET, %SBITSET..) seem to deserve separate names.
466 ;;; Could we just DEFUN (SETF SBIT) etc. and get rid of the non-ANSI names?
467 ;;; -- WHN 19990911
468 (defun %sbitset (simple-bit-array &rest stuff)
469   (declare (type (simple-array bit) simple-bit-array) (optimize (safety 1)))
470   (let ((subscripts (butlast stuff))
471         (new-value (car (last stuff))))
472     (setf (row-major-aref simple-bit-array
473                           (%array-row-major-index simple-bit-array subscripts))
474           new-value)))
475
476 #!-sb-fluid (declaim (inline (setf sbit)))
477 (defun (setf sbit) (new-value bit-array &rest subscripts)
478   (declare (type (simple-array bit) bit-array) (optimize (safety 1)))
479   (setf (row-major-aref bit-array
480                         (%array-row-major-index bit-array subscripts))
481         new-value))
482 \f
483 ;;;; miscellaneous array properties
484
485 (defun array-element-type (array)
486   #!+sb-doc
487   "Returns the type of the elements of the array"
488   (let ((type (get-type array)))
489     (macrolet ((pick-element-type (&rest stuff)
490                  `(cond ,@(mapcar #'(lambda (stuff)
491                                       (cons
492                                        (let ((item (car stuff)))
493                                          (cond ((eq item t)
494                                                 t)
495                                                ((listp item)
496                                                 (cons 'or
497                                                       (mapcar #'(lambda (x)
498                                                                   `(= type ,x))
499                                                               item)))
500                                                (t
501                                                 `(= type ,item))))
502                                        (cdr stuff)))
503                                                    stuff))))
504       (pick-element-type
505        ((sb!vm:simple-string-type sb!vm:complex-string-type) 'base-char)
506        ((sb!vm:simple-bit-vector-type sb!vm:complex-bit-vector-type) 'bit)
507        (sb!vm:simple-vector-type t)
508        (sb!vm:simple-array-unsigned-byte-2-type '(unsigned-byte 2))
509        (sb!vm:simple-array-unsigned-byte-4-type '(unsigned-byte 4))
510        (sb!vm:simple-array-unsigned-byte-8-type '(unsigned-byte 8))
511        (sb!vm:simple-array-unsigned-byte-16-type '(unsigned-byte 16))
512        (sb!vm:simple-array-unsigned-byte-32-type '(unsigned-byte 32))
513        (sb!vm:simple-array-signed-byte-8-type '(signed-byte 8))
514        (sb!vm:simple-array-signed-byte-16-type '(signed-byte 16))
515        (sb!vm:simple-array-signed-byte-30-type '(signed-byte 30))
516        (sb!vm:simple-array-signed-byte-32-type '(signed-byte 32))
517        (sb!vm:simple-array-single-float-type 'single-float)
518        (sb!vm:simple-array-double-float-type 'double-float)
519        #!+long-float
520        (sb!vm:simple-array-long-float-type 'long-float)
521        (sb!vm:simple-array-complex-single-float-type '(complex single-float))
522        (sb!vm:simple-array-complex-double-float-type '(complex double-float))
523        #!+long-float
524        (sb!vm:simple-array-complex-long-float-type '(complex long-float))
525        ((sb!vm:simple-array-type sb!vm:complex-vector-type
526                                  sb!vm:complex-array-type)
527         (with-array-data ((array array) (start) (end))
528           (declare (ignore start end))
529           (array-element-type array)))
530        (t
531         (error "~S is not an array." array))))))
532
533 (defun array-rank (array)
534   #!+sb-doc
535   "Return the number of dimensions of ARRAY."
536   (if (array-header-p array)
537       (%array-rank array)
538       1))
539
540 (defun array-dimension (array axis-number)
541   #!+sb-doc
542   "Returns the length of dimension AXIS-NUMBER of ARRAY."
543   (declare (array array) (type index axis-number))
544   (cond ((not (array-header-p array))
545          (unless (= axis-number 0)
546            (error "Vector axis is not zero: ~S" axis-number))
547          (length (the (simple-array * (*)) array)))
548         ((>= axis-number (%array-rank array))
549          (error "~D is too big; ~S only has ~D dimension~:P."
550                 axis-number array (%array-rank array)))
551         (t
552          (%array-dimension array axis-number))))
553
554 (defun array-dimensions (array)
555   #!+sb-doc
556   "Return a list whose elements are the dimensions of the array"
557   (declare (array array))
558   (if (array-header-p array)
559       (do ((results nil (cons (array-dimension array index) results))
560            (index (1- (array-rank array)) (1- index)))
561           ((minusp index) results))
562       (list (array-dimension array 0))))
563
564 (defun array-total-size (array)
565   #!+sb-doc
566   "Return the total number of elements in the Array."
567   (declare (array array))
568   (if (array-header-p array)
569       (%array-available-elements array)
570       (length (the vector array))))
571
572 (defun array-displacement (array)
573   #!+sb-doc
574   "Return the values of :DISPLACED-TO and :DISPLACED-INDEX-offset
575    options to MAKE-ARRAY, or NIL and 0 if not a displaced array."
576   (declare (type array array))
577   (if (and (array-header-p array) ; if unsimple and
578            (%array-displaced-p array)) ; displaced
579       (values (%array-data-vector array) (%array-displacement array))
580       (values nil 0)))
581
582 (defun adjustable-array-p (array)
583   #!+sb-doc
584   "Return T if (ADJUST-ARRAY ARRAY...) would return an array identical
585    to the argument, this happens for complex arrays."
586   (declare (array array))
587   (not (typep array 'simple-array)))
588 \f
589 ;;;; fill pointer frobbing stuff
590
591 (defun array-has-fill-pointer-p (array)
592   #!+sb-doc
593   "Return T if the given ARRAY has a fill pointer, or NIL otherwise."
594   (declare (array array))
595   (and (array-header-p array) (%array-fill-pointer-p array)))
596
597 (defun fill-pointer (vector)
598   #!+sb-doc
599   "Return the FILL-POINTER of the given VECTOR."
600   (declare (vector vector))
601   (if (and (array-header-p vector) (%array-fill-pointer-p vector))
602       (%array-fill-pointer vector)
603       (error 'simple-type-error
604              :datum vector
605              :expected-type '(and vector (satisfies array-has-fill-pointer-p))
606              :format-control "~S is not an array with a fill pointer."
607              :format-arguments (list vector))))
608
609 (defun %set-fill-pointer (vector new)
610   (declare (vector vector) (fixnum new))
611   (if (and (array-header-p vector) (%array-fill-pointer-p vector))
612       (if (> new (%array-available-elements vector))
613         (error
614          "The new fill pointer, ~S, is larger than the length of the vector."
615          new)
616         (setf (%array-fill-pointer vector) new))
617       (error 'simple-type-error
618              :datum vector
619              :expected-type '(and vector (satisfies array-has-fill-pointer-p))
620              :format-control "~S is not an array with a fill pointer."
621              :format-arguments (list vector))))
622
623 ;;; FIXME: It'd probably make sense to use a MACROLET to share the
624 ;;; guts of VECTOR-PUSH between VECTOR-PUSH-EXTEND. Such a macro
625 ;;; should probably be based on the VECTOR-PUSH-EXTEND code (which is
626 ;;; new ca. sbcl-0.7.0) rather than the VECTOR-PUSH code (which dates
627 ;;; back to CMU CL).
628 (defun vector-push (new-el array)
629   #!+sb-doc
630   "Attempt to set the element of ARRAY designated by its fill pointer
631    to NEW-EL, and increment the fill pointer by one. If the fill pointer is
632    too large, NIL is returned, otherwise the index of the pushed element is
633    returned."
634   (declare (vector array))
635   (let ((fill-pointer (fill-pointer array)))
636     (declare (fixnum fill-pointer))
637     (cond ((= fill-pointer (%array-available-elements array))
638            nil)
639           (t
640            (setf (aref array fill-pointer) new-el)
641            (setf (%array-fill-pointer array) (1+ fill-pointer))
642            fill-pointer))))
643
644 (defun vector-push-extend (new-element
645                            vector
646                            &optional
647                            (extension (1+ (length vector))))
648   (declare (vector vector) (fixnum extension))
649   (let ((fill-pointer (fill-pointer vector)))
650     (declare (fixnum fill-pointer))
651     (when (= fill-pointer (%array-available-elements vector))
652       (adjust-array vector (+ fill-pointer extension)))
653     (setf (aref vector fill-pointer) new-element)
654     (setf (%array-fill-pointer vector) (1+ fill-pointer))
655     fill-pointer))
656
657 (defun vector-pop (array)
658   #!+sb-doc
659   "Decrease the fill pointer by 1 and return the element pointed to by the
660   new fill pointer."
661   (declare (vector array))
662   (let ((fill-pointer (fill-pointer array)))
663     (declare (fixnum fill-pointer))
664     (if (zerop fill-pointer)
665         (error "There is nothing left to pop.")
666         (aref array
667               (setf (%array-fill-pointer array)
668                     (1- fill-pointer))))))
669 \f
670 ;;;; ADJUST-ARRAY
671
672 (defun adjust-array (array dimensions &key
673                            (element-type (array-element-type array))
674                            (initial-element nil initial-element-p)
675                            initial-contents fill-pointer
676                            displaced-to displaced-index-offset)
677   #!+sb-doc
678   "Adjust ARRAY's dimensions to the given DIMENSIONS and stuff."
679   (let ((dimensions (if (listp dimensions) dimensions (list dimensions))))
680     (cond ((/= (the fixnum (length (the list dimensions)))
681                (the fixnum (array-rank array)))
682            (error "The number of dimensions not equal to rank of array."))
683           ((not (subtypep element-type (array-element-type array)))
684            (error "The new element type, ~S, is incompatible with old type."
685                   element-type)))
686     (let ((array-rank (length (the list dimensions))))
687       (declare (fixnum array-rank))
688       (when (and fill-pointer (> array-rank 1))
689         (error "Multidimensional arrays can't have fill pointers."))
690       (cond (initial-contents
691              ;; array former contents replaced by INITIAL-CONTENTS
692              (if (or initial-element-p displaced-to)
693                  (error "INITIAL-CONTENTS may not be specified with ~
694                  the :INITIAL-ELEMENT or :DISPLACED-TO option."))
695              (let* ((array-size (apply #'* dimensions))
696                     (array-data (data-vector-from-inits
697                                  dimensions array-size element-type
698                                  initial-contents initial-element
699                                  initial-element-p)))
700                (if (adjustable-array-p array)
701                    (set-array-header array array-data array-size
702                                  (get-new-fill-pointer array array-size
703                                                        fill-pointer)
704                                  0 dimensions nil)
705                    (if (array-header-p array)
706                        ;; simple multidimensional or single dimensional array
707                        (make-array dimensions
708                                    :element-type element-type
709                                    :initial-contents initial-contents)
710                        array-data))))
711             (displaced-to
712              ;; We already established that no INITIAL-CONTENTS was supplied.
713              (when initial-element
714                (error "The :INITIAL-ELEMENT option may not be specified ~
715                       with :DISPLACED-TO."))
716              (unless (subtypep element-type (array-element-type displaced-to))
717                (error "can't displace an array of type ~S into another of ~
718                        type ~S"
719                       element-type (array-element-type displaced-to)))
720              (let ((displacement (or displaced-index-offset 0))
721                    (array-size (apply #'* dimensions)))
722                (declare (fixnum displacement array-size))
723                (if (< (the fixnum (array-total-size displaced-to))
724                       (the fixnum (+ displacement array-size)))
725                    (error "The :DISPLACED-TO array is too small."))
726                (if (adjustable-array-p array)
727                    ;; None of the original contents appear in adjusted array.
728                    (set-array-header array displaced-to array-size
729                                      (get-new-fill-pointer array array-size
730                                                            fill-pointer)
731                                      displacement dimensions t)
732                    ;; simple multidimensional or single dimensional array
733                    (make-array dimensions
734                                :element-type element-type
735                                :displaced-to displaced-to
736                                :displaced-index-offset
737                                displaced-index-offset))))
738             ((= array-rank 1)
739              (let ((old-length (array-total-size array))
740                    (new-length (car dimensions))
741                    new-data)
742                (declare (fixnum old-length new-length))
743                (with-array-data ((old-data array) (old-start)
744                                  (old-end old-length))
745                  (cond ((or (%array-displaced-p array)
746                             (< old-length new-length))
747                         (setf new-data
748                               (data-vector-from-inits
749                                dimensions new-length element-type
750                                initial-contents initial-element
751                                initial-element-p))
752                         (replace new-data old-data
753                                  :start2 old-start :end2 old-end))
754                        (t (setf new-data
755                                 (shrink-vector old-data new-length))))
756                  (if (adjustable-array-p array)
757                      (set-array-header array new-data new-length
758                                        (get-new-fill-pointer array new-length
759                                                              fill-pointer)
760                                        0 dimensions nil)
761                      new-data))))
762             (t
763              (let ((old-length (%array-available-elements array))
764                    (new-length (apply #'* dimensions)))
765                (declare (fixnum old-length new-length))
766                (with-array-data ((old-data array) (old-start)
767                                  (old-end old-length))
768                  (declare (ignore old-end))
769                  (let ((new-data (if (or (%array-displaced-p array)
770                                          (> new-length old-length))
771                                      (data-vector-from-inits
772                                       dimensions new-length
773                                       element-type () initial-element
774                                       initial-element-p)
775                                      old-data)))
776                    (if (or (zerop old-length) (zerop new-length))
777                        (when initial-element-p (fill new-data initial-element))
778                        (zap-array-data old-data (array-dimensions array)
779                                        old-start
780                                        new-data dimensions new-length
781                                        element-type initial-element
782                                        initial-element-p))
783                    (set-array-header array new-data new-length
784                                      new-length 0 dimensions nil)))))))))
785
786 (defun get-new-fill-pointer (old-array new-array-size fill-pointer)
787   (cond ((not fill-pointer)
788          (when (array-has-fill-pointer-p old-array)
789            (when (> (%array-fill-pointer old-array) new-array-size)
790              (error "cannot ADJUST-ARRAY an array (~S) to a size (~S) that is ~
791                     smaller than its fill pointer (~S)"
792                     old-array new-array-size (fill-pointer old-array)))
793            (%array-fill-pointer old-array)))
794         ((not (array-has-fill-pointer-p old-array))
795          (error "cannot supply a non-NIL value (~S) for :FILL-POINTER ~
796                 in ADJUST-ARRAY unless the array (~S) was originally ~
797                 created with a fill pointer"
798                 fill-pointer
799                 old-array))
800         ((numberp fill-pointer)
801          (when (> fill-pointer new-array-size)
802            (error "can't supply a value for :FILL-POINTER (~S) that is larger ~
803                   than the new length of the vector (~S)"
804                   fill-pointer new-array-size))
805          fill-pointer)
806         ((eq fill-pointer t)
807          new-array-size)
808         (t
809          (error "bogus value for :FILL-POINTER in ADJUST-ARRAY: ~S"
810                 fill-pointer))))
811
812 ;;; Destructively alter VECTOR, changing its length to NEW-LENGTH,
813 ;;; which must be less than or equal to its current length.
814 (defun shrink-vector (vector new-length)
815   (declare (vector vector))
816   (unless (array-header-p vector)
817     (macrolet ((frob (name &rest things)
818                  `(etypecase ,name
819                     ,@(mapcar #'(lambda (thing)
820                                   `(,(car thing)
821                                     (fill (truly-the ,(car thing) ,name)
822                                           ,(cadr thing)
823                                           :start new-length)))
824                               things))))
825       (frob vector
826         (simple-vector 0)
827         (simple-base-string #.default-init-char)
828         (simple-bit-vector 0)
829         ((simple-array (unsigned-byte 2) (*)) 0)
830         ((simple-array (unsigned-byte 4) (*)) 0)
831         ((simple-array (unsigned-byte 8) (*)) 0)
832         ((simple-array (unsigned-byte 16) (*)) 0)
833         ((simple-array (unsigned-byte 32) (*)) 0)
834         ((simple-array (signed-byte 8) (*)) 0)
835         ((simple-array (signed-byte 16) (*)) 0)
836         ((simple-array (signed-byte 30) (*)) 0)
837         ((simple-array (signed-byte 32) (*)) 0)
838         ((simple-array single-float (*)) (coerce 0 'single-float))
839         ((simple-array double-float (*)) (coerce 0 'double-float))
840         #!+long-float
841         ((simple-array long-float (*)) (coerce 0 'long-float))
842         ((simple-array (complex single-float) (*))
843          (coerce 0 '(complex single-float)))
844         ((simple-array (complex double-float) (*))
845          (coerce 0 '(complex double-float)))
846         #!+long-float
847         ((simple-array (complex long-float) (*))
848          (coerce 0 '(complex long-float))))))
849   ;; Only arrays have fill-pointers, but vectors have their length
850   ;; parameter in the same place.
851   (setf (%array-fill-pointer vector) new-length)
852   vector)
853
854 ;;; Fill in array header with the provided information, and return the array.
855 (defun set-array-header (array data length fill-pointer displacement dimensions
856                          &optional displacedp)
857   (setf (%array-data-vector array) data)
858   (setf (%array-available-elements array) length)
859   (cond (fill-pointer
860          (setf (%array-fill-pointer array) fill-pointer)
861          (setf (%array-fill-pointer-p array) t))
862         (t
863          (setf (%array-fill-pointer array) length)
864          (setf (%array-fill-pointer-p array) nil)))
865   (setf (%array-displacement array) displacement)
866   (if (listp dimensions)
867       (dotimes (axis (array-rank array))
868         (declare (type index axis))
869         (setf (%array-dimension array axis) (pop dimensions)))
870       (setf (%array-dimension array 0) dimensions))
871   (setf (%array-displaced-p array) displacedp)
872   array)
873 \f
874 ;;;; ZAP-ARRAY-DATA for ADJUST-ARRAY
875
876 ;;; a temporary to be used when OLD-DATA and NEW-DATA are EQ.
877 ;;; KLUDGE: Boy, DYNAMIC-EXTENT would be nice.
878 (defvar *zap-array-data-temp* (make-array 1000 :initial-element t))
879
880 (defun zap-array-data-temp (length element-type initial-element
881                             initial-element-p)
882   (declare (fixnum length))
883   (when (> length (the fixnum (length *zap-array-data-temp*)))
884     (setf *zap-array-data-temp*
885           (make-array length :initial-element t)))
886   (when initial-element-p
887     (unless (typep initial-element element-type)
888       (error "~S can't be used to initialize an array of type ~S."
889              initial-element element-type))
890     (fill (the simple-vector *zap-array-data-temp*) initial-element
891           :end length))
892   *zap-array-data-temp*)
893
894 ;;; This does the grinding work for ADJUST-ARRAY. It zaps the data
895 ;;; from the OLD-DATA in an arrangement specified by the OLD-DIMS to
896 ;;; the NEW-DATA in an arrangement specified by the NEW-DIMS. OFFSET
897 ;;; is a displaced offset to be added to computed indices of OLD-DATA.
898 ;;; NEW-LENGTH, ELEMENT-TYPE, INITIAL-ELEMENT, and INITIAL-ELEMENT-P
899 ;;; are used when OLD-DATA and NEW-DATA are EQ; in this case, a
900 ;;; temporary must be used and filled appropriately. When OLD-DATA and
901 ;;; NEW-DATA are not EQ, NEW-DATA has already been filled with any
902 ;;; specified initial-element.
903 (defun zap-array-data (old-data old-dims offset new-data new-dims new-length
904                        element-type initial-element initial-element-p)
905   (declare (list old-dims new-dims))
906   (setq old-dims (nreverse old-dims))
907   (setq new-dims (reverse new-dims))
908   (if (eq old-data new-data)
909       (let ((temp (zap-array-data-temp new-length element-type
910                                        initial-element initial-element-p)))
911         (zap-array-data-aux old-data old-dims offset temp new-dims)
912         (dotimes (i new-length) (setf (aref new-data i) (aref temp i))))
913       (zap-array-data-aux old-data old-dims offset new-data new-dims)))
914
915 (defun zap-array-data-aux (old-data old-dims offset new-data new-dims)
916   (declare (fixnum offset))
917   (let ((limits (mapcar #'(lambda (x y)
918                             (declare (fixnum x y))
919                             (1- (the fixnum (min x y))))
920                         old-dims new-dims)))
921     (macrolet ((bump-index-list (index limits)
922                  `(do ((subscripts ,index (cdr subscripts))
923                        (limits ,limits (cdr limits)))
924                       ((null subscripts) nil)
925                     (cond ((< (the fixnum (car subscripts))
926                               (the fixnum (car limits)))
927                            (rplaca subscripts
928                                    (1+ (the fixnum (car subscripts))))
929                            (return ,index))
930                           (t (rplaca subscripts 0))))))
931       (do ((index (make-list (length old-dims) :initial-element 0)
932                   (bump-index-list index limits)))
933           ((null index))
934         (setf (aref new-data (row-major-index-from-dims index new-dims))
935               (aref old-data
936                     (+ (the fixnum (row-major-index-from-dims index old-dims))
937                        offset)))))))
938
939 ;;; Figure out the row-major-order index of an array reference from a
940 ;;; list of subscripts and a list of dimensions. This is for internal
941 ;;; calls only, and the subscripts and dim-list variables are assumed
942 ;;; to be reversed from what the user supplied.
943 (defun row-major-index-from-dims (rev-subscripts rev-dim-list)
944   (do ((rev-subscripts rev-subscripts (cdr rev-subscripts))
945        (rev-dim-list rev-dim-list (cdr rev-dim-list))
946        (chunk-size 1)
947        (result 0))
948       ((null rev-dim-list) result)
949     (declare (fixnum chunk-size result))
950     (setq result (+ result
951                     (the fixnum (* (the fixnum (car rev-subscripts))
952                                    chunk-size))))
953     (setq chunk-size (* chunk-size (the fixnum (car rev-dim-list))))))
954 \f
955 ;;;; some bit stuff
956
957 (defun bit-array-same-dimensions-p (array1 array2)
958   (declare (type (array bit) array1 array2))
959   (and (= (array-rank array1)
960           (array-rank array2))
961        (dotimes (index (array-rank array1) t)
962          (when (/= (array-dimension array1 index)
963                    (array-dimension array2 index))
964            (return nil)))))
965
966 (defun pick-result-array (result-bit-array bit-array-1)
967   (case result-bit-array
968     ((t) bit-array-1)
969     ((nil) (make-array (array-dimensions bit-array-1)
970                        :element-type 'bit
971                        :initial-element 0))
972     (t
973      (unless (bit-array-same-dimensions-p bit-array-1
974                                           result-bit-array)
975        (error "~S and ~S don't have the same dimensions."
976               bit-array-1 result-bit-array))
977      result-bit-array)))
978
979 (defmacro def-bit-array-op (name function)
980   `(defun ,name (bit-array-1 bit-array-2 &optional result-bit-array)
981      ,(format nil
982               "Perform a bit-wise ~A on the elements of BIT-ARRAY-1 and ~
983               BIT-ARRAY-2,~%  putting the results in RESULT-BIT-ARRAY. ~
984               If RESULT-BIT-ARRAY is T,~%  BIT-ARRAY-1 is used. If ~
985               RESULT-BIT-ARRAY is NIL or omitted, a new array is~%  created. ~
986               All the arrays must have the same rank and dimensions."
987               (symbol-name function))
988      (declare (type (array bit) bit-array-1 bit-array-2)
989               (type (or (array bit) (member t nil)) result-bit-array))
990      (unless (bit-array-same-dimensions-p bit-array-1 bit-array-2)
991        (error "~S and ~S don't have the same dimensions."
992               bit-array-1 bit-array-2))
993      (let ((result-bit-array (pick-result-array result-bit-array bit-array-1)))
994        (if (and (simple-bit-vector-p bit-array-1)
995                 (simple-bit-vector-p bit-array-2)
996                 (simple-bit-vector-p result-bit-array))
997            (locally (declare (optimize (speed 3) (safety 0)))
998              (,name bit-array-1 bit-array-2 result-bit-array))
999            (with-array-data ((data1 bit-array-1) (start1) (end1))
1000              (declare (ignore end1))
1001              (with-array-data ((data2 bit-array-2) (start2) (end2))
1002                (declare (ignore end2))
1003                (with-array-data ((data3 result-bit-array) (start3) (end3))
1004                  (do ((index-1 start1 (1+ index-1))
1005                       (index-2 start2 (1+ index-2))
1006                       (index-3 start3 (1+ index-3)))
1007                      ((>= index-3 end3) result-bit-array)
1008                    (declare (type index index-1 index-2 index-3))
1009                    (setf (sbit data3 index-3)
1010                          (logand (,function (sbit data1 index-1)
1011                                             (sbit data2 index-2))
1012                                  1))))))))))
1013
1014 (def-bit-array-op bit-and logand)
1015 (def-bit-array-op bit-ior logior)
1016 (def-bit-array-op bit-xor logxor)
1017 (def-bit-array-op bit-eqv logeqv)
1018 (def-bit-array-op bit-nand lognand)
1019 (def-bit-array-op bit-nor lognor)
1020 (def-bit-array-op bit-andc1 logandc1)
1021 (def-bit-array-op bit-andc2 logandc2)
1022 (def-bit-array-op bit-orc1 logorc1)
1023 (def-bit-array-op bit-orc2 logorc2)
1024
1025 (defun bit-not (bit-array &optional result-bit-array)
1026   #!+sb-doc
1027   "Performs a bit-wise logical NOT on the elements of BIT-ARRAY,
1028   putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
1029   BIT-ARRAY is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
1030   created. Both arrays must have the same rank and dimensions."
1031   (declare (type (array bit) bit-array)
1032            (type (or (array bit) (member t nil)) result-bit-array))
1033   (let ((result-bit-array (pick-result-array result-bit-array bit-array)))
1034     (if (and (simple-bit-vector-p bit-array)
1035              (simple-bit-vector-p result-bit-array))
1036         (locally (declare (optimize (speed 3) (safety 0)))
1037           (bit-not bit-array result-bit-array))
1038         (with-array-data ((src bit-array) (src-start) (src-end))
1039           (declare (ignore src-end))
1040           (with-array-data ((dst result-bit-array) (dst-start) (dst-end))
1041             (do ((src-index src-start (1+ src-index))
1042                  (dst-index dst-start (1+ dst-index)))
1043                 ((>= dst-index dst-end) result-bit-array)
1044               (declare (type index src-index dst-index))
1045               (setf (sbit dst dst-index)
1046                     (logxor (sbit src src-index) 1))))))))