scanner.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package ftp
  2. // A scanner for fields delimited by one or more whitespace characters
  3. type scanner struct {
  4. bytes []byte
  5. position int
  6. }
  7. // newScanner creates a new scanner
  8. func newScanner(str string) *scanner {
  9. return &scanner{
  10. bytes: []byte(str),
  11. }
  12. }
  13. // NextFields returns the next `count` fields
  14. func (s *scanner) NextFields(count int) []string {
  15. fields := make([]string, 0, count)
  16. for i := 0; i < count; i++ {
  17. if field := s.Next(); field != "" {
  18. fields = append(fields, field)
  19. } else {
  20. break
  21. }
  22. }
  23. return fields
  24. }
  25. // Next returns the next field
  26. func (s *scanner) Next() string {
  27. sLen := len(s.bytes)
  28. // skip trailing whitespace
  29. for s.position < sLen {
  30. if s.bytes[s.position] != ' ' {
  31. break
  32. }
  33. s.position++
  34. }
  35. start := s.position
  36. // skip non-whitespace
  37. for s.position < sLen {
  38. if s.bytes[s.position] == ' ' {
  39. s.position++
  40. return string(s.bytes[start : s.position-1])
  41. }
  42. s.position++
  43. }
  44. return string(s.bytes[start:s.position])
  45. }
  46. // Remaining returns the remaining string
  47. func (s *scanner) Remaining() string {
  48. return string(s.bytes[s.position:len(s.bytes)])
  49. }