-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdataset.go
More file actions
1030 lines (931 loc) · 27.6 KB
/
Copy pathdataset.go
File metadata and controls
1030 lines (931 loc) · 27.6 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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package godicom
import (
"context"
"fmt"
"io"
"math"
"sort"
"strconv"
"strings"
)
// Dataset represents a DICOM Dataset - a collection of DataElements keyed by Tag.
type Dataset struct {
elements map[Tag]*DataElement
privateBlocks map[privateBlockKey]*PrivateBlock
originalEnc EncodingInfo
originalCharsets []string // SpecificCharacterSet at read time; nil if unset/new
writeEnc *EncodingInfo // nil = same as originalEnc for IsOriginalEncoding
parent *Sequence
IsUndefinedLengthSequenceItem bool
readCtx *readContext
}
// readContext holds the source used for deferred element loading and the
// call-scoped logger context for this parse.
type readContext struct {
// data is the in-memory source (ReadBytes / non-seekable Read). Deferred
// element offsets are relative to it, so for a Deflated transfer syntax it
// holds the inflated dataset rather than the file's bytes -- and is then the
// only source that can serve a deferred load, since filename and src still
// hold compressed bytes.
data []byte
filename string // reopen path for streaming ReadFile
modTime int64
size int64 // file size when filename is used without data
// src is the random-access source a seekable Read parsed from, kept so
// deferred values remain loadable when there is no path to reopen (for
// example an io.ReadSeeker that is not an *os.File). When it is the
// seekerReaderAt wrapper, reading through it moves the underlying reader's
// position and is not safe for concurrent use; a reader that was already an
// io.ReaderAt is held as-is and keeps whatever guarantees it makes.
src io.ReaderAt
ctx context.Context
// onDiag is ReadOptions.OnDiagnostic, kept so deferred loads can report
// through the same hook after the read has returned.
onDiag func(Diagnostic) error
// dict is ReadOptions.Dictionary, nil for PS3.6. It lives here rather than on
// codecContext -- where the rest of the per-element decoding state lives --
// because it has to outlive the parse. A deferred load reruns the header
// decode after the read returned, and a private element's VR has to resolve
// the same way it did the first time or the reload is rejected as a mismatch.
// readContext is the only piece of parse state that survives, as
// Dataset.readCtx.
dict Dictionary
// seqPath is the sequences currently being descended into, and the item of
// each, used to stamp Diagnostic.Path.
seqPath []PathStep
// baseOffset shifts diagnostic offsets back into source coordinates when a
// parser is handed a buffer copied out of the middle of the source.
baseOffset int64
}
// dictionary returns the data dictionary this parse resolves against: the one
// ReadOptions.Dictionary supplied, or PS3.6. Nil-safe, because a decoder handed
// no readContext at all still has to resolve VRs.
func (rc *readContext) dictionary() Dictionary {
if rc == nil {
return Standard()
}
return dictionaryOrStandard(rc.dict)
}
func (rc *readContext) logCtx() context.Context {
if rc != nil && rc.ctx != nil {
return rc.ctx
}
return context.Background()
}
// EncodingInfo describes the DICOM encoding used when reading/writing.
type EncodingInfo struct {
IsImplicitVR bool
IsLittleEndian bool
}
// FileMetaDataset holds DICOM File Meta Information (group 0x0002).
type FileMetaDataset struct {
*Dataset
}
// FileDataset extends Dataset with file-specific info.
type FileDataset struct {
*Dataset
Filename string
Preamble []byte
FileMeta *FileMetaDataset
Timestamp string // file modification time as Unix seconds (deferred read checks)
}
func NewDataset() *Dataset {
return &Dataset{
elements: make(map[Tag]*DataElement),
privateBlocks: make(map[privateBlockKey]*PrivateBlock),
originalEnc: EncodingInfo{IsImplicitVR: false, IsLittleEndian: true},
}
}
func NewFileMetaDataset() *FileMetaDataset {
return &FileMetaDataset{Dataset: NewDataset()}
}
// --- Element access ---
func (d *Dataset) Get(tag Tag) (*DataElement, bool) {
if err := d.loadDeferred(tag); err != nil {
return nil, false
}
e, ok := d.elements[tag]
if !ok {
return nil, false
}
if IsAmbiguousVR(e.VR) && e.IsRaw() {
_ = correctAmbiguousVRElement(e, d, d.originalEnc.IsLittleEndian, d.ambiguousVRAncestors())
}
return e, true
}
// LoadDeferred reads a deferred element's value from the source file/buffer.
// Mirrors pydicom deferred read triggered by Dataset.__getitem__.
func (d *Dataset) LoadDeferred(tag Tag) error {
return d.loadDeferred(tag)
}
func (d *Dataset) loadDeferred(tag Tag) error {
elem, ok := d.elements[tag]
if !ok || !elem.Deferred {
return nil
}
if d.readCtx == nil {
return d.deferredFailed(elem, fmt.Errorf("godicom: deferred read requires source data"))
}
if err := loadDeferredElement(d.readCtx, d, elem); err != nil {
return d.deferredFailed(elem, err)
}
return nil
}
// deferredFailed reports a deferred value that could not be loaded. Get turns
// the error into a plain "absent", so without this the tag stays listed by
// SortedTags while every read of it silently returns nothing.
func (d *Dataset) deferredFailed(elem *DataElement, cause error) error {
if err := d.readCtx.report(Diagnostic{
Kind: DiagnosticDeferredValueUnreadable,
Tag: elem.Tag,
VR: elem.VR,
Offset: elem.ValueTell,
Need: int64(elem.ValueLength),
Err: cause,
}); err != nil {
return err
}
return cause
}
func (d *Dataset) Set(element *DataElement) {
if element.VR == VRSQ {
if seq, ok := element.Value.(*Sequence); ok && seq != nil {
seq.owner = d
for _, item := range seq.Items() {
if item != nil {
item.parent = seq
}
}
}
}
// Replacing an element clears any prior raw bytes; caller-owned elements
// created via NewElement do not carry RawValue unless set explicitly.
d.elements[element.Tag] = element
// Overwriting a Private Creator reassigns its block to a different vendor, so
// any block cached under the old name now points into the new vendor's
// elements. Drop the cache rather than let it answer for a name the dataset no
// longer holds.
if len(d.privateBlocks) > 0 && element.Tag.IsPrivateCreator() {
d.invalidatePrivateBlocks()
}
}
func (d *Dataset) ambiguousVRAncestors() []*Dataset {
ancestors := []*Dataset{d}
cur := d
for cur.parent != nil {
owner := cur.parent.owner
if owner == nil {
break
}
ancestors = append(ancestors, owner)
cur = owner
}
return ancestors
}
// Delete removes the element for tag, and does nothing if it was not there.
//
// Deleting a Private Creator element drops the private-block cache: the blocks
// that element reserved no longer resolve, and a cached PrivateBlock still
// answering for one would write elements no reader can attribute to a vendor.
func (d *Dataset) Delete(tag Tag) {
delete(d.elements, tag)
if len(d.privateBlocks) > 0 && tag.IsPrivateCreator() {
d.invalidatePrivateBlocks()
}
}
func (d *Dataset) Has(tag Tag) bool {
_, ok := d.elements[tag]
return ok
}
func (d *Dataset) Elements() map[Tag]*DataElement {
elements := make(map[Tag]*DataElement, len(d.elements))
for tag, elem := range d.elements {
elements[tag] = elem
}
return elements
}
// SortedTags returns all tags in ascending order.
func (d *Dataset) SortedTags() []Tag {
tags := make([]Tag, 0, len(d.elements))
for t := range d.elements {
tags = append(tags, t)
}
sort.Slice(tags, func(i, j int) bool { return tags[i] < tags[j] })
return tags
}
// Iter returns all elements sorted by tag.
func (d *Dataset) Iter() []*DataElement {
tags := d.SortedTags()
elems := make([]*DataElement, len(tags))
for i, t := range tags {
elems[i] = d.elements[t]
}
return elems
}
// --- Convenience getters ---
func (d *Dataset) GetString(tag Tag) (string, bool) {
if err := d.loadDeferred(tag); err != nil {
return "", false
}
e, ok := d.elements[tag]
if !ok || e.Value == nil {
return "", false
}
switch v := e.Value.(type) {
case string:
return v, true
case PersonName:
return v.String(), true
case DA:
return v.String(), true
case TM:
return v.String(), true
case DT:
return v.String(), true
case DS:
return v.String(), true
case IS:
return v.String(), true
case UID:
return string(v), true
default:
return fmt.Sprintf("%v", v), true
}
}
func (d *Dataset) GetInt(tag Tag) (int, bool) {
if err := d.loadDeferred(tag); err != nil {
return 0, false
}
e, ok := d.elements[tag]
if !ok || e.Value == nil {
return 0, false
}
switch v := e.Value.(type) {
case int:
return v, true
case int16:
return int(v), true
case uint16:
return int(v), true
case int32:
return int(v), true
case uint32:
return int(v), true
case int64:
return int(v), true
case uint64:
return int(v), true
case IS:
return int(v.Value), true
case string:
is, err := ParseIS(v)
if err != nil {
return 0, false
}
return int(is.Value), true
}
return 0, false
}
func (d *Dataset) GetDA(tag Tag) (DA, bool) {
if err := d.loadDeferred(tag); err != nil {
return DA{}, false
}
e, ok := d.elements[tag]
if !ok || e.Value == nil {
return DA{}, false
}
switch v := e.Value.(type) {
case DA:
return v, true
case string:
da, err := ParseDA(v)
if err != nil {
return DA{}, false
}
return da, true
}
return DA{}, false
}
func (d *Dataset) GetTM(tag Tag) (TM, bool) {
if err := d.loadDeferred(tag); err != nil {
return TM{}, false
}
e, ok := d.elements[tag]
if !ok || e.Value == nil {
return TM{}, false
}
switch v := e.Value.(type) {
case TM:
return v, true
case string:
tm, err := ParseTM(v)
if err != nil {
return TM{}, false
}
return tm, true
}
return TM{}, false
}
func (d *Dataset) GetDT(tag Tag) (DT, bool) {
if err := d.loadDeferred(tag); err != nil {
return DT{}, false
}
e, ok := d.elements[tag]
if !ok || e.Value == nil {
return DT{}, false
}
switch v := e.Value.(type) {
case DT:
return v, true
case string:
dt, err := ParseDT(v)
if err != nil {
return DT{}, false
}
return dt, true
}
return DT{}, false
}
func (d *Dataset) GetPN(tag Tag) (PersonName, bool) {
if err := d.loadDeferred(tag); err != nil {
return PersonName{}, false
}
e, ok := d.elements[tag]
if !ok || e.Value == nil {
return PersonName{}, false
}
switch v := e.Value.(type) {
case PersonName:
return v, true
case string:
return ParsePersonName(v), true
}
return PersonName{}, false
}
func (d *Dataset) GetDS(tag Tag) (DS, bool) {
if err := d.loadDeferred(tag); err != nil {
return DS{}, false
}
e, ok := d.elements[tag]
if !ok || e.Value == nil {
return DS{}, false
}
switch v := e.Value.(type) {
case DS:
return v, true
case float64:
return DS{Value: v, Original: strconv.FormatFloat(v, 'g', -1, 64)}, true
case string:
ds, err := ParseDS(v)
if err != nil {
return DS{}, false
}
return ds, true
}
return DS{}, false
}
func (d *Dataset) GetIS(tag Tag) (IS, bool) {
if err := d.loadDeferred(tag); err != nil {
return IS{}, false
}
e, ok := d.elements[tag]
if !ok || e.Value == nil {
return IS{}, false
}
switch v := e.Value.(type) {
case IS:
return v, true
case int:
return IS{Value: int64(v), Original: strconv.FormatInt(int64(v), 10)}, true
case int64:
return IS{Value: v, Original: strconv.FormatInt(v, 10)}, true
case string:
is, err := ParseIS(v)
if err != nil {
return IS{}, false
}
return is, true
}
return IS{}, false
}
func (d *Dataset) GetFloat(tag Tag) (float64, bool) {
vals, ok := d.GetFloats(tag)
if !ok || len(vals) == 0 {
return 0, false
}
return vals[0], true
}
// GetFloats returns all floating values for a DS/FD/FL multi-valued element.
func (d *Dataset) GetFloats(tag Tag) ([]float64, bool) {
if err := d.loadDeferred(tag); err != nil {
return nil, false
}
e, ok := d.elements[tag]
if !ok || e.Value == nil {
return nil, false
}
switch v := e.Value.(type) {
case float64:
return []float64{v}, true
case DS:
return []float64{v.Value}, true
case string:
ds, err := ParseDS(v)
if err != nil {
return nil, false
}
return []float64{ds.Value}, true
case *MultiValue[float64]:
out := make([]float64, v.Len())
copy(out, v.Values())
return out, true
case *MultiValue[DS]:
out := make([]float64, v.Len())
for i, ds := range v.Values() {
out[i] = ds.Value
}
return out, true
case *MultiValue[string]:
out := make([]float64, 0, v.Len())
for _, s := range v.Values() {
ds, err := ParseDS(s)
if err != nil {
return nil, false
}
out = append(out, ds.Value)
}
return out, true
case *MultiValue[interface{}]:
out := make([]float64, 0, v.Len())
for _, item := range v.Values() {
f, ok := floatFromValue(item)
if !ok {
return nil, false
}
out = append(out, f)
}
return out, true
}
return nil, false
}
func floatFromValue(v interface{}) (float64, bool) {
switch x := v.(type) {
case float64:
return x, true
case float32:
return float64(x), true
case DS:
return x.Value, true
case int:
return float64(x), true
case int64:
return float64(x), true
case string:
ds, err := ParseDS(x)
if err != nil {
return 0, false
}
return ds.Value, true
default:
return 0, false
}
}
func (d *Dataset) GetBytes(tag Tag) ([]byte, bool) {
if err := d.loadDeferred(tag); err != nil {
return nil, false
}
e, ok := d.elements[tag]
if !ok || e.Value == nil {
return nil, false
}
b, ok := e.Value.([]byte)
return b, ok
}
func (d *Dataset) GetSequence(tag Tag) (*Sequence, bool) {
if err := d.loadDeferred(tag); err != nil {
return nil, false
}
e, ok := d.elements[tag]
if !ok || e.Value == nil {
return nil, false
}
s, ok := e.Value.(*Sequence)
return s, ok
}
func (d *Dataset) StringValue(tag Tag) (string, bool) {
return d.GetString(tag)
}
func (d *Dataset) IntValue(tag Tag) (int, bool) {
return d.GetInt(tag)
}
func (d *Dataset) FloatValue(tag Tag) (float64, bool) {
return d.GetFloat(tag)
}
func (d *Dataset) BytesValue(tag Tag) ([]byte, bool) {
return d.GetBytes(tag)
}
func (d *Dataset) SequenceValue(tag Tag) (*Sequence, bool) {
return d.GetSequence(tag)
}
func (d *Dataset) GetDataElement(tag Tag) *DataElement {
if err := d.loadDeferred(tag); err != nil {
return nil
}
return d.elements[tag]
}
// --- Convenience setters ---
//
// Each setter mirrors the getter of the same name: the VR comes from the data
// dictionary, so callers do not repeat it. Tags outside the dictionary (private
// tags in particular) have no dictionary VR and return an error; pass the VR
// explicitly with Set(NewDataElement(tag, vr, value)) for those.
//
// The typed setters also reject value kinds the tag's VR cannot hold, which
// turns a silently mis-encoded element into an error at the call site.
// SetValue stores value under tag using the VR from the data dictionary.
// The value type is not checked against the VR; the typed setters below do that.
func (d *Dataset) SetValue(tag Tag, value interface{}) error {
return d.setDictionary(tag, value, "", nil)
}
// setDictionary resolves tag's dictionary VR, checks it admits kind, and stores
// value. A nil allow skips the kind check.
func (d *Dataset) setDictionary(tag Tag, value interface{}, kind string, allow func(VR) bool) error {
vr, err := dictionaryVR(tag)
if err != nil {
return fmt.Errorf("%w; pass the VR explicitly with Set(NewDataElement(tag, vr, value))", err)
}
if allow != nil && !allow(vr) {
return fmt.Errorf("godicom: tag %s has VR %s, which does not hold %s values", tag, vr, kind)
}
if err := checkRepresentable(tag, vr, value); err != nil {
return err
}
d.Set(NewDataElement(tag, vr, value))
return nil
}
// checkRepresentable rejects values that pass the VR kind check but that the VR
// still cannot spell, so the caller hears about it here rather than getting a
// silently corrupt element -- or, since the write path now refuses these, an
// error from a later Save.
//
// Only DS is affected today. DS is a float VR, so setsFloat admits NaN and ±Inf
// for it, but a decimal string has no spelling for either. FD and FL are float
// VRs too and do represent them exactly, per IEEE 754, so they are left alone.
func checkRepresentable(tag Tag, vr VR, value interface{}) error {
if vr != VRDS {
return nil
}
bad := func(f float64) bool { return math.IsNaN(f) || math.IsInf(f, 0) }
switch v := value.(type) {
case float64:
if bad(v) {
return fmt.Errorf("godicom: tag %s has VR DS, which cannot represent %g", tag, v)
}
case *MultiValue[float64]:
for i, f := range v.Values() {
if bad(f) {
return fmt.Errorf("godicom: tag %s has VR DS, which cannot represent %g (value %d)", tag, f, i)
}
}
}
return nil
}
// Value kinds admitted by each typed setter. The ambiguous VRs are included
// where any of their candidate VRs admits the kind; the write path resolves
// them via CorrectAmbiguousVR.
func setsString(vr VR) bool { return IsStringVR(vr) }
func setsInt(vr VR) bool {
return IsIntVR(vr) || vr == VRUsSS || vr == VRUsOw || vr == VRUsSsOw
}
func setsFloat(vr VR) bool { return IsFloatVR(vr) }
func setsBytes(vr VR) bool {
return IsBinaryVR(vr) || vr == VRObOw || vr == VRUsOw || vr == VRUsSsOw
}
func (d *Dataset) SetString(tag Tag, value string) error {
return d.setDictionary(tag, value, "string", setsString)
}
// SetStrings stores a multi-valued string element (backslash-separated on write).
func (d *Dataset) SetStrings(tag Tag, values ...string) error {
return d.setDictionary(tag, NewMultiValue(values), "string", setsString)
}
func (d *Dataset) SetInt(tag Tag, value int) error {
return d.setDictionary(tag, value, "integer", setsInt)
}
// SetInts stores a multi-valued integer element.
func (d *Dataset) SetInts(tag Tag, values ...int) error {
return d.setDictionary(tag, NewMultiValue(values), "integer", setsInt)
}
func (d *Dataset) SetFloat(tag Tag, value float64) error {
return d.setDictionary(tag, value, "floating-point", setsFloat)
}
// SetFloats stores a multi-valued floating-point element.
func (d *Dataset) SetFloats(tag Tag, values ...float64) error {
return d.setDictionary(tag, NewMultiValue(values), "floating-point", setsFloat)
}
func (d *Dataset) SetBytes(tag Tag, value []byte) error {
return d.setDictionary(tag, value, "binary", setsBytes)
}
func (d *Dataset) SetSequence(tag Tag, seq *Sequence) error {
return d.setDictionary(tag, seq, "sequence", func(vr VR) bool { return vr == VRSQ })
}
func (d *Dataset) SetDA(tag Tag, value DA) error {
return d.setDictionary(tag, value, "date", func(vr VR) bool { return vr == VRDA })
}
func (d *Dataset) SetTM(tag Tag, value TM) error {
return d.setDictionary(tag, value, "time", func(vr VR) bool { return vr == VRTM })
}
func (d *Dataset) SetDT(tag Tag, value DT) error {
return d.setDictionary(tag, value, "date-time", func(vr VR) bool { return vr == VRDT })
}
func (d *Dataset) SetPN(tag Tag, value PersonName) error {
return d.setDictionary(tag, value, "person name", func(vr VR) bool { return vr == VRPN })
}
func (d *Dataset) SetDS(tag Tag, value DS) error {
return d.setDictionary(tag, value, "decimal string", func(vr VR) bool { return vr == VRDS })
}
func (d *Dataset) SetIS(tag Tag, value IS) error {
return d.setDictionary(tag, value, "integer string", func(vr VR) bool { return vr == VRIS })
}
// --- Private blocks ---
//
// PrivateBlock, NewPrivateBlock and PrivateCreators live in private_block.go,
// with the PS3.5 block-allocation rules they implement.
// --- String ---
const (
// DefaultElementFormat matches pydicom Dataset.default_element_format.
DefaultElementFormat = "%(tag)s %(name)-35.35s %(VR)s: %(repval)s"
// DefaultSequenceElementFormat matches pydicom Dataset.default_sequence_element_format.
DefaultSequenceElementFormat = "%(tag)s %(name)-35.35s %(VR)s: %(repval)s"
datasetIndentChars = " "
)
// FormatLinesOptions controls Dataset.FormattedLines output.
type FormatLinesOptions struct {
ElementFormat string
SequenceElementFormat string
}
func (d *Dataset) String() string {
return d.prettyString(0, false)
}
// Top returns a string representation of only top-level elements.
// Mirrors pydicom Dataset.top.
func (d *Dataset) Top() string {
return d.prettyString(0, true)
}
// FormattedLines returns formatted lines for every element, recursing into sequences.
// Mirrors pydicom Dataset.formatted_lines.
func (d *Dataset) FormattedLines(opts *FormatLinesOptions) []string {
elemFmt := DefaultElementFormat
seqFmt := DefaultSequenceElementFormat
if opts != nil {
if opts.ElementFormat != "" {
elemFmt = opts.ElementFormat
}
if opts.SequenceElementFormat != "" {
seqFmt = opts.SequenceElementFormat
}
}
var out []string
for _, elem := range d.IterAll() {
if elem.VR == VRSQ {
out = append(out, formatElementLine(elem, seqFmt))
} else {
out = append(out, formatElementLine(elem, elemFmt))
}
}
return out
}
func (d *Dataset) prettyString(indent int, topLevelOnly bool) string {
var lines []string
indentStr := strings.Repeat(datasetIndentChars, indent)
nextIndentStr := strings.Repeat(datasetIndentChars, indent+1)
for _, elem := range d.Iter() {
if elem.VR == VRSQ {
n := 0
seq, ok := elem.Value.(*Sequence)
if ok {
n = seq.Len()
}
lines = append(lines, fmt.Sprintf("%s%s %s %d item(s) ---- ", indentStr, elem.Tag, elem.Name(), n))
if topLevelOnly || !ok {
continue
}
for _, item := range seq.Items() {
if item == nil {
lines = append(lines, nextIndentStr+"---------")
continue
}
nested := item.prettyString(indent+1, false)
if nested != "" {
lines = append(lines, nested)
}
lines = append(lines, nextIndentStr+"---------")
}
continue
}
lines = append(lines, indentStr+elem.String())
}
return strings.Join(lines, "\n")
}
func formatElementLine(elem *Element, format string) string {
tag := elem.Tag.String()
name := elem.Name()
vr := string(elem.VR)
repval := elem.ReprValue()
out := format
out = strings.ReplaceAll(out, "%(tag)s", tag)
out = strings.ReplaceAll(out, "%(VR)s", vr)
out = strings.ReplaceAll(out, "%(repval)s", repval)
if strings.Contains(out, "%(name)-35.35s") {
out = strings.ReplaceAll(out, "%(name)-35.35s", padTruncateRunes(name, 35))
}
out = strings.ReplaceAll(out, "%(name)s", name)
return out
}
func padTruncateRunes(s string, width int) string {
runes := []rune(s)
if len(runes) > width {
runes = runes[:width]
}
padded := string(runes)
if n := width - len([]rune(padded)); n > 0 {
padded += strings.Repeat(" ", n)
}
return padded
}
// WalkFunc is called for each element in a Dataset during Walk.
type WalkFunc func(ds *Dataset, elem *Element)
// Walk visits each element in tag order, optionally recursing into sequences.
// Mirrors pydicom Dataset.walk.
func (d *Dataset) Walk(fn WalkFunc, recursive bool) {
d.walk(fn, recursive)
}
func (d *Dataset) walk(fn WalkFunc, recursive bool) {
for _, tag := range d.SortedTags() {
elem, ok := d.Get(tag)
if !ok {
continue
}
fn(d, elem)
if !recursive || elem.VR != VRSQ {
continue
}
seq, ok := elem.Value.(*Sequence)
if !ok {
continue
}
for _, item := range seq.Items() {
item.walk(fn, recursive)
}
}
}
// IterAll returns all elements in tag order, recursing into sequences.
// Mirrors pydicom Dataset.iterall.
func (d *Dataset) IterAll() []*DataElement {
var out []*DataElement
d.Walk(func(_ *Dataset, elem *Element) {
out = append(out, elem)
}, true)
return out
}
// Clear removes all elements from the dataset.
// Mirrors pydicom Dataset.clear.
func (d *Dataset) Clear() {
d.elements = make(map[Tag]*DataElement)
d.invalidatePrivateBlocks()
}
// Pop removes and returns the element for tag.
// Mirrors pydicom Dataset.pop for tag keys.
func (d *Dataset) Pop(tag Tag) (*DataElement, bool) {
elem, ok := d.Get(tag)
if !ok {
return nil, false
}
d.Delete(tag)
return elem, true
}
// Update copies elements from other into d (overwriting matching tags).
// Mirrors pydicom Dataset.update for Dataset sources.
func (d *Dataset) Update(other *Dataset) {
if other == nil {
return
}
for _, elem := range other.Iter() {
d.Set(cloneElement(elem))
}
}
// GroupDataset returns a new dataset containing only elements of the given group.
// Mirrors pydicom Dataset.group_dataset.
func (d *Dataset) GroupDataset(group int) *Dataset {
out := NewDataset()
for _, elem := range d.Iter() {
if int(elem.Tag.Group()) == group {
out.Set(cloneElement(elem))
}
}
return out
}
// RemovePrivateTags deletes all private elements, including nested sequences.
// Mirrors pydicom Dataset.remove_private_tags.
func (d *Dataset) RemovePrivateTags() {
d.Walk(func(ds *Dataset, elem *Element) {
if elem.IsPrivate() {
ds.Delete(elem.Tag)
}
}, true)
}
// ElementByKeyword returns the element for a DICOM keyword, if present.
// Mirrors pydicom Dataset.data_element.
func (d *Dataset) ElementByKeyword(keyword string) (*DataElement, bool) {
tag, err := TagFromKeyword(keyword)
if err != nil {
return nil, false
}
return d.Get(tag)
}
// Equal reports whether d and other contain the same tags, VRs, and values.
// Mirrors pydicom Dataset.__eq__ for Dataset values.
func (d *Dataset) Equal(other *Dataset) bool {
if d == other {
return true
}
if d == nil || other == nil {
return false
}
if d.Len() != other.Len() {
return false
}
for _, tag := range d.SortedTags() {
a, okA := d.Get(tag)
b, okB := other.Get(tag)
if !okA || !okB || !a.Equal(b) {
return false
}
}
return true
}
// SetOriginalEncoding records the encoding used when the dataset was decoded.
// Mirrors pydicom Dataset.set_original_encoding.
func (d *Dataset) SetOriginalEncoding(isImplicit, isLittleEndian bool, charsets []string) {
d.originalEnc = EncodingInfo{IsImplicitVR: isImplicit, IsLittleEndian: isLittleEndian}
if charsets == nil {
d.originalCharsets = []string{DefaultCharacterSet}
} else {
d.originalCharsets = ConvertCharacterSets(charsets)
}
enc := d.originalEnc
d.writeEnc = &enc
}
// SetWriteEncoding sets the VR/endianness that would be used for writing.
// Used with IsOriginalEncoding; nil write encoding means "same as original".
func (d *Dataset) SetWriteEncoding(isImplicit, isLittleEndian bool) {
d.writeEnc = &EncodingInfo{IsImplicitVR: isImplicit, IsLittleEndian: isLittleEndian}
}
// IsOriginalEncoding reports whether the current write encoding and
// SpecificCharacterSet match those captured when the dataset was read.
// Mirrors pydicom Dataset.is_original_encoding.
func (d *Dataset) IsOriginalEncoding() bool {
if d == nil || d.originalCharsets == nil {
return false
}
if charsetChanged(d) {
return false
}
if d.writeEnc == nil {
return true
}
return d.writeEnc.IsImplicitVR == d.originalEnc.IsImplicitVR &&
d.writeEnc.IsLittleEndian == d.originalEnc.IsLittleEndian
}
// Clone returns a deep copy of the dataset, including sequence items.
func (d *Dataset) Clone() *Dataset {
return cloneDataset(d)
}
// --- Save / Encode ---
func (d *Dataset) SaveAs(filename string, opts *WriteOptions) error {
return WriteFileContext(context.Background(), filename, d, opts)
}
func (fd *FileDataset) SaveAs(filename string, opts *WriteOptions) error {