kclib1について#3

(1) KPtrPool



#define KPTRPOOL_REPORT 1

typedef struct KPtrPool_ {
    int s, n;
    void *p;
    void *fw;
    #if (KPTRPOOL_REPORT != 0)
        int a, u;
    #endif
} KPtrPool;

#include "kclib1.h"
#include <stdlib.h>

void KPtrPool_init(KPtrPool *w, int s, void *fw)
{
    if (s < (int) sizeof (void *))
        s = sizeof (void *);
    w->n = 64 * 1024 / s;
    w->s = s;
    if (w->n < 1)
        w->n = 1;
    w->p = 0;
    w->fw = fw;
    #if (KPTRPOOL_REPORT != 0)
        w->a = w->u = 0;
    #endif
}

void KPtrPool_free(KPtrPool *w, void *p)
{
    *((void **) p) = w->p;
    w->p = p;
    #if (KPTRPOOL_REPORT != 0)
        w->u--;
    #endif
}

void *KPtrPool_alloc(KPtrPool *w)
{
    char *p;
    void *(*f)(void *, int);
    if (w->p == 0) {
        int i;
        f = *((void **) w->fw);
        p = f(w->fw, w->n * w->s);
        if (p == 0) goto fin;
        p += w->n * w->s;
        for (i = 0; i < w->n; i++) {
            p -= w->s;
            KPtrPool_free(w, p);
        }
        #if (KPTRPOOL_REPORT != 0)
            w->a += w->n;
            w->u += w->n;
        #endif
    }
    p = w->p;
    w->p = *(void **) p;
    #if (KPTRPOOL_REPORT != 0)
        w->u++;
    #endif
fin:
    return p;
}

void *KPtrPool_f_malloc(void *w, int s)
{
    void *p = malloc(s);
    (void) w;
    if (p == 0)
        kerrorExit("KPtrPool_f_malloc: out of memory");
    return p;
}

void *KPtrPool_fw_malloc[1] = { (void *) &KPtrPool_f_malloc };

こめんと欄


コメントお名前NameLink

トップ 一覧 検索 最終更新 バックアップ   ヘルプ   最終更新のRSS