github.com/zerosnake0/jzon@v0.0.9-0.20230801092939-1b135cb83f7f/iterator_array.go (about)

     1  package jzon
     2  
     3  // ReadArrayBegin starts to read an array
     4  //
     5  // var (
     6  //     more bool
     7  //     err error
     8  // )
     9  // for more, err = it.ReadArray();
    10  //     more;
    11  //     more, err = it.ReadArrayMore() {
    12  // }
    13  // if err != nil {
    14  //     // error handling
    15  // }
    16  func (it *Iterator) ReadArrayBegin() (ret bool, err error) {
    17  	c, err := it.nextToken()
    18  	if err != nil {
    19  		return false, err
    20  	}
    21  	if c != '[' {
    22  		return false, UnexpectedByteError{got: c, exp: '['}
    23  	}
    24  	it.head++
    25  	c, err = it.nextToken()
    26  	if err != nil {
    27  		return false, err
    28  	}
    29  	if c == ']' {
    30  		it.head++
    31  		return false, nil
    32  	}
    33  	return true, nil
    34  }
    35  
    36  // ReadArrayMore tells if there is more item to read in the array
    37  func (it *Iterator) ReadArrayMore() (ret bool, err error) {
    38  	c, err := it.nextToken()
    39  	if err != nil {
    40  		return false, err
    41  	}
    42  	switch c {
    43  	case ',':
    44  		it.head++
    45  		return true, nil
    46  	case ']':
    47  		it.head++
    48  		return false, nil
    49  	default:
    50  		return false, UnexpectedByteError{got: c, exp: ',', exp2: ']'}
    51  	}
    52  }
    53  
    54  // ReadArrayCB reads the array with a callback
    55  // The caller should make sure that the callback is correct
    56  func (it *Iterator) ReadArrayCB(cb func(*Iterator) error) error {
    57  	c, err := it.nextToken()
    58  	if err != nil {
    59  		return err
    60  	}
    61  	if c != '[' {
    62  		return UnexpectedByteError{got: c, exp: '['}
    63  	}
    64  	it.head++
    65  	c, err = it.nextToken()
    66  	if err != nil {
    67  		return err
    68  	}
    69  	if c == ']' {
    70  		it.head++
    71  		return nil
    72  	}
    73  	for {
    74  		if err := cb(it); err != nil {
    75  			return err
    76  		}
    77  		c, err = it.nextToken()
    78  		if err != nil {
    79  			return err
    80  		}
    81  		switch c {
    82  		case ',':
    83  			it.head++
    84  		case ']':
    85  			it.head++
    86  			return nil
    87  		default:
    88  			return UnexpectedByteError{got: c, exp: ',', exp2: ']'}
    89  		}
    90  	}
    91  }