1 | //===-- Implementation of puts --------------------------------------------===// |
---|---|
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 | #include "src/stdio/puts.h" |
10 | #include "src/__support/CPP/string_view.h" |
11 | #include "src/__support/File/file.h" |
12 | |
13 | #include "src/errno/libc_errno.h" |
14 | #include <stdio.h> |
15 | |
16 | namespace LIBC_NAMESPACE { |
17 | |
18 | namespace { |
19 | |
20 | // Simple helper to unlock the file once destroyed. |
21 | struct ScopedLock { |
22 | ScopedLock(LIBC_NAMESPACE::File *stream) : stream(stream) { stream->lock(); } |
23 | ~ScopedLock() { stream->unlock(); } |
24 | |
25 | private: |
26 | LIBC_NAMESPACE::File *stream; |
27 | }; |
28 | |
29 | } // namespace |
30 | |
31 | LLVM_LIBC_FUNCTION(int, puts, (const char *__restrict str)) { |
32 | cpp::string_view str_view(str); |
33 | |
34 | // We need to lock the stream to ensure the newline is always appended. |
35 | ScopedLock lock(LIBC_NAMESPACE::stdout); |
36 | |
37 | auto result = LIBC_NAMESPACE::stdout->write_unlocked(data: str, len: str_view.size()); |
38 | if (result.has_error()) |
39 | libc_errno = result.error; |
40 | size_t written = result.value; |
41 | if (str_view.size() != written) { |
42 | // The stream should be in an error state in this case. |
43 | return EOF; |
44 | } |
45 | result = LIBC_NAMESPACE::stdout->write_unlocked(data: "\n", len: 1); |
46 | if (result.has_error()) |
47 | libc_errno = result.error; |
48 | written = result.value; |
49 | if (1 != written) { |
50 | // The stream should be in an error state in this case. |
51 | return EOF; |
52 | } |
53 | return 0; |
54 | } |
55 | |
56 | } // namespace LIBC_NAMESPACE |
57 |