github.com/jmigpin/editor@v1.6.0/util/iout/iorw/rwundo/undoredo.go (about)

     1  package rwundo
     2  
     3  import (
     4  	"github.com/jmigpin/editor/util/iout"
     5  	"github.com/jmigpin/editor/util/iout/iorw"
     6  )
     7  
     8  type UndoRedo struct {
     9  	Index int
    10  	D     []byte // deleted bytes of the original op
    11  	I     []byte // inserted bytes of the original op
    12  }
    13  
    14  func NewUndoRedoOverwrite(rw iorw.ReadWriterAt, i, n int, p []byte) (*UndoRedo, error) {
    15  	// copy delete
    16  	b0, err := rw.ReadFastAt(i, n)
    17  	if err != nil {
    18  		return nil, err
    19  	}
    20  	b1 := iout.CopyBytes(b0)
    21  	// copy insert
    22  	b2 := make([]byte, len(p))
    23  	copy(b2, p)
    24  
    25  	if err := rw.OverwriteAt(i, n, p); err != nil {
    26  		return nil, err
    27  	}
    28  	ur := &UndoRedo{Index: i, D: b1, I: b2}
    29  	return ur, nil
    30  }
    31  
    32  //----------
    33  
    34  func (ur *UndoRedo) Apply(redo bool, w iorw.WriterAt) error {
    35  	if redo {
    36  		return w.OverwriteAt(ur.Index, len(ur.D), ur.I)
    37  	} else {
    38  		return w.OverwriteAt(ur.Index, len(ur.I), ur.D)
    39  	}
    40  }
    41  
    42  func (ur *UndoRedo) IsInsertOnly() bool {
    43  	return len(ur.D) == 0 && len(ur.I) != 0
    44  }
    45  func (ur *UndoRedo) IsDeleteOnly() bool {
    46  	return len(ur.D) != 0 && len(ur.I) == 0
    47  }