Add :license to system file.
[zs3.git] / utils.lisp
blobce2cfc6b9c52c83e3f09b909c9e5928c6a0f36cd
1 ;;;;
2 ;;;; Copyright (c) 2008 Zachary Beane, All Rights Reserved
3 ;;;;
4 ;;;; Redistribution and use in source and binary forms, with or without
5 ;;;; modification, are permitted provided that the following conditions
6 ;;;; are met:
7 ;;;;
8 ;;;; * Redistributions of source code must retain the above copyright
9 ;;;; notice, this list of conditions and the following disclaimer.
10 ;;;;
11 ;;;; * Redistributions in binary form must reproduce the above
12 ;;;; copyright notice, this list of conditions and the following
13 ;;;; disclaimer in the documentation and/or other materials
14 ;;;; provided with the distribution.
15 ;;;;
16 ;;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
17 ;;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 ;;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 ;;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
20 ;;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 ;;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
22 ;;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 ;;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
24 ;;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
25 ;;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26 ;;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 ;;;;
28 ;;;; utils.lisp
30 (in-package #:zs3)
32 (defvar *months* #("Jan" "Feb" "Mar" "Apr" "May" "Jun"
33 "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"))
35 (defvar *days* #("Mon" "Tue" "Wed" "Thu" "Fri" "Sat" "Sun"))
37 (deftype octet ()
38 '(unsigned-byte 8))
40 (deftype octet-vector (&optional size)
41 `(simple-array octet (,size)))
43 (defun http-date-string (&optional (time (get-universal-time)))
44 "Return a HTTP-style date string."
45 (multiple-value-bind (second minute hour day month year day-of-week)
46 (decode-universal-time time 0)
47 (let ((*print-pretty* nil))
48 (format nil "~A, ~2,'0D ~A ~4,'0D ~2,'0D:~2,'0D:~2,'0D GMT"
49 (aref *days* day-of-week)
50 day
51 (aref *months* (1- month))
52 year
53 hour
54 minute
55 second))))
57 (defun iso8601-date-string (&optional (time (get-universal-time)))
58 "Return a HTTP-style date string."
59 (multiple-value-bind (second minute hour day month year)
60 (decode-universal-time time 0)
61 (let ((*print-pretty* nil))
62 (format nil "~4,'0D-~2,'0D-~2,'0DT~2,'0D:~2,'0D:~2,'0DZ"
63 year month day hour minute second))))
65 (defun string-octets (string)
66 "Return the UTF-8 encoding of STRING as a vector of octets."
67 (flexi-streams:string-to-octets string :external-format :utf-8))
69 (defun string64 (string)
70 (cl-base64:usb8-array-to-base64-string (string-octets string)))
72 (defun url-decode (string)
73 (with-output-to-string (out)
74 (let ((code 0))
75 (labels ((in-string (char)
76 (case char
77 (#\%
78 #'h1)
80 (write-char char out)
81 #'in-string)))
82 (weight (char)
83 (let ((weight (digit-char-p char 16)))
84 (unless weight
85 (error "~S is not a hex digit" char))
86 weight))
87 (h1 (char)
88 (setf code (ash (weight char) 4))
89 #'h2)
90 (h2 (char)
91 (incf code (weight char))
92 (write-char (code-char code) out)
93 #'in-string))
94 (let ((state #'in-string))
95 (loop for char across string
96 do (setf state (funcall state char))))))))
98 ;;; The following two functions were adatpted from Drakma source. The
99 ;;; only change is to escape space as "%20", not #\+
101 (defun url-encode (string)
102 "Returns a URL-encoded version of the string STRING using the
103 LispWorks external format EXTERNAL-FORMAT."
104 (let ((*print-pretty* nil))
105 (with-output-to-string (out)
106 (loop for octet across (string-octets (or string ""))
107 for char = (code-char octet)
108 do (cond ((or (char<= #\0 char #\9)
109 (char<= #\a char #\z)
110 (char<= #\A char #\Z)
111 (find char "$-_.!*'()," :test #'char=))
112 (write-char char out))
113 ((char= char #\Space)
114 (write-string "%20" out))
115 (t (format out "%~2,'0x" (char-code char))))))))
117 (defun alist-to-url-encoded-string (alist)
118 "ALIST is supposed to be an alist of name/value pairs where both
119 names and values are strings. This function returns a string where
120 this list is represented as for the content type
121 `application/x-www-form-urlencoded', i.e. the values are URL-encoded
122 using the external format EXTERNAL-FORMAT, the pairs are joined with a
123 #\\& character, and each name is separated from its value with a #\\=
124 character."
125 (let ((*print-pretty* nil))
126 (with-output-to-string (out)
127 (loop for first = t then nil
128 for (name . value) in alist
129 unless first do (write-char #\& out)
130 do (format out "~A=~A"
131 (url-encode name)
132 (url-encode value))))))
134 (defun save (response file)
135 "Write a sequence of octets RESPONSE to FILE."
136 (with-open-file (stream file :direction :output
137 :if-exists :supersede
138 :element-type 'octet)
139 (write-sequence response stream))
140 (probe-file file))
142 (defun parse-amazon-timestamp (string)
143 "Convert the ISO 8601-format STRING to a universal time."
144 (flet ((number-at (start length)
145 (parse-integer string :start start :end (+ start length))))
146 (let ((year (number-at 0 4))
147 (month (number-at 5 2))
148 (day (number-at 8 2))
149 (hour (number-at 11 2))
150 (minute (number-at 14 2))
151 (second (number-at 17 2)))
152 (encode-universal-time second minute hour day month year 0))))
154 (defun stringify (thing)
155 (typecase thing
156 (string thing)
157 (symbol (symbol-name thing))
158 (t (princ-to-string thing))))
160 (defun parameters-alist (&rest args &key &allow-other-keys)
161 "Construct an ALIST based on all keyword arguments passed to the
162 function. Keywords are converted to their lowercase symbol name and
163 values are converted to strings."
164 (loop for (key value) on args by #'cddr
165 when value
166 collect (cons (if (symbolp key)
167 (string-downcase (symbol-name key))
168 key)
169 (stringify value))))
171 (defun last-entry (array)
172 "If ARRAY has one ore more entries, return the last one. Otherwise,
173 return NIL."
174 (and (plusp (length array))
175 (aref array (1- (length array)))))
177 (defun file-size (file)
178 (with-open-file (stream file :element-type 'octet)
179 (file-length stream)))
181 (defvar +unix-time-difference+
182 (encode-universal-time 0 0 0 1 1 1970 0))
184 (defun unix-time (&optional (universal-time (get-universal-time)))
185 (- universal-time +unix-time-difference+))
187 (defun octet-vector (&rest octets)
188 (make-array (length octets) :element-type 'octet
189 :initial-contents octets))
191 (defun keywordify (string-designator)
192 (intern (string string-designator) :keyword))
194 (defun make-octet-vector (size)
195 (make-array size :element-type 'octet))
197 (defun now+ (delta)
198 (+ (get-universal-time) delta))
200 (defun now- (delta)
201 (- (get-universal-time) delta))
203 (defun copy-n-octets (count input output)
204 "Copy the first N octets from the stream INPUT to the stream OUTPUT."
205 (let ((buffer (make-octet-vector 4096)))
206 (multiple-value-bind (loops rest)
207 (truncate count 4096)
208 (dotimes (i loops)
209 (read-sequence buffer input)
210 (write-sequence buffer output))
211 (let ((trailing-count (read-sequence buffer input :end rest)))
212 (assert (= trailing-count rest))
213 (write-sequence buffer output :end rest)))))
215 (defun starts-with (prefix string)
216 (and (<= (length prefix) (length string))
217 (string= prefix string :end2 (length prefix))))
219 (defun ends-with (suffix string)
220 (and (<= (length suffix) (length string))
221 (string= suffix string :start2 (- (length string)
222 (length suffix)))))
224 ;;; Getting stream/file subset vectors
226 (defparameter *file-buffer-size* 8192)
228 (defun make-file-buffer ()
229 (make-octet-vector *file-buffer-size*))
231 (defun read-exactly-n-octets (stream n &optional buffer)
232 "Read exactly N octets from STREAM into BUFFER. If fewer than N
233 octets are read, signal an CL:END-OF-FILE error. If BUFFER is not
234 supplied or is NIL, create a fresh buffer of length N and return it."
235 (unless buffer
236 (setf buffer (make-octet-vector n)))
237 (let ((end (min (length buffer) n)))
238 (let ((count (read-sequence buffer stream :end end)))
239 (unless (= n count)
240 (error 'end-of-file :stream stream))
241 buffer)))
243 (defun read-complete-file-buffer (stream &optional buffer)
244 "Read a complete buffer of size *FILE-BUFFER-SIZE*."
245 (read-exactly-n-octets stream *file-buffer-size* buffer))
247 (defun merge-file-buffers (buffers size)
248 "Create one big vector from BUFFERS and TRAILER."
249 (let ((output (make-octet-vector size))
250 (start 0))
251 (dotimes (i (ceiling size *file-buffer-size*))
252 (replace output (pop buffers) :start1 start)
253 (incf start *file-buffer-size*))
254 output))
256 (defun skip-stream-octets (stream count)
257 "Read and discard COUNT octets from STREAM."
258 (let ((buffer (make-file-buffer)))
259 (multiple-value-bind (loops rest)
260 (truncate count *file-buffer-size*)
261 (dotimes (i loops)
262 (read-complete-file-buffer stream buffer))
263 (read-exactly-n-octets stream rest buffer)))
266 (defun drained-stream-vector (stream)
267 "Read octets from STREAM until EOF and them as an octet vector."
268 (let ((buffers '())
269 (size 0))
270 (loop
271 (let* ((buffer (make-file-buffer))
272 (count (read-sequence buffer stream)))
273 (incf size count)
274 (push buffer buffers)
275 (when (/= count *file-buffer-size*)
276 (return (merge-file-buffers (nreverse buffers) size)))))))
279 (defun partial-stream-vector (stream n)
280 "Read N octets from STREAM and return them in an octet vector."
281 (let ((buffers '()))
282 (multiple-value-bind (loops rest)
283 (truncate n *file-buffer-size*)
284 (dotimes (i loops)
285 (let ((buffer (make-file-buffer)))
286 (read-complete-file-buffer stream buffer)
287 (push buffer buffers)))
288 (push (read-exactly-n-octets stream rest) buffers)
289 (merge-file-buffers (nreverse buffers) n))))
291 (defun stream-subset-vector (stream start end)
292 (unless start
293 (setf start 0))
294 (when (minusp start)
295 (error "START must be non-negative"))
296 (when (and end (< end start))
297 (error "END must be greater than START"))
298 (when (plusp start)
299 (skip-stream-octets stream start))
300 (if (not end)
301 (drained-stream-vector stream)
302 (partial-stream-vector stream (- end start))))
304 (defun file-subset-vector (file start end)
305 (with-open-file (stream file :element-type 'octet)
306 (stream-subset-vector stream start end)))