string_to_unsigned.hpp 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #ifndef BOOST_THREAD_DETAIL_STRING_TO_UNSIGNED_HPP_INCLUDED
  2. #define BOOST_THREAD_DETAIL_STRING_TO_UNSIGNED_HPP_INCLUDED
  3. // Copyright 2023 Peter Dimov
  4. // Distributed under the Boost Software License, Version 1.0.
  5. // https://www.boost.org/LICENSE_1_0.txt
  6. #include <string>
  7. #include <climits>
  8. namespace boost
  9. {
  10. namespace thread_detail
  11. {
  12. inline bool string_to_unsigned( std::string const& s, unsigned& v )
  13. {
  14. v = 0;
  15. if( s.empty() )
  16. {
  17. return false;
  18. }
  19. for( char const* p = s.c_str(); *p; ++p )
  20. {
  21. unsigned char ch = static_cast<unsigned char>( *p );
  22. if( ch < '0' || ch > '9' )
  23. {
  24. return false;
  25. }
  26. if( v > UINT_MAX / 10 )
  27. {
  28. return false;
  29. }
  30. unsigned q = static_cast<unsigned>( ch - '0' );
  31. if( v == UINT_MAX / 10 && q > UINT_MAX % 10 )
  32. {
  33. return false;
  34. }
  35. v = v * 10 + q;
  36. }
  37. return true;
  38. }
  39. } // namespace thread_detail
  40. } // namespace boost
  41. #endif // #ifndef BOOST_THREAD_DETAIL_STRING_TO_UNSIGNED_HPP_INCLUDED