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_string.h"
8
9 #include <utility>
10 #include <vector>
11
12 #include "core/fpdfapi/parser/cpdf_encryptor.h"
13 #include "core/fpdfapi/parser/fpdf_parser_decode.h"
14 #include "core/fxcrt/fx_stream.h"
15 #include "third_party/base/ptr_util.h"
16
17 CPDF_String::CPDF_String() = default;
18
CPDF_String(WeakPtr<ByteStringPool> pPool,const ByteString & str,bool bHex)19 CPDF_String::CPDF_String(WeakPtr<ByteStringPool> pPool,
20 const ByteString& str,
21 bool bHex)
22 : m_String(str), m_bHex(bHex) {
23 if (pPool)
24 m_String = pPool->Intern(m_String);
25 }
26
CPDF_String(WeakPtr<ByteStringPool> pPool,const WideString & str)27 CPDF_String::CPDF_String(WeakPtr<ByteStringPool> pPool, const WideString& str)
28 : m_String(PDF_EncodeText(str)) {
29 if (pPool)
30 m_String = pPool->Intern(m_String);
31 }
32
33 CPDF_String::~CPDF_String() = default;
34
GetType() const35 CPDF_Object::Type CPDF_String::GetType() const {
36 return kString;
37 }
38
Clone() const39 RetainPtr<CPDF_Object> CPDF_String::Clone() const {
40 auto pRet = pdfium::MakeRetain<CPDF_String>();
41 pRet->m_String = m_String;
42 pRet->m_bHex = m_bHex;
43 return pRet;
44 }
45
GetString() const46 ByteString CPDF_String::GetString() const {
47 return m_String;
48 }
49
SetString(const ByteString & str)50 void CPDF_String::SetString(const ByteString& str) {
51 m_String = str;
52 }
53
IsString() const54 bool CPDF_String::IsString() const {
55 return true;
56 }
57
AsString()58 CPDF_String* CPDF_String::AsString() {
59 return this;
60 }
61
AsString() const62 const CPDF_String* CPDF_String::AsString() const {
63 return this;
64 }
65
GetUnicodeText() const66 WideString CPDF_String::GetUnicodeText() const {
67 return PDF_DecodeText(m_String.raw_span());
68 }
69
WriteTo(IFX_ArchiveStream * archive,const CPDF_Encryptor * encryptor) const70 bool CPDF_String::WriteTo(IFX_ArchiveStream* archive,
71 const CPDF_Encryptor* encryptor) const {
72 std::vector<uint8_t> encrypted_data;
73 pdfium::span<const uint8_t> data = m_String.raw_span();
74 if (encryptor) {
75 encrypted_data = encryptor->Encrypt(data);
76 data = encrypted_data;
77 }
78 const ByteString content =
79 PDF_EncodeString(ByteString(data.data(), data.size()), IsHex());
80 return archive->WriteString(content.AsStringView());
81 }
82