1//  Copyright (c) 2017 Couchbase, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// 		http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package vellum
16
17import (
18	"encoding/binary"
19	"fmt"
20	"io"
21)
22
23const headerSize = 16
24
25type encoderConstructor func(w io.Writer) encoder
26type decoderConstructor func([]byte) decoder
27
28var encoders = map[int]encoderConstructor{}
29var decoders = map[int]decoderConstructor{}
30
31type encoder interface {
32	start() error
33	encodeState(s *builderNode, addr int) (int, error)
34	finish(count, rootAddr int) error
35	reset(w io.Writer)
36}
37
38func loadEncoder(ver int, w io.Writer) (encoder, error) {
39	if cons, ok := encoders[ver]; ok {
40		return cons(w), nil
41	}
42	return nil, fmt.Errorf("no encoder for version %d registered", ver)
43}
44
45func registerEncoder(ver int, cons encoderConstructor) {
46	encoders[ver] = cons
47}
48
49type decoder interface {
50	clear()
51	getRoot() int
52	getLen() int
53	reload(data []byte)
54	stateAt(addr int, prealloc fstState) (fstState, error)
55}
56
57func loadDecoder(ver int, data []byte) (decoder, error) {
58	if cons, ok := decoders[ver]; ok {
59		return cons(data), nil
60	}
61	return nil, fmt.Errorf("no decoder for version %d registered", ver)
62}
63
64func registerDecoder(ver int, cons decoderConstructor) {
65	decoders[ver] = cons
66}
67
68func decodeHeader(header []byte) (ver int, typ int, err error) {
69	if len(header) < headerSize {
70		err = fmt.Errorf("invalid header < 16 bytes")
71		return
72	}
73	ver = int(binary.LittleEndian.Uint64(header[0:8]))
74	typ = int(binary.LittleEndian.Uint64(header[8:16]))
75	return
76}
77
78// fstState represents a state inside the FTS runtime
79// It is the main contract between the FST impl and the decoder
80// The FST impl should work only with this interface, while only the decoder
81// impl knows the physical representation.
82type fstState interface {
83	Address() int
84	Final() bool
85	FinalOutput() uint64
86	NumTransitions() int
87	TransitionFor(b byte) (int, int, uint64)
88	TransitionAt(i int) byte
89}
90