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