]> asedeno.scripts.mit.edu Git - cl-protobufs.git/blob - utilities.lisp
A few whitespace changes
[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 ;;; Functional programming, please
262
263 (defun curry (function &rest args)
264   "Returns a function that applies 'function' to 'args', plus any
265    additional arguments given at the call site."
266   (if (and args (null (cdr args)))                      ;fast test for length = 1
267     (let ((arg (car args)))
268       #'(lambda (&rest more-args)
269           (apply function arg more-args)))
270     #'(lambda (&rest more-args)
271         (apply function (append args more-args)))))
272
273 (define-compiler-macro curry (&whole form function &rest args &environment env)
274   (declare (ignore env))
275   (if (and (listp function)
276            (eq (first function) 'function)
277            (symbolp (second function))
278            (and args (null (cdr args))))
279     `#'(lambda (&rest more-args)
280          (apply ,function ,(car args) more-args))
281     form))
282
283
284 ;;; Types
285
286 ;; A parameterized list type for repeated fields
287 ;; The elements aren't type-checked
288 (deftype list-of (type)
289   (if (eq type 'nil)            ;a list that cannot have any element (element-type nil) is null
290     'null
291     'list))
292
293 ;; The same, but use a (stretchy) vector
294 (deftype vector-of (type)
295   (if (eq type 'nil)            ;an array that cannot have any element (element-type nil) is of size 0
296     '(array * (0))
297     '(array * (*))))            ;a 1-dimensional array of any type
298
299 ;; This corresponds to the :bytes Protobufs type
300 (deftype byte-vector () '(array (unsigned-byte 8) (*)))
301
302 (defun make-byte-vector (size)
303   (make-array size :element-type '(unsigned-byte 8)))
304
305 ;; The Protobufs integer types
306 (deftype    int32 () '(signed-byte 32))
307 (deftype    int64 () '(signed-byte 64))
308 (deftype   uint32 () '(unsigned-byte 32))
309 (deftype   uint64 () '(unsigned-byte 64))
310 (deftype   sint32 () '(signed-byte 32))
311 (deftype   sint64 () '(signed-byte 64))
312 (deftype  fixed32 () '(signed-byte 32))
313 (deftype  fixed64 () '(signed-byte 64))
314 (deftype sfixed32 () '(signed-byte 32))
315 (deftype sfixed64 () '(signed-byte 64))
316
317 ;; Type expansion
318 (defun type-expand (type)
319   #+allegro (excl:normalize-type type :default type)
320   #+ccl (ccl::type-expand type)
321   #+clisp (ext:type-expand type)
322   #+cmu (kernel:type-expand type)
323   #+lispworks (type:expand-user-type type)
324   #+sbcl (sb-ext:typexpand type)
325   #-(or allegro ccl clisp cmu lispworks sbcl) type)
326
327
328 ;;; Code generation utilities
329
330 (defvar *proto-name-separators* '(#\- #\_ #\/ #\space))
331 (defvar *camel-case-field-names* nil)
332
333 (defun find-proto-package (name)
334   "A very fuzzy definition of 'find-package'."
335   (typecase name
336     ((or string symbol)
337      ;; Try looking under the given name and the all-uppercase name
338      (or (find-package (string name))
339          (find-package (string-upcase (string name)))))
340     (cons
341      ;; If 'name' is a list, it's actually a fully-qualified path
342      (or (find-proto-package (first name))
343          (find-proto-package (format nil "~{~A~^.~}" name))))))
344
345 ;; "class-name" -> "ClassName", ("ClassName")
346 ;; "outer-class.inner-class" -> "InnerClass", ("OuterClass" "InnerClass")
347 (defun class-name->proto (x)
348   "Given a Lisp class name, returns a Protobufs message or enum name.
349    The second value is the fully qualified name, as a list."
350   (let* ((xs (split-string (string x) :separators '(#\.)))
351          (ns (loop for x in (butlast xs)
352                    collect (remove-if-not #'alphanumericp
353                                           (camel-case (format nil "~A" x) *proto-name-separators*))))
354          (nx (car (last xs)))
355          (name (remove-if-not #'alphanumericp (camel-case nx *proto-name-separators*))))
356     (values name (append ns (list name))
357             ;; This might be the name of a package, too
358             (format nil "~{~A~^.~}" (butlast xs)))))
359
360 ;; "enum-value" -> "ENUM_VALUE", ("ENUM_VALUE")
361 ;; "class-name.enum-value" -> "ENUM_VALUE", ("ClassName" "ENUM_VALUE")
362 (defun enum-name->proto (x &optional prefix)
363   "Given a Lisp enum value name, returns a Protobufs enum value name.
364    The second value is the fully qualified name, as a list."
365   (let* ((xs (split-string (string x) :separators '(#\.)))
366          (ns (loop for x in (butlast xs)
367                    collect (remove-if-not #'alphanumericp
368                                           (camel-case (format nil "~A" x) *proto-name-separators*))))
369          (nx (string-upcase (car (last xs))))
370          (nx (if (and prefix (starts-with nx prefix)) (subseq nx (length prefix)) nx))
371          ;; Keep underscores, they are standards separators in Protobufs enum names
372          (name (remove-if-not #'(lambda (x) (or (alphanumericp x) (eql x #\_)))
373                               (format nil "~{~A~^_~}"
374                                       (split-string nx :separators *proto-name-separators*)))))
375     (values name (append ns (list name))
376             (format nil "~{~A~^.~}" (butlast xs)))))
377
378 ;; "slot-name" -> "slot_name", ("slot_name") or "slotName", ("slotName")
379 ;; "class-name.slot-name" -> "Class.slot_name", ("ClassName" "slot_name")
380 (defun slot-name->proto (x)
381   "Given a Lisp slot name, returns a Protobufs field name.
382    The second value is the fully qualified name, as a list."
383   (let* ((xs (split-string (string x) :separators '(#\.)))
384          (ns (loop for x in (butlast xs)
385                    collect (remove-if-not #'alphanumericp
386                                           (camel-case (format nil "~A" x) *proto-name-separators*))))
387          (nx (string-downcase (car (last xs))))
388          (name (if *camel-case-field-names*
389                  (remove-if-not #'alphanumericp
390                                 (camel-case-but-one (format nil "~A" nx) *proto-name-separators*))
391                  ;; Keep underscores, they are standards separators in Protobufs field names
392                  (remove-if-not #'(lambda (x) (or (alphanumericp x) (eql x #\_)))
393                                 (format nil "~{~A~^_~}"
394                                         (split-string nx :separators *proto-name-separators*))))))
395     (values name (append ns (list name))
396             (format nil "~{~A~^.~}" (butlast xs)))))
397
398
399 ;; "ClassName" -> 'class-name
400 ;; "cl-user.ClassName" -> 'cl-user::class-name
401 ;; "cl-user.OuterClass.InnerClass" -> 'cl-user::outer-class.inner-class
402 (defun proto->class-name (x &optional package)
403   "Given a Protobufs message or enum type name, returns a Lisp class or type name.
404    This resolves Protobufs qualified names as best as it can."
405   (let* ((xs (split-string (substitute #\- #\_ (uncamel-case x))
406                            :separators '(#\.)))
407          (pkg1 (and (cdr xs) (find-proto-package (first xs))))
408          (pkgn (and (cdr xs) (find-proto-package (butlast xs))))
409          (package (or pkg1 pkgn package))
410          (name (format nil "~{~A~^.~}" (if pkg1 (cdr xs) (if pkgn (last xs) xs)))))
411     (values (if package (intern name package) (make-symbol name)) package xs
412             ;; This might be the name of a package, too
413             (format nil "~{~A~^.~}" (butlast xs)))))
414
415 ;; "ENUM_VALUE" -> :enum-value
416 ;; "cl-user.ENUM_VALUE" -> :enum-value
417 ;; "cl-user.OuterClass.ENUM_VALUE" -> :enum-value
418 (defun proto->enum-name (x &optional package)
419   "Given a Protobufs enum value name, returns a Lisp enum value name.
420    This resolves Protobufs qualified names as best as it can."
421   (let* ((xs (split-string (substitute #\- #\_ (uncamel-case x))
422                            :separators '(#\.)))
423          (pkg1 (and (cdr xs) (find-proto-package (first xs))))
424          (pkgn (and (cdr xs) (find-proto-package (butlast xs))))
425          (package (or pkg1 pkgn package))
426          (name (format nil "~{~A~^.~}" (if pkg1 (cdr xs) (if pkgn (last xs) xs)))))
427     (values (kintern name) package xs
428             (format nil "~{~A~^.~}" (butlast xs)))))
429
430 ;; "slot_name" or "slotName" -> 'slot-name
431 ;; "cl-user.slot_name" or "cl-user.slotName" -> 'cl-user::slot-name
432 ;; "cl-user.OuterClass.slot_name" -> 'cl-user::outer-class.slot-name
433 (defun proto->slot-name (x &optional package)
434   "Given a Protobufs field value name, returns a Lisp slot name.
435    This resolves Protobufs qualified names as best as it can."
436   (let* ((xs (split-string (substitute #\- #\_ (uncamel-case x))
437                            :separators '(#\.)))
438          (pkg1 (and (cdr xs) (find-proto-package (first xs))))
439          (pkgn (and (cdr xs) (find-proto-package (butlast xs))))
440          (package (or pkg1 pkgn package))
441          (name (format nil "~{~A~^.~}" (if pkg1 (cdr xs) (if pkgn (last xs) xs)))))
442     (values (if package (intern name package) (make-symbol name)) package xs
443             (format nil "~{~A~^.~}" (butlast xs)))))
444
445
446 ;;; Warnings
447
448 (define-condition protobufs-warning (warning simple-condition) ())
449
450 (defun protobufs-warn (format-control &rest format-arguments)
451   (warn 'protobufs-warning
452         :format-control format-control
453         :format-arguments format-arguments))
454
455
456 #-(or allegro lispworks)
457 (defmacro without-redefinition-warnings (() &body body)
458   `(progn ,@body))
459     
460 #+allegro
461 (defmacro without-redefinition-warnings (() &body body)
462   `(excl:without-redefinition-warnings ,@body))
463
464 #+lispworks
465 (defmacro without-redefinition-warnings (() &body body)
466   `(let ((dspec:*redefinition-action* :quiet)) ,@body))
467
468 \f
469 ;;; Portable floating point utilities
470
471 #+(or abcl allegro ccl cmu sbcl lispworks)
472 (defun single-float-bits (x)
473   (declare (type single-float x))
474   #+abcl    (system:single-float-bits x)
475   #+allegro (multiple-value-bind (high low)
476                 (excl:single-float-to-shorts x)
477               (declare (type (unsigned-byte 16) high low))
478               (logior (ash high 16) low))
479   #+ccl (ccl::single-float-bits x)
480   #+cmu  (kernel:single-float-bits x)
481   #+sbcl (sb-kernel:single-float-bits x)
482   #+lispworks (lispworks-float:single-float-bits x))
483
484 #-(or abcl allegro ccl cmu sbcl lispworks)
485 (defun single-float-bits (x)
486   (declare (type single-float x))
487   (assert (= (float-radix x) 2))
488   (if (zerop x)
489     (if (eql x 0.0f0) 0 #x-80000000)
490     (multiple-value-bind (lisp-significand lisp-exponent lisp-sign)
491         (integer-decode-float x)
492       (assert (plusp lisp-significand))
493       (let* ((significand lisp-significand)
494              (exponent (+ lisp-exponent 23 127))
495              (unsigned-result
496               (if (plusp exponent)                      ;if not obviously denormalized
497                 (do () (nil)
498                   (cond
499                     ;; Special termination case for denormalized float number
500                     ((zerop exponent)
501                      ;; Denormalized numbers have exponent one greater than
502                      ;; in the exponent field
503                      (return (ash significand -1)))
504                     ;; Ordinary termination case
505                     ((>= significand (expt 2 23))
506                      (assert (< 0 significand (expt 2 24)))
507                      ;; Exponent 0 is reserved for denormalized numbers,
508                      ;; and 255 is reserved for specials like NaN
509                      (assert (< 0 exponent 255))
510                      (return (logior (ash exponent 23)
511                                      (logand significand (1- (ash 1 23))))))
512                     (t
513                      ;; Shift as necessary to set bit 24 of significand
514                      (setq significand (ash significand 1)
515                            exponent (1- exponent)))))
516                 (do () ((zerop exponent)
517                         ;; Denormalized numbers have exponent one greater than
518                         ;; the exponent field
519                         (ash significand -1))
520                   (unless (zerop (logand significand 1))
521                     (warn "Denormalized '~S' losing bits in ~D" 'single-float-bits x))
522                   (setq significand (ash significand -1)
523                         exponent (1+ exponent))))))
524         (ecase lisp-sign
525           ((1)  unsigned-result)
526           ((-1) (logior unsigned-result (- (expt 2 31)))))))))
527
528
529 #+(or abcl allegro ccl cmu sbcl lispworks)
530 (defun double-float-bits (x)
531   (declare (type double-float x))
532   #+abcl    (values (system:double-float-low-bits x)
533                     (system:double-float-high-bits x))
534   #+allegro (multiple-value-bind (us3 us2 us1 us0)
535                 (excl:double-float-to-shorts x)
536               (logior (ash us1 16) us0)
537               (logior (ash us3 16) us2))
538   #+ccl  (multiple-value-bind (high low)
539              (ccl::double-float-bits x)
540            (values low high))
541   #+cmu  (values (kernel:double-float-low-bits x)
542                  (kernel:double-float-high-bits x))
543   #+sbcl (values (sb-kernel:double-float-low-bits x)
544                  (sb-kernel:double-float-high-bits x))
545   #+lispworks (let ((bits (lispworks-float:double-float-bits x)))
546                 (values (logand #xffffffff bits)
547                         (ash bits -32))))
548
549 #-(or abcl allegro ccl cmu sbcl lispworks)
550 (defun double-float-bits (x)
551   (declare (type double-float x))
552   (assert (= (float-radix x) 2))
553   (if (zerop x)
554     (if (eql x 0.0d0) 0 #x-8000000000000000)
555     (multiple-value-bind (lisp-significand lisp-exponent lisp-sign)
556         (integer-decode-float x)
557       (assert (plusp lisp-significand))
558       (let* ((significand lisp-significand)
559              (exponent (+ lisp-exponent 52 1023))
560              (unsigned-result
561               (if (plusp exponent)                      ;if not obviously denormalized
562                 (do () (nil)
563                   (cond
564                     ;; Special termination case for denormalized float number
565                     ((zerop exponent)
566                      ;; Denormalized numbers have exponent one greater than
567                      ;; in the exponent field
568                      (return (ash significand -1)))
569                     ;; Ordinary termination case
570                     ((>= significand (expt 2 52))
571                      (assert (< 0 significand (expt 2 53)))
572                      ;; Exponent 0 is reserved for denormalized numbers,
573                      ;; and 2047 is reserved for specials like NaN
574                      (assert (< 0 exponent 2047))
575                      (return (logior (ash exponent 52)
576                                      (logand significand (1- (ash 1 52))))))
577                     (t
578                      ;; Shift as necessary to set bit 53 of significand
579                      (setq significand (ash significand 1)
580                            exponent (1- exponent)))))
581                 (do () ((zerop exponent)
582                         ;; Denormalized numbers have exponent one greater than
583                         ;; the exponent field
584                         (ash significand -1))
585                   (unless (zerop (logand significand 1))
586                     (warn "Denormalized '~S' losing bits in ~D" 'double-float-bits x))
587                   (setq significand (ash significand -1)
588                         exponent (1+ exponent))))))
589         (let ((result
590                (ecase lisp-sign
591                  ((1)  unsigned-result)
592                  ((-1) (logior unsigned-result (- (expt 2 63)))))))
593           ;; Return the low bits and the high bits
594           (values (logand #xffffffff result) (ash result -32)))))))
595
596
597 #+(or abcl allegro ccl cmu sbcl lispworks)
598 (defun make-single-float (bits)
599   (declare (type (signed-byte 32) bits))
600   #+abcl    (system:make-single-float bits)
601   #+allegro (excl:shorts-to-single-float (ldb (byte 16 16) bits)
602                                          (ldb (byte 16 0) bits))
603   #+ccl  (ccl::host-single-float-from-unsigned-byte-32 bits)
604   #+cmu  (kernel:make-single-float bits)
605   #+sbcl (sb-kernel:make-single-float bits)
606   #+lispworks (lispworks-float:make-single-float bits))
607
608 #-(or abcl allegro ccl cmu sbcl lispworks)
609 (defun make-single-float (bits)
610   (declare (type (signed-byte 32) bits))
611   (cond
612     ;; IEEE float special cases
613     ((zerop bits) 0.0)
614     ((= bits #x-80000000) -0.0)
615     (t
616      (let* ((sign (ecase (ldb (byte 1 31) bits)
617                     (0 1.0)
618                     (1 -1.0)))
619             (iexpt (ldb (byte 8 23) bits))
620             (exponent (if (zerop iexpt)                 ;denormalized
621                         -126
622                         (- iexpt 127)))
623             (mantissa (* (logior (ldb (byte 23 0) bits)
624                                  (if (zerop iexpt) 0 (ash 1 23)))
625                          (expt 0.5 23))))
626        (* sign (expt 2.0 exponent) mantissa)))))
627
628
629 #+(or abcl allegro ccl cmu sbcl lispworks)
630 (defun make-double-float (low high)
631   (declare (type (unsigned-byte 32) low)
632            (type (signed-byte   32) high))
633   #+abcl (system:make-double-float (logior (ash high 32) low))
634   #+allegro (excl:shorts-to-double-float (ldb (byte 16 16) high)
635                                          (ldb (byte 16 0) high)
636                                          (ldb (byte 16 16) low)
637                                          (ldb (byte 16 0) low))
638   #+ccl  (ccl::double-float-from-bits (logand high #xffffffff) low)
639   #+cmu  (kernel:make-double-float high low)
640   #+sbcl (sb-kernel:make-double-float high low)
641   #+lispworks (lispworks-float:make-double-float high low))
642
643 #-(or abcl allegro ccl cmu sbcl lispworks)
644 (defun make-double-float (low high)
645   (declare (type (unsigned-byte 32) low)
646            (type (signed-byte   32) high))
647   (cond
648     ;; IEEE float special cases
649     ((and (zerop high) (zerop low)) 0.0d0)
650     ((and (= high #x-80000000)
651           (zerop low)) -0.0d0)
652     (t
653      (let* ((bits (logior (ash high 32) low))
654             (sign (ecase (ldb (byte 1 63) bits)
655                     (0 1.0d0)
656                     (1 -1.0d0)))
657             (iexpt (ldb (byte 11 52) bits))
658             (exponent (if (zerop iexpt)                 ;denormalized
659                         -1022
660                         (- iexpt 1023)))
661             (mantissa (* (logior (ldb (byte 52 0) bits)
662                                  (if (zerop iexpt) 0 (ash 1 52)))
663                          (expt 0.5d0 52))))
664        (* sign (expt 2.0d0 exponent) mantissa)))))