1 /*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "perfetto/base/status.h"
18
19 #include <stdarg.h>
20 #include <algorithm>
21
22 namespace perfetto {
23 namespace base {
24
ErrStatus(const char * format,...)25 Status ErrStatus(const char* format, ...) {
26 char buffer[1024];
27 va_list ap;
28 va_start(ap, format);
29 vsnprintf(buffer, sizeof(buffer), format, ap);
30 va_end(ap);
31 Status status(buffer);
32 return status;
33 }
34
GetPayload(std::string_view type_url) const35 std::optional<std::string_view> Status::GetPayload(
36 std::string_view type_url) const {
37 if (ok()) {
38 return std::nullopt;
39 }
40 for (const auto& kv : payloads_) {
41 if (kv.type_url == type_url) {
42 return kv.payload;
43 }
44 }
45 return std::nullopt;
46 }
47
SetPayload(std::string_view type_url,std::string value)48 void Status::SetPayload(std::string_view type_url, std::string value) {
49 if (ok()) {
50 return;
51 }
52 for (auto& kv : payloads_) {
53 if (kv.type_url == type_url) {
54 kv.payload = value;
55 return;
56 }
57 }
58 payloads_.push_back(Payload{std::string(type_url), std::move(value)});
59 }
60
ErasePayload(std::string_view type_url)61 bool Status::ErasePayload(std::string_view type_url) {
62 if (ok()) {
63 return false;
64 }
65 auto it = std::remove_if(
66 payloads_.begin(), payloads_.end(),
67 [type_url](const Payload& p) { return p.type_url == type_url; });
68 bool erased = it != payloads_.end();
69 payloads_.erase(it, payloads_.end());
70 return erased;
71 }
72
73 } // namespace base
74 } // namespace perfetto
75