silk.compress.tar.
Read and write tar archives as streams, one block of bytes at a time.
When to use#
Use a TarReader to unpack a .tar file, or a .tar.gz file as a
silk.compress.inflate.Decoder decodes it. Give it the archive in pieces of any size with
TarReader.step: it reports each member's header, then the member's content, and it never
holds more than one header block. Use a TarWriter to write an archive to the ambient
silk.io.writer.Writer: add members with TarWriter.file and TarWriter.directory, or
send a large file in pieces with TarWriter.beginFile and TarWriter.writeContent, and
end the archive with TarWriter.finish. For a .tar.gz, provide a
silk.compress.deflate.EncodeWriter as the Writer. This module does not compress or
decompress.
Details#
The reader understands ustar, GNU, and pax archives: the ustar prefix field, GNU long names
and long link names, pax path, linkpath, and size records, and base-256 numbers. It does
not allocate and does not keep a borrow of your input. Each header's checksum is checked. A
member's path is checked before the member is reported: an absolute path, a backslash, a NUL,
or a .. segment refuses the archive, so a caller that joins a path to a directory and creates
no links never writes outside it. Empty and . segments are allowed, because tar -C dir .
writes paths such as ./include/x.h.
The writer writes ustar headers with fixed metadata: modification time 0, owner and group 0
with no names, and mode 644, or 755 for an executable file or a directory. A path longer than
100 bytes goes in the ustar prefix field when it splits at a /, else in a pax path
record. The same members in the same order give the same bytes on every host, so a checksum of
the archive names its content.
Errors#
TarErrorfromTarReader.stepwhen a header is corrupt, the archive ends inside a member, a path is unsafe, or a long path does not fit the reader.TarErrorfrom the writer when a path is one the reader would refuse, or when the members and their content come in the wrong order.WriterErrorfrom the writer when the ambientWriterfails.
Examples#
Count the files of an archive given in small pieces#
import silk.collections.slice {Slice}
import silk.compress.tar {TarError, TarKind, TarProgress, TarReader, TarStatus}
import silk.core.result {Result}
// Counts the regular files of `archive`, or answers -1 when it is not a valid tar archive. It
// gives the reader 100 bytes at a time, as a network or a decompressor would.
fn files(archive: &[u8]) -> i32 {
let mut reader = TarReader.make()
let mut count = 0
let mut offset: usize = 0
while true {
let length = if archive.length - offset < 100 { archive.length - offset } else { 100 }
let last = offset + length == archive.length
let progress = match TarReader.step(&mut reader, Slice.view<u8>(archive, offset, length), last) {
Result<TarProgress, TarError>.Success {value} => value
Result<TarProgress, TarError>.Failure {..} => { return -1 }
}
offset = offset + progress.consumed
if progress.status == TarStatus.Member && TarReader.member(&reader).kind == TarKind.File { count = count + 1 }
if progress.status == TarStatus.End { return count }
}
return count
}
pub fn main() -> i32 {
let empty: [u8; 1024] = [0; 1024]
return files(&empty)
}Write an archive and read it back#
import silk.collections.slice {Slice}
import silk.compress.tar {TarError, TarProgress, TarReader, TarStatus, TarWriter}
import silk.core.effect {Effect}
import silk.core.result {Result}
import silk.io.writer {Writer, WriterError}
// A `Writer` that keeps up to 8 KiB in memory.
struct Memory {
bytes: [u8; 8192],
length: usize,
}
impl Writer for Memory {
effect fn writeAll(self: &mut Self, value: &[u8]) -> () ! WriterError ? &mut Writer {
if value.length > 8192 - self.length { fail Writer.failure() }
Slice.copyInto<u8>(&mut self.bytes, self.length, value)
self.length = self.length + value.length
}
effect fn flush(self: &mut Self) -> () ! WriterError ? &mut Writer { return () }
}
effect fn archive() -> () ! TarError | WriterError ? &mut Writer {
let mut writer = TarWriter.make()
run TarWriter.directory(&mut writer, b"app/bin")
run TarWriter.file(&mut writer, b"app/bin/run", b"#!/bin/sh\n", true)
// A file whose content arrives in pieces.
run TarWriter.beginFile(&mut writer, b"app/README", 6, false)
run TarWriter.writeContent(&mut writer, b"hel")
run TarWriter.writeContent(&mut writer, b"lo\n")
return run TarWriter.finish(move writer)
}
pub effect fn main() -> i32 ! TarError | WriterError {
let mut memory = Memory {bytes: [0; 8192], length: 0}
run archive() |> Effect.provideMut<Writer>(&mut memory)
let mut reader = TarReader.make()
let mut offset: usize = 0
let mut members = 0
while true {
let input = Slice.view<u8>(&memory.bytes, offset, memory.length - offset)
let progress = match TarReader.step(&mut reader, input, true) {
Result<TarProgress, TarError>.Success {value} => value
Result<TarProgress, TarError>.Failure {..} => { return 1 }
}
offset = offset + progress.consumed
if progress.status == TarStatus.Member { members = members + 1 }
if progress.status == TarStatus.End { break }
}
return if members == 3 { 0 } else { 2 }
}Import as TarReader with import silk.compress.tar { TarReader }.
Public declarations: 8.
TarError#
pub enum TarErrorThe reason a tar archive was refused, or a reader or writer was used out of order.
Truncated#
TruncatedThe archive ends inside a header or inside a member's content.
BadHeader#
BadHeaderA header's checksum does not match its bytes, a number field holds something other than an octal or base-256 number, or a pax record is malformed.
UnsafePath#
UnsafePathA member path is absolute, holds a backslash or a NUL, or has a .. segment.
PathTooLong#
PathTooLongA GNU long name or long link name, or a pax path or linkpath record, is longer than
PATH_LIMIT bytes.
InvalidUse#
InvalidUseA TarWriter call came in the wrong order: a new member or the end of the archive before
the current file got all its content, or more content than the file's size. Or a
TarReader was used after it failed.
Implementation TarError#
impl TarErrorAssociated function describe#
pub fn describe(error: TarError) -> string<'static>Returns a short sentence that describes error, such as "the tar archive is truncated".
Implementation Debug for TarError#
impl Debug for TarErrorOperation debug#
effect fn debug(self: &Self, formatter: &mut Formatter) -> () ! WriterError ? &mut WriterWrites the name of the variant, such as Truncated.
PATH_LIMIT#
pub const PATH_LIMIT: usizeThe longest path or link target, in bytes, that a GNU long-name header or a pax record can give
a TarReader: 4096, the PATH_MAX of Linux.
TarKind#
pub enum TarKindWhat a tar member is.
File#
FileA regular file. Its bytes come as Content progress after its Member progress.
Directory#
DirectoryA directory. Its name has no trailing /, and it has no content.
SymbolicLink#
SymbolicLinkA symbolic link to link, which the reader does not check.
HardLink#
HardLinkA hard link to the earlier member link, which the reader does not check.
Other#
OtherA device, a FIFO, or a type this module does not know.
TarMember#
pub struct TarMember<'a>The header of one member of a tar archive: its checked path, its kind, and its size.
Details#
The member's path is prefix/name, name alone when prefix is empty, or prefix alone when
name is empty, as ustar writes a long directory path. A GNU long name or a pax path record
comes back as name with an empty prefix. The slices borrow the TarReader, so copy what
you keep before the next TarReader.step.
Field prefix#
pub prefix: &'a [u8]The ustar prefix field, or empty.
Field name#
pub name: &'a [u8]The rest of the path, without the trailing / a directory may carry.
Field kind#
pub kind: TarKindWhether the member is a file, a directory, a link, or something else.
Field executable#
pub executable: boolWhether the member is a file whose mode has an execute permission bit.
Field link#
pub link: &'a [u8]The target of a symbolic or hard link, from a GNU long link name, a pax linkpath record, or
the header's 100-byte link field. It is empty for other kinds.
Field size#
pub size: u64The number of content bytes of a regular file. It is zero for other kinds.
TarStatus#
pub enum TarStatusWhat a successful TarReader.step found.
NeedInput#
NeedInputAll input is consumed and the archive goes on. Call again with more input.
Member#
MemberA member's header is complete. Read it with TarReader.member before the next step. The
content of a file follows as Content progress.
Content#
ContentThe first consumed bytes of the input are content of the current file, in order. Call
TarReader.remaining to learn how many more follow.
End#
EndThe archive ended, at its end-of-archive block or at the end of the final input. Later steps
return End and consume nothing.
TarProgress#
pub struct TarProgressThe result of one successful TarReader.step.
Field consumed#
pub consumed: usizeThe number of input bytes that this call consumed, from the start of the input.
Field status#
pub status: TarStatusWhat the reader found.
Implementation Copy for TarProgress#
impl Copy for TarProgressTarReader#
pub struct TarReaderA tar reader that takes the archive in pieces of any size.
When to use#
Make one with TarReader.make and call TarReader.step with the archive's bytes until it
returns End. Each call consumes a prefix of its input, and the next call takes the input
after that prefix. The archive can come from memory, a file, a socket, or a
silk.compress.inflate.Decoder.
Details#
The reader does not allocate and does not borrow your input. It holds one 512-byte header and
room for a long path and a long link target, PATH_LIMIT bytes each. Content is not copied:
a Content progress names a prefix of the input that you gave. When you give the whole
archive at once, each file's content comes back in one piece. The reader stops at the first
all-zero block. After a failure, each step fails with InvalidUse.
Implementation TarReader#
impl TarReaderAssociated function make#
pub fn make() -> TarReaderReturns a reader at the start of an archive.
Method step#
pub fn step(self: &mut Self, input: &[u8], last: bool) -> Result<TarProgress, TarError>Reads from the start of input and returns how much it consumed and what it found.
Details#
On the next call, give only the input after the consumed prefix, followed by any new bytes.
The call returns at the first member header (Member), with the content of the current file
(Content, always from the start of input), at the end of the archive (End), or when it
consumed all of input (NeedInput). Set last when input holds the rest of the archive:
then the archive may end without its end-of-archive blocks, at a member boundary or after a
file's content without its final padding. GNU long-name and pax headers are read as part of
the member they name, and pax global headers are skipped.
Errors#
TarErrorwithTruncatedwhenlastis set and the archive ends inside a header or a member,BadHeaderwhen a checksum, number, or pax record is invalid,UnsafePathwhen the member's path is absolute, holds a backslash or a NUL, or has a..segment, andPathTooLongfor a long path overPATH_LIMITbytes. After a failure, each step fails withInvalidUse.
Method member#
pub fn member<'a>(self: &'a Self) -> TarMember<'a>Returns the header of the member that the last step reported with Member.
Details#
The member borrows the reader. It is valid until the next TarReader.step, which may
overwrite the bytes it names. Before the first Member, it returns an empty member of kind
Other.
Method remaining#
pub fn remaining(self: &Self) -> u64Returns the number of content bytes of the current file that no step has reported yet. It is
zero between members, and after a file's last Content progress.
TarWriter#
pub struct TarWriterA tar archive being written to the ambient Writer, one member at a time.
When to use#
Make one with TarWriter.make, add members in the order the archive should list them, and
end the archive with TarWriter.finish. Use TarWriter.file for a file whose content is
in memory, and TarWriter.beginFile then TarWriter.writeContent for a file whose content
comes in pieces.
Details#
The writer holds no buffer: each header, each piece of content, and each block's padding goes
to the Writer as it comes. It writes ustar headers with fixed metadata: modification time
zero, owner and group zero with empty names, and mode 644 for a file, 755 for an executable
file or a directory. The same members in the same order therefore always give the same bytes,
on any host. A path longer than the 100-byte name field is split into the ustar prefix and name
at a / when it fits, and is otherwise written in a pax path record. A file of 8 GiB or more
records its size in base-256. TarReader reads every archive the writer makes.
Gotchas#
The writer does not flush the Writer. Flush or finish the provider after
TarWriter.finish.
Implementation TarWriter#
impl TarWriterAssociated function make#
pub fn make() -> TarWriterReturns a writer with no members.
Method file#
pub effect fn file(self: &mut Self, path: &[u8], content: &[u8], executable: bool) -> ()
! TarError | WriterError
? &mut WriterAdds the regular file path holding content, with mode 755 when executable and 644
otherwise.
Errors#
TarErrorwithUnsafePathwhenpathis empty, absolute, ends in/, or holds a backslash, a NUL, or a..segment, andInvalidUsewhen the last file begun withTarWriter.beginFiledid not get all its content. Nothing is written.WriterErrorwhen theWriterfails.
Method beginFile#
pub effect fn beginFile(self: &mut Self, path: &[u8], size: u64, executable: bool) -> ()
! TarError | WriterError
? &mut WriterWrites the header of the regular file path of size bytes, with mode 755 when
executable and 644 otherwise. Send its content with TarWriter.writeContent.
Errors#
TarErrorwithUnsafePathwhenpathis empty, absolute, ends in/, or holds a backslash, a NUL, or a..segment, andInvalidUsewhen the last file did not get all its content. Nothing is written.WriterErrorwhen theWriterfails.
Method writeContent#
pub effect fn writeContent(self: &mut Self, content: &[u8]) -> ()
! TarError | WriterError
? &mut WriterWrites the next content bytes of the file that TarWriter.beginFile began, and the
padding to a whole block after its last byte.
Errors#
TarErrorwithInvalidUsewhencontentis longer than the bytes the file still needs. Nothing is written.WriterErrorwhen theWriterfails.
Method directory#
pub effect fn directory(self: &mut Self, path: &[u8]) -> ()
! TarError | WriterError
? &mut WriterAdds the directory path, with mode 755. Write it without a trailing /.
Errors#
TarErrorwithUnsafePathwhenpathis empty, absolute, ends in/, or holds a backslash, a NUL, or a..segment, andInvalidUsewhen the last file did not get all its content. Nothing is written.WriterErrorwhen theWriterfails.
Method finish#
pub effect fn finish(self: TarWriter) -> ()
! TarError | WriterError
? &mut WriterEnds the archive with its two zero blocks.
Errors#
TarErrorwithInvalidUsewhen the last file did not get all its content. Nothing is written.WriterErrorwhen theWriterfails.
Category: Data formats.
Profiles: aarch64-apple-darwin, aarch64-unknown-linux-gnu, aarch64-unknown-linux-gnu-no-libc, x86_64-unknown-linux-gnu, x86_64-unknown-linux-gnu-no-libc, wasm32-unknown-unknown, wasm32-wasip1, wasm32-wasip2, x86_64-pc-windows-msvc, wasm64-unknown-unknown.