1 // Copyright (c) 2016 The WebM project authors. All Rights Reserved.
2 //
3 // Use of this source code is governed by a BSD-style license
4 // that can be found in the LICENSE file in the root of the source
5 // tree. An additional intellectual property rights grant can be found
6 // in the file PATENTS. All contributing project authors may
7 // be found in the AUTHORS file in the root of the source tree.
8 #include "src/float_parser.h"
9
10 #include <cassert>
11 #include <cstdint>
12 #include <cstring>
13 #include <limits>
14
15 #include "src/parser_utils.h"
16 #include "webm/element.h"
17 #include "webm/reader.h"
18 #include "webm/status.h"
19
20 namespace webm {
21
FloatParser(double default_value)22 FloatParser::FloatParser(double default_value)
23 : default_value_(default_value) {}
24
Init(const ElementMetadata & metadata,std::uint64_t max_size)25 Status FloatParser::Init(const ElementMetadata& metadata,
26 std::uint64_t max_size) {
27 assert(metadata.size == kUnknownElementSize || metadata.size <= max_size);
28
29 if (metadata.size == 0) {
30 value_ = default_value_;
31 } else if (metadata.size == 4 || metadata.size == 8) {
32 uint64_value_ = 0;
33 } else {
34 return Status(Status::kInvalidElementSize);
35 }
36
37 num_bytes_remaining_ = static_cast<int>(metadata.size);
38 use_32_bits_ = metadata.size == 4;
39
40 return Status(Status::kOkCompleted);
41 }
42
Feed(Callback * callback,Reader * reader,std::uint64_t * num_bytes_read)43 Status FloatParser::Feed(Callback* callback, Reader* reader,
44 std::uint64_t* num_bytes_read) {
45 assert(callback != nullptr);
46 assert(reader != nullptr);
47 assert(num_bytes_read != nullptr);
48
49 if (num_bytes_remaining_ == 0) {
50 return Status(Status::kOkCompleted);
51 }
52
53 const Status status = AccumulateIntegerBytes(num_bytes_remaining_, reader,
54 &uint64_value_, num_bytes_read);
55 num_bytes_remaining_ -= static_cast<int>(*num_bytes_read);
56
57 if (num_bytes_remaining_ == 0) {
58 if (use_32_bits_) {
59 static_assert(std::numeric_limits<float>::is_iec559,
60 "Your compiler does not support 32-bit IEC 559/IEEE 754 "
61 "floating point types");
62 std::uint32_t uint32_value = static_cast<std::uint32_t>(uint64_value_);
63 float float32_value;
64 std::memcpy(&float32_value, &uint32_value, 4);
65 value_ = float32_value;
66 } else {
67 static_assert(std::numeric_limits<double>::is_iec559,
68 "Your compiler does not support 64-bit IEC 559/IEEE 754 "
69 "floating point types");
70 std::memcpy(&value_, &uint64_value_, 8);
71 }
72 }
73
74 return status;
75 }
76
77 } // namespace webm
78