#ifndef LOCKFREE_READ_HELPER_H #define LOCKFREE_READ_HELPER_H #include #include #include #include #ifndef P_ERR #ifdef PRINT_READ_PROCESS #define P_ERR(...) fprintf(stderr, __VA_ARGS__) #else #define P_ERR(...) #endif #endif template class ReadHelper { // typedef unsigned long long key_type; key_type max_value = std::numeric_limits::min(), min_value = std::numeric_limits::max(); inline void store_into_vector(key_type value) { if (max_value < value) { max_value = value; } if (min_value > value) { min_value = value; } population_vector.push_back(value); } char const *filename; static constexpr size_t REVERSED_BLOCK = 256; auto genRandomRow(size_t total_row) const { if (total_row != 0) { assert(total_row > (population_length + sample_length + REVERSED_BLOCK)); return randomRow(total_row - population_length - sample_length - REVERSED_BLOCK); } return 0UL; } public: const size_t sample_length, population_length, random_number; ReadHelper(char const *filename, size_t sample_length, size_t population_length, size_t total_row = 0) : filename(filename), sample_length(sample_length), population_length(population_length), random_number(genRandomRow(total_row)) {} key_type maxValue() const { return max_value; } key_type minValue() const { return min_value; } std::vector population_vector; static unsigned long randomRow(unsigned long max_value_) { std::random_device randomDevice; std::mt19937 mt19937(randomDevice()); std::uniform_int_distribution dst(0, max_value_); return dst(mt19937); } bool readFile() { this->population_vector.clear(); auto read_number = 0UL; std::ifstream fin(filename); if (!fin.is_open()) { return false; } for (key_type i; read_number < sample_length && !fin.eof(); store_into_vector(i)) { fin >> i; read_number++; } if (random_number > 0) { read_number = random_number; for (key_type i; read_number > 0 && !fin.eof(); fin >> i) read_number--; } read_number = 0; auto remain = population_length + REVERSED_BLOCK; for (key_type i; read_number < remain && !fin.eof(); store_into_vector(i)) { fin >> i; read_number++; } fin.close(); return true; } void split_into(std::vector &sample, std::vector &p) { sample.resize(sample_length - 2); p.resize(population_length); memcpy(sample.data(), population_vector.data(), sizeof(key_type) * (sample_length - 2)); sample.push_back(this->max_value); sample.push_back(this->min_value); memcpy(p.data(), population_vector.data() + sample_length, sizeof(key_type) * population_length); } size_t size() const { return this->population_vector.size(); } }; #endif