1 | /* |
2 | * Copyright 2016-present Facebook, Inc. |
3 | * |
4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
5 | * you may not use this file except in compliance with the License. |
6 | * You may obtain a copy of the License at |
7 | * |
8 | * http://www.apache.org/licenses/LICENSE-2.0 |
9 | * |
10 | * Unless required by applicable law or agreed to in writing, software |
11 | * distributed under the License is distributed on an "AS IS" BASIS, |
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
13 | * See the License for the specific language governing permissions and |
14 | * limitations under the License. |
15 | */ |
16 | |
17 | #include <folly/portability/Stdio.h> |
18 | |
19 | #ifdef _WIN32 |
20 | |
21 | #include <cstdlib> |
22 | |
23 | #include <folly/ScopeGuard.h> |
24 | #include <folly/portability/Unistd.h> |
25 | |
26 | extern "C" { |
27 | int dprintf(int fd, const char* fmt, ...) { |
28 | va_list args; |
29 | va_start(args, fmt); |
30 | SCOPE_EXIT { |
31 | va_end(args); |
32 | }; |
33 | |
34 | int ret = vsnprintf(nullptr, 0, fmt, args); |
35 | if (ret <= 0) { |
36 | return -1; |
37 | } |
38 | size_t len = size_t(ret); |
39 | char* buf = new char[len + 1]; |
40 | SCOPE_EXIT { |
41 | delete[] buf; |
42 | }; |
43 | if (size_t(vsnprintf(buf, len + 1, fmt, args)) == len && |
44 | write(fd, buf, len) == ssize_t(len)) { |
45 | return ret; |
46 | } |
47 | |
48 | return -1; |
49 | } |
50 | |
51 | int pclose(FILE* f) { |
52 | return _pclose(f); |
53 | } |
54 | |
55 | FILE* popen(const char* name, const char* mode) { |
56 | return _popen(name, mode); |
57 | } |
58 | |
59 | void setbuffer(FILE* f, char* buf, size_t size) { |
60 | setvbuf(f, buf, _IOFBF, size); |
61 | } |
62 | |
63 | int vasprintf(char** dest, const char* format, va_list ap) { |
64 | int len = vsnprintf(nullptr, 0, format, ap); |
65 | if (len <= 0) { |
66 | return -1; |
67 | } |
68 | char* buf = *dest = (char*)malloc(size_t(len + 1)); |
69 | if (vsnprintf(buf, size_t(len + 1), format, ap) == len) { |
70 | return len; |
71 | } |
72 | free(buf); |
73 | return -1; |
74 | } |
75 | } |
76 | |
77 | #endif |
78 | |