aboutsummaryrefslogtreecommitdiff
path: root/misc.c
diff options
context:
space:
mode:
authorSimon Tatham <anakin@pobox.com>2005-07-17 12:12:16 +0000
committerSimon Tatham <anakin@pobox.com>2005-07-17 12:12:16 +0000
commit782a4f3fece388a3b5e541f4b1b11f86f69d5921 (patch)
tree34596c9273c608a317b1701a8aefe5e1a56e538f /misc.c
parenta31934f233581da07153af6b4ee717f1e63387dd (diff)
downloadpuzzles-782a4f3fece388a3b5e541f4b1b11f86f69d5921.zip
puzzles-782a4f3fece388a3b5e541f4b1b11f86f69d5921.tar.gz
puzzles-782a4f3fece388a3b5e541f4b1b11f86f69d5921.tar.bz2
puzzles-782a4f3fece388a3b5e541f4b1b11f86f69d5921.tar.xz
Get rid of the malloc in shuffle(), by defining a subfunction
memswap() which declares a fixed-size buffer on the stack and uses it multiple times if necessary. [originally from svn r6107]
Diffstat (limited to 'misc.c')
-rw-r--r--misc.c25
1 files changed, 18 insertions, 7 deletions
diff --git a/misc.c b/misc.c
index b832ee0..5ad4d0b 100644
--- a/misc.c
+++ b/misc.c
@@ -194,21 +194,32 @@ void game_mkhighlight(frontend *fe, float *ret,
}
}
+void memswap(void *av, void *bv, int size)
+{
+ char tmpbuf[512];
+ char *a = av, *b = bv;
+
+ while (size > 0) {
+ int thislen = min(size, sizeof(tmpbuf));
+ memcpy(tmpbuf, a, thislen);
+ memcpy(a, b, thislen);
+ memcpy(b, tmpbuf, thislen);
+ a += thislen;
+ b += thislen;
+ size -= thislen;
+ }
+}
+
void shuffle(void *array, int nelts, int eltsize, random_state *rs)
{
- char *tmp = smalloc(eltsize);
char *carray = (char *)array;
int i;
for (i = nelts; i-- > 1 ;) {
int j = random_upto(rs, i+1);
- if (j != i) {
- memcpy(tmp, carray + eltsize * i, eltsize);
- memcpy(carray + eltsize * i, carray + eltsize * j, eltsize);
- memcpy(carray + eltsize * j, tmp, eltsize);
- }
+ if (j != i)
+ memswap(carray + eltsize * i, carray + eltsize * j, eltsize);
}
- sfree(tmp);
}
void draw_rect_outline(frontend *fe, int x, int y, int w, int h, int colour)