IgrOS-Kernel 0.1.34.545
Simple C++20 Kernel for i386/x86_64
Loading...
Searching...
No Matches
kPrint.cpp
Go to the documentation of this file.
1
11
12
13// C++
14#include <algorithm>
15#include <array>
16#include <bit>
17#include <cstdarg>
18#include <limits>
19#include <string_view>
20#include <type_traits>
21#include <utility>
22// IgrOS-Kernel arch
23#include <arch/irq.hpp>
24// IgrOS-Kernel drivers
26#include <drivers/vga/vmem.hpp>
27// IgrOS-Kernel library
28#include <klib/kPrint.hpp>
29#include <klib/kString.hpp>
30
31
32// Kernel library code zone
33namespace igros::klib {
34
35
37 namespace {
38
39
48
50 struct spec_t {
51 igros_usize_t width {0_usize};
53 bool zero {false};
54 bool left {false};
55 };
56
57
59 class writer_t final {
60
61 char* mPos;
62 char* const mEnd;
63
64 public:
65
69 writer_t(char* const buffer, const igros_usize_t size) noexcept :
70 mPos {buffer},
71 mEnd {buffer + size - 1_usize} {}
72
75 [[nodiscard]]
76 auto isFull() const noexcept -> bool {
77 return mPos >= mEnd;
78 }
79
82 void put(const char symbol) noexcept {
83 if (!isFull()) [[likely]] {
84 *mPos++ = symbol;
85 }
86 }
87
90 void put(const std::string_view text) noexcept {
91 mPos = std::ranges::copy_n(text.data(), static_cast<std::ptrdiff_t>(std::min(text.size(), space())), mPos).out;
92 }
93
97 void fill(const char symbol, const igros_usize_t count) noexcept {
98 mPos = std::ranges::fill_n(mPos, static_cast<std::ptrdiff_t>(std::min(count, space())), symbol);
99 }
100
105 void padded(const std::string_view prefix, const std::string_view text, const spec_t &spec) noexcept {
106 const auto length {prefix.size() + text.size()};
107 const auto padding {(spec.width > length) ? (spec.width - length) : 0_usize};
108 if (spec.left) {
109 put(prefix);
110 put(text);
111 fill(' ', padding);
112 } else if (spec.zero) {
113 put(prefix);
114 fill('0', padding);
115 put(text);
116 } else {
117 fill(' ', padding);
118 put(prefix);
119 put(text);
120 }
121 }
122
126 auto finish(const char* const buffer) noexcept -> igros_usize_t {
127 *mPos = '\0';
128 return static_cast<igros_usize_t>(mPos - buffer);
129 }
130
131 private:
132
135 [[nodiscard]]
136 auto space() const noexcept -> igros_usize_t {
137 return static_cast<igros_usize_t>(mEnd - mPos);
138 }
139 };
140
141
149 template<std::integral T>
150 void putInteger(writer_t &out, const T value, const radix_t radix, const spec_t &spec, const bool upper = false) noexcept {
151 using U = std::make_unsigned_t<T>;
152 // Sign (compile time views: no strlen at run time)
153 constexpr auto MINUS {std::string_view {"-"}};
154 constexpr auto NONE {std::string_view {}};
155 const auto isNegative {std::cmp_less(value, static_cast<T>(0))};
156 const auto magnitude {isNegative ? static_cast<U>(static_cast<U>(0) - static_cast<U>(value)) : static_cast<U>(value)};
157 auto digits {std::array<char, std::numeric_limits<U>::digits> {}};
158 out.padded(isNegative ? MINUS : NONE, kdigits(digits, magnitude, radix, upper), spec);
159 }
160
168 void putArgument(writer_t &out, std::va_list &list, const radix_t radix, const spec_t &spec, const bool isSigned, const bool upper) noexcept {
169 // Smaller than int arguments are promoted to int
170 switch (spec.size) {
171 case argSize_t::BYTE:
172 isSigned ?
173 putInteger(out, static_cast<igros_sbyte_t>(va_arg(list, igros_sdword_t)), radix, spec, upper) :
174 putInteger(out, static_cast<igros_byte_t>(va_arg(list, igros_dword_t)), radix, spec, upper);
175 break;
176 case argSize_t::WORD:
177 isSigned ?
178 putInteger(out, static_cast<igros_sword_t>(va_arg(list, igros_sdword_t)), radix, spec, upper) :
179 putInteger(out, static_cast<igros_word_t>(va_arg(list, igros_dword_t)), radix, spec, upper);
180 break;
181 case argSize_t::DWORD:
182 isSigned ?
183 putInteger(out, va_arg(list, igros_sdword_t), radix, spec, upper) :
184 putInteger(out, va_arg(list, igros_dword_t), radix, spec, upper);
185 break;
186 case argSize_t::QUAD: // NOLINT(bugprone-branch-clone): same as SIZE on 64-bit only
187 isSigned ?
188 putInteger(out, va_arg(list, igros_squad_t), radix, spec, upper) :
189 putInteger(out, va_arg(list, igros_quad_t), radix, spec, upper);
190 break;
191 case argSize_t::SIZE:
192 isSigned ?
193 putInteger(out, va_arg(list, igros_ssize_t), radix, spec, upper) :
194 putInteger(out, va_arg(list, igros_usize_t), radix, spec, upper);
195 break;
196 }
197 }
198
199
200
206 [[nodiscard]]
207 auto parseSpec(const char*&fmt) noexcept -> spec_t {
208
209 auto spec {spec_t {}};
210
211 // Flags
212 while (('0' == fmt[1]) || ('-' == fmt[1])) {
213 if ('0' == fmt[1]) {
214 spec.zero = true;
215 } else {
216 spec.left = true;
217 }
218 ++fmt;
219 }
220
221 // Field width (any number of digits)
222 while (('0' <= fmt[1]) && ('9' >= fmt[1])) {
223 spec.width = (spec.width * 10_usize) + static_cast<igros_usize_t>(fmt[1] - '0');
224 ++fmt;
225 }
226
227 // Length modifier
228 switch (fmt[1]) {
229 case 'h':
230 spec.size = ('h' == fmt[2]) ? argSize_t::BYTE : argSize_t::WORD;
231 fmt += (argSize_t::BYTE == spec.size) ? 2 : 1;
232 break;
233 case 'l':
234 // Long is 32 bits on i386, 64 bits on x86_64
235 spec.size = (('l' == fmt[2]) || (sizeof(long) == sizeof(igros_quad_t))) ? argSize_t::QUAD : argSize_t::DWORD;
236 fmt += ('l' == fmt[2]) ? 2 : 1;
237 break;
238 case 'z':
239 case 't':
240 spec.size = argSize_t::SIZE;
241 ++fmt;
242 break;
243 default:
244 break;
245 }
246
247 return spec;
248 }
249
250
251 } // namespace
252
253
254 // Kernel vsnprintf function
255 auto kvsnprintf(char* const buffer, const igros_usize_t size, const char* const format, std::va_list list) noexcept -> igros_usize_t {
256
257 // Error checks
258 if ((nullptr == buffer) || (0_usize == size) || (nullptr == format)) [[unlikely]] {
259 return 0_usize;
260 }
261
262 // Output
263 auto out {writer_t {buffer, size}};
264 // Local copy of arguments (parameter may be decayed array, it can't be passed by reference)
265 std::va_list args {};
266 va_copy(args, list);
267
268 // Format string position (stops when output is full: remaining arguments are not needed)
269 const auto* fmt {format};
270 while (('\0' != *fmt) && !out.isFull()) {
271
272 // Plain character
273 if ('%' != *fmt) [[likely]] {
274 out.put(*fmt++);
275 continue;
276 }
277
278 // Flags, field width, length modifier
279 const auto spec {parseSpec(fmt)};
280
281 // Unterminated placeholder at format end
282 if ('\0' == fmt[1]) [[unlikely]] {
283 break;
284 }
285
286 // Conversion
287 switch (*++fmt) {
288 // Placeholder symbol itself
289 case '%':
290 out.put('%');
291 break;
292 // Character (promoted to int)
293 case 'c': {
294 const auto symbol {static_cast<char>(va_arg(args, igros_sdword_t))};
295 out.padded({}, std::string_view {&symbol, 1_usize}, spec);
296 } break;
297 // String (null prints nothing)
298 case 's': {
299 const auto* const str {va_arg(args, const char*)};
300 out.padded({}, kstrview(str), spec);
301 } break;
302 // Signed decimal
303 case 'd':
304 case 'i':
305 putArgument(out, args, radix_t::DEC, spec, true, false);
306 break;
307 // Unsigned integers
308 case 'u':
309 putArgument(out, args, radix_t::DEC, spec, false, false);
310 break;
311 case 'b':
312 putArgument(out, args, radix_t::BIN, spec, false, false);
313 break;
314 case 'o':
315 putArgument(out, args, radix_t::OCT, spec, false, false);
316 break;
317 case 'x':
318 putArgument(out, args, radix_t::HEX, spec, false, false);
319 break;
320 case 'X':
321 putArgument(out, args, radix_t::HEX, spec, false, true);
322 break;
323 // Pointer: all hex digits
324 case 'p':
325 putInteger(out, std::bit_cast<igros_usize_t>(va_arg(args, igros_pointer_t)), radix_t::HEX, spec_t {.width = sizeof(igros_pointer_t) << 1, .zero = true});
326 break;
327 // Unknown conversion
328 default:
329 out.put('?');
330 break;
331 }
332 // Next format character
333 ++fmt;
334 }
335
336 // Done with arguments
337 va_end(args);
338 // Insert null terminator
339 return out.finish(buffer);
340 }
341
342
343 // Kernel snprintf function
344 auto ksnprintf(char* const buffer, const igros_usize_t size, const char* const format, ...) noexcept -> igros_usize_t {
345 // Kernel variadic argument list
346 std::va_list list {};
347 // Initialize variadic arguments list
348 va_start(list, format);
349 // Format string
350 const auto length {kvsnprintf(buffer, size, format, list)};
351 // End variadic arguments list
352 va_end(list);
353 return length;
354 }
355
356
357 // Kernel printf function
358 void kprintf(const char* const format, ...) noexcept {
359 // Line end (compile time: no strlen at run time)
360 constexpr auto NEWLINE {std::string_view {"\n"}};
361 // Shared buffer and output must not be interrupted by IRQ handler printing too
362 const arch::irq::guard noInterrupts {};
363 // Text buffer
364 constinit static auto buffer {std::array<char, 1024_usize> {}};
365 // Kernel variadic argument list
366 std::va_list list {};
367 // Initialize variadic arguments list
368 va_start(list, format);
369 // Format string
370 const auto text {std::string_view {buffer.data(), kvsnprintf(buffer.data(), buffer.size(), format, list)}};
371 // End variadic arguments list
372 va_end(list);
373 // Output to screen and serial
374 arch::vmemWrite(text);
375 arch::vmemWrite(NEWLINE);
376 arch::serialWrite(text);
377 arch::serialWrite(NEWLINE);
378 }
379
380
381} // namespace igros::klib
382
Disable interrupts in scope (restores previous state on exit).
Definition irq.hpp:175
Output buffer writer: never writes past last position (reserved for terminator).
Definition kPrint.cpp:59
void padded(const std::string_view prefix, const std::string_view text, const spec_t &spec) noexcept
Prefix (sign) and text padded to field width.
Definition kPrint.cpp:105
auto space() const noexcept -> igros_usize_t
Space left.
Definition kPrint.cpp:136
auto isFull() const noexcept -> bool
No space left.
Definition kPrint.cpp:76
auto finish(const char *const buffer) noexcept -> igros_usize_t
Terminate, return written length.
Definition kPrint.cpp:126
writer_t(char *const buffer, const igros_usize_t size) noexcept
Writer for buffer of given size (at least 1).
Definition kPrint.cpp:69
void fill(const char symbol, const igros_usize_t count) noexcept
Repeated character (clipped).
Definition kPrint.cpp:97
void put(const std::string_view text) noexcept
Text (clipped; no substr: it may throw).
Definition kPrint.cpp:90
void put(const char symbol) noexcept
Character.
Definition kPrint.cpp:82
std::uint16_t igros_word_t
16-bit unsigned integer
Definition types.hpp:42
std::int64_t igros_squad_t
64-bit signed integer
Definition types.hpp:38
std::size_t igros_usize_t
Unsigned size.
Definition types.hpp:51
std::uint8_t igros_byte_t
8-bit unsigned integer
Definition types.hpp:41
std::uint32_t igros_dword_t
32-bit unsigned integer
Definition types.hpp:43
std::add_pointer_t< void > igros_pointer_t
Common pointer type.
Definition types.hpp:55
std::int8_t igros_sbyte_t
8-bit signed integer
Definition types.hpp:35
std::ptrdiff_t igros_ssize_t
Signed size (difference).
Definition types.hpp:52
std::int16_t igros_sword_t
16-bit signed integer
Definition types.hpp:36
std::int32_t igros_sdword_t
32-bit signed integer
Definition types.hpp:37
std::uint64_t igros_quad_t
64-bit unsigned integer
Definition types.hpp:44
Architecture interrupts type deduction.
Kernel text print functions.
Kernel string functions.
auto serialWrite(const SERIAL_PORT port, const std::string_view text) noexcept -> igros_usize_t
Serial write.
Definition serial.cpp:242
void vmemWrite(const char symbol) noexcept
Write symbol to VGA memory.
Definition vmem.cpp:134
argSize_t
Argument size (length modifier).
Definition kPrint.cpp:41
void putArgument(writer_t &out, std::va_list &list, const radix_t radix, const spec_t &spec, const bool isSigned, const bool upper) noexcept
Integer argument of given size: signed or unsigned.
Definition kPrint.cpp:168
auto parseSpec(const char *&fmt) noexcept -> spec_t
Parse flags, field width and length modifier of a placeholder.
Definition kPrint.cpp:207
void putInteger(writer_t &out, const T value, const radix_t radix, const spec_t &spec, const bool upper=false) noexcept
Integer with sign (signed types, decimal only) and padding.
Definition kPrint.cpp:150
Freestanding kernel library: printing, math, alignment, flags, strings.
auto ksnprintf(char *const buffer, const igros_usize_t size, const char *const format,...) noexcept -> igros_usize_t
Kernel snprintf function (returns written length without terminator).
Definition kPrint.cpp:344
constexpr auto kstrview(const char *const src) noexcept -> std::string_view
View of null-terminated string (null pointer is empty string).
Definition kString.hpp:28
void kprintf(const char *const format,...) noexcept
Kernel printf function (arguments are checked against format at compile time).
Definition kPrint.cpp:358
auto kvsnprintf(char *const buffer, const igros_usize_t size, const char *const format, std::va_list list) noexcept -> igros_usize_t
Kernel vsnprintf function (returns written length without terminator).
Definition kPrint.cpp:255
radix_t
Integer representation types.
Definition kPrint.hpp:35
@ BIN
(Base 2) Binary integer format
Definition kPrint.hpp:36
@ DEC
(Base 10) Decimal integer format
Definition kPrint.hpp:38
@ OCT
(Base 8) Oct integer format
Definition kPrint.hpp:37
@ HEX
(Base 16) Hexidemical integer format
Definition kPrint.hpp:39
constexpr auto kdigits(const std::span< char > buffer, U value, const radix_t radix, const bool upper=false) noexcept -> std::string_view
Digits of unsigned value written to the end of buffer (no sign, no terminator).
Definition kPrint.hpp:54
UART driver.
igros_usize_t width
Minimal field width.
Definition kPrint.cpp:51
bool zero
Pad numbers with '0' (after sign).
Definition kPrint.cpp:53
bool left
Left-justify (pad with spaces after text).
Definition kPrint.cpp:54
VGA memory low-level operations.