snappy-stubs-internal.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. // Copyright 2011 Google Inc. All Rights Reserved.
  2. //
  3. // Redistribution and use in source and binary forms, with or without
  4. // modification, are permitted provided that the following conditions are
  5. // met:
  6. //
  7. // * Redistributions of source code must retain the above copyright
  8. // notice, this list of conditions and the following disclaimer.
  9. // * Redistributions in binary form must reproduce the above
  10. // copyright notice, this list of conditions and the following disclaimer
  11. // in the documentation and/or other materials provided with the
  12. // distribution.
  13. // * Neither the name of Google Inc. nor the names of its
  14. // contributors may be used to endorse or promote products derived from
  15. // this software without specific prior written permission.
  16. //
  17. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  20. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  21. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  22. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  23. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  24. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  25. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  27. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. //
  29. // Various stubs for the open-source version of Snappy.
  30. #ifndef UTIL_SNAPPY_OPENSOURCE_SNAPPY_STUBS_INTERNAL_H_
  31. #define UTIL_SNAPPY_OPENSOURCE_SNAPPY_STUBS_INTERNAL_H_
  32. #ifdef HAVE_CONFIG_H
  33. #include "config.h"
  34. #endif
  35. #include <string>
  36. #include <assert.h>
  37. #include <stdlib.h>
  38. #include <string.h>
  39. #ifdef HAVE_SYS_MMAN_H
  40. #include <sys/mman.h>
  41. #endif
  42. #include "snappy-stubs-public.h"
  43. #if defined(__x86_64__)
  44. // Enable 64-bit optimized versions of some routines.
  45. #define ARCH_K8 1
  46. #endif
  47. // Needed by OS X, among others.
  48. #ifndef MAP_ANONYMOUS
  49. #define MAP_ANONYMOUS MAP_ANON
  50. #endif
  51. // Pull in std::min, std::ostream, and the likes. This is safe because this
  52. // header file is never used from any public header files.
  53. using namespace std;
  54. // The size of an array, if known at compile-time.
  55. // Will give unexpected results if used on a pointer.
  56. // We undefine it first, since some compilers already have a definition.
  57. #ifdef ARRAYSIZE
  58. #undef ARRAYSIZE
  59. #endif
  60. #define ARRAYSIZE(a) (sizeof(a) / sizeof(*(a)))
  61. // Static prediction hints.
  62. #ifdef HAVE_BUILTIN_EXPECT
  63. #define PREDICT_FALSE(x) (__builtin_expect(x, 0))
  64. #define PREDICT_TRUE(x) (__builtin_expect(!!(x), 1))
  65. #else
  66. #define PREDICT_FALSE(x) x
  67. #define PREDICT_TRUE(x) x
  68. #endif
  69. // This is only used for recomputing the tag byte table used during
  70. // decompression; for simplicity we just remove it from the open-source
  71. // version (anyone who wants to regenerate it can just do the call
  72. // themselves within main()).
  73. #define DEFINE_bool(flag_name, default_value, description) \
  74. bool FLAGS_ ## flag_name = default_value
  75. #define DECLARE_bool(flag_name) \
  76. extern bool FLAGS_ ## flag_name
  77. namespace snappy {
  78. static const uint32 kuint32max = static_cast<uint32>(0xFFFFFFFF);
  79. static const int64 kint64max = static_cast<int64>(0x7FFFFFFFFFFFFFFFLL);
  80. // Potentially unaligned loads and stores.
  81. // x86 and PowerPC can simply do these loads and stores native.
  82. #if defined(__i386__) || defined(__x86_64__) || defined(__powerpc__)
  83. #define UNALIGNED_LOAD16(_p) (*reinterpret_cast<const uint16 *>(_p))
  84. #define UNALIGNED_LOAD32(_p) (*reinterpret_cast<const uint32 *>(_p))
  85. #define UNALIGNED_LOAD64(_p) (*reinterpret_cast<const uint64 *>(_p))
  86. #define UNALIGNED_STORE16(_p, _val) (*reinterpret_cast<uint16 *>(_p) = (_val))
  87. #define UNALIGNED_STORE32(_p, _val) (*reinterpret_cast<uint32 *>(_p) = (_val))
  88. #define UNALIGNED_STORE64(_p, _val) (*reinterpret_cast<uint64 *>(_p) = (_val))
  89. // ARMv7 and newer support native unaligned accesses, but only of 16-bit
  90. // and 32-bit values (not 64-bit); older versions either raise a fatal signal,
  91. // do an unaligned read and rotate the words around a bit, or do the reads very
  92. // slowly (trip through kernel mode). There's no simple #define that says just
  93. // “ARMv7 or higher”, so we have to filter away all ARMv5 and ARMv6
  94. // sub-architectures.
  95. //
  96. // This is a mess, but there's not much we can do about it.
  97. #elif defined(__arm__) && \
  98. !defined(__ARM_ARCH_4__) && \
  99. !defined(__ARM_ARCH_4T__) && \
  100. !defined(__ARM_ARCH_5__) && \
  101. !defined(__ARM_ARCH_5T__) && \
  102. !defined(__ARM_ARCH_5TE__) && \
  103. !defined(__ARM_ARCH_5TEJ__) && \
  104. !defined(__ARM_ARCH_6__) && \
  105. !defined(__ARM_ARCH_6J__) && \
  106. !defined(__ARM_ARCH_6K__) && \
  107. !defined(__ARM_ARCH_6Z__) && \
  108. !defined(__ARM_ARCH_6ZK__) && \
  109. !defined(__ARM_ARCH_6T2__)
  110. #define UNALIGNED_LOAD16(_p) (*reinterpret_cast<const uint16 *>(_p))
  111. #define UNALIGNED_LOAD32(_p) (*reinterpret_cast<const uint32 *>(_p))
  112. #define UNALIGNED_STORE16(_p, _val) (*reinterpret_cast<uint16 *>(_p) = (_val))
  113. #define UNALIGNED_STORE32(_p, _val) (*reinterpret_cast<uint32 *>(_p) = (_val))
  114. // TODO(user): NEON supports unaligned 64-bit loads and stores.
  115. // See if that would be more efficient on platforms supporting it,
  116. // at least for copies.
  117. inline uint64 UNALIGNED_LOAD64(const void *p) {
  118. uint64 t;
  119. memcpy(&t, p, sizeof t);
  120. return t;
  121. }
  122. inline void UNALIGNED_STORE64(void *p, uint64 v) {
  123. memcpy(p, &v, sizeof v);
  124. }
  125. #else
  126. // These functions are provided for architectures that don't support
  127. // unaligned loads and stores.
  128. inline uint16 UNALIGNED_LOAD16(const void *p) {
  129. uint16 t;
  130. memcpy(&t, p, sizeof t);
  131. return t;
  132. }
  133. inline uint32 UNALIGNED_LOAD32(const void *p) {
  134. uint32 t;
  135. memcpy(&t, p, sizeof t);
  136. return t;
  137. }
  138. inline uint64 UNALIGNED_LOAD64(const void *p) {
  139. uint64 t;
  140. memcpy(&t, p, sizeof t);
  141. return t;
  142. }
  143. inline void UNALIGNED_STORE16(void *p, uint16 v) {
  144. memcpy(p, &v, sizeof v);
  145. }
  146. inline void UNALIGNED_STORE32(void *p, uint32 v) {
  147. memcpy(p, &v, sizeof v);
  148. }
  149. inline void UNALIGNED_STORE64(void *p, uint64 v) {
  150. memcpy(p, &v, sizeof v);
  151. }
  152. #endif
  153. // This can be more efficient than UNALIGNED_LOAD64 + UNALIGNED_STORE64
  154. // on some platforms, in particular ARM.
  155. inline void UnalignedCopy64(const void *src, void *dst) {
  156. if (sizeof(void *) == 8) {
  157. UNALIGNED_STORE64(dst, UNALIGNED_LOAD64(src));
  158. } else {
  159. const char *src_char = reinterpret_cast<const char *>(src);
  160. char *dst_char = reinterpret_cast<char *>(dst);
  161. UNALIGNED_STORE32(dst_char, UNALIGNED_LOAD32(src_char));
  162. UNALIGNED_STORE32(dst_char + 4, UNALIGNED_LOAD32(src_char + 4));
  163. }
  164. }
  165. // The following guarantees declaration of the byte swap functions.
  166. #ifdef WORDS_BIGENDIAN
  167. #ifdef HAVE_SYS_BYTEORDER_H
  168. #include <sys/byteorder.h>
  169. #endif
  170. #ifdef HAVE_SYS_ENDIAN_H
  171. #include <sys/endian.h>
  172. #endif
  173. #ifdef _MSC_VER
  174. #include <stdlib.h>
  175. #define bswap_16(x) _byteswap_ushort(x)
  176. #define bswap_32(x) _byteswap_ulong(x)
  177. #define bswap_64(x) _byteswap_uint64(x)
  178. #elif defined(__APPLE__)
  179. // Mac OS X / Darwin features
  180. #include <libkern/OSByteOrder.h>
  181. #define bswap_16(x) OSSwapInt16(x)
  182. #define bswap_32(x) OSSwapInt32(x)
  183. #define bswap_64(x) OSSwapInt64(x)
  184. #elif defined(HAVE_BYTESWAP_H)
  185. #include <byteswap.h>
  186. #elif defined(bswap32)
  187. // FreeBSD defines bswap{16,32,64} in <sys/endian.h> (already #included).
  188. #define bswap_16(x) bswap16(x)
  189. #define bswap_32(x) bswap32(x)
  190. #define bswap_64(x) bswap64(x)
  191. #elif defined(BSWAP_64)
  192. // Solaris 10 defines BSWAP_{16,32,64} in <sys/byteorder.h> (already #included).
  193. #define bswap_16(x) BSWAP_16(x)
  194. #define bswap_32(x) BSWAP_32(x)
  195. #define bswap_64(x) BSWAP_64(x)
  196. #else
  197. inline uint16 bswap_16(uint16 x) {
  198. return (x << 8) | (x >> 8);
  199. }
  200. inline uint32 bswap_32(uint32 x) {
  201. x = ((x & 0xff00ff00UL) >> 8) | ((x & 0x00ff00ffUL) << 8);
  202. return (x >> 16) | (x << 16);
  203. }
  204. inline uint64 bswap_64(uint64 x) {
  205. x = ((x & 0xff00ff00ff00ff00ULL) >> 8) | ((x & 0x00ff00ff00ff00ffULL) << 8);
  206. x = ((x & 0xffff0000ffff0000ULL) >> 16) | ((x & 0x0000ffff0000ffffULL) << 16);
  207. return (x >> 32) | (x << 32);
  208. }
  209. #endif
  210. #endif // WORDS_BIGENDIAN
  211. // Convert to little-endian storage, opposite of network format.
  212. // Convert x from host to little endian: x = LittleEndian.FromHost(x);
  213. // convert x from little endian to host: x = LittleEndian.ToHost(x);
  214. //
  215. // Store values into unaligned memory converting to little endian order:
  216. // LittleEndian.Store16(p, x);
  217. //
  218. // Load unaligned values stored in little endian converting to host order:
  219. // x = LittleEndian.Load16(p);
  220. class LittleEndian {
  221. public:
  222. // Conversion functions.
  223. #ifdef WORDS_BIGENDIAN
  224. static uint16 FromHost16(uint16 x) { return bswap_16(x); }
  225. static uint16 ToHost16(uint16 x) { return bswap_16(x); }
  226. static uint32 FromHost32(uint32 x) { return bswap_32(x); }
  227. static uint32 ToHost32(uint32 x) { return bswap_32(x); }
  228. static bool IsLittleEndian() { return false; }
  229. #else // !defined(WORDS_BIGENDIAN)
  230. static uint16 FromHost16(uint16 x) { return x; }
  231. static uint16 ToHost16(uint16 x) { return x; }
  232. static uint32 FromHost32(uint32 x) { return x; }
  233. static uint32 ToHost32(uint32 x) { return x; }
  234. static bool IsLittleEndian() { return true; }
  235. #endif // !defined(WORDS_BIGENDIAN)
  236. // Functions to do unaligned loads and stores in little-endian order.
  237. static uint16 Load16(const void *p) {
  238. return ToHost16(UNALIGNED_LOAD16(p));
  239. }
  240. static void Store16(void *p, uint16 v) {
  241. UNALIGNED_STORE16(p, FromHost16(v));
  242. }
  243. static uint32 Load32(const void *p) {
  244. return ToHost32(UNALIGNED_LOAD32(p));
  245. }
  246. static void Store32(void *p, uint32 v) {
  247. UNALIGNED_STORE32(p, FromHost32(v));
  248. }
  249. };
  250. // Some bit-manipulation functions.
  251. class Bits {
  252. public:
  253. // Return floor(log2(n)) for positive integer n. Returns -1 iff n == 0.
  254. static int Log2Floor(uint32 n);
  255. // Return the first set least / most significant bit, 0-indexed. Returns an
  256. // undefined value if n == 0. FindLSBSetNonZero() is similar to ffs() except
  257. // that it's 0-indexed.
  258. static int FindLSBSetNonZero(uint32 n);
  259. static int FindLSBSetNonZero64(uint64 n);
  260. private:
  261. DISALLOW_COPY_AND_ASSIGN(Bits);
  262. };
  263. #ifdef HAVE_BUILTIN_CTZ
  264. inline int Bits::Log2Floor(uint32 n) {
  265. return n == 0 ? -1 : 31 ^ __builtin_clz(n);
  266. }
  267. inline int Bits::FindLSBSetNonZero(uint32 n) {
  268. return __builtin_ctz(n);
  269. }
  270. inline int Bits::FindLSBSetNonZero64(uint64 n) {
  271. return __builtin_ctzll(n);
  272. }
  273. #else // Portable versions.
  274. inline int Bits::Log2Floor(uint32 n) {
  275. if (n == 0)
  276. return -1;
  277. int log = 0;
  278. uint32 value = n;
  279. for (int i = 4; i >= 0; --i) {
  280. int shift = (1 << i);
  281. uint32 x = value >> shift;
  282. if (x != 0) {
  283. value = x;
  284. log += shift;
  285. }
  286. }
  287. assert(value == 1);
  288. return log;
  289. }
  290. inline int Bits::FindLSBSetNonZero(uint32 n) {
  291. int rc = 31;
  292. for (int i = 4, shift = 1 << 4; i >= 0; --i) {
  293. const uint32 x = n << shift;
  294. if (x != 0) {
  295. n = x;
  296. rc -= shift;
  297. }
  298. shift >>= 1;
  299. }
  300. return rc;
  301. }
  302. // FindLSBSetNonZero64() is defined in terms of FindLSBSetNonZero().
  303. inline int Bits::FindLSBSetNonZero64(uint64 n) {
  304. const uint32 bottombits = static_cast<uint32>(n);
  305. if (bottombits == 0) {
  306. // Bottom bits are zero, so scan in top bits
  307. return 32 + FindLSBSetNonZero(static_cast<uint32>(n >> 32));
  308. } else {
  309. return FindLSBSetNonZero(bottombits);
  310. }
  311. }
  312. #endif // End portable versions.
  313. // Variable-length integer encoding.
  314. class Varint {
  315. public:
  316. // Maximum lengths of varint encoding of uint32.
  317. static const int kMax32 = 5;
  318. // Attempts to parse a varint32 from a prefix of the bytes in [ptr,limit-1].
  319. // Never reads a character at or beyond limit. If a valid/terminated varint32
  320. // was found in the range, stores it in *OUTPUT and returns a pointer just
  321. // past the last byte of the varint32. Else returns NULL. On success,
  322. // "result <= limit".
  323. static const char* Parse32WithLimit(const char* ptr, const char* limit,
  324. uint32* OUTPUT);
  325. // REQUIRES "ptr" points to a buffer of length sufficient to hold "v".
  326. // EFFECTS Encodes "v" into "ptr" and returns a pointer to the
  327. // byte just past the last encoded byte.
  328. static char* Encode32(char* ptr, uint32 v);
  329. // EFFECTS Appends the varint representation of "value" to "*s".
  330. static void Append32(string* s, uint32 value);
  331. };
  332. inline const char* Varint::Parse32WithLimit(const char* p,
  333. const char* l,
  334. uint32* OUTPUT) {
  335. const unsigned char* ptr = reinterpret_cast<const unsigned char*>(p);
  336. const unsigned char* limit = reinterpret_cast<const unsigned char*>(l);
  337. uint32 b, result;
  338. if (ptr >= limit) return NULL;
  339. b = *(ptr++); result = b & 127; if (b < 128) goto done;
  340. if (ptr >= limit) return NULL;
  341. b = *(ptr++); result |= (b & 127) << 7; if (b < 128) goto done;
  342. if (ptr >= limit) return NULL;
  343. b = *(ptr++); result |= (b & 127) << 14; if (b < 128) goto done;
  344. if (ptr >= limit) return NULL;
  345. b = *(ptr++); result |= (b & 127) << 21; if (b < 128) goto done;
  346. if (ptr >= limit) return NULL;
  347. b = *(ptr++); result |= (b & 127) << 28; if (b < 16) goto done;
  348. return NULL; // Value is too long to be a varint32
  349. done:
  350. *OUTPUT = result;
  351. return reinterpret_cast<const char*>(ptr);
  352. }
  353. inline char* Varint::Encode32(char* sptr, uint32 v) {
  354. // Operate on characters as unsigneds
  355. unsigned char* ptr = reinterpret_cast<unsigned char*>(sptr);
  356. static const int B = 128;
  357. if (v < (1<<7)) {
  358. *(ptr++) = v;
  359. } else if (v < (1<<14)) {
  360. *(ptr++) = v | B;
  361. *(ptr++) = v>>7;
  362. } else if (v < (1<<21)) {
  363. *(ptr++) = v | B;
  364. *(ptr++) = (v>>7) | B;
  365. *(ptr++) = v>>14;
  366. } else if (v < (1<<28)) {
  367. *(ptr++) = v | B;
  368. *(ptr++) = (v>>7) | B;
  369. *(ptr++) = (v>>14) | B;
  370. *(ptr++) = v>>21;
  371. } else {
  372. *(ptr++) = v | B;
  373. *(ptr++) = (v>>7) | B;
  374. *(ptr++) = (v>>14) | B;
  375. *(ptr++) = (v>>21) | B;
  376. *(ptr++) = v>>28;
  377. }
  378. return reinterpret_cast<char*>(ptr);
  379. }
  380. // If you know the internal layout of the std::string in use, you can
  381. // replace this function with one that resizes the string without
  382. // filling the new space with zeros (if applicable) --
  383. // it will be non-portable but faster.
  384. inline void STLStringResizeUninitialized(string* s, size_t new_size) {
  385. s->resize(new_size);
  386. }
  387. // Return a mutable char* pointing to a string's internal buffer,
  388. // which may not be null-terminated. Writing through this pointer will
  389. // modify the string.
  390. //
  391. // string_as_array(&str)[i] is valid for 0 <= i < str.size() until the
  392. // next call to a string method that invalidates iterators.
  393. //
  394. // As of 2006-04, there is no standard-blessed way of getting a
  395. // mutable reference to a string's internal buffer. However, issue 530
  396. // (http://www.open-std.org/JTC1/SC22/WG21/docs/lwg-defects.html#530)
  397. // proposes this as the method. It will officially be part of the standard
  398. // for C++0x. This should already work on all current implementations.
  399. inline char* string_as_array(string* str) {
  400. return str->empty() ? NULL : &*str->begin();
  401. }
  402. } // namespace snappy
  403. #endif // UTIL_SNAPPY_OPENSOURCE_SNAPPY_STUBS_INTERNAL_H_