小组成员:姚凯文(kevinyao0901),姜嘉琪
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
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 "leveldb/env.h"
  10. #include "leveldb/slice.h"
  11. namespace leveldb {
  12. void AppendNumberTo(std::string* str, uint64_t num) {
  13. char buf[30];
  14. snprintf(buf, sizeof(buf), "%llu", (unsigned long long) num);
  15. str->append(buf);
  16. }
  17. void AppendEscapedStringTo(std::string* str, const Slice& value) {
  18. for (size_t i = 0; i < value.size(); i++) {
  19. char c = value[i];
  20. if (c >= ' ' && c <= '~') {
  21. str->push_back(c);
  22. } else {
  23. char buf[10];
  24. snprintf(buf, sizeof(buf), "\\x%02x",
  25. static_cast<unsigned int>(c) & 0xff);
  26. str->append(buf);
  27. }
  28. }
  29. }
  30. std::string NumberToString(uint64_t num) {
  31. std::string r;
  32. AppendNumberTo(&r, num);
  33. return r;
  34. }
  35. std::string EscapeString(const Slice& value) {
  36. std::string r;
  37. AppendEscapedStringTo(&r, value);
  38. return r;
  39. }
  40. bool ConsumeDecimalNumber(Slice* in, uint64_t* val) {
  41. // Constants that will be optimized away.
  42. constexpr const uint64_t kMaxUint64 = std::numeric_limits<uint64_t>::max();
  43. constexpr const char kLastDigitOfMaxUint64 =
  44. '0' + static_cast<char>(kMaxUint64 % 10);
  45. uint64_t value = 0;
  46. // reinterpret_cast-ing from char* to unsigned char* to avoid signedness.
  47. const unsigned char* start =
  48. reinterpret_cast<const unsigned char*>(in->data());
  49. const unsigned char* end = start + in->size();
  50. const unsigned char* current = start;
  51. for (; current != end; ++current) {
  52. const unsigned char ch = *current;
  53. if (ch < '0' || ch > '9')
  54. break;
  55. // Overflow check.
  56. // kMaxUint64 / 10 is also constant and will be optimized away.
  57. if (value > kMaxUint64 / 10 ||
  58. (value == kMaxUint64 / 10 && ch > kLastDigitOfMaxUint64)) {
  59. return false;
  60. }
  61. value = (value * 10) + (ch - '0');
  62. }
  63. *val = value;
  64. const size_t digits_consumed = current - start;
  65. in->remove_prefix(digits_consumed);
  66. return digits_consumed != 0;
  67. }
  68. } // namespace leveldb