github.com/e154/smart-home@v0.17.2-0.20240311175135-e530a6e5cd45/common/null/int64.go (about)

     1  // This file is part of the Smart Home
     2  // Program complex distribution https://github.com/e154/smart-home
     3  // Copyright (C) 2016-2023, Filippov Alex
     4  //
     5  // This library is free software: you can redistribute it and/or
     6  // modify it under the terms of the GNU Lesser General Public
     7  // License as published by the Free Software Foundation; either
     8  // version 3 of the License, or (at your option) any later version.
     9  //
    10  // This library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    13  // Library General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Lesser General Public
    16  // License along with this library.  If not, see
    17  // <https://www.gnu.org/licenses/>.
    18  
    19  package null
    20  
    21  import (
    22  	"database/sql/driver"
    23  	"strconv"
    24  )
    25  
    26  // Int64 ...
    27  type Int64 struct {
    28  	Int64 int64
    29  	Valid bool // Valid is true if Int64 is not NULL
    30  }
    31  
    32  // NewInt64 ...
    33  func NewInt64(value interface{}) (i Int64) {
    34  	i = Int64{}
    35  	_ = i.Scan(value)
    36  	return
    37  }
    38  
    39  // Scan ...
    40  func (n *Int64) Scan(value interface{}) error {
    41  	if value == nil {
    42  		n.Int64, n.Valid = 0, false
    43  		return nil
    44  	}
    45  	n.Valid = true
    46  	return convertAssign(&n.Int64, value)
    47  }
    48  
    49  // Value ...
    50  func (n Int64) Value() (driver.Value, error) {
    51  	if !n.Valid {
    52  		return nil, nil
    53  	}
    54  	return n.Int64, nil
    55  }
    56  
    57  // String ...
    58  func (n Int64) String() (value string) {
    59  	if !n.Valid {
    60  		value = "null"
    61  		return
    62  	}
    63  	value = strconv.FormatInt(n.Int64, 10)
    64  	return
    65  }
    66  
    67  // MarshalJSON ...
    68  func (n Int64) MarshalJSON() ([]byte, error) {
    69  	return []byte(n.String()), nil
    70  }
    71  
    72  // UnmarshalJSON ...
    73  func (n *Int64) UnmarshalJSON(data []byte) error {
    74  	i64, err := strconv.ParseInt(string(data), 10, 0)
    75  	if err != nil {
    76  		return nil
    77  	}
    78  	n.Valid = true
    79  	return n.Scan(i64)
    80  }