github.com/matrixorigin/matrixone@v1.2.0/pkg/container/types/bool.go (about)

     1  // Copyright 2021 - 2022 Matrix Origin
     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 types
    16  
    17  import (
    18  	"go/constant"
    19  	"strconv"
    20  	"strings"
    21  
    22  	"github.com/matrixorigin/matrixone/pkg/common/moerr"
    23  	"github.com/matrixorigin/matrixone/pkg/sql/parsers/tree"
    24  )
    25  
    26  func ParseValueToBool(num *tree.NumVal) (bool, error) {
    27  	val := num.Value
    28  	str := num.String()
    29  	if !num.Negative() {
    30  		v, _ := constant.Uint64Val(val)
    31  		if v == 0 {
    32  			return false, nil
    33  		} else if v == 1 {
    34  			return true, nil
    35  		}
    36  	}
    37  	return false, moerr.NewInvalidInputNoCtx("'%s' is not a valid bool expression", str)
    38  }
    39  
    40  func AppendBoolToByteArray(b bool, arr []byte) []byte {
    41  	if b {
    42  		arr = append(arr, '1')
    43  	} else {
    44  		arr = append(arr, '0')
    45  	}
    46  	return arr
    47  }
    48  
    49  func ParseBool(s string) (bool, error) {
    50  	s = strings.ToLower(s)
    51  	if s == "true" {
    52  		return true, nil
    53  	} else if s == "false" {
    54  		return false, nil
    55  	}
    56  	val, err := strconv.ParseFloat(s, 64)
    57  	if err == nil {
    58  		if val != 0 {
    59  			return true, nil
    60  		} else {
    61  			return false, nil
    62  		}
    63  	}
    64  	return false, moerr.NewInvalidInputNoCtx("'%s' is not a valid bool expression", s)
    65  
    66  }
    67  
    68  // ToIntString print out 1 or 0 as true/false.
    69  func BoolToIntString(b bool) string {
    70  	if b {
    71  		return "1"
    72  	}
    73  	return "0"
    74  }