1 /* 2 * Handy secure string adapter functions for mbedTLS, 3 * converting from `StringCchVPrintfEx` to `_vsnprintf_s`. 4 * 5 * Copyright 2015 Ismael Ferreras Morezuelas <swyterzone+ros@gmail.com> 6 * 7 * This library is free software; you can redistribute it and/or 8 * modify it under the terms of the GNU Lesser General Public 9 * License as published by the Free Software Foundation; either 10 * version 2.1 of the License, or (at your option) any later version. 11 * 12 * This library is distributed in the hope that it will be useful, 13 * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 * Lesser General Public License for more details. 16 * 17 * You should have received a copy of the GNU Lesser General Public 18 * License along with this library; if not, write to the Free Software 19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA 20 */ 21 22 #include <windef.h> 23 #include <strsafe.h> 24 25 int _vsnprintf_s(char *buffer, size_t sizeOfBuffer, size_t count, const char *format, va_list argptr) 26 { 27 size_t cchRemaining; 28 29 HRESULT ret = StringCchVPrintfEx(buffer, sizeOfBuffer, NULL, &cchRemaining, 0, format, argptr); 30 31 // EXAMPLE ////////////////////////// 32 // -------- > Size of provided buffer in chars (8). 33 // ABC0____ > Buffer contents after StringCchVPrintfEx gets called. 34 // --- > What we actually need to return (3). 35 // ----- > Remaining chars in buffer, including post string NULL, returned by StringCchVPrintfEx (5). 36 37 /* _vsnprintf_s returns the number of characters written, not including 38 the terminating null, or a negative value if an output error occurs. */ 39 40 switch (ret) 41 { 42 case S_OK: 43 return (sizeOfBuffer - cchRemaining); 44 45 case STRSAFE_E_INVALID_PARAMETER: 46 case STRSAFE_E_INSUFFICIENT_BUFFER: 47 default: 48 return -1; 49 } 50 }