1 ;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
6 ;;;; Purpose: UFFI Example file for zlib compression
7 ;;;; Programmer: Kevin M. Rosenberg
8 ;;;; Date Started: Feb 2002
10 ;;;; $Id: compress.lisp,v 1.2 2002/12/03 06:58:39 kevin Exp $
12 ;;;; This file, part of UFFI, is Copyright (c) 2002 by Kevin M. Rosenberg
14 ;;;; UFFI users are granted the rights to distribute and use this software
15 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
16 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
17 ;;;; *************************************************************************
21 (eval-when (:load-toplevel :execute)
22 (unless (uffi:load-foreign-library
24 (uffi:find-foreign-library
26 '("/usr/local/lib/" "/usr/lib/" "/zlib/")
29 (uffi:find-foreign-library "z"
30 `(,(pathname-directory *load-pathname*)))
32 :supporting-libraries '("c"))
33 (warn "Unable to load zlib")))
35 (uffi:def-function ("compress" c-compress)
36 ((dest (* :unsigned-char))
43 (defun compress (source)
44 "Returns two values: array of bytes containing the compressed data
45 and the numbe of compressed bytes"
46 (let* ((sourcelen (length source))
47 (destsize (+ 12 (ceiling (* sourcelen 1.01))))
48 (dest (uffi:allocate-foreign-string destsize :unsigned t))
49 (destlen (uffi:allocate-foreign-object :long)))
50 (setf (uffi:deref-pointer destlen :long) destsize)
51 (uffi:with-cstring (source-native source)
52 (let ((result (c-compress dest destlen source-native sourcelen))
53 (newdestlen (uffi:deref-pointer destlen :long)))
56 (values (uffi:convert-from-foreign-string
59 :null-terminated-p nil)
61 (error "zlib error, code ~D" result))
63 (uffi:free-foreign-object destlen)
64 (uffi:free-foreign-object dest)))))))
69 (flet ((print-results (str)
70 (multiple-value-bind (compressed len) (compress str)
71 (format t "~&(compress ~S) => " str)
73 (format t "~X" (char-code (char compressed i))))
74 (format t ",~D" len))))
76 (print-results "test")
77 (print-results "test2")))
79 ;; Results of the above on my system:
80 ;; (compress "") => 789c300001,8
81 ;; (compress "test") => 789c2b492d2e1045d1c1,12
82 ;; (compress "test2") => 789c2b492d2e31206501f3,13