Last active
August 29, 2015 14:18
-
-
Save richardlehane/9539e1c564b2acad142c to your computer and use it in GitHub Desktop.
GuidFromName
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| testName := "Bagaaqy23kudbhchAaq5u2chNd" | |
| testGuid := "{20001801-5DE6-11D1-8E38-00C04FB9386D}" | |
| func GuidFromName(n string) (Guid, error) { | |
| n = strings.ToLower(n) | |
| buf, err := charConvert([]byte(n)) | |
| if err != nil { | |
| return Guid{}, err | |
| } | |
| return makeGuid(buf, binary.LittleEndian), nil | |
| } | |
| func charConvert(in []byte) ([]byte, error) { | |
| if len(in) != 26 { | |
| return nil, errors.New("invalid GUID: expecting 26 characters") | |
| } | |
| out := make([]byte, 16) | |
| idx, right, left := 0, 0, 3 | |
| var b byte | |
| for _, v := range in { | |
| this, ok := characterMapping[v] | |
| if !ok { | |
| return nil, errors.New("invalid Guid: invalid character") | |
| } | |
| if right > 0 || left == 0 { | |
| b = b | this >> right | |
| out[idx] = b | |
| b = 0 | |
| idx++ | |
| } | |
| if left > 0 { | |
| b = b | this << left | |
| } | |
| rem := 5 - l | |
| if rem <= 0 { | |
| rem = 8 + rem | |
| r = 0 | |
| } else { | |
| r = rem | |
| } | |
| l = 8 - rem | |
| } | |
| return out, nil | |
| } | |
| const ( | |
| charA byte = iota | |
| charB | |
| charC | |
| charD | |
| charE | |
| charF | |
| charG | |
| charH | |
| charI | |
| charJ | |
| charK | |
| charL | |
| charM | |
| charN | |
| charO | |
| charP | |
| charQ | |
| charR | |
| charS | |
| charT | |
| charU | |
| charV | |
| charW | |
| charX | |
| charY | |
| charZ | |
| char0 | |
| char1 | |
| char2 | |
| char3 | |
| char4 | |
| char5 | |
| ) | |
| var characterMapping = map[byte]byte{ | |
| 'a': charA, | |
| 'b': charB, | |
| 'c': charC, | |
| 'd': charD, | |
| 'e': charE, | |
| 'f': charF, | |
| 'g': charG, | |
| 'h': charH, | |
| 'i': charI, | |
| 'j': charJ, | |
| 'k': charK, | |
| 'l': charL, | |
| 'm': charM, | |
| 'n': charN, | |
| 'o': charO, | |
| 'p': charP, | |
| 'q': charQ, | |
| 'r': charR, | |
| 's': charS, | |
| 't': charT, | |
| 'u': charU, | |
| 'v': charV, | |
| 'w': charW, | |
| 'x': charX, | |
| 'y': charY, | |
| 'z': charZ, | |
| '0': char0, | |
| '1': char1, | |
| '2': char2, | |
| '3': char3, | |
| '4': char4, | |
| '5': char5, | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment