Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: d184e7eb7eeeafe01bfa4813919d0bd7747c848a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
/*******************************************************************************
 * Copyright (c) 2014 Wind River Systems, Inc. and others. All rights reserved.
 * This program and the accompanying materials are made available under the terms
 * of the Eclipse Public License v1.0 which accompanies this distribution, and is
 * available at http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Wind River Systems - initial API and implementation
 *******************************************************************************/
package org.eclipse.tcf.debug.test.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ExecutionException;

import org.eclipse.tcf.protocol.Protocol;

/**
 * Cache for efficiently retrieving overlapping ranges of elements from an
 * asynchronous data source. The results of a range request (see
 * {@link #getRange(long, int)}) are kept around and reused in subsequent
 * requests. E.g., two individual, initial requests for 4 bytes at offsets 0 and
 * 4 will relieve a subsequent request for 4 bytes at offset 2 from having to
 * asynchronously retrieve the data from the source. The results from the first
 * two range requests are used to service the third.
 * 
 * <p>
 * Clients of this cache should call {@link #getRange(long, int)} to get a cache
 * for that given range of elements. Sub-classes must implement
 * {@link #retrieve(long, int, DataRequestMonitor)} to retrieve data from the
 * asynchronous data source.
 * 
 * 
 * 
 * @since 2.2
 */
abstract public class RangeCache<V> {
    
    private class Request extends CallbackCache<List<V>> implements Comparable<Request> {
        long fOffset;
        int fCount;
        @Override
        protected void retrieve(DataCallback<java.util.List<V>> rm) {
            RangeCache.this.retrieve(fOffset, fCount, rm); 
        }
        
        Request(long offset, int count) {
            fOffset = offset;
            fCount = count;
        }
        
        public int compareTo(RangeCache<V>.Request o) {
            if (fOffset > o.fOffset) {
                return 1;
            } else if (fOffset == o.fOffset) {
                return 0;
            } else /*if (fOffset < o.fOffset)*/ {
                return -1;
            }
        }
        
        @Override
        public boolean equals(Object _o) {
            if (_o instanceof RangeCache<?>.Request) {
                RangeCache<?>.Request o = (RangeCache<?>.Request)_o;
                return fOffset == o.fOffset && fCount == o.fCount;
            }
            return false;
        }
        
        @Override
        public int hashCode() {
            return (int)fOffset^fCount;
        }
        
        @Override
        public String toString() {
            return "" + fOffset + "(" + fCount + ") -> " + (fOffset + fCount); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        }
    }

    /**
     * This transaction class implements the main logic of the range cache. 
     * It examines the current requests held by the cache and and creates 
     * requests ones as needed.  Once the requests are all valid it returns
     * the completed data to the client.
     */
    private class RangeTransaction extends Transaction<List<V>> { 
        
        long fOffset;
        int fCount;

        RangeTransaction(long offset, int count) {
            fOffset = offset;
            fCount = count;
        }
        @Override
        protected List<V> process() throws InvalidCacheException, ExecutionException {
            clearCanceledRequests();
            
            List<Request> transactionRequests = getRequests(fOffset, fCount);
            validate(transactionRequests);

            return makeElementsListFromRequests(transactionRequests, fOffset, fCount);
        }
                
        private void clearCanceledRequests() {
            for (Iterator<Request> itr = fRequests.iterator(); itr.hasNext();) {
                Request request = itr.next();
                if (!request.isValid() && request.isCanceled()) {
                    itr.remove();
                }
            }
        }
    }

    /**
     * Requests currently held by this cache.  The requests should be for 
     * non-overlapping ranges of elements.  
     */
    
    private SortedSet<Request> fRequests = new TreeSet<Request>(); 

    /**
     * Retrieves data from the data source. 
     * 
     * @param offset Offset in data range where the requested list of data should start.
     * @param count Number of elements requests.
     * @param rm Callback for the data.
     */
    protected abstract void retrieve(long offset, int count, DataCallback<List<V>> rm);
    
    /**
     * Returns a cache for the range of requested data.  The cache object needs 
     * to be retrieved from range cache every time that the cache is a
     * 
     * @param offset Offset in data range where the requested list of data should start.
     * @param count Number of elements requests.
     * @return Cache object for the requested data.  
     */
    public ICache<List<V>> getRange(final long offset, final int count) {
        assert Protocol.isDispatchThread();
        
        List<Request> requests = getRequests(offset, count);
        
        CallbackCache<List<V>> range = new CallbackCache<List<V>>() {
            @Override
            protected void retrieve(DataCallback<List<V>> rm) {
                new RangeTransaction(offset, count).request(rm);
            }
        };
        
        boolean valid = true;
        List<Throwable> errors = null; 
        for (ICache<?> request : requests) {
            if (request.isValid()) {
                if (request.getError() != null) {
                    errors = errors != null ? errors : new ArrayList<Throwable>(requests.size());
                    errors.add(request.getError());
                }
            } else {
                valid = false;
                break;
            }
        }
        
        if (valid) {
            if (errors == null) {
                range.set(makeElementsListFromRequests(requests, offset, count), null, true);
            } else {
                if (errors.size() == 1) {
                    range.set(null, errors.get(0), true);
                } else {
                    AggregateError aggregateError = new AggregateError("Multiple Errors");
                    for (Throwable error : errors) aggregateError.add(error);
                }
            }
        }
        
        return range; 
    }
    
