github.com/bir3/gocompiler@v0.9.2202/src/xvendor/golang.org/x/sys/unix/timestruct.go (about)

     1  // Copyright 2017 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos
     6  
     7  package unix
     8  
     9  import "time"
    10  
    11  // TimespecToNsec returns the time stored in ts as nanoseconds.
    12  func TimespecToNsec(ts Timespec) int64 { return ts.Nano() }
    13  
    14  // NsecToTimespec converts a number of nanoseconds into a Timespec.
    15  func NsecToTimespec(nsec int64) Timespec {
    16  	sec := nsec / 1e9
    17  	nsec = nsec % 1e9
    18  	if nsec < 0 {
    19  		nsec += 1e9
    20  		sec--
    21  	}
    22  	return setTimespec(sec, nsec)
    23  }
    24  
    25  // TimeToTimespec converts t into a Timespec.
    26  // On some 32-bit systems the range of valid Timespec values are smaller
    27  // than that of time.Time values.  So if t is out of the valid range of
    28  // Timespec, it returns a zero Timespec and ERANGE.
    29  func TimeToTimespec(t time.Time) (Timespec, error) {
    30  	sec := t.Unix()
    31  	nsec := int64(t.Nanosecond())
    32  	ts := setTimespec(sec, nsec)
    33  
    34  	// Currently all targets have either int32 or int64 for Timespec.Sec.
    35  	// If there were a new target with floating point type for it, we have
    36  	// to consider the rounding error.
    37  	if int64(ts.Sec) != sec {
    38  		return Timespec{}, ERANGE
    39  	}
    40  	return ts, nil
    41  }
    42  
    43  // TimevalToNsec returns the time stored in tv as nanoseconds.
    44  func TimevalToNsec(tv Timeval) int64 { return tv.Nano() }
    45  
    46  // NsecToTimeval converts a number of nanoseconds into a Timeval.
    47  func NsecToTimeval(nsec int64) Timeval {
    48  	nsec += 999 // round up to microsecond
    49  	usec := nsec % 1e9 / 1e3
    50  	sec := nsec / 1e9
    51  	if usec < 0 {
    52  		usec += 1e6
    53  		sec--
    54  	}
    55  	return setTimeval(sec, usec)
    56  }
    57  
    58  // Unix returns the time stored in ts as seconds plus nanoseconds.
    59  func (ts *Timespec) Unix() (sec int64, nsec int64) {
    60  	return int64(ts.Sec), int64(ts.Nsec)
    61  }
    62  
    63  // Unix returns the time stored in tv as seconds plus nanoseconds.
    64  func (tv *Timeval) Unix() (sec int64, nsec int64) {
    65  	return int64(tv.Sec), int64(tv.Usec) * 1000
    66  }
    67  
    68  // Nano returns the time stored in ts as nanoseconds.
    69  func (ts *Timespec) Nano() int64 {
    70  	return int64(ts.Sec)*1e9 + int64(ts.Nsec)
    71  }
    72  
    73  // Nano returns the time stored in tv as nanoseconds.
    74  func (tv *Timeval) Nano() int64 {
    75  	return int64(tv.Sec)*1e9 + int64(tv.Usec)*1000
    76  }