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 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
|
// Copyright ©2012 The bíogo Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package step implements a step vector type.
//
// A step vector can be used to represent high volume data that would be
// efficiently stored by run-length encoding.
package step
import (
"errors"
"fmt"
"github.com/biogo/store/llrb"
)
var (
ErrOutOfRange = errors.New("step: index out of range")
ErrInvertedRange = errors.New("step: inverted range")
ErrZeroLength = errors.New("step: attempt to create zero length vector")
)
type (
position struct {
pos int
val Equaler
}
lower int
query int
upper int
)
func (p *position) Compare(c llrb.Comparable) int {
return p.pos - c.(*position).pos
}
func (q lower) Compare(c llrb.Comparable) (d int) {
d = int(q) - c.(*position).pos
if d == 0 {
d = -1
}
return
}
func (q query) Compare(c llrb.Comparable) (d int) {
switch c := c.(type) {
case *position:
d = int(q) - c.pos
case query:
d = int(q) - int(c)
}
return
}
func (q upper) Compare(c llrb.Comparable) (d int) {
d = int(q) - c.(*position).pos
if d == 0 {
d = 1
}
return
}
// An Equaler is a type that can return whether it equals another Equaler.
type Equaler interface {
Equal(Equaler) bool
}
// An Int is an int type satisfying the Equaler interface.
type Int int
// Equal returns whether i equals e. Equal assumes the underlying type of e is Int.
func (i Int) Equal(e Equaler) bool {
return i == e.(Int)
}
// A Float is a float64 type satisfying the Equaler interface.
type Float float64
// Equal returns whether f equals e. For the purposes of the step package here, NaN == NaN
// evaluates to true. Equal assumes the underlying type of e is Float.
func (f Float) Equal(e Equaler) bool {
ef := e.(Float)
if f != f && ef != ef { // For our purposes NaN == NaN.
return true
}
return f == ef
}
// A Vector is type that support the storage of array type data in a run-length
// encoding format.
type Vector struct {
Zero Equaler // Ground state for the step vector.
Relaxed bool // If true, dynamic vector resize is allowed.
t llrb.Tree
min, max *position
}
// New returns a new Vector with the extent defined by start and end,
// and the ground state defined by zero. The Vector's extent is mutable
// if the Relaxed field is set to true. If a zero length vector is requested
// an error is returned.
func New(start, end int, zero Equaler) (*Vector, error) {
if start >= end {
return nil, ErrZeroLength
}
v := &Vector{
Zero: zero,
min: &position{
pos: start,
val: zero,
},
max: &position{
pos: end,
val: nil,
},
}
v.t.Insert(v.min)
v.t.Insert(v.max)
return v, nil
}
// Start returns the index of minimum position of the Vector.
func (v *Vector) Start() int { return v.min.pos }
// End returns the index of lowest position beyond the end of the Vector.
func (v *Vector) End() int { return v.max.pos }
// Len returns the length of the represented data array, that is the distance
// between the start and end of the vector.
func (v *Vector) Len() int { return v.End() - v.Start() }
// Count returns the number of steps represented in the vector.
func (v *Vector) Count() int { return v.t.Len() - 1 }
// At returns the value of the vector at position i. If i is outside the extent
// of the vector an error is returned.
func (v *Vector) At(i int) (Equaler, error) {
if i < v.Start() || i >= v.End() {
return nil, ErrOutOfRange
}
st := v.t.Floor(query(i)).(*position)
return st.val, nil
}
// StepAt returns the value and range of the step at i, where start <= i < end.
// If i is outside the extent of the vector, an error is returned.
func (v *Vector) StepAt(i int) (start, end int, e Equaler, err error) {
if i < v.Start() || i >= v.End() {
return 0, 0, nil, ErrOutOfRange
}
lo := v.t.Floor(query(i)).(*position)
hi := v.t.Ceil(upper(i)).(*position)
return lo.pos, hi.pos, lo.val, nil
}
// Set sets the value of position i to e.
func (v *Vector) Set(i int, e Equaler) {
if i < v.min.pos || v.max.pos <= i {
if !v.Relaxed {
panic(ErrOutOfRange)
}
if i < v.min.pos {
if i == v.min.pos-1 {
if e.Equal(v.min.val) {
v.min.pos--
} else {
v.min = &position{pos: i, val: e}
v.t.Insert(v.min)
}
} else {
if v.min.val.Equal(v.Zero) {
v.min.pos = i + 1
} else {
v.min = &position{pos: i + 1, val: v.Zero}
v.t.Insert(v.min)
}
if e.Equal(v.Zero) {
v.min.pos--
} else {
v.min = &position{pos: i, val: e}
v.t.Insert(v.min)
}
}
} else if i >= v.max.pos {
if i == v.max.pos {
v.max.pos++
prev := v.t.Floor(query(i)).(*position)
if !e.Equal(prev.val) {
v.t.Insert(&position{pos: i, val: e})
}
} else {
mpos := v.max.pos
v.max.pos = i + 1
prev := v.t.Floor(query(i)).(*position)
if !prev.val.Equal(v.Zero) {
v.t.Insert(&position{pos: mpos, val: v.Zero})
}
if !e.Equal(v.Zero) {
v.t.Insert(&position{pos: i, val: e})
}
}
}
return
}
lo := v.t.Floor(query(i)).(*position)
if e.Equal(lo.val) {
return
}
hi := v.t.Ceil(upper(i)).(*position)
if lo.pos == i {
if hi.pos == i+1 {
if hi != v.max && e.Equal(hi.val) {
v.t.Delete(query(i))
hi.pos--
if v.min.pos == i {
v.min = hi
}
} else {
lo.val = e
}
if i > v.min.pos {
prev := v.t.Floor(query(i - 1)).(*position)
if e.Equal(prev.val) {
v.t.Delete(query(i))
}
}
} else {
lo.pos = i + 1
prev := v.t.Floor(query(i))
if prev == nil {
v.min = &position{pos: i, val: e}
v.t.Insert(v.min)
} else if !e.Equal(prev.(*position).val) {
v.t.Insert(&position{pos: i, val: e})
}
}
} else {
if hi.pos == i+1 {
if hi != v.max && e.Equal(hi.val) {
hi.pos--
} else {
v.t.Insert(&position{pos: i, val: e})
}
} else {
v.t.Insert(&position{pos: i, val: e})
v.t.Insert(&position{pos: i + 1, val: lo.val})
}
}
}
// SetRange sets the value of positions [start, end) to e.
func (v *Vector) SetRange(start, end int, e Equaler) {
switch l := end - start; {
case l == 0:
if !v.Relaxed && (start < v.min.pos || start >= v.max.pos) {
panic(ErrOutOfRange)
}
return
case l == 1:
v.Set(start, e)
return
case l < 0:
panic(ErrInvertedRange)
}
if !v.Relaxed && (start < v.min.pos || end > v.max.pos || start == v.max.pos) {
panic(ErrOutOfRange)
}
// Do fast path complete vector replacement if possible.
if start <= v.min.pos && v.max.pos <= end {
v.t = llrb.Tree{}
*v.min = position{pos: start, val: e}
v.t.Insert(v.min)
v.max.pos = end
v.t.Insert(v.max)
return
}
// Handle cases where the given range is entirely outside the vector.
switch {
case start >= v.max.pos:
oldEnd := v.max.pos
v.max.pos = end
if start != oldEnd {
prev := v.t.Floor(query(oldEnd)).(*position)
if !prev.val.Equal(v.Zero) {
v.t.Insert(&position{pos: oldEnd, val: v.Zero})
}
}
last := v.t.Floor(query(start)).(*position)
if !e.Equal(last.val) {
v.t.Insert(&position{pos: start, val: e})
}
return
case end < v.min.pos:
if v.min.val.Equal(v.Zero) {
v.min.pos = end
} else {
v.min = &position{pos: end, val: v.Zero}
v.t.Insert(v.min)
}
fallthrough
case end == v.min.pos:
if e.Equal(v.min.val) {
v.min.pos = start
} else {
v.min = &position{pos: start, val: e}
v.t.Insert(v.min)
}
return
}
// Handle cases where the given range
last := v.t.Floor(query(end)).(*position)
deleteRangeInclusive(&v.t, start, end)
switch {
// is entirely within the existing vector;
case v.min.pos < start && end <= v.max.pos:
prev := v.t.Floor(query(start)).(*position)
if !e.Equal(prev.val) {
v.t.Insert(&position{pos: start, val: e})
}
if last.val == nil {
v.t.Insert(v.max)
} else if !e.Equal(last.val) {
v.t.Insert(&position{pos: end, val: last.val})
}
// hangs over the left end and the right end is in the vector; or
case start <= v.min.pos:
lastVal := last.val
*v.min = position{pos: start, val: e}
v.t.Insert(v.min)
if !e.Equal(lastVal) {
v.t.Insert(&position{pos: end, val: lastVal})
}
// hangs over the right end and the left end is in the vector.
case end > v.max.pos:
v.max.pos = end
v.t.Insert(v.max)
prev := v.t.Floor(query(start)).(*position)
if e.Equal(prev.val) {
return
}
if last.val == nil || !e.Equal(last.val) {
v.t.Insert(&position{pos: start, val: e})
}
default:
panic("step: unexpected case")
}
}
// deleteRangeInclusive deletes all steps within the given range.
// Note that llrb.(*Tree).DoRange does not operate on the node matching the end of a range.
func deleteRangeInclusive(t *llrb.Tree, start, end int) {
var delQ []llrb.Comparable
t.DoRange(func(c llrb.Comparable) (done bool) {
delQ = append(delQ, c)
return
}, query(start), query(end+1))
for _, p := range delQ {
t.Delete(p)
}
}
// An Operation is a non-mutating function that can be applied to a vector using Do
// and DoRange.
type Operation func(start, end int, e Equaler)
// Do performs the function fn on steps stored in the Vector in ascending sort order
// of start position. fn is passed the start, end and value of the step.
func (v *Vector) Do(fn Operation) {
var (
la *position
min = v.min.pos
)
v.t.Do(func(c llrb.Comparable) (done bool) {
p := c.(*position)
if p.pos != min {
fn(la.pos, p.pos, la.val)
}
la = p
return
})
}
// Do performs the function fn on steps stored in the Vector over the range [from, to)
// in ascending sort order of start position. fn is passed the start, end and value of
// the step.
func (v *Vector) DoRange(from, to int, fn Operation) error {
if to < from {
return ErrInvertedRange
}
var (
la *position
min = v.min.pos
max = v.max.pos
)
if to <= min || from >= max {
return ErrOutOfRange
}
_, end, e, _ := v.StepAt(from)
if end > to {
end = to
}
fn(from, end, e)
if end == to {
return nil
}
v.t.DoRange(func(c llrb.Comparable) (done bool) {
p := c.(*position)
if p.pos != end {
fn(la.pos, p.pos, la.val)
}
la = p
return
}, query(end), query(to))
if to > la.pos {
fn(la.pos, to, la.val)
}
return nil
}
// A Mutator is a function that is used by Apply and ApplyRange to alter values within
// a Vector.
type Mutator func(Equaler) Equaler
// Convenience mutator functions. Mutator functions are used by Apply and ApplyRange
// to alter step values in a value-dependent manner. These mutators assume the stored
// type matches the function and will panic is this is not true.
var (
IncInt Mutator = incInt // Increment an int value.
DecInt Mutator = decInt // Decrement an int value.
IncFloat Mutator = incFloat // Increment a float64 value.
DecFloat Mutator = decFloat // Decrement a float64 value.
)
func incInt(e Equaler) Equaler { return e.(Int) + 1 }
func decInt(e Equaler) Equaler { return e.(Int) - 1 }
func incFloat(e Equaler) Equaler { return e.(Float) + 1 }
func decFloat(e Equaler) Equaler { return e.(Float) - 1 }
// Apply applies the mutator function m to steps stored in the Vector in ascending sort order
// of start position. Redundant steps resulting from changes in step values are erased.
func (v *Vector) Apply(m Mutator) {
var (
la Equaler
min = v.min.pos
max = v.max.pos
delQ []query
)
v.t.Do(func(c llrb.Comparable) (done bool) {
p := c.(*position)
if p.pos == max {
return true
}
p.val = m(p.val)
if p.pos != min && p.pos != max && p.val.Equal(la) {
delQ = append(delQ, query(p.pos))
}
la = p.val
return
})
for _, d := range delQ {
v.t.Delete(d)
}
}
// Apply applies the mutator function m to steps stored in the Vector in over the range
// [from, to) in ascending sort order of start position. Redundant steps resulting from
// changes in step values are erased.
func (v *Vector) ApplyRange(from, to int, m Mutator) error {
if to < from {
return ErrInvertedRange
}
if from == to {
return nil
}
var (
la Equaler
old position
min = v.min.pos
max = v.max.pos
delQ []query
)
if !v.Relaxed && (to <= min || from >= max) {
return ErrOutOfRange
}
if v.Relaxed {
if from < min {
v.SetRange(from, min, v.Zero)
}
if max < to {
v.SetRange(max, to, v.Zero)
}
}
var end int
old.pos, end, old.val, _ = v.StepAt(from)
la = old.val
la = m(la)
if to <= end {
v.SetRange(from, to, la)
return nil
}
if !la.Equal(old.val) {
switch {
case from > min:
if !la.Equal(v.t.Floor(lower(from)).(*position).val) {
v.t.Insert(&position{from, la})
} else {
v.t.Delete(query(from))
}
case from < min:
v.SetRange(from, min, la)
default:
*v.min = position{from, la}
}
}
var tail *position
v.t.DoRange(func(c llrb.Comparable) (done bool) {
p := c.(*position)
if p.pos == max {
// We should be at v.t.Max(), but don't stop
// just in case there is more. We want to fail
// noisily if max < v.t.Max().
return
}
if p.pos == to {
tail = p
return
}
old = *p // Needed for fix-up of last step if to is not at a step boundary.
p.val = m(p.val)
if p.pos != min && p.val.Equal(la) {
delQ = append(delQ, query(p.pos))
}
la = p.val
return
}, query(end), upper(to))
for _, d := range delQ {
v.t.Delete(d)
}
if to < max {
if tail == nil {
prev := v.t.Floor(lower(to)).(*position)
if old.pos != from && !old.val.Equal(prev.val) {
v.t.Insert(&position{to, old.val})
}
} else {
prev := v.t.Floor(lower(tail.pos)).(*position)
if tail.val != nil && tail.val.Equal(prev.val) {
v.t.Delete(query(tail.pos))
}
}
return nil
}
if v.Relaxed && to > max {
v.SetRange(max, to, m(v.Zero))
}
return nil
}
// String returns a string representation a Vector, displaying step start
// positions and values. The last step indicates the end of the vector and
// always has an associated value of nil.
func (v *Vector) String() string {
sb := make([]string, 0, v.t.Len())
v.t.Do(func(c llrb.Comparable) (done bool) {
p := c.(*position)
sb = append(sb, fmt.Sprintf("%d:%v", p.pos, p.val))
return
})
return fmt.Sprintf("%v", sb)
}
|