//===-- lib/Evaluate/static-data.cpp --------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "flang/Evaluate/static-data.h" #include "flang/Parser/characters.h" namespace Fortran::evaluate { bool StaticDataObject::bigEndian{false}; llvm::raw_ostream &StaticDataObject::AsFortran(llvm::raw_ostream &o) const { if (auto string{AsString()}) { o << parser::QuoteCharacterLiteral(*string); } else if (auto string{AsU16String()}) { o << "2_" << parser::QuoteCharacterLiteral(*string); } else if (auto string{AsU32String()}) { o << "4_" << parser::QuoteCharacterLiteral(*string); } else { CRASH_NO_CASE; } return o; } StaticDataObject &StaticDataObject::Push(const std::string &string) { for (auto ch : string) { data_.push_back(static_cast(ch)); } return *this; } StaticDataObject &StaticDataObject::Push(const std::u16string &string) { int shift{bigEndian * 8}; for (auto ch : string) { data_.push_back(static_cast(ch >> shift)); data_.push_back(static_cast(ch >> (shift ^ 8))); } return *this; } StaticDataObject &StaticDataObject::Push(const std::u32string &string) { int shift{bigEndian * 24}; for (auto ch : string) { data_.push_back(static_cast(ch >> shift)); data_.push_back(static_cast(ch >> (shift ^ 8))); data_.push_back(static_cast(ch >> (shift ^ 16))); data_.push_back(static_cast(ch >> (shift ^ 24))); } return *this; } std::optional StaticDataObject::AsString() const { if (itemBytes_ <= 1) { std::string result; for (std::uint8_t byte : data_) { result += static_cast(byte); } return {std::move(result)}; } return std::nullopt; } std::optional StaticDataObject::AsU16String() const { if (itemBytes_ == 2) { int shift{bigEndian * 8}; std::u16string result; auto end{data_.cend()}; for (auto byte{data_.cbegin()}; byte < end;) { result += static_cast(*byte++) << shift | static_cast(*byte++) << (shift ^ 8); } return {std::move(result)}; } return std::nullopt; } std::optional StaticDataObject::AsU32String() const { if (itemBytes_ == 4) { int shift{bigEndian * 24}; std::u32string result; auto end{data_.cend()}; for (auto byte{data_.cbegin()}; byte < end;) { result += static_cast(*byte++) << shift | static_cast(*byte++) << (shift ^ 8) | static_cast(*byte++) << (shift ^ 16) | static_cast(*byte++) << (shift ^ 24); } return {std::move(result)}; } return std::nullopt; } } // namespace Fortran::evaluate