vile / scheme / port_standard.h
41 lines · 41 sloc · 1.4 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1#ifndef VILE_PORT_STANDARD_H
2#define VILE_PORT_STANDARD_H
3#ifdef _WIN32
4#include <errno.h>
5#include <stdio.h>
6#include <io.h>
7#include <fcntl.h>
8/* A duplicate has its own CRT translation flags. Never change the process
9 standard descriptor's mode, and close only the duplicate owned by the port. */
10static int vile_binary_standard_duplicate(int standard) {
11 int copy = _dup(standard);
12 if (copy < 0) return -(errno ? errno : EIO);
13 if (_setmode(copy, _O_BINARY) < 0) {
14 int saved = errno ? errno : EIO;
15 _close(copy);
16 return -saved;
17 }
18 return copy;
19}
20/* Keep stdin's existing FILE read-ahead. The temporary descriptor mode is
21 confined to this locked C call; no V allocation or callback can run here. */
22static int vile_binary_standard_read(void *bytes, unsigned int length) {
23 if (!length) return 0;
24 _lock_file(stdin);
25 int fd = _fileno(stdin);
26 int previous = _setmode(fd, _O_BINARY);
27 if (previous < 0) {
28 int saved = errno ? errno : EIO;
29 _unlock_file(stdin);
30 return -saved;
31 }
32 size_t count = _fread_nolock(bytes, 1, length, stdin);
33 int saved = count == 0 && ferror(stdin) ? (errno ? errno : EIO) : 0;
34 if (saved) clearerr(stdin);
35 int restored = _setmode(fd, previous);
36 if (restored < 0 && count == 0 && !saved) saved = errno ? errno : EIO;
37 _unlock_file(stdin);
38 return saved ? -saved : (int)count;
39}
40#endif
41#endif
42