-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgroup_write.go
More file actions
656 lines (582 loc) · 20.1 KB
/
group_write.go
File metadata and controls
656 lines (582 loc) · 20.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
package hdf5
import (
"fmt"
"sort"
"strings"
"github.com/scigolib/hdf5/internal/core"
"github.com/scigolib/hdf5/internal/structures"
"github.com/scigolib/hdf5/internal/writer"
)
// GroupWriter represents an HDF5 group opened for writing.
// Groups organize datasets and other groups in a hierarchical structure.
//
// This type enables writing attributes to groups, similar to datasets.
// It provides a clean, object-oriented API consistent with DatasetWriter.
//
// Example:
//
// fw, _ := hdf5.CreateForWrite("data.h5", hdf5.CreateTruncate)
// defer fw.Close()
//
// // Create group
// group, _ := fw.CreateGroup("/mygroup")
//
// // Write attributes to group
// group.WriteAttribute("description", "My data group")
// group.WriteAttribute("version", int32(1))
//
// Note: This is a write-only handle. For reading group contents, use
// the file-level Walk() or Group() methods after reopening the file.
type GroupWriter struct {
// path is the full path of this group (e.g., "/mygroup" or "/data/experiments")
path string
// headerAddr is the address of the group's object header in the HDF5 file.
// This is used for writing attributes and linking to this group.
headerAddr uint64
// file is a reference to the parent FileWriter.
// This is needed for attribute operations and accessing file-level structures.
file *FileWriter
}
// WriteAttribute writes an attribute to this group.
//
// Storage strategy (automatic):
// - 0-7 attributes: Compact storage (object header messages)
// - 8+ attributes: Dense storage (Fractal Heap + B-tree v2)
//
// Supported value types:
// - Scalars: int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64
// - Arrays: []int32, []float64, etc. (1D arrays only)
// - Strings: string (fixed-length, converted to byte array)
//
// Parameters:
// - name: Attribute name (ASCII, no null bytes)
// - value: Attribute value (Go scalar, slice, or string)
//
// Returns:
// - error: If attribute cannot be written
//
// Example:
//
// group, _ := fw.CreateGroup("/mygroup")
// group.WriteAttribute("MATLAB_class", "double")
// group.WriteAttribute("MATLAB_complex", uint8(1))
// group.WriteAttribute("description", "Temperature measurements")
//
// Limitations:
// - No variable-length strings
// - No compound types
// - Attributes cannot be modified after creation (write-once)
// - No attribute deletion
func (g *GroupWriter) WriteAttribute(name string, value interface{}) error {
// Delegate to existing attribute writing infrastructure
// This reuses the same code path as DatasetWriter.WriteAttribute
return writeAttribute(g.file, g.headerAddr, name, value)
}
// Path returns the full path of this group.
//
// This can be used to display the group's location in the file hierarchy
// or for debugging purposes.
//
// Returns:
// - string: The group's path (e.g., "/mygroup" or "/data/experiments")
//
// Example:
//
// group, _ := fw.CreateGroup("/mygroup")
// fmt.Println(group.Path()) // Output: /mygroup
func (g *GroupWriter) Path() string {
return g.path
}
// validateGroupPath validates group path is not empty, starts with '/', and is not root.
func validateGroupPath(path string) error {
if path == "" {
return fmt.Errorf("group path cannot be empty")
}
if path[0] != '/' {
return fmt.Errorf("group path must start with '/' (got %q)", path)
}
if path == "/" {
return fmt.Errorf("root group already exists")
}
return nil
}
// createGroupStructures creates and writes the local heap, symbol table node, and B-tree for a group.
// Returns (heapAddr, stNodeAddr, btreeAddr, error).
func (fw *FileWriter) createGroupStructures() (uint64, uint64, uint64, error) {
offsetSize := int(fw.file.sb.OffsetSize)
// Create local heap
heap := structures.NewLocalHeap(256)
heapAddr, err := fw.writer.Allocate(heap.Size())
if err != nil {
return 0, 0, 0, fmt.Errorf("failed to allocate heap: %w", err)
}
// Create symbol table node
stNode := structures.NewSymbolTableNode(32)
entrySize := 2*offsetSize + 4 + 4 + 16
stNodeSize := uint64(8 + 32*entrySize)
stNodeAddr, err := fw.writer.Allocate(stNodeSize)
if err != nil {
return 0, 0, 0, fmt.Errorf("failed to allocate symbol table node: %w", err)
}
if err := stNode.WriteAt(fw.writer, stNodeAddr, uint8(offsetSize), 32, fw.file.sb.Endianness); err != nil { //nolint:gosec // Safe: offsetSize is 8
return 0, 0, 0, fmt.Errorf("failed to write symbol table node: %w", err)
}
// Create B-tree
btree := structures.NewBTreeNodeV1(0, 16)
if err := btree.AddKey(0, stNodeAddr); err != nil {
return 0, 0, 0, fmt.Errorf("failed to add B-tree key: %w", err)
}
btreeSize := uint64(24 + (2*16+1)*offsetSize + 2*16*offsetSize)
btreeAddr, err := fw.writer.Allocate(btreeSize)
if err != nil {
return 0, 0, 0, fmt.Errorf("failed to allocate B-tree: %w", err)
}
if err := btree.WriteAt(fw.writer, btreeAddr, uint8(offsetSize), 16, fw.file.sb.Endianness); err != nil { //nolint:gosec // Safe: offsetSize is 8
return 0, 0, 0, fmt.Errorf("failed to write B-tree: %w", err)
}
// Write heap
if err := heap.WriteTo(fw.writer, heapAddr); err != nil {
return 0, 0, 0, fmt.Errorf("failed to write local heap: %w", err)
}
return heapAddr, stNodeAddr, btreeAddr, nil
}
// CreateGroup creates a new empty group in the HDF5 file.
// Groups organize datasets and other groups in a hierarchical structure.
//
// This method creates an empty group using symbol table format (old HDF5 format).
// For groups with many links, consider using CreateDenseGroup() or CreateGroupWithLinks().
//
// Parameters:
// - path: Group path (must start with "/", e.g., "/data" or "/data/experiments")
//
// Returns:
// - *GroupWriter: Handle for writing attributes to the group
// - error: If creation fails
//
// Example:
//
// fw, _ := hdf5.CreateForWrite("data.h5", hdf5.CreateTruncate)
// defer fw.Close()
//
// // Create root-level group
// group, _ := fw.CreateGroup("/data")
// group.WriteAttribute("description", "My data group")
//
// // Create nested group
// nested, _ := fw.CreateGroup("/data/experiments")
// nested.WriteAttribute("MATLAB_class", "double")
//
// Limitations for MVP (v0.11.0-beta):
// - Only symbol table structure (no indexed groups)
// - No link creation time tracking
// - Maximum 32 entries per group (symbol table node capacity)
// - Parent group must exist (create parents first)
func (fw *FileWriter) CreateGroup(path string) (*GroupWriter, error) {
// Validate path
if err := validateGroupPath(path); err != nil {
return nil, err
}
// Parse path into parent and name
parent, name := parsePath(path)
// Validate parent exists (if not root)
if parent != "" && parent != "/" {
if _, exists := fw.groups[parent]; !exists {
return nil, fmt.Errorf("parent group %q does not exist (create it first)", parent)
}
}
// Create group structures (heap, symbol table, B-tree)
heapAddr, stNodeAddr, btreeAddr, err := fw.createGroupStructures()
if err != nil {
return nil, err
}
// Store group metadata for nested dataset linking
fw.groups[path] = &GroupMetadata{
heapAddr: heapAddr,
stNodeAddr: stNodeAddr,
btreeAddr: btreeAddr,
}
// Create object header for the group
// Message 1: Symbol Table Message (type 0x11)
stMsg := core.EncodeSymbolTableMessage(btreeAddr, heapAddr, int(fw.file.sb.OffsetSize), int(fw.file.sb.LengthSize))
ohw := &core.ObjectHeaderWriter{
Version: 2,
Flags: 0,
Messages: []core.MessageWriter{
{Type: core.MsgSymbolTable, Data: stMsg},
},
}
// Calculate object header size using the writer's own method
headerSize := ohw.Size()
headerAddr, err := fw.writer.Allocate(headerSize)
if err != nil {
return nil, fmt.Errorf("failed to allocate object header: %w", err)
}
// Write object header
writtenSize, err := ohw.WriteTo(fw.writer, headerAddr)
if err != nil {
return nil, fmt.Errorf("failed to write object header: %w", err)
}
if writtenSize != headerSize {
return nil, fmt.Errorf("header size mismatch: expected %d, wrote %d", headerSize, writtenSize)
}
// Link to parent group
if err := fw.linkToParent(parent, name, headerAddr); err != nil {
return nil, fmt.Errorf("failed to link to parent: %w", err)
}
// Return GroupWriter handle
return &GroupWriter{
path: path,
headerAddr: headerAddr,
file: fw,
}, nil
}
// parsePath splits a path into parent directory and name.
// Examples:
// - "/group1" → ("", "group1")
// - "/data/experiments" → ("/data", "experiments")
// - "/" → ("", "")
func parsePath(path string) (parent, name string) {
if path == "/" {
return "", ""
}
// Remove trailing slash if present
path = strings.TrimSuffix(path, "/")
// Find last slash
lastSlash := strings.LastIndex(path, "/")
if lastSlash == 0 {
// Root-level path like "/group1"
return "", path[1:] // Return ("", "group1")
}
// Nested path like "/data/experiments"
return path[:lastSlash], path[lastSlash+1:]
}
// linkToParent links a child object to its parent group.
// Links the child by adding an entry to the parent's symbol table.
//
// Parameters:
// - parentPath: Path to parent group ("" or "/" for root)
// - childName: Name of the child object
// - childAddr: Address of the child's object header
//
// Returns:
// - error: If linking fails
//
//nolint:gocognit,gocyclo,cyclop // Complex but necessary: sorted insertion + string-based B-tree key update
func (fw *FileWriter) linkToParent(parentPath, childName string, childAddr uint64) error {
// Get parent group metadata
var heapAddr, stNodeAddr, btreeAddr uint64
if parentPath == "" || parentPath == "/" {
// Root group - use root metadata
heapAddr = fw.rootHeapAddr
stNodeAddr = fw.rootStNodeAddr
btreeAddr = fw.rootBTreeAddr
} else {
// Non-root group - look up metadata
meta, exists := fw.groups[parentPath]
if !exists {
return fmt.Errorf("parent group %q not found (create it first)", parentPath)
}
heapAddr = meta.heapAddr
stNodeAddr = meta.stNodeAddr
btreeAddr = meta.btreeAddr
}
// Step 1: Read existing local heap
heap, err := fw.readLocalHeap(heapAddr)
if err != nil {
return fmt.Errorf("read local heap: %w", err)
}
// Step 2: Add child name to heap
nameOffset, err := heap.AddString(childName)
if err != nil {
return fmt.Errorf("add string to heap: %w", err)
}
// Step 3: Read existing symbol table node
stNode, err := fw.readSymbolTableNode(stNodeAddr)
if err != nil {
return fmt.Errorf("read symbol table node: %w", err)
}
// Step 4: Add entry to symbol table
entry := structures.SymbolTableEntry{
LinkNameOffset: nameOffset,
ObjectAddress: childAddr,
CacheType: 0, // No cache (MVP)
Reserved: 0,
}
if err := stNode.AddEntry(entry); err != nil {
return fmt.Errorf("add entry to symbol table: %w", err)
}
// Step 4b: Sort SNOD entries by name (HDF5 format requirement).
// The C library expects symbol table entries sorted by strcmp on the name
// looked up from the local heap. Without sorting, h5dump/h5ls fail when
// entries are added in non-alphabetical order.
sort.Slice(stNode.Entries, func(i, j int) bool {
ni, nj := stNode.Entries[i].LinkNameOffset, stNode.Entries[j].LinkNameOffset
var si, sj string
if ni == nameOffset {
si = childName
} else {
si, _ = heap.GetString(ni)
}
if nj == nameOffset {
sj = childName
} else {
sj, _ = heap.GetString(nj)
}
return si < sj
})
// Step 5: Write updated heap
if err := heap.WriteTo(fw.writer, heapAddr); err != nil {
return fmt.Errorf("write heap: %w", err)
}
// Step 6: Write updated symbol table node
offsetSize := fw.file.sb.OffsetSize
if err := stNode.WriteAt(fw.writer, stNodeAddr, offsetSize, 32, fw.file.sb.Endianness); err != nil {
return fmt.Errorf("write symbol table: %w", err)
}
// Step 7: Update B-tree right key (key[1]) to reflect the lexicographically
// largest name's local heap offset. Per HDF5 spec, B-tree v1 group nodes
// compare keys by looking up strings in the local heap and using strcmp.
// The right key must be the offset of the string that sorts LAST, not the
// numerically largest offset. Without this, h5dump/h5ls cannot find entries
// whose names sort after the right key's name.
//
// Note: heap.GetString() reads from heap.Data (on-disk snapshot). The entry
// we just added (at nameOffset) is only in heap.strings (not yet flushed to
// Data), so we use childName directly for that entry.
var maxNameOffset uint64
var maxName string
for _, e := range stNode.Entries {
var entryName string
if e.LinkNameOffset == nameOffset {
// This is the entry we just added — use childName directly
// because heap.Data hasn't been updated yet.
entryName = childName
} else {
var nameErr error
entryName, nameErr = heap.GetString(e.LinkNameOffset)
if nameErr != nil {
continue
}
}
if entryName > maxName {
maxName = entryName
maxNameOffset = e.LinkNameOffset
}
}
// Key[1] is at: btreeAddr + 24 (header) + 2*offsetSize (key[0] + child[0])
rightKeyOffset := btreeAddr + 24 + 2*uint64(offsetSize)
var keyBuf [8]byte
fw.file.sb.Endianness.PutUint64(keyBuf[:], maxNameOffset)
//nolint:gosec // G115: Safe — rightKeyOffset is within B-tree bounds
if _, err := fw.writer.WriteAt(keyBuf[:offsetSize], int64(rightKeyOffset)); err != nil {
return fmt.Errorf("write B-tree right key: %w", err)
}
return nil
}
// readLocalHeap reads a local heap from the file at the specified address.
// This is used to modify the heap by adding new strings for linking.
//
// Parameters:
// - addr: Address of the local heap in the file
//
// Returns:
// - *structures.LocalHeap: The heap structure (writable)
// - error: If read fails
func (fw *FileWriter) readLocalHeap(addr uint64) (*structures.LocalHeap, error) {
// Load existing heap from disk
heap, err := structures.LoadLocalHeap(fw.writer, addr, fw.file.sb)
if err != nil {
return nil, fmt.Errorf("load local heap: %w", err)
}
// Convert to writable mode (copies Data to internal strings buffer)
if err := heap.PrepareForModification(); err != nil {
return nil, fmt.Errorf("prepare heap for modification: %w", err)
}
// Set write-mode fields
// Note: DataSegmentAddress is set by WriteTo(), not here
heap.OffsetToHeadFreeList = 1 // MVP: no free list (1 = H5HL_FREE_NULL)
return heap, nil
}
// readSymbolTableNode reads a symbol table node from the file at the specified address.
// This is used to modify the node by adding new entries for linking.
//
// Parameters:
// - addr: Address of the symbol table node in the file
//
// Returns:
// - *structures.SymbolTableNode: The node structure (writable)
// - error: If read fails
func (fw *FileWriter) readSymbolTableNode(addr uint64) (*structures.SymbolTableNode, error) {
// Use the existing ParseSymbolTableNode function from structures package
return structures.ParseSymbolTableNode(fw.writer, addr, fw.file.sb)
}
// CreateDenseGroup creates new dense group (HDF5 1.8+ format).
//
// Dense groups are more efficient for large numbers of links (>8).
// They use fractal heap + B-tree v2 instead of symbol table.
//
// Parameters:
// - name: Group name (must start with "/")
// - links: Map of link_name → target_path
//
// Returns:
// - error: Non-nil if creation fails
//
// Example:
//
// err := fw.CreateDenseGroup("/large_group", map[string]string{
// "dataset1": "/data/dataset1",
// "dataset2": "/data/dataset2",
// // ... many links
// })
//
// Reference: H5Gcreate.c - H5Gcreate2().
func (fw *FileWriter) CreateDenseGroup(name string, links map[string]string) error {
// Validate name
if !strings.HasPrefix(name, "/") {
return fmt.Errorf("group name must start with /: %s", name)
}
// Create DenseGroupWriter
dgw := writer.NewDenseGroupWriter(name)
// Add all links
for linkName, targetPath := range links {
// Resolve target path to object header address
targetAddr, err := fw.resolveObjectAddress(targetPath)
if err != nil {
return fmt.Errorf("failed to resolve target %s: %w", targetPath, err)
}
err = dgw.AddLink(linkName, targetAddr)
if err != nil {
return fmt.Errorf("failed to add link %s: %w", linkName, err)
}
}
// Write dense group
ohAddr, err := dgw.WriteToFile(fw.writer, fw.writer.Allocator(), fw.file.sb)
if err != nil {
return fmt.Errorf("failed to write dense group: %w", err)
}
// Link to parent
parent, childName := parsePath(name)
// Validate parent exists (if not root)
if parent != "" && parent != "/" {
if _, exists := fw.groups[parent]; !exists {
return fmt.Errorf("parent group %q does not exist (create it first)", parent)
}
}
if err := fw.linkToParent(parent, childName, ohAddr); err != nil {
return fmt.Errorf("failed to link to parent: %w", err)
}
return nil
}
// resolveObjectAddress resolves object path to file address.
//
// This is a helper for link creation - looks up the target object's
// address in the file by its path. Supports both root-level and nested objects.
//
// Parameters:
// - path: Object path (e.g., "/data/dataset1" or "/dataset1")
//
// Returns:
// - uint64: File address of object header
// - error: Non-nil if object not found or parent doesn't exist
func (fw *FileWriter) resolveObjectAddress(path string) (uint64, error) {
// Handle root group
if path == "/" {
return fw.rootGroupAddr, nil
}
if !strings.HasPrefix(path, "/") {
return 0, fmt.Errorf("path must start with /: %s", path)
}
// Parse path
parent, name := parsePath(path)
// Get parent group metadata
var stNodeAddr, heapAddr uint64
if parent == "" || parent == "/" {
// Root group
stNodeAddr = fw.rootStNodeAddr
heapAddr = fw.rootHeapAddr
} else {
// Non-root group - look up metadata
meta, exists := fw.groups[parent]
if !exists {
return 0, fmt.Errorf("parent group %q not found", parent)
}
stNodeAddr = meta.stNodeAddr
heapAddr = meta.heapAddr
}
// Read parent group's symbol table to find the object
stNode, err := fw.readSymbolTableNode(stNodeAddr)
if err != nil {
return 0, fmt.Errorf("failed to read symbol table: %w", err)
}
heap, err := fw.readLocalHeap(heapAddr)
if err != nil {
return 0, fmt.Errorf("failed to read local heap: %w", err)
}
// Search for object in symbol table
for _, entry := range stNode.Entries {
// Get link name from heap
linkName, err := heap.GetString(entry.LinkNameOffset)
if err != nil {
continue
}
if linkName == name {
return entry.ObjectAddress, nil
}
}
return 0, fmt.Errorf("object not found: %s", path)
}
// Dense group threshold (HDF5 default: switch to dense when >8 links).
const denseGroupThreshold = 8
// CreateGroupWithLinks creates group with automatic format selection.
//
// This method automatically chooses the most efficient storage format:
// - Symbol table (old format) for ≤8 links (compact)
// - Dense format (new format) for >8 links (scalable)
//
// This matches HDF5 1.8+ behavior: start compact, use dense when needed.
//
// Parameters:
// - name: Group name (must start with "/")
// - links: Map of link_name → target_path (can be empty)
//
// Returns:
// - error: Non-nil if creation fails
//
// Example:
//
// // Small group (will use symbol table)
// fw.CreateGroupWithLinks("/small", map[string]string{
// "data1": "/dataset1",
// "data2": "/dataset2",
// })
//
// // Large group (will use dense format)
// largeLinks := make(map[string]string)
// for i := 0; i < 100; i++ {
// largeLinks[fmt.Sprintf("link%d", i)] = fmt.Sprintf("/dataset%d", i)
// }
// fw.CreateGroupWithLinks("/large", largeLinks)
//
// Reference: H5Gint.c - H5G_convert_to_dense().
func (fw *FileWriter) CreateGroupWithLinks(name string, links map[string]string) error {
if len(links) > denseGroupThreshold {
// Use dense format for large groups
return fw.CreateDenseGroup(name, links)
}
// Use symbol table format for small groups
// Create empty group first
_, err := fw.CreateGroup(name)
if err != nil {
return err
}
// For MVP: linking is handled by CreateDenseGroup for dense groups
// For symbol table groups, links would need to be added via linkToParent
// This is a limitation of the MVP - symbol table groups can be created empty,
// but adding links after creation requires manual linkToParent calls
// Future: implement addLinkToGroup() to add links to existing symbol table groups
if len(links) > 0 {
return fmt.Errorf("adding links to symbol table groups not yet supported in MVP (group %s has %d links)", name, len(links))
}
return nil
}