seqnum.go raw

   1  // Copyright 2018 The gVisor Authors.
   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 seqnum defines the types and methods for TCP sequence numbers such
  16  // that they fit in 32-bit words and work properly when overflows occur.
  17  package seqnum
  18  
  19  // Value represents the value of a sequence number.
  20  type Value uint32
  21  
  22  // Size represents the size (length) of a sequence number window.
  23  type Size uint32
  24  
  25  // LessThan checks if v is before w, i.e., v < w.
  26  func (v Value) LessThan(w Value) bool {
  27  	return int32(v-w) < 0
  28  }
  29  
  30  // LessThanEq returns true if v==w or v is before i.e., v < w.
  31  func (v Value) LessThanEq(w Value) bool {
  32  	if v == w {
  33  		return true
  34  	}
  35  	return v.LessThan(w)
  36  }
  37  
  38  // InRange checks if v is in the range [a,b), i.e., a <= v < b.
  39  func (v Value) InRange(a, b Value) bool {
  40  	return v-a < b-a
  41  }
  42  
  43  // InWindow checks if v is in the window that starts at 'first' and spans 'size'
  44  // sequence numbers.
  45  func (v Value) InWindow(first Value, size Size) bool {
  46  	return v.InRange(first, first.Add(size))
  47  }
  48  
  49  // Add calculates the sequence number following the [v, v+s) window.
  50  func (v Value) Add(s Size) Value {
  51  	return v + Value(s)
  52  }
  53  
  54  // Size calculates the size of the window defined by [v, w).
  55  func (v Value) Size(w Value) Size {
  56  	return Size(w - v)
  57  }
  58  
  59  // UpdateForward updates v such that it becomes v + s.
  60  func (v *Value) UpdateForward(s Size) {
  61  	*v += Value(s)
  62  }
  63