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