github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/core/port/range.go (about)

     1  /*
     2   * Copyright (C) 2019 The "MysteriumNetwork/node" Authors.
     3   *
     4   * This program is free software: you can redistribute it and/or modify
     5   * it under the terms of the GNU General Public License as published by
     6   * the Free Software Foundation, either version 3 of the License, or
     7   * (at your option) any later version.
     8   *
     9   * This program is distributed in the hope that it will be useful,
    10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12   * GNU General Public License for more details.
    13   *
    14   * You should have received a copy of the GNU General Public License
    15   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    16   */
    17  
    18  package port
    19  
    20  import (
    21  	"fmt"
    22  	"strconv"
    23  	"strings"
    24  
    25  	"github.com/pkg/errors"
    26  )
    27  
    28  // Range represents a networking port range
    29  type Range struct {
    30  	Start, End int
    31  }
    32  
    33  // ParseRange parses port range expression, e.g. "1000:1200" into Range struct
    34  func ParseRange(rangeExpr string) (Range, error) {
    35  	bounds := strings.Split(rangeExpr, ":")
    36  	if len(bounds) != 2 {
    37  		return Range{}, errors.New("invalid port range expression: " + rangeExpr)
    38  	}
    39  
    40  	start, err := strconv.Atoi(bounds[0])
    41  	if err != nil {
    42  		return Range{}, errors.New("invalid start port number: " + bounds[0])
    43  	}
    44  
    45  	end, err := strconv.Atoi(bounds[1])
    46  	if err != nil {
    47  		return Range{}, errors.New("invalid end port number: " + bounds[0])
    48  	}
    49  
    50  	if start > end {
    51  		return Range{}, errors.New("start port cannot be greater than end port: " + rangeExpr)
    52  	}
    53  
    54  	return Range{start, end}, nil
    55  }
    56  
    57  // Capacity returns range capacity
    58  func (r *Range) Capacity() int {
    59  	return r.End - r.Start
    60  }
    61  
    62  // String returns port range expression, e.g. "1000:1200"
    63  func (r *Range) String() string {
    64  	return fmt.Sprintf("%d:%d", r.Start, r.End)
    65  }