0.pre7.1:
[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 (defun vector-push (new-el array)
624   #!+sb-doc
625   "Attempt to set the element of ARRAY designated by its fill pointer
626    to NEW-EL, and increment the fill pointer by one. If the fill pointer is
627    too large, NIL is returned, otherwise the index of the pushed element is
628    returned."
629   (declare (vector array))
630   (let ((fill-pointer (fill-pointer array)))
631     (declare (fixnum fill-pointer))
632     (cond ((= fill-pointer (%array-available-elements array))
633            nil)
634           (t
635            (setf (aref array fill-pointer) new-el)
636            (setf (%array-fill-pointer array) (1+ fill-pointer))
637            fill-pointer))))
638
639 (defun vector-push-extend (new-element
640                            vector
641                            &optional
642                            (extension (1+ (length vector))))
643   #!+sb-doc
644   "This is like Vector-Push except that if the fill pointer gets too
645    large, the Vector is extended rather than Nil being returned."
646   (declare (vector vector) (fixnum extension))
647   (let ((fill-pointer (fill-pointer vector)))
648     (declare (fixnum fill-pointer))
649     (when (= fill-pointer (%array-available-elements vector))
650       (adjust-array vector (+ fill-pointer extension)))
651     (setf (aref vector fill-pointer) new-element)
652     (setf (%array-fill-pointer vector) (1+ fill-pointer))
653     fill-pointer))
654
655 (defun vector-pop (array)
656   #!+sb-doc
657   "Attempts to decrease the fill pointer by 1 and return the element
658    pointer to by the new fill pointer. If the original value of the fill
659    pointer is 0, an error occurs."
660   (declare (vector array))
661   (let ((fill-pointer (fill-pointer array)))
662     (declare (fixnum fill-pointer))
663     (if (zerop fill-pointer)
664         (error "There is nothing left to pop.")
665         (aref array
666               (setf (%array-fill-pointer array)
667                     (1- fill-pointer))))))
668 \f
669 ;;;; ADJUST-ARRAY
670
671 (defun adjust-array (array dimensions &key
672                            (element-type (array-element-type array))
673                            (initial-element nil initial-element-p)
674                            initial-contents fill-pointer
675                            displaced-to displaced-index-offset)
676   #!+sb-doc
677   "Adjusts the Array's dimensions to the given Dimensions and stuff."
678   (let ((dimensions (if (listp dimensions) dimensions (list dimensions))))
679     (cond ((/= (the fixnum (length (the list dimensions)))
680                (the fixnum (array-rank array)))
681            (error "The number of dimensions not equal to rank of array."))
682           ((not (subtypep element-type (array-element-type array)))
683            (error "The new element type, ~S, is incompatible with old type."
684                   element-type)))
685     (let ((array-rank (length (the list dimensions))))
686       (declare (fixnum array-rank))
687       (when (and fill-pointer (> array-rank 1))
688         (error "Multidimensional arrays can't have fill pointers."))
689       (cond (initial-contents
690              ;; array former contents replaced by INITIAL-CONTENTS
691              (if (or initial-element-p displaced-to)
692                  (error "INITIAL-CONTENTS may not be specified with ~
693                  the :INITIAL-ELEMENT or :DISPLACED-TO option."))
694              (let* ((array-size (apply #'* dimensions))
695                     (array-data (data-vector-from-inits
696                                  dimensions array-size element-type
697                                  initial-contents initial-element
698                                  initial-element-p)))
699                (if (adjustable-array-p array)
700                    (set-array-header array array-data array-size
701                                  (get-new-fill-pointer array array-size
702                                                        fill-pointer)
703                                  0 dimensions nil)
704                    (if (array-header-p array)
705                        ;; simple multidimensional or single dimensional array
706                        (make-array dimensions
707                                    :element-type element-type
708                                    :initial-contents initial-contents)
709                        array-data))))
710             (displaced-to
711              ;; We already established that no INITIAL-CONTENTS was supplied.
712              (when initial-element
713                (error "The :INITIAL-ELEMENT option may not be specified ~
714                       with :DISPLACED-TO."))
715              (unless (subtypep element-type (array-element-type displaced-to))
716                (error "can't displace an array of type ~S into another of ~
717                        type ~S"
718                       element-type (array-element-type displaced-to)))
719              (let ((displacement (or displaced-index-offset 0))
720                    (array-size (apply #'* dimensions)))
721                (declare (fixnum displacement array-size))
722                (if (< (the fixnum (array-total-size displaced-to))
723                       (the fixnum (+ displacement array-size)))
724                    (error "The :DISPLACED-TO array is too small."))
725                (if (adjustable-array-p array)
726                    ;; None of the original contents appear in adjusted array.
727                    (set-array-header array displaced-to array-size
728                                      (get-new-fill-pointer array array-size
729                                                            fill-pointer)
730                                      displacement dimensions t)
731                    ;; simple multidimensional or single dimensional array
732                    (make-array dimensions
733                                :element-type element-type
734                                :displaced-to displaced-to
735                                :displaced-index-offset
736                                displaced-index-offset))))
737             ((= array-rank 1)
738              (let ((old-length (array-total-size array))
739                    (new-length (car dimensions))
740                    new-data)
741                (declare (fixnum old-length new-length))
742                (with-array-data ((old-data array) (old-start)
743                                  (old-end old-length))
744                  (cond ((or (%array-displaced-p array)
745                             (< old-length new-length))
746                         (setf new-data
747                               (data-vector-from-inits
748                                dimensions new-length element-type
749                                initial-contents initial-element
750                                initial-element-p))
751                         (replace new-data old-data
752                                  :start2 old-start :end2 old-end))
753                        (t (setf new-data
754                                 (shrink-vector old-data new-length))))
755                  (if (adjustable-array-p array)
756                      (set-array-header array new-data new-length
757                                        (get-new-fill-pointer array new-length
758                                                              fill-pointer)
759                                        0 dimensions nil)
760                      new-data))))
761             (t
762              (let ((old-length (%array-available-elements array))
763                    (new-length (apply #'* dimensions)))
764                (declare (fixnum old-length new-length))
765                (with-array-data ((old-data array) (old-start)
766                                  (old-end old-length))
767                  (declare (ignore old-end))
768                  (let ((new-data (if (or (%array-displaced-p array)
769                                          (> new-length old-length))
770                                      (data-vector-from-inits
771                                       dimensions new-length
772                                       element-type () initial-element
773                                       initial-element-p)
774                                      old-data)))
775                    (if (or (zerop old-length) (zerop new-length))
776                        (when initial-element-p (fill new-data initial-element))
777                        (zap-array-data old-data (array-dimensions array)
778                                        old-start
779                                        new-data dimensions new-length
780                                        element-type initial-element
781                                        initial-element-p))
782                    (set-array-header array new-data new-length
783                                      new-length 0 dimensions nil)))))))))
784
785 (defun get-new-fill-pointer (old-array new-array-size fill-pointer)
786   (cond ((not fill-pointer)
787          (when (array-has-fill-pointer-p old-array)
788            (when (> (%array-fill-pointer old-array) new-array-size)
789              (error "cannot ADJUST-ARRAY an array (~S) to a size (~S) that is ~
790                     smaller than its fill pointer (~S)"
791                     old-array new-array-size (fill-pointer old-array)))
792            (%array-fill-pointer old-array)))
793         ((not (array-has-fill-pointer-p old-array))
794          (error "cannot supply a non-NIL value (~S) for :FILL-POINTER ~
795                 in ADJUST-ARRAY unless the array (~S) was originally ~
796                 created with a fill pointer"
797                 fill-pointer
798                 old-array))
799         ((numberp fill-pointer)
800          (when (> fill-pointer new-array-size)
801            (error "can't supply a value for :FILL-POINTER (~S) that is larger ~
802                   than the new length of the vector (~S)"
803                   fill-pointer new-array-size))
804          fill-pointer)
805         ((eq fill-pointer t)
806          new-array-size)
807         (t
808          (error "bogus value for :FILL-POINTER in ADJUST-ARRAY: ~S"
809                 fill-pointer))))
810
811 ;;; Destructively alter VECTOR, changing its length to NEW-LENGTH,
812 ;;; which must be less than or equal to its current length.
813 (defun shrink-vector (vector new-length)
814   (declare (vector vector))
815   (unless (array-header-p vector)
816     (macrolet ((frob (name &rest things)
817                  `(etypecase ,name
818                     ,@(mapcar #'(lambda (thing)
819                                   `(,(car thing)
820                                     (fill (truly-the ,(car thing) ,name)
821                                           ,(cadr thing)
822                                           :start new-length)))
823                               things))))
824       (frob vector
825         (simple-vector 0)
826         (simple-base-string #.default-init-char)
827         (simple-bit-vector 0)
828         ((simple-array (unsigned-byte 2) (*)) 0)
829         ((simple-array (unsigned-byte 4) (*)) 0)
830         ((simple-array (unsigned-byte 8) (*)) 0)
831         ((simple-array (unsigned-byte 16) (*)) 0)
832         ((simple-array (unsigned-byte 32) (*)) 0)
833         ((simple-array (signed-byte 8) (*)) 0)
834         ((simple-array (signed-byte 16) (*)) 0)
835         ((simple-array (signed-byte 30) (*)) 0)
836         ((simple-array (signed-byte 32) (*)) 0)
837         ((simple-array single-float (*)) (coerce 0 'single-float))
838         ((simple-array double-float (*)) (coerce 0 'double-float))
839         #!+long-float
840         ((simple-array long-float (*)) (coerce 0 'long-float))
841         ((simple-array (complex single-float) (*))
842          (coerce 0 '(complex single-float)))
843         ((simple-array (complex double-float) (*))
844          (coerce 0 '(complex double-float)))
845         #!+long-float
846         ((simple-array (complex long-float) (*))
847          (coerce 0 '(complex long-float))))))
848   ;; Only arrays have fill-pointers, but vectors have their length
849   ;; parameter in the same place.
850   (setf (%array-fill-pointer vector) new-length)
851   vector)
852
853 ;;; Fill in array header with the provided information, and return the array.
854 (defun set-array-header (array data length fill-pointer displacement dimensions
855                          &optional displacedp)
856   (setf (%array-data-vector array) data)
857   (setf (%array-available-elements array) length)
858   (cond (fill-pointer
859          (setf (%array-fill-pointer array) fill-pointer)
860          (setf (%array-fill-pointer-p array) t))
861         (t
862          (setf (%array-fill-pointer array) length)
863          (setf (%array-fill-pointer-p array) nil)))
864   (setf (%array-displacement array) displacement)
865   (if (listp dimensions)
866       (dotimes (axis (array-rank array))
867         (declare (type index axis))
868         (setf (%array-dimension array axis) (pop dimensions)))
869       (setf (%array-dimension array 0) dimensions))
870   (setf (%array-displaced-p array) displacedp)
871   array)
872 \f
873 ;;;; ZAP-ARRAY-DATA for ADJUST-ARRAY
874
875 ;;; a temporary to be used when OLD-DATA and NEW-DATA are EQ.
876 ;;; KLUDGE: Boy, DYNAMIC-EXTENT would be nice.
877 (defvar *zap-array-data-temp* (make-array 1000 :initial-element t))
878
879 (defun zap-array-data-temp (length element-type initial-element
880                             initial-element-p)
881   (declare (fixnum length))
882   (when (> length (the fixnum (length *zap-array-data-temp*)))
883     (setf *zap-array-data-temp*
884           (make-array length :initial-element t)))
885   (when initial-element-p
886     (unless (typep initial-element element-type)
887       (error "~S can't be used to initialize an array of type ~S."
888              initial-element element-type))
889     (fill (the simple-vector *zap-array-data-temp*) initial-element
890           :end length))
891   *zap-array-data-temp*)
892
893 ;;; This does the grinding work for ADJUST-ARRAY. It zaps the data
894 ;;; from the OLD-DATA in an arrangement specified by the OLD-DIMS to
895 ;;; the NEW-DATA in an arrangement specified by the NEW-DIMS. OFFSET
896 ;;; is a displaced offset to be added to computed indices of OLD-DATA.
897 ;;; NEW-LENGTH, ELEMENT-TYPE, INITIAL-ELEMENT, and INITIAL-ELEMENT-P
898 ;;; are used when OLD-DATA and NEW-DATA are EQ; in this case, a
899 ;;; temporary must be used and filled appropriately. When OLD-DATA and
900 ;;; NEW-DATA are not EQ, NEW-DATA has already been filled with any
901 ;;; specified initial-element.
902 (defun zap-array-data (old-data old-dims offset new-data new-dims new-length
903                        element-type initial-element initial-element-p)
904   (declare (list old-dims new-dims))
905   (setq old-dims (nreverse old-dims))
906   (setq new-dims (reverse new-dims))
907   (if (eq old-data new-data)
908       (let ((temp (zap-array-data-temp new-length element-type
909                                        initial-element initial-element-p)))
910         (zap-array-data-aux old-data old-dims offset temp new-dims)
911         (dotimes (i new-length) (setf (aref new-data i) (aref temp i))))
912       (zap-array-data-aux old-data old-dims offset new-data new-dims)))
913
914 (defun zap-array-data-aux (old-data old-dims offset new-data new-dims)
915   (declare (fixnum offset))
916   (let ((limits (mapcar #'(lambda (x y)
917                             (declare (fixnum x y))
918                             (1- (the fixnum (min x y))))
919                         old-dims new-dims)))
920     (macrolet ((bump-index-list (index limits)
921                  `(do ((subscripts ,index (cdr subscripts))
922                        (limits ,limits (cdr limits)))
923                       ((null subscripts) nil)
924                     (cond ((< (the fixnum (car subscripts))
925                               (the fixnum (car limits)))
926                            (rplaca subscripts
927                                    (1+ (the fixnum (car subscripts))))
928                            (return ,index))
929                           (t (rplaca subscripts 0))))))
930       (do ((index (make-list (length old-dims) :initial-element 0)
931                   (bump-index-list index limits)))
932           ((null index))
933         (setf (aref new-data (row-major-index-from-dims index new-dims))
934               (aref old-data
935                     (+ (the fixnum (row-major-index-from-dims index old-dims))
936                        offset)))))))
937
938 ;;; Figure out the row-major-order index of an array reference from a
939 ;;; list of subscripts and a list of dimensions. This is for internal
940 ;;; calls only, and the subscripts and dim-list variables are assumed
941 ;;; to be reversed from what the user supplied.
942 (defun row-major-index-from-dims (rev-subscripts rev-dim-list)
943   (do ((rev-subscripts rev-subscripts (cdr rev-subscripts))
944        (rev-dim-list rev-dim-list (cdr rev-dim-list))
945        (chunk-size 1)
946        (result 0))
947       ((null rev-dim-list) result)
948     (declare (fixnum chunk-size result))
949     (setq result (+ result
950                     (the fixnum (* (the fixnum (car rev-subscripts))
951                                    chunk-size))))
952     (setq chunk-size (* chunk-size (the fixnum (car rev-dim-list))))))
953 \f
954 ;;;; some bit stuff
955
956 (defun bit-array-same-dimensions-p (array1 array2)
957   (declare (type (array bit) array1 array2))
958   (and (= (array-rank array1)
959           (array-rank array2))
960        (dotimes (index (array-rank array1) t)
961          (when (/= (array-dimension array1 index)
962                    (array-dimension array2 index))
963            (return nil)))))
964
965 (defun pick-result-array (result-bit-array bit-array-1)
966   (case result-bit-array
967     ((t) bit-array-1)
968     ((nil) (make-array (array-dimensions bit-array-1)
969                        :element-type 'bit
970                        :initial-element 0))
971     (t
972      (unless (bit-array-same-dimensions-p bit-array-1
973                                           result-bit-array)
974        (error "~S and ~S don't have the same dimensions."
975               bit-array-1 result-bit-array))
976      result-bit-array)))
977
978 (defmacro def-bit-array-op (name function)
979   `(defun ,name (bit-array-1 bit-array-2 &optional result-bit-array)
980      ,(format nil
981               "Perform a bit-wise ~A on the elements of BIT-ARRAY-1 and ~
982               BIT-ARRAY-2,~%  putting the results in RESULT-BIT-ARRAY. ~
983               If RESULT-BIT-ARRAY is T,~%  BIT-ARRAY-1 is used. If ~
984               RESULT-BIT-ARRAY is NIL or omitted, a new array is~%  created. ~
985               All the arrays must have the same rank and dimensions."
986               (symbol-name function))
987      (declare (type (array bit) bit-array-1 bit-array-2)
988               (type (or (array bit) (member t nil)) result-bit-array))
989      (unless (bit-array-same-dimensions-p bit-array-1 bit-array-2)
990        (error "~S and ~S don't have the same dimensions."
991               bit-array-1 bit-array-2))
992      (let ((result-bit-array (pick-result-array result-bit-array bit-array-1)))
993        (if (and (simple-bit-vector-p bit-array-1)
994                 (simple-bit-vector-p bit-array-2)
995                 (simple-bit-vector-p result-bit-array))
996            (locally (declare (optimize (speed 3) (safety 0)))
997              (,name bit-array-1 bit-array-2 result-bit-array))
998            (with-array-data ((data1 bit-array-1) (start1) (end1))
999              (declare (ignore end1))
1000              (with-array-data ((data2 bit-array-2) (start2) (end2))
1001                (declare (ignore end2))
1002                (with-array-data ((data3 result-bit-array) (start3) (end3))
1003                  (do ((index-1 start1 (1+ index-1))
1004                       (index-2 start2 (1+ index-2))
1005                       (index-3 start3 (1+ index-3)))
1006                      ((>= index-3 end3) result-bit-array)
1007                    (declare (type index index-1 index-2 index-3))
1008                    (setf (sbit data3 index-3)
1009                          (logand (,function (sbit data1 index-1)
1010                                             (sbit data2 index-2))
1011                                  1))))))))))
1012
1013 (def-bit-array-op bit-and logand)
1014 (def-bit-array-op bit-ior logior)
1015 (def-bit-array-op bit-xor logxor)
1016 (def-bit-array-op bit-eqv logeqv)
1017 (def-bit-array-op bit-nand lognand)
1018 (def-bit-array-op bit-nor lognor)
1019 (def-bit-array-op bit-andc1 logandc1)
1020 (def-bit-array-op bit-andc2 logandc2)
1021 (def-bit-array-op bit-orc1 logorc1)
1022 (def-bit-array-op bit-orc2 logorc2)
1023
1024 (defun bit-not (bit-array &optional result-bit-array)
1025   #!+sb-doc
1026   "Performs a bit-wise logical NOT on the elements of BIT-ARRAY,
1027   putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
1028   BIT-ARRAY is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
1029   created. Both arrays must have the same rank and dimensions."
1030   (declare (type (array bit) bit-array)
1031            (type (or (array bit) (member t nil)) result-bit-array))
1032   (let ((result-bit-array (pick-result-array result-bit-array bit-array)))
1033     (if (and (simple-bit-vector-p bit-array)
1034              (simple-bit-vector-p result-bit-array))
1035         (locally (declare (optimize (speed 3) (safety 0)))
1036           (bit-not bit-array result-bit-array))
1037         (with-array-data ((src bit-array) (src-start) (src-end))
1038           (declare (ignore src-end))
1039           (with-array-data ((dst result-bit-array) (dst-start) (dst-end))
1040             (do ((src-index src-start (1+ src-index))
1041                  (dst-index dst-start (1+ dst-index)))
1042                 ((>= dst-index dst-end) result-bit-array)
1043               (declare (type index src-index dst-index))
1044               (setf (sbit dst dst-index)
1045                     (logxor (sbit src src-index) 1))))))))