"errors"
"hash"
"sync"
+ "sync/atomic"
)
// The size of a CRC-32 checksum in bytes.
var castagnoliArchImpl bool
var updateCastagnoli func(crc uint32, p []byte) uint32
var castagnoliOnce sync.Once
+var haveCastagnoli uint32
func castagnoliInit() {
castagnoliTable = simpleMakeTable(Castagnoli)
return slicingUpdate(crc, castagnoliTable8, p)
}
}
+
+ atomic.StoreUint32(&haveCastagnoli, 1)
}
// IEEETable is the table for the IEEE polynomial.
// Update returns the result of adding the bytes in p to the crc.
func Update(crc uint32, tab *Table, p []byte) uint32 {
- switch tab {
- case castagnoliTable:
+ switch {
+ case atomic.LoadUint32(&haveCastagnoli) != 0 && tab == castagnoliTable:
return updateCastagnoli(crc, p)
- case IEEETable:
+ case tab == IEEETable:
// Unfortunately, because IEEETable is exported, IEEE may be used without a
// call to MakeTable. We have to make sure it gets initialized in that case.
ieeeOnce.Do(ieeeInit)
}
func (d *digest) Write(p []byte) (n int, err error) {
- switch d.tab {
- case castagnoliTable:
+ switch {
+ case atomic.LoadUint32(&haveCastagnoli) != 0 && d.tab == castagnoliTable:
d.crc = updateCastagnoli(d.crc, p)
- case IEEETable:
+ case d.tab == IEEETable:
// We only create digest objects through New() which takes care of
// initialization in this case.
d.crc = updateIEEE(d.crc, p)
"testing"
)
+// First test, so that it can be the one to initialize castagnoliTable.
+func TestCastagnoliRace(t *testing.T) {
+ // The MakeTable(Castagnoli) lazily initializes castagnoliTable,
+ // which races with the switch on tab during Write to check
+ // whether tab == castagnoliTable.
+ ieee := NewIEEE()
+ go MakeTable(Castagnoli)
+ ieee.Write([]byte("hello"))
+}
+
type test struct {
ieee, castagnoli uint32
in string