From 496bcff52bf95961f1314e023e05e8f630e74e03 Mon Sep 17 00:00:00 2001 From: Vadim Zeitlin Date: Mon, 30 Jun 2014 01:00:45 +0000 Subject: [PATCH] Check for conversion failure correctly in wx[F]File::Write(). Check for the length of the buffer to determine whether the conversion failed instead of checking whether it's NULL because this is currently never the case because of the code in wxString::AsCharBuf() which returns "" and not NULL in case of conversion failure. This at least eliminates silent data loss when saving data that can't be converted to the current locale encoding. Closes #16348. git-svn-id: https://svn.wxwidgets.org/svn/wx/wxWidgets/trunk@76798 c3d73ce0-8a6f-49c7-b76d-6d57e0e08775 --- src/common/ffile.cpp | 23 +++++++++++++++++------ src/common/file.cpp | 23 +++++++++++++++++------ 2 files changed, 34 insertions(+), 12 deletions(-) diff --git a/src/common/ffile.cpp b/src/common/ffile.cpp index a302d16373..1f729c2cc2 100644 --- a/src/common/ffile.cpp +++ b/src/common/ffile.cpp @@ -155,17 +155,28 @@ size_t wxFFile::Write(const void *pBuf, size_t nCount) bool wxFFile::Write(const wxString& s, const wxMBConv& conv) { - const wxWX2MBbuf buf = s.mb_str(conv); - if ( !buf ) - return false; + // Writing nothing always succeeds -- and simplifies the check for + // conversion failure below. + if ( s.empty() ) + return true; + + const wxWX2MBbuf buf = s.mb_str(conv); #if wxUSE_UNICODE - const size_t size = buf.length(); + const size_t size = buf.length(); + + if ( !size ) + { + // This means that the conversion failed as the original string wasn't + // empty (we explicitly checked for this above) and in this case we + // must fail too to indicate that we can't save the data. + return false; + } #else - const size_t size = s.length(); + const size_t size = s.length(); #endif - return Write(buf, size) == size; + return Write(buf, size) == size; } bool wxFFile::Flush() diff --git a/src/common/file.cpp b/src/common/file.cpp index e363493554..018816f80a 100644 --- a/src/common/file.cpp +++ b/src/common/file.cpp @@ -351,17 +351,28 @@ size_t wxFile::Write(const void *pBuf, size_t nCount) bool wxFile::Write(const wxString& s, const wxMBConv& conv) { - const wxWX2MBbuf buf = s.mb_str(conv); - if ( !buf ) - return false; + // Writing nothing always succeeds -- and simplifies the check for + // conversion failure below. + if ( s.empty() ) + return true; + + const wxWX2MBbuf buf = s.mb_str(conv); #if wxUSE_UNICODE - const size_t size = buf.length(); + const size_t size = buf.length(); + + if ( !size ) + { + // This means that the conversion failed as the original string wasn't + // empty (we explicitly checked for this above) and in this case we + // must fail too to indicate that we can't save the data. + return false; + } #else - const size_t size = s.length(); + const size_t size = s.length(); #endif - return Write(buf, size) == size; + return Write(buf, size) == size; } // flush