Git Product home page Git Product logo

uuid's Introduction

uuid

The uuid package generates and inspects UUIDs based on RFC 4122 and DCE 1.1: Authentication and Security Services.

This package is based on the github.com/pborman/uuid package (previously named code.google.com/p/go-uuid). It differs from these earlier packages in that a UUID is a 16 byte array rather than a byte slice. One loss due to this change is the ability to represent an invalid UUID (vs a NIL UUID).

Install
go get github.com/google/uuid
Documentation

Go Reference

Full go doc style documentation for the package can be viewed online without installing this package by using the GoDoc site here: https://pkg.go.dev/github.com/google/uuid

uuid's People

Contributors

alexandear avatar ayang64 avatar bmatsuo avatar bormanp avatar deining avatar dsymonds avatar it512 avatar jackterm avatar jboverfelt avatar johejo avatar kortschak avatar kotaroyamazaki avatar kveselkov avatar ljahier avatar martinlindhe avatar noahdietz avatar pborman avatar prochac avatar release-please[bot] avatar sallescosta avatar sejr avatar shawnps avatar sjeandeaux avatar syohex avatar thatguystone avatar theory avatar trabetti avatar wallclockbuilder avatar wawan93 avatar yusufpapurcu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

uuid's Issues

Update documentation and code for Invalid Variant

It would be nice if the uuid.Invalid documentation or the (uuid.UUID).Variant() documentation mentioned this in addition to the readme, as it was confusing until I saw 3943dc5. I had read through the documentation, code, and tests before the readme of the repository, so there was a little wasted effort and confusion.

Specifically, the unit tests are a little misleading, as uuid.Parse() returns an error in the Invalid cases:

uuid/uuid_test.go

Lines 62 to 67 in 44b5fee

{"f47ac10b158cc-5372-a567-0e02b2c3d479", 0, Invalid, false},
{"f47ac10b-58cc25372-a567-0e02b2c3d479", 0, Invalid, false},
{"f47ac10b-58cc-53723a567-0e02b2c3d479", 0, Invalid, false},
{"f47ac10b-58cc-5372-a56740e02b2c3d479", 0, Invalid, false},
{"f47ac10b-58cc-5372-a567-0e02-2c3d479", 0, Invalid, false},
{"g47ac10b-58cc-4372-a567-0e02b2c3d479", 0, Invalid, false},

The variant is never checked in the unit tests in an error scenario:

uuid/uuid_test.go

Lines 99 to 101 in 44b5fee

if err != nil {
return
}

The func of New() cost more than 9 minute

My online app is use this lib by uuid.New(),
About 3 million concurrent
I found per call of uuid.New() cost more than 9 minutes.
I found many mutex in it's call chain.
Is there any problems?

Add parsing support for braced and non-dashed string forms

I would like to prepare and submit a pull request that adds parsing support for two string forms that are not RFC-4122 compliant:

Braced

{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}

Non-dashed

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

The first is commonly generated by APIs and tools on the Windows platform.

The second is the hexadecimal encoding of the uuid without any further treatment.

Both assume the hexadecimal values to be in big-endian order, as per the spec. Any platform-specific byte-reordering would be left to the user.

The form of an input string can quickly be determined by its length, and the lengths are unique so parsing remains deterministic.

Zero Value Check

I can write a convenience function to check for the zero value. For example:

package main

import (
	"fmt"

	"github.com/google/uuid"
)

func IsZero(id uuid.UUID) bool {
	for x := 0; x < 16; x++ {
		if id[x] != 0 {
			return false
		}
	}
	return true
}

func main() {
	id := uuid.UUID{}
	fmt.Printf("is %v zero? %t\n", id, IsZero(id))
	id, _ = uuid.NewRandom()
	fmt.Printf("is %v zero? %t\n", id, IsZero(id))
}

Is that the thing to do, or is there a better way to check for the zero value?

Is this package cryptographically secure?

I am working on a legacy app that used UUID v4 as its authentication key. Is that secure? (Some implementations, like python3's are secure, meanwhile others aren't)

Moving the entire app to crytpo/rand would be way too much.

0.1.0 seems to be broken

Hey,

I installed uuid via glide init method, which recognizes the release as:

- package: github.com/google/uuid
  version: ^0.1.0

