|
| 1 | +// Licensed to Elasticsearch B.V. under one or more contributor |
| 2 | +// license agreements. See the NOTICE file distributed with |
| 3 | +// this work for additional information regarding copyright |
| 4 | +// ownership. Elasticsearch B.V. licenses this file to you under |
| 5 | +// the Apache License, Version 2.0 (the "License"); you may |
| 6 | +// not use this file except in compliance with the License. |
| 7 | +// You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +package bytesutil |
| 19 | + |
| 20 | +import ( |
| 21 | + "iter" |
| 22 | +) |
| 23 | + |
| 24 | +var asciiSpace = [256]bool{'\t': true, '\n': true, '\v': true, '\f': true, '\r': true, ' ': true} |
| 25 | + |
| 26 | +// Fields returns an iterator that yields the fields of byte array b split around each single |
| 27 | +// ASCII white space character (space, tab, newline, vertical tab, form feed, carriage return). |
| 28 | +// It can be used with range loops like this: |
| 29 | +// |
| 30 | +// for i, field := range stringutil.Fields(b) { |
| 31 | +// fmt.Printf("Field %d: %v\n", i, field) |
| 32 | +// } |
| 33 | +func Fields(b []byte) iter.Seq2[int, []byte] { |
| 34 | + return func(yield func(int, []byte) bool) { |
| 35 | + for i, bi := 0, 0; bi < len(b); i++ { |
| 36 | + fieldStart := bi |
| 37 | + // Find the end of the field |
| 38 | + for bi < len(b) && !asciiSpace[b[bi]] { |
| 39 | + bi++ |
| 40 | + } |
| 41 | + if !yield(i, b[fieldStart:bi]) { |
| 42 | + return |
| 43 | + } |
| 44 | + bi++ |
| 45 | + } |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +// Split returns an iterator that yields the fields of byte array b split around |
| 50 | +// the given character. |
| 51 | +// It can be used with range loops like this: |
| 52 | +// |
| 53 | +// for i, field := range stringutil.Split(b, ',') { |
| 54 | +// fmt.Printf("Field %d: %v\n", i, field) |
| 55 | +// } |
| 56 | +func Split(b []byte, sep byte) iter.Seq2[int, []byte] { |
| 57 | + return func(yield func(int, []byte) bool) { |
| 58 | + for i, bi := 0, 0; bi < len(b); i++ { |
| 59 | + fieldStart := bi |
| 60 | + // Find the end of the field |
| 61 | + for bi < len(b) && b[bi] != sep { |
| 62 | + bi++ |
| 63 | + } |
| 64 | + if !yield(i, b[fieldStart:bi]) { |
| 65 | + return |
| 66 | + } |
| 67 | + bi++ |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments