// Copyright 2013 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package model

import (
	
	
	
	
	
	
	
)

const (
	// MinimumTick is the minimum supported time resolution. This has to be
	// at least time.Second in order for the code below to work.
	minimumTick = time.Millisecond
	// second is the Time duration equivalent to one second.
	second = int64(time.Second / minimumTick)
	// The number of nanoseconds per minimum tick.
	nanosPerTick = int64(minimumTick / time.Nanosecond)

	// Earliest is the earliest Time representable. Handy for
	// initializing a high watermark.
	Earliest = Time(math.MinInt64)
	// Latest is the latest Time representable. Handy for initializing
	// a low watermark.
	Latest = Time(math.MaxInt64)
)

// Time is the number of milliseconds since the epoch
// (1970-01-01 00:00 UTC) excluding leap seconds.
type Time int64

// Interval describes an interval between two timestamps.
type Interval struct {
	Start, End Time
}

// Now returns the current time as a Time.
func () Time {
	return TimeFromUnixNano(time.Now().UnixNano())
}

// TimeFromUnix returns the Time equivalent to the Unix Time t
// provided in seconds.
func ( int64) Time {
	return Time( * second)
}

// TimeFromUnixNano returns the Time equivalent to the Unix Time
// t provided in nanoseconds.
func ( int64) Time {
	return Time( / nanosPerTick)
}

// Equal reports whether two Times represent the same instant.
func ( Time) ( Time) bool {
	return  == 
}

// Before reports whether the Time t is before o.
func ( Time) ( Time) bool {
	return  < 
}

// After reports whether the Time t is after o.
func ( Time) ( Time) bool {
	return  > 
}

// Add returns the Time t + d.
func ( Time) ( time.Duration) Time {
	return  + Time(/minimumTick)
}

// Sub returns the Duration t - o.
func ( Time) ( Time) time.Duration {
	return time.Duration(-) * minimumTick
}

// Time returns the time.Time representation of t.
func ( Time) () time.Time {
	return time.Unix(int64()/second, (int64()%second)*nanosPerTick)
}

// Unix returns t as a Unix time, the number of seconds elapsed
// since January 1, 1970 UTC.
func ( Time) () int64 {
	return int64() / second
}

// UnixNano returns t as a Unix time, the number of nanoseconds elapsed
// since January 1, 1970 UTC.
func ( Time) () int64 {
	return int64() * nanosPerTick
}

// The number of digits after the dot.
var dotPrecision = int(math.Log10(float64(second)))

// String returns a string representation of the Time.
func ( Time) () string {
	return strconv.FormatFloat(float64()/float64(second), 'f', -1, 64)
}

// MarshalJSON implements the json.Marshaler interface.
func ( Time) () ([]byte, error) {
	return []byte(.String()), nil
}

// UnmarshalJSON implements the json.Unmarshaler interface.
func ( *Time) ( []byte) error {
	 := strings.Split(string(), ".")
	switch len() {
	case 1:
		,  := strconv.ParseInt(string([0]), 10, 64)
		if  != nil {
			return 
		}
		* = Time( * second)

	case 2:
		,  := strconv.ParseInt(string([0]), 10, 64)
		if  != nil {
			return 
		}
		 *= second

		 := dotPrecision - len([1])
		if  < 0 {
			[1] = [1][:dotPrecision]
		} else if  > 0 {
			[1] = [1] + strings.Repeat("0", )
		}

		,  := strconv.ParseInt([1], 10, 32)
		if  != nil {
			return 
		}

		// If the value was something like -0.1 the negative is lost in the
		// parsing because of the leading zero, this ensures that we capture it.
		if len([0]) > 0 && [0][0] == '-' && + > 0 {
			* = Time(+) * -1
		} else {
			* = Time( + )
		}

	default:
		return fmt.Errorf("invalid time %q", string())
	}
	return nil
}

// Duration wraps time.Duration. It is used to parse the custom duration format
// from YAML.
// This type should not propagate beyond the scope of input/output processing.
type Duration time.Duration

// Set implements pflag/flag.Value
func ( *Duration) ( string) error {
	var  error
	*,  = ParseDuration()
	return 
}

// Type implements pflag.Value
func ( *Duration) () string {
	return "duration"
}

