opc

package
v0.0.0-...-2a9920d Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 12, 2026 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Overview

Package opc provides a Go implementation of the OOXML Open Packaging Convention (OPC), used for processing Office Open XML file formats such as PPTX.

Index

Constants

View Source
const (
	// OPC relationship content type
	ContentTypeRelationships = "application/vnd.openxmlformats-package.relationships+xml"

	// PPTX core content types
	ContentTypePresentation   = "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml"
	ContentTypeSlide          = "application/vnd.openxmlformats-officedocument.presentationml.slide+xml"
	ContentTypeSlideLayout    = "application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"
	ContentTypeSlideMaster    = "application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml"
	ContentTypeNotesSlide     = "application/vnd.openxmlformats-officedocument.presentationml.notesSlide+xml"
	ContentTypeHandoutMaster  = "application/vnd.openxmlformats-officedocument.presentationml.handoutMaster+xml"
	ContentTypeNotesMaster    = "application/vnd.openxmlformats-officedocument.presentationml.notesMaster+xml"
	ContentTypePresentationML = "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml"
	ContentTypePresProps      = "application/vnd.openxmlformats-officedocument.presentationml.presProps+xml"
	ContentTypeViewProps      = "application/vnd.openxmlformats-officedocument.presentationml.viewProps+xml"
	ContentTypeTableStyles    = "application/vnd.openxmlformats-officedocument.presentationml.tableStyles+xml"

	// Theme and styles
	ContentTypeTheme         = "application/vnd.openxmlformats-officedocument.theme+xml"
	ContentTypeThemeOverride = "application/vnd.openxmlformats-officedocument.themeOverride+xml"
	ContentTypeStyles        = "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"

	// Charts
	ContentTypeChart   = "application/vnd.openxmlformats-officedocument.drawingml.chart+xml"
	ContentTypeChartEx = "application/vnd.ms-office.chartex+xml"

	// Core properties
	ContentTypeCoreProperties = "application/vnd.openxmlformats-package.core-properties+xml"

	// Extended properties
	ContentTypeExtendedProperties = "application/vnd.openxmlformats-officedocument.extended-properties+xml"

	// Custom properties
	ContentTypeCustomProperties = "application/vnd.openxmlformats-officedocument.custom-properties+xml"

	// Image content types
	ContentTypePNG  = "image/png"
	ContentTypeJPEG = "image/jpeg"
	ContentTypeGIF  = "image/gif"
	ContentTypeBMP  = "image/bmp"
	ContentTypeTIFF = "image/tiff"
	ContentTypeWMF  = "image/x-wmf"
	ContentTypeEMF  = "image/x-emf"
	ContentTypeSVG  = "image/svg+xml"

	// Audio content types
	ContentTypeWAV  = "audio/wav"
	ContentTypeMP3  = "audio/mpeg"
	ContentTypeMIDI = "audio/midi"

	// Video content types
	ContentTypeMP4 = "video/mp4"
	ContentTypeAVI = "video/x-msvideo"
	ContentTypeWMV = "video/x-ms-wmv"

	// Other
	ContentTypeXML  = "application/xml"
	ContentTypeFont = "application/x-font"

	// Default content type (fallback for unknown extensions)
	ContentTypeDefault = "application/octet-stream"
)

Content type constants (Content Types)

View Source
const (
	// OPC core relationship
	RelTypeCoreProperties = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties"

	// Office document relationship
	RelTypeOfficeDocument = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"

	// Extended and custom properties
	RelTypeExtendedProperties = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties"
	RelTypeCustomProperties   = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties"

	// Slide relationships
	RelTypeSlide         = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide"
	RelTypeSlideLayout   = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout"
	RelTypeSlideMaster   = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster"
	RelTypeNotesSlide    = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide"
	RelTypeNotesMaster   = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesMaster"
	RelTypeHandoutMaster = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/handoutMaster"

	// Theme relationships
	RelTypeTheme         = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme"
	RelTypeThemeOverride = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/themeOverride"

	// Presentation auxiliary parts
	RelTypePresProps   = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/presProps"
	RelTypeViewProps   = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/viewProps"
	RelTypeTableStyles = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/tableStyles"

	// Media relationships
	RelTypeImage = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"
	RelTypeAudio = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/audio"
	RelTypeVideo = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/video"
	RelTypeMedia = "http://schemas.microsoft.com/office/2007/relationships/media"

	// Hyperlinks
	RelTypeHyperlink = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"

	// Fonts
	RelTypeFont = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/font"

	// OLE objects
	RelTypeOLEObject = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject"

	// Thumbnails
	RelTypeThumbnail = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail"

	// Styles
	RelTypeStyles = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"
)

Relationship type constants (Relationship Types)

View Source
const (
	NamespaceOPCPackage      = "http://schemas.openxmlformats.org/package/2006/content-types"
	NamespaceRelationships   = "http://schemas.openxmlformats.org/package/2006/relationships"
	NamespaceRelationshipsNs = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
)

OPC namespaces

View Source
const (
	PathContentTypes = "[Content_Types].xml"
	PathRelsDir      = "_rels"
	PathRelsFile     = ".rels"
)

OPC default paths

View Source
const DefaultMaxPartBytes int64 = 100 << 20 // 100 MB

DefaultMaxPartBytes is the default per-part decompressed size ceiling applied when opening a package. A part larger than this is rejected with ErrPartTooLarge rather than allocated, bounding memory use on untrusted input (CLAUDE.md §7). Callers override via WithMaxPartBytes; a value <= 0 disables the bound.

