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
17 #include "tink/cc/pybind/input_stream_adapter.h"
18
19 #include <string>
20 #include <utility>
21
22 #include "pybind11/pybind11.h"
23 #include "tink/cc/input_stream_adapter.h"
24 #include "tink/cc/pybind/tink_exception.h"
25
26 namespace crypto {
27 namespace tink {
28
29 namespace {
30
31 class TinkStreamFinishedException : public std::exception {
32 public:
TinkStreamFinishedException(const crypto::tink::util::Status & status)33 explicit TinkStreamFinishedException(const crypto::tink::util::Status& status)
34 : error_code_(static_cast<int>(status.code())),
35 what_(status.ToString()) {}
36
error_code() const37 int error_code() const { return error_code_; }
38
what() const39 const char* what() const noexcept override { return what_.c_str(); }
40
41 private:
42 int error_code_;
43 std::string what_;
44 };
45
46 } // namespace
47
48 using pybind11::google_tink::TinkException;
49
PybindRegisterInputStreamAdapter(pybind11::module * module)50 void PybindRegisterInputStreamAdapter(pybind11::module* module) {
51 namespace py = pybind11;
52 py::module& m = *module;
53
54 py::register_exception<TinkStreamFinishedException>(
55 m, "PythonTinkStreamFinishedException");
56
57 // TODO(b/146492561): Reduce the number of complicated lambdas.
58 py::class_<InputStreamAdapter>(m, "InputStreamAdapter")
59 .def(
60 "read",
61 [](InputStreamAdapter* self, int64_t size) -> py::bytes {
62 util::StatusOr<std::string> read_result = self->Read(size);
63 if (read_result.status().code() == absl::StatusCode::kOutOfRange) {
64 throw TinkStreamFinishedException(
65 std::move(read_result).status());
66 }
67 if (!read_result.ok()) {
68 throw TinkException(read_result.status());
69 }
70 return *std::move(read_result);
71 },
72 py::arg("size"));
73 }
74
75 } // namespace tink
76 } // namespace crypto
77