[haiku-commits] Re: r40800 - haiku/trunk/src/add-ons/translators/raw

  • From: Ingo Weinhold <ingo_weinhold@xxxxxx>
  • To: haiku-commits@xxxxxxxxxxxxx
  • Date: Sat, 05 Mar 2011 00:15:27 +0100

On 2011-03-04 at 13:46:38 [+0100], Ryan Leavengood <leavengood@xxxxxxxxx> 
wrote:
> Given your concern over mixing status_t and ssize_t probably most of
> the methods of this class need to be changed not to assign the result
> of reading the stream to fError. So probably something like:
> 
> template<class T> inline void
> operator()(T &data)
> {
>     ssize_t bytesRead = fStream.Read((void *)&data, sizeof(T));
>     if (bytesRead > 0) {
>         if (IsSwapping())
>             byte_swap(data);
>         return;
>     }
> 
>     if (bytesRead == 0)
>         fError = B_ERROR;
>     throw fError;
> }

Actually the correct handling, if you expect to read a certain amount of 
data, is (in pseudo code):

        size_t bytesExpected = ...;

        ssize_t bytesRead = read bytesExpected bytes from source
        if (bytesRead < 0)
                bail out with error code bytesRead
        if ((size_t)bytesRead != bytesExpected)
                bail out with general error (or handle partial read)

        handle success ...

If you also want to deal correctly with FIFOs, sockets, etc., the full 
version is:

        size_t bytesExpected = ...;

        while (bytesExpected > 0) {
                ssize_t bytesRead = read bytesExpected bytes from source
                if (bytesRead < 0)
                        bail out with error code bytesRead
                if (bytesRead == 0)
                        bail out with general error (or handle partial read)

                bytesExpected -= bytesRead
        }

        handle success ...

CU, Ingo

Other related posts: