Root/
| 1 | /* |
| 2 | * array.c - Growable baseless 2D array |
| 3 | * |
| 4 | * Written 2010 by Werner Almesberger |
| 5 | * Copyright 2010 by Werner Almesberger |
| 6 | * |
| 7 | * This program is free software; you can redistribute it and/or modify |
| 8 | * it under the terms of the GNU General Public License as published by |
| 9 | * the Free Software Foundation; either version 2 of the License, or |
| 10 | * (at your option) any later version. |
| 11 | */ |
| 12 | |
| 13 | |
| 14 | #include <stdlib.h> |
| 15 | |
| 16 | #include "util.h" |
| 17 | #include "array.h" |
| 18 | |
| 19 | |
| 20 | static void resize(struct array *a, |
| 21 | int nx0, int nx1, int ny0, int ny1) |
| 22 | { |
| 23 | int ox, oy, nx, ny; |
| 24 | int n, x, y; |
| 25 | int *tmp; |
| 26 | |
| 27 | ox = a->max_x-a->min_x; |
| 28 | oy = a->max_y-a->min_y; |
| 29 | nx = nx1-nx0; |
| 30 | ny = ny1-ny0; |
| 31 | if (ox == nx && oy == ny) |
| 32 | return; |
| 33 | n = (nx+1)*(ny+1); |
| 34 | tmp = alloc_size(n*sizeof(int)); |
| 35 | for (x = 0; x != n; x++) |
| 36 | tmp[x] = UNDEF; |
| 37 | for (x = a->min_x; x <= a->max_x; x++) |
| 38 | for (y = a->min_y; y <= a->max_y; y++) |
| 39 | tmp[x-nx0+(nx+1)*(y-ny0)] = |
| 40 | a->data[x-a->min_x+(ox+1)*(y-a->min_y)]; |
| 41 | free(a->data); |
| 42 | a->data = tmp; |
| 43 | a->min_x = nx0; |
| 44 | a->max_x = nx1; |
| 45 | a->min_y = ny0; |
| 46 | a->max_y = ny1; |
| 47 | } |
| 48 | |
| 49 | |
| 50 | struct array *new_array(void) |
| 51 | { |
| 52 | struct array *a; |
| 53 | |
| 54 | a = alloc_type(struct array); |
| 55 | a->data = NULL; |
| 56 | return a; |
| 57 | } |
| 58 | |
| 59 | |
| 60 | void free_array(struct array *a) |
| 61 | { |
| 62 | free(a->data); |
| 63 | free(a); |
| 64 | } |
| 65 | |
| 66 | |
| 67 | void set(struct array *a, int x, int y, int z) |
| 68 | { |
| 69 | if (!a->data) { |
| 70 | a->min_x = a->max_x = x; |
| 71 | a->min_y = a->max_y = y; |
| 72 | a->min_z = a->max_z = z; |
| 73 | a->data = alloc_type(int); |
| 74 | *a->data = z; |
| 75 | } else { |
| 76 | resize(a, |
| 77 | x < a->min_x ? x : a->min_x, x > a->max_x ? x : a->max_x, |
| 78 | y < a->min_y ? y : a->min_y, y > a->max_y ? y : a->max_y); |
| 79 | if (z < a->min_z) |
| 80 | a->min_z = z; |
| 81 | if (z > a->max_z) |
| 82 | a->max_z = z; |
| 83 | a->data[x-a->min_x+(a->max_x-a->min_x+1)*(y-a->min_y)] = z; |
| 84 | } |
| 85 | } |
| 86 |
Branches:
master
