...

Source file src/github.com/pborman/uuid/marshal.go

Documentation: github.com/pborman/uuid

     1  // Copyright 2016 Google Inc.  All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package uuid
     6  
     7  import (
     8  	"errors"
     9  	"fmt"
    10  
    11  	guuid "github.com/google/uuid"
    12  )
    13  
    14  // MarshalText implements encoding.TextMarshaler.
    15  func (u UUID) MarshalText() ([]byte, error) {
    16  	if len(u) != 16 {
    17  		return nil, nil
    18  	}
    19  	var js [36]byte
    20  	encodeHex(js[:], u)
    21  	return js[:], nil
    22  }
    23  
    24  // UnmarshalText implements encoding.TextUnmarshaler.
    25  func (u *UUID) UnmarshalText(data []byte) error {
    26  	if len(data) == 0 {
    27  		return nil
    28  	}
    29  	id := Parse(string(data))
    30  	if id == nil {
    31  		return errors.New("invalid UUID")
    32  	}
    33  	*u = id
    34  	return nil
    35  }
    36  
    37  // MarshalBinary implements encoding.BinaryMarshaler.
    38  func (u UUID) MarshalBinary() ([]byte, error) {
    39  	return u[:], nil
    40  }
    41  
    42  // UnmarshalBinary implements encoding.BinaryUnmarshaler.
    43  func (u *UUID) UnmarshalBinary(data []byte) error {
    44  	if len(data) == 0 {
    45  		return nil
    46  	}
    47  	if len(data) != 16 {
    48  		return fmt.Errorf("invalid UUID (got %d bytes)", len(data))
    49  	}
    50  	var id [16]byte
    51  	copy(id[:], data)
    52  	*u = id[:]
    53  	return nil
    54  }
    55  
    56  // MarshalText implements encoding.TextMarshaler.
    57  func (u Array) MarshalText() ([]byte, error) {
    58  	var js [36]byte
    59  	encodeHex(js[:], u[:])
    60  	return js[:], nil
    61  }
    62  
    63  // UnmarshalText implements encoding.TextUnmarshaler.
    64  func (u *Array) UnmarshalText(data []byte) error {
    65  	id, err := guuid.ParseBytes(data)
    66  	if err != nil {
    67  		return err
    68  	}
    69  	*u = Array(id)
    70  	return nil
    71  }
    72  
    73  // MarshalBinary implements encoding.BinaryMarshaler.
    74  func (u Array) MarshalBinary() ([]byte, error) {
    75  	return u[:], nil
    76  }
    77  
    78  // UnmarshalBinary implements encoding.BinaryUnmarshaler.
    79  func (u *Array) UnmarshalBinary(data []byte) error {
    80  	if len(data) != 16 {
    81  		return fmt.Errorf("invalid UUID (got %d bytes)", len(data))
    82  	}
    83  	copy(u[:], data)
    84  	return nil
    85  }
    86  

View as plain text