This causes the following error during compile time:

./vendor/github.com/google/uuid/json.go:28: multiple-value Parse() in single-value context

Thanks,

Asaf.

The hexadecimal input required by ParseBytes may surprise users

When I first encountered the ParseBytes function I was very surprised that it wasn't meant to parse the raw 16 bytes of a uuid, but instead was meant to parse hexadecimal data. I suspect other users of the library will have the same reaction. It turned out that what I actually was looking for was FromBytes.

I realize that it's useful to have a hexadecimal byte-parsing function for performance reasons because it avoids copying data around, but if I hadn't checked the docs I might not have realized I had the wrong function until I received an error from it.

I propose that one of two actions be taken:

  1. Rename ParseBytes to ParseHexBytes to make its intention more clear
  2. Modify ParseBytes to include handling for 16-byte inputs that are then fed into UnmarshalBinary

error: certificate signed by unknown authority

Hi,

Thank you for the package! I'm struggling with the following problem due installation instruction from README. Right after the command go get github.com/google/uuid I'm getting the following error:

$ go get github.com/google/uuid

go: downloading github.com/google/uuid v1.3.0
go get: github.com/google/[email protected]: verifying module: github.com/google/[email protected]: Get "https://sum.golang.org/lookup/github.com/google/[email protected]": x509: certificate signed by unknown authority

version:

$ go version                   
go version go1.17.2 darwin/amd64

Could you help me please?

not able to install uuid package

RUN go install github.com/google/[email protected] or RUN go install github.com/google/uuid running these command but getting such error,
RUN go install github.com/google/[email protected]:
#10 0.943 go: downloading github.com/google/uuid v1.3.0
#10 2.980 package github.com/google/uuid is not a main package

executor failed running [/bin/sh -c go install github.com/google/[email protected]]: exit code: 1

please give me some solution for same

Is there a method to generate empty UUID v4?

Hi! I noticed there is a uuid.Nil for UUID v1 but no uuid.Nil (for example uuid.Nil4) for UUID v4 could be useful adding this method to the library? (I could also make a PR)

Getting time

Greetings !!

How do I print the time of the parsed UUID?

Thanks in advance.

Are there any plans for v1?

Seems like the repo hasn't been tended to in a while - are there any plans to make a v1 release as mentioned in the readme?

Casting byte slice to UUID?

We are passing 16 byte binary UUIDs via grpc and need to be able to cast these from byte slice back to type uuid.UUID. There doesn't seem to be an easy way to do this. It would be nice if the package had a method for this.
This works but is there a better way?

  var b [16]byte

   copy(b[:], bslice)
   guid := uuid.UUID(b)


The v1.0.0 release has old source in zip and tar.gz files.

I found this by using Go 1.11 modules. It would download the v1.0.0 zip file but the file contents are quite old. The copyright on each file is from 2016 and the MustParse function is missing.

I manually download the zip and tar.gz files and they also contain the old source.

https://github.com/google/uuid/archive/v1.0.0.zip
https://github.com/google/uuid/archive/v1.0.0.tar.gz

I had to switch my go modules to use master to work around this issue.

Test failures (TestNode, TestNodeID)

I'm getting the following test failures with Golang 1.10:

=== RUN   TestNode
--- FAIL: TestNode (0.00s)
        uuid_test.go:306: NodeInterface returned an empty string
=== RUN   TestNodeID
--- FAIL: TestNodeID (0.00s)
        uuid_test.go:376: NodeInterface "user" after SetInteface

[HELP] Is there any ways to improve the performance in multi-goroutine env ?

Hello, we have a scenario that needs to generate UUID quickly.
At present, its performance in multi-threaded environment is not ideal. Do you have any solutions
Here is the benchmark data:
BenchmarkUUIDSinleGoroutine-32 1000000000 0.0000038 ns/op 0 B/op 0 allocs/op
BenchmarkUUIDMultiGoroutine-32 2307704 523.6 ns/op 16 B/op 1 allocs/op

Thanks :)

Add support for bazel BUILD

