map.go 13.8 KB
Newer Older
1 2 3 4 5 6 7 8
package impls

import (
	"fmt"

	ipld "github.com/ipld/go-ipld-prime/_rsrch/nodesolution"
)

9 10 11 12 13 14 15
var (
	_ ipld.Node          = &plainMap{}
	_ ipld.NodeStyle     = Style__Map{}
	_ ipld.NodeBuilder   = &plainMap__Builder{}
	_ ipld.NodeAssembler = &plainMap__Assembler{}
)

16 17 18
// plainMap is a concrete type that provides a map-kind ipld.Node.
// It can contain any kind of value.
// plainMap is also embedded in the 'any' struct and usable from there.
Eric Myhre's avatar
Eric Myhre committed
19
type plainMap struct {
20
	m map[string]ipld.Node // string key -- even if a runtime schema wrapper is using us for storage, we must have a comparable type here, and string is all we know.
21
	t []plainMap__Entry    // table for fast iteration, order keeping, and yielding pointers to enable alloc/conv amortization.
22 23
}

Eric Myhre's avatar
Eric Myhre committed
24 25
type plainMap__Entry struct {
	k plainString // address of this used when we return keys as nodes, such as in iterators.  Need in one place to amortize shifts to heap when ptr'ing for iface.
26 27
	v ipld.Node   // identical to map values.  keeping them here simplifies iteration.  (in codegen'd maps, this position is also part of amortization, but in this implementation, that's less useful.)
	// note on alternate implementations: 'v' could also use the 'any' type, and thus amortize value allocations.  the memory size trade would be large however, so we don't, here.
Eric Myhre's avatar
Eric Myhre committed
28 29
}

30 31
// -- Node interface methods -->

Eric Myhre's avatar
Eric Myhre committed
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
func (plainMap) ReprKind() ipld.ReprKind {
	return ipld.ReprKind_Map
}
func (n *plainMap) LookupString(key string) (ipld.Node, error) {
	v, exists := n.m[key]
	if !exists {
		return nil, ipld.ErrNotExists{ipld.PathSegmentOfString(key)}
	}
	return v, nil
}
func (n *plainMap) Lookup(key ipld.Node) (ipld.Node, error) {
	ks, err := key.AsString()
	if err != nil {
		return nil, err
	}
	return n.LookupString(ks)
}
func (plainMap) LookupIndex(idx int) (ipld.Node, error) {
	return nil, ipld.ErrWrongKind{TypeName: "map", MethodName: "LookupIndex", AppropriateKind: ipld.ReprKindSet_JustList, ActualKind: ipld.ReprKind_Map}
}
func (n *plainMap) LookupSegment(seg ipld.PathSegment) (ipld.Node, error) {
	return n.LookupString(seg.String())
}
func (n *plainMap) MapIterator() ipld.MapIterator {
	return &plainMap_MapIterator{n, 0}
}
func (plainMap) ListIterator() ipld.ListIterator {
	panic("no")
}
func (n *plainMap) Length() int {
	return len(n.t)
}
func (plainMap) IsUndefined() bool {
	return false
}
func (plainMap) IsNull() bool {
	return false
}
func (plainMap) AsBool() (bool, error) {
	return false, ipld.ErrWrongKind{TypeName: "map", MethodName: "AsBool", AppropriateKind: ipld.ReprKindSet_JustBool, ActualKind: ipld.ReprKind_Map}
}
func (plainMap) AsInt() (int, error) {
	return 0, ipld.ErrWrongKind{TypeName: "map", MethodName: "AsInt", AppropriateKind: ipld.ReprKindSet_JustFloat, ActualKind: ipld.ReprKind_Map}
}
func (plainMap) AsFloat() (float64, error) {
	return 0, ipld.ErrWrongKind{TypeName: "map", MethodName: "AsFloat", AppropriateKind: ipld.ReprKindSet_JustFloat, ActualKind: ipld.ReprKind_Map}
}
func (plainMap) AsString() (string, error) {
	return "", ipld.ErrWrongKind{TypeName: "map", MethodName: "AsString", AppropriateKind: ipld.ReprKindSet_JustString, ActualKind: ipld.ReprKind_Map}
}
func (plainMap) AsBytes() ([]byte, error) {
	return nil, ipld.ErrWrongKind{TypeName: "map", MethodName: "AsBytes", AppropriateKind: ipld.ReprKindSet_JustBytes, ActualKind: ipld.ReprKind_Map}
}
func (plainMap) AsLink() (ipld.Link, error) {
	return nil, ipld.ErrWrongKind{TypeName: "map", MethodName: "AsLink", AppropriateKind: ipld.ReprKindSet_JustLink, ActualKind: ipld.ReprKind_Map}
}
func (plainMap) Style() ipld.NodeStyle {
89
	return Style__Map{}
Eric Myhre's avatar
Eric Myhre committed
90 91 92 93 94
}

