]> asedeno.scripts.mit.edu Git - cl-protobufs.git/blob - utilities.lisp
ff2dc70389b042eb0870d0218aaf545455faed1b
[cl-protobufs.git] / utilities.lisp
1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2 ;;;                                                                  ;;;
3 ;;; Free Software published under an MIT-like license. See LICENSE   ;;;
4 ;;;                                                                  ;;;
5 ;;; Copyright (c) 2012 Google, Inc.  All rights reserved.            ;;;
6 ;;;                                                                  ;;;
7 ;;; Original author: Scott McKay                                     ;;;
8 ;;;                                                                  ;;;
9 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
10
11 (in-package "PROTO-IMPL")
12
13
14 ;;; Optimized fixnum arithmetic
15
16 (eval-when (:compile-toplevel :load-toplevel :execute)
17
18 (defparameter $optimize-default     '(optimize (speed 1) (safety 3) (debug 3))
19   "Compiler optimization settings for safe, debuggable code.")
20 (defparameter $optimize-fast-unsafe '(optimize (speed 3) (safety 0) (debug 0))
21   "Compiler optimization settings for fast, unsafe, hard-to-debug code.")
22
23 )       ;eval-when
24
25
26 (defmacro i+ (&rest fixnums)
27   `(the fixnum (+ ,@(loop for n in fixnums collect `(the fixnum ,n)))))
28
29 (defmacro i- (number &rest fixnums)
30   `(the fixnum (- (the fixnum ,number) ,@(loop for n in fixnums collect `(the fixnum ,n)))))
31
32 (defmacro i* (&rest fixnums)
33   `(the fixnum (* ,@(loop for n in fixnums collect `(the fixnum ,n)))))
34
35 (defmacro i= (&rest fixnums)
36   `(= ,@(loop for n in fixnums collect `(the fixnum ,n))))
37
38 (defmacro i< (&rest fixnums)
39   `(< ,@(loop for n in fixnums collect `(the fixnum ,n))))
40
41 (defmacro i<= (&rest fixnums)
42   `(<= ,@(loop for n in fixnums collect `(the fixnum ,n))))
43
44 (defmacro i> (&rest fixnums)
45   `(> ,@(loop for n in fixnums collect `(the fixnum ,n))))
46
47 (defmacro i>= (&rest fixnums)
48   `(>= ,@(loop for n in fixnums collect `(the fixnum ,n))))
49
50 (defmacro iash (value count)
51   `(the fixnum (ash (the fixnum ,value) (the fixnum ,count))))
52
53 (defmacro ilogior (&rest fixnums)
54   (if (cdr fixnums)
55     `(the fixnum (logior (the fixnum ,(car fixnums))
56                          ,(if (cddr fixnums)
57                             `(ilogior ,@(cdr fixnums))
58                             `(the fixnum ,(cadr fixnums)))))
59     `(the fixnum ,(car fixnums))))
60
61 (defmacro ilogand (&rest fixnums)
62   (if (cdr fixnums)
63     `(the fixnum (logand (the fixnum ,(car fixnums))
64                          ,(if (cddr fixnums)
65                             `(ilogand ,@(cdr fixnums))
66                             `(the fixnum ,(cadr fixnums)))))
67     `(the fixnum ,(car fixnums))))
68
69 (define-modify-macro iincf (&optional (delta 1)) i+)
70 (define-modify-macro idecf (&optional (delta 1)) i-)
71
72 (defmacro ildb (bytespec value)
73   `(the fixnum (ldb ,bytespec (the fixnum ,value))))
74
75
76 ;;; String utilities
77
78 (defun starts-with (string prefix &key (start 0))
79   "Returns true if 'string' starts with the prefix 'prefix' (case insensitive)."
80   (and (i>= (length string) (i+ start (length prefix)))
81        (string-equal string prefix :start1 start :end1 (i+ start (length prefix)))
82        prefix))
83
84 (defun ends-with (string suffix &key (end (length string)))
85   "Returns true if 'string' ends with the prefix 'prefix' (case insensitive)."
86   (and (i>= end (length suffix))
87        (string-equal string suffix :start1 (i- end (length suffix)) :end1 end)
88        suffix))
89
90 (defun strcat (&rest strings)
91   "Concatenate a bunch of strings."
92   (declare (dynamic-extent strings))
93   (apply #'concatenate 'string strings))
94
95
96 ;; (camel-case "camel-case") => "CamelCase"
97 (defun camel-case (string &optional (separators '(#\-)))
98   "Take a hyphen-separated string and turn it into a camel-case string."
99   (let ((words (split-string string :separators separators)))
100     (format nil "~{~@(~A~)~}" words)))
101
102 ;; (camel-case-but-one "camel-case") => "camelCase"
103 (defun camel-case-but-one (string &optional (separators '(#\-)))
104   "Take a hyphen-separated string and turn its tail into a camel-case string."
105   (let ((words (split-string string :separators separators)))
106     (format nil "~(~A~)~{~@(~A~)~}" (car words) (cdr words))))
107
108
109 ;; (uncamel-case "CamelCase") => "CAMEL-CASE"
110 ;; (uncamel-case "TCPConnection") => "TCP-CONNECTION"
111 ;; (uncamel-case "NewTCPConnection") => "NEW-TCP-CONNECTION"
112 ;; (uncamel-case "new_RPC_LispService") => "NEW-RPC-LISP-SERVICE"
113 ;; (uncamel-case "RPC_LispServiceRequest_get_request") => "RPC-LISP-SERVICE-REQUEST-GET-REQUEST"
114 ;; (uncamel-case "TCP2Name3") => "TCP2-NAME3"
115 (defun uncamel-case (name)
116   "Take a camel-case string and turn it into a hyphen-separated string."
117   ;; We need a whole state machine to get this right
118   (labels ((uncamel (chars state result)
119              (let ((ch (first chars)))
120                (cond ((null chars)
121                       result)
122                      ((upper-case-p ch)
123                       (uncamel (rest chars) 'upper
124                                (case state
125                                  ((upper)
126                                   ;; "TCPConnection" => "TCP-CONNECTION"
127                                   (if (and (second chars) (lower-case-p (second chars)))
128                                     (list* ch #\- result)
129                                     (cons ch result)))
130                                  ((lower digit) (list* ch #\- result))
131                                  (otherwise (cons ch result)))))
132                      ((lower-case-p ch)
133                       (uncamel (rest chars) 'lower
134                                (cons (char-upcase ch) result)))
135                      ((digit-char-p ch)
136                       (uncamel (rest chars) 'digit 
137                                (cons ch result)))
138                      ((or (eql ch #\-) (eql ch #\_))
139                       (uncamel (rest chars) 'dash
140                                (cons #\- result)))
141                      ((eql ch #\.)
142                       (uncamel (rest chars) 'dot
143                                (cons #\. result)))
144                      (t
145                       (error "Invalid name character: ~A" ch))))))
146     (strcat (nreverse (uncamel (concatenate 'list name) nil ())))))
147
148
149 (defun split-string (line &key (start 0) (end (length line)) (separators '(#\-)))
150   "Given a string 'string', splits it at each of the separators.
151    Returns a list of the string pieces, with empty pieces removed."
152   (unless (i= start end)
153     (loop for this fixnum = start then (i+ next 1)
154           for next fixnum = (or (position-if #'(lambda (ch) (member ch separators)) line
155                                              :start this :end end)
156                                 end)
157           for piece = (string-right-trim '(#\space) (subseq line this next))
158           when (not (i= (length piece) 0))
159             collect piece
160           until (i>= next end))))
161
162
163 ;;; Managing symbols
164
165 (defmacro with-gensyms ((&rest bindings) &body body)
166   `(let ,(mapcar #'(lambda (b) `(,b (gensym ,(string b)))) bindings)
167      ,@body))
168
169 (defun make-lisp-symbol (string)
170   "Intern a string of the 'package:string' and return the symbol."
171   (let* ((string (string string))
172          (colon  (position #\: string))
173          (pkg    (if colon (subseq string 0 colon) "KEYWORD"))
174          (sym    (if colon (subseq string (+ colon 1)) string)))
175     (intern sym pkg)))
176
177 (defun fintern (format-string &rest format-args)
178   "Interns a new symbol in the current package."
179   (declare (dynamic-extent format-args))
180   (intern (nstring-upcase (apply #'format nil format-string format-args))))
181
182 (defun kintern (format-string &rest format-args)
183   "Interns a new symbol in the keyword package."
184   (declare (dynamic-extent format-args))
185   (intern (nstring-upcase (apply #'format nil format-string format-args)) "KEYWORD"))
186
187 (defun keywordify (x)
188   "Given a symbol designator 'x', return a keyword whose name is 'x'.
189    If 'x' is nil, this returns nil."
190   (check-type x (or string symbol null))
191   (cond ((null x) nil)
192         ((keywordp x) x)
193         ((symbolp x) (keywordify (symbol-name x)))
194         ((zerop (length x)) nil)
195         ((string-not-equal x "nil")
196          (intern (string-upcase x) (find-package "KEYWORD")))
197         (t nil)))
198
199
200 ;;; Collectors, etc
201
202 (defmacro with-collectors ((&rest collection-descriptions) &body body)
203   "'collection-descriptions' is a list of clauses of the form (coll function).
204    The body can call each 'function' to add a value to 'coll'. 'function'
205    runs in constant time, regardless of the length of the list."
206   (let ((let-bindings  ())
207         (flet-bindings ())
208         (dynamic-extents ())
209         (vobj '#:OBJECT))
210     (dolist (description collection-descriptions)
211       (destructuring-bind (place name) description
212         (let ((vtail (make-symbol (format nil "~A-TAIL" place))))
213           (setq dynamic-extents
214                 (nconc dynamic-extents `(#',name)))
215           (setq let-bindings
216                 (nconc let-bindings
217                        `((,place ())
218                          (,vtail nil))))
219           (setq flet-bindings
220                 (nconc flet-bindings
221                        `((,name (,vobj)
222                            (setq ,vtail (if ,vtail
223                                           (setf (cdr ,vtail)  (list ,vobj))
224                                           (setf ,place (list ,vobj)))))))))))
225     `(let (,@let-bindings)
226        (flet (,@flet-bindings)
227          ,@(and dynamic-extents
228                 `((declare (dynamic-extent ,@dynamic-extents))))
229          ,@body))))
230
231 (defmacro with-prefixed-accessors (names (prefix object) &body body)
232   `(with-accessors (,@(loop for name in names
233                             collect `(,name ,(fintern "~A~A" prefix name))))
234        ,object
235      ,@body))
236
237 (defmacro dovector ((var vector &optional value) &body body)
238   "Like 'dolist', but iterates over the vector 'vector'."
239   (with-gensyms (vidx vlen vvec)
240     `(let* ((,vvec ,vector)
241             (,vlen (length ,vvec)))
242        (loop for ,vidx fixnum from 0 below ,vlen
243              as ,var = (aref ,vvec ,vidx)
244              do (progn ,@body)
245              finally (return ,value)))))
246
247 (defmacro doseq ((var sequence &optional value) &body body)
248   "Iterates over a sequence, using 'dolist' or 'dovector' depending on
249    the type of the sequence. In optimized code, this turns out to be
250    faster than (map () #'f sequence).
251    Note that the body gets expanded twice!"
252   (with-gensyms (vseq)
253     `(let ((,vseq ,sequence))
254        (if (vectorp ,vseq)
255          (dovector (,var ,vseq ,value)
256            ,@body)
257          (dolist (,var ,vseq ,value)
258            ,@body)))))
259
260
261 (defmacro appendf (place tail)
262   "Append 'tail' to the list given by 'place', then set the place to the new list."
263   `(setf ,place (append ,place ,tail)))
264
265
266 ;;; Functional programming, please
267
268 (defun curry (function &rest args)
269   "Returns a function that applies 'function' to 'args', plus any
270    additional arguments given at the call site."
271   (if (and args (null (cdr args)))                      ;fast test for length = 1
272     (let ((arg (car args)))
273       #'(lambda (&rest more-args)
274           (apply function arg more-args)))
275     #'(lambda (&rest more-args)
276         (apply function (append args more-args)))))
277
278 (define-compiler-macro curry (&whole form function &rest args &environment env)
279   (declare (ignore env))
280   (if (and (listp function)
281            (eq (first function) 'function)
282            (symbolp (second function))
283            (and args (null (cdr args))))
284     `#'(lambda (&rest more-args)
285          (apply ,function ,(car args) more-args))
286     form))
287
288
289 ;;; Types
290
291 ;; A parameterized list type for repeated fields
292 ;; The elements aren't type-checked
293 (deftype list-of (type)
294   (if (eq type 'nil)            ;a list that cannot have any element (element-type nil) is null
295     'null
296     'list))
297
298 ;; The same, but use a (stretchy) vector
299 (deftype vector-of (type)
300   (if (eq type 'nil)            ;an array that cannot have any element (element-type nil) is of size 0
301     '(array * (0))
302     '(array * (*))))            ;a 1-dimensional array of any type
303
304 ;; This corresponds to the :bytes Protobufs type
305 (deftype byte-vector () '(array (unsigned-byte 8) (*)))
306
307 (defun make-byte-vector (size)
308   (make-array size :element-type '(unsigned-byte 8)))
309
310 ;; The Protobufs integer types
311 (deftype    int32 () '(signed-byte 32))
312 (deftype    int64 () '(signed-byte 64))
313 (deftype   uint32 () '(unsigned-byte 32))
314 (deftype   uint64 () '(unsigned-byte 64))
315 (deftype   sint32 () '(signed-byte 32))
316 (deftype   sint64 () '(signed-byte 64))
317 (deftype  fixed32 () '(signed-byte 32))
318 (deftype  fixed64 () '(signed-byte 64))
319 (deftype sfixed32 () '(signed-byte 32))
320 (deftype sfixed64 () '(signed-byte 64))
321
322 ;; Type expansion
323 (defun type-expand (type)
324   #+allegro (excl:normalize-type type :default type)
325   #+ccl (ccl::type-expand type)
326   #+clisp (ext:type-expand type)
327   #+cmu (kernel:type-expand type)
328   #+(or ecl mkcl) (si::expand-deftype type)
329   #+lispworks (type:expand-user-type type)
330   #+sbcl (sb-ext:typexpand type)
331   #-(or allegro ccl clisp cmu ecl lispworks mkcl sbcl) type)
332
333
334 ;;; Code generation utilities
335
336 (defparameter *proto-name-separators* '(#\- #\_ #\/ #\space))
337 (defparameter *camel-case-field-names* nil)
338
339 (defun find-proto-package (name)
340   "A very fuzzy definition of 'find-package'."
341   (typecase name
342     ((or string symbol)
343      ;; Try looking under the given name and the all-uppercase name
344      (or (find-package (string name))
345          (find-package (string-upcase (string name)))))
346     (cons
347      ;; If 'name' is a list, it's actually a fully-qualified path
348      (or (find-proto-package (first name))
349          (find-proto-package (format nil "~{~A~^.~}" name))))))
350
351 ;; "class-name" -> "ClassName", ("ClassName")
352 ;; "outer-class.inner-class" -> "InnerClass", ("OuterClass" "InnerClass")
353 (defun class-name->proto (x)
354   "Given a Lisp class name, returns a Protobufs message or enum name.
355    The second value is the fully qualified name, as a list."
356   (let* ((xs (split-string (string x) :separators '(#\.)))
357          (ns (loop for x in (butlast xs)
358                    collect (remove-if-not #'alphanumericp
359                                           (camel-case (format nil "~A" x) *proto-name-separators*))))
360          (nx (car (last xs)))
361          (name (remove-if-not #'alphanumericp (camel-case nx *proto-name-separators*))))
362     (values name (append ns (list name))
363             ;; This might be the name of a package, too
364             (format nil "~{~A~^.~}" (butlast xs)))))
365
366 ;; "enum-value" -> "ENUM_VALUE", ("ENUM_VALUE")
367 ;; "class-name.enum-value" -> "ENUM_VALUE", ("ClassName" "ENUM_VALUE")
368 (defun enum-name->proto (x &optional prefix)
369   "Given a Lisp enum value name, returns a Protobufs enum value name.
370    The second value is the fully qualified name, as a list."
371   (let* ((xs (split-string (string x) :separators '(#\.)))
372          (ns (loop for x in (butlast xs)
373                    collect (remove-if-not #'alphanumericp
374                                           (camel-case (format nil "~A" x) *proto-name-separators*))))
375          (nx (string-upcase (car (last xs))))
376          (nx (if (and prefix (starts-with nx prefix)) (subseq nx (length prefix)) nx))
377          ;; Keep underscores, they are standards separators in Protobufs enum names
378          (name (remove-if-not #'(lambda (x) (or (alphanumericp x) (eql x #\_)))
379                               (format nil "~{~A~^_~}"
380                                       (split-string nx :separators *proto-name-separators*)))))
381     (values name (append ns (list name))
382             (format nil "~{~A~^.~}" (butlast xs)))))
383
384 ;; "slot-name" -> "slot_name", ("slot_name") or "slotName", ("slotName")
385 ;; "class-name.slot-name" -> "Class.slot_name", ("ClassName" "slot_name")
386 (defun slot-name->proto (x)
387   "Given a Lisp slot name, returns a Protobufs field name.
388    The second value is the fully qualified name, as a list."
389   (let* ((xs (split-string (string x) :separators '(#\.)))
390          (ns (loop for x in (butlast xs)
391                    collect (remove-if-not #'alphanumericp
392                                           (camel-case (format nil "~A" x) *proto-name-separators*))))
393          (nx (string-downcase (car (last xs))))
394          (name (if *camel-case-field-names*
395                  (remove-if-not #'alphanumericp
396                                 (camel-case-but-one (format nil "~A" nx) *proto-name-separators*))
397                  ;; Keep underscores, they are standards separators in Protobufs field names
398                  (remove-if-not #'(lambda (x) (or (alphanumericp x) (eql x #\_)))
399                                 (format nil "~{~A~^_~}"
400                                         (split-string nx :separators *proto-name-separators*))))))
401     (values name (append ns (list name))
402             (format nil "~{~A~^.~}" (butlast xs)))))
403
404
405 ;; "ClassName" -> 'class-name
406 ;; "cl-user.ClassName" -> 'cl-user::class-name
407 ;; "cl-user.OuterClass.InnerClass" -> 'cl-user::outer-class.inner-class
408 (defun proto->class-name (x &optional package)
409   "Given a Protobufs message or enum type name, returns a Lisp class or type name.
410    This resolves Protobufs qualified names as best as it can."
411   (let* ((xs (split-string (substitute #\- #\_ (uncamel-case x))
412                            :separators '(#\.)))
413          (pkg1 (and (cdr xs) (find-proto-package (first xs))))
414          (pkgn (and (cdr xs) (find-proto-package (butlast xs))))
415          (package (or pkg1 pkgn package))
416          (name (format nil "~{~A~^.~}" (if pkg1 (cdr xs) (if pkgn (last xs) xs)))))
417     (values (if package (intern name package) (make-symbol name)) package xs
418             ;; This might be the name of a package, too
419             (format nil "~{~A~^.~}" (butlast xs)))))
420
421 ;; "ENUM_VALUE" -> :enum-value
422 ;; "cl-user.ENUM_VALUE" -> :enum-value
423 ;; "cl-user.OuterClass.ENUM_VALUE" -> :enum-value
424 (defun proto->enum-name (x &optional package)
425   "Given a Protobufs enum value name, returns a Lisp enum value name.
426    This resolves Protobufs qualified names as best as it can."
427   (let* ((xs (split-string (substitute #\- #\_ (uncamel-case x))
428                            :separators '(#\.)))
429          (pkg1 (and (cdr xs) (find-proto-package (first xs))))
430          (pkgn (and (cdr xs) (find-proto-package (butlast xs))))
431          (package (or pkg1 pkgn package))
432          (name (format nil "~{~A~^.~}" (if pkg1 (cdr xs) (if pkgn (last xs) xs)))))
433     (values (kintern name) package xs
434             (format nil "~{~A~^.~}" (butlast xs)))))
435
436 ;; "slot_name" or "slotName" -> 'slot-name
437 ;; "cl-user.slot_name" or "cl-user.slotName" -> 'cl-user::slot-name
438 ;; "cl-user.OuterClass.slot_name" -> 'cl-user::outer-class.slot-name
439 (defun proto->slot-name (x &optional package)
440   "Given a Protobufs field value name, returns a Lisp slot name.
441    This resolves Protobufs qualified names as best as it can."
442   (let* ((xs (split-string (substitute #\- #\_ (uncamel-case x))
443                            :separators '(#\.)))
444          (pkg1 (and (cdr xs) (find-proto-package (first xs))))
445          (pkgn (and (cdr xs) (find-proto-package (butlast xs))))
446          (package (or pkg1 pkgn package))
447          (name (format nil "~{~A~^.~}" (if pkg1 (cdr xs) (if pkgn (last xs) xs)))))
448     (values (if package (intern name package) (make-symbol name)) package xs
449             (format nil "~{~A~^.~}" (butlast xs)))))
450
451
452 ;;; Warnings
453
454 (define-condition protobufs-warning (warning simple-condition) ())
455
456 (defun protobufs-warn (format-control &rest format-arguments)
457   (warn 'protobufs-warning
458         :format-control format-control
459         :format-arguments format-arguments))
460
461
462 #-(or allegro lispworks)
463 (defmacro without-redefinition-warnings (() &body body)
464   `(progn ,@body))
465     
466 #+allegro
467 (defmacro without-redefinition-warnings (() &body body)
468   `(excl:without-redefinition-warnings ,@body))
469
470 #+lispworks
471 (defmacro without-redefinition-warnings (() &body body)
472   `(let ((dspec:*redefinition-action* :quiet)) ,@body))
473
474 \f
475 ;;; Portable floating point utilities
476
477 #+(or abcl allegro ccl cmu sbcl lispworks)
478 (defun single-float-bits (x)
479   (declare (type single-float x))
480   #+abcl    (system:single-float-bits x)
481   #+allegro (multiple-value-bind (high low)
482                 (excl:single-float-to-shorts x)
483               (declare (type (unsigned-byte 16) high low))
484               (logior (ash high 16) low))
485   #+ccl (ccl::single-float-bits x)
486   #+cmu  (kernel:single-float-bits x)
487   #+sbcl (sb-kernel:single-float-bits x)
488   #+lispworks (lispworks-float:single-float-bits x))
489
490 #-(or abcl allegro ccl cmu sbcl lispworks)
491 (defun single-float-bits (x)
492   (declare (type single-float x))
493   (assert (= (float-radix x) 2))
494   (if (zerop x)
495     (if (eql x 0.0f0) 0 #x-80000000)
496     (multiple-value-bind (lisp-significand lisp-exponent lisp-sign)
497         (integer-decode-float x)
498       (assert (plusp lisp-significand))
499       (let* ((significand lisp-significand)
500              (exponent (+ lisp-exponent 23 127))
501              (unsigned-result
502               (if (plusp exponent)                      ;if not obviously denormalized
503                 (do () (nil)
504                   (cond
505                     ;; Special termination case for denormalized float number
506                     ((zerop exponent)
507                      ;; Denormalized numbers have exponent one greater than
508                      ;; in the exponent field
509                      (return (ash significand -1)))
510                     ;; Ordinary termination case
511                     ((>= significand (expt 2 23))
512                      (assert (< 0 significand (expt 2 24)))
513                      ;; Exponent 0 is reserved for denormalized numbers,
514                      ;; and 255 is reserved for specials like NaN
515                      (assert (< 0 exponent 255))
516                      (return (logior (ash exponent 23)
517                                      (logand significand (1- (ash 1 23))))))
518                     (t
519                      ;; Shift as necessary to set bit 24 of significand
520                      (setq significand (ash significand 1)
521                            exponent (1- exponent)))))
522                 (do () ((zerop exponent)
523                         ;; Denormalized numbers have exponent one greater than
524                         ;; the exponent field
525                         (ash significand -1))
526                   (unless (zerop (logand significand 1))
527                     (warn "Denormalized '~S' losing bits in ~D" 'single-float-bits x))
528                   (setq significand (ash significand -1)
529                         exponent (1+ exponent))))))
530         (ecase lisp-sign
531           ((1)  unsigned-result)
532           ((-1) (logior unsigned-result (- (expt 2 31)))))))))
533
534
535 #+(or abcl allegro ccl cmu sbcl lispworks)
536 (defun double-float-bits (x)
537   (declare (type double-float x))
538   #+abcl    (values (system:double-float-low-bits x)
539                     (system:double-float-high-bits x))
540   #+allegro (multiple-value-bind (us3 us2 us1 us0)
541                 (excl:double-float-to-shorts x)
542               (logior (ash us1 16) us0)
543               (logior (ash us3 16) us2))
544   #+ccl  (multiple-value-bind (high low)
545              (ccl::double-float-bits x)
546            (values low high))
547   #+cmu  (values (kernel:double-float-low-bits x)
548                  (kernel:double-float-high-bits x))
549   #+sbcl (values (sb-kernel:double-float-low-bits x)
550                  (sb-kernel:double-float-high-bits x))
551   #+lispworks (let ((bits (lispworks-float:double-float-bits x)))
552                 (values (logand #xffffffff bits)
553                         (ash bits -32))))
554
555 #-(or abcl allegro ccl cmu sbcl lispworks)
556 (defun double-float-bits (x)
557   (declare (type double-float x))
558   (assert (= (float-radix x) 2))
559   (if (zerop x)
560     (if (eql x 0.0d0) 0 #x-8000000000000000)
561     (multiple-value-bind (lisp-significand lisp-exponent lisp-sign)
562         (integer-decode-float x)
563       (assert (plusp lisp-significand))
564       (let* ((significand lisp-significand)
565              (exponent (+ lisp-exponent 52 1023))
566              (unsigned-result
567               (if (plusp exponent)                      ;if not obviously denormalized
568                 (do () (nil)
569                   (cond
570                     ;; Special termination case for denormalized float number
571                     ((zerop exponent)
572                      ;; Denormalized numbers have exponent one greater than
573                      ;; in the exponent field
574                      (return (ash significand -1)))
575                     ;; Ordinary termination case
576                     ((>= significand (expt 2 52))
577                      (assert (< 0 significand (expt 2 53)))
578                      ;; Exponent 0 is reserved for denormalized numbers,
579                      ;; and 2047 is reserved for specials like NaN
580                      (assert (< 0 exponent 2047))
581                      (return (logior (ash exponent 52)
582                                      (logand significand (1- (ash 1 52))))))
583                     (t
584                      ;; Shift as necessary to set bit 53 of significand
585                      (setq significand (ash significand 1)
586                            exponent (1- exponent)))))
587                 (do () ((zerop exponent)
588                         ;; Denormalized numbers have exponent one greater than
589                         ;; the exponent field
590                         (ash significand -1))
591                   (unless (zerop (logand significand 1))
592                     (warn "Denormalized '~S' losing bits in ~D" 'double-float-bits x))
593                   (setq significand (ash significand -1)
594                         exponent (1+ exponent))))))
595         (let ((result
596                (ecase lisp-sign
597                  ((1)  unsigned-result)
598                  ((-1) (logior unsigned-result (- (expt 2 63)))))))
599           ;; Return the low bits and the high bits
600           (values (logand #xffffffff result) (ash result -32)))))))
601
602
603 #+(or abcl allegro ccl cmu sbcl lispworks)
604 (defun make-single-float (bits)
605   (declare (type (signed-byte 32) bits))
606   #+abcl    (system:make-single-float bits)
607   #+allegro (excl:shorts-to-single-float (ldb (byte 16 16) bits)
608                                          (ldb (byte 16 0) bits))
609   #+ccl  (ccl::host-single-float-from-unsigned-byte-32 bits)
610   #+cmu  (kernel:make-single-float bits)
611   #+sbcl (sb-kernel:make-single-float bits)
612   #+lispworks (lispworks-float:make-single-float bits))
613
614 #-(or abcl allegro ccl cmu sbcl lispworks)
615 (defun make-single-float (bits)
616   (declare (type (signed-byte 32) bits))
617   (cond
618     ;; IEEE float special cases
619     ((zerop bits) 0.0)
620     ((= bits #x-80000000) -0.0)
621     (t
622      (let* ((sign (ecase (ldb (byte 1 31) bits)
623                     (0 1.0)
624                     (1 -1.0)))
625             (iexpt (ldb (byte 8 23) bits))
626             (exponent (if (zerop iexpt)                 ;denormalized
627                         -126
628                         (- iexpt 127)))
629             (mantissa (* (logior (ldb (byte 23 0) bits)
630                                  (if (zerop iexpt) 0 (ash 1 23)))
631                          (expt 0.5 23))))
632        (* sign (expt 2.0 exponent) mantissa)))))
633
634
635 #+(or abcl allegro ccl cmu sbcl lispworks)
636 (defun make-double-float (low high)
637   (declare (type (unsigned-byte 32) low)
638            (type (signed-byte   32) high))
639   #+abcl (system:make-double-float (logior (ash high 32) low))
640   #+allegro (excl:shorts-to-double-float (ldb (byte 16 16) high)
641                                          (ldb (byte 16 0) high)
642                                          (ldb (byte 16 16) low)
643                                          (ldb (byte 16 0) low))
644   #+ccl  (ccl::double-float-from-bits (logand high #xffffffff) low)
645   #+cmu  (kernel:make-double-float high low)
646   #+sbcl (sb-kernel:make-double-float high low)
647   #+lispworks (lispworks-float:make-double-float high low))
648
649 #-(or abcl allegro ccl cmu sbcl lispworks)
650 (defun make-double-float (low high)
651   (declare (type (unsigned-byte 32) low)
652            (type (signed-byte   32) high))
653   (cond
654     ;; IEEE float special cases
655     ((and (zerop high) (zerop low)) 0.0d0)
656     ((and (= high #x-80000000)
657           (zerop low)) -0.0d0)
658     (t
659      (let* ((bits (logior (ash high 32) low))
660             (sign (ecase (ldb (byte 1 63) bits)
661                     (0 1.0d0)
662                     (1 -1.0d0)))
663             (iexpt (ldb (byte 11 52) bits))
664             (exponent (if (zerop iexpt)                 ;denormalized
665                         -1022
666                         (- iexpt 1023)))
667             (mantissa (* (logior (ldb (byte 52 0) bits)
668                                  (if (zerop iexpt) 0 (ash 1 52)))
669                          (expt 0.5d0 52))))
670        (* sign (expt 2.0d0 exponent) mantissa)))))