crc_casts.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2010 Google Inc. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Casting between integers and compound CRC types.
  15. #ifndef CRCUTIL_CRC_CASTS_H_
  16. #define CRCUTIL_CRC_CASTS_H_
  17. #include "base_types.h" // uint8, uint64
  18. #include "platform.h" // __forceinline
  19. namespace crcutil {
  20. // Downcasts a value of (oftentimes larger) Crc type to (smaller base integer)
  21. // Result type, enabling specialized downcasts implemented by "large integer"
  22. // classes (e.g. uint128_sse2).
  23. template<typename Crc, typename Result>
  24. __forceinline Result Downcast(const Crc &x) {
  25. return static_cast<Result>(x);
  26. }
  27. // Extracts 8 least significant bits from a value of Crc type.
  28. #define TO_BYTE(x) Downcast<Crc, uint8>(x)
  29. // Converts a pair of uint64 bit values into single value of CRC type.
  30. // It is caller's responsibility to ensure that the input is correct.
  31. template<typename Crc>
  32. __forceinline Crc CrcFromUint64(uint64 lo, uint64 hi = 0) {
  33. if (sizeof(Crc) <= sizeof(lo)) {
  34. return static_cast<Crc>(lo);
  35. } else {
  36. // static_cast to keep compiler happy.
  37. Crc result = static_cast<Crc>(hi);
  38. result = SHIFT_LEFT_SAFE(result, 8 * sizeof(lo));
  39. result ^= lo;
  40. return result;
  41. }
  42. }
  43. // Converts Crc value to a pair of uint64 values.
  44. template<typename Crc>
  45. __forceinline void Uint64FromCrc(const Crc &crc,
  46. uint64 *lo, uint64 *hi = NULL) {
  47. if (sizeof(*lo) >= sizeof(crc)) {
  48. *lo = Downcast<Crc, uint64>(crc);
  49. if (hi != NULL) {
  50. *hi = 0;
  51. }
  52. } else {
  53. *lo = Downcast<Crc, uint64>(crc);
  54. *hi = Downcast<Crc, uint64>(SHIFT_RIGHT_SAFE(crc, 8 * sizeof(lo)));
  55. }
  56. }
  57. } // namespace crcutil
  58. #endif // CRCUTIL_CRC_CASTS_H_