github.com/matrixorigin/matrixone@v0.7.0/pkg/vm/engine/tae/common/range.go (about)

     1  // Copyright 2021 Matrix Origin
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package common
    16  
    17  import (
    18  	"fmt"
    19  
    20  	"github.com/matrixorigin/matrixone/pkg/common/moerr"
    21  )
    22  
    23  var (
    24  	ErrRangeNotContinuous = moerr.NewInternalErrorNoCtx("tae: range not continuous")
    25  	ErrRangeInvalid       = moerr.NewInternalErrorNoCtx("tae: invalid range")
    26  )
    27  
    28  type Range struct {
    29  	Left  uint64 `json:"l"`
    30  	Right uint64 `json:"r"`
    31  }
    32  
    33  func (r *Range) String() string {
    34  	if r == nil {
    35  		return "[]"
    36  	}
    37  	return fmt.Sprintf("[%d, %d]", r.Left, r.Right)
    38  }
    39  
    40  func (r *Range) Valid() bool {
    41  	return r.Left <= r.Right
    42  }
    43  
    44  func (r *Range) LT(id uint64) bool {
    45  	return r.Right < id
    46  }
    47  
    48  func (r *Range) GT(id uint64) bool {
    49  	return r.Left > id
    50  }
    51  
    52  func (r *Range) ClosedIn(id uint64) bool {
    53  	return r.Left <= id && r.Right >= id
    54  }
    55  
    56  func (r *Range) CanCover(o *Range) bool {
    57  	if r == nil {
    58  		return false
    59  	}
    60  	if o == nil {
    61  		return true
    62  	}
    63  	return r.Left <= o.Left && r.Right >= o.Right
    64  }
    65  
    66  func (r *Range) CommitLeft(left uint64) bool {
    67  	if left > r.Right {
    68  		return false
    69  	}
    70  	if left < r.Left {
    71  		r.Left = left
    72  	}
    73  	return true
    74  }
    75  
    76  func (r *Range) Union(o *Range) error {
    77  	if o.Left > r.Right+1 || r.Left > o.Right+1 {
    78  		return ErrRangeNotContinuous
    79  	}
    80  	if r.Left > o.Left {
    81  		r.Left = o.Left
    82  	}
    83  	if r.Right < o.Right {
    84  		r.Right = o.Right
    85  	}
    86  	return nil
    87  }
    88  
    89  func (r *Range) Append(right uint64) error {
    90  	if r.Left == r.Right && r.Right == 0 {
    91  		r.Right = right
    92  		r.Left = right
    93  		return nil
    94  	}
    95  	// if right < r.Left || right > r.Right+1 {
    96  	if right <= r.Right {
    97  		return ErrRangeInvalid
    98  	}
    99  	r.Right = right
   100  	return nil
   101  }