util.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package raft
  2. import (
  3. "fmt"
  4. "io"
  5. "math/rand"
  6. "os"
  7. "time"
  8. )
  9. // uint64Slice implements sort interface
  10. type uint64Slice []uint64
  11. func (p uint64Slice) Len() int { return len(p) }
  12. func (p uint64Slice) Less(i, j int) bool { return p[i] < p[j] }
  13. func (p uint64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  14. // WriteFile writes data to a file named by filename.
  15. // If the file does not exist, WriteFile creates it with permissions perm;
  16. // otherwise WriteFile truncates it before writing.
  17. // This is copied from ioutil.WriteFile with the addition of a Sync call to
  18. // ensure the data reaches the disk.
  19. func writeFileSynced(filename string, data []byte, perm os.FileMode) error {
  20. f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
  21. if err != nil {
  22. return err
  23. }
  24. defer f.Close() // Idempotent
  25. n, err := f.Write(data)
  26. if err == nil && n < len(data) {
  27. return io.ErrShortWrite
  28. } else if err != nil {
  29. return err
  30. }
  31. if err = f.Sync(); err != nil {
  32. return err
  33. }
  34. return f.Close()
  35. }
  36. // Waits for a random time between two durations and sends the current time on
  37. // the returned channel.
  38. func afterBetween(min time.Duration, max time.Duration) <-chan time.Time {
  39. rand := rand.New(rand.NewSource(time.Now().UnixNano()))
  40. d, delta := min, (max - min)
  41. if delta > 0 {
  42. d += time.Duration(rand.Int63n(int64(delta)))
  43. }
  44. return time.After(d)
  45. }
  46. // TODO(xiangli): Remove assertions when we reach version 1.0
  47. // _assert will panic with a given formatted message if the given condition is false.
  48. func _assert(condition bool, msg string, v ...interface{}) {
  49. if !condition {
  50. panic(fmt.Sprintf("assertion failed: "+msg, v...))
  51. }
  52. }