func isdigit( byte) bool { return  >= '0' &&  <= '9' }

// Units are required to go in order from biggest to smallest.
// This guards against confusion from "1m1d" being 1 minute + 1 day, not 1 month + 1 day.
var unitMap = map[string]struct {
	pos  int
	mult uint64
}{
	"ms": {7, uint64(time.Millisecond)},
	"s":  {6, uint64(time.Second)},
	"m":  {5, uint64(time.Minute)},
	"h":  {4, uint64(time.Hour)},
	"d":  {3, uint64(24 * time.Hour)},
	"w":  {2, uint64(7 * 24 * time.Hour)},
	"y":  {1, uint64(365 * 24 * time.Hour)},
}

// ParseDuration parses a string into a time.Duration, assuming that a year
// always has 365d, a week always has 7d, and a day always has 24h.
func ( string) (Duration, error) {
	switch  {
	case "0":
		// Allow 0 without a unit.
		return 0, nil
	case "":
		return 0, errors.New("empty duration string")
	}

	 := 
	var  uint64
	 := 0

	for  != "" {
		if !isdigit([0]) {
			return 0, fmt.Errorf("not a valid duration string: %q", )
		}
		// Consume [0-9]*
		 := 0
		for ;  < len() && isdigit([]); ++ {
		}
		,  := strconv.ParseUint([:], 10, 0)
		if  != nil {
			return 0, fmt.Errorf("not a valid duration string: %q", )
		}
		 = [:]

		// Consume unit.
		for  = 0;  < len() && !isdigit([]); ++ {
		}
		if  == 0 {
			return 0, fmt.Errorf("not a valid duration string: %q", )
		}
		 := [:]
		 = [:]
		,  := unitMap[]
		if ! {
			return 0, fmt.Errorf("unknown unit %q in duration %q", , )
		}
		if .pos <=  { // Units must go in order from biggest to smallest.
			return 0, fmt.Errorf("not a valid duration string: %q", )
		}
		 = .pos
		// Check if the provided duration overflows time.Duration (> ~ 290years).
		if  > 1<<63/.mult {
			return 0, errors.New("duration out of range")
		}
		 +=  * .mult
		if  > 1<<63-1 {
			return 0, errors.New("duration out of range")
		}
	}
	return Duration(), nil
}

func ( Duration) () string {
	var (
		 = int64(time.Duration() / time.Millisecond)
		  = ""
	)
	if  == 0 {
		return "0s"
	}

	 := func( string,  int64,  bool) {
		if  && % != 0 {
			return
		}
		if  :=  / ;  > 0 {
			 += fmt.Sprintf("%d%s", , )
			 -=  * 
		}
	}

	// Only format years and weeks if the remainder is zero, as it is often
	// easier to read 90d than 12w6d.
	("y", 1000*60*60*24*365, true)
	("w", 1000*60*60*24*7, true)

	("d", 1000*60*60*24, false)
	("h", 1000*60*60, false)
	("m", 1000*60, false)
	("s", 1000, false)
	("ms", 1, false)

	return 
}

// MarshalJSON implements the json.Marshaler interface.
func ( Duration) () ([]byte, error) {
	return json.Marshal(.String())
}

// UnmarshalJSON implements the json.Unmarshaler interface.
func ( *Duration) ( []byte) error {
	var  string
	if  := json.Unmarshal(, &);  != nil {
		return 
	}
	,  := ParseDuration()
	if  != nil {
		return 
	}
	* = 
	return nil
}

// MarshalText implements the encoding.TextMarshaler interface.
func ( *Duration) () ([]byte, error) {
	return []byte(.String()), nil
}

// UnmarshalText implements the encoding.TextUnmarshaler interface.
func ( *Duration) ( []byte) error {
	var  error
	*,  = ParseDuration(string())
	return 
}

// MarshalYAML implements the yaml.Marshaler interface.
func ( Duration) () (interface{}, error) {
	return .String(), nil
}

// UnmarshalYAML implements the yaml.Unmarshaler interface.
func ( *Duration) ( func(interface{}) error) error {
	var  string
	if  := (&);  != nil {
		return 
	}
	,  := ParseDuration()
	if  != nil {
		return 
	}
	* = 
	return nil
}