1 /*
2 *
3 * Copyright 2017 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19 #include <grpc/support/port_platform.h>
20
21 #include "src/core/lib/transport/status_metadata.h"
22
23 #include "src/core/lib/slice/slice_string_helpers.h"
24 #include "src/core/lib/transport/static_metadata.h"
25
26 /* we offset status by a small amount when storing it into transport metadata
27 as metadata cannot store a 0 value (which is used as OK for grpc_status_codes
28 */
29 #define STATUS_OFFSET 1
30
destroy_status(void *)31 static void destroy_status(void* /*ignored*/) {}
32
grpc_get_status_code_from_metadata(grpc_mdelem md)33 grpc_status_code grpc_get_status_code_from_metadata(grpc_mdelem md) {
34 if (grpc_mdelem_static_value_eq(md, GRPC_MDELEM_GRPC_STATUS_0)) {
35 return GRPC_STATUS_OK;
36 }
37 if (grpc_mdelem_static_value_eq(md, GRPC_MDELEM_GRPC_STATUS_1)) {
38 return GRPC_STATUS_CANCELLED;
39 }
40 if (grpc_mdelem_static_value_eq(md, GRPC_MDELEM_GRPC_STATUS_2)) {
41 return GRPC_STATUS_UNKNOWN;
42 }
43 void* user_data = grpc_mdelem_get_user_data(md, destroy_status);
44 if (user_data != nullptr) {
45 return static_cast<grpc_status_code>(reinterpret_cast<intptr_t>(user_data) -
46 STATUS_OFFSET);
47 }
48 uint32_t status;
49 if (!grpc_parse_slice_to_uint32(GRPC_MDVALUE(md), &status)) {
50 status = GRPC_STATUS_UNKNOWN; /* could not parse status code */
51 }
52 grpc_mdelem_set_user_data(md, destroy_status,
53 reinterpret_cast<void*>(status + STATUS_OFFSET));
54 return static_cast<grpc_status_code>(status);
55 }
56
grpc_get_reffed_status_elem_slowpath(int status_code)57 grpc_mdelem grpc_get_reffed_status_elem_slowpath(int status_code) {
58 char tmp[GPR_LTOA_MIN_BUFSIZE];
59 gpr_ltoa(status_code, tmp);
60 return grpc_mdelem_from_slices(GRPC_MDSTR_GRPC_STATUS,
61 grpc_core::UnmanagedMemorySlice(tmp));
62 }
63