xref: /aosp_15_r20/external/tink/python/tink/cc/pybind/output_stream_adapter.cc (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
1 // Copyright 2019 Google Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15 ///////////////////////////////////////////////////////////////////////////////
16 #include "tink/cc/pybind/output_stream_adapter.h"
17 
18 #include <algorithm>
19 #include <string>
20 #include <utility>
21 
22 #include "pybind11/pybind11.h"
23 #include "tink/cc/output_stream_adapter.h"
24 #include "tink/cc/pybind/tink_exception.h"
25 
26 namespace crypto {
27 namespace tink {
28 
29 using pybind11::google_tink::TinkException;
30 
PybindRegisterOutputStreamAdapter(pybind11::module * module)31 void PybindRegisterOutputStreamAdapter(pybind11::module* module) {
32   namespace py = pybind11;
33   py::module& m = *module;
34 
35   // TODO(b/146492561): Reduce the number of complicated lambdas.
36   py::class_<OutputStreamAdapter>(m, "OutputStreamAdapter")
37       .def(
38           "write",
39           [](OutputStreamAdapter* self, const py::bytes& data) -> int64_t {
40             util::StatusOr<int64_t> result = self->Write(std::string(data));
41             if (!result.ok()) {
42               throw TinkException(result.status());
43             }
44             return *std::move(result);
45           },
46           py::arg("data"))
47       .def("close", [](OutputStreamAdapter* self) -> void {
48         util::Status result = self->Close();
49         if (!result.ok()) {
50           throw TinkException(result);
51         }
52       });
53 }
54 
55 }  // namespace tink
56 }  // namespace crypto
57