github.com/kaleido-io/firefly@v0.0.0-20210622132723-8b4b6aacb971/pkg/fftypes/uuid.go (about)

     1  // Copyright © 2021 Kaleido, Inc.
     2  //
     3  // SPDX-License-Identifier: Apache-2.0
     4  //
     5  // Licensed under the Apache License, Version 2.0 (the "License");
     6  // you may not use this file except in compliance with the License.
     7  // You may obtain a copy of the License at
     8  //
     9  //     http://www.apache.org/licenses/LICENSE-2.0
    10  //
    11  // Unless required by applicable law or agreed to in writing, software
    12  // distributed under the License is distributed on an "AS IS" BASIS,
    13  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14  // See the License for the specific language governing permissions and
    15  // limitations under the License.
    16  
    17  package fftypes
    18  
    19  import (
    20  	"context"
    21  	"database/sql/driver"
    22  
    23  	"github.com/google/uuid"
    24  	"github.com/kaleido-io/firefly/internal/i18n"
    25  )
    26  
    27  // UUID is a wrapper on a UUID implementation, ensuring Value handles nil
    28  type UUID uuid.UUID
    29  
    30  func ParseUUID(ctx context.Context, uuidStr string) (*UUID, error) {
    31  	u, err := uuid.Parse(uuidStr)
    32  	if err != nil {
    33  		return nil, i18n.WrapError(context.Background(), err, i18n.MsgInvalidUUID)
    34  	}
    35  	uuid := UUID(u)
    36  	return &uuid, nil
    37  }
    38  
    39  func MustParseUUID(uuidStr string) *UUID {
    40  	uuid := UUID(uuid.MustParse(uuidStr))
    41  	return &uuid
    42  }
    43  
    44  func NewUUID() *UUID {
    45  	u := UUID(uuid.New())
    46  	return &u
    47  }
    48  
    49  func (u *UUID) String() string {
    50  	if u == nil {
    51  		return ""
    52  	}
    53  	return (*uuid.UUID)(u).String()
    54  }
    55  
    56  func (u UUID) MarshalText() ([]byte, error) {
    57  	return (uuid.UUID)(u).MarshalText()
    58  }
    59  
    60  func (u *UUID) UnmarshalText(b []byte) error {
    61  	return (*uuid.UUID)(u).UnmarshalText(b)
    62  }
    63  
    64  func (u UUID) MarshalBinary() ([]byte, error) {
    65  	return (uuid.UUID)(u).MarshalBinary()
    66  }
    67  
    68  func (u *UUID) UnmarshalBinary(b []byte) error {
    69  	return (*uuid.UUID)(u).UnmarshalBinary(b)
    70  }
    71  
    72  func (u *UUID) Value() (driver.Value, error) {
    73  	if u == nil {
    74  		return nil, nil
    75  	}
    76  	return (uuid.UUID)(*u).Value()
    77  }
    78  
    79  func (u *UUID) Scan(src interface{}) error {
    80  	return (*uuid.UUID)(u).Scan(src)
    81  }
    82  
    83  func (u *UUID) Equals(u2 *UUID) bool {
    84  	switch {
    85  	case u == nil && u2 == nil:
    86  		return true
    87  	case u == nil || u2 == nil:
    88  		return false
    89  	default:
    90  		return *u == *u2
    91  	}
    92  }