status.cc 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. #include "libhdfs++/status.h"
  19. #include <cassert>
  20. #include <cstring>
  21. namespace hdfs {
  22. Status::Status(int code, const char *msg1)
  23. : state_(ConstructState(code, msg1, nullptr))
  24. {}
  25. Status::Status(int code, const char *msg1, const char *msg2)
  26. : state_(ConstructState(code, msg1, msg2))
  27. {}
  28. const char *Status::ConstructState(int code, const char *msg1, const char *msg2) {
  29. assert(code != kOk);
  30. const uint32_t len1 = strlen(msg1);
  31. const uint32_t len2 = msg2 ? strlen(msg2) : 0;
  32. const uint32_t size = len1 + (len2 ? (2 + len2) : 0);
  33. char* result = new char[size + 8 + 2];
  34. *reinterpret_cast<uint32_t*>(result) = size;
  35. *reinterpret_cast<uint32_t*>(result + 4) = code;
  36. memcpy(result + 8, msg1, len1);
  37. if (len2) {
  38. result[8 + len1] = ':';
  39. result[9 + len1] = ' ';
  40. memcpy(result + 10 + len1, msg2, len2);
  41. }
  42. return result;
  43. }
  44. std::string Status::ToString() const {
  45. if (!state_) {
  46. return "OK";
  47. } else {
  48. uint32_t length = *reinterpret_cast<const uint32_t*>(state_);
  49. return std::string(state_ + 8, length);
  50. }
  51. }
  52. const char* Status::CopyState(const char* state) {
  53. uint32_t size;
  54. memcpy(&size, state, sizeof(size));
  55. char* result = new char[size + 8];
  56. memcpy(result, state, size + 8);
  57. return result;
  58. }
  59. }