to_string.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // Copyright (c) 2024 Google LLC
  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. #include "source/to_string.h"
  15. #include <cassert>
  16. namespace spvtools {
  17. std::string to_string(uint32_t n) {
  18. // This implementation avoids using standard library features that access
  19. // the locale. Using the locale requires taking a mutex which causes
  20. // annoying serialization.
  21. constexpr int max_digits = 10; // max uint has 10 digits
  22. // Contains the resulting digits, with least significant digit in the last
  23. // entry.
  24. char buf[max_digits];
  25. int write_index = max_digits - 1;
  26. if (n == 0) {
  27. buf[write_index] = '0';
  28. } else {
  29. while (n > 0) {
  30. int units = n % 10;
  31. buf[write_index--] = "0123456789"[units];
  32. n = (n - units) / 10;
  33. }
  34. write_index++;
  35. }
  36. assert(write_index >= 0);
  37. return std::string(buf + write_index, max_digits - write_index);
  38. }
  39. } // namespace spvtools