github.com/anonymouse64/snapd@v0.0.0-20210824153203-04c4c42d842d/timeout/timeout.go (about)

     1  // -*- Mode: Go; indent-tabs-mode: t -*-
     2  
     3  /*
     4   * Copyright (C) 2014-2015 Canonical Ltd
     5   *
     6   * This program is free software: you can redistribute it and/or modify
     7   * it under the terms of the GNU General Public License version 3 as
     8   * published by the Free Software Foundation.
     9   *
    10   * This program is distributed in the hope that it will be useful,
    11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13   * GNU General Public License for more details.
    14   *
    15   * You should have received a copy of the GNU General Public License
    16   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    17   *
    18   */
    19  
    20  package timeout
    21  
    22  import (
    23  	"encoding/json"
    24  	"time"
    25  )
    26  
    27  // Timeout is a time.Duration that knows how to roundtrip to json and yaml
    28  type Timeout time.Duration
    29  
    30  // DefaultTimeout specifies the timeout for services that do not specify StopTimeout
    31  var DefaultTimeout = Timeout(30 * time.Second)
    32  
    33  // MarshalJSON is from the json.Marshaler interface
    34  func (t Timeout) MarshalJSON() ([]byte, error) {
    35  	return json.Marshal(t.String())
    36  }
    37  
    38  // UnmarshalJSON is from the json.Unmarshaler interface
    39  func (t *Timeout) UnmarshalJSON(buf []byte) error {
    40  	var str string
    41  	if err := json.Unmarshal(buf, &str); err != nil {
    42  		return err
    43  	}
    44  
    45  	dur, err := time.ParseDuration(str)
    46  	if err != nil {
    47  		return err
    48  	}
    49  
    50  	*t = Timeout(dur)
    51  
    52  	return nil
    53  }
    54  
    55  func (t *Timeout) UnmarshalYAML(unmarshal func(interface{}) error) error {
    56  	var str string
    57  	if err := unmarshal(&str); err != nil {
    58  		return err
    59  	}
    60  	dur, err := time.ParseDuration(str)
    61  	if err != nil {
    62  		return err
    63  	}
    64  	*t = Timeout(dur)
    65  	return nil
    66  }
    67  
    68  // String returns a string representing the duration
    69  func (t Timeout) String() string {
    70  	return time.Duration(t).String()
    71  }
    72  
    73  // Seconds returns the duration as a floating point number of seconds.
    74  func (t Timeout) Seconds() float64 {
    75  	return time.Duration(t).Seconds()
    76  }