rbmatlab 0.10.01
|
00001 function res = cache(command, fn, varargin) 00002 %function res = cache(command, fn, varargin) 00003 % 00004 % function simulating a ram-disk. 00005 % 00006 % D = cache('load','myfile') : loading of myfile from cache. If not 00007 % in cache, the real file is loaded. Take 00008 % care: if the file is changed while data is 00009 % in cache, this is not detected! 00010 % D = cache('clear','myfile') : clearing myfile from cache. 00011 % D = cache('clear') : the whole cache is cleared. 00012 % cache('save', 'myfile', data): saving data to myfile in 00013 % cache, no real saving to disk is performed! 00014 % list = cache('list') : return list of current entries 00015 % res = cache('exist',fn) : 1 if dataset exists in cache, 0 otherwise 00016 % cache('limit',limsize) : sets the size limit to limsize (in byte) 00017 % default: 1 MB 00018 00019 % Bernard Haasdonk 23.8.2007 00020 00021 persistent keys data limsize 00022 00023 if isempty(limsize) 00024 limsize = 10000000; 00025 end; 00026 00027 %i = find(ismember(keys,fn)); 00028 00029 switch command 00030 case 'exist' 00031 res = 0; 00032 00033 for j=1:length(keys) 00034 if length(keys{j})==length(fn) & ... 00035 isequal(keys{j},fn) 00036 res = 1; 00037 return; 00038 end; 00039 end; 00040 00041 case 'load' 00042 00043 i = []; 00044 for j=1:length(keys) 00045 if length(keys{j})==length(fn) & ... 00046 isequal(keys{j},fn) 00047 i = j; 00048 end; 00049 end; 00050 00051 if ~isempty(i) 00052 res = data{i}; 00053 else 00054 res = load(fn); 00055 data{end+1} = res; 00056 keys{end+1} = fn; 00057 end; 00058 00059 case 'save' 00060 00061 i = []; 00062 for j=1:length(keys) 00063 if length(keys{j})==length(fn) & ... 00064 isequal(keys{j},fn) 00065 i = j; 00066 end; 00067 end; 00068 00069 if ~isempty(i) 00070 data{i} = varargin{1}; 00071 else 00072 data{end+1} = varargin{1}; 00073 keys{end+1} = fn; 00074 end; 00075 00076 case 'clear' 00077 00078 if nargin < 2 % clear all entries 00079 keys = {}; 00080 data = {}; 00081 00082 else % clear entries matching with filename 00083 i = []; 00084 for j=1:length(keys) 00085 if length(keys{j})==length(fn) & ... 00086 isequal(keys{j},fn) 00087 i = j; 00088 end; 00089 end; 00090 00091 j = ones(1,length(keys)) 00092 j(i) = 0; 00093 jj = find(j); 00094 keys = keys(jj); 00095 data = data(jj); 00096 res = []; 00097 end; 00098 00099 case 'list' 00100 res = keys; 00101 00102 case 'limit' 00103 limsize = fn; 00104 00105 otherwise 00106 error('command unknown') 00107 end; 00108 00109 s = whos('data'); 00110 su = sum(s.bytes); 00111 if su>limsize 00112 disp(['warning: cache size ',num2str(su),' bytes exceeds limit. Delete entries or rise limit.']); 00113 end; 00114 00115 %| \docupdate