util.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright (c) 2013, Suryandaru Triandana <syndtr@gmail.com>
  2. // All rights reserved.
  3. //
  4. // Use of this source code is governed by a BSD-style license that can be
  5. // found in the LICENSE file.
  6. // Package util provides utilities used throughout leveldb.
  7. package util
  8. import (
  9. "errors"
  10. )
  11. var (
  12. ErrReleased = errors.New("leveldb: resource already relesed")
  13. ErrHasReleaser = errors.New("leveldb: releaser already defined")
  14. )
  15. // Releaser is the interface that wraps the basic Release method.
  16. type Releaser interface {
  17. // Release releases associated resources. Release should always success
  18. // and can be called multiple times without causing error.
  19. Release()
  20. }
  21. // ReleaseSetter is the interface that wraps the basic SetReleaser method.
  22. type ReleaseSetter interface {
  23. // SetReleaser associates the given releaser to the resources. The
  24. // releaser will be called once coresponding resources released.
  25. // Calling SetReleaser with nil will clear the releaser.
  26. //
  27. // This will panic if a releaser already present or coresponding
  28. // resource is already released. Releaser should be cleared first
  29. // before assigned a new one.
  30. SetReleaser(releaser Releaser)
  31. }
  32. // BasicReleaser provides basic implementation of Releaser and ReleaseSetter.
  33. type BasicReleaser struct {
  34. releaser Releaser
  35. released bool
  36. }
  37. // Released returns whether Release method already called.
  38. func (r *BasicReleaser) Released() bool {
  39. return r.released
  40. }
  41. // Release implements Releaser.Release.
  42. func (r *BasicReleaser) Release() {
  43. if !r.released {
  44. if r.releaser != nil {
  45. r.releaser.Release()
  46. r.releaser = nil
  47. }
  48. r.released = true
  49. }
  50. }
  51. // SetReleaser implements ReleaseSetter.SetReleaser.
  52. func (r *BasicReleaser) SetReleaser(releaser Releaser) {
  53. if r.released {
  54. panic(ErrReleased)
  55. }
  56. if r.releaser != nil && releaser != nil {
  57. panic(ErrHasReleaser)
  58. }
  59. r.releaser = releaser
  60. }
  61. type NoopReleaser struct{}
  62. func (NoopReleaser) Release() {}