import*as Platform from"../platform/platform.js";export class Segment{constructor(e,t,s){if(e>t)throw new Error("Invalid segment");this.begin=e,this.end=t,this.data=s}intersects(e){return this.begin<e.end&&e.begin<this.end}}export class SegmentedRange{constructor(e){this._segments=[],this._mergeCallback=e}append(e){let t=Platform.ArrayUtilities.lowerBound(this._segments,e,((e,t)=>e.begin-t.begin)),s=t,n=null;if(t>0){const s=this._segments[t-1];n=this._tryMerge(s,e),n?(--t,e=n):this._segments[t-1].end>=e.begin&&(e.end<s.end&&this._segments.splice(t,0,new Segment(e.end,s.end,s.data)),s.end=e.begin)}for(;s<this._segments.length&&this._segments[s].end<=e.end;)++s;s<this._segments.length&&(n=this._tryMerge(e,this._segments[s]),n?(s++,e=n):e.intersects(this._segments[s])&&(this._segments[s].begin=e.end)),this._segments.splice(t,s-t,e)}appendRange(e){e.segments().forEach((e=>this.append(e)))}segments(){return this._segments}_tryMerge(e,t){const s=this._mergeCallback&&this._mergeCallback(e,t);return s?(s.begin=e.begin,s.end=Math.max(e.end,t.end),s):null}}