Created
February 4, 2020 09:15
-
-
Save pgp/fbf3ecba9cfbe800377c3b5e9305ddf6 to your computer and use it in GitHub Desktop.
qsort example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
#include <cstdlib> | |
#include <cstdint> | |
#include <cstring> | |
/** | |
* g++ -O3 qsortExample.cpp | |
* | |
* # MinGW | |
* g++ -O3 qsortExample.cpp -lbcrypt | |
*/ | |
#ifdef _WIN32 | |
#define WIN32_NO_STATUS | |
#include <windows.h> | |
#undef WIN32_NO_STATUS | |
#include <winternl.h> | |
#include <ntstatus.h> | |
#include <winerror.h> | |
#include <bcrypt.h> | |
#include <sal.h> | |
void randombytes(unsigned char *x, unsigned long long xlen) { | |
if (!NT_SUCCESS(BCryptGenRandom(nullptr,x,xlen,BCRYPT_USE_SYSTEM_PREFERRED_RNG))) { | |
_Exit(-1); | |
} | |
} | |
#else | |
#include <unistd.h> | |
#include <sys/types.h> | |
#include <sys/stat.h> | |
#include <fcntl.h> | |
ssize_t readAll(int fd, void* buf_, size_t count) { | |
auto buf = (uint8_t*)buf_; | |
size_t alreadyRead = 0; | |
size_t remaining = count; | |
for(;;) { | |
ssize_t curr = read(fd, buf+alreadyRead,remaining); | |
if (curr <= 0) return curr; // EOF | |
remaining -= curr; | |
alreadyRead += curr; | |
if (remaining == 0) return count; // all expected bytes read | |
} | |
} | |
void readAllOrExit(int fd, void* buf, size_t count) { | |
ssize_t readBytes = readAll(fd,buf,count); | |
ssize_t count_ = count; | |
if (readBytes < count_) _Exit(-2); | |
} | |
void randombytes(unsigned char *x, unsigned long long xlen) { | |
static int fd = -1; | |
if(fd < 0) { | |
if((fd = open("/dev/urandom",O_RDONLY))==-1) _Exit(-1); | |
} | |
readAllOrExit(fd,x,xlen); | |
} | |
#endif | |
constexpr size_t VSZ = 128*1048576; | |
constexpr size_t ISZ = 64; | |
constexpr size_t nmemb = VSZ/ISZ; | |
int comp(const void* p1, const void* p2) { | |
return memcmp(p1,p2,ISZ); | |
} | |
int main() { | |
std::vector<uint8_t> v(VSZ,0); | |
randombytes(&v[0],VSZ); | |
std::cout<<"RNG OK"<<std::endl; | |
std::cout<<"Items:"<<nmemb<<std::endl; | |
qsort(&v[0],nmemb,ISZ,comp); | |
std::cout<<"SORT OK"<<std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment