Changeset View
Changeset View
Standalone View
Standalone View
src/compressor.cpp
Show First 20 Lines • Show All 133 Lines • ▼ Show 20 Lines | |||||
// * if e<9, the last digit of the resulting number cannot be 0; store it as d, | // * if e<9, the last digit of the resulting number cannot be 0; store it as d, | ||||
// and drop it (divide by 10) | // and drop it (divide by 10) | ||||
// * call the result n | // * call the result n | ||||
// * output 1 + 10*(9*n + d - 1) + e | // * output 1 + 10*(9*n + d - 1) + e | ||||
// * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n | // * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n | ||||
// - 1) + 9 | // - 1) + 9 | ||||
// (this is decodable, as d is in [1-9] and e is in [0-9]) | // (this is decodable, as d is in [1-9] and e is in [0-9]) | ||||
uint64_t CTxOutCompressor::CompressAmount(uint64_t n) { | uint64_t CTxOutCompressor::CompressAmount(CAmount ca) { | ||||
// Convert CAmount to uint64_t for bit manipulations | |||||
uint64_t n = ca / 1; | |||||
if (n == 0) { | if (n == 0) { | ||||
return 0; | return 0; | ||||
} | } | ||||
int e = 0; | int e = 0; | ||||
while (((n % 10) == 0) && e < 9) { | while (((n % 10) == 0) && e < 9) { | ||||
n /= 10; | n /= 10; | ||||
e++; | e++; | ||||
} | } | ||||
if (e < 9) { | if (e < 9) { | ||||
int d = (n % 10); | int d = (n % 10); | ||||
assert(d >= 1 && d <= 9); | assert(d >= 1 && d <= 9); | ||||
n /= 10; | n /= 10; | ||||
return 1 + (n * 9 + d - 1) * 10 + e; | return 1 + (n * 9 + d - 1) * 10 + e; | ||||
} else { | } else { | ||||
return 1 + (n - 1) * 10 + 9; | return 1 + (n - 1) * 10 + 9; | ||||
} | } | ||||
} | } | ||||
uint64_t CTxOutCompressor::DecompressAmount(uint64_t x) { | CAmount CTxOutCompressor::DecompressAmount(uint64_t x) { | ||||
// x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9 | // x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9 | ||||
if (x == 0) { | if (x == 0) { | ||||
return 0; | return 0; | ||||
} | } | ||||
x--; | x--; | ||||
// x = 10*(9*n + d - 1) + e | // x = 10*(9*n + d - 1) + e | ||||
int e = x % 10; | int e = x % 10; | ||||
x /= 10; | x /= 10; | ||||
uint64_t n = 0; | uint64_t n = 0; | ||||
if (e < 9) { | if (e < 9) { | ||||
// x = 9*n + d - 1 | // x = 9*n + d - 1 | ||||
int d = (x % 9) + 1; | int d = (x % 9) + 1; | ||||
x /= 9; | x /= 9; | ||||
// x = n | // x = n | ||||
n = x * 10 + d; | n = x * 10 + d; | ||||
} else { | } else { | ||||
n = x + 1; | n = x + 1; | ||||
} | } | ||||
while (e) { | while (e) { | ||||
n *= 10; | n *= 10; | ||||
e--; | e--; | ||||
} | } | ||||
return n; | return CAmount(n); | ||||
} | } |