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