type plainMap_MapIterator struct {
	n   *plainMap
	idx int
95 96
}

Eric Myhre's avatar
Eric Myhre committed
97 98 99 100 101 102 103 104 105 106 107 108 109
func (itr *plainMap_MapIterator) Next() (k ipld.Node, v ipld.Node, _ error) {
	if itr.Done() {
		return nil, nil, ipld.ErrIteratorOverread{}
	}
	k = &itr.n.t[itr.idx].k
	v = itr.n.t[itr.idx].v
	itr.idx++
	return
}
func (itr *plainMap_MapIterator) Done() bool {
	return itr.idx >= len(itr.n.t)
}

110 111
// -- NodeStyle -->

Eric Myhre's avatar
Eric Myhre committed
112 113 114 115 116 117
type Style__Map struct{}

func (Style__Map) NewBuilder() ipld.NodeBuilder {
	return &plainMap__Builder{plainMap__Assembler{w: &plainMap{}}}
}

118
// -- NodeBuilder -->
119

Eric Myhre's avatar
Eric Myhre committed
120 121 122 123 124
type plainMap__Builder struct {
	plainMap__Assembler
}

func (nb *plainMap__Builder) Build() (ipld.Node, error) {
125 126
	if nb.state != maState_finished {
		panic("invalid state: assembler must be 'finished' before Build can be called!")
127
	}
Eric Myhre's avatar
Eric Myhre committed
128 129 130 131 132 133 134
	return nb.w, nil
}
func (nb *plainMap__Builder) Reset() {
	*nb = plainMap__Builder{}
	nb.w = &plainMap{}
}

135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
// -- NodeAssembler -->

type plainMap__Assembler struct {
	w *plainMap

	ka plainMap__KeyAssembler
	va plainMap__ValueAssembler

	state maState
}
type plainMap__KeyAssembler struct {
	ma *plainMap__Assembler
}
type plainMap__ValueAssembler struct {
	ma *plainMap__Assembler
}

// maState is an enum of the state machine for a map assembler.
// (this might be something to export reusably, but it's also very much an impl detail that need not be seen, so, dubious.)
type maState uint8

const (
157 158
	maState_initial     maState = iota // also the 'expect key or finish' state
	maState_midKey                     // waiting for a 'finished' state in the KeyAssembler.
159
	maState_expectValue                // 'AssembleValue' is the only valid next step
160 161
	maState_midValue                   // waiting for a 'finished' state in the ValueAssembler.
	maState_finished                   // 'w' will also be nil, but this is a politer statement
162 163
)

Eric Myhre's avatar
Eric Myhre committed
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
func (na *plainMap__Assembler) BeginMap(sizeHint int) (ipld.MapNodeAssembler, error) {
	// Allocate storage space.
	na.w.t = make([]plainMap__Entry, 0, sizeHint)
	na.w.m = make(map[string]ipld.Node, sizeHint)
	// That's it; return self as the MapNodeAssembler.  We already have all the right methods on this structure.
	return na, nil
}
func (plainMap__Assembler) BeginList(sizeHint int) (ipld.ListNodeAssembler, error) { panic("no") }
func (plainMap__Assembler) AssignNull() error                                      { panic("no") }
func (plainMap__Assembler) AssignBool(bool) error                                  { panic("no") }
func (plainMap__Assembler) AssignInt(int) error                                    { panic("no") }
func (plainMap__Assembler) AssignFloat(float64) error                              { panic("no") }
func (plainMap__Assembler) AssignString(v string) error                            { panic("no") }
func (plainMap__Assembler) AssignBytes([]byte) error                               { panic("no") }
func (na *plainMap__Assembler) Assign(v ipld.Node) error {
	// todo: apply a generic 'copy' function.
	// todo: probably can also shortcut to copying na.t and na.m if it's our same concrete type?
	//  (can't quite just `na.w = v`, because we don't have 'freeze' features, and we don't wanna open door to mutation of 'v'.)
182
	//   (wait... actually, probably we can?  'Assign' is a "finish" method.  we can&should invalidate the wip pointer here.)
Eric Myhre's avatar
Eric Myhre committed
183 184 185
	panic("later")
}
func (plainMap__Assembler) Style() ipld.NodeStyle { panic("later") }
186

187 188 189 190
// -- MapNodeAssembler -->

