]> mj.ucw.cz Git - libucw.git/commitdiff
Resources can be allocated from static memory buffers
authorPavel Charvat <pchar@ucw.cz>
Wed, 20 Jun 2012 10:51:59 +0000 (12:51 +0200)
committerMartin Mares <mj@ucw.cz>
Thu, 12 Jul 2012 15:07:07 +0000 (17:07 +0200)
ucw/resource.c
ucw/resource.h

index 3fd163ae5c5836b5fd1a0be669d23cc5a236d1f9..86cc8ab385d3c810480e99b4a31c623ce9bd95a5 100644 (file)
@@ -100,20 +100,38 @@ res_alloc(const struct res_class *rc)
 {
   struct respool *rp = rp_current();
   ASSERT(rp);
-
   uns size = (rc->res_size ? : sizeof(struct resource));
-  struct resource *r = (rp->mpool ? mp_alloc_fast(rp->mpool, size) : xmalloc(size));
+  struct resource *r;
+  if (rp->mpool)
+    {
+      r = mp_alloc_fast(rp->mpool, size);
+      r->flags = 0;
+    }
+  else
+    {
+      r = xmalloc(size);
+      r->flags = RES_FLAG_XFREE;
+    }
+  res_add(r);
+  return r;
+}
+
+void
+res_add(struct resource *r)
+{
+  struct respool *rp = rp_current();
+  ASSERT(rp);
   r->rpool = rp;
   clist_add_tail(&rp->resources, &r->n);
-  r->flags = rp->default_res_flags;
-  return r;
+  r->flags &= ~RES_FLAG_TEMP;
+  r->flags |= rp->default_res_flags & RES_FLAG_TEMP;
 }
 
 void
 res_drop(struct resource *r)
 {
   clist_remove(&r->n);
-  if (!r->rpool->mpool)
+  if (r->flags & RES_FLAG_XFREE)
     xfree(r);
 }
 
index a4b8c88f554d91ac4b75072dc7597a85f30f3f26..74de3607c0727a303a0fda01b26e729935711bac 100644 (file)
@@ -43,6 +43,7 @@ struct resource {
 /** Resource flags **/
 enum resource_flags {
   RES_FLAG_TEMP = 1,                                   // Resource is temporary
+  RES_FLAG_XFREE = 2,                                  // Resource structure needs to be deallocated by xfree()
 };
 
 /**
@@ -130,6 +131,23 @@ struct res_class {
   uns res_size;                                                // Size of the resource structure (0=default)
 };
 
+/**
+ * Initialize a pre-allocated buffer to the specific class of resource, setting its private data to @priv.
+ * This resource can be added to the current pool by @res_add().
+ **/
+static inline struct resource *res_init(struct resource *r, const struct res_class *rc, void *priv)
+{
+  r->flags = 0;
+  r->rclass = rc;
+  r->priv = priv;
+  return r;
+}
+
+/**
+ * Links a pre-initialized resource to the active pool.
+ **/
+void res_add(struct resource *r);
+
 /**
  * Unlinks a resource from a pool and releases its meta-data. Unlike @res_detach(),
  * it does not invoke any callbacks. The caller must make sure that no references to