rbmatlab  1.16.09
 All Classes Namespaces Files Functions Variables Modules Pages
cache.m
1 function res = cache(command, fn, varargin)
2 %function res = cache(command, fn, varargin)
3 %
4 % function simulating a ram-disk.
5 %
6 % D = cache('load','myfile') : loading of myfile from cache. If not
7 % in cache, the real file is loaded. Take
8 % care: if the file is changed while data is
9 % in cache, this is not detected!
10 % D = cache('clear','myfile') : clearing myfile from cache.
11 % D = cache('clear') : the whole cache is cleared.
12 % cache('save', 'myfile', data): saving data to myfile in
13 % cache, no real saving to disk is performed!
14 % list = cache('list') : return list of current entries
15 % res = cache('exist',fn) : 1 if dataset exists in cache, 0 otherwise
16 % cache('limit',limsize) : sets the size limit to limsize (in byte)
17 % default: 1 MB
18 
19 % Bernard Haasdonk 23.8.2007
20 
21 persistent keys data limsize
22 
23 if isempty(limsize)
24  limsize = 10000000;
25 end;
26 
27 %i = find(ismember(keys,fn));
28 
29 switch command
30  case 'exist'
31  res = 0;
32 
33  for j=1:length(keys)
34  if length(keys{j})==length(fn) & ...
35  isequal(keys{j},fn)
36  res = 1;
37  return;
38  end;
39  end;
40 
41  case 'load'
42 
43  i = [];
44  for j=1:length(keys)
45  if length(keys{j})==length(fn) & ...
46  isequal(keys{j},fn)
47  i = j;
48  end;
49  end;
50 
51  if ~isempty(i)
52  res = data{i};
53  else
54  res = load(fn);
55  data{end+1} = res;
56  keys{end+1} = fn;
57  end;
58 
59  case 'save'
60 
61  i = [];
62  for j=1:length(keys)
63  if length(keys{j})==length(fn) & ...
64  isequal(keys{j},fn)
65  i = j;
66  end;
67  end;
68 
69  if ~isempty(i)
70  data{i} = varargin{1};
71  else
72  data{end+1} = varargin{1};
73  keys{end+1} = fn;
74  end;
75 
76  case 'clear'
77 
78  if nargin < 2 % clear all entries
79  keys = {};
80  data = {};
81 
82  else % clear entries matching with filename
83  i = [];
84  for j=1:length(keys)
85  if length(keys{j})==length(fn) & ...
86  isequal(keys{j},fn)
87  i = j;
88  end;
89  end;
90 
91  j = ones(1,length(keys))
92  j(i) = 0;
93  jj = find(j);
94  keys = keys(jj);
95  data = data(jj);
96  res = [];
97  end;
98 
99  case 'list'
100  res = keys;
101 
102  case 'limit'
103  limsize = fn;
104 
105  otherwise
106  error('command unknown')
107 end;
108 
109 s = whos('data');
110 su = sum(s.bytes);
111 if su>limsize
112  disp(['warning: cache size ',num2str(su),' bytes exceeds limit. Delete entries or rise limit.']);
113 end;
114 
115 %| \docupdate