Sese Framework  x.y.z
A cross-platform framework
载入中...
搜索中...
未找到
FormatOption.h
浏览该文件的文档.
1// Copyright 2024 libsese
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#pragma once
16
17#include <sese/Config.h>
18
19namespace sese::text {
20
21enum class Align {
22 LEFT,
23 CENTER,
24 RIGHT
25};
26
29 char wide_char = ' ';
30 uint16_t wide = 0;
31 uint16_t float_placeholder = 0;
32 char ext_type = 0;
33
34 SESE_ALWAYS_INLINE static bool is_align(const char CH) {
35 return CH == '<' || CH == '>' || CH == '^';
36 }
37
38 SESE_ALWAYS_INLINE static Align delect_align(const char CH) {
39 if (CH == '<') {
40 return Align::LEFT;
41 }
42 if (CH == '>') {
43 return Align::RIGHT;
44 }
45 if (CH == '^') {
46 return Align::CENTER;
47 }
48 assert(false);
49 return Align::LEFT;
50 }
51
52 bool parse(const std::string &value) {
53 if (value[0] != ':') {
54 return false;
55 }
56
57 // 这种情况只可能是拓展类型
58 if (value.size() == 2 && !is_align(value[1])) {
59 ext_type = value[1];
60 return true;
61 }
62
63 // 对齐相关判断
64 bool has_align = false;
65 auto pos = value.begin() + 1;
66 if (pos == value.end()) {
67 // 不存在手动指定的对齐方式,直接退出
69 return true;
70 }
71 if (!is_align(*pos)) {
72 if (pos + 1 != value.end() && is_align(*(pos + 1))) {
73 wide_char = *pos;
74 pos += 1;
75 has_align = true;
76 }
77 } else {
78 has_align = true;
79 }
80 if (has_align) {
81 align = delect_align(*pos);
82 pos += 1;
83 }
84 if (pos == value.end()) {
85 return true;
86 }
87 char *end;
88 wide = static_cast<uint16_t>(std::strtol(value.data() + (pos - value.begin()), &end, 10));
89 pos = value.begin() + (end - value.data());
90
91 // end 不为 \0 将直接返回,无需额外判断
92 // 浮点精度相关判断
93 if (*end == '.') {
94 char *new_end;
95 float_placeholder = static_cast<uint16_t>(std::strtol(end + 1, &new_end, 10));
96 if (end == new_end) {
97 // 缺少精度
98 return false;
99 }
100 end = new_end;
101 pos = value.begin() + (end - value.data());
102 }
103 if (pos == value.end()) {
104 return true;
105 }
106
107 // 拓展类型判断
108 ext_type = *pos;
109 if (pos + 1 == value.end()) {
110 return true;
111 }
112
113 return false;
114 }
115};
116
117} // namespace sese::text