github.com/weaviate/weaviate@v1.24.6/adapters/repos/db/aggregator/boolean.go (about)

     1  //                           _       _
     2  // __      _____  __ ___   ___  __ _| |_ ___
     3  // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
     4  //  \ V  V /  __/ (_| |\ V /| | (_| | ||  __/
     5  //   \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
     6  //
     7  //  Copyright © 2016 - 2024 Weaviate B.V. All rights reserved.
     8  //
     9  //  CONTACT: hello@weaviate.io
    10  //
    11  
    12  package aggregator
    13  
    14  import (
    15  	"bytes"
    16  	"encoding/binary"
    17  
    18  	"github.com/pkg/errors"
    19  	"github.com/weaviate/weaviate/entities/aggregation"
    20  )
    21  
    22  func newBoolAggregator() *boolAggregator {
    23  	return &boolAggregator{}
    24  }
    25  
    26  type boolAggregator struct {
    27  	countTrue  uint64
    28  	countFalse uint64
    29  }
    30  
    31  func (a *boolAggregator) AddBoolRow(value []byte, count uint64) error {
    32  	var valueParsed bool
    33  
    34  	if err := binary.Read(bytes.NewReader(value), binary.LittleEndian,
    35  		&valueParsed); err != nil {
    36  		return errors.Wrap(err, "read bool")
    37  	}
    38  
    39  	if count == 0 {
    40  		// skip
    41  		return nil
    42  	}
    43  
    44  	if valueParsed {
    45  		a.countTrue += count
    46  	} else {
    47  		a.countFalse += count
    48  	}
    49  
    50  	return nil
    51  }
    52  
    53  func (a *boolAggregator) AddBool(value bool) error {
    54  	if value {
    55  		a.countTrue++
    56  	} else {
    57  		a.countFalse++
    58  	}
    59  
    60  	return nil
    61  }
    62  
    63  func (a *boolAggregator) Res() aggregation.Boolean {
    64  	out := aggregation.Boolean{}
    65  
    66  	count := int(a.countTrue) + int(a.countFalse)
    67  	if count == 0 {
    68  		return out
    69  	}
    70  
    71  	out.Count = count
    72  	out.TotalFalse = int(a.countFalse)
    73  	out.TotalTrue = int(a.countTrue)
    74  	out.PercentageTrue = float64(a.countTrue) / float64(count)
    75  	out.PercentageFalse = float64(a.countFalse) / float64(count)
    76  
    77  	return out
    78  }