github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/core/connection/connectionstate/stats.go (about)

     1  /*
     2   * Copyright (C) 2020 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 connectionstate
    19  
    20  import (
    21  	"fmt"
    22  	"time"
    23  
    24  	"github.com/mysteriumnetwork/node/datasize"
    25  )
    26  
    27  // Statistics represents connection statistics.
    28  type Statistics struct {
    29  	At            time.Time
    30  	BytesSent     uint64
    31  	BytesReceived uint64
    32  }
    33  
    34  // Diff calculates the difference in bytes between the old stats and new.
    35  func (stats Statistics) Diff(new Statistics) Statistics {
    36  	return Statistics{
    37  		At:            new.At,
    38  		BytesSent:     diff(stats.BytesSent, new.BytesSent),
    39  		BytesReceived: diff(stats.BytesReceived, new.BytesReceived),
    40  	}
    41  }
    42  
    43  // diff takes in the old and the new values of statistics, returns the calculated delta.
    44  func diff(old, new uint64) (res uint64) {
    45  	if old > new {
    46  		return new
    47  	}
    48  	return new - old
    49  }
    50  
    51  // Plus adds up the given statistics with the diff and returns new stats
    52  func (stats Statistics) Plus(diff Statistics) Statistics {
    53  	return Statistics{
    54  		At:            stats.At,
    55  		BytesReceived: stats.BytesReceived + diff.BytesReceived,
    56  		BytesSent:     stats.BytesSent + diff.BytesSent,
    57  	}
    58  }
    59  
    60  func (stats Statistics) String() string {
    61  	return fmt.Sprintf(
    62  		"Received: %s, sent: %s",
    63  		datasize.FromBytes(stats.BytesReceived),
    64  		datasize.FromBytes(stats.BytesSent),
    65  	)
    66  }