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