Line data Source code
1 : // Copyright 2020 The LevelDB-Go and Pebble Authors. All rights reserved. Use 2 : // of this source code is governed by a BSD-style license that can be found in 3 : // the LICENSE file. 4 : 5 : //go:build invariants || race 6 : // +build invariants race 7 : 8 : package invariants 9 : 10 : // Enabled is true if we were built with the "invariants" or "race" build tags. 11 : const Enabled = true 12 : 13 : // CloseChecker is used to check that objects are closed exactly once. 14 : type CloseChecker struct { 15 : closed bool 16 : } 17 : 18 : // Close panics if called twice on the same object (if we were built with the 19 : // "invariants" or "race" build tags). 20 1 : func (d *CloseChecker) Close() { 21 1 : if d.closed { 22 0 : // Note: to debug a double-close, you can add a stack field to CloseChecker 23 0 : // and set it to string(debug.Stack()) in Close, then print that in this 24 0 : // panic. 25 0 : panic("double close") 26 : } 27 1 : d.closed = true 28 : } 29 : 30 : // AssertClosed panics in invariant builds if Close was not called. 31 0 : func (d *CloseChecker) AssertClosed() { 32 0 : if !d.closed { 33 0 : panic("not closed") 34 : } 35 : } 36 : 37 : // AssertNotClosed panics in invariant builds if Close was called. 38 0 : func (d *CloseChecker) AssertNotClosed() { 39 0 : if d.closed { 40 0 : panic("closed") 41 : } 42 : }