blob: f76aec0a36769fbc6fdb9e3ddb12395f897d9c14 [file] [log] [blame]
George Engelbrecht832a00a2019-12-26 16:02:08 -07001// Copyright 2019 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5package main
6
7import (
8 "bytes"
9 "compress/gzip"
10 "errors"
11 "fmt"
12 "math"
13 "time"
14
15 "github.com/golang/glog"
16)
17
18// AgeInDays returns the age in days from event.
19func AgeInDays(event time.Time) (int64, error) {
20 age := int64(math.Floor(time.Since(event).Hours() / 24.0))
21 if age < 0 {
22 return 0, errors.New("object date can't be in the future")
23 }
24 return age, nil
25}
26
27// IntMin returns the minimum of two int64s.
28func IntMin(x, y int) int {
29 if x < y {
30 return x
31 }
32 return y
33}
34
35// StringInSlice returns a bool if a string exists in a slice.
36func StringInSlice(a string, list []string) bool {
37 for _, b := range list {
38 if b == a {
39 return true
40 }
41 }
42 return false
43}
44
45// compressBytes gzips an array of bytes into a buffer.
46func compressBytes(data *[]byte) (*bytes.Buffer, error) {
47 var compressedBytes bytes.Buffer
48 gzipWriter := gzip.NewWriter(&compressedBytes)
49 _, err := gzipWriter.Write(*data)
50 if err != nil {
51 glog.Errorf("error compressing logs, gzip failed: %v", err)
52 return nil, err
53 }
54 err = gzipWriter.Close()
55 if err != nil {
56 glog.Errorf("error compressing logs, gzip failed: %v", err)
57 return nil, err
58 }
59 return &compressedBytes, nil
60}
61
62// ByteCountSI gives human readable sizes.
63func ByteCountSI(b int64) string {
64 const unit = 1000
65 if b < unit {
66 return fmt.Sprintf("%d B", b)
67 }
68 div, exp := int64(unit), 0
69 for n := b / unit; n >= unit; n /= unit {
70 div *= unit
71 exp++
72 }
73 return fmt.Sprintf("%.1f %cB",
74 float64(b)/float64(div), "kMGTPE"[exp])
75}