function dh = dispInternal( obj, className, objName )
;%#ok<NOSEM> Undocumented

% Use shared DisplayHelpers to work out how to display an array

% Copyright 2008-2019 The MathWorks, Inc.

if existsOnGPU( obj )
    N  = 1000;
    dh = parallel.internal.shared.buildDisplayHelper( ...
        obj, @iTransferPortionDense, @iTransferAndTruncateSparse, ...
        objName, className, N );
else
    % Doesn't exist on GPU. Check if we can still gather.
    if canGather( obj )
        msg = getString(message('parallel:gpu:array:InvalidDataCanGather'));
    else
        msg = getString(message('parallel:gpu:array:NoLongerExists'));
    end
    dh = parallel.internal.shared.DisplayHelperInvalid( objName, className, msg );
end
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function data = iTransferAndTruncateSparse( x, N )
[i, j, v] = find( x, N, 'first' );
data = sparse( gather(i), gather(j), gather(v) );
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Gather a portion of the array
function data = iTransferPortionDense( x, rangeStruct )
N = numel( rangeStruct.start );
szArgs = cell( N, 1 );
for ii=1:N
    szArgs{ii} = rangeStruct.start(ii):rangeStruct.end(ii);
end
% Form subsref parameters
s = struct( 'type', '()', 'subs', {szArgs} );
data = gather( subsref( x, s ) );
end
