小组成员: 曹可心-10223903406 朴祉燕-10224602413
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

84 řádky
2.2 KiB

  1. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  4. #include "util/logging.h"
  5. #include <errno.h>
  6. #include <stdarg.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <limits>
  10. #include "leveldb/env.h"
  11. #include "leveldb/slice.h"
  12. namespace leveldb {
  13. void AppendNumberTo(std::string* str, uint64_t num) {
  14. char buf[30];
  15. snprintf(buf, sizeof(buf), "%llu", (unsigned long long) num);
  16. str->append(buf);
  17. }
  18. void AppendEscapedStringTo(std::string* str, const Slice& value) {
  19. for (size_t i = 0; i < value.size(); i++) {
  20. char c = value[i];
  21. if (c >= ' ' && c <= '~') {
  22. str->push_back(c);
  23. } else {
  24. char buf[10];
  25. snprintf(buf, sizeof(buf), "\\x%02x",
  26. static_cast<unsigned int>(c) & 0xff);
  27. str->append(buf);
  28. }
  29. }
  30. }
  31. std::string NumberToString(uint64_t num) {
  32. std::string r;
  33. AppendNumberTo(&r, num);
  34. return r;
  35. }
  36. std::string EscapeString(const Slice& value) {
  37. std::string r;
  38. AppendEscapedStringTo(&r, value);
  39. return r;
  40. }
  41. bool ConsumeDecimalNumber(Slice* in, uint64_t* val) {
  42. // Constants that will be optimized away.
  43. constexpr const uint64_t kMaxUint64 = std::numeric_limits<uint64_t>::max();
  44. constexpr const char kLastDigitOfMaxUint64 =
  45. '0' + static_cast<char>(kMaxUint64 % 10);
  46. uint64_t value = 0;
  47. // reinterpret_cast-ing from char* to unsigned char* to avoid signedness.
  48. const unsigned char* start =
  49. reinterpret_cast<const unsigned char*>(in->data());
  50. const unsigned char* end = start + in->size();
  51. const unsigned char* current = start;
  52. for (; current != end; ++current) {
  53. const unsigned char ch = *current;
  54. if (ch < '0' || ch > '9')
  55. break;
  56. // Overflow check.
  57. // kMaxUint64 / 10 is also constant and will be optimized away.
  58. if (value > kMaxUint64 / 10 ||
  59. (value == kMaxUint64 / 10 && ch > kLastDigitOfMaxUint64)) {
  60. return false;
  61. }
  62. value = (value * 10) + (ch - '0');
  63. }
  64. *val = value;
  65. const size_t digits_consumed = current - start;
  66. in->remove_prefix(digits_consumed);
  67. return digits_consumed != 0;
  68. }
  69. } // namespace leveldb