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
17// Transducer represents the general contract of a byte-based finite transducer
18type Transducer interface {
19
20	// all transducers are also automatons
21	Automaton
22
23	// IsMatchWithValue returns true if and only if the state is a match
24	// additionally it returns a states final value (if any)
25	IsMatchWithVal(int) (bool, uint64)
26
27	// Accept returns the next state given the input to the specified state
28	// additionally it returns the value associated with the transition
29	AcceptWithVal(int, byte) (int, uint64)
30}
31
32// TransducerGet implements an generic Get() method which works
33// on any implementation of Transducer
34// The caller MUST check the boolean return value for a match.
35// Zero is a valid value regardless of match status,
36// and if it is NOT a match, the value collected so far is returned.
37func TransducerGet(t Transducer, k []byte) (bool, uint64) {
38	var total uint64
39	i := 0
40	curr := t.Start()
41	for t.CanMatch(curr) && i < len(k) {
42		var transVal uint64
43		curr, transVal = t.AcceptWithVal(curr, k[i])
44		if curr == noneAddr {
45			break
46		}
47		total += transVal
48		i++
49	}
50	if i != len(k) {
51		return false, total
52	}
53	match, finalVal := t.IsMatchWithVal(curr)
54	return match, total + finalVal
55}
56