github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/services/authorizations/id.go (about)

     1  /*
     2   * Copyright 2023 Wang Min Xiang
     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  
    18  package authorizations
    19  
    20  import (
    21  	"fmt"
    22  	"github.com/aacfactory/errors"
    23  	"github.com/aacfactory/fns/commons/bytex"
    24  	"strconv"
    25  )
    26  
    27  type Id []byte
    28  
    29  func (id Id) MarshalJSON() ([]byte, error) {
    30  	return bytex.FromString(fmt.Sprintf("\"%s\"", id.String())), nil
    31  }
    32  
    33  func (id *Id) UnmarshalJSON(p []byte) error {
    34  	pLen := len(p)
    35  	if pLen < 2 {
    36  		return nil
    37  	}
    38  	s := make([]byte, pLen-2)
    39  	copy(s, p[1:pLen-1])
    40  	*id = s
    41  	return nil
    42  }
    43  
    44  func (id Id) Int() int64 {
    45  	if len(id) == 0 {
    46  		return 0
    47  	}
    48  	v, err := strconv.ParseInt(id.String(), 10, 64)
    49  	if err != nil {
    50  		panic(errors.Warning("authorizations: get int value from id failed").WithCause(err).WithMeta("id", id.String()))
    51  		return 0
    52  	}
    53  	return v
    54  }
    55  
    56  func (id Id) String() string {
    57  	return bytex.ToString(id)
    58  }
    59  
    60  func (id Id) Exist() (ok bool) {
    61  	ok = len(id) > 0
    62  	return
    63  }
    64  
    65  func StringId(id []byte) Id {
    66  	return id
    67  }
    68  
    69  func IntId(id int64) Id {
    70  	return bytex.FromString(strconv.FormatInt(id, 10))
    71  }