libc3: remerged
[simavr] / examples / shared / libc3 / src / c3pixels.c
1 /*
2         c3pixels.c
3
4         Copyright 2008-2012 Michel Pollet <buserror@gmail.com>
5
6         This file is part of libc3.
7
8         libc3 is free software: you can redistribute it and/or modify
9         it under the terms of the GNU General Public License as published by
10         the Free Software Foundation, either version 3 of the License, or
11         (at your option) any later version.
12
13         libc3 is distributed in the hope that it will be useful,
14         but WITHOUT ANY WARRANTY; without even the implied warranty of
15         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16         GNU General Public License for more details.
17
18         You should have received a copy of the GNU General Public License
19         along with libc3.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 #include <stdlib.h>
23 #include <string.h>
24 #include "c3pixels.h"
25
26 c3pixels_p
27 c3pixels_new(
28                 uint32_t w,
29                 uint32_t h,
30                 int      psize /* in bytes */,
31                 size_t row,
32                 void * base)
33 {
34         c3pixels_p p = malloc(sizeof(*p));
35         c3pixels_init(p, w, h, psize, row, base);
36         p->alloc = 1;
37         return p;
38 }
39
40 c3pixels_p
41 c3pixels_init(
42                 c3pixels_p p,
43                 uint32_t w,
44                 uint32_t h,
45                 int      psize /* in bytes */,
46                 size_t row,
47                 void * base)
48 {
49         memset (p, 0, sizeof(*p));
50         p->w = w;
51         p->h = h;
52         p->row = row;
53         p->psize = psize;
54         p->base = base;
55         c3pixels_alloc(p);
56         return p;
57 }
58
59 void
60 c3pixels_dispose(
61                 c3pixels_p p )
62 {
63         if (p->own && p->base)
64                 free(p->base);
65         if (p->alloc)
66                 free(p);
67         else
68                 memset(p, 0, sizeof(*p));
69 }
70
71 void
72 c3pixels_alloc(
73                 c3pixels_p p )
74 {
75         if (p->base)
76                 return;
77         p->base = malloc(p->row * p->h);
78         p->own = p->base != NULL;
79 }
80
81 void
82 c3pixels_purge(
83                 c3pixels_p p )
84 {
85         if (!p->base)
86                 return;
87         if (p->own)
88                 free(p->base);
89         p->own = 0;
90         p->base = NULL;
91 }
92
93 void
94 c3pixels_zero(
95                 c3pixels_p p)
96 {
97         if (!p->base)
98                 return;
99         memset(p->base, 0, p->h * p->row);
100 }