1 // Copyright 2016 PDFium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
6 
7 #include "core/fpdfapi/parser/cpdf_number.h"
8 #include "core/fxcrt/fx_stream.h"
9 #include "third_party/base/ptr_util.h"
10 
CPDF_Number()11 CPDF_Number::CPDF_Number() : m_bInteger(true), m_Integer(0) {}
12 
CPDF_Number(int value)13 CPDF_Number::CPDF_Number(int value) : m_bInteger(true), m_Integer(value) {}
14 
CPDF_Number(float value)15 CPDF_Number::CPDF_Number(float value) : m_bInteger(false), m_Float(value) {}
16 
CPDF_Number(const ByteStringView & str)17 CPDF_Number::CPDF_Number(const ByteStringView& str)
18     : m_bInteger(FX_atonum(str, &m_Integer)) {}
19 
~CPDF_Number()20 CPDF_Number::~CPDF_Number() {}
21 
GetType() const22 CPDF_Object::Type CPDF_Number::GetType() const {
23   return NUMBER;
24 }
25 
Clone() const26 std::unique_ptr<CPDF_Object> CPDF_Number::Clone() const {
27   return m_bInteger ? pdfium::MakeUnique<CPDF_Number>(m_Integer)
28                     : pdfium::MakeUnique<CPDF_Number>(m_Float);
29 }
30 
GetNumber() const31 float CPDF_Number::GetNumber() const {
32   return m_bInteger ? static_cast<float>(m_Integer) : m_Float;
33 }
34 
GetInteger() const35 int CPDF_Number::GetInteger() const {
36   return m_bInteger ? m_Integer : static_cast<int>(m_Float);
37 }
38 
IsNumber() const39 bool CPDF_Number::IsNumber() const {
40   return true;
41 }
42 
AsNumber()43 CPDF_Number* CPDF_Number::AsNumber() {
44   return this;
45 }
46 
AsNumber() const47 const CPDF_Number* CPDF_Number::AsNumber() const {
48   return this;
49 }
50 
SetString(const ByteString & str)51 void CPDF_Number::SetString(const ByteString& str) {
52   m_bInteger = FX_atonum(str.AsStringView(), &m_Integer);
53 }
54 
GetString() const55 ByteString CPDF_Number::GetString() const {
56   return m_bInteger ? ByteString::FormatInteger(m_Integer)
57                     : ByteString::FormatFloat(m_Float);
58 }
59 
WriteTo(IFX_ArchiveStream * archive) const60 bool CPDF_Number::WriteTo(IFX_ArchiveStream* archive) const {
61   return archive->WriteString(" ") &&
62          archive->WriteString(GetString().AsStringView());
63 }
64