| 560 | } |
| 561 | |
| 562 | func (b *Bundle) WriteTo(w io.Writer) (int64, error) { |
| 563 | cw := NewCountingWriter(w) |
| 564 | |
| 565 | is := &indexSection{} |
| 566 | rs := newResponsesSection(len(b.Exchanges)) |
| 567 | |
| 568 | for _, e := range b.Exchanges { |
| 569 | if err := addExchange(is, rs, e); err != nil { |
| 570 | return cw.Written, err |
| 571 | } |
| 572 | } |
| 573 | if err := is.Finalize(b.Version); err != nil { |
| 574 | return cw.Written, err |
| 575 | } |
| 576 | |
| 577 | sections := []section{} |
| 578 | sections = append(sections, is) |
| 579 | if !b.Version.HasPrimaryURLFieldInHeader() && b.PrimaryURL != nil { |
| 580 | ps, err := newPrimarySection(b.PrimaryURL) |
| 581 | if err != nil { |
| 582 | return cw.Written, err |
| 583 | } |
| 584 | sections = append(sections, ps) |
| 585 | } |
| 586 | if b.ManifestURL != nil { |
| 587 | if !b.Version.SupportsManifestSection() { |
| 588 | return cw.Written, errors.New("This version of the WebBundle does not support storing manifest URL.") |
| 589 | } |
| 590 | ms, err := newManifestSection(b.ManifestURL) |
| 591 | if err != nil { |
| 592 | return cw.Written, err |
| 593 | } |
| 594 | sections = append(sections, ms) |
| 595 | } |
| 596 | if b.Signatures != nil && b.Version.SupportsSignatures() { |
| 597 | ss, err := newSignaturesSection(b.Signatures) |
| 598 | if err != nil { |
| 599 | return cw.Written, err |
| 600 | } |
| 601 | sections = append(sections, ss) |
| 602 | } |
| 603 | sections = append(sections, rs) // resources section must be the last. |
| 604 | |
| 605 | if _, err := cw.Write(b.Version.HeaderMagicBytes()); err != nil { |
| 606 | return cw.Written, err |
| 607 | } |
| 608 | if b.Version.HasPrimaryURLFieldInHeader() { |
| 609 | if err := writePrimaryURL(cw, b.PrimaryURL); err != nil { |
| 610 | return cw.Written, err |
| 611 | } |
| 612 | } |
| 613 | if err := writeSectionOffsets(cw, sections); err != nil { |
| 614 | return cw.Written, err |
| 615 | } |
| 616 | if err := writeSectionHeader(cw, len(sections)); err != nil { |
| 617 | return cw.Written, err |
| 618 | } |
| 619 | for _, s := range sections { |