diff --git a/src/lua/internal/sysbench.rand.lua b/src/lua/internal/sysbench.rand.lua index 2a05aade7..33b3109f5 100644 --- a/src/lua/internal/sysbench.rand.lua +++ b/src/lua/internal/sysbench.rand.lua @@ -79,6 +79,15 @@ function sysbench.rand.varstring(min_len, max_len) return ffi.string(buf, nchars) end +function sysbench.rand.hexadecimal(min_len, max_len) + assert(min_len <= max_len) + assert(max_len > 0) + local buflen = max_len + local buf = ffi.new("uint8_t[?]", buflen) + local nchars = ffi.C.sb_rand_hexadecimal(buf, min_len, max_len) + return ffi.string(buf, nchars) +end + function sysbench.rand.uniform_double() return ffi.C.sb_rand_uniform_double() end diff --git a/src/sb_rand.c b/src/sb_rand.c index 563b566e3..9692bae63 100644 --- a/src/sb_rand.c +++ b/src/sb_rand.c @@ -305,6 +305,36 @@ uint32_t sb_rand_varstr(char *buf, uint32_t min_len, uint32_t max_len) return num_chars; } +/* + Generates a random string of ASCII characters between '0' and 'f' of a length + between min and max. buf should have enough room for max len bytes. Returns + the number of characters written into the buffer. + */ + +uint32_t sb_rand_hexadecimal(char *buf, uint32_t min_len, uint32_t max_len) +{ + unsigned int i; + char charset[] = "abcdef0123456789"; + uint32_t num_chars; + if (max_len == 0) { + return 0; /* we can't be sure buf is long enough to populate, so be safe */ + } + if (min_len > max_len) + { + min_len = 1; + } + int key; + int l = (int) (sizeof(charset) -1); + + num_chars = sb_rand_uniform(min_len, max_len); + for (i=0; i < num_chars; i++) + { + key=rand() % l; + buf[i] = charset[key]; + } + return num_chars; +} + /* Unique random sequence generator. This is based on public domain code from https://github.com/preshing/RandomSequence diff --git a/src/sb_rand.h b/src/sb_rand.h index 6cb3dab2d..7c6c89a08 100644 --- a/src/sb_rand.h +++ b/src/sb_rand.h @@ -70,5 +70,6 @@ uint32_t sb_rand_zipfian(uint32_t, uint32_t); uint32_t sb_rand_unique(void); void sb_rand_str(const char *, char *); uint32_t sb_rand_varstr(char *, uint32_t, uint32_t); +uint32_t sb_rand_hexadecimal(char *, uint32_t, uint32_t); #endif /* SB_RAND_H */