1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17package ipc // import "github.com/apache/arrow/go/v6/arrow/ipc"
18
19import (
20	"github.com/apache/arrow/go/v6/arrow"
21	"github.com/apache/arrow/go/v6/arrow/array"
22	"golang.org/x/xerrors"
23)
24
25type dictMap map[int64]array.Interface
26type dictTypeMap map[int64]arrow.Field
27
28type dictMemo struct {
29	dict2id map[array.Interface]int64
30	id2dict dictMap // map of dictionary ID to dictionary array
31}
32
33func newMemo() dictMemo {
34	return dictMemo{
35		dict2id: make(map[array.Interface]int64),
36		id2dict: make(dictMap),
37	}
38}
39
40func (memo *dictMemo) Len() int { return len(memo.id2dict) }
41
42func (memo *dictMemo) delete() {
43	for id, v := range memo.id2dict {
44		delete(memo.id2dict, id)
45		delete(memo.dict2id, v)
46		v.Release()
47	}
48}
49
50func (memo dictMemo) Dict(id int64) (array.Interface, bool) {
51	v, ok := memo.id2dict[id]
52	return v, ok
53}
54
55func (memo *dictMemo) ID(v array.Interface) int64 {
56	id, ok := memo.dict2id[v]
57	if ok {
58		return id
59	}
60
61	v.Retain()
62	id = int64(len(memo.dict2id))
63	memo.dict2id[v] = id
64	memo.id2dict[id] = v
65	return id
66}
67
68func (memo dictMemo) HasDict(v array.Interface) bool {
69	_, ok := memo.dict2id[v]
70	return ok
71}
72
73func (memo dictMemo) HasID(id int64) bool {
74	_, ok := memo.id2dict[id]
75	return ok
76}
77
78func (memo *dictMemo) Add(id int64, v array.Interface) {
79	if _, dup := memo.id2dict[id]; dup {
80		panic(xerrors.Errorf("arrow/ipc: duplicate id=%d", id))
81	}
82	v.Retain()
83	memo.id2dict[id] = v
84	memo.dict2id[v] = id
85}
86