github.com/unigraph-dev/dgraph@v1.1.1-0.20200923154953-8b52b426f765/task/conversion.go (about)

     1  /*
     2   * Copyright 2017-2018 Dgraph Labs, Inc. and Contributors
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package task
    18  
    19  import (
    20  	"encoding/binary"
    21  
    22  	"github.com/dgraph-io/dgraph/protos/pb"
    23  )
    24  
    25  var (
    26  	// TrueVal is the pb.TaskValue value equivalent to the "true" boolean.
    27  	TrueVal = FromBool(true)
    28  	// FalseVal is the pb.TaskValue value equivalent to the "false" boolean.
    29  	FalseVal = FromBool(false)
    30  )
    31  
    32  // FromInt converts the given int value into a pb.TaskValue object.
    33  func FromInt(val int) *pb.TaskValue {
    34  	bs := make([]byte, 8)
    35  	binary.LittleEndian.PutUint64(bs, uint64(val))
    36  	return &pb.TaskValue{Val: []byte(bs), ValType: pb.Posting_INT}
    37  }
    38  
    39  // ToInt converts the given pb.TaskValue object into an integer.
    40  func ToInt(val *pb.TaskValue) int64 {
    41  	result := binary.LittleEndian.Uint64(val.Val)
    42  	return int64(result)
    43  }
    44  
    45  // FromBool converts the given boolean in to a pb.TaskValue object.
    46  func FromBool(val bool) *pb.TaskValue {
    47  	if val {
    48  		return FromInt(1)
    49  	}
    50  	return FromInt(0)
    51  }
    52  
    53  // ToBool converts the given pb.TaskValue object into a boolean.
    54  func ToBool(val *pb.TaskValue) bool {
    55  	if len(val.Val) == 0 {
    56  		return false
    57  	}
    58  	result := ToInt(val)
    59  	return result != 0
    60  }