// Copyright 2021 Google Inc.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package uuid

import (
	
	
	
	
)

var jsonNull = []byte("null")

// NullUUID represents a UUID that may be null.
// NullUUID implements the SQL driver.Scanner interface so
// it can be used as a scan destination:
//
//  var u uuid.NullUUID
//  err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&u)
//  ...
//  if u.Valid {
//     // use u.UUID
//  } else {
//     // NULL value
//  }
//
type NullUUID struct {
	UUID  UUID
	Valid bool // Valid is true if UUID is not NULL
}

// Scan implements the SQL driver.Scanner interface.
func ( *NullUUID) ( interface{}) error {
	if  == nil {
		.UUID, .Valid = Nil, false
		return nil
	}

	 := .UUID.Scan()
	if  != nil {
		.Valid = false
		return 
	}

	.Valid = true
	return nil
}

// Value implements the driver Valuer interface.
func ( NullUUID) () (driver.Value, error) {
	if !.Valid {
		return nil, nil
	}
	// Delegate to UUID Value function
	return .UUID.Value()
}

// MarshalBinary implements encoding.BinaryMarshaler.
func ( NullUUID) () ([]byte, error) {
	if .Valid {
		return .UUID[:], nil
	}

	return []byte(nil), nil
}

// UnmarshalBinary implements encoding.BinaryUnmarshaler.
func ( *NullUUID) ( []byte) error {
	if len() != 16 {
		return fmt.Errorf("invalid UUID (got %d bytes)", len())
	}
	copy(.UUID[:], )
	.Valid = true
	return nil
}

// MarshalText implements encoding.TextMarshaler.
func ( NullUUID) () ([]byte, error) {
	if .Valid {
		return .UUID.MarshalText()
	}

	return jsonNull, nil
}

// UnmarshalText implements encoding.TextUnmarshaler.
func ( *NullUUID) ( []byte) error {
	,  := ParseBytes()
	if  != nil {
		.Valid = false
		return 
	}
	.UUID = 
	.Valid = true
	return nil
}

// MarshalJSON implements json.Marshaler.
func ( NullUUID) () ([]byte, error) {
	if .Valid {
		return json.Marshal(.UUID)
	}

	return jsonNull, nil
}

// UnmarshalJSON implements json.Unmarshaler.
func ( *NullUUID) ( []byte) error {
	if bytes.Equal(, jsonNull) {
		* = NullUUID{}
		return nil // valid null UUID
	}
	 := json.Unmarshal(, &.UUID)
	.Valid =  == nil
	return 
}