github.com/tursom/GoCollections@v0.3.10/lang/Float32.go (about)

     1  /*
     2   * Copyright (c) 2022 tursom. All rights reserved.
     3   * Use of this source code is governed by a GPL-3
     4   * license that can be found in the LICENSE file.
     5   */
     6  
     7  package lang
     8  
     9  import (
    10  	"fmt"
    11  )
    12  
    13  type Float32 float32
    14  
    15  func CastFloat32(v any) (float32, bool) {
    16  	switch i := v.(type) {
    17  	case int:
    18  		return float32(i), true
    19  	case int8:
    20  		return float32(i), true
    21  	case int16:
    22  		return float32(i), true
    23  	case int32:
    24  		return float32(i), true
    25  	case int64:
    26  		return float32(i), true
    27  	case uint:
    28  		return float32(i), true
    29  	case uint8:
    30  		return float32(i), true
    31  	case uint16:
    32  		return float32(i), true
    33  	case uint32:
    34  		return float32(i), true
    35  	case uint64:
    36  		return float32(i), true
    37  	case float32:
    38  		return i, true
    39  	case float64:
    40  		return float32(i), true
    41  	case Number:
    42  		return float32(i.ToFloat64().V()), true
    43  	default:
    44  		return 0, false
    45  	}
    46  }
    47  
    48  func EqualsFloat32(i1 Number, i2 any) bool {
    49  	i2, ok := CastFloat32(i2)
    50  	return ok && i2 == i1.ToFloat64().V()
    51  }
    52  
    53  func (i Float32) V() float32 {
    54  	return float32(i)
    55  }
    56  
    57  func (i Float32) String() string {
    58  	return fmt.Sprint(float32(i))
    59  }
    60  
    61  func (i Float32) AsObject() Object {
    62  	return i
    63  }
    64  
    65  func (i Float32) Equals(e Object) bool {
    66  	return EqualsFloat32(i, e)
    67  }
    68  
    69  func (i Float32) ToString() String {
    70  	return NewString(i.String())
    71  }
    72  
    73  func (i Float32) HashCode() int32 {
    74  	return HashFloat32(float32(i))
    75  }
    76  
    77  func (i Float32) Compare(t Float32) int {
    78  	switch {
    79  	case i > t:
    80  		return 1
    81  	case i == t:
    82  		return 0
    83  	default:
    84  		return -1
    85  	}
    86  }
    87  
    88  func (i Float32) ToInt64() Int64 {
    89  	return Int64(i)
    90  }
    91  
    92  func (i Float32) ToUInt64() UInt64 {
    93  	return UInt64(i)
    94  }
    95  
    96  func (i Float32) ToFloat64() Float64 {
    97  	return Float64(i)
    98  }
    99  
   100  func HashFloat32(f float32) int32 {
   101  	return Hash32(&f)
   102  }