// AssembleDirectly is part of conforming to MapAssembler, which we do on
// plainMap__Assembler so that BeginMap can just return a retyped pointer rather than new object.
Eric Myhre's avatar
Eric Myhre committed
191
func (ma *plainMap__Assembler) AssembleDirectly(k string) (ipld.NodeAssembler, error) {
192 193
	// Sanity check, then update, assembler state.
	if ma.state != maState_initial {
194 195
		panic("misuse")
	}
196 197
	ma.state = maState_midValue
	// Check for dup keys; error if so.
198 199 200 201
	_, exists := ma.w.m[k]
	if exists {
		return nil, ipld.ErrRepeatedMapKey{String(k)}
	}
Eric Myhre's avatar
Eric Myhre committed
202
	ma.w.t = append(ma.w.t, plainMap__Entry{k: plainString(k)})
203 204
	// Make value assembler valid by giving it pointer back to whole 'ma'; yield it.
	ma.va.ma = ma
205
	return &ma.va, nil
206 207
}

208 209
// AssembleKey is part of conforming to MapAssembler, which we do on
// plainMap__Assembler so that BeginMap can just return a retyped pointer rather than new object.
Eric Myhre's avatar
Eric Myhre committed
210
func (ma *plainMap__Assembler) AssembleKey() ipld.NodeAssembler {
211 212
	// Sanity check, then update, assembler state.
	if ma.state != maState_initial {
Eric Myhre's avatar
Eric Myhre committed
213 214
		panic("misuse")
	}
215 216
	ma.state = maState_midKey
	// Extend entry table.
Eric Myhre's avatar
Eric Myhre committed
217
	ma.w.t = append(ma.w.t, plainMap__Entry{})
218 219
	// Make key assembler valid by giving it pointer back to whole 'ma'; yield it.
	ma.ka.ma = ma
Eric Myhre's avatar
Eric Myhre committed
220
	return &ma.ka
221
}
222 223 224

// AssembleValue is part of conforming to MapAssembler, which we do on
// plainMap__Assembler so that BeginMap can just return a retyped pointer rather than new object.
Eric Myhre's avatar
Eric Myhre committed
225
func (ma *plainMap__Assembler) AssembleValue() ipld.NodeAssembler {
226 227
	// Sanity check, then update, assembler state.
	if ma.state != maState_expectValue {
Eric Myhre's avatar
Eric Myhre committed
228 229
		panic("misuse")
	}
230
	ma.state = maState_midValue
231 232
	// Make value assembler valid by giving it pointer back to whole 'ma'; yield it.
	ma.va.ma = ma
Eric Myhre's avatar
Eric Myhre committed
233
	return &ma.va
234
}
235

236
// Finish is part of conforming to MapAssembler, which we do on
237
// plainMap__Assembler so that BeginMap can just return a retyped pointer rather than new object.
238
func (ma *plainMap__Assembler) Finish() error {
239 240
	// Sanity check, then update, assembler state.
	if ma.state != maState_initial {
241 242
		panic("misuse")
	}
243
	ma.state = maState_finished
244
	// validators could run and report errors promptly, if this type had any.
Eric Myhre's avatar
Eric Myhre committed
245 246 247 248 249
	return nil
}
func (plainMap__Assembler) KeyStyle() ipld.NodeStyle   { panic("later") }
func (plainMap__Assembler) ValueStyle() ipld.NodeStyle { panic("later") }

250 251
// -- MapNodeAssembler.KeyAssembler -->

Eric Myhre's avatar
Eric Myhre committed
252 253 254 255 256 257 258
func (plainMap__KeyAssembler) BeginMap(sizeHint int) (ipld.MapNodeAssembler, error)   { panic("no") }
func (plainMap__KeyAssembler) BeginList(sizeHint int) (ipld.ListNodeAssembler, error) { panic("no") }
func (plainMap__KeyAssembler) AssignNull() error                                      { panic("no") }
func (plainMap__KeyAssembler) AssignBool(bool) error                                  { panic("no") }
func (plainMap__KeyAssembler) AssignInt(int) error                                    { panic("no") }
func (plainMap__KeyAssembler) AssignFloat(float64) error                              { panic("no") }
func (mka *plainMap__KeyAssembler) AssignString(v string) error {
259
	// Check for dup keys; error if so.
Eric Myhre's avatar
Eric Myhre committed
260
	_, exists := mka.ma.w.m[v]
261
	if exists {
262
		return ipld.ErrRepeatedMapKey{plainString(v)}
263
	}
264 265 266 267
	// Assign the key into the end of the entry table;
	//  we'll be doing map insertions after we get the value in hand.
	//  (There's no need to delegate to another assembler for the key type,
	//   because we're just at Data Model level here, which only regards plain strings.)
Eric Myhre's avatar
Eric Myhre committed
268
	mka.ma.w.t[len(mka.ma.w.t)-1].k = plainString(v)
269 270
	// Update parent assembler state: clear to proceed.
	mka.ma.state = maState_expectValue
271
	mka.ma = nil // invalidate self to prevent further incorrect use.
272 273
	return nil
}
Eric Myhre's avatar
Eric Myhre committed
274 275
func (plainMap__KeyAssembler) AssignBytes([]byte) error { panic("no") }
func (mka *plainMap__KeyAssembler) Assign(v ipld.Node) error {
276 277 278 279 280 281
	vs, err := v.AsString()
	if err != nil {
		return fmt.Errorf("cannot assign non-string node into map key assembler") // FIXME:errors: this doesn't quite fit in ErrWrongKind cleanly; new error type?
	}
	return mka.AssignString(vs)
}
Eric Myhre's avatar
Eric Myhre committed
282
func (plainMap__KeyAssembler) Style() ipld.NodeStyle { panic("later") } // probably should give the style of plainString, which could say "only stores string kind" (though we haven't made such a feature part of the interface yet).
283

