57 lines
		
	
	
	
		
			1.1 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
			
		
		
	
	
			57 lines
		
	
	
	
		
			1.1 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
| package models
 | |
| 
 | |
| import (
 | |
| 	"bytes"
 | |
| 	"errors"
 | |
| 	"fmt"
 | |
| 	"regexp"
 | |
| 
 | |
| 	"codeberg.org/danjones000/my-log/tools"
 | |
| )
 | |
| 
 | |
| type Meta struct {
 | |
| 	Key   string
 | |
| 	Value any
 | |
| }
 | |
| 
 | |
| func (m Meta) MarshalText() ([]byte, error) {
 | |
| 	if regexp.MustCompile(`\s`).MatchString(m.Key) {
 | |
| 		return []byte{}, fmt.Errorf("whitespace is not allowed in key: %s", m.Key)
 | |
| 	}
 | |
| 	buff := &bytes.Buffer{}
 | |
| 	buff.WriteRune('@')
 | |
| 	buff.WriteString(m.Key)
 | |
| 	buff.WriteRune(' ')
 | |
| 	n, err := tools.WriteValue(buff, m.Value)
 | |
| 	if n == 0 || err != nil {
 | |
| 		return []byte{}, err
 | |
| 	}
 | |
| 
 | |
| 	return buff.Bytes(), nil
 | |
| }
 | |
| 
 | |
| func (m *Meta) UnmarshalText(in []byte) error {
 | |
| 	if len(in) == 0 {
 | |
| 		return newParsingError(errors.New("Unable to Unmarshal empty string"))
 | |
| 	}
 | |
| 	re := regexp.MustCompile("(?s)^@([^ ]+) (.*)( @end)?$")
 | |
| 	match := re.FindSubmatch(in)
 | |
| 	if len(match) == 0 {
 | |
| 		return newParsingError(fmt.Errorf("Failed to match %s", in))
 | |
| 	}
 | |
| 	m.Key = string(match[1])
 | |
| 	return m.processMeta(match[2])
 | |
| }
 | |
| 
 | |
| func (m *Meta) processMeta(in []byte) error {
 | |
| 	if len(in) == 0 {
 | |
| 		return newParsingError(errors.New("No value found"))
 | |
| 	}
 | |
| 	v := tools.ParseBytes(in)
 | |
| 	if v == "" {
 | |
| 		return newParsingError(errors.New("No value found"))
 | |
| 	}
 | |
| 
 | |
| 	m.Value = v
 | |
| 	return nil
 | |
| }
 |