Hello,
I've just added a dependency to this project in a bazel compiled system and it was a bit clunky with no BUILD file around.
My current dependency looks like this:
new_git_repository(
name = "google_uuid",
build_file_content = """
load("@io_bazel_rules_go//go:def.bzl", "go_prefix")
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_prefix("github.com/google/uuid")
go_library(
name = "go_default_library",
srcs = glob([".go"], exclude=["_test.go"]),
deps = [
],
visibility = ["//visibility:public"],
)
""",
tag = "0.2",
remote = "https://github.com/google/uuid",
)

It would be fairly simple to add a BUILD file - if you are ok with that I can just send a pull request (and simplify my dependencies ;-) ).

Requesting some clarification on a sentence in README

Hi, could someone confirm if my understanding of this sentence is correct?

"One loss due to this change is the ability to represent an invalid UUID (vs a NIL UUID)."

This is saying that it's not possible to represent an invalid UUID with the google/uuid library because it is a strict 16-byte array rather than a byte slice? When/why would I want to be able to represent invalid UUIDs, for testing?

Thank you!

MarshalBinary() error return value redundant

err is always nil, is there any reason behind it? I know it probably won't be fixed to avoid breaking changes. But doesn't this cause unneeded overhead, or is the compiler smart enough to ignore this?

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

return uuid[:], nil

Allow concurrent, re-creatable usage

Hi, I am using this package to generate uuids for a test generator. I have a use case where multiple instances of the generator run asynchronously to create tests.
I need to be able to recreate failed tests, the current implementation holds only one seed, so there is no way to ensure recreation when processes are running asynchronously.
I have forked the repository and added a UuidSource, similar to a source in math/rand, which holds the rander, this solves my use case.
I suggest to do a PR from my fork.

UUID with repeat ending

Greetings!

I would like to know why version 1 repeats the ends of sequences, ie using NewUUID() the results always end in -0022684e5e1b. Is there a way to change this or a purpose for this to occur?

Thanks in advance.

Panic when uuid.New().String()

I run a horizontally scaled application in k8s producing UUIDs for messages. However, rarely, some replicated pods restart due to a panic coming for the UUID library.

panic: unexpected EOF                                                                                                                                                                                                                        
goroutine 197286 [running]:                                                                                                                                                                                                                  
github.com/google/uuid.Must(...)                                                                                                                                                                                                             
 /home/vagrant/go/pkg/mod/github.com/google/[email protected]/uuid.go:178                                                                                                                                                                      
github.com/google/uuid.New(...)                                                                                                                                                                                                              
 /home/vagrant/go/pkg/mod/github.com/google/[email protected]/version4.go:14

Is there any OS/library causing these issues, like too little entropy? On my local machine, I run a test producing billions of UUIDs without any panic.

UUID to []byte?

Is there any function to get []byte from a UUID instance, or I should write the code as below?

func getBytes(u uuid.UUID) []byte {
	b := make([]byte, 16)
	for i := range b {
		b[i] = u[i]
	}
	return b
}

📝 Compile Version not matches

📝 Compile Version not matches

I input in terminal go get github.com/google/uuid
Go version: - go version go1.15.3 darwin/amd64

Go env

GO111MODULE=""
GOARCH="amd64"
GOBIN="/Users/vovs03/go/bin"
GOCACHE="/Users/vovs03/Library/Caches/go-build"
GOENV="/Users/vovs03/Library/Application Support/go/env"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOINSECURE=""
GOMODCACHE="/Users/vovs03/go/pkg/mod"
GONOPROXY=""
GONOSUMDB=""
GOOS="darwin"
GOPATH="/Users/vovs03/go"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/usr/local/go"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/local/go/pkg/tool/darwin_amd64"
GCCGO="gccgo"
AR="ar"
CC="clang"
CXX="clang++"
CGO_ENABLED="1"
GOMOD=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/zr/05xnlj6d0bz4fqxf6mv7km1h0000gn/T/go-build085126828=/tmp/go-build -gno-record-gcc-switches -fno-common"

🅰️ Problem

result of go get github.com/google/uuid

Снимок экрана 2020-11-06 в 9 23 19

How can me solve this problem? Any ideas...

About NullUUID MarshalText() output

Is it right that MarshalText() function, if the input is not valid, returns the same output ([]byte("null")) as MarshalJSON() function?

uuid/null.go

Line 85 in 44b5fee

return jsonNull, nil