    /**
     * Sets the given list and status to the cache.  Subsequent range requests 
     * that fall in its the range will return the given data.  Requests outside 
     * of its range will trigger a call to {@link #retrieve(long, int, DataRequestMonitor)}.<br>
     * The given data parameter can be <code>null</code> if the given status 
     * parameter contains an error.  In this case all requests in the given 
     * range will return the error. 
     * 
     * @param offset Offset of the given data to set to cache.
     * @param count Count of the given data to set to cache.
     * @param data List of elements to set to cache.  Can be <code>null</code>. 
     * @param error Error object to set to cache or <code>null</code> if none.
     */
    public void set(long offset, int count, List<V> data, Throwable error) {
        for (Request request : fRequests) {
            if (!request.isValid()) {
                request.set(null, null, false);
            }
        }
        fRequests.clear();
        Request request = new Request(offset, count);
        request.set(data, error, true);
        fRequests.add(request);
    }
    
    /**
     * Forces the cache into an invalid state.  If there are any pending 
     * requests, their will continue and their results will be cached. 
     */
    protected void reset() {
        for (Iterator<Request> itr = fRequests.iterator(); itr.hasNext();) {
            Request request = itr.next();
            if (request.isValid()) {
                request.reset();
                itr.remove();
            }
        }
    }
    
    private List<Request> getRequests(long fOffset, int fCount) {
        List<Request> requests = new ArrayList<Request>(1);
        
        // Create a new request for the data to retrieve.
        Request current = new Request(fOffset, fCount);
        
        current = adjustRequestHead(current, requests, fOffset, fCount);
        if (current != null) {
            current = adjustRequestTail(current, requests, fOffset, fCount);
        }
        if (current != null) {
            requests.add(current);
            fRequests.add(current);
        }
        return requests;
    }
    
    // Adjust the beginning of the requested range of data.  If there 
    // is already an overlapping range in front of the requested range, 
    // then use it.
    private Request adjustRequestHead(Request request, List<Request> transactionRequests, long offset, int count) {
        SortedSet<Request> headRequests = fRequests.headSet(request);
        if (!headRequests.isEmpty()) {
            Request headRequest = headRequests.last();
            long headEndOffset = headRequest.fOffset + headRequest.fCount;
            if (headEndOffset > offset) {
                transactionRequests.add(headRequest);
                request.fCount = (int)(request.fCount - (headEndOffset - offset));
                request.fOffset = headEndOffset;
            }
        }
        if (request.fCount > 0) {
            return request;
        } else {
            return null;
        }
    }

    /**
     * Adjust the end of the requested range of data.
     * @param current
     * @param transactionRequests
     * @return
     */
    private Request adjustRequestTail(Request current, List<Request> transactionRequests, long offset, int count) {
        // Create a duplicate of the tailSet, in order to avoid a concurrent modification exception.
        List<Request> tailSet = new ArrayList<Request>(fRequests.tailSet(current));
        
        // Iterate through the matching requests and add them to the requests list.
        for (Request tailRequest : tailSet) {
            if (tailRequest.fOffset < current.fOffset + count) {
                // found overlapping request add it to list
                if (tailRequest.fOffset <= current.fOffset) {
                    // next request starts off at the beginning of current request
                    transactionRequests.add(tailRequest);
                    current.fOffset = tailRequest.fOffset + tailRequest.fCount;
                    current.fCount = ((int)(offset - current.fOffset)) + count ;
                    if (current.fCount <= 0) {
                        return null;
                    }
                } else {
                    current.fCount = (int)(tailRequest.fOffset - current.fOffset);
                    transactionRequests.add(current);
                    fRequests.add(current);
                    current = null;
                    transactionRequests.add(tailRequest);
                    long tailEndOffset = tailRequest.fOffset + tailRequest.fCount;
                    long rangeEndOffset = offset + count;
                    if (tailEndOffset >= rangeEndOffset) {
                        return null;
                    } else {
                        current = new Request(tailEndOffset, (int)(rangeEndOffset - tailEndOffset));
                    }
                }
            } else {
                break;
            }
        }
        return current;
    }
    
    private List<V> makeElementsListFromRequests(List<Request> requests, long offset, int count) {
        List<V> retVal = new ArrayList<V>(count);
        long index = offset;
        long end = offset + count;
        int requestIdx = 0;
        while (index < end ) {
            Request request = requests.get(requestIdx);
            if (index < request.fOffset + request.fCount) {
                int dataIndex = (int)(index - request.fOffset);
                if (dataIndex < request.getData().size()) {
                    retVal.add( request.getData().get(dataIndex) );
                } else {
                    // If request didnt' return enough data, pad range with nulls.
                    retVal.add(null);
                }
                index ++;
            } else {
                requestIdx++;
            }
        }
        return retVal;
    }    
}

Back to the top