Skip to Content
go-dicom(3)
Packages

filebase

The byte-level reader and writer the file packages are built on: an io.ReadSeeker or io.WriteSeeker with a byte order, position tracking and 16- and 32-bit reads and writes.

import "github.com/amrshadid/go-dicom/filebase" · pkg.go.dev

When to use it

Mostly as the adapter in one line: filebase.NewFileReader(f) to hand a file to filereader, and filebase.NewFileWriter(f) to hand one to filewriter. Any io.ReadSeeker works, so a bytes.Reader reads a file held in memory.

Use it directly only to parse something by hand. For DICOM files, use filereader and filewriter; for byte-order helpers on slices, see fileutil.

Key types and functions

NameWhat it is for
NewFileReader, FileReaderWrap an io.ReadSeeker; little endian until told otherwise.
NewFileWriter, FileWriterWrap an io.WriteSeeker.
Reader, WriterThe interfaces filereader and filewriter take.
ByteOrderLittleEndian or BigEndian, set with SetByteOrder.
FileReader.ReadBytes, ReadUint16, ReadUint32Read exactly so many bytes, or an integer in the current byte order.
FileReader.Tell, SeekThe position, and moving it.
BufferPoolReusable byte slices of one size.

Example

// Check the preamble and "DICM" prefix of a file by hand.
package main

import (
	"fmt"
	"io"
	"log"
	"os"

	"github.com/amrshadid/go-dicom/filebase"
)

func main() {
	f, err := os.Open(os.Args[1])
	if err != nil {
		log.Fatal(err)
	}
	r := filebase.NewFileReader(f) // little endian by default
	defer r.Close()                // closes f too

	if _, err := r.Seek(128, io.SeekStart); err != nil { // skip the preamble
		log.Fatal(err)
	}
	prefix := make([]byte, 4)
	if err := r.ReadBytes(prefix); err != nil {
		log.Fatal(err)
	}
	group, err := r.ReadUint16()
	if err != nil {
		log.Fatal(err)
	}
	pos, _ := r.Tell()
	fmt.Printf("prefix %q, first group %04X, now at %d\n", prefix, group, pos)
}

On a Part 10 file it prints prefix "DICM", first group 0002, now at 134.

Notes

  • Close on a FileReader or FileWriter closes what it wraps when that is an io.Closer, so do not close the file twice.
  • The position and byte order are guarded by a lock, but a seek followed by a read is two calls: goroutines sharing one reader still interleave. Give each goroutine its own reader.
  • The Execute…Hook functions return a map describing an operation; nothing in the library calls them.

Note

The package documentation's "API Reference" is out of step in places: NewFileWriter takes an io.WriteSeeker, ByteOrder is an int, and BufferPool has no Close.

See also

filereader · filewriter · fileutil

On this page