github.com/blend/go-sdk@v1.20220411.3/bufferutil/buffer_chunk.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package bufferutil
     9  
    10  import (
    11  	"encoding/json"
    12  	"time"
    13  )
    14  
    15  // BufferChunkHandler is a handler for output chunks.
    16  type BufferChunkHandler func(BufferChunk)
    17  
    18  // BufferChunk is a single write to a buffer with a timestamp.
    19  type BufferChunk struct {
    20  	Timestamp time.Time
    21  	Data      []byte
    22  }
    23  
    24  // Copy returns a copy of the chunk.
    25  func (bc BufferChunk) Copy() BufferChunk {
    26  	data := make([]byte, len(bc.Data))
    27  	copy(data, bc.Data)
    28  	return BufferChunk{
    29  		Timestamp: bc.Timestamp,
    30  		Data:      data,
    31  	}
    32  }
    33  
    34  // MarshalJSON implemnts json.Marshaler.
    35  func (bc BufferChunk) MarshalJSON() ([]byte, error) {
    36  	return json.Marshal(map[string]interface{}{
    37  		"_ts":  bc.Timestamp,
    38  		"data": string(bc.Data),
    39  	})
    40  }
    41  
    42  // UnmarshalJSON implements json.Unmarshaler.
    43  func (bc *BufferChunk) UnmarshalJSON(contents []byte) error {
    44  	raw := make(map[string]interface{})
    45  	if err := json.Unmarshal(contents, &raw); err != nil {
    46  		return err
    47  	}
    48  
    49  	if typed, ok := raw["_ts"].(string); ok {
    50  		parsed, err := time.Parse(time.RFC3339, typed)
    51  		if err != nil {
    52  			return err
    53  		}
    54  		bc.Timestamp = parsed
    55  	}
    56  	if typed, ok := raw["data"].(string); ok {
    57  		bc.Data = []byte(typed)
    58  	}
    59  	return nil
    60  }