| 1 | // Handles xsd:duration to time.Duration conversion |
| 2 | |
| 3 | package xsd |
| 4 | |
| 5 | import ( |
| 6 | "bytes" |
| 7 | "fmt" |
| 8 | "strconv" |
| 9 | "time" |
| 10 | ) |
| 11 | |
| 12 | // Extending time constants with the values for day, week, month, year |
| 13 | const ( |
| 14 | Day = time.Hour * 24 |
| 15 | // These values are not precise, probably why the time package does not implement them |
| 16 | // We need them here because xsd:duration uses them |
| 17 | Monthish = Day * 30 |
| 18 | Yearish = Day * 356 |
| 19 | ) |
| 20 | |
| 21 | // durationPair holds information about a pair of (uint/ufloat)(PeriodTag) values in a xsd:duration string |
| 22 | type durationPair struct { |
| 23 | v time.Duration |
| 24 | typ byte |
| 25 | } |
| 26 | |
| 27 | func getTimeBaseDuration(b byte) time.Duration { |
| 28 | switch b { |
| 29 | case tagHour: |
| 30 | return time.Hour |
| 31 | case tagMinute: |
| 32 | return time.Minute |
| 33 | case tagSecond: |
| 34 | return time.Second |
| 35 | } |
| 36 | return 0 |
| 37 | } |
| 38 | |
| 39 | func getDateBaseDuration(b byte) time.Duration { |
| 40 | switch b { |
| 41 | case tagYear: |
| 42 | return Yearish |
| 43 | case tagMonth: |
| 44 | return Monthish |
| 45 | case tagDay: |
| 46 | return Day |
| 47 | } |
| 48 | return 0 |
| 49 | } |
| 50 | |
| 51 | // validByteForFloats checks |
| 52 | func validByteForFloats(b byte) bool { |
| 53 | // + , - . 0 1 2 3 4 5 6 7 8 9 |
| 54 | return (b >= 43 && b <= 46) || (b >= 48 && b <= 57) |
| 55 | } |
| 56 | |
| 57 | func parseTagWithValue(data []byte, start, tagPos int, isTime bool) (*durationPair, error) { |
| 58 | d := new(durationPair) |
| 59 | d.typ = data[tagPos] |
| 60 | if d.typ == tagSecond { |
| 61 | // seconds can be represented in float, we need to parse accordingly |
| 62 | if v, err := strconv.ParseFloat(string(data[start:tagPos]), 32); err == nil { |
| 63 | d.v = time.Duration(float64(time.Second) * v) |
| 64 | } |
| 65 | } else { |
| 66 | if v, err := strconv.ParseInt(string(data[start:tagPos]), 10, 32); err == nil { |
| 67 | if isTime { |
| 68 | d.v = getTimeBaseDuration(d.typ) * time.Duration(v) |
| 69 | } else { |
| 70 | d.v = getDateBaseDuration(d.typ) * time.Duration(v) |
| 71 | } |
| 72 | } |
| 73 | } |
| 74 | if d.v < 0 { |
| 75 | return nil, fmt.Errorf("the minus sign must appear first in the duration") |
| 76 | } |
| 77 | return d, nil |
| 78 | } |
| 79 | |
| 80 | // loadUintVal receives the data and position at which to try to load the duration element |
| 81 | // isTime is used for distinguishing between P1M - 1 month, and PT1M - 1 minute |
| 82 | // it returns a duration pair if it can read one at the start of data, |
| 83 | // and the number of bytes read from data |
| 84 | func loadUintVal(data []byte, start int, isTime bool) (*durationPair, int, error) { |
| 85 | for i := start; i < len(data); i++ { |
| 86 | chr := data[i] |
| 87 | if validTag(data[i]) { |
| 88 | d, err := parseTagWithValue(data, start, i, isTime) |
| 89 | return d, i, err |
| 90 | } |
| 91 | if validByteForFloats(chr) { |
| 92 | continue |
| 93 | } |
| 94 | return nil, i, fmt.Errorf("invalid character %c at pos %d", chr, i) |
| 95 | } |
| 96 | return nil, len(data), fmt.Errorf("unable to recognize any duration value") |
| 97 | } |
| 98 | |
| 99 | const ( |
| 100 | tagDuration = 'P' |
| 101 | tagTime = 'T' |
| 102 | tagYear = 'Y' |
| 103 | tagMonth = 'M' |
| 104 | tagDay = 'D' |
| 105 | tagHour = 'H' |
| 106 | tagMinute = 'M' |
| 107 | tagSecond = 'S' |
| 108 | ) |
| 109 | |
| 110 | func validTag(b byte) bool { |
| 111 | return b == tagYear || b == tagMonth || b == tagDay || b == tagHour || b == tagMinute || b == tagSecond |
| 112 | } |
| 113 | |
| 114 | // Unmarshal takes a byte array and unmarshals it to a time.Duration value |
| 115 | // It is used to parse values in the following format: -PuYuMuDTuHuMufS, where: |
| 116 | // * - shows if the duration is negative |
| 117 | // * P is the duration tag |
| 118 | // * T is the time tag separator |
| 119 | // * Y,M,D,H,M,S are tags for year, month, day, hour, minute, second values |
| 120 | // * u is an unsigned integer value |
| 121 | // * uf is an unsigned float value (just for seconds) |
| 122 | func Unmarshal(data []byte, d *time.Duration) error { |
| 123 | if len(data) == 0 { |
| 124 | return fmt.Errorf("invalid xsd:duration: empty value") |
| 125 | } |
| 126 | pos := 0 |
| 127 | // loading if the value is negative |
| 128 | negative := data[pos] == '-' |
| 129 | if negative { |
| 130 | // skipping over the minus |
| 131 | pos++ |
| 132 | } |
| 133 | if data[pos] != tagDuration { |
| 134 | return fmt.Errorf("invalid xsd:duration: first character must be %q", 'P') |
| 135 | } |
| 136 | // skipping over the "P" |
| 137 | pos++ |
| 138 | |
| 139 | onePastEnd := len(data) |
| 140 | if pos >= onePastEnd { |
| 141 | return fmt.Errorf("invalid xsd:duration: at least one number and designator are required") |
| 142 | } |
| 143 | isTime := false |
| 144 | duration := time.Duration(0) |
| 145 | for { |
| 146 | if data[pos] == tagTime { |
| 147 | pos++ |
| 148 | isTime = true |
| 149 | } |
| 150 | p, cnt, err := loadUintVal(data, pos, isTime) |
| 151 | if err != nil { |
| 152 | return fmt.Errorf("invalid xsd:duration: %w", err) |
| 153 | } |
| 154 | duration += p.v |
| 155 | pos = cnt + 1 |
| 156 | if pos+1 >= onePastEnd { |
| 157 | break |
| 158 | } |
| 159 | } |
| 160 | if negative { |
| 161 | duration *= -1 |
| 162 | } |
| 163 | if onePastEnd > pos+1 { |
| 164 | return fmt.Errorf("data contains more bytes than we are able to parse") |
| 165 | } |
| 166 | if d == nil { |
| 167 | return fmt.Errorf("unable to store time.Duration to nil pointer") |
| 168 | } |
| 169 | *d = duration |
| 170 | return nil |
| 171 | } |
| 172 | |
| 173 | func Days(d time.Duration) float64 { |
| 174 | dd := d / Day |
| 175 | h := d % Day |
| 176 | return float64(dd) + float64(h)/(24*60*60*1e9) |
| 177 | } |
| 178 | |
| 179 | func Months(d time.Duration) float64 { |
| 180 | m := d / Monthish |
| 181 | w := d % Monthish |
| 182 | return float64(m) + float64(w)/(4*7*24*60*60*1e9) |
| 183 | } |
| 184 | |
| 185 | func Years(d time.Duration) float64 { |
| 186 | y := d / Yearish |
| 187 | m := d % Yearish |
| 188 | return float64(y) + float64(m)/(12*4*7*24*60*60*1e9) |
| 189 | } |
| 190 | |
| 191 | func Marshal(d time.Duration) ([]byte, error) { |
| 192 | if d == 0 { |
| 193 | return []byte{tagDuration, tagTime, '0', tagSecond}, nil |
| 194 | } |
| 195 | |
| 196 | neg := d < 0 |
| 197 | if neg { |
| 198 | d = -d |
| 199 | } |
| 200 | y := Years(d) |
| 201 | d -= time.Duration(y) * Yearish |
| 202 | m := Months(d) |
| 203 | d -= time.Duration(m) * Monthish |
| 204 | dd := Days(d) |
| 205 | d -= time.Duration(dd) * Day |
| 206 | H := d.Hours() |
| 207 | d -= time.Duration(H) * time.Hour |
| 208 | M := d.Minutes() |
| 209 | d -= time.Duration(M) * time.Minute |
| 210 | s := d.Seconds() |
| 211 | d -= time.Duration(s) * time.Second |
| 212 | b := bytes.Buffer{} |
| 213 | if neg { |
| 214 | b.Write([]byte{'-'}) |
| 215 | } |
| 216 | b.Write([]byte{'P'}) |
| 217 | if int(y) > 0 { |
| 218 | b.WriteString(fmt.Sprintf("%d%c", int64(y), tagYear)) |
| 219 | } |
| 220 | if int(m) > 0 { |
| 221 | b.WriteString(fmt.Sprintf("%d%c", int64(m), tagMonth)) |
| 222 | } |
| 223 | if int(dd) > 0 { |
| 224 | b.WriteString(fmt.Sprintf("%d%c", int64(dd), tagDay)) |
| 225 | } |
| 226 | |
| 227 | if H+M+s > 0 { |
| 228 | b.Write([]byte{tagTime}) |
| 229 | if int(H) > 0 { |
| 230 | b.WriteString(fmt.Sprintf("%d%c", int64(H), tagHour)) |
| 231 | } |
| 232 | if int(M) > 0 { |
| 233 | b.WriteString(fmt.Sprintf("%d%c", int64(M), tagMinute)) |
| 234 | } |
| 235 | if int(s) > 0 { |
| 236 | if s-float64(int(s)) < 0.01 { |
| 237 | b.WriteString(fmt.Sprintf("%d%c", int(s), tagSecond)) |
| 238 | } else { |
| 239 | b.WriteString(fmt.Sprintf("%.1f%c", s, tagSecond)) |
| 240 | } |
| 241 | } |
| 242 | } |
| 243 | return b.Bytes(), nil |
| 244 | } |