-
Notifications
You must be signed in to change notification settings - Fork 1
/
MM_autoreleasepool.c
67 lines (60 loc) · 1.62 KB
/
MM_autoreleasepool.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//
// autoreleasepool.c
// libmemmgmt
//
// Created by Hubert Godfroy on 27/06/12.
// Copyright (c) 2012 Mines de Nancy. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include "MM_base.h"
#include "MM_autoreleasepool.h"
typedef struct _scope{
struct _scope* SurroundingScope;
AutoReleasePool* pool;
}Scope;
static Scope* CURRENT_SCOPE = NULL;
static Scope* newScope(){
Scope* res = malloc(sizeof(Scope));
return res;
}
AutoReleasePool* newAutoReleasePool(){
AutoReleasePool* res = malloc(sizeof(AutoReleasePool));
res->obj = NULL;
res->next = NULL;
Scope* newscope = newScope();
newscope->SurroundingScope = CURRENT_SCOPE;
newscope->pool = res;
CURRENT_SCOPE = newscope;
return res;
}
void autorelease(void* obj){
AutoReleasePool* CurrentPool = CURRENT_SCOPE->pool;
if (CurrentPool->obj == NULL) {
CurrentPool->obj = obj;
return;
}
AutoReleasePool* next = malloc(sizeof(AutoReleasePool));
next->next = CurrentPool->next;
next->obj = CurrentPool->obj;
CurrentPool->next = next;
CurrentPool->obj = obj;
}
void drain(AutoReleasePool* pool){
if (pool != CURRENT_SCOPE->pool) {
printf("le pool à effacer n'est pas le pool courant\n");
exit(EXIT_FAILURE);
}
AutoReleasePool* tete = pool;
while (tete != NULL) {
if (tete->obj != NULL) {
release(tete->obj);
}
AutoReleasePool* next = tete->next;
free(tete);
tete = next;
}
Scope* surroundingScope = CURRENT_SCOPE->SurroundingScope;
free(CURRENT_SCOPE);
CURRENT_SCOPE = surroundingScope;
}