gen.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. // Copyright 2012 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // +build ignore
  5. package main
  6. // This program generates table.go and table_test.go based on the authoritative
  7. // public suffix list at https://publicsuffix.org/list/effective_tld_names.dat
  8. //
  9. // The version is derived from
  10. // https://api.github.com/repos/publicsuffix/list/commits?path=public_suffix_list.dat
  11. // and a human-readable form is at
  12. // https://github.com/publicsuffix/list/commits/master/public_suffix_list.dat
  13. //
  14. // To fetch a particular git revision, such as 5c70ccd250, pass
  15. // -url "https://raw.githubusercontent.com/publicsuffix/list/5c70ccd250/public_suffix_list.dat"
  16. // and -version "an explicit version string".
  17. import (
  18. "bufio"
  19. "bytes"
  20. "flag"
  21. "fmt"
  22. "go/format"
  23. "io"
  24. "io/ioutil"
  25. "net/http"
  26. "os"
  27. "regexp"
  28. "sort"
  29. "strings"
  30. "golang.org/x/net/idna"
  31. )
  32. const (
  33. // These sum of these four values must be no greater than 32.
  34. nodesBitsChildren = 10
  35. nodesBitsICANN = 1
  36. nodesBitsTextOffset = 15
  37. nodesBitsTextLength = 6
  38. // These sum of these four values must be no greater than 32.
  39. childrenBitsWildcard = 1
  40. childrenBitsNodeType = 2
  41. childrenBitsHi = 14
  42. childrenBitsLo = 14
  43. )
  44. var (
  45. maxChildren int
  46. maxTextOffset int
  47. maxTextLength int
  48. maxHi uint32
  49. maxLo uint32
  50. )
  51. func max(a, b int) int {
  52. if a < b {
  53. return b
  54. }
  55. return a
  56. }
  57. func u32max(a, b uint32) uint32 {
  58. if a < b {
  59. return b
  60. }
  61. return a
  62. }
  63. const (
  64. nodeTypeNormal = 0
  65. nodeTypeException = 1
  66. nodeTypeParentOnly = 2
  67. numNodeType = 3
  68. )
  69. func nodeTypeStr(n int) string {
  70. switch n {
  71. case nodeTypeNormal:
  72. return "+"
  73. case nodeTypeException:
  74. return "!"
  75. case nodeTypeParentOnly:
  76. return "o"
  77. }
  78. panic("unreachable")
  79. }
  80. const (
  81. defaultURL = "https://publicsuffix.org/list/effective_tld_names.dat"
  82. gitCommitURL = "https://api.github.com/repos/publicsuffix/list/commits?path=public_suffix_list.dat"
  83. )
  84. var (
  85. labelEncoding = map[string]uint32{}
  86. labelsList = []string{}
  87. labelsMap = map[string]bool{}
  88. rules = []string{}
  89. numICANNRules = 0
  90. // validSuffixRE is used to check that the entries in the public suffix
  91. // list are in canonical form (after Punycode encoding). Specifically,
  92. // capital letters are not allowed.
  93. validSuffixRE = regexp.MustCompile(`^[a-z0-9_\!\*\-\.]+$`)
  94. shaRE = regexp.MustCompile(`"sha":"([^"]+)"`)
  95. dateRE = regexp.MustCompile(`"committer":{[^{]+"date":"([^"]+)"`)
  96. comments = flag.Bool("comments", false, "generate table.go comments, for debugging")
  97. subset = flag.Bool("subset", false, "generate only a subset of the full table, for debugging")
  98. url = flag.String("url", defaultURL, "URL of the publicsuffix.org list. If empty, stdin is read instead")
  99. v = flag.Bool("v", false, "verbose output (to stderr)")
  100. version = flag.String("version", "", "the effective_tld_names.dat version")
  101. )
  102. func main() {
  103. if err := main1(); err != nil {
  104. fmt.Fprintln(os.Stderr, err)
  105. os.Exit(1)
  106. }
  107. }
  108. func main1() error {
  109. flag.Parse()
  110. if nodesBitsTextLength+nodesBitsTextOffset+nodesBitsICANN+nodesBitsChildren > 32 {
  111. return fmt.Errorf("not enough bits to encode the nodes table")
  112. }
  113. if childrenBitsLo+childrenBitsHi+childrenBitsNodeType+childrenBitsWildcard > 32 {
  114. return fmt.Errorf("not enough bits to encode the children table")
  115. }
  116. if *version == "" {
  117. if *url != defaultURL {
  118. return fmt.Errorf("-version was not specified, and the -url is not the default one")
  119. }
  120. sha, date, err := gitCommit()
  121. if err != nil {
  122. return err
  123. }
  124. *version = fmt.Sprintf("publicsuffix.org's public_suffix_list.dat, git revision %s (%s)", sha, date)
  125. }
  126. var r io.Reader = os.Stdin
  127. if *url != "" {
  128. res, err := http.Get(*url)
  129. if err != nil {
  130. return err
  131. }
  132. if res.StatusCode != http.StatusOK {
  133. return fmt.Errorf("bad GET status for %s: %s", *url, res.Status)
  134. }
  135. r = res.Body
  136. defer res.Body.Close()
  137. }
  138. var root node
  139. icann := false
  140. br := bufio.NewReader(r)
  141. for {
  142. s, err := br.ReadString('\n')
  143. if err != nil {
  144. if err == io.EOF {
  145. break
  146. }
  147. return err
  148. }
  149. s = strings.TrimSpace(s)
  150. if strings.Contains(s, "BEGIN ICANN DOMAINS") {
  151. if len(rules) != 0 {
  152. return fmt.Errorf(`expected no rules before "BEGIN ICANN DOMAINS"`)
  153. }
  154. icann = true
  155. continue
  156. }
  157. if strings.Contains(s, "END ICANN DOMAINS") {
  158. icann, numICANNRules = false, len(rules)
  159. continue
  160. }
  161. if s == "" || strings.HasPrefix(s, "//") {
  162. continue
  163. }
  164. s, err = idna.ToASCII(s)
  165. if err != nil {
  166. return err
  167. }
  168. if !validSuffixRE.MatchString(s) {
  169. return fmt.Errorf("bad publicsuffix.org list data: %q", s)
  170. }
  171. if *subset {
  172. switch {
  173. case s == "ac.jp" || strings.HasSuffix(s, ".ac.jp"):
  174. case s == "ak.us" || strings.HasSuffix(s, ".ak.us"):
  175. case s == "ao" || strings.HasSuffix(s, ".ao"):
  176. case s == "ar" || strings.HasSuffix(s, ".ar"):
  177. case s == "arpa" || strings.HasSuffix(s, ".arpa"):
  178. case s == "cy" || strings.HasSuffix(s, ".cy"):
  179. case s == "dyndns.org" || strings.HasSuffix(s, ".dyndns.org"):
  180. case s == "jp":
  181. case s == "kobe.jp" || strings.HasSuffix(s, ".kobe.jp"):
  182. case s == "kyoto.jp" || strings.HasSuffix(s, ".kyoto.jp"):
  183. case s == "om" || strings.HasSuffix(s, ".om"):
  184. case s == "uk" || strings.HasSuffix(s, ".uk"):
  185. case s == "uk.com" || strings.HasSuffix(s, ".uk.com"):
  186. case s == "tw" || strings.HasSuffix(s, ".tw"):
  187. case s == "zw" || strings.HasSuffix(s, ".zw"):
  188. case s == "xn--p1ai" || strings.HasSuffix(s, ".xn--p1ai"):
  189. // xn--p1ai is Russian-Cyrillic "рф".
  190. default:
  191. continue
  192. }
  193. }
  194. rules = append(rules, s)
  195. nt, wildcard := nodeTypeNormal, false
  196. switch {
  197. case strings.HasPrefix(s, "*."):
  198. s, nt = s[2:], nodeTypeParentOnly
  199. wildcard = true
  200. case strings.HasPrefix(s, "!"):
  201. s, nt = s[1:], nodeTypeException
  202. }
  203. labels := strings.Split(s, ".")
  204. for n, i := &root, len(labels)-1; i >= 0; i-- {
  205. label := labels[i]
  206. n = n.child(label)
  207. if i == 0 {
  208. if nt != nodeTypeParentOnly && n.nodeType == nodeTypeParentOnly {
  209. n.nodeType = nt
  210. }
  211. n.icann = n.icann && icann
  212. n.wildcard = n.wildcard || wildcard
  213. }
  214. labelsMap[label] = true
  215. }
  216. }
  217. labelsList = make([]string, 0, len(labelsMap))
  218. for label := range labelsMap {
  219. labelsList = append(labelsList, label)
  220. }
  221. sort.Strings(labelsList)
  222. if err := generate(printReal, &root, "table.go"); err != nil {
  223. return err
  224. }
  225. if err := generate(printTest, &root, "table_test.go"); err != nil {
  226. return err
  227. }
  228. return nil
  229. }
  230. func generate(p func(io.Writer, *node) error, root *node, filename string) error {
  231. buf := new(bytes.Buffer)
  232. if err := p(buf, root); err != nil {
  233. return err
  234. }
  235. b, err := format.Source(buf.Bytes())
  236. if err != nil {
  237. return err
  238. }
  239. return ioutil.WriteFile(filename, b, 0644)
  240. }
  241. func gitCommit() (sha, date string, retErr error) {
  242. res, err := http.Get(gitCommitURL)
  243. if err != nil {
  244. return "", "", err
  245. }
  246. if res.StatusCode != http.StatusOK {
  247. return "", "", fmt.Errorf("bad GET status for %s: %s", gitCommitURL, res.Status)
  248. }
  249. defer res.Body.Close()
  250. b, err := ioutil.ReadAll(res.Body)
  251. if err != nil {
  252. return "", "", err
  253. }
  254. if m := shaRE.FindSubmatch(b); m != nil {
  255. sha = string(m[1])
  256. }
  257. if m := dateRE.FindSubmatch(b); m != nil {
  258. date = string(m[1])
  259. }
  260. if sha == "" || date == "" {
  261. retErr = fmt.Errorf("could not find commit SHA and date in %s", gitCommitURL)
  262. }
  263. return sha, date, retErr
  264. }
  265. func printTest(w io.Writer, n *node) error {
  266. fmt.Fprintf(w, "// generated by go run gen.go; DO NOT EDIT\n\n")
  267. fmt.Fprintf(w, "package publicsuffix\n\nconst numICANNRules = %d\n\nvar rules = [...]string{\n", numICANNRules)
  268. for _, rule := range rules {
  269. fmt.Fprintf(w, "%q,\n", rule)
  270. }
  271. fmt.Fprintf(w, "}\n\nvar nodeLabels = [...]string{\n")
  272. if err := n.walk(w, printNodeLabel); err != nil {
  273. return err
  274. }
  275. fmt.Fprintf(w, "}\n")
  276. return nil
  277. }
  278. func printReal(w io.Writer, n *node) error {
  279. const header = `// generated by go run gen.go; DO NOT EDIT
  280. package publicsuffix
  281. const version = %q
  282. const (
  283. nodesBitsChildren = %d
  284. nodesBitsICANN = %d
  285. nodesBitsTextOffset = %d
  286. nodesBitsTextLength = %d
  287. childrenBitsWildcard = %d
  288. childrenBitsNodeType = %d
  289. childrenBitsHi = %d
  290. childrenBitsLo = %d
  291. )
  292. const (
  293. nodeTypeNormal = %d
  294. nodeTypeException = %d
  295. nodeTypeParentOnly = %d
  296. )
  297. // numTLD is the number of top level domains.
  298. const numTLD = %d
  299. `
  300. fmt.Fprintf(w, header, *version,
  301. nodesBitsChildren, nodesBitsICANN, nodesBitsTextOffset, nodesBitsTextLength,
  302. childrenBitsWildcard, childrenBitsNodeType, childrenBitsHi, childrenBitsLo,
  303. nodeTypeNormal, nodeTypeException, nodeTypeParentOnly, len(n.children))
  304. text := combineText(labelsList)
  305. if text == "" {
  306. return fmt.Errorf("internal error: makeText returned no text")
  307. }
  308. for _, label := range labelsList {
  309. offset, length := strings.Index(text, label), len(label)
  310. if offset < 0 {
  311. return fmt.Errorf("internal error: could not find %q in text %q", label, text)
  312. }
  313. maxTextOffset, maxTextLength = max(maxTextOffset, offset), max(maxTextLength, length)
  314. if offset >= 1<<nodesBitsTextOffset {
  315. return fmt.Errorf("text offset %d is too large, or nodeBitsTextOffset is too small", offset)
  316. }
  317. if length >= 1<<nodesBitsTextLength {
  318. return fmt.Errorf("text length %d is too large, or nodeBitsTextLength is too small", length)
  319. }
  320. labelEncoding[label] = uint32(offset)<<nodesBitsTextLength | uint32(length)
  321. }
  322. fmt.Fprintf(w, "// Text is the combined text of all labels.\nconst text = ")
  323. for len(text) > 0 {
  324. n, plus := len(text), ""
  325. if n > 64 {
  326. n, plus = 64, " +"
  327. }
  328. fmt.Fprintf(w, "%q%s\n", text[:n], plus)
  329. text = text[n:]
  330. }
  331. if err := n.walk(w, assignIndexes); err != nil {
  332. return err
  333. }
  334. fmt.Fprintf(w, `
  335. // nodes is the list of nodes. Each node is represented as a uint32, which
  336. // encodes the node's children, wildcard bit and node type (as an index into
  337. // the children array), ICANN bit and text.
  338. //
  339. // If the table was generated with the -comments flag, there is a //-comment
  340. // after each node's data. In it is the nodes-array indexes of the children,
  341. // formatted as (n0x1234-n0x1256), with * denoting the wildcard bit. The
  342. // nodeType is printed as + for normal, ! for exception, and o for parent-only
  343. // nodes that have children but don't match a domain label in their own right.
  344. // An I denotes an ICANN domain.
  345. //
  346. // The layout within the uint32, from MSB to LSB, is:
  347. // [%2d bits] unused
  348. // [%2d bits] children index
  349. // [%2d bits] ICANN bit
  350. // [%2d bits] text index
  351. // [%2d bits] text length
  352. var nodes = [...]uint32{
  353. `,
  354. 32-nodesBitsChildren-nodesBitsICANN-nodesBitsTextOffset-nodesBitsTextLength,
  355. nodesBitsChildren, nodesBitsICANN, nodesBitsTextOffset, nodesBitsTextLength)
  356. if err := n.walk(w, printNode); err != nil {
  357. return err
  358. }
  359. fmt.Fprintf(w, `}
  360. // children is the list of nodes' children, the parent's wildcard bit and the
  361. // parent's node type. If a node has no children then their children index
  362. // will be in the range [0, 6), depending on the wildcard bit and node type.
  363. //
  364. // The layout within the uint32, from MSB to LSB, is:
  365. // [%2d bits] unused
  366. // [%2d bits] wildcard bit
  367. // [%2d bits] node type
  368. // [%2d bits] high nodes index (exclusive) of children
  369. // [%2d bits] low nodes index (inclusive) of children
  370. var children=[...]uint32{
  371. `,
  372. 32-childrenBitsWildcard-childrenBitsNodeType-childrenBitsHi-childrenBitsLo,
  373. childrenBitsWildcard, childrenBitsNodeType, childrenBitsHi, childrenBitsLo)
  374. for i, c := range childrenEncoding {
  375. s := "---------------"
  376. lo := c & (1<<childrenBitsLo - 1)
  377. hi := (c >> childrenBitsLo) & (1<<childrenBitsHi - 1)
  378. if lo != hi {
  379. s = fmt.Sprintf("n0x%04x-n0x%04x", lo, hi)
  380. }
  381. nodeType := int(c>>(childrenBitsLo+childrenBitsHi)) & (1<<childrenBitsNodeType - 1)
  382. wildcard := c>>(childrenBitsLo+childrenBitsHi+childrenBitsNodeType) != 0
  383. if *comments {
  384. fmt.Fprintf(w, "0x%08x, // c0x%04x (%s)%s %s\n",
  385. c, i, s, wildcardStr(wildcard), nodeTypeStr(nodeType))
  386. } else {
  387. fmt.Fprintf(w, "0x%x,\n", c)
  388. }
  389. }
  390. fmt.Fprintf(w, "}\n\n")
  391. fmt.Fprintf(w, "// max children %d (capacity %d)\n", maxChildren, 1<<nodesBitsChildren-1)
  392. fmt.Fprintf(w, "// max text offset %d (capacity %d)\n", maxTextOffset, 1<<nodesBitsTextOffset-1)
  393. fmt.Fprintf(w, "// max text length %d (capacity %d)\n", maxTextLength, 1<<nodesBitsTextLength-1)
  394. fmt.Fprintf(w, "// max hi %d (capacity %d)\n", maxHi, 1<<childrenBitsHi-1)
  395. fmt.Fprintf(w, "// max lo %d (capacity %d)\n", maxLo, 1<<childrenBitsLo-1)
  396. return nil
  397. }
  398. type node struct {
  399. label string
  400. nodeType int
  401. icann bool
  402. wildcard bool
  403. // nodesIndex and childrenIndex are the index of this node in the nodes
  404. // and the index of its children offset/length in the children arrays.
  405. nodesIndex, childrenIndex int
  406. // firstChild is the index of this node's first child, or zero if this
  407. // node has no children.
  408. firstChild int
  409. // children are the node's children, in strictly increasing node label order.
  410. children []*node
  411. }
  412. func (n *node) walk(w io.Writer, f func(w1 io.Writer, n1 *node) error) error {
  413. if err := f(w, n); err != nil {
  414. return err
  415. }
  416. for _, c := range n.children {
  417. if err := c.walk(w, f); err != nil {
  418. return err
  419. }
  420. }
  421. return nil
  422. }
  423. // child returns the child of n with the given label. The child is created if
  424. // it did not exist beforehand.
  425. func (n *node) child(label string) *node {
  426. for _, c := range n.children {
  427. if c.label == label {
  428. return c
  429. }
  430. }
  431. c := &node{
  432. label: label,
  433. nodeType: nodeTypeParentOnly,
  434. icann: true,
  435. }
  436. n.children = append(n.children, c)
  437. sort.Sort(byLabel(n.children))
  438. return c
  439. }
  440. type byLabel []*node
  441. func (b byLabel) Len() int { return len(b) }
  442. func (b byLabel) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
  443. func (b byLabel) Less(i, j int) bool { return b[i].label < b[j].label }
  444. var nextNodesIndex int
  445. // childrenEncoding are the encoded entries in the generated children array.
  446. // All these pre-defined entries have no children.
  447. var childrenEncoding = []uint32{
  448. 0 << (childrenBitsLo + childrenBitsHi), // Without wildcard bit, nodeTypeNormal.
  449. 1 << (childrenBitsLo + childrenBitsHi), // Without wildcard bit, nodeTypeException.
  450. 2 << (childrenBitsLo + childrenBitsHi), // Without wildcard bit, nodeTypeParentOnly.
  451. 4 << (childrenBitsLo + childrenBitsHi), // With wildcard bit, nodeTypeNormal.
  452. 5 << (childrenBitsLo + childrenBitsHi), // With wildcard bit, nodeTypeException.
  453. 6 << (childrenBitsLo + childrenBitsHi), // With wildcard bit, nodeTypeParentOnly.
  454. }
  455. var firstCallToAssignIndexes = true
  456. func assignIndexes(w io.Writer, n *node) error {
  457. if len(n.children) != 0 {
  458. // Assign nodesIndex.
  459. n.firstChild = nextNodesIndex
  460. for _, c := range n.children {
  461. c.nodesIndex = nextNodesIndex
  462. nextNodesIndex++
  463. }
  464. // The root node's children is implicit.
  465. if firstCallToAssignIndexes {
  466. firstCallToAssignIndexes = false
  467. return nil
  468. }
  469. // Assign childrenIndex.
  470. maxChildren = max(maxChildren, len(childrenEncoding))
  471. if len(childrenEncoding) >= 1<<nodesBitsChildren {
  472. return fmt.Errorf("children table size %d is too large, or nodeBitsChildren is too small", len(childrenEncoding))
  473. }
  474. n.childrenIndex = len(childrenEncoding)
  475. lo := uint32(n.firstChild)
  476. hi := lo + uint32(len(n.children))
  477. maxLo, maxHi = u32max(maxLo, lo), u32max(maxHi, hi)
  478. if lo >= 1<<childrenBitsLo {
  479. return fmt.Errorf("children lo %d is too large, or childrenBitsLo is too small", lo)
  480. }
  481. if hi >= 1<<childrenBitsHi {
  482. return fmt.Errorf("children hi %d is too large, or childrenBitsHi is too small", hi)
  483. }
  484. enc := hi<<childrenBitsLo | lo
  485. enc |= uint32(n.nodeType) << (childrenBitsLo + childrenBitsHi)
  486. if n.wildcard {
  487. enc |= 1 << (childrenBitsLo + childrenBitsHi + childrenBitsNodeType)
  488. }
  489. childrenEncoding = append(childrenEncoding, enc)
  490. } else {
  491. n.childrenIndex = n.nodeType
  492. if n.wildcard {
  493. n.childrenIndex += numNodeType
  494. }
  495. }
  496. return nil
  497. }
  498. func printNode(w io.Writer, n *node) error {
  499. for _, c := range n.children {
  500. s := "---------------"
  501. if len(c.children) != 0 {
  502. s = fmt.Sprintf("n0x%04x-n0x%04x", c.firstChild, c.firstChild+len(c.children))
  503. }
  504. encoding := labelEncoding[c.label]
  505. if c.icann {
  506. encoding |= 1 << (nodesBitsTextLength + nodesBitsTextOffset)
  507. }
  508. encoding |= uint32(c.childrenIndex) << (nodesBitsTextLength + nodesBitsTextOffset + nodesBitsICANN)
  509. if *comments {
  510. fmt.Fprintf(w, "0x%08x, // n0x%04x c0x%04x (%s)%s %s %s %s\n",
  511. encoding, c.nodesIndex, c.childrenIndex, s, wildcardStr(c.wildcard),
  512. nodeTypeStr(c.nodeType), icannStr(c.icann), c.label,
  513. )
  514. } else {
  515. fmt.Fprintf(w, "0x%x,\n", encoding)
  516. }
  517. }
  518. return nil
  519. }
  520. func printNodeLabel(w io.Writer, n *node) error {
  521. for _, c := range n.children {
  522. fmt.Fprintf(w, "%q,\n", c.label)
  523. }
  524. return nil
  525. }
  526. func icannStr(icann bool) string {
  527. if icann {
  528. return "I"
  529. }
  530. return " "
  531. }
  532. func wildcardStr(wildcard bool) string {
  533. if wildcard {
  534. return "*"
  535. }
  536. return " "
  537. }
  538. // combineText combines all the strings in labelsList to form one giant string.
  539. // Overlapping strings will be merged: "arpa" and "parliament" could yield
  540. // "arparliament".
  541. func combineText(labelsList []string) string {
  542. beforeLength := 0
  543. for _, s := range labelsList {
  544. beforeLength += len(s)
  545. }
  546. text := crush(removeSubstrings(labelsList))
  547. if *v {
  548. fmt.Fprintf(os.Stderr, "crushed %d bytes to become %d bytes\n", beforeLength, len(text))
  549. }
  550. return text
  551. }
  552. type byLength []string
  553. func (s byLength) Len() int { return len(s) }
  554. func (s byLength) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  555. func (s byLength) Less(i, j int) bool { return len(s[i]) < len(s[j]) }
  556. // removeSubstrings returns a copy of its input with any strings removed
  557. // that are substrings of other provided strings.
  558. func removeSubstrings(input []string) []string {
  559. // Make a copy of input.
  560. ss := append(make([]string, 0, len(input)), input...)
  561. sort.Sort(byLength(ss))
  562. for i, shortString := range ss {
  563. // For each string, only consider strings higher than it in sort order, i.e.
  564. // of equal length or greater.
  565. for _, longString := range ss[i+1:] {
  566. if strings.Contains(longString, shortString) {
  567. ss[i] = ""
  568. break
  569. }
  570. }
  571. }
  572. // Remove the empty strings.
  573. sort.Strings(ss)
  574. for len(ss) > 0 && ss[0] == "" {
  575. ss = ss[1:]
  576. }
  577. return ss
  578. }
  579. // crush combines a list of strings, taking advantage of overlaps. It returns a
  580. // single string that contains each input string as a substring.
  581. func crush(ss []string) string {
  582. maxLabelLen := 0
  583. for _, s := range ss {
  584. if maxLabelLen < len(s) {
  585. maxLabelLen = len(s)
  586. }
  587. }
  588. for prefixLen := maxLabelLen; prefixLen > 0; prefixLen-- {
  589. prefixes := makePrefixMap(ss, prefixLen)
  590. for i, s := range ss {
  591. if len(s) <= prefixLen {
  592. continue
  593. }
  594. mergeLabel(ss, i, prefixLen, prefixes)
  595. }
  596. }
  597. return strings.Join(ss, "")
  598. }
  599. // mergeLabel merges the label at ss[i] with the first available matching label
  600. // in prefixMap, where the last "prefixLen" characters in ss[i] match the first
  601. // "prefixLen" characters in the matching label.
  602. // It will merge ss[i] repeatedly until no more matches are available.
  603. // All matching labels merged into ss[i] are replaced by "".
  604. func mergeLabel(ss []string, i, prefixLen int, prefixes prefixMap) {
  605. s := ss[i]
  606. suffix := s[len(s)-prefixLen:]
  607. for _, j := range prefixes[suffix] {
  608. // Empty strings mean "already used." Also avoid merging with self.
  609. if ss[j] == "" || i == j {
  610. continue
  611. }
  612. if *v {
  613. fmt.Fprintf(os.Stderr, "%d-length overlap at (%4d,%4d): %q and %q share %q\n",
  614. prefixLen, i, j, ss[i], ss[j], suffix)
  615. }
  616. ss[i] += ss[j][prefixLen:]
  617. ss[j] = ""
  618. // ss[i] has a new suffix, so merge again if possible.
  619. // Note: we only have to merge again at the same prefix length. Shorter
  620. // prefix lengths will be handled in the next iteration of crush's for loop.
  621. // Can there be matches for longer prefix lengths, introduced by the merge?
  622. // I believe that any such matches would by necessity have been eliminated
  623. // during substring removal or merged at a higher prefix length. For
  624. // instance, in crush("abc", "cde", "bcdef"), combining "abc" and "cde"
  625. // would yield "abcde", which could be merged with "bcdef." However, in
  626. // practice "cde" would already have been elimintated by removeSubstrings.
  627. mergeLabel(ss, i, prefixLen, prefixes)
  628. return
  629. }
  630. }
  631. // prefixMap maps from a prefix to a list of strings containing that prefix. The
  632. // list of strings is represented as indexes into a slice of strings stored
  633. // elsewhere.
  634. type prefixMap map[string][]int
  635. // makePrefixMap constructs a prefixMap from a slice of strings.
  636. func makePrefixMap(ss []string, prefixLen int) prefixMap {
  637. prefixes := make(prefixMap)
  638. for i, s := range ss {
  639. // We use < rather than <= because if a label matches on a prefix equal to
  640. // its full length, that's actually a substring match handled by
  641. // removeSubstrings.
  642. if prefixLen < len(s) {
  643. prefix := s[:prefixLen]
  644. prefixes[prefix] = append(prefixes[prefix], i)
  645. }
  646. }
  647. return prefixes
  648. }