-
Notifications
You must be signed in to change notification settings - Fork 37
/
LagStepImpl.cs
443 lines (369 loc) · 14.6 KB
/
LagStepImpl.cs
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
using Spreads.Utils;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace Spreads.Cursors.Internal
{
// Value is lagged cursor.
internal struct LagStepImpl<TKey, TValue, TCursor> :
ICursorSeries<TKey, TCursor, LagStepImpl<TKey, TValue, TCursor>>
where TCursor : ISpecializedCursor<TKey, TValue, TCursor>
{
#region Cursor state
// This region must contain all cursor state that is passed via constructor.
// No additional state must be created.
// All state elements should be assigned in Initialize and Clone methods
// All inner cursors must be disposed in the Dispose method but references to them must be kept (they could be used as factories)
// for re-initialization.
// NB must be mutable, could be a struct
// ReSharper disable once FieldCanBeMadeReadOnly.Local
internal TCursor _cursor;
// ReSharper disable once FieldCanBeMadeReadOnly.Local
internal TCursor _laggedCursor;
internal int _width;
internal int _step;
internal bool _allowIncomplete;
internal int _currentWidth;
internal CursorState State { get; set; }
internal TCursor CurrentCursor
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return _cursor; }
}
internal TCursor LaggedCursor
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return _laggedCursor; }
}
#endregion Cursor state
#region Constructors
internal LagStepImpl(TCursor cursor, int width = 1, int step = 1, bool allowIncomplete = false) : this()
{
if (width <= 0) { ThrowHelper.ThrowArgumentOutOfRangeException(nameof(width)); }
if (step <= 0) { ThrowHelper.ThrowArgumentOutOfRangeException(nameof(step)); }
if (allowIncomplete && _step > 1) { ThrowHelper.ThrowNotImplementedException("TODO incomplete with step is not implemented"); }
_cursor = cursor;
_width = width;
_step = step;
_allowIncomplete = allowIncomplete;
}
#endregion Constructors
#region Lifetime management
/// <inheritdoc />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public LagStepImpl<TKey, TValue, TCursor> Clone()
{
var instance = new LagStepImpl<TKey, TValue, TCursor>
{
_cursor = _cursor.Clone(),
_laggedCursor = _laggedCursor.Clone(),
_width = _width,
_step = _step,
_allowIncomplete = _allowIncomplete,
_currentWidth = _currentWidth,
State = State
};
return instance;
}
/// <inheritdoc />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public LagStepImpl<TKey, TValue, TCursor> Initialize()
{
var instance = new LagStepImpl<TKey, TValue, TCursor>
{
_cursor = _cursor.Initialize(),
_laggedCursor = _cursor.Initialize(),
_width = _width,
_step = _step,
_allowIncomplete = _allowIncomplete,
_currentWidth = 0,
State = CursorState.Initialized
};
return instance;
}
/// <inheritdoc />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
{
// NB keep cursor state for reuse
// dispose is called on the result of Initialize(), the cursor from
// constructor could be uninitialized but contain some state, e.g. _value for this FillCursor
_cursor.Dispose();
_laggedCursor.Dispose();
State = CursorState.None;
}
/// <inheritdoc />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Reset()
{
_cursor.Reset();
_laggedCursor.Reset();
State = CursorState.Initialized;
}
ICursor<TKey, TCursor> ICursor<TKey, TCursor>.Clone()
{
return Clone();
}
#endregion Lifetime management
#region ICursor members
/// <inheritdoc />
public KeyValuePair<TKey, TCursor> Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return new KeyValuePair<TKey, TCursor>(CurrentKey, CurrentValue); }
}
/// <inheritdoc />
public TKey CurrentKey
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return _cursor.CurrentKey; }
}
/// <inheritdoc />
public TCursor CurrentValue
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return _laggedCursor; }
}
/// <inheritdoc />
public IReadOnlySeries<TKey, TCursor> CurrentBatch => null;
/// <inheritdoc />
public KeyComparer<TKey> Comparer => _cursor.Comparer;
object IEnumerator.Current => Current;
/// <summary>
/// LagImpl cursor is discrete even if its input cursor is continuous.
/// </summary>
public bool IsContinuous => false;
/// <inheritdoc />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool TryGetValue(TKey key, out TCursor value)
{
throw new NotSupportedException();
}
/// <inheritdoc />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveAt(TKey key, Lookup direction)
{
if (State == CursorState.None)
{
ThrowHelper.ThrowInvalidOperationException($"ICursorSeries {GetType().Name} is not initialized as a cursor. Call the Initialize() method and *use* (as IDisposable) the returned value to access ICursor MoveXXX members.");
}
var wasMoving = State == CursorState.Moving;
var ck = wasMoving ? _cursor.CurrentKey : default(TKey);
var lk = wasMoving ? _laggedCursor.CurrentKey : default(TKey);
var moved = _cursor.MoveAt(key, direction);
if (moved)
{
if (wasMoving)
{
_laggedCursor.Dispose();
}
_laggedCursor = _cursor.Clone();
// step is irrelevant here, need to move lagged by width
_currentWidth = 1;
while (_currentWidth < _width)
{
moved = _laggedCursor.MovePrevious();
_currentWidth++;
}
// NB important to do inside if, first move must be true
moved = moved || _allowIncomplete;
}
if (moved)
{
State = CursorState.Moving;
}
else if (wasMoving && !_cursor.MoveAt(ck, Lookup.EQ) && _laggedCursor.MoveAt(lk, Lookup.EQ))
{
ThrowHelper.ThrowOutOfOrderKeyException(ck);
}
return moved;
}
/// <inheritdoc />
[MethodImpl(MethodImplOptions.NoInlining)] // NB NoInlining is important to speed-up MoveNext
public bool MoveFirst()
{
if (State == CursorState.None)
{
ThrowHelper.ThrowInvalidOperationException($"ICursorSeries {GetType().Name} is not initialized as a cursor. Call the Initialize() method and *use* (as IDisposable) the returned value to access ICursor MoveXXX members.");
}
var wasMoving = State == CursorState.Moving;
var moved = _cursor.MoveFirst();
if (moved)
{
if (wasMoving)
{
_laggedCursor.Dispose();
}
_laggedCursor = _cursor.Clone();
_currentWidth = 1;
while (_currentWidth < _width)
{
moved = _cursor.MoveNext();
_currentWidth++;
}
// NB important to do inside if, first move must be true
moved = moved || _allowIncomplete;
}
if (moved)
{
State = CursorState.Moving;
}
else if (State == CursorState.Moving)
{
// if cursor was moving that it must have had at least one value
ThrowHelper.ThrowOutOfOrderKeyException(_cursor.CurrentKey);
}
return moved;
}
/// <inheritdoc />
[MethodImpl(MethodImplOptions.NoInlining)] // NB NoInlining is important to speed-up MovePrevious
public bool MoveLast()
{
if (State == CursorState.None)
{
ThrowHelper.ThrowInvalidOperationException($"ICursorSeries {GetType().Name} is not initialized as a cursor. Call the Initialize() method and *use* (as IDisposable) the returned value to access ICursor MoveXXX members.");
}
var wasMoving = State == CursorState.Moving;
var moved = _cursor.MoveFirst();
if (moved)
{
if (wasMoving)
{
_laggedCursor.Dispose();
}
_laggedCursor = _cursor.Clone();
_currentWidth = 1;
while (_currentWidth < _width)
{
moved = _laggedCursor.MovePrevious();
_currentWidth++;
}
// NB important to do inside if, first move must be true
moved = moved || _allowIncomplete;
}
if (moved)
{
State = CursorState.Moving;
}
else if (State == CursorState.Moving)
{
// if cursor was moving that it must have had at least one value
ThrowHelper.ThrowOutOfOrderKeyException(_cursor.CurrentKey);
}
return moved;
}
/// <inheritdoc />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
if (State < CursorState.Moving) return MoveFirst();
var ck = _cursor.CurrentKey;
if (_allowIncomplete) ThrowHelper.ThrowNotImplementedException("TODO");
var moved = false;
var moves = 0;
while (moves < _step)
{
moved = _cursor.MoveNext() && _laggedCursor.MoveNext(); // NB order, lagged moves only after current moves
moves++;
}
if (!moved)
{
// roll back
for (var i = 0; i < moves; i++)
{
try
{
var movedBack = _cursor.MovePrevious() && _laggedCursor.MovePrevious();
if (!movedBack)
{
ThrowHelper.ThrowInvalidOperationException("MovePrevious should succeed after MoveNext or throw OutOfOrderKeyException");
}
}
catch (OutOfOrderKeyException<TKey>)
{
ThrowHelper.ThrowOutOfOrderKeyException(ck);
}
}
}
return moved;
}
/// <inheritdoc />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Task<bool> MoveNextBatch(CancellationToken cancellationToken)
{
if (State == CursorState.None)
{
ThrowHelper.ThrowInvalidOperationException($"CursorSeries {GetType().Name} is not initialized as a cursor. Call the Initialize() method and *use* (as IDisposable) the returned value to access ICursor MoveXXX members.");
}
return TaskUtil.FalseTask;
}
/// <inheritdoc />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MovePrevious()
{
if (State < CursorState.Moving) return MoveLast();
var ck = _cursor.CurrentKey;
if (_allowIncomplete) ThrowHelper.ThrowNotImplementedException("TODO");
var moved = false;
var moves = 0;
while (moves < _step)
{
moved = _laggedCursor.MovePrevious() && _cursor.MovePrevious(); // NB order, current moves only after lagged moves
moves++;
}
if (!moved)
{
// roll back
for (var i = 0; i < moves; i++)
{
try
{
var moveForward = _laggedCursor.MoveNext() && _cursor.MoveNext();
if (!moveForward)
{
ThrowHelper.ThrowInvalidOperationException("MoveNext should succeed after MovePrevious or throw OutOfOrderKeyException");
}
}
catch (OutOfOrderKeyException<TKey>)
{
ThrowHelper.ThrowOutOfOrderKeyException(ck);
}
}
}
return moved;
}
/// <inheritdoc />
IReadOnlySeries<TKey, TCursor> ICursor<TKey, TCursor>.Source => new Series<TKey, TCursor, LagStepImpl<TKey, TValue, TCursor>>(this);
/// <summary>
/// Get a <see cref="Series{TKey,TValue,TCursor}"/> based on this cursor.
/// </summary>
public Series<TKey, TCursor, LagStepImpl<TKey, TValue, TCursor>> Source => new Series<TKey, TCursor, LagStepImpl<TKey, TValue, TCursor>>(this);
/// <inheritdoc />
public Task<bool> MoveNext(CancellationToken cancellationToken)
{
throw new NotSupportedException();
}
#endregion ICursor members
#region ICursorSeries members
/// <inheritdoc />
public bool IsIndexed => _cursor.Source.IsIndexed;
/// <inheritdoc />
public bool IsReadOnly
{
// NB this property is repeatedly called from MNA
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return _cursor.Source.IsReadOnly; }
}
/// <inheritdoc />
public Task<bool> Updated
{
// NB this property is repeatedly called from MNA
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return _cursor.Source.Updated; }
}
#endregion ICursorSeries members
}
}