print.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package litter
  2. import (
  3. "io"
  4. "math"
  5. "strconv"
  6. )
  7. func printBool(w io.Writer, value bool) {
  8. if value {
  9. w.Write([]byte("true"))
  10. return
  11. }
  12. w.Write([]byte("false"))
  13. }
  14. func printInt(w io.Writer, val int64, base int) {
  15. w.Write([]byte(strconv.FormatInt(val, base)))
  16. }
  17. func printUint(w io.Writer, val uint64, base int) {
  18. w.Write([]byte(strconv.FormatUint(val, base)))
  19. }
  20. func printFloat(w io.Writer, val float64, precision int) {
  21. if math.Trunc(val) == val {
  22. // Ensure that floats like 1.0 are always printed with a decimal point
  23. w.Write([]byte(strconv.FormatFloat(val, 'f', 1, precision)))
  24. } else {
  25. w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision)))
  26. }
  27. }
  28. func printComplex(w io.Writer, c complex128, floatPrecision int) {
  29. w.Write([]byte("complex"))
  30. printInt(w, int64(floatPrecision*2), 10)
  31. r := real(c)
  32. w.Write([]byte("("))
  33. w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision)))
  34. i := imag(c)
  35. if i >= 0 {
  36. w.Write([]byte("+"))
  37. }
  38. w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision)))
  39. w.Write([]byte("i)"))
  40. }
  41. func printNil(w io.Writer) {
  42. w.Write([]byte("nil"))
  43. }