1 //
2 //
3 // Copyright 2015 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 <vector>
20 
21 #include <grpc/byte_buffer.h>
22 #include <grpc/byte_buffer_reader.h>
23 #include <grpc/grpc.h>
24 #include <grpc/impl/compression_types.h>
25 #include <grpc/slice.h>
26 #include <grpcpp/support/byte_buffer.h>
27 #include <grpcpp/support/slice.h>
28 #include <grpcpp/support/status.h>
29 
30 namespace grpc {
31 
TrySingleSlice(Slice * slice) const32 Status ByteBuffer::TrySingleSlice(Slice* slice) const {
33   if (!buffer_) {
34     return Status(StatusCode::FAILED_PRECONDITION, "Buffer not initialized");
35   }
36   if ((buffer_->type == GRPC_BB_RAW) &&
37       (buffer_->data.raw.compression == GRPC_COMPRESS_NONE) &&
38       (buffer_->data.raw.slice_buffer.count == 1)) {
39     grpc_slice internal_slice = buffer_->data.raw.slice_buffer.slices[0];
40     *slice = Slice(internal_slice, Slice::ADD_REF);
41     return Status::OK;
42   } else {
43     return Status(StatusCode::FAILED_PRECONDITION,
44                   "Buffer isn't made up of a single uncompressed slice.");
45   }
46 }
47 
DumpToSingleSlice(Slice * slice) const48 Status ByteBuffer::DumpToSingleSlice(Slice* slice) const {
49   if (!buffer_) {
50     return Status(StatusCode::FAILED_PRECONDITION, "Buffer not initialized");
51   }
52   grpc_byte_buffer_reader reader;
53   if (!grpc_byte_buffer_reader_init(&reader, buffer_)) {
54     return Status(StatusCode::INTERNAL,
55                   "Couldn't initialize byte buffer reader");
56   }
57   grpc_slice s = grpc_byte_buffer_reader_readall(&reader);
58   *slice = Slice(s, Slice::STEAL_REF);
59   grpc_byte_buffer_reader_destroy(&reader);
60   return Status::OK;
61 }
62 
Dump(std::vector<Slice> * slices) const63 Status ByteBuffer::Dump(std::vector<Slice>* slices) const {
64   slices->clear();
65   if (!buffer_) {
66     return Status(StatusCode::FAILED_PRECONDITION, "Buffer not initialized");
67   }
68   grpc_byte_buffer_reader reader;
69   if (!grpc_byte_buffer_reader_init(&reader, buffer_)) {
70     return Status(StatusCode::INTERNAL,
71                   "Couldn't initialize byte buffer reader");
72   }
73   grpc_slice s;
74   while (grpc_byte_buffer_reader_next(&reader, &s)) {
75     slices->push_back(Slice(s, Slice::STEAL_REF));
76   }
77   grpc_byte_buffer_reader_destroy(&reader);
78   return Status::OK;
79 }
80 
81 }  // namespace grpc
82