aboutsummaryrefslogtreecommitdiff
path: root/feed/score.go
blob: 9a03c500099882163cf3f0f79e306d298381e3c9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package feed

import (
  "encoding/json"
  "fmt"
  "math"
  "strconv"
)

// CVSS score
type Score uint8

// // create new score from floating point value.
// func NewScore(v float64) (Score, error) {
//   // check score
//   if v < 0.0 || v > 10.0 {
//     return Score(0), fmt.Errorf("CVSS score out of bounds: %2.1f", v)
//   } else {
//     // convert to score, return success
//     return Score(uint8(math.Trunc(10.0 * v))), nil
//   }
// }

// Unmarshal CVSS score from JSON.
func (me *Score) UnmarshalJSON(b []byte) error {
  // decode float, check for error
  var v float64
  if err := json.Unmarshal(b, &v); err != nil {
    return err
  }

  // check score
  if v < 0.0 || v > 10.0 {
    return fmt.Errorf("CVSS score out of bounds: %2.1f", v)
  }

  // save result, return success
  *me = Score(uint8(math.Trunc(10.0 * v)))
  return nil
}

// Convert to string.
func (me Score) String() string {
  val := float64(me) / 10.0
  return strconv.FormatFloat(val, 'f', 1, 64)
}