1 /*
2 * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11 #include "modules/audio_processing/test/protobuf_utils.h"
12
13 #include <memory>
14
15 #include "rtc_base/system/arch.h"
16
17 namespace {
18 // Allocates new memory in the memory owned by the unique_ptr to fit the raw
19 // message and returns the number of bytes read when having a string stream as
20 // input.
ReadMessageBytesFromString(std::stringstream * input,std::unique_ptr<uint8_t[]> * bytes)21 size_t ReadMessageBytesFromString(std::stringstream* input,
22 std::unique_ptr<uint8_t[]>* bytes) {
23 int32_t size = 0;
24 input->read(reinterpret_cast<char*>(&size), sizeof(int32_t));
25 int32_t size_read = input->gcount();
26 if (size_read != sizeof(int32_t))
27 return 0;
28 if (size <= 0)
29 return 0;
30
31 *bytes = std::make_unique<uint8_t[]>(size);
32 input->read(reinterpret_cast<char*>(bytes->get()),
33 size * sizeof((*bytes)[0]));
34 size_read = input->gcount();
35 return size_read == size ? size : 0;
36 }
37 } // namespace
38
39 namespace webrtc {
40
ReadMessageBytesFromFile(FILE * file,std::unique_ptr<uint8_t[]> * bytes)41 size_t ReadMessageBytesFromFile(FILE* file, std::unique_ptr<uint8_t[]>* bytes) {
42 // The "wire format" for the size is little-endian. Assume we're running on
43 // a little-endian machine.
44 #ifndef WEBRTC_ARCH_LITTLE_ENDIAN
45 #error "Need to convert messsage from little-endian."
46 #endif
47 int32_t size = 0;
48 if (fread(&size, sizeof(size), 1, file) != 1)
49 return 0;
50 if (size <= 0)
51 return 0;
52
53 *bytes = std::make_unique<uint8_t[]>(size);
54 return fread(bytes->get(), sizeof((*bytes)[0]), size, file);
55 }
56
57 // Returns true on success, false on error or end-of-file.
ReadMessageFromFile(FILE * file,MessageLite * msg)58 bool ReadMessageFromFile(FILE* file, MessageLite* msg) {
59 std::unique_ptr<uint8_t[]> bytes;
60 size_t size = ReadMessageBytesFromFile(file, &bytes);
61 if (!size)
62 return false;
63
64 msg->Clear();
65 return msg->ParseFromArray(bytes.get(), size);
66 }
67
68 // Returns true on success, false on error or end of string stream.
ReadMessageFromString(std::stringstream * input,MessageLite * msg)69 bool ReadMessageFromString(std::stringstream* input, MessageLite* msg) {
70 std::unique_ptr<uint8_t[]> bytes;
71 size_t size = ReadMessageBytesFromString(input, &bytes);
72 if (!size)
73 return false;
74
75 msg->Clear();
76 return msg->ParseFromArray(bytes.get(), size);
77 }
78
79 } // namespace webrtc
80