Remove CVS $Id$ keyword
[clsql.git] / db-db2 / foreign-resources.lisp
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
4 ;;;;
5 ;;;; This file is part of CLSQL.
6 ;;;;
7 ;;;; CLSQL users are granted the rights to distribute and use this software
8 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
9 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
10 ;;;; *************************************************************************
11
12 (in-package #:clsql-db2)
13
14 (defparameter *foreign-resource-hash* (make-hash-table :test #'equal))
15
16 (defstruct (foreign-resource)
17   (type (error "Missing TYPE.")
18         :read-only t)
19   (sizeof (error "Missing SIZEOF.")
20           :read-only t)
21   (buffer (error "Missing BUFFER.")
22           :read-only t)
23   (in-use nil :type boolean))
24
25
26 (defun %get-resource (type sizeof)
27   (let ((resources (gethash type *foreign-resource-hash*)))
28     (car (member-if
29           #'(lambda (res)
30               (and (= (foreign-resource-sizeof res) sizeof)
31                    (not (foreign-resource-in-use res))))
32           resources))))
33
34 (defun %insert-foreign-resource (type res)
35   (let ((resource (gethash type *foreign-resource-hash*)))
36     (setf (gethash type *foreign-resource-hash*)
37           (cons res resource))))
38
39 (defmacro acquire-foreign-resource (type &optional size)
40   `(let ((res (%get-resource ,type ,size)))
41      (unless res
42        (setf res (make-foreign-resource
43                   :type ,type :sizeof ,size
44                   :buffer (uffi:allocate-foreign-object ,type ,size)))
45        (%insert-foreign-resource ',type res))
46      (claim-foreign-resource res)))
47
48 (defun free-foreign-resource (ares)
49   (setf (foreign-resource-in-use ares) nil)
50   ares)
51
52 (defun claim-foreign-resource (ares)
53   (setf (foreign-resource-in-use ares) t)
54   ares)
55
56
57