Format emits a string representation of a Duration to a Buffer truncated to microseconds.
(buf *bytes.Buffer)
| 265 | |
| 266 | // Format emits a string representation of a Duration to a Buffer truncated to microseconds. |
| 267 | func (d Duration) Format(buf *bytes.Buffer) { |
| 268 | if d.nanos == 0 && d.Days == 0 && d.Months == 0 { |
| 269 | buf.WriteString("00:00:00") |
| 270 | return |
| 271 | } |
| 272 | |
| 273 | wrote := false |
| 274 | // Defining both arguments in the signature gives a 10% speedup. |
| 275 | wrotePrev := func(wrote bool, buf *bytes.Buffer) bool { |
| 276 | if wrote { |
| 277 | buf.WriteString(" ") |
| 278 | } |
| 279 | return true |
| 280 | } |
| 281 | |
| 282 | negDays := d.Months < 0 || d.Days < 0 |
| 283 | if absGE(d.Months, 12) { |
| 284 | years := d.Months / 12 |
| 285 | wrote = wrotePrev(wrote, buf) |
| 286 | fmt.Fprintf(buf, "%d year%s", years, isPlural(years)) |
| 287 | d.Months %= 12 |
| 288 | } |
| 289 | if d.Months != 0 { |
| 290 | wrote = wrotePrev(wrote, buf) |
| 291 | fmt.Fprintf(buf, "%d mon%s", d.Months, isPlural(d.Months)) |
| 292 | } |
| 293 | if d.Days != 0 { |
| 294 | wrote = wrotePrev(wrote, buf) |
| 295 | fmt.Fprintf(buf, "%d day%s", d.Days, isPlural(d.Days)) |
| 296 | } |
| 297 | |
| 298 | if d.nanos == 0 { |
| 299 | return |
| 300 | } |
| 301 | |
| 302 | wrotePrev(wrote, buf) |
| 303 | |
| 304 | if d.nanos/nanosInMicro < 0 { |
| 305 | buf.WriteString("-") |
| 306 | } else if negDays { |
| 307 | buf.WriteString("+") |
| 308 | } |
| 309 | |
| 310 | // Extract abs(d.nanos). See https://play.golang.org/p/U3_gNMpyUew. |
| 311 | var nanos uint64 |
| 312 | if d.nanos >= 0 { |
| 313 | nanos = uint64(d.nanos) |
| 314 | } else { |
| 315 | nanos = uint64(-d.nanos) |
| 316 | } |
| 317 | |
| 318 | hn := nanos / hourNanos |
| 319 | nanos %= hourNanos |
| 320 | mn := nanos / minuteNanos |
| 321 | nanos %= minuteNanos |
| 322 | sn := nanos / secondNanos |
| 323 | nanos %= secondNanos |
| 324 | fmt.Fprintf(buf, "%02d:%02d:%02d", hn, mn, sn) |
no test coverage detected