FLANG
char.h
1//===-- include/flang/Evaluate/char.h ---------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef FORTRAN_EVALUATE_CHAR_H_
10#define FORTRAN_EVALUATE_CHAR_H_
11
12#include "flang/Evaluate/type.h"
13#include <string>
14
15namespace Fortran::evaluate::value {
16
18template <int KIND> class Character {
19 using Word = Scalar<Type<TypeCategory::Character, KIND>>;
20 using CharT = typename Word::value_type;
21
22public:
23 // rule-of-five
24 ~Character() = default;
25 Character(const Character &v) : word_(v) {}
26 Character(Character &&v) : word_(std::move(v)) {}
27 Character &operator=(const Character &v) {
28 word_ = v.word_;
29 return &this;
30 }
31 Character &operator=(Character &&v) {
32 word_ = std::move(v.word_);
33 return *this;
34 }
35
36 // ctors
37 Character() = default;
38 Character(const Word &v) : word_(v) {}
39 Character(Word &&v) : word_(std::move(v)) {}
40 Character &operator=(const Word &v) { word_ = v; }
41 Character &operator=(Word &&v) { word_ = std::move(v); }
42
44 auto size() const { return word_.size(); }
45
48 static Word FromRawBytes(const void *raw, std::size_t size) {
49 CHECK(size % sizeof(CharT) == 0);
50 Word s;
51 if (size > 0) {
52 s.assign(static_cast<const CharT *>(raw), size / sizeof(CharT));
53 }
54 return s;
55 }
56
63 void StoreRawBytes(void *dst, std::size_t size, bool *changed = nullptr) {
64 CHECK(size % sizeof(CharT) == 0);
65 if (size > 0) {
66 std::size_t payloadSize{std::min(size, sizeof(CharT) * word_.size())};
67 std::size_t padSize{size - payloadSize};
68
69 // Pad with spaces
70 Word strWithPadding{word_};
71 strWithPadding.append(padSize / sizeof(CharT), static_cast<CharT>(' '));
72
73 if (changed) {
74 if (std::memcmp(dst, strWithPadding.data(), size) == 0) {
75 return;
76 }
77 *changed = true;
78 }
79 std::memcpy(dst, strWithPadding.data(), size);
80 }
81 }
82
83private:
84 Word word_;
85};
86
87} // namespace Fortran::evaluate::value
88#endif // FORTRAN_EVALUATE_CHAR_H_
static Word FromRawBytes(const void *raw, std::size_t size)
Definition char.h:48
void StoreRawBytes(void *dst, std::size_t size, bool *changed=nullptr)
Definition char.h:63
auto size() const
Returns the number of characters stored; not the number of bytes.
Definition char.h:44