while TStream_TryRead() do

It has always irked me that in C you can write:

while (0<(BytesRead=Read(...))) {
  // ..
}

But in Delphi you have to use the much less readable

BytesRead := Stream.Read(Buffer, BufSize);
while BytesRead > 0 do begin
  // ..
  BytesRead := Stream.Read(Buffer, BufSize);
end;

Today I had enough and wrote these simple helper functions:

function TStream_TryRead(_st: TStream; var _Buffer: TBytes; _Count: Int32; out _BytesRead: Int32): Boolean; overload; inline;
begin
  _BytesRead := _st.Read(_Buffer, _Count);
  Result := (_BytesRead > 0);
end;

function TStream_TryRead(_st: TStream; var _Buffer; _Count: Int32; out _BytesRead: Int32): Boolean; overload; inline;
begin
  _BytesRead := _st.Read(_Buffer, _Count);
  Result := (_BytesRead > 0);
end;

function TStream_TryRead(_st: TStream; _Buffer: TBytes; _Offset, _Count: Int32; out _BytesRead: Int32): Boolean; overload; inline;
begin
  _BytesRead := _st.Read(_Buffer, _Offset, _Count);
  Result := (_BytesRead > 0);
end;

function TStream_TryRead(_st: TStream; _Buffer: TBytes; _Offset, _Count: Int64; out _BytesRead: Int64): Boolean; overload; inline;
begin
  _BytesRead := _st.Read64(_Buffer, _Offset, _Count);
  Result := (_BytesRead > 0);
end;

With these you can write:

  while TStream_TryRead(Buffer, BufSize, BytesRead) do begin
    // ..
  end;

Yes, that’s far from being rocket science. It’s probably possible to convert these into a class helper, but I can’t be bothered.