284 285
// -- MapNodeAssembler.ValueAssembler -->

Eric Myhre's avatar
Eric Myhre committed
286
func (mva *plainMap__ValueAssembler) BeginMap(sizeHint int) (ipld.MapNodeAssembler, error) {
287
	ma := plainMap__ValueAssemblerMap{}
288
	ma.ca.w = &plainMap{}
289
	ma.p = mva.ma
290
	_, err := ma.ca.BeginMap(sizeHint)
291
	return &ma, err
292
}
Eric Myhre's avatar
Eric Myhre committed
293 294
func (mva *plainMap__ValueAssembler) BeginList(sizeHint int) (ipld.ListNodeAssembler, error) {
	panic("todo") // now please
295
}
Eric Myhre's avatar
Eric Myhre committed
296 297 298 299
func (mva *plainMap__ValueAssembler) AssignNull() error     { panic("todo") }
func (mva *plainMap__ValueAssembler) AssignBool(bool) error { panic("todo") }
func (mva *plainMap__ValueAssembler) AssignInt(v int) error {
	vb := plainInt(v)
300
	return mva.Assign(&vb)
301
}
302 303 304
func (mva *plainMap__ValueAssembler) AssignFloat(float64) error { panic("todo") }
func (mva *plainMap__ValueAssembler) AssignString(v string) error {
	vb := plainString(v)
305
	return mva.Assign(&vb)
306 307
}
func (mva *plainMap__ValueAssembler) AssignBytes([]byte) error { panic("todo") }
Eric Myhre's avatar
Eric Myhre committed
308 309 310 311
func (mva *plainMap__ValueAssembler) Assign(v ipld.Node) error {
	l := len(mva.ma.w.t) - 1
	mva.ma.w.t[l].v = v
	mva.ma.w.m[string(mva.ma.w.t[l].k)] = v
312
	mva.ma.state = maState_initial
313
	mva.ma = nil // invalidate self to prevent further incorrect use.
314 315
	return nil
}
Eric Myhre's avatar
Eric Myhre committed
316
func (plainMap__ValueAssembler) Style() ipld.NodeStyle { panic("later") }
317 318

type plainMap__ValueAssemblerMap struct {
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
	ca plainMap__Assembler
	p  *plainMap__Assembler // pointer back to parent, for final insert and state bump
}

// just embedding plainMap__Assembler works, but generates a lot more and less-inlined assembly than you'd think.
// explicitly writing the handful of methods we need to have delegated here removes many autogen'd methods from the assembly,
// and (TODO TEST THIS) also creates much more inlined results for each of these functions.

// oh lol.  no actually, on that last part: these methods were already the ones you could just jump for.
// why?  i dunno.
// this format does do actual inlining instead of a JMP at the end, but...
//   i guess that's probably same-speed and is assembly-longer?
//    i think the asm size overall is small since such fewer methods, but it's odd we lose the JMP style.
//    but whatever, i'm not really optimizing for assembly size.  uh, much.

func (ma *plainMap__ValueAssemblerMap) AssembleDirectly(k string) (ipld.NodeAssembler, error) {
	return ma.ca.AssembleDirectly(k)
}
func (ma *plainMap__ValueAssemblerMap) AssembleKey() ipld.NodeAssembler {
	return ma.ca.AssembleKey()
}
func (ma *plainMap__ValueAssemblerMap) AssembleValue() ipld.NodeAssembler {
	return ma.ca.AssembleValue()
342
}
343 344
func (plainMap__ValueAssemblerMap) KeyStyle() ipld.NodeStyle   { panic("later") }
func (plainMap__ValueAssemblerMap) ValueStyle() ipld.NodeStyle { panic("later") }
345

346 347
func (ma *plainMap__ValueAssemblerMap) Finish() error {
	if err := ma.ca.Finish(); err != nil {
348 349
		return err
	}
350
	return ma.p.va.Assign(ma.ca.w)
351
}