View Source
const XMLDeclaration = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>`

XMLDeclaration is the standard XML declaration header used in all XML files within an OPC package.

Variables

View Source
var ContentTypeToExtension = map[string]string{
	ContentTypePNG:           ".png",
	ContentTypeJPEG:          ".jpg",
	ContentTypeGIF:           ".gif",
	ContentTypeBMP:           ".bmp",
	ContentTypeTIFF:          ".tiff",
	ContentTypeWMF:           ".wmf",
	ContentTypeEMF:           ".emf",
	ContentTypeSVG:           ".svg",
	ContentTypeWAV:           ".wav",
	ContentTypeMP3:           ".mp3",
	ContentTypeMIDI:          ".mid",
	ContentTypeMP4:           ".mp4",
	ContentTypeAVI:           ".avi",
	ContentTypeWMV:           ".wmv",
	ContentTypeRelationships: ".rels",
	ContentTypeXML:           ".xml",
}

ContentTypeToExtension maps content types to their canonical file extensions.

View Source
var DefaultContentTypes = map[string]string{
	".xml":   ContentTypeXML,
	".rels":  ContentTypeRelationships,
	".png":   ContentTypePNG,
	".jpg":   ContentTypeJPEG,
	".jpeg":  ContentTypeJPEG,
	".gif":   ContentTypeGIF,
	".bmp":   ContentTypeBMP,
	".tiff":  ContentTypeTIFF,
	".tif":   ContentTypeTIFF,
	".wmf":   ContentTypeWMF,
	".emf":   ContentTypeEMF,
	".svg":   ContentTypeSVG,
	".wav":   ContentTypeWAV,
	".mp3":   ContentTypeMP3,
	".mid":   ContentTypeMIDI,
	".midi":  ContentTypeMIDI,
	".mp4":   ContentTypeMP4,
	".avi":   ContentTypeAVI,
	".wmv":   ContentTypeWMV,
	".font":  ContentTypeFont,
	".odttf": ContentTypeFont,
}

DefaultContentTypes maps file extensions to their default content types.

View Source
var ErrPartTooLarge = errors.New("opc: part exceeds maximum size")

ErrPartTooLarge is returned when a package part's decompressed size exceeds the configured per-part limit. It wraps via %w so callers can errors.Is it.

View Source
var ErrUnsafePartPath = errors.New("opc: unsafe part path")

ErrUnsafePartPath is returned when a ZIP entry's path escapes the package root — an absolute path or one containing a ".." segment (a zip-slip attempt). Such entries are rejected at parse time (CLAUDE.md §7).

Functions

func ComputeHash

func ComputeHash(data []byte) string

ComputeHash computes a hash of the given data. Note: this is a fast non-cryptographic FNV-1a hash, not SHA-256. It avoids an extra import; callers that need cryptographic strength should use crypto/sha256.

func GetContentTypeByExtension

func GetContentTypeByExtension(ext string) string

GetContentTypeByExtension returns the content type for the given file extension.

func GetExtensionByContentType

func GetExtensionByContentType(contentType string) string

GetExtensionByContentType returns the file extension for the given content type.

func IsImageContentType

func IsImageContentType(contentType string) bool

IsImageContentType reports whether the content type represents an image.

func IsImmutableContentType

func IsImmutableContentType(contentType string) bool

IsImmutableContentType reports whether the content type represents an immutable resource. Immutable resources can be shared via zero-copy without deep-copying their data.

func IsLargeBinaryContentType

func IsLargeBinaryContentType(contentType string) bool

IsLargeBinaryContentType reports whether the content type represents a large binary payload. Used to determine whether zero-copy optimization is worthwhile.

func IsMediaContentType

func IsMediaContentType(contentType string) bool

IsMediaContentType reports whether the content type represents audio or video.

func IsValidPackURI

func IsValidPackURI(uri string) bool

IsValidPackURI reports whether the given string is a valid pack URI.

func NormalizeURI

func NormalizeURI(uri string) string

NormalizeURI normalizes a URI string.

func NormalizeZipPath

func NormalizeZipPath(path string) string

NormalizeZipPath normalizes an internal ZIP path. Designed specifically for paths read from ZIP archives, handling Windows backslash issues. Unlike NormalizeURI, this function does not add a leading slash — it preserves the relative form.

Types

type BytesReader

type BytesReader struct {
	// contains filtered or unexported fields
}

BytesReader is a simple io.Reader implementation over a byte slice.

func NewBytesReader

func NewBytesReader(data []byte) *BytesReader

NewBytesReader creates a new BytesReader.

func (*BytesReader) Read

func (r *BytesReader) Read(p []byte) (n int, err error)

Read implements io.Reader.

type BytesSource

type BytesSource struct {
	// contains filtered or unexported fields
}

BytesSource is a data source backed by an in-memory byte slice.

func NewBytesSource

func NewBytesSource(data []byte) *BytesSource

NewBytesSource creates a data source from a byte slice.

func (*BytesSource) Open

func (s *BytesSource) Open() (io.ReadCloser, error)

Open returns a reader over the byte slice.

func (*BytesSource) Size

func (s *BytesSource) Size() int64

Size returns the data size.

type ConcurrentZipCollector

type ConcurrentZipCollector struct {
	// contains filtered or unexported fields
}

ConcurrentZipCollector collects part data from a channel and writes it to a ZIP archive concurrently.

func NewConcurrentZipCollector

func NewConcurrentZipCollector(w io.Writer, bufferSize int) *ConcurrentZipCollector

NewConcurrentZipCollector creates a concurrent ZIP collector.

func (*ConcurrentZipCollector) Close

func (c *ConcurrentZipCollector) Close() error

Close signals that no more data will be submitted and waits for the collector to finish.

func (*ConcurrentZipCollector) DataChannel

func (c *ConcurrentZipCollector) DataChannel() PartDataChannel

DataChannel returns the data channel (for external producers).

func (*ConcurrentZipCollector) Start

func (c *ConcurrentZipCollector) Start()

Start launches the collector goroutine.

func (*ConcurrentZipCollector) Submit

func (c *ConcurrentZipCollector) Submit(data *PartData) error

Submit submits part data to the collector.

func (*ConcurrentZipCollector) SubmitBytes

func (c *ConcurrentZipCollector) SubmitBytes(path string, data []byte) error

SubmitBytes submits a byte slice as a ZIP entry.

func (*ConcurrentZipCollector) Wait

func (c *ConcurrentZipCollector) Wait() error

Wait waits for the collector to finish (alias for Close).

type ContentTypes

type ContentTypes struct {
	// contains filtered or unexported fields
}

ContentTypes represents the contents of [Content_Types].xml, which defines the content type of every part in the package.

func NewContentTypes

func NewContentTypes() *ContentTypes

NewContentTypes creates a new ContentTypes definition populated with the default mappings.

func (*ContentTypes) AddDefault

func (ct *ContentTypes) AddDefault(extension, contentType string)

AddDefault adds a default content type mapping for the given extension.

func (*ContentTypes) AddOverride

func (ct *ContentTypes) AddOverride(uri *PackURI, contentType string)

AddOverride adds a content type override for a specific URI.

func (*ContentTypes) Defaults

func (ct *ContentTypes) Defaults() map[string]string

Defaults returns a snapshot of all default content type mappings.

func (*ContentTypes) FromXML

func (ct *ContentTypes) FromXML(data []byte) error

FromXML parses content types from XML data.

func (*ContentTypes) GetContentType

func (ct *ContentTypes) GetContentType(uri *PackURI) string

GetContentType returns the content type for the given URI. Overrides take precedence over defaults.

func (*ContentTypes) GetDefault

func (ct *ContentTypes) GetDefault(extension string) string

GetDefault returns the default content type for the given extension.

func (*ContentTypes) GetOverride

func (ct *ContentTypes) GetOverride(uri *PackURI) string

GetOverride returns the content type override for the given URI.

func (*ContentTypes) Overrides

func (ct *ContentTypes) Overrides() map[string]string

Overrides returns a snapshot of all content type overrides.

func (*ContentTypes) RemoveOverride

func (ct *ContentTypes) RemoveOverride(uri *PackURI)

RemoveOverride removes the content type override for the given URI.

func (*ContentTypes) ToXML

func (ct *ContentTypes) ToXML() ([]byte, error)

ToXML serializes the content types to XML.

type ContentTypesStreamer

type ContentTypesStreamer struct {
	// contains filtered or unexported fields
}

ContentTypesStreamer is a streaming writer for ContentTypes.

func NewContentTypesStreamer

func NewContentTypesStreamer(ct *ContentTypes) *ContentTypesStreamer

NewContentTypesStreamer creates a streaming writer for ContentTypes.

func (*ContentTypesStreamer) StreamWriteTo

func (cs *ContentTypesStreamer) StreamWriteTo(w io.Writer) error

StreamWriteTo implements StreamWriter.

type CoreProperties

type CoreProperties struct {
	// contains filtered or unexported fields
}

CoreProperties represents the core properties (Dublin Core metadata) of a package.

func (*CoreProperties) Category

func (cp *CoreProperties) Category() string

Category returns the category.

func (*CoreProperties) ContentType

func (cp *CoreProperties) ContentType() string

ContentType returns the content type.

func (*CoreProperties) Created

func (cp *CoreProperties) Created() string

Created returns the created timestamp.

func (*CoreProperties) Creator

func (cp *CoreProperties) Creator() string

Creator returns the creator.

func (*CoreProperties) Description

func (cp *CoreProperties) Description() string

Description returns the description.

func (*CoreProperties) FromXML

func (cp *CoreProperties) FromXML(data []byte) error

FromXML parses core properties from XML data.

func (*CoreProperties) Keywords

func (cp *CoreProperties) Keywords() string

Keywords returns the keywords.

func (*CoreProperties) Language

func (cp *CoreProperties) Language() string

Language returns the language.

func (*CoreProperties) LastModifiedBy

func (cp *CoreProperties) LastModifiedBy() string

LastModifiedBy returns the name of the last modifier.

func (*CoreProperties) Modified

func (cp *CoreProperties) Modified() string

Modified returns the modified timestamp.

func (*CoreProperties) Revision

func (cp *CoreProperties) Revision() string

Revision returns the revision number.

func (*CoreProperties) SetCategory

func (cp *CoreProperties) SetCategory(category string)

SetCategory sets the category.

func (*CoreProperties) SetContentType

func (cp *CoreProperties) SetContentType(contentType string)

SetContentType sets the content type.

func (*CoreProperties) SetCreated

func (cp *CoreProperties) SetCreated(created string)

SetCreated sets the created timestamp.

func (*CoreProperties) SetCreator

func (cp *CoreProperties) SetCreator(creator string)

SetCreator sets the creator.

func (*CoreProperties) SetDescription

func (cp *CoreProperties) SetDescription(description string)

SetDescription sets the description.

func (*CoreProperties) SetKeywords

func (cp *CoreProperties) SetKeywords(keywords string)

SetKeywords sets the keywords.

func (*CoreProperties) SetLanguage

func (cp *CoreProperties) SetLanguage(language string)

SetLanguage sets the language.

func (*CoreProperties) SetLastModifiedBy

func (cp *CoreProperties) SetLastModifiedBy(lastModifiedBy string)

SetLastModifiedBy sets the name of the last modifier.

func (*CoreProperties) SetModified

func (cp *CoreProperties) SetModified(modified string)

SetModified sets the modified timestamp.

func (*CoreProperties) SetRevision

func (cp *CoreProperties) SetRevision(revision string)

SetRevision sets the revision number.

func (*CoreProperties) SetSubject

func (cp *CoreProperties) SetSubject(subject string)

SetSubject sets the subject.

func (*CoreProperties) SetTitle

func (cp *CoreProperties) SetTitle(title string)

SetTitle sets the title.

func (*CoreProperties) Subject

func (cp *CoreProperties) Subject() string

Subject returns the subject.

func (*CoreProperties) Title

func (cp *CoreProperties) Title() string

Title returns the title.

func (*CoreProperties) ToXML

func (cp *CoreProperties) ToXML() ([]byte, error)

ToXML serializes the core properties to XML.

type DefaultPartFactory

type DefaultPartFactory struct{}

DefaultPartFactory is the default part factory.

func (*DefaultPartFactory) CreatePart

func (f *DefaultPartFactory) CreatePart(uri *PackURI, contentType string, blob []byte) (*Part, error)

CreatePart implements PartFactory.

type OpenOption

type OpenOption func(*openConfig)

OpenOption customizes how a package is opened. Both the eager (Open/OpenFile) and streaming (OpenStream/OpenStreamFromReader) entry points accept these.

func WithMaxPartBytes

func WithMaxPartBytes(n int64) OpenOption

WithMaxPartBytes sets the per-part decompressed size ceiling. A value <= 0 disables the bound (unlimited).

type PackURI

type PackURI struct {
	// contains filtered or unexported fields
}

PackURI represents a URI within a package (e.g. /ppt/slides/slide1.xml). It follows the URI rules defined in the OPC specification.

func ContentTypesURI

func ContentTypesURI() *PackURI

ContentTypesURI returns the URI of [Content_Types].xml.

func NewPackURI

func NewPackURI(uri string) *PackURI

NewPackURI creates a new PackURI.

func PackageRelsURI

func PackageRelsURI() *PackURI

PackageRelsURI returns the URI of the package-level relationships file.

func RootURI

func RootURI() *PackURI

RootURI returns the package root URI.

func (*PackURI) BaseName

func (p *PackURI) BaseName() string

BaseName returns the base name of the URI without its extension. Example: /ppt/slides/slide1.xml -> slide1

func (*PackURI) Clone

func (p *PackURI) Clone() *PackURI

Clone returns a copy of this PackURI.

func (*PackURI) DirName

func (p *PackURI) DirName() string

DirName returns the parent directory path. Example: /ppt/slides/slide1.xml -> /ppt/slides

func (*PackURI) DirSegments

func (p *PackURI) DirSegments() []string

DirSegments returns the directory segments of the URI (excluding the file name).

func (*PackURI) Equals

func (p *PackURI) Equals(other *PackURI) bool

Equals reports whether two PackURIs are equal.

func (*PackURI) EqualsStr

func (p *PackURI) EqualsStr(uri string) bool

EqualsStr reports whether the URI equals the given string URI.

func (*PackURI) Extension

func (p *PackURI) Extension() string

Extension returns the file extension. Example: /ppt/slides/slide1.xml -> .xml

func (*PackURI) FileName

func (p *PackURI) FileName() string

FileName returns the file name including the extension. Example: /ppt/slides/slide1.xml -> slide1.xml

func (*PackURI) IsAbsolute

func (p *PackURI) IsAbsolute() bool

IsAbsolute reports whether the URI is an absolute path.

func (*PackURI) IsPackageRels

func (p *PackURI) IsPackageRels() bool

IsPackageRels reports whether this URI refers to the package-level relationships file.

func (*PackURI) IsRelationshipsPart

func (p *PackURI) IsRelationshipsPart() bool

IsRelationshipsPart reports whether this URI refers to a relationships part.

func (*PackURI) Join

func (p *PackURI) Join(relativePath string) *PackURI

Join resolves a relative path against this URI and returns a new PackURI.

func (PackURI) MarshalText

func (p PackURI) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (*PackURI) MemberName

func (p *PackURI) MemberName() string

MemberName returns the member name relative to the package root (suitable for use in ZIP archives). The leading / is removed.

func (*PackURI) RelPath

func (p *PackURI) RelPath() string

RelPath returns the relative path (used as a relationship target).

func (*PackURI) RelPathFrom

func (p *PackURI) RelPathFrom(other *PackURI) string

RelPathFrom computes the relative path from another URI to this URI.

func (*PackURI) RelationshipsURI

func (p *PackURI) RelationshipsURI() *PackURI

RelationshipsURI returns the URI of the relationships file for this part. Example: /ppt/slides/slide1.xml -> /ppt/slides/_rels/slide1.xml.rels

func (*PackURI) Segments

func (p *PackURI) Segments() []string

Segments returns the individual path segments of the URI.

func (*PackURI) SourceURI

func (p *PackURI) SourceURI() *PackURI

SourceURI returns the source part URI from a relationships file path. Example: /ppt/slides/_rels/slide1.xml.rels -> /ppt/slides/slide1.xml

func (*PackURI) String

func (p *PackURI) String() string

String returns the URI string representation.

func (*PackURI) URI

func (p *PackURI) URI() string

URI returns the raw URI string.

func (*PackURI) UnmarshalText

func (p *PackURI) UnmarshalText(data []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type Package

type Package struct {
	// contains filtered or unexported fields
}

Package represents an OPC package (e.g. a PPTX file).

func NewPackage

func NewPackage() *Package

NewPackage creates a new, empty OPC package.

func Open

func Open(r io.ReaderAt, size int64, opts ...OpenOption) (*Package, error)

Open opens an OPC package from a ZIP stream. By default each part is bounded to DefaultMaxPartBytes and unsafe (zip-slip) entry paths are rejected at parse time (CLAUDE.md §7); WithMaxPartBytes overrides the bound.

func OpenFile

func OpenFile(path string, opts ...OpenOption) (*Package, error)

OpenFile opens an OPC package from a file path.

func (*Package) AddPart

func (p *Package) AddPart(part *Part) error

AddPart adds a part to the package.

func (*Package) AddRelationship

func (p *Package) AddRelationship(relType, targetURI string, isExternal bool) (*Relationship, error)

AddRelationship adds a package-level relationship.

func (*Package) AllParts

func (p *Package) AllParts() []*Part

AllParts returns all parts.

func (*Package) Clone

func (p *Package) Clone() *Package

Clone clones the entire package (smart copy: zero-copy for static resources, deep copy for dynamic ones).

func (*Package) CloneDeep

func (p *Package) CloneDeep() *Package

CloneDeep clones the entire package using a full deep copy (no zero-copy sharing). Use this when a fully independent replica is required.

func (*Package) Close

func (p *Package) Close() error

Close closes the package and releases its resources.

func (*Package) ContainsPart

func (p *Package) ContainsPart(uri *PackURI) bool

ContainsPart reports whether a part with the given URI exists.

func (*Package) ContentTypes

func (p *Package) ContentTypes() *ContentTypes

ContentTypes returns the content type definitions.

func (*Package) CoreProperties

func (p *Package) CoreProperties() *CoreProperties

CoreProperties returns the core properties.

func (*Package) CreatePart

func (p *Package) CreatePart(uri *PackURI, contentType string, blob []byte) (*Part, error)

CreatePart creates and adds a new part.

func (*Package) CreatePartFromReader

func (p *Package) CreatePartFromReader(uri *PackURI, contentType string, r io.Reader) (*Part, error)

CreatePartFromReader creates and adds a part from a Reader.

func (*Package) CreatePartFromXML

func (p *Package) CreatePartFromXML(uri *PackURI, contentType string, v interface{}) (*Part, error)

CreatePartFromXML creates and adds a part from an XML struct.

func (*Package) DirtyParts

func (p *Package) DirtyParts() []*Part

DirtyParts returns all modified parts.

func (*Package) GetPart

func (p *Package) GetPart(uri *PackURI) *Part

GetPart returns the part with the given URI.

func (*Package) GetPartByRelType

func (p *Package) GetPartByRelType(relType string) *Part

GetPartByRelType returns the target part of the first package-level relationship with the given type.

func (*Package) GetPartByStr

func (p *Package) GetPartByStr(uri string) *Part

GetPartByStr returns the part with the given string URI.

func (*Package) GetPartsByType

func (p *Package) GetPartsByType(contentType string) []*Part

GetPartsByType returns all parts with the given content type.

func (*Package) GetRelationship

func (p *Package) GetRelationship(rID string) *Relationship

GetRelationship returns the package-level relationship with the given rID.

func (*Package) GetRelationshipsByType

func (p *Package) GetRelationshipsByType(relType string) []*Relationship

GetRelationshipsByType returns all package-level relationships of the given type.

func (*Package) PartCount

func (p *Package) PartCount() int

PartCount returns the number of parts.

func (*Package) PartURIs

func (p *Package) PartURIs() []*PackURI

PartURIs returns all part URIs.

func (*Package) Parts

func (p *Package) Parts() *PartCollection

Parts returns the part collection.

func (*Package) Relationships

func (p *Package) Relationships() *Relationships

Relationships returns the package-level relationships.

func (*Package) RemovePart

func (p *Package) RemovePart(uri *PackURI) error

RemovePart removes a part from the package.

func (*Package) ResolveRelationship

func (p *Package) ResolveRelationship(source *Part, relType string) *Part

ResolveRelationship resolves the target part of the first relationship of the given type from source.

func (*Package) Save

func (p *Package) Save(w io.Writer) error

Save writes the package as a ZIP archive to w.

func (*Package) SaveFile

func (p *Package) SaveFile(path string) error

SaveFile saves the package to a file.

func (*Package) SaveToBytes

func (p *Package) SaveToBytes() ([]byte, error)

SaveToBytes saves the package to a byte slice.

func (*Package) SetCoreProperties

func (p *Package) SetCoreProperties(props *CoreProperties)

SetCoreProperties sets the core properties.

type Part

type Part struct {
	// contains filtered or unexported fields
}

Part represents a single part within a package.

func NewPart

func NewPart(uri *PackURI, contentType string, blob []byte) *Part

NewPart creates a new part.

func NewPartFromReader

func NewPartFromReader(uri *PackURI, contentType string, r io.Reader) (*Part, error)

NewPartFromReader creates a part by reading all content from r.

func NewSharedPart

func NewSharedPart(uri *PackURI, contentType string, sharedBlob []byte) *Part

NewSharedPart creates a part that shares its data (zero-copy, for immutable resources). The caller must guarantee that sharedBlob will not be modified for the lifetime of the Part.

func (*Part) AddRelationship

func (p *Part) AddRelationship(relType, targetURI string, isExternal bool) (*Relationship, error)

AddRelationship adds a relationship to this part.

func (*Part) Blob

func (p *Part) Blob() []byte

Blob returns the raw content. For immutable resources it returns the shared read-only slice; otherwise it returns the owned copy.

func (*Part) Clone

func (p *Part) Clone() *Part

Clone returns a deep copy of the part (suitable for mutable content).

func (*Part) CloneShared

func (p *Part) CloneShared() *Part

CloneShared returns a zero-copy clone of the part (for immutable resources). The caller must ensure the part's content will never be modified.

func (*Part) ContentType

func (p *Part) ContentType() string

ContentType returns the content type.

func (*Part) GetRelatedPart

func (p *Part) GetRelatedPart(rID string) *PackURI

GetRelatedPart returns the target URI of the relationship with the given rID. A Package context is required to resolve the URI to an actual Part.

func (*Part) HasRelationships

func (p *Part) HasRelationships() bool

HasRelationships reports whether the part has any relationships.

func (*Part) IsDirty

func (p *Part) IsDirty() bool

IsDirty reports whether the part has been modified.

func (*Part) IsImmutable

func (p *Part) IsImmutable() bool

IsImmutable reports whether the part is an immutable resource.

func (*Part) LoadRelationships

func (p *Part) LoadRelationships(data []byte) error

LoadRelationships loads relationships from XML data.

func (*Part) MarshalToBlob

func (p *Part) MarshalToBlob(v interface{}) error

MarshalToBlob marshals v as XML and stores the result in the blob.

func (*Part) PartURI

func (p *Part) PartURI() *PackURI

PartURI returns the part URI.

func (*Part) Reader

func (p *Part) Reader() io.Reader

Reader returns an io.Reader over the part content.

func (*Part) Relationships

func (p *Part) Relationships() *Relationships

Relationships returns the relationship collection for this part.

func (*Part) RelationshipsBlob

func (p *Part) RelationshipsBlob() ([]byte, error)

RelationshipsBlob returns the serialized XML of the relationships.

func (*Part) RelationshipsURI

func (p *Part) RelationshipsURI() *PackURI

RelationshipsURI returns the URI of the relationships file for this part.

func (*Part) RemoveRelationship

func (p *Part) RemoveRelationship(rID string) error

RemoveRelationship removes a relationship from this part.

func (*Part) SetBlob

func (p *Part) SetBlob(blob []byte)

SetBlob sets the content, triggering a copy-on-write by releasing the shared reference.

func (*Part) SetBlobFromReader

func (p *Part) SetBlobFromReader(r io.Reader) error

SetBlobFromReader sets the content from a Reader.

func (*Part) SetContentType

func (p *Part) SetContentType(ct string)

SetContentType sets the content type.

func (*Part) SetDirty

func (p *Part) SetDirty(dirty bool)

SetDirty sets the dirty flag.

func (*Part) SetImmutable

func (p *Part) SetImmutable(immutable bool)

SetImmutable marks the part as an immutable resource.

func (*Part) Size

func (p *Part) Size() int

Size returns the content size in bytes.

func (*Part) UnmarshalBlob

func (p *Part) UnmarshalBlob(v interface{}) error

UnmarshalBlob unmarshals the part's blob as XML into v.

type PartCollection

type PartCollection struct {
	// contains filtered or unexported fields
}

PartCollection is an ordered collection of parts.

func NewPartCollection

func NewPartCollection() *PartCollection

NewPartCollection creates a new, empty PartCollection.

func (*PartCollection) Add

func (c *PartCollection) Add(part *Part) error

Add adds a part to the collection.

func (*PartCollection) All

func (c *PartCollection) All() []*Part

All returns all parts in insertion order.

func (*PartCollection) Clear

func (c *PartCollection) Clear()

Clear removes all parts from the collection.

func (*PartCollection) Contains

func (c *PartCollection) Contains(uri *PackURI) bool

Contains reports whether a part with the given URI exists.

func (*PartCollection) Count

func (c *PartCollection) Count() int

Count returns the number of parts.

func (*PartCollection) DirtyParts

func (c *PartCollection) DirtyParts() []*Part

DirtyParts returns all modified parts.

func (*PartCollection) Get

func (c *PartCollection) Get(uri *PackURI) *Part

Get returns the part with the given URI.

func (*PartCollection) GetByStr

func (c *PartCollection) GetByStr(uri string) *Part

GetByStr returns the part with the given string URI.

func (*PartCollection) GetByType

func (c *PartCollection) GetByType(contentType string) []*Part

GetByType returns all parts with the given content type.

func (*PartCollection) Remove

func (c *PartCollection) Remove(uri *PackURI) error

Remove removes the part with the given URI.

func (*PartCollection) URIs

func (c *PartCollection) URIs() []*PackURI

URIs returns all part URIs in insertion order.

type PartData

type PartData struct {
	URI         string     // Part URI
	Path        string     // ZIP internal path
	ContentType string     // Content type
	Data        []byte     // Data payload
	Source      PartSource // Data source (for lazy loading)
	Error       error      // Write error, if any
}

PartData carries part data through a channel.

type PartDataChannel

type PartDataChannel chan *PartData

PartDataChannel is the channel type for PartData.

func NewPartDataChannel

func NewPartDataChannel(bufferSize int) PartDataChannel

NewPartDataChannel creates a buffered PartData channel.

type PartFactory

type PartFactory interface {
	// CreatePart creates a part.
	CreatePart(uri *PackURI, contentType string, blob []byte) (*Part, error)
}

PartFactory is the interface for creating parts.

type PartIterator

type PartIterator struct {
	// contains filtered or unexported fields
}

PartIterator iterates over the parts of a StreamPackage.

func (*PartIterator) FilterByType

func (it *PartIterator) FilterByType(contentType string) *PartIterator

FilterByType restricts the iterator to parts with the given content type.

func (*PartIterator) Next

func (it *PartIterator) Next() bool

Next advances to the next matching part and reports whether one was found.

func (*PartIterator) Open

func (it *PartIterator) Open() (io.ReadCloser, error)

Open opens the content stream of the current part.

func (*PartIterator) Part

func (it *PartIterator) Part() *StreamPart

Part returns the current part.

type PartSource

type PartSource interface {
	Open() (io.ReadCloser, error)
	Size() int64
}

PartSource is the interface for a part's data source.

type ReaderSource

type ReaderSource struct {
	// contains filtered or unexported fields
}

ReaderSource is a data source backed by an io.Reader.

func NewReaderSource

func NewReaderSource(r io.Reader, size int64) *ReaderSource

NewReaderSource creates a data source from an io.Reader.

func (*ReaderSource) Open

func (s *ReaderSource) Open() (io.ReadCloser, error)

Open returns the underlying reader.

func (*ReaderSource) Size

func (s *ReaderSource) Size() int64

Size returns the data size.

type RelTypeCollection

type RelTypeCollection struct {
	// contains filtered or unexported fields
}

RelTypeCollection is a collection of relationships grouped by type.

func NewRelTypeCollection

func NewRelTypeCollection() *RelTypeCollection

NewRelTypeCollection creates a new, empty RelTypeCollection.

func (*RelTypeCollection) Add

func (c *RelTypeCollection) Add(rel *Relationship)

Add adds a relationship to the type collection.

func (*RelTypeCollection) GetByType

func (c *RelTypeCollection) GetByType(relType string) []*Relationship

GetByType returns all relationships of the given type.

func (*RelTypeCollection) Types

func (c *RelTypeCollection) Types() []string

Types returns all distinct relationship types in sorted order.

type Relatable

type Relatable interface {
	// PartURI returns the part's URI.
	PartURI() *PackURI
	// Relationships returns the part's relationship collection.
	Relationships() *Relationships
	// AddRelationship adds a relationship.
	AddRelationship(relType, targetURI string, isExternal bool) (*Relationship, error)
}

Relatable is the interface for parts that can hold relationships.

type Relationship

type Relationship struct {
	// contains filtered or unexported fields
}

Relationship represents a relationship between two parts.

func NewRelationship

func NewRelationship(rID, relType, targetURI string, isExternal bool, source *PackURI) *Relationship

NewRelationship creates a new relationship.

func (*Relationship) Equals

func (r *Relationship) Equals(other *Relationship) bool

Equals reports whether two relationships are equal.

func (*Relationship) IsExternal

func (r *Relationship) IsExternal() bool

IsExternal reports whether this is an external relationship.

func (*Relationship) RID

func (r *Relationship) RID() string

RID returns the relationship ID.

func (*Relationship) SetSource

func (r *Relationship) SetSource(source *PackURI)

SetSource sets the source URI.

func (*Relationship) SourceURI

func (r *Relationship) SourceURI() *PackURI

SourceURI returns the source URI.

func (*Relationship) TargetMode

func (r *Relationship) TargetMode() string

TargetMode returns the target mode string.

func (*Relationship) TargetRef

func (r *Relationship) TargetRef() string

TargetRef returns the target reference (relative or absolute). If a source part is set, returns the relative path from the source to the target.

func (*Relationship) TargetURI

func (r *Relationship) TargetURI() *PackURI

TargetURI returns the target URI.

func (*Relationship) Type

func (r *Relationship) Type() string

Type returns the relationship type.

type Relationships

type Relationships struct {
	// contains filtered or unexported fields
}

Relationships is an ordered collection of relationships.

func NewRelationships

func NewRelationships(sourceURI *PackURI) *Relationships

NewRelationships creates a new, empty Relationships collection.

func ParseRelationshipsFromXML

func ParseRelationshipsFromXML(data []byte, sourceURI *PackURI) (*Relationships, error)

ParseRelationshipsFromXML parses a Relationships collection from XML data.

func (*Relationships) Add

func (rs *Relationships) Add(rel *Relationship) error

Add adds a relationship to the collection.

func (*Relationships) AddNew

func (rs *Relationships) AddNew(relType, targetURI string, isExternal bool) (*Relationship, error)

AddNew creates and adds a new relationship, allocating an ID atomically.

func (*Relationships) All

func (rs *Relationships) All() []*Relationship

All returns all relationships in insertion order.

func (*Relationships) Clone

func (rs *Relationships) Clone() *Relationships

Clone returns a deep copy of the relationship collection.

func (*Relationships) Contains

func (rs *Relationships) Contains(rID string) bool

Contains reports whether a relationship with the given rID exists.

func (*Relationships) Count

func (rs *Relationships) Count() int

Count returns the number of relationships.

func (*Relationships) FromXML

func (rs *Relationships) FromXML(data []byte) error

FromXML parses the relationship collection from XML data.

func (*Relationships) Get

func (rs *Relationships) Get(rID string) *Relationship

Get returns the relationship with the given rID.

func (*Relationships) GetByTarget

func (rs *Relationships) GetByTarget(targetURI *PackURI) *Relationship

GetByTarget returns the relationship whose target matches the given URI.

func (*Relationships) GetByType

func (rs *Relationships) GetByType(relType string) []*Relationship

GetByType returns all relationships of the given type.

func (*Relationships) InitRIDCounter

func (rs *Relationships) InitRIDCounter()

InitRIDCounter initializes the rID counter from the existing relationships, ensuring newly allocated IDs do not clash with existing ones. Call this after loading relationships from XML.

func (*Relationships) MarshalXML

func (rs *Relationships) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML implements xml.Marshaler.

func (*Relationships) NextRID

func (rs *Relationships) NextRID() string

NextRID returns the next relationship ID without consuming it (idempotent preview). Multiple calls return the same value until AddNew actually uses it.

func (*Relationships) Remove

func (rs *Relationships) Remove(rID string) error

Remove removes the relationship with the given rID.

func (*Relationships) SetSourceURI

func (rs *Relationships) SetSourceURI(sourceURI *PackURI)

SetSourceURI sets the source URI and propagates it to all relationships.

func (*Relationships) SourceURI

func (rs *Relationships) SourceURI() *PackURI

SourceURI returns the source URI.

func (*Relationships) ToXML

func (rs *Relationships) ToXML() ([]byte, error)

ToXML serializes the relationship collection to XML.

func (*Relationships) UnmarshalXML

func (rs *Relationships) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error

UnmarshalXML implements xml.Unmarshaler.

type RelationshipsStreamer

type RelationshipsStreamer struct {
	// contains filtered or unexported fields
}

RelationshipsStreamer is a streaming writer for relationships.

func NewRelationshipsStreamer

func NewRelationshipsStreamer(rels *Relationships) *RelationshipsStreamer

NewRelationshipsStreamer creates a streaming writer for relationships.

func (*RelationshipsStreamer) StreamWriteTo

func (rs *RelationshipsStreamer) StreamWriteTo(w io.Writer) error

StreamWriteTo implements StreamWriter.

type ResourceDedupPool

type ResourceDedupPool struct {
	// contains filtered or unexported fields
}

ResourceDedupPool is a globally shared resource deduplication pool. It uses sync.Map for concurrent-safe deduplication.

func GetGlobalResourcePool

func GetGlobalResourcePool() *ResourceDedupPool

GetGlobalResourcePool returns the global resource deduplication pool.

func NewResourceDedupPool

func NewResourceDedupPool() *ResourceDedupPool

NewResourceDedupPool creates a new resource deduplication pool.

func (*ResourceDedupPool) Clear

func (p *ResourceDedupPool) Clear()

Clear removes all entries from the pool.

func (*ResourceDedupPool) Lookup

func (p *ResourceDedupPool) Lookup(hash string) (*ResourceEntry, bool)

Lookup looks up a resource by hash.

func (*ResourceDedupPool) Register

func (p *ResourceDedupPool) Register(uri string, data []byte) (isNew bool, existingURI string)

Register registers a resource and returns whether it is new. If the resource already exists, its reference count is incremented and false is returned.

func (*ResourceDedupPool) RegisterWithHash

func (p *ResourceDedupPool) RegisterWithHash(uri string, hash string, size int64) (isNew bool, existingURI string)

RegisterWithHash registers a resource using a pre-computed hash.

func (*ResourceDedupPool) Release

func (p *ResourceDedupPool) Release(hash string)

Release decrements the reference count for the resource with the given hash.

func (*ResourceDedupPool) Stats

func (p *ResourceDedupPool) Stats() (count int, totalSize int64)

Stats returns the count and total size of all registered resources.

type ResourceEntry

type ResourceEntry struct {
	URI       string // Part URI
	Hash      string // Content hash (SHA256)
	Size      int64  // Original size
	Reference int    // Reference count
}

ResourceEntry is an entry in the deduplication pool.

type ResourceHashKey

type ResourceHashKey string

ResourceHashKey is the key type used in the deduplication pool.

type ResourcePool

type ResourcePool struct {
	// contains filtered or unexported fields
}

ResourcePool is a global pool that manages shareable static resources. It uses a zero-copy strategy so multiple Packages can share the same binary data.

func GetGlobalPool

func GetGlobalPool() *ResourcePool

GetGlobalPool returns the global resource pool.

func (*ResourcePool) CreateSharedPart

func (p *ResourcePool) CreateSharedPart(uri *PackURI, contentType string, loader func() ([]byte, error)) (*Part, error)

CreateSharedPart creates a shared Part backed by the pool. If the resource is not already in the pool it is loaded via loader.

func (*ResourcePool) GetOrLoad

func (p *ResourcePool) GetOrLoad(uri string, contentType string, loader func() ([]byte, error)) ([]byte, error)

GetOrLoad returns the cached resource for the given URI, loading it via loader if absent. The loader is called at most once per unique URI.

func (*ResourcePool) Prefetch

func (p *ResourcePool) Prefetch(resources map[string]func() ([]byte, error)) error

Prefetch pre-loads a set of resources into the pool to avoid load latency at render time.

func (*ResourcePool) Release

func (p *ResourcePool) Release(uri string)

Release decrements the reference count for the given URI. When the count reaches zero the resource is removed from the pool.

func (*ResourcePool) ReleaseAll

func (p *ResourcePool) ReleaseAll()

ReleaseAll removes all resources from the pool. Use with care.

func (*ResourcePool) Stats

func (p *ResourcePool) Stats() map[string]int

Stats returns resource pool statistics.

type StreamPackage

type StreamPackage struct {
	// contains filtered or unexported fields
}

StreamPackage is a streaming OPC package that supports lazy loading and streaming writes.

func NewStreamPackage

func NewStreamPackage() *StreamPackage

NewStreamPackage creates a new, empty streaming package.

func OpenStream

func OpenStream(path string, opts ...OpenOption) (*StreamPackage, error)

OpenStream opens an OPC package from a file path using streaming (lazy loading). The file handle remains open to support on-demand part loading.

func OpenStreamFromReader

func OpenStreamFromReader(r io.ReaderAt, size int64, opts ...OpenOption) (*StreamPackage, error)

OpenStreamFromReader opens an OPC package from an io.ReaderAt using streaming. Note: the caller is responsible for keeping the ReaderAt valid for the lifetime of the package.

func (*StreamPackage) AddMediaPartWithDedup

func (p *StreamPackage) AddMediaPartWithDedup(uri *PackURI, contentType string, data []byte) (actualURI *PackURI, isNew bool, err error)

AddMediaPartWithDedup adds a media part with deduplication. If the resource already exists, returns the existing part's URI without creating a new part.

func (*StreamPackage) AddPart

func (p *StreamPackage) AddPart(part *StreamPart) error

AddPart adds a streaming part to the package.

func (*StreamPackage) AddRelationship

func (p *StreamPackage) AddRelationship(relType, targetURI string, isExternal bool) (*Relationship, error)

AddRelationship adds a package-level relationship.

func (*StreamPackage) AllParts

func (p *StreamPackage) AllParts() []*StreamPart

AllParts returns all parts in insertion order.

func (*StreamPackage) ClearMediaDedupPool

func (p *StreamPackage) ClearMediaDedupPool()

ClearMediaDedupPool clears the media resource deduplication pool.

func (*StreamPackage) Close

func (p *StreamPackage) Close() error

Close closes the package and releases its resources.

func (*StreamPackage) ConcurrentStreamSave

func (p *StreamPackage) ConcurrentStreamSave(w io.Writer, workerCount, bufferSize int) error

ConcurrentStreamSave saves the package concurrently using a goroutine collector. workerCount controls the number of concurrent worker goroutines. bufferSize controls the channel buffer size.

func (*StreamPackage) ConcurrentStreamSaveFile

func (p *StreamPackage) ConcurrentStreamSaveFile(path string, workerCount, bufferSize int) error

ConcurrentStreamSaveFile saves the package to a file using concurrent streaming.

func (*StreamPackage) ContainsPart

func (p *StreamPackage) ContainsPart(uri *PackURI) bool

ContainsPart reports whether a part with the given URI exists.

func (*StreamPackage) ContentTypes

func (p *StreamPackage) ContentTypes() *ContentTypes

ContentTypes returns the content type definitions.

func (*StreamPackage) CoreProperties

func (p *StreamPackage) CoreProperties() *CoreProperties

CoreProperties returns the core properties.

func (*StreamPackage) CreatePartFromBytes

func (p *StreamPackage) CreatePartFromBytes(uri *PackURI, contentType string, data []byte) (*StreamPart, error)

CreatePartFromBytes creates a part from a byte slice, loading it immediately into memory.

func (*StreamPackage) CreateStreamPart

func (p *StreamPackage) CreateStreamPart(uri *PackURI, contentType string, source PartSource) (*StreamPart, error)

CreateStreamPart creates and adds a streaming part.

func (*StreamPackage) GetMediaDedupStats

func (p *StreamPackage) GetMediaDedupStats() (count int, totalSize int64)

GetMediaDedupStats returns deduplication statistics for media resources.

func (*StreamPackage) GetPart

func (p *StreamPackage) GetPart(uri *PackURI) *StreamPart

GetPart returns the part with the given URI (content is loaded on demand).

func (*StreamPackage) GetPartByRelType

func (p *StreamPackage) GetPartByRelType(relType string) *StreamPart

GetPartByRelType returns the target part of the first relationship of the given type.

func (*StreamPackage) GetPartByStr

func (p *StreamPackage) GetPartByStr(uri string) *StreamPart

GetPartByStr returns the part with the given string URI.

func (*StreamPackage) GetPartsByType

func (p *StreamPackage) GetPartsByType(contentType string) []*StreamPart

GetPartsByType returns all parts with the given content type.

func (*StreamPackage) NewPartIterator

func (p *StreamPackage) NewPartIterator() *PartIterator

NewPartIterator creates a part iterator for the package.

func (*StreamPackage) PartCount

func (p *StreamPackage) PartCount() int

PartCount returns the number of parts.

func (*StreamPackage) PartURIs

func (p *StreamPackage) PartURIs() []*PackURI

PartURIs returns all part URIs in insertion order.

func (*StreamPackage) RegisterMediaWithDedup

func (p *StreamPackage) RegisterMediaWithDedup(uri string, data []byte) (isNew bool, existingURI string)

RegisterMediaWithDedup registers a media resource and deduplicates it. Returns isNew (true if this is the first registration) and existingURI (the canonical URI).

func (*StreamPackage) Relationships

func (p *StreamPackage) Relationships() *Relationships

Relationships returns the package-level relationships.

func (*StreamPackage) RemovePart

func (p *StreamPackage) RemovePart(uri *PackURI) error

RemovePart removes a part from the package.

func (*StreamPackage) SetCoreProperties

func (p *StreamPackage) SetCoreProperties(props *CoreProperties)

SetCoreProperties sets the core properties.

func (*StreamPackage) StreamSave

func (p *StreamPackage) StreamSave(w io.Writer) error

StreamSave writes the package as a ZIP archive to w using streaming.

func (*StreamPackage) StreamSaveFile

func (p *StreamPackage) StreamSaveFile(path string) error

StreamSaveFile writes the package to a file using streaming.

type StreamPart

type StreamPart struct {
	// contains filtered or unexported fields
}

StreamPart is a streaming part that supports lazy loading.

func NewStreamPart

func NewStreamPart(uri *PackURI, contentType string, source PartSource) *StreamPart

NewStreamPart creates a streaming part.

func (*StreamPart) Blob

func (p *StreamPart) Blob() ([]byte, error)

Blob returns the content, loading it first if necessary.

func (*StreamPart) Clone

func (p *StreamPart) Clone() *StreamPart

Clone returns a deep copy of the part.

func (*StreamPart) ContentType

func (p *StreamPart) ContentType() string

ContentType returns the content type.

func (*StreamPart) HasRelationships

func (p *StreamPart) HasRelationships() bool

HasRelationships reports whether the part has any relationships.

func (*StreamPart) IsDirty

func (p *StreamPart) IsDirty() bool

IsDirty reports whether the part has been modified.

func (*StreamPart) IsLoaded

func (p *StreamPart) IsLoaded() bool

IsLoaded reports whether the content has been loaded into memory.

func (*StreamPart) Load

func (p *StreamPart) Load() error

Load reads the part content into memory.

func (*StreamPart) LoadRelationships

func (p *StreamPart) LoadRelationships(data []byte) error

LoadRelationships loads relationships from XML data.

func (*StreamPart) Open

func (p *StreamPart) Open() (io.ReadCloser, error)

Open opens the part content stream.

func (*StreamPart) PartURI

func (p *StreamPart) PartURI() *PackURI

PartURI returns the part URI.

func (*StreamPart) Relationships

func (p *StreamPart) Relationships() *Relationships

Relationships returns the relationship collection.

func (*StreamPart) RelationshipsBlob

func (p *StreamPart) RelationshipsBlob() ([]byte, error)

RelationshipsBlob returns the serialized XML of the relationships.

func (*StreamPart) RelationshipsURI

func (p *StreamPart) RelationshipsURI() *PackURI

RelationshipsURI returns the URI of the relationships file for this part.

func (*StreamPart) SetBlob

func (p *StreamPart) SetBlob(data []byte)

SetBlob sets the content.

func (*StreamPart) SetBlobFromReader

func (p *StreamPart) SetBlobFromReader(r io.Reader) error

SetBlobFromReader sets the content from a Reader.

func (*StreamPart) SetContentType

func (p *StreamPart) SetContentType(ct string)

SetContentType sets the content type.

func (*StreamPart) SetDirty

func (p *StreamPart) SetDirty(dirty bool)

SetDirty sets the dirty flag.

func (*StreamPart) Size

func (p *StreamPart) Size() int64

Size returns the content size.

func (*StreamPart) UnmarshalBlob

func (p *StreamPart) UnmarshalBlob(v any) error

UnmarshalBlob unmarshals the blob as XML into v, loading it first if necessary.

type StreamWriter

type StreamWriter interface {
	StreamWriteTo(w io.Writer) error
}

StreamWriter is the interface for streaming writers.

type StreamingZipWriter

type StreamingZipWriter struct {
	// contains filtered or unexported fields
}

StreamingZipWriter is a streaming ZIP writer.

func NewStreamingZipWriter

func NewStreamingZipWriter(w io.Writer) *StreamingZipWriter

NewStreamingZipWriter creates a streaming ZIP writer.

func (*StreamingZipWriter) Close

func (sw *StreamingZipWriter) Close() error

Close closes the underlying ZIP writer.

func (*StreamingZipWriter) Create

func (sw *StreamingZipWriter) Create(path string) (io.Writer, error)

Create creates a ZIP entry and returns a writer for it.

func (*StreamingZipWriter) WriteBytes

func (sw *StreamingZipWriter) WriteBytes(path string, data []byte) error

WriteBytes writes a byte slice to a ZIP entry.

func (*StreamingZipWriter) WriteFromReader

func (sw *StreamingZipWriter) WriteFromReader(path string, reader io.Reader) error

WriteFromReader streams a ZIP entry from a Reader.

func (*StreamingZipWriter) WriteFromStreamer

func (sw *StreamingZipWriter) WriteFromStreamer(path string, streamer StreamWriter) error

WriteFromStreamer streams a ZIP entry using a StreamWriter.

func (*StreamingZipWriter) WriteFromXMLStreamer

func (sw *StreamingZipWriter) WriteFromXMLStreamer(path string, streamer XMLStreamer) error

WriteFromXMLStreamer streams a ZIP entry using an XMLStreamer (automatically prepends the XML declaration).

func (*StreamingZipWriter) WriteStreamPart

func (sw *StreamingZipWriter) WriteStreamPart(part *StreamPart) error

WriteStreamPart streams a StreamPart to the ZIP archive.

func (*StreamingZipWriter) WriteXML

func (sw *StreamingZipWriter) WriteXML(path string, data []byte) error

WriteXML writes XML data to a ZIP entry, automatically prepending the XML declaration.

type XContentTypes

type XContentTypes struct {
	XMLName   xml.Name    `xml:"Types"`
	Xmlns     string      `xml:"xmlns,attr"`
	Defaults  []XDefault  `xml:"Default"`
	Overrides []XOverride `xml:"Override"`
}

XContentTypes is the root element for XML serialization of content types.

type XCoreProperties

type XCoreProperties struct {
	XMLName        xml.Name   `xml:"coreProperties"`
	XmlnsDc        string     `xml:"xmlns:dc,attr"`
	XmlnsDcterms   string     `xml:"xmlns:dcterms,attr"`
	XmlnsDcmitype  string     `xml:"xmlns:dcmitype,attr"`
	XmlnsXsi       string     `xml:"xmlns:xsi,attr"`
	XmlnsCore      string     `xml:"xmlns,attr"`
	Title          string     `xml:"dc:title"`
	Creator        string     `xml:"dc:creator"`
	Subject        string     `xml:"dc:subject"`
	Description    string     `xml:"dc:description"`
	Keywords       *XKeywords `xml:"cp:keywords"`
	Created        *XDate     `xml:"dcterms:created"`
	Modified       *XDate     `xml:"dcterms:modified"`
	LastModifiedBy string     `xml:"cp:lastModifiedBy"`
	Revision       string     `xml:"cp:revision"`
	Category       string     `xml:"cp:category"`
	ContentType    string     `xml:"cp:contentType"`
}

XCoreProperties is the XML representation of core properties.

type XDate

type XDate struct {
	Type  string `xml:"xsi:type,attr"`
	Value string `xml:",chardata"`
}

XDate is the XML representation of a date element.

type XDefault

type XDefault struct {
	Extension   string `xml:"Extension,attr"`
	ContentType string `xml:"ContentType,attr"`
}

XDefault is the XML representation of a default content type entry.

type XKeywords

type XKeywords struct {
	Value string `xml:",chardata"`
}

XKeywords is the XML representation of the keywords element.

type XMLStreamer

type XMLStreamer interface {
	StreamXML(enc *xml.Encoder) error
}

XMLStreamer is the interface for XML streaming writers.

type XOverride

type XOverride struct {
	PartName    string `xml:"PartName,attr"`
	ContentType string `xml:"ContentType,attr"`
}

XOverride is the XML representation of a content type override entry.

type XRelationship

type XRelationship struct {
	ID         string `xml:"Id,attr"`
	Type       string `xml:"Type,attr"`
	Target     string `xml:"Target,attr"`
	TargetMode string `xml:"TargetMode,attr,omitempty"`
}

XRelationship is the XML element for a single relationship.

type XRelationships

type XRelationships struct {
	XMLName       xml.Name        `xml:"Relationships"`
	Xmlns         string          `xml:"xmlns,attr"`
	Relationships []XRelationship `xml:"Relationship"`
}

XRelationships is the XML root element for relationships.

type ZipFileSource

type ZipFileSource struct {
	// contains filtered or unexported fields
}

ZipFileSource is a data source backed by an entry in a ZIP archive.

func NewZipFileSource

func NewZipFileSource(f *zip.File) *ZipFileSource

NewZipFileSource creates a data source from a zip.File.

func (*ZipFileSource) Open

func (s *ZipFileSource) Open() (io.ReadCloser, error)

Open opens the ZIP archive entry.

func (*ZipFileSource) Size

func (s *ZipFileSource) Size() int64

Size returns the uncompressed size.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL