Sprintf.h 1.1 KB

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