diff --git a/src/textstream/textstream.h b/src/textstream/textstream.h index d43a8c7..9b17b32 100644 --- a/src/textstream/textstream.h +++ b/src/textstream/textstream.h @@ -5,7 +5,7 @@ */ /* - * Copyright (c) 2012-2022, Tomasz Sowa + * Copyright (c) 2012-2023, Tomasz Sowa * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -155,6 +155,13 @@ public: std::string to_str() const; std::wstring to_wstr() const; + /* + * returns true if the buffer was sufficient large and there were no convertion errors + */ + bool to_str(char * str, size_t max_buf_len) const; + bool to_str(wchar_t * str, size_t max_buf_len) const; + + char get_char(size_t index) const; wchar_t get_wchar(size_t index) const; @@ -597,7 +604,6 @@ void TextStreamBase::to_str(std::string if( str.capacity() < str.size() + size() ) str.reserve(str.size() + size()); - if constexpr (sizeof(char_type) == sizeof(char) ) { const_iterator i = begin(); @@ -658,6 +664,89 @@ std::wstring TextStreamBase::to_wstr() c } + +template +bool TextStreamBase::to_str(char * str, size_t max_buf_len) const +{ + bool converted_correctly = false; + + if( max_buf_len > 0 ) + { + if constexpr (sizeof(char_type) == sizeof(char) ) + { + converted_correctly = true; + const_iterator i = begin(); + const_iterator i_end = end(); + size_t len = 0; + max_buf_len -= 1; // for terminating null character + + for( ; i != i_end ; ++i, ++len) + { + if( len < max_buf_len ) + { + str[len] = *i; + } + else + { + converted_correctly = false; + break; + } + } + + str[len] = 0; + } + else + { + converted_correctly = wide_stream_to_utf8(*this, str, max_buf_len); + } + } + + return converted_correctly; +} + + + +template +bool TextStreamBase::to_str(wchar_t * str, size_t max_buf_len) const +{ + bool converted_correctly = false; + + if( max_buf_len > 0 ) + { + if constexpr (sizeof(char_type) == sizeof(wchar_t) ) + { + converted_correctly = true; + const_iterator i = begin(); + const_iterator i_end = end(); + size_t len = 0; + max_buf_len -= 1; // for terminating null character + + for( ; i != i_end ; ++i, ++len) + { + if( len < max_buf_len ) + { + str[len] = *i; + } + else + { + converted_correctly = false; + break; + } + } + + str[len] = 0; + } + else + { + converted_correctly = utf8_to_wide(*this, str, max_buf_len); + } + } + + return converted_correctly; +} + + + template char TextStreamBase::get_char(size_t index) const {