Simple Directmedia Layer
at main 3.0 kB view raw
1/* 2 Simple DirectMedia Layer 3 Copyright (C) 1997-2024 Sam Lantinga <slouken@libsdl.org> 4 5 This software is provided 'as-is', without any express or implied 6 warranty. In no event will the authors be held liable for any damages 7 arising from the use of this software. 8 9 Permission is granted to anyone to use this software for any purpose, 10 including commercial applications, and to alter it and redistribute it 11 freely, subject to the following restrictions: 12 13 1. The origin of this software must not be misrepresented; you must not 14 claim that you wrote the original software. If you use this software 15 in a product, an acknowledgment in the product documentation would be 16 appreciated but is not required. 17 2. Altered source versions must be plainly marked as such, and must not be 18 misrepresented as being the original software. 19 3. This notice may not be removed or altered from any source distribution. 20*/ 21#include "SDL_internal.h" 22 23// Simple error handling in SDL 24 25#include "SDL_error_c.h" 26 27bool SDL_SetError(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) 28{ 29 va_list ap; 30 bool result; 31 32 va_start(ap, fmt); 33 result = SDL_SetErrorV(fmt, ap); 34 va_end(ap); 35 return result; 36} 37 38bool SDL_SetErrorV(SDL_PRINTF_FORMAT_STRING const char *fmt, va_list ap) 39{ 40 // Ignore call if invalid format pointer was passed 41 if (fmt) { 42 int result; 43 SDL_error *error = SDL_GetErrBuf(true); 44 va_list ap2; 45 46 error->error = SDL_ErrorCodeGeneric; 47 48 va_copy(ap2, ap); 49 result = SDL_vsnprintf(error->str, error->len, fmt, ap2); 50 va_end(ap2); 51 52 if (result >= 0 && (size_t)result >= error->len && error->realloc_func) { 53 size_t len = (size_t)result + 1; 54 char *str = (char *)error->realloc_func(error->str, len); 55 if (str) { 56 error->str = str; 57 error->len = len; 58 va_copy(ap2, ap); 59 (void)SDL_vsnprintf(error->str, error->len, fmt, ap2); 60 va_end(ap2); 61 } 62 } 63 64 if (SDL_GetLogPriority(SDL_LOG_CATEGORY_ERROR) <= SDL_LOG_PRIORITY_DEBUG) { 65 // If we are in debug mode, print out the error message 66 SDL_LogDebug(SDL_LOG_CATEGORY_ERROR, "%s", error->str); 67 } 68 } 69 70 return false; 71} 72 73const char *SDL_GetError(void) 74{ 75 const SDL_error *error = SDL_GetErrBuf(false); 76 77 if (!error) { 78 return ""; 79 } 80 81 switch (error->error) { 82 case SDL_ErrorCodeGeneric: 83 return error->str; 84 case SDL_ErrorCodeOutOfMemory: 85 return "Out of memory"; 86 default: 87 return ""; 88 } 89} 90 91bool SDL_ClearError(void) 92{ 93 SDL_error *error = SDL_GetErrBuf(false); 94 95 if (error) { 96 error->error = SDL_ErrorCodeNone; 97 } 98 return true; 99} 100 101bool SDL_OutOfMemory(void) 102{ 103 SDL_error *error = SDL_GetErrBuf(true); 104 105 if (error) { 106 error->error = SDL_ErrorCodeOutOfMemory; 107 } 108 return false; 109} 110