tpls

Extendable, Fast Template Engine for Go
git clone git://git.lair.cx/tpls
Log | Files | Refs | README | LICENSE

bytestack.go (942B)


      1 package stacks
      2 
      3 import (
      4 	"sync"
      5 )
      6 
      7 type ByteStack struct {
      8 	sync.Mutex
      9 	buf   []byte
     10 	stack [][]byte
     11 }
     12 
     13 func NewByteStack(buf []byte) *ByteStack {
     14 	return &ByteStack{
     15 		buf: buf,
     16 	}
     17 }
     18 
     19 func (s *ByteStack) Put(item []byte) {
     20 	s.Lock()
     21 	defer s.Unlock()
     22 	s.buf = append(s.buf, item...)
     23 	s.stack = append(s.stack, s.buf[len(s.buf)-len(item):])
     24 }
     25 
     26 // Pop removes last item from stack and return it.
     27 //
     28 // The buffer is valid until the next Put is called.
     29 // To ensure data, call Lock directly and use UnsafePop.
     30 func (s *ByteStack) Pop() (item []byte, ok bool) {
     31 	s.Lock()
     32 	defer s.Unlock()
     33 	return s.UnsafePop()
     34 }
     35 
     36 func (s *ByteStack) UnsafePop() (item []byte, ok bool) {
     37 	var i = len(s.stack) - 1
     38 	if i < 0 {
     39 		return nil, false
     40 	}
     41 	item, s.stack = s.stack[i], s.stack[:i]
     42 	s.buf = s.buf[:len(s.buf)-len(item)]
     43 	return item, true
     44 }
     45 
     46 func (s *ByteStack) Len() int {
     47 	return len(s.stack)
     48 }
     49 
     50 func (s *ByteStack) Buffer() []byte {
     51 	return s.buf
     52 }