1// Copyright 2017 The Wuffs Authors. 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// https://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// ---------------- 16 17// Package base38 converts a 4-byte string, each byte in [ 0-9?a-z], to a base 18// 38 number. 19package base38 20 21const ( 22 // Max is the inclusive upper bound for the value returned by Encode. Its 23 // value equals (38*38*38*38 - 1). 24 Max = 2085135 25 // MaxBits is the number of bits required to represent Max. It satisfies 26 // (1<<(MaxBits-1) <= Max) && (Max < 1<<MaxBits). 27 MaxBits = 21 28) 29 30// Encode encodes a 4-byte string as a uint32 in the range [0, Max]. 31// 32// Each byte must be ' ', be in the range '0'-'9', be '?' or be in the range 33// 'a'-'z'. 34// 35// The string " " is mapped to zero. 36func Encode(s string) (u uint32, ok bool) { 37 if len(s) == 4 { 38 for i := 0; i < 4; i++ { 39 x := uint32(table[s[i]]) 40 if x == 0 { 41 break 42 } 43 u += x - 1 44 if i == 3 { 45 return u, true 46 } 47 u *= 38 48 } 49 } 50 return 0, false 51} 52 53var table = [256]uint8{ 54 ' ': 1, 55 '0': 2, 56 '1': 3, 57 '2': 4, 58 '3': 5, 59 '4': 6, 60 '5': 7, 61 '6': 8, 62 '7': 9, 63 '8': 10, 64 '9': 11, 65 '?': 12, 66 'a': 13, 67 'b': 14, 68 'c': 15, 69 'd': 16, 70 'e': 17, 71 'f': 18, 72 'g': 19, 73 'h': 20, 74 'i': 21, 75 'j': 22, 76 'k': 23, 77 'l': 24, 78 'm': 25, 79 'n': 26, 80 'o': 27, 81 'p': 28, 82 'q': 29, 83 'r': 30, 84 's': 31, 85 't': 32, 86 'u': 33, 87 'v': 34, 88 'w': 35, 89 'x': 36, 90 'y': 37, 91 'z': 38, 92} 93