summaryrefslogtreecommitdiff
path: root/chromium/third_party/trace-viewer/src/base/interval_tree.js
blob: fd1634e8b286d78ac302a56c51f5c57b27e3180f (plain)
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
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

base.exportTo('base', function() {
  function max(a, b) {
    if (a === undefined)
      return b;
    if (b === undefined)
      return a;
    return Math.max(a, b);
  }

  /**
   * This class implements an interval tree.
   *    See: http://wikipedia.org/wiki/Interval_tree
   *
   * Internally the tree is a Red-Black tree. The insertion/colour is done using
   * the Left-leaning Red-Black Trees algorithm as described in:
   *       http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf
   *
   * @param {function} beginPositionCb Callback to retrieve the begin position.
   * @param {function} endPositionCb Callback to retrieve the end position.
   *
   * @constructor
   */
  function IntervalTree(beginPositionCb, endPositionCb) {
    this.beginPositionCb_ = beginPositionCb;
    this.endPositionCb_ = endPositionCb;

    this.root_ = undefined;
    this.size_ = 0;
  }

  IntervalTree.prototype = {
    /**
     * Insert events into the interval tree.
     *
     * @param {Object} begin The left object.
     * @param {Object=} opt_end The end object, optional. If not provided the
     *     begin object is assumed to also be the end object.
     */
    insert: function(begin, opt_end) {
      var startPosition = this.beginPositionCb_(begin);
      var endPosition = this.endPositionCb_(opt_end || begin);

      var node = new IntervalTreeNode(begin, opt_end || begin,
                                      startPosition, endPosition);
      this.size_++;

      this.root_ = this.insertNode_(this.root_, node);
      this.root_.colour = Colour.BLACK;
    },

    insertNode_: function(root, node) {
      if (root === undefined)
        return node;

      if (root.leftNode && root.leftNode.isRed &&
          root.rightNode && root.rightNode.isRed)
        this.flipNodeColour_(root);

      if (node.key < root.key)
        root.leftNode = this.insertNode_(root.leftNode, node);
      else if (node.key === root.key)
        root.merge(node);
      else
        root.rightNode = this.insertNode_(root.rightNode, node);

      if (root.rightNode && root.rightNode.isRed &&
          (root.leftNode === undefined || !root.leftNode.isRed))
        root = this.rotateLeft_(root);

      if (root.leftNode && root.leftNode.isRed &&
          root.leftNode.leftNode && root.leftNode.leftNode.isRed)
        root = this.rotateRight_(root);

      return root;
    },

    rotateRight_: function(node) {
      var sibling = node.leftNode;
      node.leftNode = sibling.rightNode;
      sibling.rightNode = node;
      sibling.colour = node.colour;
      node.colour = Colour.RED;
      return sibling;
    },

    rotateLeft_: function(node) {
      var sibling = node.rightNode;
      node.rightNode = sibling.leftNode;
      sibling.leftNode = node;
      sibling.colour = node.colour;
      node.colour = Colour.RED;
      return sibling;
    },

    flipNodeColour_: function(node) {
      node.colour = this.flipColour_(node.colour);
      node.leftNode.colour = this.flipColour_(node.leftNode.colour);
      node.rightNode.colour = this.flipColour_(node.rightNode.colour);
    },

    flipColour_: function(colour) {
      return colour === Colour.RED ? Colour.BLACK : Colour.RED;
    },

    /* The high values are used to find intersection. It should be called after
     * all of the nodes are inserted. Doing it each insert is _slow_. */
    updateHighValues: function() {
      this.updateHighValues_(this.root_);
    },

    /* There is probably a smarter way to do this by starting from the inserted
     * node, but need to handle the rotations correctly. Went the easy route
     * for now. */
    updateHighValues_: function(node) {
      if (node === undefined)
        return undefined;

      node.maxHighLeft = this.updateHighValues_(node.leftNode);
      node.maxHighRight = this.updateHighValues_(node.rightNode);

      return max(max(node.maxHighLeft, node.highValue), node.maxHighRight);
    },

    /**
     * Retrieve all overlapping intervals.
     *
     * @param {number} lowValue The low value for the intersection interval.
     * @param {number} highValue The high value for the intersection interval.
     * @return {Array} All [begin, end] pairs inside intersecting intervals.
     */
    findIntersection: function(lowValue, highValue) {
      if (lowValue === undefined || highValue === undefined)
        throw new Error('lowValue and highValue must be defined');
      if ((typeof lowValue !== 'number') || (typeof highValue !== 'number'))
        throw new Error('lowValue and highValue must be numbers');

      if (this.root_ === undefined)
        return [];

      return this.findIntersection_(this.root_, lowValue, highValue);
    },

    findIntersection_: function(node, lowValue, highValue) {
      var ret = [];

      /* This node starts has a start point at or further right then highValue
       * so we know this node is out and all right children are out. Just need
       * to check left */
      if (node.lowValue >= highValue) {
        if (!node.hasLeftNode)
          return [];
        return this.findIntersection_(node.leftNode, lowValue, highValue);
      }

      /* If we have a maximum left high value that is bigger then lowValue we
       * need to check left for matches */
      if (node.maxHighLeft > lowValue) {
        ret = ret.concat(
            this.findIntersection_(node.leftNode, lowValue, highValue));
      }

      /* We know that this node starts before highValue, if any of it's data
       * ends after lowValue we need to add those nodes */
      if (node.highValue > lowValue) {
        for (var i = (node.data.length - 1); i >= 0; --i) {
          /* data nodes are sorted by high value, so as soon as we see one
           * before low value we're done. */
          if (node.data[i].high < lowValue)
            break;

          ret.unshift([node.data[i].start, node.data[i].end]);
        }
      }

      /* check for matches in the right tree */
      if (node.hasRightNode) {
        ret = ret.concat(
            this.findIntersection_(node.rightNode, lowValue, highValue));
      }

      return ret;
    },

    /**
     * Returns the number of nodes in the tree.
     */
    get size() {
      return this.size_;
    },

    /**
     * Returns the root node in the tree.
     */
    get root() {
      return this.root_;
    },

    /**
     * Dumps out the [lowValue, highValue] pairs for each node in depth-first
     * order.
     */
    dump_: function() {
      if (this.root_ === undefined)
        return [];
      return this.dumpNode_(this.root_);
    },

    dumpNode_: function(node) {
      var ret = {};
      if (node.hasLeftNode)
        ret['left'] = this.dumpNode_(node.leftNode);

      ret['node'] = node.dump();

      if (node.hasRightNode)
        ret['right'] = this.dumpNode_(node.rightNode);

      return ret;
    }
  };

  var Colour = {
    RED: 'red',
    BLACK: 'black'
  };

  function IntervalTreeNode(startObject, endObject, lowValue, highValue) {
    this.lowValue_ = lowValue;

    this.data_ = [{
      start: startObject,
      end: endObject,
      high: highValue,
      low: lowValue
    }];

    this.colour_ = Colour.RED;

    this.parentNode_ = undefined;
    this.leftNode_ = undefined;
    this.rightNode_ = undefined;

    this.maxHighLeft_ = undefined;
    this.maxHighRight_ = undefined;
  }

  IntervalTreeNode.prototype = {
    get colour() {
      return this.colour_;
    },

    set colour(colour) {
      this.colour_ = colour;
    },

    get key() {
      return this.lowValue_;
    },

    get lowValue() {
      return this.lowValue_;
    },

    get highValue() {
      return this.data_[this.data_.length - 1].high;
    },

    set leftNode(left) {
      this.leftNode_ = left;
    },

    get leftNode() {
      return this.leftNode_;
    },

    get hasLeftNode() {
      return this.leftNode_ !== undefined;
    },

    set rightNode(right) {
      this.rightNode_ = right;
    },

    get rightNode() {
      return this.rightNode_;
    },

    get hasRightNode() {
      return this.rightNode_ !== undefined;
    },

    set parentNode(parent) {
      this.parentNode_ = parent;
    },

    get parentNode() {
      return this.parentNode_;
    },

    get isRootNode() {
      return this.parentNode_ === undefined;
    },

    set maxHighLeft(high) {
      this.maxHighLeft_ = high;
    },

    get maxHighLeft() {
      return this.maxHighLeft_;
    },

    set maxHighRight(high) {
      this.maxHighRight_ = high;
    },

    get maxHighRight() {
      return this.maxHighRight_;
    },

    get data() {
      return this.data_;
    },

    get isRed() {
      return this.colour_ === Colour.RED;
    },

    merge: function(node) {
      this.data_ = this.data_.concat(node.data);
      this.data_.sort(function(a, b) {
        return a.high - b.high;
      });
    },

    dump: function() {
      if (this.data_.length === 1)
        return [this.data_[0].low, this.data[0].high];

      return this.data_.map(function(d) { return [d.low, d.high]; });
    }
  };

  return {
    IntervalTree: IntervalTree
  };
});