From 5f6d20ea4cdcddbd10fd8d2c3f2bef89f1e14f42 Mon Sep 17 00:00:00 2001 From: "Steinar H. Gunderson" Date: Sun, 14 Dec 2014 23:24:55 +0100 Subject: [PATCH] Refactoring in binlookup. --- binlookup.cpp | 53 ++++++++++++++++++++++++++++++--------------------- 1 file changed, 31 insertions(+), 22 deletions(-) diff --git a/binlookup.cpp b/binlookup.cpp index 894da9d..19d0393 100644 --- a/binlookup.cpp +++ b/binlookup.cpp @@ -13,6 +13,32 @@ using namespace std; +string read_hex_line(FILE *fp) +{ + char hex[256]; + if (fgets(hex, sizeof(hex), fp) == NULL) { + return ""; + } + char *ptr = strchr(hex, '\n'); + if (ptr != NULL) { + *ptr = 0; + } + + string ret; + ret.resize(strlen(hex) / 2); + + for (size_t i = 0; i < ret.size(); ++i) { + char x[3]; + x[0] = hex[i * 2 + 0]; + x[1] = hex[i * 2 + 1]; + x[2] = 0; + int k; + sscanf(x, "%02x", &k); + ret[i] = k; + } + return ret; +} + int main(int argc, char **argv) { int num_buckets = atoi(argv[2]); @@ -24,29 +50,12 @@ int main(int argc, char **argv) } while (!feof(stdin)) { - char hex_bpfen[256]; - if (fgets(hex_bpfen, sizeof(hex_bpfen), stdin) == NULL) { + string bpfen = read_hex_line(stdin); + if (bpfen.empty()) { break; } - char *ptr = strchr(hex_bpfen, '\n'); - if (ptr != NULL) { - *ptr = 0; - } - - const int bpfen_len = strlen(hex_bpfen) / 2; - uint8_t *bpfen = new uint8_t[bpfen_len]; - - for (int i = 0; i < bpfen_len; ++i) { - char x[3]; - x[0] = hex_bpfen[i * 2 + 0]; - x[1] = hex_bpfen[i * 2 + 1]; - x[2] = 0; - int k; - sscanf(x, "%02x", &k); - bpfen[i] = k; - } - int bucket = hash_key_to_bucket((const char *)bpfen, bpfen_len, num_buckets); + int bucket = hash_key_to_bucket(bpfen.data(), bpfen.size(), num_buckets); if (mtbls[bucket] == NULL) { char filename[256]; snprintf(filename, sizeof(filename), "%s.part%04d", argv[1], bucket); @@ -56,10 +65,10 @@ int main(int argc, char **argv) } // Give back the hash of the position to be kind to the user - uint16_t board_hash = util::Hash32((const char *)bpfen, bpfen_len); + uint16_t board_hash = util::Hash32(bpfen.data(), bpfen.size()); printf("%d\n", board_hash); - mtbl_iter *it = mtbl_source_get_prefix(srcs[bucket], bpfen, bpfen_len); + mtbl_iter *it = mtbl_source_get_prefix(srcs[bucket], (const uint8_t *)bpfen.data(), bpfen.size()); const uint8_t *key, *val; size_t len_key, len_val; -- 2.39.2