Updated version to 1.3.3.
[zs3.git] / utils.lisp
blob6a3c606c355397a2fd043b82bf221eb382e17342
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 (deftype empty-vector ()
44 `(vector * 0))
46 (defun http-date-string (&optional (time (get-universal-time)))
47 "Return a HTTP-style date string."
48 (multiple-value-bind (second minute hour day month year day-of-week)
49 (decode-universal-time time 0)
50 (let ((*print-pretty* nil))
51 (format nil "~A, ~2,'0D ~A ~4,'0D ~2,'0D:~2,'0D:~2,'0D GMT"
52 (aref *days* day-of-week)
53 day
54 (aref *months* (1- month))
55 year
56 hour
57 minute
58 second))))
60 (defun iso8601-date-string (&optional (time (get-universal-time)))
61 "Return an ISO8601-style date string."
62 (multiple-value-bind (second minute hour day month year)
63 (decode-universal-time time 0)
64 (let ((*print-pretty* nil))
65 (format nil "~4,'0D-~2,'0D-~2,'0DT~2,'0D:~2,'0D:~2,'0DZ"
66 year month day hour minute second))))
68 (defun iso8601-basic-timestamp-string (&optional (time (get-universal-time)))
69 "Return an ISO8601-style basic date string."
70 (multiple-value-bind (second minute hour day month year)
71 (decode-universal-time time 0)
72 (let ((*print-pretty* nil))
73 (format nil "~4,'0D~2,'0D~2,'0DT~2,'0D~2,'0D~2,'0DZ"
74 year month day hour minute second))))
76 (defun iso8601-basic-date-string (&optional (time (get-universal-time)))
77 "Return an ISO8601-style basic date string."
78 (multiple-value-bind (second minute hour day month year)
79 (decode-universal-time time 0)
80 (declare (ignore second minute hour))
81 (let ((*print-pretty* nil))
82 (format nil "~4,'0D~2,'0D~2,'0D"
83 year month day))))
85 (defun string-octets (string)
86 "Return the UTF-8 encoding of STRING as a vector of octets."
87 (flexi-streams:string-to-octets string :external-format :utf-8))
89 (defun string64 (string)
90 (cl-base64:usb8-array-to-base64-string (string-octets string)))
92 (defun url-decode (string)
93 (with-output-to-string (out)
94 (let ((code 0))
95 (labels ((in-string (char)
96 (case char
97 (#\%
98 #'h1)
100 (write-char char out)
101 #'in-string)))
102 (weight (char)
103 (let ((weight (digit-char-p char 16)))
104 (unless weight
105 (error "~S is not a hex digit" char))
106 weight))
107 (h1 (char)
108 (setf code (ash (weight char) 4))
109 #'h2)
110 (h2 (char)
111 (incf code (weight char))
112 (write-char (code-char code) out)
113 #'in-string))
114 (let ((state #'in-string))
115 (loop for char across string
116 do (setf state (funcall state char))))))))
118 ;;; The following two functions were adatpted from Drakma source. It
119 ;;; has been adapted to more closely follow the description of
120 ;;; UriEncode() in
121 ;;; http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html
123 (defun url-encode (string &key (encode-slash t))
124 "Returns a URL-encoded version of the string STRING using the
125 LispWorks external format EXTERNAL-FORMAT."
126 (let ((*print-pretty* nil))
127 (with-output-to-string (out)
128 (loop for octet across (string-octets (or string ""))
129 for char = (code-char octet)
130 ;;'A'-'Z', 'a'-'z', '0'-'9', '-', '.', '_', and '~'
131 do (cond ((or (char<= #\0 char #\9)
132 (char<= #\a char #\z)
133 (char<= #\A char #\Z)
134 (and (not encode-slash) (char= char #\/))
135 (find char "-._~" :test #'char=))
136 (write-char char out))
137 ((or (char= char #\Space)
138 (char= char #\+))
139 (write-string "%20" out))
140 (t (format out "~:@(%~2,'0x~)" octet)))))))
142 (defun alist-to-url-encoded-string (alist)
143 "ALIST is supposed to be an alist of name/value pairs where both
144 names and values are strings. This function returns a string where
145 this list is represented as for the content type
146 `application/x-www-form-urlencoded', i.e. the values are URL-encoded
147 using the external format EXTERNAL-FORMAT, the pairs are joined with a
148 #\\& character, and each name is separated from its value with a #\\=
149 character."
150 (let ((*print-pretty* nil))
151 (with-output-to-string (out)
152 (loop for first = t then nil
153 for (name . value) in alist
154 unless first do (write-char #\& out)
155 do (format out "~A=~A"
156 (url-encode name)
157 (url-encode value))))))
159 (defun save (response file)
160 "Write a sequence of octets RESPONSE to FILE."
161 (with-open-file (stream file :direction :output
162 :if-exists :supersede
163 :element-type 'octet)
164 (write-sequence response stream))
165 (probe-file file))
167 (defun parse-amazon-timestamp (string)
168 "Convert the ISO 8601-format STRING to a universal time."
169 (flet ((number-at (start length)
170 (parse-integer string :start start :end (+ start length))))
171 (let ((year (number-at 0 4))
172 (month (number-at 5 2))
173 (day (number-at 8 2))
174 (hour (number-at 11 2))
175 (minute (number-at 14 2))
176 (second (number-at 17 2)))
177 (encode-universal-time second minute hour day month year 0))))
179 (defun stringify (thing)
180 (typecase thing
181 (string thing)
182 (symbol (symbol-name thing))
183 (t (princ-to-string thing))))
185 (defun parameters-alist (&rest args &key &allow-other-keys)
186 "Construct an ALIST based on all keyword arguments passed to the
187 function. Keywords are converted to their lowercase symbol name and
188 values are converted to strings."
189 (loop for (key value) on args by #'cddr
190 when value
191 collect (cons (if (symbolp key)
192 (string-downcase (symbol-name key))
193 key)
194 (stringify value))))
196 (defun last-entry (array)
197 "If ARRAY has one ore more entries, return the last one. Otherwise,
198 return NIL."
199 (and (plusp (length array))
200 (aref array (1- (length array)))))
202 (defun file-size (file)
203 (with-open-file (stream file :element-type 'octet)
204 (file-length stream)))
206 (defvar +unix-time-difference+
207 (encode-universal-time 0 0 0 1 1 1970 0))
209 (defun unix-time (&optional (universal-time (get-universal-time)))
210 (- universal-time +unix-time-difference+))
212 (defun octet-vector (&rest octets)
213 (make-array (length octets) :element-type 'octet
214 :initial-contents octets))
216 (defun keywordify (string-designator)
217 (intern (string string-designator) :keyword))
219 (defun make-octet-vector (size)
220 (make-array size :element-type 'octet))
222 (defun now+ (delta)
223 (+ (get-universal-time) delta))
225 (defun now- (delta)
226 (- (get-universal-time) delta))
228 (defun copy-n-octets (count input output)
229 "Copy the first N octets from the stream INPUT to the stream OUTPUT."
230 (let ((buffer (make-octet-vector 4096)))
231 (multiple-value-bind (loops rest)
232 (truncate count 4096)
233 (dotimes (i loops)
234 (read-sequence buffer input)
235 (write-sequence buffer output))
236 (let ((trailing-count (read-sequence buffer input :end rest)))
237 (assert (= trailing-count rest))
238 (write-sequence buffer output :end rest)))))
240 (defun starts-with (prefix string)
241 (and (<= (length prefix) (length string))
242 (string= prefix string :end2 (length prefix))))
244 (defun ends-with (suffix string)
245 (and (<= (length suffix) (length string))
246 (string= suffix string :start2 (- (length string)
247 (length suffix)))))
249 ;;; Getting stream/file subset vectors
251 (defparameter *file-buffer-size* 8192)
253 (defun make-file-buffer ()
254 (make-octet-vector *file-buffer-size*))
256 (defun read-exactly-n-octets (stream n &optional buffer)
257 "Read exactly N octets from STREAM into BUFFER. If fewer than N
258 octets are read, signal an CL:END-OF-FILE error. If BUFFER is not
259 supplied or is NIL, create a fresh buffer of length N and return it."
260 (unless buffer
261 (setf buffer (make-octet-vector n)))
262 (let ((end (min (length buffer) n)))
263 (let ((count (read-sequence buffer stream :end end)))
264 (unless (= n count)
265 (error 'end-of-file :stream stream))
266 buffer)))
268 (defun read-complete-file-buffer (stream &optional buffer)
269 "Read a complete buffer of size *FILE-BUFFER-SIZE*."
270 (read-exactly-n-octets stream *file-buffer-size* buffer))
272 (defun merge-file-buffers (buffers size)
273 "Create one big vector from BUFFERS and TRAILER."
274 (let ((output (make-octet-vector size))
275 (start 0))
276 (dotimes (i (ceiling size *file-buffer-size*))
277 (replace output (pop buffers) :start1 start)
278 (incf start *file-buffer-size*))
279 output))
281 (defun skip-stream-octets (stream count)
282 "Read and discard COUNT octets from STREAM."
283 (let ((buffer (make-file-buffer)))
284 (multiple-value-bind (loops rest)
285 (truncate count *file-buffer-size*)
286 (dotimes (i loops)
287 (read-complete-file-buffer stream buffer))
288 (read-exactly-n-octets stream rest buffer)))
291 (defun drained-stream-vector (stream)
292 "Read octets from STREAM until EOF and them as an octet vector."
293 (let ((buffers '())
294 (size 0))
295 (loop
296 (let* ((buffer (make-file-buffer))
297 (count (read-sequence buffer stream)))
298 (incf size count)
299 (push buffer buffers)
300 (when (/= count *file-buffer-size*)
301 (return (merge-file-buffers (nreverse buffers) size)))))))
304 (defun partial-stream-vector (stream n)
305 "Read N octets from STREAM and return them in an octet vector."
306 (let ((buffers '()))
307 (multiple-value-bind (loops rest)
308 (truncate n *file-buffer-size*)
309 (dotimes (i loops)
310 (let ((buffer (make-file-buffer)))
311 (read-complete-file-buffer stream buffer)
312 (push buffer buffers)))
313 (push (read-exactly-n-octets stream rest) buffers)
314 (merge-file-buffers (nreverse buffers) n))))
316 (defun stream-subset-vector (stream start end)
317 (unless start
318 (setf start 0))
319 (when (minusp start)
320 (error "START must be non-negative"))
321 (when (and end (< end start))
322 (error "END must be greater than START"))
323 (when (plusp start)
324 (skip-stream-octets stream start))
325 (if (not end)
326 (drained-stream-vector stream)
327 (partial-stream-vector stream (- end start))))
329 (defun file-subset-vector (file start end)
330 (with-open-file (stream file :element-type 'octet)
331 (stream-subset-vector stream start end)))
333 (defun alist-plist (alist)
334 (loop for (key . value) in alist
335 collect key collect value))