本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.6KB

  1. package plumbing
  2. import (
  3. "bytes"
  4. "io"
  5. "io/ioutil"
  6. )
  7. // MemoryObject on memory Object implementation
  8. type MemoryObject struct {
  9. t ObjectType
  10. h Hash
  11. cont []byte
  12. sz int64
  13. }
  14. // Hash returns the object Hash, the hash is calculated on-the-fly the first
  15. // time it's called, in all subsequent calls the same Hash is returned even
  16. // if the type or the content have changed. The Hash is only generated if the
  17. // size of the content is exactly the object size.
  18. func (o *MemoryObject) Hash() Hash {
  19. if o.h == ZeroHash && int64(len(o.cont)) == o.sz {
  20. o.h = ComputeHash(o.t, o.cont)
  21. }
  22. return o.h
  23. }
  24. // Type return the ObjectType
  25. func (o *MemoryObject) Type() ObjectType { return o.t }
  26. // SetType sets the ObjectType
  27. func (o *MemoryObject) SetType(t ObjectType) { o.t = t }
  28. // Size return the size of the object
  29. func (o *MemoryObject) Size() int64 { return o.sz }
  30. // SetSize set the object size, a content of the given size should be written
  31. // afterwards
  32. func (o *MemoryObject) SetSize(s int64) { o.sz = s }
  33. // Reader returns a ObjectReader used to read the object's content.
  34. func (o *MemoryObject) Reader() (io.ReadCloser, error) {
  35. return ioutil.NopCloser(bytes.NewBuffer(o.cont)), nil
  36. }
  37. // Writer returns a ObjectWriter used to write the object's content.
  38. func (o *MemoryObject) Writer() (io.WriteCloser, error) {
  39. return o, nil
  40. }
  41. func (o *MemoryObject) Write(p []byte) (n int, err error) {
  42. o.cont = append(o.cont, p...)
  43. o.sz = int64(len(o.cont))
  44. return len(p), nil
  45. }
  46. // Close releases any resources consumed by the object when it is acting as a
  47. // ObjectWriter.
  48. func (o *MemoryObject) Close() error { return nil }
上海开阖软件有限公司 沪ICP备12045867号-1