ascii-chat 0.8.38
Real-time terminal-based video chat with ASCII art conversion
Loading...
Searching...
No Matches
abstraction.c
Go to the documentation of this file.
1
8#include <errno.h>
9#include <ascii-chat/platform/terminal.h>
10#include <ascii-chat/platform/abstraction.h>
11#include <ascii-chat/options/options.h>
12#include <ascii-chat/common.h>
13
14// ============================================================================
15// Common Platform Functions
16// ============================================================================
17// This file is reserved for common platform functions that don't need
18// OS-specific implementations. Currently all functions are OS-specific.
19//
20// The OS-specific implementations are in:
21// - platform_windows.c (Windows)
22// - platform_posix.c (POSIX/Unix/Linux/macOS)
23//
24// Socket-specific implementations are in:
25// - platform/socket.c (Common socket utilities like socket_optimize_for_streaming)
26// ============================================================================
27
39size_t platform_write_all(int fd, const void *buf, size_t count) {
40 if (!buf || count == 0) {
41 return 0;
42 }
43
44 size_t written_total = 0;
45 int attempts = 0;
46 const int MAX_ATTEMPTS = 1000;
47
48 while (written_total < count && attempts < MAX_ATTEMPTS) {
49 ssize_t result = platform_write(fd, (const char *)buf + written_total, count - written_total);
50
51 if (result > 0) {
52 written_total += (size_t)result;
53 attempts = 0; // Reset attempt counter on successful write
54 } else if (result < 0) {
55 // Handle EAGAIN (non-blocking would-block) with sleep instead of tight loop
56 if (errno == EAGAIN || errno == EWOULDBLOCK) {
57 // Sleep 100us before retrying to avoid busy-waiting and spinning CPU
59 } else {
60 // Other write errors - log and retry
61 log_warn("platform_write_all: write() error on fd=%d (wrote %zu/%zu so far, errno=%d)", fd, written_total,
62 count, errno);
63 }
64 attempts++;
65 } else {
66 // result == 0: no bytes written, retry
67 attempts++;
68 }
69 }
70
71 if (attempts >= MAX_ATTEMPTS && written_total < count) {
72 log_warn("platform_write_all: Hit retry limit on fd=%d: wrote %zu of %zu bytes", fd, written_total, count);
73 }
74
75 return written_total;
76}
77
91 if (fd < 0) {
92 return false;
93 }
94 if (GET_OPTION(snapshot_mode)) {
95 return false;
96 }
97 const char *testing_env = SAFE_GETENV("TESTING");
98 if (testing_env != NULL) {
99 return false;
100 }
101 return platform_isatty(fd) != 0;
102}
size_t platform_write_all(int fd, const void *buf, size_t count)
Write all data to file descriptor with automatic retry on transient errors.
Definition abstraction.c:39
bool terminal_should_use_control_sequences(int fd)
Check if terminal control sequences should be used for the given fd.
Definition abstraction.c:90
void platform_sleep_us(unsigned int us)
int platform_isatty(int fd)
Definition util.c:61
ssize_t platform_write(int fd, const void *buf, size_t count)