r1555: *** empty log message ***
[uffi.git] / examples / compress.cl
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
4 ;;;;
5 ;;;; Name:          compress.cl
6 ;;;; Purpose:       UFFI Example file for zlib compression
7 ;;;; Programmer:    Kevin M. Rosenberg
8 ;;;; Date Started:  Feb 2002
9 ;;;;
10 ;;;; $Id: compress.cl,v 1.7 2002/03/14 21:03:12 kevin Exp $
11 ;;;;
12 ;;;; This file, part of UFFI, is Copyright (c) 2002 by Kevin M. Rosenberg
13 ;;;;
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 ;;;; *************************************************************************
18
19 (in-package :cl-user)
20
21 (unless (uffi:load-foreign-library "/usr/lib/libz.so" 
22                                    :module "zlib" 
23                                    :supporting-libraries '("c"))
24   (warn "Unable to load zlib"))
25
26 (uffi:def-function ("compress" c-compress)
27     ((dest (* :unsigned-char))
28      (destlen (* :long))
29      (source :cstring)
30      (source-len :long))
31   :returning :int
32   :module "zlib")
33   
34 (defun compress (source)
35   "Returns two values: array of bytes containing the compressed data
36  and the numbe of compressed bytes"
37   (let* ((sourcelen (length source))
38          (destsize (+ 12 (ceiling (* sourcelen 1.01))))
39          (dest (uffi:allocate-foreign-string destsize :unsigned t))
40          (destlen (uffi:allocate-foreign-object :long)))
41     (setf (uffi:deref-pointer destlen :long) destsize)
42     (uffi:with-cstring (source-native source)
43       (let ((result (c-compress dest destlen source-native sourcelen))
44             (newdestlen (uffi:deref-pointer destlen :long)))
45         (unwind-protect
46             (if (zerop result)
47                 (values (uffi:convert-from-foreign-string 
48                          dest
49                          :length newdestlen
50                          :null-terminated-p nil)
51                         newdestlen)
52               (error "zlib error, code ~D" result))
53           (progn
54             (uffi:free-foreign-object destlen)
55             (uffi:free-foreign-object dest)))))))
56
57
58 #+test-uffi
59 (progn
60   (flet ((print-results (str)
61            (multiple-value-bind (compressed len) (compress str)
62                (format t "~&(compress ~S) => ~S,~D" str compressed len))))
63     (print-results "")
64     (print-results "test")
65     (print-results "test2")))