作者: 韩晨旭 10225101440 李畅 10225102463

77 lignes
2.0 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 "leveldb/status.h"
  5. #include <cstdio>
  6. #include "port/port.h"
  7. namespace leveldb {
  8. const char* Status::CopyState(const char* state) {
  9. uint32_t size;
  10. std::memcpy(&size, state, sizeof(size));
  11. char* result = new char[size + 5];
  12. std::memcpy(result, state, size + 5);
  13. return result;
  14. }
  15. Status::Status(Code code, const Slice& msg, const Slice& msg2) {
  16. assert(code != kOk);
  17. const uint32_t len1 = static_cast<uint32_t>(msg.size());
  18. const uint32_t len2 = static_cast<uint32_t>(msg2.size());
  19. const uint32_t size = len1 + (len2 ? (2 + len2) : 0);
  20. char* result = new char[size + 5];
  21. std::memcpy(result, &size, sizeof(size));
  22. result[4] = static_cast<char>(code);
  23. std::memcpy(result + 5, msg.data(), len1);
  24. if (len2) {
  25. result[5 + len1] = ':';
  26. result[6 + len1] = ' ';
  27. std::memcpy(result + 7 + len1, msg2.data(), len2);
  28. }
  29. state_ = result;
  30. }
  31. std::string Status::ToString() const {
  32. if (state_ == nullptr) {
  33. return "OK";
  34. } else {
  35. char tmp[30];
  36. const char* type;
  37. switch (code()) {
  38. case kOk:
  39. type = "OK";
  40. break;
  41. case kNotFound:
  42. type = "NotFound: ";
  43. break;
  44. case kCorruption:
  45. type = "Corruption: ";
  46. break;
  47. case kNotSupported:
  48. type = "Not implemented: ";
  49. break;
  50. case kInvalidArgument:
  51. type = "Invalid argument: ";
  52. break;
  53. case kIOError:
  54. type = "IO error: ";
  55. break;
  56. default:
  57. std::snprintf(tmp, sizeof(tmp),
  58. "Unknown code(%d): ", static_cast<int>(code()));
  59. type = tmp;
  60. break;
  61. }
  62. std::string result(type);
  63. uint32_t length;
  64. std::memcpy(&length, state_, sizeof(length));
  65. result.append(state_ + 5, length);
  66. return result;
  67. }
  68. }
  69. } // namespace leveldb