73 satır
1.8 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. uint64_t v = 0;
  42. int digits = 0;
  43. while (!in->empty()) {
  44. char c = (*in)[0];
  45. if (c >= '0' && c <= '9') {
  46. ++digits;
  47. // |delta| intentionally unit64_t to avoid Android crash (see log).
  48. const uint64_t delta = (c - '0');
  49. static const uint64_t kMaxUint64 = ~static_cast<uint64_t>(0);
  50. if (v > kMaxUint64/10 ||
  51. (v == kMaxUint64/10 && delta > kMaxUint64%10)) {
  52. // Overflow
  53. return false;
  54. }
  55. v = (v * 10) + delta;
  56. in->remove_prefix(1);
  57. } else {
  58. break;
  59. }
  60. }
  61. *val = v;
  62. return (digits > 0);
  63. }
  64. } // namespace leveldb