xref: /aosp_15_r20/external/tink/cc/util/input_stream_util.cc (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
1 // Copyright 2019 Google LLC
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/util/input_stream_util.h"
18 
19 #include <algorithm>
20 #include <string>
21 
22 #include "absl/algorithm/container.h"
23 #include "absl/strings/str_cat.h"
24 #include "absl/types/span.h"
25 #include "tink/input_stream.h"
26 #include "tink/util/statusor.h"
27 
28 namespace crypto {
29 namespace tink {
30 
31 namespace {
32 template <typename Result>
ReadBytesFromStreamImpl(int num_bytes,InputStream * input_stream)33 util::StatusOr<Result> ReadBytesFromStreamImpl(int num_bytes,
34                                                InputStream* input_stream) {
35   const void* buffer;
36   Result result;
37   if (num_bytes > 0) {
38     result.resize(num_bytes);
39   }
40   int num_bytes_read = 0;
41 
42   while (num_bytes_read < num_bytes) {
43     auto next_result = input_stream->Next(&buffer);
44     if (!next_result.ok()) return next_result.status();
45 
46     int num_bytes_in_chunk = next_result.value();
47     int num_bytes_to_copy =
48         std::min(num_bytes - num_bytes_read, num_bytes_in_chunk);
49     absl::c_copy(absl::MakeSpan(reinterpret_cast<const char*>(buffer),
50                                 num_bytes_to_copy),
51                  result.begin() + num_bytes_read);
52     input_stream->BackUp(num_bytes_in_chunk - num_bytes_to_copy);
53     num_bytes_read += num_bytes_to_copy;
54   }
55   return result;
56 }
57 }  // namespace
58 
ReadBytesFromStream(int num_bytes,InputStream * input_stream)59 util::StatusOr<std::string> ReadBytesFromStream(int num_bytes,
60                                                 InputStream* input_stream) {
61   return ReadBytesFromStreamImpl<std::string>(num_bytes, input_stream);
62 }
63 
ReadSecretBytesFromStream(int num_bytes,InputStream * input_stream)64 util::StatusOr<util::SecretData> ReadSecretBytesFromStream(
65     int num_bytes, InputStream* input_stream) {
66   return ReadBytesFromStreamImpl<util::SecretData>(num_bytes, input_stream);
67 }
68 
69 }  // namespace tink
70 }  // namespace crypto
71