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	getRoot() int
51	getLen() int
52	stateAt(addr int, prealloc fstState) (fstState, error)
53}
54
55func loadDecoder(ver int, data []byte) (decoder, error) {
56	if cons, ok := decoders[ver]; ok {
57		return cons(data), nil
58	}
59	return nil, fmt.Errorf("no decoder for version %d registered", ver)
60}
61
62func registerDecoder(ver int, cons decoderConstructor) {
63	decoders[ver] = cons
64}
65
66func decodeHeader(header []byte) (ver int, typ int, err error) {
67	if len(header) < headerSize {
68		err = fmt.Errorf("invalid header < 16 bytes")
69		return
70	}
71	ver = int(binary.LittleEndian.Uint64(header[0:8]))
72	typ = int(binary.LittleEndian.Uint64(header[8:16]))
73	return
74}
75
76// fstState represents a state inside the FTS runtime
77// It is the main contract between the FST impl and the decoder
78// The FST impl should work only with this interface, while only the decoder
79// impl knows the physical representation.
80type fstState interface {
81	Address() int
82	Final() bool
83	FinalOutput() uint64
84	NumTransitions() int
85	TransitionFor(b byte) (int, int, uint64)
86	TransitionAt(i int) byte
87}
88