git.lukeshu.com/go/lowmemjson@v0.3.9-0.20230723050957-72f6d13f6fb2/reencode_nl.go (about)

     1  // Copyright (C) 2022-2023  Luke Shumaker <lukeshu@lukeshu.com>
     2  //
     3  // SPDX-License-Identifier: GPL-2.0-or-later
     4  
     5  package lowmemjson
     6  
     7  import (
     8  	"git.lukeshu.com/go/lowmemjson/internal/jsonparse"
     9  )
    10  
    11  type reEncodeForceNL struct {
    12  	out reEncoderModule
    13  
    14  	// state
    15  	skipNL bool
    16  }
    17  
    18  var _ reEncoderModule = (*reEncodeForceNL)(nil)
    19  
    20  func (enc *reEncodeForceNL) PopWriteBarrier() {
    21  	enc.out.PopWriteBarrier()
    22  }
    23  
    24  func (enc *reEncodeForceNL) HandleRune(c rune, t jsonparse.RuneType, escape BackslashEscapeMode, stackSize int) error {
    25  	switch {
    26  	case t == jsonparse.RuneTypeEOF:
    27  		if err := enc.out.HandleRune('\n', jsonparse.RuneTypeSpace, 0, stackSize); err != nil {
    28  			return err
    29  		}
    30  		enc.skipNL = true
    31  		return enc.out.HandleRune(c, t, escape, stackSize)
    32  	case c == '\n' && t == jsonparse.RuneTypeSpace && enc.skipNL:
    33  		enc.skipNL = false
    34  		return nil
    35  	default:
    36  		enc.skipNL = false
    37  		return enc.out.HandleRune(c, t, escape, stackSize)
    38  	}
    39  }