github.com/shogo-ma/goa@v1.3.1/uuid/uuid_js.go (about)

     1  // +build js
     2  
     3  //This part is copied from github.com/satori/go.uuid but some feature uses non gopherjs compliants calls
     4  //Since goa only needs a subset of the features the js copies them in here
     5  
     6  package uuid
     7  
     8  import (
     9  	"bytes"
    10  	"encoding/hex"
    11  	"fmt"
    12  )
    13  
    14  // String parse helpers.
    15  var (
    16  	urnPrefix  = []byte("urn:uuid:")
    17  	byteGroups = []int{8, 4, 4, 4, 12}
    18  )
    19  
    20  // FromString returns UUID parsed from string input.
    21  // Input is expected in a form accepted by UnmarshalText.
    22  func FromString(input string) (u UUID, err error) {
    23  	err = u.UnmarshalText([]byte(input))
    24  	return
    25  }
    26  
    27  // UnmarshalText implements the encoding.TextUnmarshaler interface.
    28  // Following formats are supported:
    29  // "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
    30  // "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
    31  // "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8"
    32  func (u *UUID) UnmarshalText(text []byte) (err error) {
    33  	if len(text) < 32 {
    34  		err = fmt.Errorf("uuid: UUID string too short: %s", text)
    35  		return
    36  	}
    37  
    38  	t := text[:]
    39  
    40  	if bytes.Equal(t[:9], urnPrefix) {
    41  		t = t[9:]
    42  	} else if t[0] == '{' {
    43  		t = t[1:]
    44  	}
    45  
    46  	b := u[:]
    47  
    48  	for _, byteGroup := range byteGroups {
    49  		if t[0] == '-' {
    50  			t = t[1:]
    51  		}
    52  
    53  		if len(t) < byteGroup {
    54  			err = fmt.Errorf("uuid: UUID string too short: %s", text)
    55  			return
    56  		}
    57  
    58  		_, err = hex.Decode(b[:byteGroup/2], t[:byteGroup])
    59  
    60  		if err != nil {
    61  			return
    62  		}
    63  
    64  		t = t[byteGroup:]
    65  		b = b[byteGroup/2:]
    66  	}
    67  
    68  	return
    69  }
    70  
    71  // Used in string method conversion
    72  const dash byte = '-'
    73  
    74  // Returns canonical string representation of UUID:
    75  // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
    76  func (u UUID) String() string {
    77  	buf := make([]byte, 36)
    78  
    79  	hex.Encode(buf[0:8], u[0:4])
    80  	buf[8] = dash
    81  	hex.Encode(buf[9:13], u[4:6])
    82  	buf[13] = dash
    83  	hex.Encode(buf[14:18], u[6:8])
    84  	buf[18] = dash
    85  	hex.Encode(buf[19:23], u[8:10])
    86  	buf[23] = dash
    87  	hex.Encode(buf[24:], u[10:])
    88  
    89  	return string(buf)
    90  }