NewWordCounter returns a new WordCounter stats object. The WordCounter object is thread-safe and counts the number of words recorded. If a WordCounter stats object with the same name already exists it is returned.
(name string)
| 378 | // The WordCounter object is thread-safe and counts the number of words recorded. |
| 379 | // If a WordCounter stats object with the same name already exists it is returned. |
| 380 | func NewWordCounter(name string) *WordCounter { |
| 381 | c := &WordCounter{ |
| 382 | count: atomic.NewInt64(0), |
| 383 | words: sync.Map{}, |
| 384 | } |
| 385 | existing := expvar.Get(statsPrefix + name) |
| 386 | if existing != nil { |
| 387 | if w, ok := existing.(*WordCounter); ok { |
| 388 | return w |
| 389 | } |
| 390 | panic(fmt.Sprintf("%v is set to a non-WordCounter value", name)) |
| 391 | } |
| 392 | expvar.Publish(statsPrefix+name, c) |
| 393 | return c |
| 394 | } |
| 395 | |
| 396 | func (w *WordCounter) Add(word string) { |
| 397 | if _, loaded := w.words.LoadOrStore(xxhash.Sum64String(word), struct{}{}); !loaded { |