Path: blob/main/vendor/golang.org/x/net/html/atom/atom.go
2893 views
// Copyright 2012 The Go Authors. All rights reserved.1// Use of this source code is governed by a BSD-style2// license that can be found in the LICENSE file.34// Package atom provides integer codes (also known as atoms) for a fixed set of5// frequently occurring HTML strings: tag names and attribute keys such as "p"6// and "id".7//8// Sharing an atom's name between all elements with the same tag can result in9// fewer string allocations when tokenizing and parsing HTML. Integer10// comparisons are also generally faster than string comparisons.11//12// The value of an atom's particular code is not guaranteed to stay the same13// between versions of this package. Neither is any ordering guaranteed:14// whether atom.H1 < atom.H2 may also change. The codes are not guaranteed to15// be dense. The only guarantees are that e.g. looking up "div" will yield16// atom.Div, calling atom.Div.String will return "div", and atom.Div != 0.17package atom // import "golang.org/x/net/html/atom"1819// Atom is an integer code for a string. The zero value maps to "".20type Atom uint322122// String returns the atom's name.23func (a Atom) String() string {24start := uint32(a >> 8)25n := uint32(a & 0xff)26if start+n > uint32(len(atomText)) {27return ""28}29return atomText[start : start+n]30}3132func (a Atom) string() string {33return atomText[a>>8 : a>>8+a&0xff]34}3536// fnv computes the FNV hash with an arbitrary starting value h.37func fnv(h uint32, s []byte) uint32 {38for i := range s {39h ^= uint32(s[i])40h *= 1677761941}42return h43}4445func match(s string, t []byte) bool {46for i, c := range t {47if s[i] != c {48return false49}50}51return true52}5354// Lookup returns the atom whose name is s. It returns zero if there is no55// such atom. The lookup is case sensitive.56func Lookup(s []byte) Atom {57if len(s) == 0 || len(s) > maxAtomLen {58return 059}60h := fnv(hash0, s)61if a := table[h&uint32(len(table)-1)]; int(a&0xff) == len(s) && match(a.string(), s) {62return a63}64if a := table[(h>>16)&uint32(len(table)-1)]; int(a&0xff) == len(s) && match(a.string(), s) {65return a66}67return 068}6970// String returns a string whose contents are equal to s. In that sense, it is71// equivalent to string(s) but may be more efficient.72func String(s []byte) string {73if a := Lookup(s); a != 0 {74return a.String()75}76return string(s)77}787980