github.com/zuoyebang/bitalosdb@v1.1.1-0.20240516111551-79a8c4d8ce20/bithash/bithash_writer.go (about)

     1  // Copyright 2021 The Bitalosdb author(hustxrb@163.com) and other contributors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package bithash
    16  
    17  import "github.com/zuoyebang/bitalosdb/internal/base"
    18  
    19  type BithashWriter struct {
    20  	b       *Bithash
    21  	wr      *Writer
    22  	compact bool
    23  }
    24  
    25  func (w *BithashWriter) Add(ikey base.InternalKey, value []byte) (FileNum, error) {
    26  	var err error
    27  	if w.wr == nil {
    28  		return FileNum(0), err
    29  	}
    30  
    31  	if err = w.wr.Add(ikey, value); err != nil {
    32  		return FileNum(0), err
    33  	}
    34  
    35  	fileNum := w.wr.fileNum
    36  	w.b.stats.KeyTotal.Add(1)
    37  
    38  	_ = w.maybeSplitTable()
    39  
    40  	return fileNum, nil
    41  }
    42  
    43  func (w *BithashWriter) AddIkey(key *InternalKey, value []byte, khash uint32, fileNum FileNum) error {
    44  	return w.wr.AddIkey(key.Clone(), value, khash, fileNum)
    45  }
    46  
    47  func (w *BithashWriter) maybeSplitTable() error {
    48  	if !w.wr.isWriteFull() {
    49  		return nil
    50  	}
    51  
    52  	if err := w.wr.Flush(); err != nil {
    53  		return err
    54  	}
    55  
    56  	writer, err := NewTableWriter(w.b, w.compact)
    57  	if err != nil {
    58  		return err
    59  	}
    60  
    61  	closeWriter := w.wr
    62  	w.wr = writer
    63  
    64  	w.b.closeTableAsync(closeWriter, false)
    65  
    66  	return nil
    67  }
    68  
    69  func (w *BithashWriter) Finish() error {
    70  	if w.wr == nil {
    71  		return nil
    72  	}
    73  
    74  	if err := w.wr.Flush(); err != nil {
    75  		return err
    76  	}
    77  
    78  	if w.compact {
    79  		return w.b.closeTable(w.wr, true)
    80  	}
    81  
    82  	if !w.wr.isWriteFull() {
    83  		w.b.pushMutableWriters(w.wr)
    84  	}
    85  
    86  	return nil
    87  }
    88  
    89  func (w *BithashWriter) GetFileNum() FileNum {
    90  	return w.wr.fileNum
    91  }
    92  
    93  func (w *BithashWriter) Remove() error {
    94  	return w.wr.Remove()
    95  }