summaryrefslogtreecommitdiff
path: root/goo
diff options
context:
space:
mode:
authorFabio D'Urso <fabiodurso@hotmail.it>2012-08-06 02:06:47 +0200
committerAlbert Astals Cid <aacid@kde.org>2012-09-06 22:06:46 +0200
commitfaff947d8106048b19ba74dd483b90b8cebb16c7 (patch)
tree8a0cc6eafb73ddaabdc82fd88fe0d12c970cfaa9 /goo
parentaf8d05d1ab89b74e307e90aaf19c750528f5f561 (diff)
Added goo/grandom.[cc|h] with POSIX implementation
Diffstat (limited to 'goo')
-rw-r--r--goo/Makefile.am6
-rw-r--r--goo/grandom.cc68
-rw-r--r--goo/grandom.h32
3 files changed, 104 insertions, 2 deletions
diff --git a/goo/Makefile.am b/goo/Makefile.am
index f4f97304..0764e79c 100644
--- a/goo/Makefile.am
+++ b/goo/Makefile.am
@@ -18,7 +18,8 @@ poppler_goo_include_HEADERS = \
TiffWriter.h \
ImgWriter.h \
GooLikely.h \
- gstrtod.h
+ gstrtod.h \
+ grandom.h
endif
@@ -59,4 +60,5 @@ libgoo_la_SOURCES = \
TiffWriter.cc \
ImgWriter.cc \
gtypes_p.h \
- gstrtod.cc
+ gstrtod.cc \
+ grandom.cc
diff --git a/goo/grandom.cc b/goo/grandom.cc
new file mode 100644
index 00000000..bafa4b60
--- /dev/null
+++ b/goo/grandom.cc
@@ -0,0 +1,68 @@
+/*
+ * grandom.cc
+ *
+ * Pseudo-random number generation
+ *
+ * Copyright (C) 2012 Fabio D'Urso <fabiodurso@hotmail.it>
+ */
+
+#include <config.h>
+#include "grandom.h"
+#include "gtypes.h"
+
+#ifdef HAVE_RAND_R // rand_r backend (POSIX)
+
+static GBool initialized = gFalse;
+
+#include <stdlib.h>
+#include <time.h>
+static unsigned int seed;
+
+static void initialize() {
+ if (!initialized) {
+ seed = time(NULL);
+ initialized = gTrue;
+ }
+}
+
+void grandom_fill(Guchar *buff, int size)
+{
+ initialize();
+ while (size--)
+ *buff++ = rand_r(&seed) % 256;
+}
+
+double grandom_double()
+{
+ initialize();
+ return rand_r(&seed) / (1 + (double)RAND_MAX);
+}
+
+#else // srand+rand backend (unsafe, because it may interfere with the application)
+
+static GBool initialized = gFalse;
+
+#include <stdlib.h>
+#include <time.h>
+
+static void initialize() {
+ if (!initialized) {
+ srand(time(NULL));
+ initialized = gTrue;
+ }
+}
+
+void grandom_fill(Guchar *buff, int size)
+{
+ initialize();
+ while (size--)
+ *buff++ = rand() % 256;
+}
+
+double grandom_double()
+{
+ initialize();
+ return rand() / (1 + (double)RAND_MAX);
+}
+
+#endif
diff --git a/goo/grandom.h b/goo/grandom.h
new file mode 100644
index 00000000..763e8e0c
--- /dev/null
+++ b/goo/grandom.h
@@ -0,0 +1,32 @@
+/*
+ * grandom.h
+ *
+ * Pseudo-random number generation
+ *
+ * Copyright (C) 2012 Fabio D'Urso <fabiodurso@hotmail.it>
+ */
+
+#ifndef GRANDOM_H
+#define GRANDOM_H
+
+#include "gtypes.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Fills the given buffer with random bytes
+ */
+extern void grandom_fill(Guchar *buff, int size);
+
+/*
+ * Returns a random number in [0,1)
+ */
+extern double grandom_double();
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif