slices.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. package main
  5. import (
  6. "io/ioutil"
  7. "regexp"
  8. )
  9. func AppendByte(slice []byte, data ...byte) []byte {
  10. m := len(slice)
  11. n := m + len(data)
  12. if n > cap(slice) { // if necessary, reallocate
  13. // allocate double what's needed, for future growth.
  14. newSlice := make([]byte, (n+1)*2)
  15. copy(newSlice, slice)
  16. slice = newSlice
  17. }
  18. slice = slice[0:n]
  19. copy(slice[m:n], data)
  20. return slice
  21. }
  22. // STOP OMIT
  23. // Filter returns a new slice holding only
  24. // the elements of s that satisfy fn.
  25. func Filter(s []int, fn func(int) bool) []int {
  26. var p []int // == nil
  27. for _, i := range s {
  28. if fn(i) {
  29. p = append(p, i)
  30. }
  31. }
  32. return p
  33. }
  34. // STOP OMIT
  35. var digitRegexp = regexp.MustCompile("[0-9]+")
  36. func FindDigits(filename string) []byte {
  37. b, _ := ioutil.ReadFile(filename)
  38. return digitRegexp.Find(b)
  39. }
  40. // STOP OMIT
  41. func CopyDigits(filename string) []byte {
  42. b, _ := ioutil.ReadFile(filename)
  43. b = digitRegexp.Find(b)
  44. c := make([]byte, len(b))
  45. copy(c, b)
  46. return c
  47. }
  48. // STOP OMIT
  49. func main() {
  50. // place holder; no need to run
  51. }