%ByteBufferHandleWrapper
% A class that wraps a ByteBufferHandle in a RAII pattern MCOS class.

%   Copyright 2015-2016 The MathWorks, Inc.

classdef (Sealed, Hidden) ByteBufferHandleWrapper < handle
    
    properties (SetAccess = private)
        BufferHandle; % The actual ByteBufferHandle instance.
    end
    
    methods (Static)
        % Create a ByteBufferHandle by serializing the given data.
        %
        % This uses distcompserialize64 as Parallel Computing Toolbox is not
        % supported on 32-bit platforms.
        function obj = serialize(input)
            import parallel.internal.mapreduce.ByteBufferHandleWrapper
            obj = ByteBufferHandleWrapper(distcompMakeByteBufferHandle(distcompserialize64(input)));
        end
        
        % Wrap an array of ByteBufferHandle instances.
        %
        % Note, this puts each new Wrapper instance in a new output
        % variable.
        function [varargout] = createFromArray(array)
            import parallel.internal.mapreduce.ByteBufferHandleWrapper
            varargout = arrayfun(@ByteBufferHandleWrapper, array, 'UniformOutput', false);
        end
    end
    
    methods
        % Deserialize the given ByteBufferHandle instance back into MATLAB
        % data.
        function data = deserialize(obj)
            data = distcompdeserialize(obj.BufferHandle.get());
        end

        % Cleanup.
        function delete(obj)
            if ~isempty(obj.BufferHandle)
                obj.BufferHandle.free();
                obj.BufferHandle = [];
            end
        end
    end
    
    methods (Access = private)
        % Private constructor for static build methods.
        function obj = ByteBufferHandleWrapper(handle)
            obj.BufferHandle = handle;
        end
    end
    
end
