part-writer-data.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package util
  2. import (
  3. "os"
  4. "strconv"
  5. )
  6. // PartWriter interface
  7. type PartWriter interface {
  8. Next()
  9. Write(p []byte) (n int, err error)
  10. Close() error
  11. Part() uint64
  12. }
  13. // PartWriterData struct
  14. type PartWriterData struct {
  15. fn string
  16. part uint64
  17. file *os.File
  18. }
  19. // NewPartWriter func
  20. func NewPartWriter(path string, id uint64) *PartWriterData {
  21. var err error
  22. var file *os.File
  23. fn := path + "/F" + strconv.FormatUint(id, 16) + "."
  24. if file, err = os.Create(fn + strconv.FormatUint(uint64(1), 16) + ".tmp"); err != nil {
  25. panic(err)
  26. }
  27. return &PartWriterData{fn, 1, file}
  28. }
  29. // Next func
  30. func (w *PartWriterData) Next() {
  31. var err error
  32. if err = w.file.Close(); err != nil {
  33. panic(err)
  34. }
  35. w.part++
  36. if w.file, err = os.Create(w.fn + strconv.FormatUint(uint64(w.part), 16) + ".tmp"); err != nil {
  37. panic(err)
  38. }
  39. }
  40. // Write func
  41. func (w *PartWriterData) Write(p []byte) (n int, err error) {
  42. return w.file.Write(p)
  43. }
  44. // Close func
  45. func (w *PartWriterData) Close() error {
  46. return w.file.Close()
  47. }
  48. // Part func
  49. func (w *PartWriterData) Part() uint64 {
  50. return w.part
  51. }