Wouldn't it be better if it returned a[]byte{}?
Thank you, and sorry if my question seems stupid.

error in json.go

./json.go:28: multiple-value Parse() in single-value context

uu, err := Parse(string(data))
if err != nil {

Release/Tag new version

In order to use Go Dep effectively with semver, please release or tag a new version. Using revisions with many open source project dependencies makes Go Dep much less convenient. The latest version is roughly 1 year and 22 commits in the past thus I could argue a new version is likely. It also seems lately new features were thus further strengthen the idea to bump the version.

Parsing "Microsoft encoding" is very lenient

I was reading through the code for Parse and I noticed that there is no validation on the first and last characters of the uuid-to-parse when the length of the input is 38 characters:

uuid/uuid.go

Lines 38 to 61 in 16ca3ea

// Parse decodes s into a UUID or returns an error. Both the standard UUID
// forms of xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and
// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx are decoded as well as the
// Microsoft encoding {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} and the raw hex
// encoding: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.
func Parse(s string) (UUID, error) {
var uuid UUID
switch len(s) {
// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
case 36:
// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
case 36 + 9:
if strings.ToLower(s[:9]) != "urn:uuid:" {
return uuid, fmt.Errorf("invalid urn prefix: %q", s[:9])
}
s = s[9:]
// {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
case 36 + 2:
s = s[1:]
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
case 32:

I would expect there to be a check that s[0] == '{' && s[37] == '}' rather than simply ignoring those two characters. I am happy to send a PR if requested, it's a simple change. I am just verifying that this loose behavior is not actually desired.

(fwiw, it means that parsing something like a01234567-abcd-cdef-abcd-012345678901a would be parsed without an error, even though it has extra characters at the beginning and end. That's quite unexpected IMO.)

Deprecate EnableRandPool and DisableRandPool

v1.3.0 introduced the EnableRandPool and DisableRandPool functions as a means of optimizing UUID generation at the expense of security. However, there are two main issues with this.

First, as documented, neither of these are thread-safe. However, the described solution is not feasible:

// Both EnableRandPool and DisableRandPool are not thread-safe and should
// only be called when there is no possibility that New or any other
// UUID Version 4 generation function will be called concurrently.

I cannot in general easily account for what all the package initializers of all of my transitive dependencies are doing. Instead of a function called a runtime, this opt-in behavior should be controlled by a build tag, so the pool can be enabled at compile time. Then there is no race condition. (You could also replace the poolEnabled bool with an atomically read/written uint32, which at least resolves the race condition. But the build tag is more air tight.)

Second, as documented, the optimization is not suitable for security sensitive applications. However, again, I cannot account for what all of my transitive dependencies are doing. And in general, only having a global flag that effectively disables security seems like a rather poor design choice. It would be preferable if the decision could be made by the client on a case-by-case basis.

Going forward, it probably makes sense to deprecate the various global constructor functions and replace them with a factory object, similar to net.Dialer. Then this factory can easily be configured with various options that accumulate over time without needing to make new constructor functions.

Equals method

Does an "Equals(uuid1,uuid2)" method actually exists? It's not so fast comparing uuid's by parsing two values in string and then comparing then by '=='.

API Changes

Please comment in this issue about any requested API changes.

Typos and why does New panic?

Typos

'from' is repeated twice in this comment:

https://godoc.org/github.com/google/uuid#NewRandom

A note about uniqueness derived from from the UUID Wikipedia entry:

NewRandom() returns an error, not a panic:

https://godoc.org/github.com/google/uuid#NewRandom

NewRandom returns a Random (Version 4) UUID or panics.

Why does New panic?

It is surprising New() panics when compared to the html/template package, for example, where functions that panic include the word Must:

var t = template.Must(template.New("name").Parse("html"))

https://godoc.org/github.com/google/uuid#New

New is creates a new random UUID or panics. New is equivalent to the expression

SQL value more efficient at bytes

The SQL Value() gives a string representation of UUID, if this is unindexed data this may make little difference in the performance of the data but where this is either an index or even the PK this not efficient storage. Here's one of many articles on it.

This could either have a breaking change and make this provide a []byte type. If there is some more dominant SQL DB being targeted which does not benefit from this, then we could minimally have a BytesValuer() function to return a Valuer which does do this.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.