classdef (Hidden = true) LinkObjChecksumCache < handle
%LinkObjChecksumCache is singleton object caching link object checksum
%data as performance optization

% Copyright 2019 The MathWorks, Inc.

properties (SetAccess=private, GetAccess=public)
ChecksumData
end

methods(Static)
function varargout = instance(action, varargin)

persistent handle;
if strcmp(action, 'initializeCsData')
% Cleanup function to restore the previous cached data
if ~isempty(handle)
if handle.ChecksumData.Count > 0
% Deep copy
originalData = containers.Map...
(handle.ChecksumData.keys, handle.ChecksumData.values);
else
originalData = containers.Map;
end
else
originalData = [];
end
varargout{1} = onCleanup(...
@()coder.make.internal.LinkObjChecksumCache.instance('restoreCsData', originalData));
if isempty(varargin{1})
handle = coder.make.internal.LinkObjChecksumCache;
else
handle = varargin{1};
end
elseif strcmp(action, 'restoreCsData')
% Restore the previous cache
if ~isa(varargin{1}, 'containers.Map')
handle = [];
else
handle = coder.make.internal.LinkObjChecksumCache;
handle.ChecksumData = varargin{1};
end
elseif strcmp(action, 'getCsData')
varargout{1} = handle;
else
assert(false, 'Invalid action for instance function')
end
end
end

methods(Access=private)

function this = LinkObjChecksumCache
this.ChecksumData = containers.Map;
end

end

methods(Access = public)

function updateCsCache(this, compileInfoFolder, checksums)
this.ChecksumData(compileInfoFolder) = checksums;
end

end

methods(Access=public, Static=true)

function checksums = getChecksumData(lCompileInfoFile)

this = coder.make.internal.LinkObjChecksumCache.instance('getCsData');
compileInfoFolder = fileparts(lCompileInfoFile);

if ~isempty(this) && isKey(this.ChecksumData, compileInfoFolder)
% Required data is in the cache: return it
checksums = this.ChecksumData(compileInfoFolder);
else
% Load the data
checksums = coder.make.internal.CompileInfoFile.getManagedLinkObjChecksums...
(lCompileInfoFile);

if ~isempty(this)
% Populate the cache
updateCsCache(this, compileInfoFolder, checksums);
end
end

end

end
end