Sprintf.h 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. /* Provides a safer sprintf for printing to fixed-size character arrays. */
  6. #ifndef mozilla_Sprintf_h_
  7. #define mozilla_Sprintf_h_
  8. #include <stdio.h>
  9. #include <stdarg.h>
  10. #include "mozilla/Assertions.h"
  11. #include "mozilla/Attributes.h"
  12. #ifdef __cplusplus
  13. template <size_t N>
  14. int VsprintfLiteral(char (&buffer)[N], const char* format, va_list args)
  15. {
  16. MOZ_ASSERT(format != buffer);
  17. int result = vsnprintf(buffer, N, format, args);
  18. buffer[N - 1] = '\0';
  19. return result;
  20. }
  21. template <size_t N>
  22. MOZ_FORMAT_PRINTF(2, 3)
  23. int SprintfLiteral(char (&buffer)[N], const char* format, ...)
  24. {
  25. va_list args;
  26. va_start(args, format);
  27. int result = VsprintfLiteral(buffer, format, args);
  28. va_end(args);
  29. return result;
  30. }
  31. #endif
  32. #endif /* mozilla_Sprintf_h_ */