OSDN Git Service

first commit
[liveml/LiveML.git] / src / stack.c
1 /**
2  * stack - The stack data structure.
3  *
4  * MIT License
5  * Copyright (C) 2010 Nothan
6  * http://github.com/nothan/c-utils/
7  * All rights reserved.
8  *
9  * Permission is hereby granted, free of charge, to any person obtaining a copy
10  * of this software and associated documentation files (the "Software"), to deal
11  * in the Software without restriction, including without limitation the rights
12  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13  * copies of the Software, and to permit persons to whom the Software is
14  * furnished to do so, subject to the following conditions:
15  *
16  * The above copyright notice and this permission notice shall be included in all
17  * copiGes or substantial portions of the Software.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23  * LIAGBILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25  * SOFTWARE.
26  *
27  * Nothan
28  * private@nothan.xrea.jp
29  *
30  * Tsuioku Denrai
31  * http://tsuioku-denrai.xrea.jp/
32  */
33
34 #include "stack.h"
35 #include <string.h>
36 #include <malloc.h>
37
38 void stack_init(stack_data *data, int block_size)
39 {
40   data->size = 0;
41   data->block_size = block_size;
42   data->current = NULL;
43   data->pool = NULL;
44 }
45
46 void stack_free(stack_data *data)
47 {
48   if (data->pool != NULL) free(data->pool);
49 }
50
51 void stack_resize(stack_data *data, int size)
52 {
53   char* pool = malloc(data->block_size * size);
54   int used_size = data->current - data->pool;
55   if (data->pool != NULL)
56   {
57     if(used_size) memcpy(pool, data->pool, used_size);
58     free(data->pool);
59   }
60   data->pool = pool;
61   data->current = data->pool + used_size;
62   data->size = data->block_size * size;
63 }
64
65 char stack_push(stack_data *stack, void *data)
66 {
67   if (stack->current - stack->pool >= stack->size) return 1;
68   memcpy(stack->current, data, stack->block_size);
69   stack->current += stack->block_size;
70   return 0;
71 }
72
73 char stack_pop(stack_data *stack, void *data)
74 {
75   if (stack->current == stack->pool) return 1;
76   stack->current -= stack->block_size;
77   memcpy(data, stack->current, stack->block_size);
78   return 0;
79 }