...

Source file src/gitlab.com/tymonx/go-logger/logger/uuid4.go

Documentation: gitlab.com/tymonx/go-logger/logger

     1  // Copyright 2020 Tymoteusz Blazejczyk
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package logger
    16  
    17  import (
    18  	"crypto/rand"
    19  	"encoding/hex"
    20  	"io"
    21  )
    22  
    23  // An UUID4 represents uui4 generator.
    24  type UUID4 struct{}
    25  
    26  // NewUUID4 create a new UUID4 object.
    27  func NewUUID4() *UUID4 {
    28  	return &UUID4{}
    29  }
    30  
    31  // Generate generates new UUID4.
    32  func (u *UUID4) Generate() (id string, err error) {
    33  	var uuid [16]byte
    34  
    35  	var buffer [36]byte
    36  
    37  	if _, err := io.ReadFull(rand.Reader, uuid[:]); err != nil {
    38  		return "", NewRuntimeError("cannot generate UUID4", err)
    39  	}
    40  
    41  	uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4
    42  	uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10
    43  
    44  	u.encodeHex(uuid, buffer[:])
    45  
    46  	return string(buffer[:]), nil
    47  }
    48  
    49  // encodeHex encodes uuid to UUID format.
    50  func (*UUID4) encodeHex(uuid [16]byte, buffer []byte) {
    51  	hex.Encode(buffer, uuid[:4])
    52  	buffer[8] = '-'
    53  
    54  	hex.Encode(buffer[9:13], uuid[4:6])
    55  	buffer[13] = '-'
    56  
    57  	hex.Encode(buffer[14:18], uuid[6:8])
    58  	buffer[18] = '-'
    59  
    60  	hex.Encode(buffer[19:23], uuid[8:10])
    61  	buffer[23] = '-'
    62  
    63  	hex.Encode(buffer[24:], uuid[10:])
    64  }
    65  

View as plain text