% Convert bytes to diary text

%   Copyright 2020 The MathWorks, Inc.

function text = getDiaryFromBytes(rawBytes, blockSize)
    % The diary output has been streamed to the job manager in
    % UTF-16. To overcome a limitation of native2unicode only
    % supporting inputs with fewer than 2^30 bytes, we must use a
    % loop to stitch together longer diary. See g1988945.

    % Default to the largest supported size that is supported by
    % native2unicode and is divisible by 2 (can be overridden for
    % testing).
    %
    % NB: Some UTF-16LE characters are 4 bytes long and will be
    % corrupted if the block size happens to split them. However,
    % subsequent characters will not be corrupted.
    if nargin < 2
        blockSize = 2^30 - 2;
    end

    numBytes = numel(rawBytes);
    text = '';
    low = 1;
    while low <= numBytes
        high = min(low + blockSize - 1, numBytes);
        diaryBlock = native2unicode(rawBytes(low:high), 'UTF-16LE')';
        text = [text, diaryBlock]; %#ok<AGROW> diaryBlock length is not guaranteed by native2unicode
        low = high + 1;
    end
end

