@@ -22,7 +22,10 @@ SOFTWARE.
2222
2323package chomp
2424
25- import "strings"
25+ import (
26+ "fmt"
27+ "strings"
28+ )
2629
2730// Tag must match a series of characters at the beginning of the input text,
2831// in the exact order and case provided.
@@ -182,3 +185,47 @@ func Opt[T Result](c Combinator[T]) Combinator[T] {
182185 return rem , out , nil
183186 }
184187}
188+
189+ // S wraps the result of the inner combinator within a string slice.
190+ // Combinators of differing return types can be successfully chained
191+ // together while using this conversion combinator.
192+ //
193+ // chomp.S(chomp.Until(","))("Hello, World!")
194+ // // (", World!", []string{"Hello"}, nil)
195+ func S (c Combinator [string ]) Combinator [[]string ] {
196+ return func (s string ) (string , []string , error ) {
197+ rem , ext , err := c (s )
198+ if err != nil {
199+ return rem , nil , err
200+ }
201+
202+ return rem , []string {ext }, err
203+ }
204+ }
205+
206+ // I extracts and returns a single string from the result of the inner combinator.
207+ // Combinators of differing return types can be successfully chained together while
208+ // using this conversion combinator.
209+ //
210+ // chomp.I(chomp.SepPair(
211+ // chomp.Tag("Hello"),
212+ // chomp.Tag(", "),
213+ // chomp.Tag("World")), 1)("Hello, World!")
214+ // // ("!", "World", nil)
215+ func I (c Combinator [[]string ], i int ) Combinator [string ] {
216+ return func (s string ) (string , string , error ) {
217+ rem , ext , err := c (s )
218+ if err != nil {
219+ return rem , "" , err
220+ }
221+
222+ if i < 0 || i >= len (ext ) {
223+ return rem , "" , ParserError {
224+ Err : fmt .Errorf ("index %d is out of bounds within string slice of %d elements" , i , len (ext )),
225+ Type : "i" ,
226+ }
227+ }
228+
229+ return rem , ext [i ], nil
230+ }
231+ }
0 commit comments