intern.go 790 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // Package intern interns strings.
  2. // Interning is best effort only.
  3. // Interned strings may be removed automatically
  4. // at any time without notification.
  5. // All functions may be called concurrently
  6. // with themselves and each other.
  7. package intern
  8. import "sync"
  9. var (
  10. pool sync.Pool = sync.Pool{
  11. New: func() interface{} {
  12. return make(map[string]string)
  13. },
  14. }
  15. )
  16. // String returns s, interned.
  17. func String(s string) string {
  18. m := pool.Get().(map[string]string)
  19. c, ok := m[s]
  20. if ok {
  21. pool.Put(m)
  22. return c
  23. }
  24. m[s] = s
  25. pool.Put(m)
  26. return s
  27. }
  28. // Bytes returns b converted to a string, interned.
  29. func Bytes(b []byte) string {
  30. m := pool.Get().(map[string]string)
  31. c, ok := m[string(b)]
  32. if ok {
  33. pool.Put(m)
  34. return c
  35. }
  36. s := string(b)
  37. m[s] = s
  38. pool.Put(m)
  39. return s
  40. }