github.com/TrueBlocks/trueblocks-core/src/apps/chifra@v0.0.0-20241022031540-b362680128f7/pkg/index/bloom_write.go (about)

     1  package index
     2  
     3  import (
     4  	"encoding/binary"
     5  	"io"
     6  	"os"
     7  
     8  	"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/base"
     9  	"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/config"
    10  	"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/file"
    11  )
    12  
    13  // writeBloom writes a single Bloom filter to file. We do not make a backup copy of the file
    14  // because the caller is responsible for that. This is because the caller may be writing the
    15  // entire chunk (both Bloom and Index) and we want either both to succeed or both to fail.
    16  func (bl *Bloom) writeBloom(fileName string) ( /* changed */ bool, error) {
    17  	var err error
    18  	if bl.File, err = os.OpenFile(fileName, os.O_RDWR|os.O_CREATE, 0644); err == nil {
    19  		defer func() {
    20  			bl.File.Close()
    21  			bl.File = nil
    22  		}()
    23  
    24  		_, _ = bl.File.Seek(0, io.SeekStart) // already true, but can't hurt
    25  		bl.Header.Magic = file.SmallMagicNumber
    26  		bl.Header.Hash = base.BytesToHash(config.HeaderHash(config.ExpectedVersion()))
    27  
    28  		if err = binary.Write(bl.File, binary.LittleEndian, bl.Header); err != nil {
    29  			return false, err
    30  		}
    31  
    32  		if err = binary.Write(bl.File, binary.LittleEndian, bl.Count); err != nil {
    33  			return false, err
    34  		}
    35  
    36  		for _, bb := range bl.Blooms {
    37  			if err = binary.Write(bl.File, binary.LittleEndian, bb.NInserted); err != nil {
    38  				return false, err
    39  			}
    40  			if err = binary.Write(bl.File, binary.LittleEndian, bb.Bytes); err != nil {
    41  				return false, err
    42  			}
    43  		}
    44  
    45  		return true, nil
    46  	}
    47  
    48  	return false, nil
    49  }
    50  
    51  // updateTag writes a the header back to the bloom file
    52  func (bl *Bloom) updateTag(tag, fileName string) error {
    53  	var err error
    54  	if bl.File, err = os.OpenFile(fileName, os.O_RDWR, 0644); err != nil {
    55  		return err
    56  
    57  	} else {
    58  		defer func() {
    59  			_ = bl.File.Sync()
    60  			_ = bl.File.Close()
    61  			bl.File = nil
    62  		}()
    63  
    64  		bl.Header.Magic = file.SmallMagicNumber
    65  		bl.Header.Hash = base.BytesToHash(config.HeaderHash(tag))
    66  
    67  		_, _ = bl.File.Seek(0, io.SeekStart) // already true, but can't hurt
    68  		return binary.Write(bl.File, binary.LittleEndian, bl.Header)
    69  	}
    70  }