1 /* Copyright 2015 The TensorFlow Authors. All Rights Reserved. 2 3 Licensed under the Apache License, Version 2.0 (the "License"); 4 you may not use this file except in compliance with the License. 5 You may obtain a copy of the License at 6 7 http://www.apache.org/licenses/LICENSE-2.0 8 9 Unless required by applicable law or agreed to in writing, software 10 distributed under the License is distributed on an "AS IS" BASIS, 11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 See the License for the specific language governing permissions and 13 limitations under the License. 14 ==============================================================================*/ 15 16 #include "tensorflow/core/lib/strings/stringprintf.h" 17 18 #include <errno.h> 19 #include <stdarg.h> // For va_list and related operations 20 #include <stdio.h> // MSVC requires this for _vsnprintf 21 22 namespace tensorflow { 23 namespace strings { 24 25 #ifdef COMPILER_MSVC 26 enum { IS_COMPILER_MSVC = 1 }; 27 #else 28 enum { IS_COMPILER_MSVC = 0 }; 29 #endif 30 31 void Appendv(string* dst, const char* format, va_list ap) { 32 // First try with a small fixed size buffer 33 static const int kSpaceLength = 1024; 34 char space[kSpaceLength]; 35 36 // It's possible for methods that use a va_list to invalidate 37 // the data in it upon use. The fix is to make a copy 38 // of the structure before using it and use that copy instead. 39 va_list backup_ap; 40 va_copy(backup_ap, ap); 41 int result = vsnprintf(space, kSpaceLength, format, backup_ap); 42 va_end(backup_ap); 43 44 if (result < kSpaceLength) { 45 if (result >= 0) { 46 // Normal case -- everything fit. 47 dst->append(space, result); 48 return; 49 } 50 51 if (IS_COMPILER_MSVC) { 52 // Error or MSVC running out of space. MSVC 8.0 and higher 53 // can be asked about space needed with the special idiom below: 54 va_copy(backup_ap, ap); 55 result = vsnprintf(nullptr, 0, format, backup_ap); 56 va_end(backup_ap); 57 } 58 59 if (result < 0) { 60 // Just an error. 61 return; 62 } 63 } 64 65 // Increase the buffer size to the size requested by vsnprintf, 66 // plus one for the closing \0. 67 int length = result + 1; 68 char* buf = new char[length]; 69 70 // Restore the va_list before we use it again 71 va_copy(backup_ap, ap); 72 result = vsnprintf(buf, length, format, backup_ap); 73 va_end(backup_ap); 74 75 if (result >= 0 && result < length) { 76 // It fit 77 dst->append(buf, result); 78 } 79 delete[] buf; 80 } 81 82 string Printf(const char* format, ...) { 83 va_list ap; 84 va_start(ap, format); 85 string result; 86 Appendv(&result, format, ap); 87 va_end(ap); 88 return result; 89 } 90 91 void Appendf(string* dst, const char* format, ...) { 92 va_list ap; 93 va_start(ap, format); 94 Appendv(dst, format, ap); 95 va_end(ap); 96 } 97 98 } // namespace strings 99 } // namespace tensorflow 100