github.com/unigraph-dev/dgraph@v1.1.1-0.20200923154953-8b52b426f765/systest/_customtok/factor/main.go (about) 1 /* 2 * Copyright 2017-2018 Dgraph Labs, Inc. and Contributors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package main 18 19 import ( 20 "encoding/binary" 21 22 "github.com/pkg/errors" 23 ) 24 25 func Tokenizer() interface{} { return FactorTokenizer{} } 26 27 type FactorTokenizer struct{} 28 29 func (FactorTokenizer) Name() string { return "factor" } 30 func (FactorTokenizer) Type() string { return "int" } 31 func (FactorTokenizer) Identifier() byte { return 0xfe } 32 33 func (FactorTokenizer) Tokens(value interface{}) ([]string, error) { 34 x := value.(int64) 35 if x <= 1 { 36 return nil, errors.Errorf("Cannot factor int <= 1: %d", x) 37 } 38 var toks []string 39 for p := int64(2); x > 1; p++ { 40 if x%p == 0 { 41 toks = append(toks, encodeInt(p)) 42 for x%p == 0 { 43 x /= p 44 } 45 } 46 } 47 return toks, nil 48 49 } 50 51 func encodeInt(x int64) string { 52 var buf [binary.MaxVarintLen64]byte 53 n := binary.PutVarint(buf[:], x) 54 return string(buf[:n]) 55 }