1// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
2// for details. All rights reserved. Use of this source code is governed by a
3// BSD-style license that can be found in the LICENSE file.
4
5#include "platform/globals.h"
6#if defined(HOST_OS_WINDOWS)
7
8#include <io.h> // NOLINT
9#include "platform/utils.h"
10
11namespace dart {
12
13char* Utils::StrNDup(const char* s, intptr_t n) {
14 intptr_t len = strlen(s);
15 if ((n < 0) || (len < 0)) {
16 return NULL;
17 }
18 if (n < len) {
19 len = n;
20 }
21 char* result = reinterpret_cast<char*>(malloc(len + 1));
22 if (result == NULL) {
23 return NULL;
24 }
25 result[len] = '\0';
26 return reinterpret_cast<char*>(memmove(result, s, len));
27}
28
29char* Utils::StrDup(const char* s) {
30 return _strdup(s);
31}
32
33intptr_t Utils::StrNLen(const char* s, intptr_t n) {
34 return strnlen(s, n);
35}
36
37int Utils::SNPrint(char* str, size_t size, const char* format, ...) {
38 va_list args;
39 va_start(args, format);
40 int retval = VSNPrint(str, size, format, args);
41 va_end(args);
42 return retval;
43}
44
45int Utils::VSNPrint(char* str, size_t size, const char* format, va_list args) {
46 if (str == NULL || size == 0) {
47 int retval = _vscprintf(format, args);
48 if (retval < 0) {
49 FATAL1("Fatal error in Utils::VSNPrint with format '%s'", format);
50 }
51 return retval;
52 }
53 va_list args_copy;
54 va_copy(args_copy, args);
55 int written = _vsnprintf(str, size, format, args_copy);
56 va_end(args_copy);
57 if (written < 0) {
58 // _vsnprintf returns -1 if the number of characters to be written is
59 // larger than 'size', so we call _vscprintf which returns the number
60 // of characters that would have been written.
61 va_list args_retry;
62 va_copy(args_retry, args);
63 written = _vscprintf(format, args_retry);
64 if (written < 0) {
65 FATAL1("Fatal error in Utils::VSNPrint with format '%s'", format);
66 }
67 va_end(args_retry);
68 }
69 // Make sure to zero-terminate the string if the output was
70 // truncated or if there was an error.
71 // The static cast is safe here as we have already determined that 'written'
72 // is >= 0.
73 if (static_cast<size_t>(written) >= size) {
74 str[size - 1] = '\0';
75 }
76 return written;
77}
78
79int Utils::Close(int fildes) {
80 return _close(fildes);
81}
82size_t Utils::Read(int filedes, void* buf, size_t nbyte) {
83 return _read(filedes, buf, nbyte);
84}
85int Utils::Unlink(const char* path) {
86 return _unlink(path);
87}
88
89} // namespace dart
90
91#endif // defined(HOST_OS_WINDOWS)
92