├── .github ├── .gitignore └── workflows │ └── R-CMD-check.yaml ├── res_readme.fst ├── man ├── figures │ ├── fst.png │ ├── README-speed-bench-1.png │ └── README-multi-threading-1.png ├── decompress_fst.Rd ├── hash_fst.Rd ├── compress_fst.Rd ├── metadata_fst.Rd ├── fst-package.Rd ├── fst.Rd ├── threads_fst.Rd └── write_fst.Rd ├── inst └── WORDLIST ├── tests ├── testthat │ ├── keyedTable.rds │ ├── datasets │ │ ├── legacy.fst │ │ ├── legacy.rds │ │ ├── test-set.rds │ │ ├── 0.9.8-0.9.18.fst │ │ └── utf8.csv │ ├── helper_fstwrite.R │ ├── test_legacy.R │ ├── test_bigvector.R │ ├── test_nanotime.R │ ├── test_rbind.R │ ├── test_access.R │ ├── test_interface.R │ ├── test_keys.R │ ├── test_special_tables.R │ ├── test_lintr.R │ ├── test_date.R │ ├── test_integer64.R │ ├── test_omp.R │ ├── test_time.R │ ├── test_encoding.R │ ├── test_roundtrip.R │ ├── test_factor.R │ ├── test_compress.R │ ├── test_meta.R │ ├── test_fst_table.R │ └── test_fst.R └── testthat.R ├── _pkgdown.yml ├── .gitignore ├── .Rbuildignore ├── fst.Rproj ├── NAMESPACE ├── DESCRIPTION ├── R ├── RcppExports.R ├── onAttach.R ├── hash.R ├── package.R ├── type_dependencies.R ├── compress.R ├── openmp.R ├── fst.R └── fst_table.R ├── src ├── openmp.cpp ├── fst_compress.cpp ├── flex_store.cpp └── RcppExports.cpp ├── cran-comments.md ├── cran-checklist.md ├── CONTRIBUTING.md ├── CONDUCT.md ├── README.md ├── README.Rmd ├── NEWS.md └── LICENSE /.github/.gitignore: -------------------------------------------------------------------------------- 1 | *.html 2 | -------------------------------------------------------------------------------- /res_readme.fst: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fstpackage/fst/HEAD/res_readme.fst -------------------------------------------------------------------------------- /man/figures/fst.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fstpackage/fst/HEAD/man/figures/fst.png -------------------------------------------------------------------------------- /inst/WORDLIST: -------------------------------------------------------------------------------- 1 | Collet 2 | fstlib 3 | Fstlib 4 | LZ 5 | multithreaded 6 | Yann 7 | ZSTD 8 | -------------------------------------------------------------------------------- /tests/testthat/keyedTable.rds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fstpackage/fst/HEAD/tests/testthat/keyedTable.rds -------------------------------------------------------------------------------- /_pkgdown.yml: -------------------------------------------------------------------------------- 1 | url: http://www.fstpackage.org 2 | 3 | template: 4 | params: 5 | bootswatch: cerulean 6 | -------------------------------------------------------------------------------- /tests/testthat/datasets/legacy.fst: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fstpackage/fst/HEAD/tests/testthat/datasets/legacy.fst -------------------------------------------------------------------------------- /tests/testthat/datasets/legacy.rds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fstpackage/fst/HEAD/tests/testthat/datasets/legacy.rds -------------------------------------------------------------------------------- /man/figures/README-speed-bench-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fstpackage/fst/HEAD/man/figures/README-speed-bench-1.png -------------------------------------------------------------------------------- /tests/testthat/datasets/test-set.rds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fstpackage/fst/HEAD/tests/testthat/datasets/test-set.rds -------------------------------------------------------------------------------- /tests/testthat.R: -------------------------------------------------------------------------------- 1 | 2 | # required packages 3 | library(testthat) 4 | library(fst) 5 | 6 | # run tests 7 | test_check("fst") 8 | -------------------------------------------------------------------------------- /man/figures/README-multi-threading-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fstpackage/fst/HEAD/man/figures/README-multi-threading-1.png -------------------------------------------------------------------------------- /tests/testthat/datasets/0.9.8-0.9.18.fst: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fstpackage/fst/HEAD/tests/testthat/datasets/0.9.8-0.9.18.fst -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.a 2 | *.dll 3 | *.dll 4 | *.fea 5 | *.fst 6 | *.gcov 7 | *.gz 8 | *.html 9 | *.o 10 | *.orig 11 | *.pdf 12 | *.rds 13 | *.Rhistory 14 | *.Rproj 15 | *.so 16 | *.txt 17 | *.zip 18 | .Rproj.user 19 | *.TMP 20 | /revdep/* 21 | /docs/* 22 | /src-i386/ 23 | -------------------------------------------------------------------------------- /.Rbuildignore: -------------------------------------------------------------------------------- 1 | ^\.github$ 2 | ^.*\.Rproj$ 3 | ^\.Rproj\.user$ 4 | \.o$ 5 | ^_pkgdown\.yml$ 6 | ^CONDUCT\.md$ 7 | \.dll$ 8 | ^docs$ 9 | \.a$ 10 | \.Rmd$ 11 | LZ4/LICENSE$ 12 | \.md$ 13 | ^docs$ 14 | \.TMP$ 15 | \.png$ 16 | \.yml$ 17 | ^dataset\.fst$ 18 | ^res_readme\.fst$ 19 | ^_pkgdown\.yml$ 20 | ^CRAN-RELEASE$ 21 | ^revdep$ 22 | ^\.github$ 23 | ^CRAN-SUBMISSION$ 24 | -------------------------------------------------------------------------------- /man/decompress_fst.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/compress.R 3 | \name{decompress_fst} 4 | \alias{decompress_fst} 5 | \title{Decompress a raw vector with compressed data.} 6 | \usage{ 7 | decompress_fst(x) 8 | } 9 | \arguments{ 10 | \item{x}{raw vector with data previously compressed with \code{compress_fst}.} 11 | } 12 | \value{ 13 | a raw vector with previously compressed data. 14 | } 15 | \description{ 16 | Decompress a raw vector with compressed data. 17 | } 18 | -------------------------------------------------------------------------------- /fst.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: Default 4 | SaveWorkspace: Default 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 2 10 | Encoding: ISO8859-1 11 | 12 | RnwWeave: knitr 13 | LaTeX: pdfLaTeX 14 | 15 | AutoAppendNewline: Yes 16 | StripTrailingWhitespace: Yes 17 | 18 | BuildType: Package 19 | PackageUseDevtools: Yes 20 | PackageInstallArgs: --no-multiarch --with-keep.source 21 | PackageCheckArgs: --use-valgrind --as-cran 22 | PackageRoxygenize: rd,collate,namespace 23 | -------------------------------------------------------------------------------- /tests/testthat/helper_fstwrite.R: -------------------------------------------------------------------------------- 1 | 2 | # Convenience method to tests on different versions of the package 3 | # Not used in the CRAN release 4 | fstwriteproxy <- function(x, path, compress = 0, uniform_encoding = TRUE) { 5 | write_fst(x, path, compress, uniform_encoding) # use current version of fst package 6 | } 7 | 8 | 9 | fstreadproxy <- function(path, columns = NULL, from = 1, to = NULL, as_data_table = FALSE) { 10 | read_fst(path, columns, from, to, as_data_table) 11 | } 12 | 13 | 14 | fstmetaproxy <- function(path) { 15 | metadata_fst(path) 16 | } 17 | -------------------------------------------------------------------------------- /tests/testthat/test_legacy.R: -------------------------------------------------------------------------------- 1 | 2 | context("legacy format") 3 | 4 | 5 | test_that("Read legacy format", { 6 | expect_error( 7 | dt <- read_fst("datasets/legacy.fst", old_format = TRUE), 8 | "Parameter old_format is depricated" 9 | ) 10 | 11 | expect_error( 12 | metadata_fst("datasets/legacy.fst"), 13 | "File header information does not contain the fst format marker" 14 | ) 15 | }) 16 | 17 | 18 | test_that("0.9.8-0.9.18.fst", { 19 | 20 | # BigEndian systems will fail this test 21 | skip_on_cran() 22 | skip_on_ci() 23 | 24 | expect_equal( 25 | readRDS("datasets/test-set.rds"), 26 | read_fst("datasets/0.9.8-0.9.18.fst") 27 | ) 28 | }) 29 | -------------------------------------------------------------------------------- /tests/testthat/test_bigvector.R: -------------------------------------------------------------------------------- 1 | 2 | context("big vectors") 3 | 4 | 5 | # Clean testdata directory 6 | if (!file.exists("testdata")) { 7 | dir.create("testdata") 8 | } else { 9 | file.remove(list.files("testdata", full.names = TRUE)) 10 | } 11 | 12 | # nolint start 13 | # # Sample data 14 | # x <- list(X = rep(1.1, 500000000)) 15 | # setDT(x) 16 | # gc() 17 | # 18 | # require(microbenchmark) 19 | # 20 | # test_that("Read meta of sorted file", 21 | # { 22 | # microbenchmark( 23 | # write.fst(x, "testdata/big.fst"), times = 1) 24 | # 25 | # rm(x) 26 | # gc() 27 | # 28 | # microbenchmark( 29 | # y <- read.fst("testdata/big.fst", as.data.table = TRUE), 30 | # times = 1) 31 | # 32 | # rm(y) 33 | # gc() 34 | # }) 35 | # nolint end 36 | -------------------------------------------------------------------------------- /man/hash_fst.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/hash.R 3 | \name{hash_fst} 4 | \alias{hash_fst} 5 | \title{Parallel calculation of the hash of a raw vector} 6 | \usage{ 7 | hash_fst(x, seed = NULL, block_hash = TRUE) 8 | } 9 | \arguments{ 10 | \item{x}{raw vector that you want to hash} 11 | 12 | \item{seed}{The seed value for the hashing algorithm. If NULL, a default seed will be used.} 13 | 14 | \item{block_hash}{If TRUE, a multi-threaded implementation of the 64-bit xxHash algorithm will 15 | be used. Note that block_hash = TRUE or block_hash = FALSE will result in different hash values.} 16 | } 17 | \value{ 18 | hash value 19 | } 20 | \description{ 21 | Parallel calculation of the hash of a raw vector 22 | } 23 | -------------------------------------------------------------------------------- /tests/testthat/test_nanotime.R: -------------------------------------------------------------------------------- 1 | 2 | context("nanotime column") 3 | 4 | 5 | library(data.table) 6 | 7 | 8 | # Clean testdata directory 9 | if (!file.exists("testdata")) { 10 | dir.create("testdata") 11 | } else { 12 | file.remove(list.files("testdata", full.names = TRUE)) 13 | } 14 | 15 | 16 | test_that("Cycle return the nanotime type", { 17 | skip_if_not(requireNamespace("nanotime", quietly = TRUE)) 18 | 19 | # Prepare example 20 | dt_nanotime <- data.frame( 21 | Nano = nanotime::nanotime(Sys.Date() + 1:100) 22 | ) 23 | 24 | expect_true(inherits(dt_nanotime$Nano, "nanotime")) 25 | 26 | # Write to fst 27 | fstwriteproxy(dt_nanotime, "testdata/dt_nanotime.fst") 28 | dt_nanotime_read <- fstreadproxy("testdata/dt_nanotime.fst") 29 | 30 | # nanotime type preserved: 31 | expect_true(inherits(dt_nanotime_read$Nano, "nanotime")) 32 | 33 | expect_identical(dt_nanotime, dt_nanotime_read) 34 | }) 35 | -------------------------------------------------------------------------------- /tests/testthat/datasets/utf8.csv: -------------------------------------------------------------------------------- 1 | Language;ICanEatGlass 2 | Old Irish (Ogham);᚛᚛ᚉᚑᚅᚔᚉᚉᚔᚋ ᚔᚈᚔ ᚍᚂᚐᚅᚑ ᚅᚔᚋᚌᚓᚅᚐ᚜ 3 | Old Norse (Runes);ᛖᚴ ᚷᛖᛏ ᛖᛏᛁ ᚧ ᚷᛚᛖᚱ ᛘᚾ ᚦᛖᛋᛋ ᚨᚧ ᚡᛖ ᚱᚧᚨ ᛋᚨᚱ 4 | Georgian;მინას ვჭამ და არა მტკივა. 5 | Armenian;Կրնամ ապակի ուտել և ինծի անհանգիստ չըներ։ 6 | Bangla / Bengali;আমি কাঁচ খেতে পারি, তাতে আমার কোনো ক্ষতি হয় না। 7 | Marathi;मी काच खाऊ शकतो, मला ते दुखत नाही. 8 | Kannada;ನನಗೆ ಹಾನಿ ಆಗದೆ, ನಾನು ಗಜನ್ನು ತಿನಬಹುದು 9 | Hindi;मैं काँच खा सकता हूँ और मुझे उससे कोई चोट नहीं पहुंचती. 10 | Malayalam;എനിക്ക് ഗ്ലാസ് തിന്നാം. അതെന്നെ വേദനിപ്പിക്കില്ല. 11 | Telugu;నేను గాజు తినగలను మరియు అలా చేసినా నాకు ఏమి ఇబ్బంది లేదు 12 | Sinhalese;මට වීදුරු කෑමට හැකියි. එයින් මට කිසි හානියක් සිදු නොවේ. 13 | Urdu(3);چ کھا سکتا ہوں اور مجھے تکلیف نہیں ہوتی ۔ 14 | Pashto(3);زه شيشه خوړلې شم، هغه ما نه خوږوي 15 | Farsi / Persian(3;من می توانم بدونِ احساس درد شيشه بخورم 16 | Chinese (Traditional);我能吞下玻璃而不傷身體。 17 | Japanese;私はガラスを食べられます。それは私を傷つけません。 18 | -------------------------------------------------------------------------------- /NAMESPACE: -------------------------------------------------------------------------------- 1 | # Generated by roxygen2: do not edit by hand 2 | 3 | S3method("$",fst_table) 4 | S3method("[",fst_table) 5 | S3method("[[",fst_table) 6 | S3method(as.data.frame,fst_table) 7 | S3method(as.list,fst_table) 8 | S3method(dim,fst_table) 9 | S3method(dimnames,fst_table) 10 | S3method(names,fst_table) 11 | S3method(print,fst_table) 12 | S3method(print,fstmetadata) 13 | S3method(row.names,fst_table) 14 | S3method(str,fst_table) 15 | export(compress_fst) 16 | export(decompress_fst) 17 | export(fst) 18 | export(fst.metadata) 19 | export(hash_fst) 20 | export(metadata_fst) 21 | export(read.fst) 22 | export(read_fst) 23 | export(threads_fst) 24 | export(write.fst) 25 | export(write_fst) 26 | import(Rcpp) 27 | importFrom(fstcore,threads_fstlib) 28 | importFrom(parallel,detectCores) 29 | importFrom(utils,capture.output) 30 | importFrom(utils,packageVersion) 31 | importFrom(utils,str) 32 | importFrom(utils,tail) 33 | useDynLib(fst, .registration = TRUE) 34 | -------------------------------------------------------------------------------- /tests/testthat/test_rbind.R: -------------------------------------------------------------------------------- 1 | 2 | context("row binding") 3 | 4 | 5 | # Clean testdata directory 6 | if (!file.exists("testoutput")) { 7 | dir.create("testoutput") 8 | } else { 9 | file.remove(list.files("testoutput", full.names = TRUE)) 10 | } 11 | 12 | 13 | char_vec <- function(nr_of_rows) { 14 | sapply( 15 | 1:nr_of_rows, 16 | function(x) { 17 | paste(sample(LETTERS, sample(1:4, 1)), collapse = "") 18 | } 19 | ) 20 | } 21 | 22 | # Sample data 23 | nr_of_rows <- 10000L 24 | nr_of_levels <- 8 25 | 26 | char_na <- char_vec(nr_of_rows) 27 | char_na[sample(1:nr_of_rows, 10)] <- NA 28 | datatable <- data.frame( 29 | Xint = 1:nr_of_rows, 30 | Ylog = sample(c(TRUE, FALSE, NA), nr_of_rows, replace = TRUE), 31 | Zdoub = rnorm(nr_of_rows), 32 | Qchar = char_vec(nr_of_rows), 33 | WFact = factor(sample(char_vec(nr_of_levels), nr_of_rows, replace = TRUE)), 34 | char_na = char_na, 35 | stringsAsFactors = FALSE 36 | ) 37 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: fst 2 | Type: Package 3 | Title: Lightning Fast Serialization of Data Frames 4 | Description: Multithreaded serialization of compressed data frames using the 'fst' format. The 5 | 'fst' format allows for full random access of stored data and a wide range of compression 6 | settings using the LZ4 and ZSTD compressors. 7 | Version: 0.9.9 8 | Date: 2022-02-08 9 | Authors@R: 10 | person("Mark", "Klik", email = "markklik@gmail.com", role = c("aut", "cre", "cph")) 11 | Depends: 12 | R (>= 3.0.0) 13 | Imports: 14 | fstcore, 15 | Rcpp 16 | LinkingTo: 17 | Rcpp, 18 | fstcore 19 | SystemRequirements: little-endian platform 20 | RoxygenNote: 7.3.2 21 | Suggests: 22 | testthat, 23 | bit64, 24 | data.table, 25 | lintr, 26 | nanotime, 27 | crayon 28 | License: AGPL-3 | file LICENSE 29 | Encoding: UTF-8 30 | URL: http://www.fstpackage.org 31 | BugReports: https://github.com/fstpackage/fst/issues 32 | -------------------------------------------------------------------------------- /man/compress_fst.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/compress.R 3 | \name{compress_fst} 4 | \alias{compress_fst} 5 | \title{Compress a raw vector using the LZ4 or ZSTD compressor.} 6 | \usage{ 7 | compress_fst(x, compressor = "ZSTD", compression = 0, hash = FALSE) 8 | } 9 | \arguments{ 10 | \item{x}{raw vector.} 11 | 12 | \item{compressor}{compressor to use for compressing \code{x}. Valid options are "LZ4" and "ZSTD" (default).} 13 | 14 | \item{compression}{compression factor used. Must be in the range 0 (lowest compression) to 100 (maximum compression).} 15 | 16 | \item{hash}{Compute hash of compressed data. This hash is stored in the resulting raw vector and 17 | can be used during decompression to check the validity of the compressed vector. Hash 18 | computation is done with the very fast xxHash algorithm and implemented as a parallel operation, 19 | so the performance hit will be very small.} 20 | } 21 | \description{ 22 | Compress a raw vector using the LZ4 or ZSTD compressor. 23 | } 24 | -------------------------------------------------------------------------------- /man/metadata_fst.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/fst.R 3 | \name{metadata_fst} 4 | \alias{metadata_fst} 5 | \alias{fst.metadata} 6 | \title{Read metadata from a fst file} 7 | \usage{ 8 | metadata_fst(path, old_format = FALSE) 9 | 10 | fst.metadata(path, old_format = FALSE) 11 | } 12 | \arguments{ 13 | \item{path}{path to fst file} 14 | 15 | \item{old_format}{must be FALSE, the old fst file format is deprecated and can only be read and 16 | converted with fst package versions 0.8.0 to 0.8.10.} 17 | } 18 | \value{ 19 | Returns a list with meta information on the stored dataset in \code{path}. 20 | Has class \code{fstmetadata}. 21 | } 22 | \description{ 23 | Method for checking basic properties of the dataset stored in \code{path}. 24 | } 25 | \examples{ 26 | # Sample dataset 27 | x <- data.frame( 28 | First = 1:10, 29 | Second = sample(c(TRUE, FALSE, NA), 10, replace = TRUE), 30 | Last = sample(LETTERS, 10) 31 | ) 32 | 33 | # Write to fst file 34 | fst_file <- tempfile(fileext = ".fst") 35 | write_fst(x, fst_file) 36 | 37 | # Display meta information 38 | metadata_fst(fst_file) 39 | } 40 | -------------------------------------------------------------------------------- /tests/testthat/test_access.R: -------------------------------------------------------------------------------- 1 | 2 | context("access") 3 | 4 | 5 | # Clean testdata directory 6 | if (!file.exists("testdata")) { 7 | dir.create("testdata") 8 | } else { 9 | file.remove(list.files("testdata", full.names = TRUE)) 10 | } 11 | 12 | test_that("Reading non-existent file gives an error", { 13 | expect_error(fstreadproxy("AccessStore/non-existent.fst")) 14 | }) 15 | 16 | 17 | test_that("Writing to incorrect path gives an error", { 18 | expect_error(fstwriteproxy(data.frame(A = 1:10), "AccessStore/A/non-existent.fst")) 19 | }) 20 | 21 | 22 | test_that("Columns need to be of type character", { 23 | fstwriteproxy(data.frame(A = 1:10), "testdata/bla.fst") 24 | expect_error(fstreadproxy("testdata/bla.fst", 2), "Parameter 'columns' should be a character vector of column names") 25 | }) 26 | 27 | 28 | test_that("Columns need to be of type character", { 29 | expect_error(fstreadproxy("testdata/bla.fst", to = c(1, 2)), "Parameter 'to' should have a numerical value") 30 | }) 31 | 32 | 33 | test_that("Old read and write interface still functional", { 34 | x <- fstreadproxy("testdata/bla.fst") 35 | y <- read.fst("testdata/bla.fst") 36 | write.fst(y, "testdata/bla.fst") 37 | 38 | expect_identical(x, y) 39 | }) 40 | -------------------------------------------------------------------------------- /R/RcppExports.R: -------------------------------------------------------------------------------- 1 | # Generated by using Rcpp::compileAttributes() -> do not edit by hand 2 | # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 3 | 4 | fststore <- function(fileName, table, compression, uniformEncoding) { 5 | .Call(`_fst_fststore`, fileName, table, compression, uniformEncoding) 6 | } 7 | 8 | fstmetadata <- function(fileName) { 9 | .Call(`_fst_fstmetadata`, fileName) 10 | } 11 | 12 | fstretrieve <- function(fileName, columnSelection, startRow, endRow) { 13 | .Call(`_fst_fstretrieve`, fileName, columnSelection, startRow, endRow) 14 | } 15 | 16 | fsthasher <- function(rawVec, seed, blockHash) { 17 | .Call(`_fst_fsthasher`, rawVec, seed, blockHash) 18 | } 19 | 20 | fstcomp <- function(rawVec, compressor, compression, hash) { 21 | .Call(`_fst_fstcomp`, rawVec, compressor, compression, hash) 22 | } 23 | 24 | fstdecomp <- function(rawVec) { 25 | .Call(`_fst_fstdecomp`, rawVec) 26 | } 27 | 28 | getnrofthreads <- function() { 29 | .Call(`_fst_getnrofthreads`) 30 | } 31 | 32 | setnrofthreads <- function(nrOfThreads) { 33 | .Call(`_fst_setnrofthreads`, nrOfThreads) 34 | } 35 | 36 | restore_after_fork <- function(restore) { 37 | invisible(.Call(`_fst_restore_after_fork`, restore)) 38 | } 39 | 40 | hasopenmp <- function() { 41 | .Call(`_fst_hasopenmp`) 42 | } 43 | 44 | -------------------------------------------------------------------------------- /tests/testthat/test_interface.R: -------------------------------------------------------------------------------- 1 | 2 | context("package interface") 3 | 4 | 5 | # Clean testdata directory 6 | if (!file.exists("testdata")) { 7 | dir.create("testdata") 8 | } else { 9 | file.remove(list.files("testdata", full.names = TRUE)) 10 | } 11 | 12 | 13 | x <- data.table(A = 1:10, B = sample(c(TRUE, FALSE, NA), 10, replace = TRUE)) 14 | 15 | test_that("From unkeyed data.table to data.table", { 16 | fstwriteproxy(x, "testdata/nokey.fst") 17 | 18 | y <- fstreadproxy("testdata/nokey.fst") 19 | expect_false(is.data.table(y)) 20 | 21 | y <- fstreadproxy("testdata/nokey.fst", as_data_table = TRUE) 22 | expect_null(key(y)) 23 | expect_true(is.data.table(y)) 24 | 25 | z <- fstmetaproxy("testdata/nokey.fst") # expect no error 26 | }) 27 | 28 | 29 | xkey <- readRDS("keyedTable.rds") # import keyed table to avoid memory leaks in data.table (LeakSanitizer) 30 | 31 | test_that("From keyed data.table to data.table", { 32 | fstwriteproxy(xkey, "testdata/key.fst") 33 | 34 | y <- fstreadproxy("testdata/key.fst") 35 | expect_false(is.data.table(y)) 36 | 37 | y <- fstreadproxy("testdata/key.fst", as_data_table = TRUE) 38 | expect_true(is.data.table(y)) 39 | expect_equal(key(y), "B") 40 | expect_equal(xkey, y) 41 | 42 | z <- fstmetaproxy("testdata/key.fst") # expect no error 43 | }) 44 | -------------------------------------------------------------------------------- /tests/testthat/test_keys.R: -------------------------------------------------------------------------------- 1 | 2 | context("keys") 3 | 4 | 5 | # Clean testdata directory 6 | if (!file.exists("testdata")) { 7 | dir.create("testdata") 8 | } else { 9 | file.remove(list.files("testdata", full.names = TRUE)) 10 | } 11 | 12 | 13 | x <- data.table(A = 1:10, B = 10:1, C = 100:109, D = 20:29, E = 1:10) 14 | setkey(x, A, B, D) 15 | 16 | 17 | test_that("Fully keyed table", { 18 | fstwriteproxy(x, "testdata/keys.fst") 19 | y <- fstreadproxy("testdata/keys.fst", as_data_table = TRUE) 20 | expect_equal(key(y), key(x)) 21 | }) 22 | 23 | 24 | test_that("Missing last key", { 25 | fstwriteproxy(x, "testdata/keys.fst") 26 | y <- fstreadproxy("testdata/keys.fst", columns = c("A", "B", "C", "E"), as_data_table = TRUE) 27 | expect_equal(key(y), c("A", "B")) 28 | }) 29 | 30 | 31 | test_that("Missing middle key", { 32 | fstwriteproxy(x, "testdata/keys.fst") 33 | y <- fstreadproxy("testdata/keys.fst", columns = c("A", "C", "D", "E"), as_data_table = TRUE) 34 | expect_equal(key(y), c("A")) 35 | }) 36 | 37 | 38 | test_that("Missing first key", { 39 | fstwriteproxy(x, "testdata/keys.fst") 40 | res <- fst:::fstretrieve("testdata/keys.fst", c("B", "C", "D", "E"), 1L, NULL) 41 | y <- fstreadproxy("testdata/keys.fst", columns = c("B", "C", "D", "E"), as_data_table = TRUE) 42 | expect_null(key(y)) 43 | }) 44 | -------------------------------------------------------------------------------- /man/fst-package.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/package.R 3 | \docType{package} 4 | \name{fst-package} 5 | \alias{fst-package} 6 | \title{Lightning Fast Serialization of Data Frames for R.} 7 | \description{ 8 | Multithreaded serialization of compressed data frames using the 'fst' format. 9 | The 'fst' format allows for random access of stored data which can be compressed with the 10 | LZ4 and ZSTD compressors. 11 | } 12 | \details{ 13 | The fst package is based on three C++ libraries: 14 | \itemize{ 15 | \item \strong{fstlib}: library containing code to write, read and compute on files stored in the \emph{fst} format. 16 | Written and owned by Mark Klik. 17 | \item \strong{LZ4}: library containing code to compress data with the LZ4 compressor. Written and owned 18 | by Yann Collet. 19 | \item \strong{ZSTD}: library containing code to compress data with the ZSTD compressor. Written by 20 | Yann Collet and owned by Facebook, Inc. 21 | } 22 | 23 | As of version 0.9.8, these libraries are included in the fstcore package, on which fst depends. 24 | The copyright notices of the above libraries can be found in the fstcore package. 25 | } 26 | \seealso{ 27 | Useful links: 28 | \itemize{ 29 | \item \url{http://www.fstpackage.org} 30 | \item Report bugs at \url{https://github.com/fstpackage/fst/issues} 31 | } 32 | 33 | } 34 | \author{ 35 | \strong{Maintainer}: Mark Klik \email{markklik@gmail.com} [copyright holder] 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/openmp.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | fst - R package for ultra fast storage and retrieval of datasets 3 | 4 | Copyright (C) 2017-present, Mark AJ Klik 5 | 6 | This file is part of the fst R package. 7 | 8 | The fst R package is free software: you can redistribute it and/or modify it 9 | under the terms of the GNU Affero General Public License version 3 as 10 | published by the Free Software Foundation. 11 | 12 | The fst R package is distributed in the hope that it will be useful, but 13 | WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 14 | FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 15 | for more details. 16 | 17 | You should have received a copy of the GNU Affero General Public License along 18 | with the fst R package. If not, see . 19 | 20 | You can contact the author at: 21 | - fst R package source repository : https://github.com/fstpackage/fst 22 | */ 23 | 24 | 25 | #include 26 | 27 | #include 28 | 29 | 30 | // [[Rcpp::export]] 31 | SEXP getnrofthreads() 32 | { 33 | return fstcore::getnrofthreads(); 34 | } 35 | 36 | 37 | // [[Rcpp::export]] 38 | int setnrofthreads(SEXP nrOfThreads) 39 | { 40 | return fstcore::setnrofthreads(nrOfThreads); 41 | } 42 | 43 | 44 | // [[Rcpp::export]] 45 | void restore_after_fork(bool restore) 46 | { 47 | fstcore::restore_after_fork(restore); 48 | } 49 | 50 | 51 | // [[Rcpp::export]] 52 | SEXP hasopenmp() 53 | { 54 | return fstcore::hasopenmp(); 55 | } 56 | 57 | -------------------------------------------------------------------------------- /src/fst_compress.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | fst - R package for ultra fast storage and retrieval of datasets 3 | 4 | Copyright (C) 2017-present, Mark AJ Klik 5 | 6 | This file is part of the fst R package. 7 | 8 | The fst R package is free software: you can redistribute it and/or modify it 9 | under the terms of the GNU Affero General Public License version 3 as 10 | published by the Free Software Foundation. 11 | 12 | The fst R package is distributed in the hope that it will be useful, but 13 | WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 14 | FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 15 | for more details. 16 | 17 | You should have received a copy of the GNU Affero General Public License along 18 | with the fst R package. If not, see . 19 | 20 | You can contact the author at: 21 | - fst R package source repository : https://github.com/fstpackage/fst 22 | */ 23 | 24 | 25 | #include 26 | 27 | #include 28 | 29 | 30 | // [[Rcpp::export]] 31 | SEXP fsthasher(SEXP rawVec, SEXP seed, SEXP blockHash) 32 | { 33 | return fstcore::fsthasher(rawVec, seed, blockHash); 34 | } 35 | 36 | 37 | // [[Rcpp::export]] 38 | SEXP fstcomp(SEXP rawVec, SEXP compressor, SEXP compression, SEXP hash) 39 | { 40 | return fstcore::fstcomp(rawVec, compressor, compression, hash); 41 | } 42 | 43 | 44 | // [[Rcpp::export]] 45 | SEXP fstdecomp(SEXP rawVec) 46 | { 47 | return fstcore::fstdecomp(rawVec); 48 | } 49 | 50 | -------------------------------------------------------------------------------- /tests/testthat/test_special_tables.R: -------------------------------------------------------------------------------- 1 | 2 | context("special tables") 3 | 4 | 5 | # Clean testdata directory 6 | if (!file.exists("testdata")) { 7 | dir.create("testdata") 8 | } else { 9 | file.remove(list.files("testdata", full.names = TRUE)) 10 | } 11 | 12 | 13 | difftime_mode <- function(mode = "double") { 14 | vec <- (Sys.time() + 1) - Sys.time() 15 | mode(vec) <- mode 16 | vec[0] 17 | } 18 | 19 | 20 | datatable <- data.frame( 21 | Xint = integer(0), 22 | Ylog = logical(0), 23 | Zdoub = double(0), 24 | Qchar = character(0), 25 | Ordered = ordered(sample(LETTERS, 26, replace = TRUE))[0], 26 | Date = as.Date("2019-01-01")[0], 27 | Raw = as.raw(255)[0], 28 | Difftime = difftime_mode(), 29 | DiffTime_int = difftime_mode("integer"), 30 | WFact = factor(sample(LETTERS, 26, replace = TRUE))[0], 31 | WFactNA = factor(NA)[0], 32 | stringsAsFactors = FALSE 33 | ) 34 | 35 | 36 | test_that("zero row multi-column table", { 37 | 38 | # read-write cycle 39 | write_fst(datatable, "testdata/zero_row.fst") 40 | 41 | x <- fst("testdata/zero_row.fst") 42 | expect_equal(nrow(x), 0) 43 | 44 | y <- read_fst("testdata/zero_row.fst") 45 | expect_equal(datatable, y) 46 | }) 47 | 48 | 49 | test_that("zero-column table", { 50 | 51 | # read-write cycle 52 | write_fst(data.frame(), "testdata/zero_column.fst") 53 | 54 | x <- fst("testdata/zero_column.fst") 55 | expect_equal(ncol(x), 0) 56 | expect_equal(nrow(x), 0) 57 | 58 | y <- read_fst("testdata/zero_column.fst") 59 | expect_equal(data.frame(), y) 60 | }) 61 | -------------------------------------------------------------------------------- /man/fst.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/fst_table.R 3 | \name{fst} 4 | \alias{fst} 5 | \title{Access a fst file like a regular data frame} 6 | \usage{ 7 | fst(path, old_format = FALSE) 8 | } 9 | \arguments{ 10 | \item{path}{path to fst file} 11 | 12 | \item{old_format}{must be FALSE, the old fst file format is deprecated and can only be read and 13 | converted with fst package versions 0.8.0 to 0.8.10.} 14 | } 15 | \value{ 16 | An object of class \code{fst_table} 17 | } 18 | \description{ 19 | Create a fst_table object that can be accessed like a regular data frame. This object 20 | is just a reference to the actual data and requires only a small amount of memory. 21 | When data is accessed, only a subset is read from file, depending on the minimum and 22 | maximum requested row number. This is possible because the fst file format allows full 23 | random access (in columns and rows) to the stored dataset. 24 | } 25 | \examples{ 26 | \dontrun{ 27 | # generate a sample fst file 28 | path <- paste0(tempfile(), ".fst") 29 | write_fst(iris, path) 30 | 31 | # create a fst_table object that can be used as a data frame 32 | ft <- fst(path) 33 | 34 | # print head and tail 35 | print(ft) 36 | 37 | # select columns and rows 38 | x <- ft[10:14, c("Petal.Width", "Species")] 39 | 40 | # use the common list interface 41 | ft[TRUE] 42 | ft[c(TRUE, FALSE)] 43 | ft[["Sepal.Length"]] 44 | ft$Petal.Length 45 | 46 | # use data frame generics 47 | nrow(ft) 48 | ncol(ft) 49 | dim(ft) 50 | dimnames(ft) 51 | colnames(ft) 52 | rownames(ft) 53 | names(ft) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/flex_store.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | fst - R package for ultra fast storage and retrieval of datasets 3 | 4 | Copyright (C) 2017-present, Mark AJ Klik 5 | 6 | This file is part of the fst R package. 7 | 8 | The fst R package is free software: you can redistribute it and/or modify it 9 | under the terms of the GNU Affero General Public License version 3 as 10 | published by the Free Software Foundation. 11 | 12 | The fst R package is distributed in the hope that it will be useful, but 13 | WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 14 | FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 15 | for more details. 16 | 17 | You should have received a copy of the GNU Affero General Public License along 18 | with the fst R package. If not, see . 19 | 20 | You can contact the author at: 21 | - fst R package source repository : https://github.com/fstpackage/fst 22 | */ 23 | 24 | #include 25 | 26 | #include 27 | 28 | 29 | // [[Rcpp::export]] 30 | SEXP fststore(Rcpp::String fileName, SEXP table, SEXP compression, SEXP uniformEncoding) 31 | { 32 | return fstcore::fststore(fileName, table, compression, uniformEncoding); 33 | } 34 | 35 | 36 | // [[Rcpp::export]] 37 | SEXP fstmetadata(Rcpp::String fileName) 38 | { 39 | return fstcore::fstmetadata(fileName); 40 | } 41 | 42 | 43 | // [[Rcpp::export]] 44 | SEXP fstretrieve(Rcpp::String fileName, SEXP columnSelection, SEXP startRow, SEXP endRow) 45 | { 46 | return fstcore::fstretrieve(fileName, columnSelection, startRow, endRow); 47 | } 48 | -------------------------------------------------------------------------------- /.github/workflows/R-CMD-check.yaml: -------------------------------------------------------------------------------- 1 | # Workflow derived from https://github.com/r-lib/actions/tree/v2/examples 2 | 3 | name: R-CMD-check 4 | 5 | on: 6 | push: 7 | pull_request: 8 | 9 | jobs: 10 | R-CMD-check: 11 | runs-on: ${{ matrix.config.os }} 12 | 13 | name: ${{ matrix.config.os }} (${{ matrix.config.r }}) 14 | 15 | strategy: 16 | fail-fast: false 17 | matrix: 18 | config: 19 | - {os: macOS-latest, r: 'release'} 20 | - {os: windows-2022, r: 'devel'} 21 | - {os: windows-latest, r: '4.1'} 22 | - {os: windows-latest, r: '3.6'} 23 | - {os: ubuntu-latest, r: 'devel', http-user-agent: 'release'} 24 | - {os: ubuntu-latest, r: 'release'} 25 | - {os: ubuntu-20.04, r: 'release'} 26 | - {os: ubuntu-20.04, r: 'oldrel-4'} 27 | - {os: ubuntu-latest, r: 'oldrel-4'} 28 | 29 | env: 30 | GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} 31 | R_KEEP_PKG_SOURCE: yes 32 | 33 | steps: 34 | - uses: actions/checkout@v4 35 | 36 | - uses: r-lib/actions/setup-pandoc@v2 37 | 38 | - uses: r-lib/actions/setup-r@v2 39 | with: 40 | r-version: ${{ matrix.config.r }} 41 | http-user-agent: ${{ matrix.config.http-user-agent }} 42 | use-public-rspm: true 43 | 44 | - uses: r-lib/actions/setup-r-dependencies@v2 45 | with: 46 | extra-packages: any::rcmdcheck 47 | needs: check 48 | 49 | - uses: r-lib/actions/check-r-package@v2 50 | with: 51 | args: 'c("--no-manual", "--as-cran")' 52 | -------------------------------------------------------------------------------- /tests/testthat/test_lintr.R: -------------------------------------------------------------------------------- 1 | 2 | context("code quality") 3 | 4 | 5 | test_that("Package Style", { 6 | # lintr throws a lot of valgrind warnings, so skip on CRAN for now 7 | skip_on_cran() 8 | 9 | skip_on_ci() 10 | 11 | # lintr has many new and updated lints from version 2 onwards 12 | skip_if_not_installed("lintr", "2.0.0") 13 | 14 | lints <- lintr::linters_with_defaults( 15 | line_length_linter = lintr::line_length_linter(120), 16 | cyclocomp_linter = lintr::cyclocomp_linter(37) 17 | ) 18 | 19 | code_files <- list.files( 20 | c("../../R", "../../tests"), "R$", 21 | full.names = TRUE, recursive = TRUE 22 | ) 23 | 24 | # manualy remove RcppExports file and few generated files (e.g. by codecov()) 25 | code_files <- code_files[!(code_files %in% c("../../R/RcppExports.R"))] 26 | 27 | # Calculate lintr results for all code files 28 | lint_results <- lintr:::flatten_lints(lapply(code_files, function(file) { 29 | if (interactive()) { 30 | message(".", appendLF = FALSE) 31 | } 32 | lintr::lint(file, linters = lints, parse_settings = FALSE) 33 | })) 34 | 35 | # newline 36 | if (interactive()) { 37 | message() 38 | } 39 | 40 | lint_output <- NULL 41 | 42 | if (length(lint_results) > 0) { 43 | lint_results <- sapply( 44 | lint_results, 45 | function(lint_res) { 46 | paste(lint_res$filename, " (", lint_res$line_number, "): ", lint_res$message) 47 | } 48 | ) 49 | 50 | print(lint_results) 51 | } 52 | 53 | expect_true(length(lint_results) == 0, paste(lint_results, sep = "\n", collapse = "\n")) 54 | }) 55 | -------------------------------------------------------------------------------- /cran-comments.md: -------------------------------------------------------------------------------- 1 | 2 | ## Submission 3 | 4 | With this release of fst (v0.9.8), the fstlib library is no longer inluded in the fst package, but 5 | imported from package `fstcore`. This allows for better separation of updates to the fstlib C++ library and the fst 6 | wrapper package and avoids duplicate code in fst and fstcore. Packages can also directly use the interface 7 | exported from the fstcore package from C/C++ code. 8 | 9 | With this new setup the linker problem on macOS systems is also resolved. 10 | 11 | ## Test environments 12 | 13 | * macOS 11.6.2 20G314 using R 4.1.2 on github build infrastructure 14 | * Ubuntu 20.04.3 LTS using R version 4.0.5 on github build infrastructure 15 | * Ubuntu 20.04.3 LTS using R 4.1.2 on github build infrastructure 16 | * Ubuntu 20.04.3 LTS using R dev (2022-01-30 r81596) on github build infrastructure 17 | * Microsoft Windows Server 2019 10.0.17763 Datacenter using R 4.1.2 on github build infrastructure 18 | * Ubuntu 18.04 locally using clang-10.0 19 | * Docker with the rocker/r-devel-ubsan-clang instrumented image 20 | * Local Ubuntu with instrumented image using clang-10 21 | * Windows 11 local R 3.6.3 22 | * Windows 11 local R 4.1.2 23 | * Singularity-container package for running rchk on Ubuntu 18.04 24 | * Valgrind on Ubuntu 18.04 25 | * Rhub (all available systems) 26 | 27 | ## R CMD check results 28 | 29 | There are no errors or warnings. 30 | 31 | ## revdepcheck results 32 | 33 | We checked 29 reverse dependencies (26 from CRAN + 3 from Bioconductor), comparing R CMD check results across CRAN and dev versions of this package. 34 | 35 | * We saw 0 new problems 36 | * We failed to check 0 packages 37 | -------------------------------------------------------------------------------- /cran-checklist.md: -------------------------------------------------------------------------------- 1 | 2 | # Checks before releasing to CRAN 3 | 4 | * Build and test package on: 5 | - Clang 6.0.0 (on latest Ubuntu) 6 | - R-hub infrastructure (all available platforms) 7 | - docker with the rocker/r-devel-ubsan-clang instrumented image 8 | - docker with the rocker/r-devel-san instrumented image 9 | - Travis Linux and OSX 10 | - AppVeyor (Windows Server) 11 | - latest R dev version on Windows 12 | * Test packages with dependencies on fst using revdepcheck::revdep_check() 13 | * Merge develop branch into release branch 14 | * Bump version to even value in DESCRIPTION and check package startup message 15 | * Update README.Rmd and verify generated README.md on Github (release) 16 | * Update cran_comments.md 17 | * Build docs folder using pkgdown::build_site() 18 | * Update NEWS.md and make sure to remove '(in development)' in the version title and update version number 19 | * Credit all GitHub contributions in NEWS.md 20 | * Submit to CRAN 21 | 22 | # After releasing to CRAN 23 | 24 | * Update NEWS.md with the release date 25 | * Build docs folder using pkgdown::build_site(). Check that the package date is correct. 26 | * Merge branch release into master 27 | * Tag the release on Github 28 | * Commit latest docs to the fstpackage.github.io and fstpackage.github.io/fst repository 29 | * Go to the repository release page and create a new release with tag version vx.y.z. 30 | Copy and paste the contents of the relevant NEWS.md section into the release notes. 31 | * Merge branch master into release 32 | * Add '(in development)' to version title in NEWS.md and update to odd version number 33 | * Check package startup message 34 | * Merge release branch into develop 35 | -------------------------------------------------------------------------------- /tests/testthat/test_date.R: -------------------------------------------------------------------------------- 1 | 2 | context("date column") 3 | 4 | 5 | # Clean testdata directory 6 | if (!file.exists("testdata")) { 7 | dir.create("testdata") 8 | } else { 9 | file.remove(list.files("testdata", full.names = TRUE)) 10 | } 11 | 12 | 13 | test_that("Type double Date issue #22 and #33", { 14 | u1 <- data.frame(DT = Sys.Date() - 1:10, variable = rep(c("A", "B"), 5), value = 1:10) 15 | fstwriteproxy(u1, "testdata/u1.fst") 16 | expect_equal(typeof(u1$DT), "double") # double type date (expensive) 17 | 18 | u2 <- fstreadproxy("testdata/u1.fst") 19 | expect_equal(u1, u2) 20 | expect_equal(typeof(u2$DT), "double") # remains double (no conversion to integer like in feather) 21 | }) 22 | 23 | 24 | test_that("Include NA dates", { 25 | u1 <- data.frame(DT = as.Date("2010-01-01") + c(0L, 365L, NA)) 26 | fstwriteproxy(u1, "testdata/u1.fst") 27 | expect_equal(typeof(u1$DT), "double") # double type date (expensive) 28 | 29 | u2 <- fstreadproxy("testdata/u1.fst") 30 | expect_equal(u1, u2) 31 | expect_equal(typeof(u2$DT), "double") # converted to integer type date 32 | }) 33 | 34 | 35 | test_that("Include NA dates on integer Date vector", { 36 | u1 <- data.frame(DT = as.Date("2010-01-01") + c(0L, 365L, NA)) 37 | u1[, "DT"] <- as.integer(u1$DT) 38 | class(u1$DT) <- "Date" 39 | 40 | fstwriteproxy(u1, "testdata/u1.fst") 41 | expect_equal(typeof(u1$DT), "integer") # integer type date 42 | 43 | u2 <- fstreadproxy("testdata/u1.fst") 44 | expect_equal(typeof(u2$DT), "integer") # still integer type date 45 | expect_equal(as.integer(u1$DT), as.integer(u2$DT)) # integer values identical 46 | 47 | expect_equal(class(u2$DT), c("IDate", "Date")) # integer values identical 48 | }) 49 | -------------------------------------------------------------------------------- /R/onAttach.R: -------------------------------------------------------------------------------- 1 | # fst - R package for ultra fast storage and retrieval of datasets 2 | # 3 | # Copyright (C) 2017-present, Mark AJ Klik 4 | # 5 | # This file is part of the fst R package. 6 | # 7 | # The fst R package is free software: you can redistribute it and/or modify it 8 | # under the terms of the GNU Affero General Public License version 3 as 9 | # published by the Free Software Foundation. 10 | # 11 | # The fst R package is distributed in the hope that it will be useful, but 12 | # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 14 | # for more details. 15 | # 16 | # You should have received a copy of the GNU Affero General Public License along 17 | # with the fst R package. If not, see . 18 | # 19 | # You can contact the author at: 20 | # - fst R package source repository : https://github.com/fstpackage/fst 21 | 22 | 23 | .onAttach <- function(libname, pkgname) { # nolint 24 | # Runs when attached to search() path such as by library() or require() 25 | if (interactive()) { 26 | v <- packageVersion("fst") 27 | d <- read.dcf(system.file("DESCRIPTION", package = "fst"), fields = c("Packaged", "Built")) 28 | 29 | if (is.na(d[1])) { 30 | if (is.na(d[2])) { 31 | return() # neither field exists 32 | } else { 33 | d <- unlist(strsplit(d[2], split = "; "))[3] 34 | } 35 | } else { 36 | d <- d[1] 37 | } 38 | 39 | # version number odd => dev 40 | dev <- as.integer(v[1, 3]) %% 2 == 1 41 | 42 | packageStartupMessage("fst package v", v, if (dev) paste0(" IN DEVELOPMENT built ", d)) 43 | 44 | # check for old version 45 | if (dev && (Sys.Date() - as.Date(d)) > 28) 46 | packageStartupMessage("\n!!! This development version of the package is rather old, please update !!!") 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /tests/testthat/test_integer64.R: -------------------------------------------------------------------------------- 1 | 2 | context("integer64 column") 3 | 4 | 5 | library(data.table) 6 | 7 | 8 | # Clean testdata directory 9 | if (!file.exists("testdata")) { 10 | dir.create("testdata") 11 | } else { 12 | file.remove(list.files("testdata", full.names = TRUE)) 13 | } 14 | 15 | # Prepare example 16 | if (requireNamespace("bit64", quietly = TRUE)) { 17 | dtint64 <- data.frame( 18 | Int64 = bit64::as.integer64(sample(c(2345612345679, 1234567890, 8714567890), 100, replace = TRUE)) 19 | ) 20 | } 21 | 22 | 23 | test_that("Type integer64 issue #28", { 24 | 25 | skip_if_not(requireNamespace("bit64", quietly = TRUE)) 26 | 27 | expect_equal(class(dtint64$Int64), "integer64") 28 | 29 | # Write to fst 30 | fstwriteproxy(dtint64, "testdata/dt_int64.fst") 31 | 32 | # bit64 integer64 type preserved: 33 | dtint64_read <- fstreadproxy("testdata/dt_int64.fst") 34 | 35 | # bit64::integer64 type preserved: 36 | expect_equal(class(dtint64_read$Int64), "integer64") 37 | expect_identical(dtint64, dtint64_read) 38 | }) 39 | 40 | 41 | test_that("Type integer64 with compression", { 42 | 43 | skip_if_not(requireNamespace("bit64", quietly = TRUE)) 44 | 45 | # Write to fst 46 | fstwriteproxy(dtint64, "testdata/dt_int64.fst", 95) 47 | 48 | dtint64_read <- fstreadproxy("testdata/dt_int64.fst") 49 | 50 | # bit64::integer64 type preserved: 51 | expect_equal(class(dtint64_read$Int64), "integer64") 52 | expect_identical(dtint64, dtint64_read) 53 | }) 54 | 55 | 56 | test_that("Type integer64 with compression as data.table", { 57 | 58 | skip_if_not(requireNamespace("bit64", quietly = TRUE)) 59 | 60 | setDT(dtint64) 61 | fstwriteproxy(dtint64, "testdata/dt_int64.fst", 95) # Write to fst 62 | 63 | dtint64_read <- fstreadproxy("testdata/dt_int64.fst", as_data_table = TRUE) 64 | 65 | # bit64::integer64 type preserved: 66 | expect_equal(class(dtint64_read$Int64), "integer64") 67 | expect_identical(dtint64, dtint64_read) 68 | }) 69 | -------------------------------------------------------------------------------- /R/hash.R: -------------------------------------------------------------------------------- 1 | # fst - R package for ultra fast storage and retrieval of datasets 2 | # 3 | # Copyright (C) 2017-present, Mark AJ Klik 4 | # 5 | # This file is part of the fst R package. 6 | # 7 | # The fst R package is free software: you can redistribute it and/or modify it 8 | # under the terms of the GNU Affero General Public License version 3 as 9 | # published by the Free Software Foundation. 10 | # 11 | # The fst R package is distributed in the hope that it will be useful, but 12 | # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 14 | # for more details. 15 | # 16 | # You should have received a copy of the GNU Affero General Public License along 17 | # with the fst R package. If not, see . 18 | # 19 | # You can contact the author at: 20 | # - fst R package source repository : https://github.com/fstpackage/fst 21 | 22 | 23 | #' Parallel calculation of the hash of a raw vector 24 | #' 25 | #' @param x raw vector that you want to hash 26 | #' @param seed The seed value for the hashing algorithm. If NULL, a default seed will be used. 27 | #' @param block_hash If TRUE, a multi-threaded implementation of the 64-bit xxHash algorithm will 28 | #' be used. Note that block_hash = TRUE or block_hash = FALSE will result in different hash values. 29 | #' 30 | #' @return hash value 31 | #' 32 | #' @export 33 | hash_fst <- function(x, seed = NULL, block_hash = TRUE) { 34 | if (!is.null(seed)) { 35 | if (((!is.numeric(seed)) || (length(seed) != 1))) { # nolint 36 | stop("Please specify an integer value for the hash seed") 37 | } 38 | 39 | seed <- as.integer(seed) 40 | } 41 | 42 | if (!is.logical(block_hash) || length(block_hash) != 1) { 43 | stop("Please specify a logical value for parameter block_hash") 44 | } 45 | 46 | if (!is.raw(x)) { 47 | stop("Please specify a raw vector as input parameter x") 48 | } 49 | 50 | fsthasher(x, seed, block_hash) 51 | } 52 | -------------------------------------------------------------------------------- /tests/testthat/test_omp.R: -------------------------------------------------------------------------------- 1 | 2 | context("OpenMP") 3 | 4 | 5 | # Clean testdata directory 6 | if (!file.exists("testdata")) { 7 | dir.create("testdata") 8 | } else { 9 | file.remove(list.files("testdata", full.names = TRUE)) 10 | } 11 | 12 | 13 | test_that("Get number of threads", { 14 | nr_of_threads <- threads_fst() 15 | expect_gte(nr_of_threads, 1) # expect at least a single thread 16 | prev_threads <- threads_fst(2) # Set number of OpenMP threads 17 | expect_equal(nr_of_threads, prev_threads) 18 | nr_of_threads <- threads_fst() 19 | 20 | # Systems with OpenMP activated should have more than a single thread 21 | if (fst:::hasopenmp()) { 22 | expect_equal(nr_of_threads, 2) 23 | } else { 24 | expect_equal(nr_of_threads, 1) 25 | } 26 | }) 27 | 28 | 29 | test_that("threads_fst(0) use all logical cores", { 30 | threads_fst(0) 31 | nr_of_threads <- threads_fst() 32 | logical_cores <- parallel::detectCores(logical = TRUE) 33 | 34 | # Systems with OpenMP activated should have more than a single thread 35 | if (fst:::hasopenmp()) { 36 | expect_gt(nr_of_threads, 1) 37 | } else { 38 | expect_equal(nr_of_threads, 1) 39 | } 40 | }) 41 | 42 | 43 | test_that("Loading fst works with options", { 44 | 45 | # Note that neither of the tests in this block will be informative when run 46 | # on a machine without openmp. They'll pass even if the thing they're testing 47 | # is broken. 48 | 49 | orig_op <- getOption("fst_threads") 50 | options(fst_threads = 1) 51 | 52 | # First test that .onload, which happens when the namespace is loaded by ::, 53 | # reads from the fst.threads option. 54 | fstcore:::.onLoad() 55 | nr_of_threads <- threads_fst() 56 | expect_equal(nr_of_threads, 1) 57 | 58 | # Next, test that subsequently attaching the package doesn't change 59 | # the number of threads. 60 | fstcore:::.onAttach() 61 | nr_of_threads <- threads_fst() 62 | expect_equal(nr_of_threads, 1) 63 | options(fst.threads = orig_op) # reset option 64 | }) 65 | 66 | 67 | test_that("Set reset_after_fork", { 68 | 69 | expect_error(threads_fst(reset_after_fork = 3), "Parameter reset_after_fork should be set") 70 | 71 | }) 72 | -------------------------------------------------------------------------------- /man/threads_fst.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/openmp.R 3 | \name{threads_fst} 4 | \alias{threads_fst} 5 | \title{Get or set the number of threads used in parallel operations} 6 | \usage{ 7 | threads_fst(nr_of_threads = NULL, reset_after_fork = NULL) 8 | } 9 | \arguments{ 10 | \item{nr_of_threads}{number of threads to use or \code{NULL} to get the current number of threads used in 11 | multithreaded operations.} 12 | 13 | \item{reset_after_fork}{when \code{fst} is running in a forked process, the usage of OpenMP can 14 | create problems. To prevent these, \code{fst} switches back to single core usage when it detects a fork. 15 | After the fork, the number of threads is reset to it's initial setting. However, on some compilers 16 | (e.g. Intel), switching back to multi-threaded mode can lead to issues. When \code{reset_after_fork} 17 | is set to \code{FALSE}, \code{fst} is left in single-threaded mode after the fork ends. After the fork, 18 | multithreading can be activated again manually by calling \code{threads_fst} with an appropriate value 19 | for \code{nr_of_threads}. The default (\code{reset_after_fork = NULL}) leaves the fork behavior unchanged.} 20 | } 21 | \value{ 22 | the number of threads (previously) used 23 | } 24 | \description{ 25 | For parallel operations, the performance is determined to a great extend by the number of threads 26 | used. More threads will allow the CPU to perform more computational intensive tasks simultaneously, 27 | speeding up the operation. Using more threads also introduces some overhead that will scale with the 28 | number of threads used. Therefore, using the maximum number of available threads is not always the 29 | fastest solution. With \code{threads_fst} the number of threads can be adjusted to the users 30 | specific requirements. As a default, \code{fst} uses a number of threads equal to the number of 31 | logical cores in the system. 32 | } 33 | \details{ 34 | The number of threads can also be set with \code{options(fst_threads = N)}. 35 | NOTE: This option is only read when the package's namespace is first loaded, with commands like 36 | \code{library}, \code{require}, or \code{::}. If you have already used one of these, you 37 | must use \code{threads_fst} to set the number of threads. 38 | } 39 | -------------------------------------------------------------------------------- /R/package.R: -------------------------------------------------------------------------------- 1 | # fst - R package for ultra fast storage and retrieval of datasets 2 | # 3 | # Copyright (C) 2017-present, Mark AJ Klik 4 | # 5 | # This file is part of the fst R package. 6 | # 7 | # The fst R package is free software: you can redistribute it and/or modify it 8 | # under the terms of the GNU Affero General Public License version 3 as 9 | # published by the Free Software Foundation. 10 | # 11 | # The fst R package is distributed in the hope that it will be useful, but 12 | # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 14 | # for more details. 15 | # 16 | # You should have received a copy of the GNU Affero General Public License along 17 | # with the fst R package. If not, see . 18 | # 19 | # You can contact the author at: 20 | # - fst R package source repository : https://github.com/fstpackage/fst 21 | 22 | 23 | #' @useDynLib fst, .registration = TRUE 24 | #' @import Rcpp 25 | #' @importFrom fstcore threads_fstlib 26 | #' @importFrom utils packageVersion 27 | #' @importFrom utils capture.output 28 | #' @importFrom utils tail 29 | #' @importFrom utils str 30 | #' @importFrom parallel detectCores 31 | NULL 32 | 33 | 34 | #' Lightning Fast Serialization of Data Frames for R. 35 | #' 36 | #' Multithreaded serialization of compressed data frames using the 'fst' format. 37 | #' The 'fst' format allows for random access of stored data which can be compressed with the 38 | #' LZ4 and ZSTD compressors. 39 | #' 40 | #' The fst package is based on three C++ libraries: 41 | #' 42 | #' * **fstlib**: library containing code to write, read and compute on files stored in the _fst_ format. 43 | #' Written and owned by Mark Klik. 44 | #' * **LZ4**: library containing code to compress data with the LZ4 compressor. Written and owned 45 | #' by Yann Collet. 46 | #' * **ZSTD**: library containing code to compress data with the ZSTD compressor. Written by 47 | #' Yann Collet and owned by Facebook, Inc. 48 | #' 49 | #' As of version 0.9.8, these libraries are included in the fstcore package, on which fst depends. 50 | #' The copyright notices of the above libraries can be found in the fstcore package. 51 | #' 52 | #' @md 53 | #' @name fst-package 54 | #' @aliases fst-package 55 | "_PACKAGE" 56 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | 2 | # Contributions 3 | 4 | Contributions to `fst` are welcome from anyone and are best sent as pull requests on [the GitHub repository](https://github.com/fstpackage/fst/). This page provides some instructions to potential contributors about how to add to the package. 5 | 6 | 1. Contributions can be submitted as [a pull request](https://help.github.com/articles/creating-a-pull-request/) on GitHub by forking or cloning the [fst repository](https://github.com/fstpackage/fst/), making changes and submitting the pull request. 7 | 8 | 2. Pull requests should involve only one commit per substantive change. This means if you change multiple files (e.g., code and documentation), these changes should be committed together. If you don't know how to do this (e.g., you are making changes in the GitHub web interface) just submit anyway and the maintainer will clean things up. 9 | 10 | 3. Pull requests that involve code in the 3rd party libraries `LZ4`, `ZSTD` or `fstlib` (located under `src/fstcore`) will not be accepted. These libraries are used _as-is_ and any issues can be reported at their respective GitHub repositories. 11 | 12 | 4. All contributions must be submitted consistent with the package license ([AGPL-3](https://www.gnu.org/licenses/agpl-3.0.en.html)). 13 | 14 | 5. Contributions in the code (not documentation) that consist of more than 1000 characters (excluding spaces) 15 | need to be noted in the `Authors@R` field in the [`DESCRIPTION`](https://github.com/fstpackage/fst/blob/master/DESCRIPTION) file. Just follow the format of the existing entries to add your name (and, optionally, email address). 16 | 17 | 6. This package uses `royxgen` code and documentation markup, so changes should be made to `roxygen` comments in the source code `.R` files. If changes are made, `roxygen` needs to be run. The easiest way to do this is a command line call to: `Rscript -e devtools::document()`. Please resolve any `roxygen` errors before submitting a pull request. 18 | 19 | 7. Please run `R CMD BUILD fst` and `R CMD CHECK fst_VERSION.tar.gz` before submitting the pull request to check for any errors. 20 | 21 | 8. Changes requiring a new package dependency should be discussed on the GitHub issues page before submitting a pull request. 22 | 23 | Any questions you have can be opened as GitHub issues or directed to markklik (at) gmail.com. 24 | -------------------------------------------------------------------------------- /tests/testthat/test_time.R: -------------------------------------------------------------------------------- 1 | 2 | context("time") 3 | 4 | 5 | # some helper functions 6 | source("helper_fstwrite.R") 7 | 8 | 9 | roundtrip_vector <- function(x) { 10 | df <- data.frame(x = x, stringsAsFactors = FALSE) 11 | roundtrip(df)$x 12 | } 13 | 14 | 15 | roundtrip <- function(df) { 16 | temp <- tempfile() 17 | fstwriteproxy(df, temp) 18 | on.exit(unlink(temp)) 19 | 20 | fstreadproxy(temp) 21 | } 22 | 23 | 24 | # POSIXct 25 | test_that("preserves times", { 26 | x1 <- ISOdate(2001, 10, 10, tz = "US/Pacific") + c(0, NA) 27 | x2 <- roundtrip_vector(x1) 28 | 29 | expect_identical(attr(x1, "tzone"), attr(x2, "tzone")) 30 | expect_identical(attr(x1, "class"), attr(x1, "class")) 31 | expect_identical(unclass(x1), unclass(x2)) 32 | 33 | mode(x1) <- "integer" 34 | x2 <- roundtrip_vector(x1) 35 | 36 | expect_identical(attr(x1, "tzone"), attr(x2, "tzone")) 37 | expect_identical(attr(x1, "class"), attr(x1, "class")) 38 | expect_identical(unclass(x1), unclass(x2)) 39 | }) 40 | 41 | 42 | test_that("throws error on POSIXlt", { 43 | df <- data.frame(x = Sys.time()) 44 | df$x <- as.POSIXlt(df$x) 45 | 46 | expect_error(roundtrip(df), "Unknown type found in column") 47 | }) 48 | 49 | 50 | test_that("empty timezone attribute", { 51 | x1 <- Sys.time() 52 | 53 | # set to empty time zone 54 | attributes(x1)$tzone <- "" 55 | 56 | x2 <- roundtrip_vector(x1) 57 | 58 | expect_identical(attr(x1, "tzone"), attr(x2, "tzone")) 59 | expect_identical(x1, x2) 60 | 61 | mode(x1) <- "integer" 62 | 63 | x2 <- roundtrip_vector(x1) 64 | 65 | expect_identical(attr(x1, "tzone"), attr(x2, "tzone")) 66 | expect_identical(x1, x2) 67 | }) 68 | 69 | 70 | test_that("doesn't lose undue precision", { 71 | base <- ISOdate(2001, 10, 10) 72 | x1 <- base + 1e-6 * (0:3) 73 | x2 <- roundtrip_vector(x1) 74 | 75 | expect_identical(x1, x2) 76 | }) 77 | 78 | 79 | test_that("NULL tzone attribute is retained", { 80 | x1 <- Sys.time() 81 | attributes(x1)$tzone <- NULL # no tzone set 82 | 83 | expect_equal(typeof(x1), "double") 84 | 85 | # write / read cycle 86 | x2 <- roundtrip_vector(x1) 87 | 88 | expect_equal(typeof(x2), "double") 89 | expect_null(attributes(x2)$tzone) 90 | 91 | mode(x1) <- "integer" 92 | expect_equal(typeof(x1), "integer") 93 | 94 | # write / read cycle 95 | x2 <- roundtrip_vector(x1) 96 | expect_equal(typeof(x2), "integer") 97 | expect_null(attributes(x2)$tzone) 98 | }) 99 | -------------------------------------------------------------------------------- /R/type_dependencies.R: -------------------------------------------------------------------------------- 1 | # fst - R package for ultra fast storage and retrieval of datasets 2 | # 3 | # Copyright (C) 2017-present, Mark AJ Klik 4 | # 5 | # This file is part of the fst R package. 6 | # 7 | # The fst R package is free software: you can redistribute it and/or modify it 8 | # under the terms of the GNU Affero General Public License version 3 as 9 | # published by the Free Software Foundation. 10 | # 11 | # The fst R package is distributed in the hope that it will be useful, but 12 | # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 14 | # for more details. 15 | # 16 | # You should have received a copy of the GNU Affero General Public License along 17 | # with the fst R package. If not, see . 18 | # 19 | # You can contact the author at: 20 | # - fst R package source repository : https://github.com/fstpackage/fst 21 | 22 | 23 | # load bit64 namespace when integer64 type column is read from file 24 | require_bit64 <- function() { 25 | if (!requireNamespace("bit64", quietly = TRUE)) { 26 | warning( 27 | "Some columns are type 'integer64' but package bit64 is not installed. ", 28 | "Those columns will print as strange looking floating point data. ", 29 | "There is no need to reload the data. Simply install.packages('bit64') to obtain ", 30 | "the integer64 print method and print the data again." 31 | ) 32 | } 33 | } 34 | 35 | 36 | # load data.table namespace when ITime type column is read from file 37 | require_data_table <- function() { 38 | if (!requireNamespace("data.table", quietly = TRUE)) { 39 | warning( 40 | "Some columns are type 'ITime' but package data.table is not installed. ", 41 | "Those columns will print incorrectly. There is no need to ", 42 | "reload the data. Simply install.packages('data.table') to obtain the data.table print ", 43 | "method and print the data again." 44 | ) 45 | } 46 | } 47 | 48 | 49 | require_nanotime <- function() { 50 | # called in print when they see nanotime columns are present 51 | if (!requireNamespace("nanotime", quietly = TRUE)) { 52 | warning( 53 | "Some columns are type 'nanotime' but package nanotime is not installed. ", 54 | "Those columns will print as strange looking floating point data. There is no need to ", 55 | "reload the data. Simply install.packages('nanotime') to obtain the nanotime print ", 56 | "method and print the data again." 57 | ) 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /R/compress.R: -------------------------------------------------------------------------------- 1 | # fst - R package for ultra fast storage and retrieval of datasets 2 | # 3 | # Copyright (C) 2017-present, Mark AJ Klik 4 | # 5 | # This file is part of the fst R package. 6 | # 7 | # The fst R package is free software: you can redistribute it and/or modify it 8 | # under the terms of the GNU Affero General Public License version 3 as 9 | # published by the Free Software Foundation. 10 | # 11 | # The fst R package is distributed in the hope that it will be useful, but 12 | # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 14 | # for more details. 15 | # 16 | # You should have received a copy of the GNU Affero General Public License along 17 | # with the fst R package. If not, see . 18 | # 19 | # You can contact the author at: 20 | # - fst R package source repository : https://github.com/fstpackage/fst 21 | 22 | 23 | #' Compress a raw vector using the LZ4 or ZSTD compressor. 24 | #' 25 | #' @param x raw vector. 26 | #' @param compressor compressor to use for compressing \code{x}. Valid options are "LZ4" and "ZSTD" (default). 27 | #' @param compression compression factor used. Must be in the range 0 (lowest compression) to 100 (maximum compression). 28 | #' @param hash Compute hash of compressed data. This hash is stored in the resulting raw vector and 29 | #' can be used during decompression to check the validity of the compressed vector. Hash 30 | #' computation is done with the very fast xxHash algorithm and implemented as a parallel operation, 31 | #' so the performance hit will be very small. 32 | #' 33 | #' @export 34 | compress_fst <- function(x, compressor = "ZSTD", compression = 0, hash = FALSE) { 35 | if (!is.numeric(compression)) { 36 | stop("Parameter compression should be a numeric value in the range 0 to 100") 37 | } 38 | 39 | if (!is.character(compressor)) { 40 | stop("Parameter compressor should be set to 'LZ4' or 'ZSTD'.") 41 | } 42 | 43 | if (!is.raw(x)) { 44 | stop("Parameter x is not set to a raw vector.") 45 | } 46 | 47 | compressed_vec <- fstcomp(x, compressor, as.integer(compression), hash) 48 | 49 | if (inherits(compressed_vec, "fst_error")) { 50 | stop(compressed_vec) 51 | } 52 | 53 | compressed_vec 54 | } 55 | 56 | 57 | #' Decompress a raw vector with compressed data. 58 | #' 59 | #' @param x raw vector with data previously compressed with \code{compress_fst}. 60 | #' 61 | #' @return a raw vector with previously compressed data. 62 | #' @export 63 | decompress_fst <- function(x) { 64 | 65 | if (!is.raw(x)) { 66 | stop("Parameter x should be a raw vector with compressed data.") 67 | } 68 | 69 | decompressed_vec <- fstdecomp(x) 70 | 71 | if (inherits(decompressed_vec, "fst_error")) { 72 | stop(decompressed_vec) 73 | } 74 | 75 | decompressed_vec 76 | } 77 | -------------------------------------------------------------------------------- /tests/testthat/test_encoding.R: -------------------------------------------------------------------------------- 1 | 2 | context("encoding") 3 | 4 | 5 | # some helper functions 6 | source("helper_fstwrite.R") 7 | 8 | 9 | # Clean testdata directory 10 | if (!file.exists("testdata")) { 11 | dir.create("testdata") 12 | } else { 13 | file.remove(list.files("testdata", full.names = TRUE)) 14 | } 15 | 16 | 17 | testwriteread <- function(x, encoding, uniform_encoding = TRUE) { 18 | fstwriteproxy(x, "testdata/encoding.fst", uniform_encoding) 19 | y <- fstreadproxy("testdata/encoding.fst") 20 | 21 | for (col in seq_len(ncol(x))) { 22 | if (typeof(x[[col]]) == "character") { 23 | expect_equal(Encoding(y[[col]]), rep(encoding[col], nrow(x))) 24 | } 25 | } 26 | 27 | expect_equal(x, y) 28 | } 29 | 30 | 31 | test_that("utf8, native and latin1 encodings", { 32 | native <- data.frame(x = rep("Arende", 5), stringsAsFactors = FALSE) 33 | latin1 <- data.frame(x = rep("Ärende", 5), stringsAsFactors = FALSE) 34 | Encoding(latin1$x) <- "latin1" 35 | utf8 <- data.frame(x = enc2utf8(rep("Ärende", 5)), stringsAsFactors = FALSE) 36 | 37 | # test encodings 38 | testwriteread(native, c("unknown")) 39 | testwriteread(latin1, c("latin1")) 40 | testwriteread(utf8, "UTF-8") 41 | }) 42 | 43 | 44 | test_that("I can eat glass in various languages", { 45 | x <- read.csv2("datasets/utf8.csv", encoding = "UTF-8", stringsAsFactors = FALSE) 46 | 47 | testwriteread(x, c("unknown", "UTF-8")) 48 | }) 49 | 50 | 51 | test_that("Mixed encodings", { 52 | x <- data.frame(Mixed = c("Ärende", enc2native("native"), enc2utf8("Ärende")), stringsAsFactors = FALSE) 53 | Encoding(x$Mixed[1]) <- "latin1" # be sure 54 | 55 | fstwriteproxy(x, "testdata/mixed.fst") 56 | y <- fstreadproxy("testdata/mixed.fst") 57 | 58 | expect_equal(Encoding(y$Mixed), c("latin1", "unknown", "latin1")) # recoded to latin1 59 | 60 | expect_failure(expect_equal(x, y)) # mix of unknown, latin1 and UTF-8 61 | 62 | expect_error( 63 | fstwriteproxy(x, "testdata/mixed.fst", uniform_encoding = FALSE), 64 | "Character vectors with mixed encodings are currently not supported" 65 | ) 66 | 67 | Encoding(x$Mixed[1]) <- "UTF-8" # mix of unknown and UTF-8 68 | expect_error( 69 | fstwriteproxy(x, "testdata/mixed.fst", uniform_encoding = FALSE), 70 | "Character vectors with mixed encodings are currently not supported" 71 | ) 72 | 73 | fstwriteproxy(x, "testdata/mixed.fst") 74 | y <- fstreadproxy("testdata/mixed.fst") 75 | 76 | expect_equal(Encoding(y$Mixed), c("UTF-8", "unknown", "UTF-8")) # recoded to UTF-8 77 | }) 78 | 79 | 80 | test_that("Column name encoding", { 81 | x <- read.csv2("datasets/utf8.csv", encoding = "UTF-8", stringsAsFactors = FALSE)[2, 2] 82 | 83 | df <- data.frame(X = 1:10) 84 | colnames(df) <- x 85 | 86 | fstwriteproxy(df, "testdata/enc_cols.fst") 87 | y <- fstreadproxy("testdata/enc_cols.fst") 88 | 89 | expect_equal(Encoding(colnames(y)), "UTF-8") 90 | }) 91 | -------------------------------------------------------------------------------- /R/openmp.R: -------------------------------------------------------------------------------- 1 | # fst - R package for ultra fast storage and retrieval of datasets 2 | # 3 | # Copyright (C) 2017-present, Mark AJ Klik 4 | # 5 | # This file is part of the fst R package. 6 | # 7 | # The fst R package is free software: you can redistribute it and/or modify it 8 | # under the terms of the GNU Affero General Public License version 3 as 9 | # published by the Free Software Foundation. 10 | # 11 | # The fst R package is distributed in the hope that it will be useful, but 12 | # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 14 | # for more details. 15 | # 16 | # You should have received a copy of the GNU Affero General Public License along 17 | # with the fst R package. If not, see . 18 | # 19 | # You can contact the author at: 20 | # - fst R package source repository : https://github.com/fstpackage/fst 21 | 22 | 23 | #' Get or set the number of threads used in parallel operations 24 | #' 25 | #' For parallel operations, the performance is determined to a great extend by the number of threads 26 | #' used. More threads will allow the CPU to perform more computational intensive tasks simultaneously, 27 | #' speeding up the operation. Using more threads also introduces some overhead that will scale with the 28 | #' number of threads used. Therefore, using the maximum number of available threads is not always the 29 | #' fastest solution. With \code{threads_fst} the number of threads can be adjusted to the users 30 | #' specific requirements. As a default, \code{fst} uses a number of threads equal to the number of 31 | #' logical cores in the system. 32 | #' 33 | #' The number of threads can also be set with \code{options(fst_threads = N)}. 34 | #' NOTE: This option is only read when the package's namespace is first loaded, with commands like 35 | #' \code{library}, \code{require}, or \code{::}. If you have already used one of these, you 36 | #' must use \code{threads_fst} to set the number of threads. 37 | #' 38 | #' @param nr_of_threads number of threads to use or \code{NULL} to get the current number of threads used in 39 | #' multithreaded operations. 40 | #' @param reset_after_fork when \code{fst} is running in a forked process, the usage of OpenMP can 41 | #' create problems. To prevent these, \code{fst} switches back to single core usage when it detects a fork. 42 | #' After the fork, the number of threads is reset to it's initial setting. However, on some compilers 43 | #' (e.g. Intel), switching back to multi-threaded mode can lead to issues. When \code{reset_after_fork} 44 | #' is set to \code{FALSE}, \code{fst} is left in single-threaded mode after the fork ends. After the fork, 45 | #' multithreading can be activated again manually by calling \code{threads_fst} with an appropriate value 46 | #' for \code{nr_of_threads}. The default (\code{reset_after_fork = NULL}) leaves the fork behavior unchanged. 47 | #' 48 | #' @return the number of threads (previously) used 49 | #' @export 50 | threads_fst <- function(nr_of_threads = NULL, reset_after_fork = NULL) { 51 | fstcore::threads_fstlib(nr_of_threads, reset_after_fork) 52 | } 53 | -------------------------------------------------------------------------------- /man/write_fst.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/fst.R 3 | \name{write_fst} 4 | \alias{write_fst} 5 | \alias{write.fst} 6 | \alias{read_fst} 7 | \alias{read.fst} 8 | \title{Read and write fst files.} 9 | \usage{ 10 | write_fst(x, path, compress = 50, uniform_encoding = TRUE) 11 | 12 | write.fst(x, path, compress = 50, uniform_encoding = TRUE) 13 | 14 | read_fst( 15 | path, 16 | columns = NULL, 17 | from = 1, 18 | to = NULL, 19 | as.data.table = FALSE, 20 | old_format = FALSE 21 | ) 22 | 23 | read.fst( 24 | path, 25 | columns = NULL, 26 | from = 1, 27 | to = NULL, 28 | as.data.table = FALSE, 29 | old_format = FALSE 30 | ) 31 | } 32 | \arguments{ 33 | \item{x}{a data frame to write to disk} 34 | 35 | \item{path}{path to fst file} 36 | 37 | \item{compress}{value in the range 0 to 100, indicating the amount of compression to use. 38 | Lower values mean larger file sizes. The default compression is set to 50.} 39 | 40 | \item{uniform_encoding}{If `TRUE`, all character vectors will be assumed to have elements with equal encoding. 41 | The encoding (latin1, UTF8 or native) of the first non-NA element will used as encoding for the whole column. 42 | This will be a correct assumption for most use cases. 43 | If `uniform.encoding` is set to `FALSE`, no such assumption will be made and all elements will be converted 44 | to the same encoding. The latter is a relatively expensive operation and will reduce write performance for 45 | character columns.} 46 | 47 | \item{columns}{Column names to read. The default is to read all columns.} 48 | 49 | \item{from}{Read data starting from this row number.} 50 | 51 | \item{to}{Read data up until this row number. The default is to read to the last row of the stored dataset.} 52 | 53 | \item{as.data.table}{If TRUE, the result will be returned as a \code{data.table} object. Any keys set on 54 | dataset \code{x} before writing will be retained. This allows for storage of sorted datasets. This option 55 | requires \code{data.table} package to be installed.} 56 | 57 | \item{old_format}{must be FALSE, the old fst file format is deprecated and can only be read and 58 | converted with fst package versions 0.8.0 to 0.8.10.} 59 | } 60 | \value{ 61 | `read_fst` returns a data frame with the selected columns and rows. `write_fst` 62 | writes `x` to a `fst` file and invisibly returns `x` (so you can use this function in a pipeline). 63 | } 64 | \description{ 65 | Read and write data frames from and to a fast-storage (`fst`) file. 66 | Allows for compression and (file level) random access of stored data, even for compressed datasets. 67 | Multiple threads are used to obtain high (de-)serialization speeds but all background threads are 68 | re-joined before `write_fst` and `read_fst` return (reads and writes are stable). 69 | When using a `data.table` object for `x`, the key (if any) is preserved, 70 | allowing storage of sorted data. 71 | Methods `read_fst` and `write_fst` are equivalent to `read.fst` and `write.fst` (but the 72 | former syntax is preferred). 73 | } 74 | \examples{ 75 | # Sample dataset 76 | x <- data.frame(A = 1:10000, B = sample(c(TRUE, FALSE, NA), 10000, replace = TRUE)) 77 | 78 | # Default compression 79 | fst_file <- tempfile(fileext = ".fst") 80 | write_fst(x, fst_file) # filesize: 17 KB 81 | y <- read_fst(fst_file) # read fst file 82 | # Maximum compression 83 | write_fst(x, fst_file, 100) # fileSize: 4 KB 84 | y <- read_fst(fst_file) # read fst file 85 | 86 | # Random access 87 | y <- read_fst(fst_file, "B") # read selection of columns 88 | y <- read_fst(fst_file, "A", 100, 200) # read selection of columns and rows 89 | } 90 | -------------------------------------------------------------------------------- /tests/testthat/test_roundtrip.R: -------------------------------------------------------------------------------- 1 | 2 | context("roundtrip-vector") 3 | 4 | 5 | # some helper functions 6 | source("helper_fstwrite.R") 7 | 8 | 9 | roundtrip_vector <- function(x) { 10 | df <- data.frame(x = x, stringsAsFactors = FALSE) 11 | roundtrip(df)$x 12 | } 13 | 14 | 15 | roundtrip_vector_dt <- function(x) { 16 | dt <- data.table(x = x, stringsAsFactors = FALSE) 17 | roundtrip(dt)$x 18 | } 19 | 20 | 21 | roundtrip <- function(df) { 22 | temp <- tempfile() 23 | fstwriteproxy(df, temp) 24 | on.exit(unlink(temp)) 25 | 26 | fstreadproxy(temp) 27 | } 28 | 29 | 30 | # Logical 31 | test_that("preserves three logical values", { 32 | x <- c(FALSE, TRUE, NA) 33 | expect_identical(roundtrip_vector(x), x) 34 | }) 35 | 36 | 37 | # Integer 38 | test_that("preserves integer values", { 39 | x <- 1:10 40 | x[sample(1:10, 3)] <- NA 41 | expect_identical(roundtrip_vector(x), x) 42 | }) 43 | 44 | 45 | # Double 46 | test_that("preserves special floating point values", { 47 | x <- c(Inf, -Inf, NaN, NA) 48 | expect_identical(roundtrip_vector(x), x) 49 | }) 50 | 51 | 52 | test_that("doesn't lose precision", { 53 | x <- c(1 / 3, sqrt(2), pi) 54 | expect_identical(roundtrip_vector(x), x) 55 | }) 56 | 57 | 58 | # Character 59 | test_that("preserves character values", { 60 | x <- c("this is a string", "", NA, "another string") 61 | expect_identical(roundtrip_vector(x), x) 62 | }) 63 | 64 | 65 | test_that("can have NA on end of string", { 66 | x <- c("this is a string", NA) 67 | expect_identical(roundtrip_vector(x), x) 68 | }) 69 | 70 | 71 | # Factor 72 | test_that("preserves simple factor", { 73 | x <- factor(c("abc", "def")) 74 | expect_identical(roundtrip_vector(x), x) 75 | }) 76 | 77 | 78 | test_that("preserves NA in factor and levels", { 79 | x1 <- factor(c("abc", "def", NA)) 80 | x2 <- addNA(x1) 81 | 82 | expect_identical(roundtrip_vector(x1), x1) 83 | expect_identical(roundtrip_vector(x2), x2) 84 | }) 85 | 86 | 87 | # Date 88 | test_that("preserves dates", { 89 | x <- as.Date("2010-01-01") + c(0L, 365L, NA) 90 | mode(x) <- "integer" 91 | res <- roundtrip_vector(x) 92 | class(res) <- c("IDate", "Date") # gains class IDate from data.table 93 | expect_identical(as.integer(res), as.integer(x)) 94 | }) 95 | 96 | 97 | # ITime 98 | test_that("preserves time of day", { 99 | x <- as.ITime(c(1:10, NA), origin = "1970-01-01") 100 | res <- roundtrip_vector_dt(x) 101 | expect_identical(res, x) 102 | 103 | mode(x) <- "double" 104 | res <- roundtrip_vector_dt(x) 105 | expect_identical(res, x) 106 | }) 107 | 108 | 109 | # POSIXct 110 | test_that("preserves times", { 111 | x1 <- ISOdate(2001, 10, 10, tz = "US/Pacific") + c(0, NA) 112 | x2 <- roundtrip_vector(x1) 113 | 114 | expect_identical(attr(x1, "tzone"), attr(x2, "tzone")) 115 | expect_identical(attr(x1, "class"), attr(x1, "class")) 116 | expect_identical(unclass(x1), unclass(x2)) 117 | 118 | mode(x1) <- "integer" 119 | x2 <- roundtrip_vector(x1) 120 | 121 | expect_identical(attr(x1, "tzone"), attr(x2, "tzone")) 122 | expect_identical(attr(x1, "class"), attr(x1, "class")) 123 | expect_identical(unclass(x1), unclass(x2)) 124 | 125 | }) 126 | 127 | 128 | test_that("throws error on POSIXlt", { 129 | df <- data.frame(x = Sys.time()) 130 | df$x <- as.POSIXlt(df$x) 131 | 132 | expect_error(roundtrip(df), "Unknown type found in column") 133 | }) 134 | 135 | 136 | # nolint start 137 | # Time -------------------------------------------------------------------- 138 | # 139 | # test_that("preserves hms", { 140 | # x <- hms::hms(1:100) 141 | # expect_identical(roundtrip_vector(x), x) 142 | # }) 143 | # 144 | # test_that("converts time to hms", { 145 | # x1 <- structure(1:100, class = "time") 146 | # x2 <- roundtrip_vector(x1) 147 | # 148 | # expect_s3_class(x2, "hms") 149 | # }) 150 | # 151 | # 152 | # 153 | # 154 | # test_that("doesn't lose undue precision", { 155 | # base <- ISOdate(2001, 10, 10) 156 | # x1 <- base + 1e-6 * (0:3) 157 | # x2 <- roundtrip_vector(x1) 158 | # 159 | # expect_identical(x1, x2) 160 | # }) 161 | # nolint end 162 | -------------------------------------------------------------------------------- /tests/testthat/test_factor.R: -------------------------------------------------------------------------------- 1 | 2 | context("factor column") 3 | 4 | 5 | # some helper functions 6 | source("helper_fstwrite.R") 7 | 8 | 9 | # Clean testdata directory 10 | if (!file.exists("FactorStore")) { 11 | dir.create("FactorStore") 12 | } else { 13 | file.remove(list.files("FactorStore", full.names = TRUE)) 14 | } 15 | 16 | 17 | char_vec <- function(nrofrows) { 18 | sapply(1:nrofrows, function(x) { 19 | paste(sample(LETTERS, sample(1:4, 1)), collapse = "") 20 | } 21 | ) 22 | } 23 | 24 | 25 | factor_vec <- function(nrofrows, nroflevels) { 26 | levels <- NULL 27 | while (length(levels) < nroflevels) { 28 | levels <- unique(c(levels, char_vec(nroflevels))) 29 | } 30 | 31 | levels <- levels[1:nroflevels] 32 | 33 | factor(sample(levels, nrofrows, replace = TRUE), levels = levels) 34 | } 35 | 36 | 37 | sample_data <- function(nrofrows, nroflevels) { 38 | data.frame(WFact1 = factor_vec(nrofrows, nroflevels), WFact2 = factor_vec(nrofrows, nroflevels)) 39 | } 40 | 41 | 42 | to_frame <- function(x) { 43 | data.frame(x, row.names = NULL, stringsAsFactors = FALSE) 44 | } 45 | 46 | 47 | test_write_read <- function(dt, offset = 3, cap = 3) { 48 | fstwriteproxy(dt, "FactorStore/data1.fst") 49 | 50 | # Read full dataset 51 | data <- fstreadproxy("FactorStore/data1.fst") 52 | expect_equal(dt, data) 53 | 54 | # Read with small offset 55 | data <- fstreadproxy("FactorStore/data1.fst", from = offset) 56 | expect_equal(to_frame(dt[offset:nrow(dt), , drop = FALSE]), data) 57 | 58 | # Read with medium offset 59 | data <- fstreadproxy("FactorStore/data1.fst", from = nrow(dt) - cap) 60 | expect_equal(to_frame(dt[(nrow(dt) - cap):nrow(dt), , drop = FALSE]), data) 61 | 62 | # Read less rows 63 | data <- fstreadproxy("FactorStore/data1.fst", to = cap) 64 | expect_equal(to_frame(dt[1:cap, , drop = FALSE]), data) 65 | 66 | # Read less rows 67 | data <- fstreadproxy("FactorStore/data1.fst", to = nrow(dt) - cap) 68 | expect_equal(to_frame(dt[1:(nrow(dt) - cap), , drop = FALSE]), data) 69 | 70 | # Read less rows with offset 71 | data <- fstreadproxy("FactorStore/data1.fst", from = offset, to = nrow(dt) - cap) 72 | expect_equal(to_frame(dt[offset:(nrow(dt) - cap), , drop = FALSE]), data) 73 | } 74 | 75 | 76 | test_that("Multiple sizes of 1-byte factor columns are stored correctly", { 77 | dt <- sample_data(30, 10) 78 | test_write_read(dt) 79 | test_write_read(dt[1:8, ]) 80 | test_write_read(dt[1:7, ]) 81 | # test large size here ? 82 | }) 83 | 84 | 85 | test_that("Multiple sizes of 2-byte factor columns are stored correctly", { 86 | dt <- sample_data(30, 257) 87 | test_write_read(dt) 88 | test_write_read(dt[1:4, ], 2, 2) 89 | test_write_read(dt[1:3, ], 1, 1) 90 | # test large size here ? 91 | }) 92 | 93 | 94 | # with thanks to @martinblostein for tracking the corresponding bug 95 | # see: https://github.com/fstpackage/fst/issues/128 96 | test_that("length 1 factor column with 2 byte level vector is stored correctly", { 97 | df <- data.frame(a = factor("X1", levels = paste0("X", 1:128))) 98 | write_fst(df, "FactorStore/one_row.fst") 99 | x <- read_fst("FactorStore/one_row.fst") 100 | 101 | expect_equal(df, x) 102 | }) 103 | 104 | 105 | test_that("Multiple sizes of 4-byte factor columns are stored correctly", { 106 | dt <- sample_data(30, 70000) 107 | test_write_read(dt) 108 | test_write_read(dt[1:8, ]) 109 | test_write_read(dt[1:7, ]) 110 | # test large size here ? 111 | }) 112 | 113 | 114 | test_that("Small factor with a single NA level", { 115 | dt <- data.frame(A = 1:3, B = as.factor(rep(NA, 3))) 116 | fstwriteproxy(dt, "FactorStore/data1.fst") 117 | expect_equal(fstreadproxy("FactorStore/data1.fst"), dt) 118 | }) 119 | 120 | 121 | test_that("Single block one-column factor with a single NA level", { 122 | dt <- data.frame(B = as.factor(rep(NA, 10))) 123 | test_write_read(dt) 124 | }) 125 | 126 | 127 | test_that("Single block factor with a single NA level", { 128 | dt <- data.frame(A = 1:1000, B = as.factor(rep(NA, 10))) 129 | test_write_read(dt) 130 | }) 131 | 132 | 133 | test_that("Medium factor with a single NA level", { 134 | dt <- data.frame(A = 1:10000, B = as.factor(rep(NA, 10000))) 135 | test_write_read(dt) 136 | }) 137 | -------------------------------------------------------------------------------- /CONDUCT.md: -------------------------------------------------------------------------------- 1 | 2 | # Contributor Covenant Code of Conduct 3 | 4 | ## Our Pledge 5 | 6 | We as members, contributors, and leaders pledge to make participation in our 7 | community a harassment-free experience for everyone, regardless of age, body 8 | size, visible or invisible disability, ethnicity, sex characteristics, gender 9 | identity and expression, level of experience, education, socio-economic status, 10 | nationality, personal appearance, race, religion, or sexual identity 11 | and orientation. 12 | 13 | We pledge to act and interact in ways that contribute to an open, welcoming, 14 | diverse, inclusive, and healthy community. 15 | 16 | ## Our Standards 17 | 18 | Examples of behavior that contributes to a positive environment for our 19 | community include: 20 | 21 | * Demonstrating empathy and kindness toward other people 22 | * Being respectful of differing opinions, viewpoints, and experiences 23 | * Giving and gracefully accepting constructive feedback 24 | * Accepting responsibility and apologizing to those affected by our mistakes, 25 | and learning from the experience 26 | * Focusing on what is best not just for us as individuals, but for the 27 | overall community 28 | 29 | Examples of unacceptable behavior include: 30 | 31 | * The use of sexualized language or imagery, and sexual attention or 32 | advances of any kind 33 | * Trolling, insulting or derogatory comments, and personal or political attacks 34 | * Public or private harassment 35 | * Publishing others' private information, such as a physical or email 36 | address, without their explicit permission 37 | * Other conduct which could reasonably be considered inappropriate in a 38 | professional setting 39 | 40 | ## Enforcement Responsibilities 41 | 42 | Community leaders are responsible for clarifying and enforcing our standards of 43 | acceptable behavior and will take appropriate and fair corrective action in 44 | response to any behavior that they deem inappropriate, threatening, offensive, 45 | or harmful. 46 | 47 | Community leaders have the right and responsibility to remove, edit, or reject 48 | comments, commits, code, wiki edits, issues, and other contributions that are 49 | not aligned to this Code of Conduct, and will communicate reasons for moderation 50 | decisions when appropriate. 51 | 52 | ## Scope 53 | 54 | This Code of Conduct applies within all community spaces, and also applies when 55 | an individual is officially representing the community in public spaces. 56 | Examples of representing our community include using an official e-mail address, 57 | posting via an official social media account, or acting as an appointed 58 | representative at an online or offline event. 59 | 60 | ## Enforcement 61 | 62 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 63 | reported to the community leaders responsible for enforcement at 64 | [INSERT CONTACT METHOD]. 65 | All complaints will be reviewed and investigated promptly and fairly. 66 | 67 | All community leaders are obligated to respect the privacy and security of the 68 | reporter of any incident. 69 | 70 | ## Enforcement Guidelines 71 | 72 | Community leaders will follow these Community Impact Guidelines in determining 73 | the consequences for any action they deem in violation of this Code of Conduct: 74 | 75 | ### 1. Correction 76 | 77 | **Community Impact**: Use of inappropriate language or other behavior deemed 78 | unprofessional or unwelcome in the community. 79 | 80 | **Consequence**: A private, written warning from community leaders, providing 81 | clarity around the nature of the violation and an explanation of why the 82 | behavior was inappropriate. A public apology may be requested. 83 | 84 | ### 2. Warning 85 | 86 | **Community Impact**: A violation through a single incident or series 87 | of actions. 88 | 89 | **Consequence**: A warning with consequences for continued behavior. No 90 | interaction with the people involved, including unsolicited interaction with 91 | those enforcing the Code of Conduct, for a specified period of time. This 92 | includes avoiding interactions in community spaces as well as external channels 93 | like social media. Violating these terms may lead to a temporary or 94 | permanent ban. 95 | 96 | ### 3. Temporary Ban 97 | 98 | **Community Impact**: A serious violation of community standards, including 99 | sustained inappropriate behavior. 100 | 101 | **Consequence**: A temporary ban from any sort of interaction or public 102 | communication with the community for a specified period of time. No public or 103 | private interaction with the people involved, including unsolicited interaction 104 | with those enforcing the Code of Conduct, is allowed during this period. 105 | Violating these terms may lead to a permanent ban. 106 | 107 | ### 4. Permanent Ban 108 | 109 | **Community Impact**: Demonstrating a pattern of violation of community 110 | standards, including sustained inappropriate behavior, harassment of an 111 | individual, or aggression toward or disparagement of classes of individuals. 112 | 113 | **Consequence**: A permanent ban from any sort of public interaction within 114 | the community. 115 | 116 | ## Attribution 117 | 118 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 119 | version 2.0, available at 120 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 121 | 122 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 123 | enforcement ladder](https://github.com/mozilla/diversity). 124 | 125 | [homepage]: https://www.contributor-covenant.org 126 | 127 | For answers to common questions about this code of conduct, see the FAQ at 128 | https://www.contributor-covenant.org/faq. Translations are available at 129 | https://www.contributor-covenant.org/translations. 130 | -------------------------------------------------------------------------------- /src/RcppExports.cpp: -------------------------------------------------------------------------------- 1 | // Generated by using Rcpp::compileAttributes() -> do not edit by hand 2 | // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 3 | 4 | #include 5 | 6 | using namespace Rcpp; 7 | 8 | #ifdef RCPP_USE_GLOBAL_ROSTREAM 9 | Rcpp::Rostream& Rcpp::Rcout = Rcpp::Rcpp_cout_get(); 10 | Rcpp::Rostream& Rcpp::Rcerr = Rcpp::Rcpp_cerr_get(); 11 | #endif 12 | 13 | // fststore 14 | SEXP fststore(Rcpp::String fileName, SEXP table, SEXP compression, SEXP uniformEncoding); 15 | RcppExport SEXP _fst_fststore(SEXP fileNameSEXP, SEXP tableSEXP, SEXP compressionSEXP, SEXP uniformEncodingSEXP) { 16 | BEGIN_RCPP 17 | Rcpp::RObject rcpp_result_gen; 18 | Rcpp::RNGScope rcpp_rngScope_gen; 19 | Rcpp::traits::input_parameter< Rcpp::String >::type fileName(fileNameSEXP); 20 | Rcpp::traits::input_parameter< SEXP >::type table(tableSEXP); 21 | Rcpp::traits::input_parameter< SEXP >::type compression(compressionSEXP); 22 | Rcpp::traits::input_parameter< SEXP >::type uniformEncoding(uniformEncodingSEXP); 23 | rcpp_result_gen = Rcpp::wrap(fststore(fileName, table, compression, uniformEncoding)); 24 | return rcpp_result_gen; 25 | END_RCPP 26 | } 27 | // fstmetadata 28 | SEXP fstmetadata(Rcpp::String fileName); 29 | RcppExport SEXP _fst_fstmetadata(SEXP fileNameSEXP) { 30 | BEGIN_RCPP 31 | Rcpp::RObject rcpp_result_gen; 32 | Rcpp::RNGScope rcpp_rngScope_gen; 33 | Rcpp::traits::input_parameter< Rcpp::String >::type fileName(fileNameSEXP); 34 | rcpp_result_gen = Rcpp::wrap(fstmetadata(fileName)); 35 | return rcpp_result_gen; 36 | END_RCPP 37 | } 38 | // fstretrieve 39 | SEXP fstretrieve(Rcpp::String fileName, SEXP columnSelection, SEXP startRow, SEXP endRow); 40 | RcppExport SEXP _fst_fstretrieve(SEXP fileNameSEXP, SEXP columnSelectionSEXP, SEXP startRowSEXP, SEXP endRowSEXP) { 41 | BEGIN_RCPP 42 | Rcpp::RObject rcpp_result_gen; 43 | Rcpp::RNGScope rcpp_rngScope_gen; 44 | Rcpp::traits::input_parameter< Rcpp::String >::type fileName(fileNameSEXP); 45 | Rcpp::traits::input_parameter< SEXP >::type columnSelection(columnSelectionSEXP); 46 | Rcpp::traits::input_parameter< SEXP >::type startRow(startRowSEXP); 47 | Rcpp::traits::input_parameter< SEXP >::type endRow(endRowSEXP); 48 | rcpp_result_gen = Rcpp::wrap(fstretrieve(fileName, columnSelection, startRow, endRow)); 49 | return rcpp_result_gen; 50 | END_RCPP 51 | } 52 | // fsthasher 53 | SEXP fsthasher(SEXP rawVec, SEXP seed, SEXP blockHash); 54 | RcppExport SEXP _fst_fsthasher(SEXP rawVecSEXP, SEXP seedSEXP, SEXP blockHashSEXP) { 55 | BEGIN_RCPP 56 | Rcpp::RObject rcpp_result_gen; 57 | Rcpp::RNGScope rcpp_rngScope_gen; 58 | Rcpp::traits::input_parameter< SEXP >::type rawVec(rawVecSEXP); 59 | Rcpp::traits::input_parameter< SEXP >::type seed(seedSEXP); 60 | Rcpp::traits::input_parameter< SEXP >::type blockHash(blockHashSEXP); 61 | rcpp_result_gen = Rcpp::wrap(fsthasher(rawVec, seed, blockHash)); 62 | return rcpp_result_gen; 63 | END_RCPP 64 | } 65 | // fstcomp 66 | SEXP fstcomp(SEXP rawVec, SEXP compressor, SEXP compression, SEXP hash); 67 | RcppExport SEXP _fst_fstcomp(SEXP rawVecSEXP, SEXP compressorSEXP, SEXP compressionSEXP, SEXP hashSEXP) { 68 | BEGIN_RCPP 69 | Rcpp::RObject rcpp_result_gen; 70 | Rcpp::RNGScope rcpp_rngScope_gen; 71 | Rcpp::traits::input_parameter< SEXP >::type rawVec(rawVecSEXP); 72 | Rcpp::traits::input_parameter< SEXP >::type compressor(compressorSEXP); 73 | Rcpp::traits::input_parameter< SEXP >::type compression(compressionSEXP); 74 | Rcpp::traits::input_parameter< SEXP >::type hash(hashSEXP); 75 | rcpp_result_gen = Rcpp::wrap(fstcomp(rawVec, compressor, compression, hash)); 76 | return rcpp_result_gen; 77 | END_RCPP 78 | } 79 | // fstdecomp 80 | SEXP fstdecomp(SEXP rawVec); 81 | RcppExport SEXP _fst_fstdecomp(SEXP rawVecSEXP) { 82 | BEGIN_RCPP 83 | Rcpp::RObject rcpp_result_gen; 84 | Rcpp::RNGScope rcpp_rngScope_gen; 85 | Rcpp::traits::input_parameter< SEXP >::type rawVec(rawVecSEXP); 86 | rcpp_result_gen = Rcpp::wrap(fstdecomp(rawVec)); 87 | return rcpp_result_gen; 88 | END_RCPP 89 | } 90 | // getnrofthreads 91 | SEXP getnrofthreads(); 92 | RcppExport SEXP _fst_getnrofthreads() { 93 | BEGIN_RCPP 94 | Rcpp::RObject rcpp_result_gen; 95 | Rcpp::RNGScope rcpp_rngScope_gen; 96 | rcpp_result_gen = Rcpp::wrap(getnrofthreads()); 97 | return rcpp_result_gen; 98 | END_RCPP 99 | } 100 | // setnrofthreads 101 | int setnrofthreads(SEXP nrOfThreads); 102 | RcppExport SEXP _fst_setnrofthreads(SEXP nrOfThreadsSEXP) { 103 | BEGIN_RCPP 104 | Rcpp::RObject rcpp_result_gen; 105 | Rcpp::RNGScope rcpp_rngScope_gen; 106 | Rcpp::traits::input_parameter< SEXP >::type nrOfThreads(nrOfThreadsSEXP); 107 | rcpp_result_gen = Rcpp::wrap(setnrofthreads(nrOfThreads)); 108 | return rcpp_result_gen; 109 | END_RCPP 110 | } 111 | // restore_after_fork 112 | void restore_after_fork(bool restore); 113 | RcppExport SEXP _fst_restore_after_fork(SEXP restoreSEXP) { 114 | BEGIN_RCPP 115 | Rcpp::RNGScope rcpp_rngScope_gen; 116 | Rcpp::traits::input_parameter< bool >::type restore(restoreSEXP); 117 | restore_after_fork(restore); 118 | return R_NilValue; 119 | END_RCPP 120 | } 121 | // hasopenmp 122 | SEXP hasopenmp(); 123 | RcppExport SEXP _fst_hasopenmp() { 124 | BEGIN_RCPP 125 | Rcpp::RObject rcpp_result_gen; 126 | Rcpp::RNGScope rcpp_rngScope_gen; 127 | rcpp_result_gen = Rcpp::wrap(hasopenmp()); 128 | return rcpp_result_gen; 129 | END_RCPP 130 | } 131 | 132 | static const R_CallMethodDef CallEntries[] = { 133 | {"_fst_fststore", (DL_FUNC) &_fst_fststore, 4}, 134 | {"_fst_fstmetadata", (DL_FUNC) &_fst_fstmetadata, 1}, 135 | {"_fst_fstretrieve", (DL_FUNC) &_fst_fstretrieve, 4}, 136 | {"_fst_fsthasher", (DL_FUNC) &_fst_fsthasher, 3}, 137 | {"_fst_fstcomp", (DL_FUNC) &_fst_fstcomp, 4}, 138 | {"_fst_fstdecomp", (DL_FUNC) &_fst_fstdecomp, 1}, 139 | {"_fst_getnrofthreads", (DL_FUNC) &_fst_getnrofthreads, 0}, 140 | {"_fst_setnrofthreads", (DL_FUNC) &_fst_setnrofthreads, 1}, 141 | {"_fst_restore_after_fork", (DL_FUNC) &_fst_restore_after_fork, 1}, 142 | {"_fst_hasopenmp", (DL_FUNC) &_fst_hasopenmp, 0}, 143 | {NULL, NULL, 0} 144 | }; 145 | 146 | RcppExport void R_init_fst(DllInfo *dll) { 147 | R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); 148 | R_useDynamicSymbols(dll, FALSE); 149 | } 150 | -------------------------------------------------------------------------------- /tests/testthat/test_compress.R: -------------------------------------------------------------------------------- 1 | 2 | context("in-memory compression") 3 | 4 | 5 | # Sample raw vector 6 | raw_vector <- function(length) { 7 | as.raw(sample(1:10, length, replace = TRUE)) 8 | } 9 | 10 | raw_vec <- raw_vector(100) # vector size less than single block 11 | 12 | 13 | test_that("interface for compressing raw vectors", { 14 | y <- compress_fst(raw_vec) 15 | expect_equal(typeof(y), "raw") 16 | 17 | expect_error(compress_fst(5), "Parameter x is not set to a raw vector") 18 | 19 | expect_error(compress_fst(raw_vec, 4), "Parameter compressor should be set") 20 | 21 | expect_error(compress_fst(raw_vec, compression = TRUE), "Parameter compression should be a numeric value") 22 | 23 | expect_error(compress_fst(raw_vec[0], compressor = "LZ4", compression = 0), "Source contains no data") 24 | }) 25 | 26 | 27 | # rest write / read cycle for single vector and compression settings 28 | test_round_cycle <- function(vec, compressor, compression) { 29 | y <- compress_fst(raw_vec, compressor, compression) 30 | z <- decompress_fst(y) 31 | 32 | expect_equal(raw_vec, z, info = paste("compressor:", compressor, "compression:", compression)) # return type 33 | 34 | y 35 | } 36 | 37 | 38 | # rest write / read cycle for multiple compression settings 39 | test_vec <- function(raw_vec) { 40 | y1 <- test_round_cycle(raw_vec, "LZ4", 0) 41 | y2 <- test_round_cycle(raw_vec, "LZ4", 100) 42 | y3 <- test_round_cycle(raw_vec, "ZSTD", 0) 43 | y4 <- test_round_cycle(raw_vec, "ZSTD", 100) 44 | 45 | list(y1, y2, y3, y4) 46 | } 47 | 48 | 49 | test_that("compress round cycle small vector", { 50 | # single core 51 | threads_fst(1) 52 | comp_result1 <- test_vec(raw_vec) 53 | 54 | # dual core (max on CRAN) 55 | threads_fst(2) 56 | comp_result2 <- test_vec(raw_vec) 57 | 58 | # result independent of the number of blocks used 59 | expect_equal(comp_result1, comp_result2) 60 | }) 61 | 62 | 63 | test_that("compress round cycle single block", { 64 | # compress_fst prefers 48 block of at least 16384 bytes (16 kB) 65 | raw_vec <- raw_vector(16384) # exactly single block 66 | 67 | # single core single block 68 | threads_fst(1) 69 | comp_result1 <- test_vec(raw_vec) 70 | 71 | # only 1 core will be active on a single block 72 | threads_fst(2) 73 | comp_result2 <- test_vec(raw_vec) 74 | 75 | # result independent of the number of blocks used 76 | expect_equal(comp_result1, comp_result2) 77 | }) 78 | 79 | 80 | test_that("compress round cycle around single block", { 81 | # compress_fst prefers 48 block of at least 16384 bytes (16 kB) 82 | raw_vec <- raw_vector(16383) # exactly single block minus 1 83 | 84 | # single core single block 85 | threads_fst(1) 86 | comp_result1 <- test_vec(raw_vec) 87 | 88 | # only 1 core will be active on a single block 89 | threads_fst(2) 90 | comp_result2 <- test_vec(raw_vec) 91 | 92 | # result independent of the number of blocks used 93 | expect_equal(comp_result1, comp_result2) 94 | 95 | raw_vec <- raw_vector(16385) # exactly single block plus 1 96 | 97 | # single core single block 98 | threads_fst(1) 99 | comp_result1 <- test_vec(raw_vec) 100 | 101 | # 2 cores will be active on two blocks 102 | threads_fst(2) 103 | comp_result2 <- test_vec(raw_vec) 104 | 105 | # result independent of the number of blocks used 106 | expect_equal(comp_result1, comp_result2) 107 | }) 108 | 109 | 110 | test_that("compress round cycle multiple blocks per thread", { 111 | raw_vec <- raw_vector(100000) 112 | 113 | threads_fst(1) 114 | comp_result1 <- test_vec(raw_vec) 115 | 116 | threads_fst(2) 117 | comp_result2 <- test_vec(raw_vec) 118 | 119 | # result independent of the number of blocks used 120 | expect_equal(comp_result1, comp_result2) 121 | }) 122 | 123 | 124 | test_that("compress round cycle blocksize larger than 16kB", { 125 | raw_vec <- raw_vector(1000000) 126 | 127 | threads_fst(1) 128 | comp_result1 <- test_vec(raw_vec) 129 | 130 | threads_fst(2) 131 | comp_result2 <- test_vec(raw_vec) 132 | 133 | # result independent of the number of blocks used 134 | expect_equal(comp_result1, comp_result2) 135 | }) 136 | 137 | 138 | raw_vec <- raw_vector(50000) # 4 blocks 139 | 140 | 141 | test_that("erroneous compressed data", { 142 | # Test LZ4 compressor 143 | z <- compress_fst(raw_vec, compressor = "LZ4", compression = 100) # note: very bad compression ratio 144 | 145 | y <- z 146 | y[41:48] <- as.raw(0L) # mess up second block offset 147 | expect_error(decompress_fst(y), "Incorrect header information found") 148 | 149 | y <- z 150 | y[17:24] <- as.raw(0L) # set vector length to zero 151 | expect_error(decompress_fst(y), "Incorrect header information found") 152 | 153 | y <- decompress_fst(z) 154 | expect_equal(raw_vec, y) # return type 155 | 156 | # Test ZSTD compressor 157 | y <- compress_fst(raw_vec, compressor = "ZSTD", compression = 0) 158 | z <- decompress_fst(y) 159 | expect_equal(raw_vec, z) # return type 160 | 161 | y <- compress_fst(raw_vec, compressor = "ZSTD", compression = 100) # maximum compression 162 | z <- decompress_fst(y) 163 | expect_equal(raw_vec, z) # return type 164 | 165 | # Mess up compressed data block 166 | # Header has length 76, so data of first block starts at byte 77 167 | 168 | # This error is catched by ZSTD 169 | y[77] <- as.raw(0L) # set vector length to zero 170 | expect_error(decompress_fst(y), "An error was detected in the compressed data stream") 171 | 172 | # If using block hashes, erro is catched by fst 173 | y <- compress_fst(raw_vec, compressor = "ZSTD", compression = 100, hash = TRUE) # hash data blocks 174 | y[77] <- as.raw(0L) # set vector length to zero 175 | expect_error(decompress_fst(y), "Incorrect input vector") 176 | }) 177 | 178 | 179 | test_that("hash can use custom seed", { 180 | hash1 <- hash_fst(raw_vec) 181 | hash2 <- hash_fst(raw_vec, 345345) 182 | 183 | # alter vector in two places 184 | raw_vec[100] <- as.raw((as.integer(raw_vec[100]) + 2) %% 256) ## nolint 185 | raw_vec[200] <- as.raw((as.integer(raw_vec[200]) + 2) %% 256) ## nolint 186 | hash3 <- hash_fst(raw_vec) 187 | 188 | expect_true(sum(hash1 != hash2) == 2) 189 | expect_true(sum(hash1 != hash3) == 2) 190 | }) 191 | 192 | 193 | test_that("block_hash can be set", { 194 | hash1 <- hash_fst(raw_vec) 195 | 196 | # larger than 1 block raw vectors give different results 197 | hash4 <- hash_fst(raw_vec, block_hash = FALSE) # single threaded hash 198 | expect_true(sum(hash1 != hash4) == 2) 199 | 200 | small_raw_vec <- as.raw(rep(0, 10)) 201 | hash1 <- hash_fst(small_raw_vec) 202 | 203 | # smaller than 1 block raw vectors give identical results 204 | hash4 <- hash_fst(small_raw_vec, block_hash = FALSE) # single threaded hash 205 | expect_true(sum(hash1 != hash4) == 0) 206 | }) 207 | 208 | 209 | 210 | test_that("argument error", { 211 | expect_error(compress_fst(1), "Parameter x is not set to a raw vector") 212 | 213 | expect_error(hash_fst(as.raw(1), "no integer"), "Please specify an integer value for the hash seed") 214 | 215 | expect_error(hash_fst(1), "Please specify a raw vector as input parameter x") 216 | 217 | expect_error(hash_fst(as.raw(1), block_hash = 1), "Please specify a logical value for parameter block_hash") 218 | 219 | }) 220 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | [![Build 7 | Status](https://github.com/fstpackage/fst/actions/workflows/R-CMD-check.yaml/badge.svg?branch=develop)](https://github.com/fstpackage/fst/actions/workflows/R-CMD-check.yaml) 8 | [![License: AGPL 9 | v3](https://img.shields.io/badge/License-AGPL%20v3-blue.svg)](https://www.gnu.org/licenses/agpl-3.0) 10 | [![CRAN_Status_Badge](https://www.r-pkg.org/badges/version/fst)](https://cran.r-project.org/package=fst) 11 | [![fastverse status 12 | badge](https://fastverse.r-universe.dev/badges/fst)](https://fastverse.r-universe.dev/ui#package:fastverse) 13 | [![codecov](https://codecov.io/gh/fstpackage/fst/branch/develop/graph/badge.svg)](https://app.codecov.io/gh/fstpackage/fst) 14 | [![downloads](https://cranlogs.r-pkg.org/badges/fst)](http://cran.rstudio.com/web/packages/fst/index.html) 15 | [![total_downloads](https://cranlogs.r-pkg.org/badges/grand-total/fst)](http://cran.rstudio.com/web/packages/fst/index.html) 16 | 17 | ## Overview 18 | 19 | The [*fst* package](https://github.com/fstpackage/fst) for R provides a 20 | fast, easy and flexible way to serialize data frames. With access speeds 21 | of multiple GB/s, *fst* is specifically designed to unlock the potential 22 | of high speed solid state disks that can be found in most modern 23 | computers. Data frames stored in the *fst* format have full random 24 | access, both in column and rows. 25 | 26 | The figure below compares the read and write performance of the *fst* 27 | package to various alternatives. 28 | 29 | | Method | Format | Time (ms) | Size (MB) | Speed (MB/s) | N | 30 | |:--------------|:--------|:----------|:----------|:-------------|:--------| 31 | | readRDS | bin | 1577 | 1000 | 633 | 112 | 32 | | saveRDS | bin | 2042 | 1000 | 489 | 112 | 33 | | fread | csv | 2925 | 1038 | 410 | 232 | 34 | | fwrite | csv | 2790 | 1038 | 358 | 241 | 35 | | read_feather | bin | 3950 | 813 | 253 | 112 | 36 | | write_feather | bin | 1820 | 813 | 549 | 112 | 37 | | **read_fst** | **bin** | **457** | **303** | **2184** | **282** | 38 | | **write_fst** | **bin** | **314** | **303** | **3180** | **291** | 39 | 40 | These benchmarks were performed on a laptop (i7 4710HQ @2.5 GHz) with a 41 | reasonably fast SSD (M.2 Samsung SM951) using the dataset defined below. 42 | Parameter *Speed* was calculated by dividing the in-memory size of the 43 | data frame by the measured time. These results are also visualized in 44 | the following graph: 45 | 46 | ![](man/figures/README-speed-bench-1.png) 47 | 48 | As can be seen from the figure, the measured speeds for the *fst* 49 | package are very high and even top the maximum drive speed of the SSD 50 | used. The package accomplishes this by an effective combination of 51 | multi-threading and compression. The on-disk file sizes of *fst* files 52 | are also much smaller than that of the other formats tested. This is an 53 | added benefit of *fst*’s use of type-specific compressors on each stored 54 | column. 55 | 56 | In addition to methods for data frame serialization, *fst* also provides 57 | methods for multi-threaded in-memory compression with the popular LZ4 58 | and ZSTD compressors and an extremely fast multi-threaded hasher. 59 | 60 | ## Multi-threading 61 | 62 | The *fst* package relies heavily on multi-threading to boost the read- 63 | and write speed of data frames. To maximize throughput, *fst* compresses 64 | and decompresses data *in the background* and tries to keep the disk 65 | busy writing and reading data at the same time. 66 | 67 | ## Installation 68 | 69 | The easiest way to install the package is from CRAN: 70 | 71 | ``` r 72 | install.packages("fst") 73 | ``` 74 | 75 | You can also use the development version from GitHub: 76 | 77 | ``` r 78 | # install.packages("devtools") 79 | devtools::install_github("fstpackage/fst", ref = "develop") 80 | ``` 81 | 82 | ## Basic usage 83 | 84 | Using *fst* is simple. Data can be stored and retrieved using methods 85 | *write_fst* and *read_fst*: 86 | 87 | ``` r 88 | # Generate some random data frame with 10 million rows and various column types 89 | nr_of_rows <- 1e7 90 | 91 | df <- data.frame( 92 | Logical = sample(c(TRUE, FALSE, NA), prob = c(0.85, 0.1, 0.05), nr_of_rows, replace = TRUE), 93 | Integer = sample(1L:100L, nr_of_rows, replace = TRUE), 94 | Real = sample(sample(1:10000, 20) / 100, nr_of_rows, replace = TRUE), 95 | Factor = as.factor(sample(labels(UScitiesD), nr_of_rows, replace = TRUE)) 96 | ) 97 | 98 | # Store the data frame to disk 99 | write_fst(df, "dataset.fst") 100 | 101 | # Retrieve the data frame again 102 | df <- read_fst("dataset.fst") 103 | ``` 104 | 105 | *Note: the dataset defined in this example code was also used to obtain 106 | the benchmark results shown in the introduction.* 107 | 108 | ## Random access 109 | 110 | The *fst* file format provides full random access to stored datasets. 111 | You can retrieve a selection of columns and rows with: 112 | 113 | ``` r 114 | df_subset <- read_fst("dataset.fst", c("Logical", "Factor"), from = 2000, to = 5000) 115 | ``` 116 | 117 | This reads rows 2000 to 5000 from columns *Logical* and *Factor* without 118 | actually touching any other data in the stored file. That means that a 119 | subset can be read from file **without reading the complete file 120 | first**. This is different from, say, *readRDS* or *read_feather* where 121 | you have to read the complete file or column before you can make a 122 | subset. 123 | 124 | ## Compression 125 | 126 | For compression the excellent and speedy 127 | [LZ4](https://github.com/lz4/lz4) and 128 | [ZSTD](https://github.com/facebook/zstd) compression algorithms are 129 | used. These compressors (in combination with type-specific bit filters), 130 | enable *fst* to achieve high compression speeds at reasonable 131 | compression factors. The compression factor can be tuned from 0 132 | (minimum) to 100 (maximum): 133 | 134 | ``` r 135 | write_fst(df, "dataset.fst", 100) # use maximum compression 136 | ``` 137 | 138 | Compression reduces the size of the *fst* file that holds your data. But 139 | because the (de-)compression is done *on background threads*, it can 140 | increase the total read- and write speed as well. The graph below shows 141 | how the use of multiple threads enhances the read and write speed of our 142 | sample dataset. 143 | 144 | ![](man/figures/README-multi-threading-1.png) 145 | 146 | The *csv* format used by the *fread* and *fwrite* methods of package 147 | *data.table* is actually a human-readable text format and not a binary 148 | format. Normally, binary formats would be much faster than the *csv* 149 | format, because *csv* takes more space on disk, is row based, 150 | uncompressed and needs to be parsed into a computer-native format to 151 | have any meaning. So any serializer that’s working on *csv* has an 152 | enormous disadvantage as compared to binary formats. Yet, the results 153 | show that *data.table* is on par with binary formats and when more 154 | threads are used, it can even be faster. Because of this impressive 155 | performance, it was included in the graph for comparison. 156 | 157 | ## Bindings in other languages 158 | 159 | **Julia**: 160 | [**`FstFileFormat.jl`**](https://github.com/xiaodaigh/FstFileFormat.jl) 161 | A naive Julia binding using RCall.jl 162 | 163 | > **Note to users**: From CRAN release v0.8.0, the *fst* format is 164 | > stable and backwards compatible. That means that all *fst* files 165 | > generated with package v0.8.0 or later can be read by future versions 166 | > of the package. 167 | -------------------------------------------------------------------------------- /tests/testthat/test_meta.R: -------------------------------------------------------------------------------- 1 | 2 | context("metadata") 3 | 4 | 5 | library(data.table) 6 | 7 | 8 | require_extensions <- function() { 9 | requireNamespace("nanotime", quietly = TRUE) && requireNamespace("bit64", quietly = TRUE) 10 | } 11 | 12 | # Clean testdata directory 13 | if (!file.exists("testdata")) { 14 | dir.create("testdata") 15 | } else { 16 | file.remove(list.files("testdata", full.names = TRUE)) 17 | } 18 | 19 | 20 | posix_i <- as.integer(as.POSIXct("2001-02-03")) + 1L:5L 21 | class(posix_i) <- c("POSIXct", "POSIXt") 22 | 23 | date_i <- as.integer(Sys.Date() + 1:10) 24 | class(date_i) <- "Date" 25 | 26 | difftime <- (Sys.time() + 1:10) - Sys.time() 27 | difftime_int <- difftime 28 | mode(difftime_int) <- "integer" 29 | 30 | 31 | # Sample data 32 | x <- data.table( 33 | A = 1:10, 34 | B = sample(c(TRUE, FALSE, NA), 10, replace = TRUE), 35 | C = sample(1:100, 10) / 100, 36 | D = Sys.Date() + 1:10, 37 | E = sample(LETTERS, 10), 38 | F = factor(sample(LETTERS, 10)), 39 | G = as.POSIXct("2001-02-03") + 1:10, 40 | H = posix_i, 41 | I = date_i, 42 | J = as.raw(sample(0:255, 10)), 43 | K = ordered(sample(LETTERS, 10)), 44 | L = difftime, 45 | M = difftime_int, 46 | N = as.ITime(Sys.time() + 1:10) 47 | ) 48 | 49 | 50 | if (require_extensions()) { 51 | x$O <- bit64::as.integer64(101:110) # nolint 52 | x$P <- nanotime::nanotime(2:11) # nolint 53 | } 54 | 55 | 56 | test_that("v0.7.2 interface still works", { 57 | fstwriteproxy(x, "testdata/meta.fst") 58 | 59 | x <- fst.metadata("testdata/meta.fst") 60 | 61 | expect_true(!is.null(x)) 62 | }) 63 | 64 | 65 | test_that("format contains fst magic value", { 66 | zz <- file("testdata/meta.fst", "rb") # open file in binary mode 67 | header_hash <- readBin(zz, integer(), 12) 68 | close(zz) 69 | 70 | expect_equal(header_hash[3], 1) # fst format version (even numbers are dev versions) 71 | expect_equal(header_hash[12], 1346453840) # fst magic number 72 | expect_equal(header_hash[5], 0) # free bytes 73 | expect_equal(header_hash[6], 0) # free bytes 74 | }) 75 | 76 | 77 | test_that("Read meta of uncompressed file", { 78 | fstwriteproxy(x, "testdata/meta.fst") 79 | y <- fstmetaproxy("testdata/meta.fst") 80 | 81 | expect_equal(basename(y$path), basename("meta.fst")) 82 | expect_equal(y$nrOfRows, 10) 83 | expect_equal(y$keys, NULL) 84 | expect_equal(y$columnNames, LETTERS[1:16][seq_len(ncol(x))]) 85 | expect_equal(y$columnBaseTypes, c(4, 6, 5, 5, 2, 3, 5, 4, 4, 8, 3, 5, 4, 4, 7, 7)[seq_len(ncol(x))]) 86 | expect_equal(y$columnTypes, c(5, 15, 10, 11, 2, 3, 12, 6, 8, 18, 4, 13, 7, 9, 16, 17)[seq_len(ncol(x))]) 87 | }) 88 | 89 | 90 | test_that("Read meta of compressed file", { 91 | fstwriteproxy(x, "testdata/meta.fst", compress = 100) 92 | y <- fstmetaproxy("testdata/meta.fst") 93 | 94 | expect_equal(basename(y$path), "meta.fst") 95 | expect_equal(y$nrOfRows, 10) 96 | expect_equal(y$keys, NULL) 97 | expect_equal(y$columnNames, LETTERS[1:16][seq_len(ncol(x))]) 98 | expect_equal(y$columnBaseTypes, c(4, 6, 5, 5, 2, 3, 5, 4, 4, 8, 3, 5, 4, 4, 7, 7)[seq_len(ncol(x))]) 99 | expect_equal(y$columnTypes, c(5, 15, 10, 11, 2, 3, 12, 6, 8, 18, 4, 13, 7, 9, 16, 17)[seq_len(ncol(x))]) 100 | }) 101 | 102 | 103 | test_that("Print meta data without keys", { 104 | fstwriteproxy(x, "testdata/meta.fst", compress = 100) 105 | y <- fstmetaproxy("testdata/meta.fst") 106 | res <- capture_output(print(fstmetaproxy("testdata/meta.fst"))) 107 | 108 | if (require_extensions()) { 109 | expect_equal(res, paste( 110 | "\n10 rows, 16 columns (meta.fst)\n", 111 | "* 'A': integer", 112 | "* 'B': logical", 113 | "* 'C': double", 114 | "* 'D': Date", 115 | "* 'E': character", 116 | "* 'F': factor", 117 | "* 'G': POSIXct", 118 | "* 'H': POSIXct", 119 | "* 'I': IDate", 120 | "* 'J': raw", 121 | "* 'K': ordered factor", 122 | "* 'L': difftime", 123 | "* 'M': difftime", 124 | "* 'N': ITime", 125 | "* 'O': integer64", 126 | "* 'P': nanotime", 127 | sep = "\n" 128 | )) 129 | } else { 130 | expect_equal(res, paste( 131 | "\n10 rows, 14 columns (meta.fst)\n", 132 | "* 'A': integer", 133 | "* 'B': logical", 134 | "* 'C': double", 135 | "* 'D': Date", 136 | "* 'E': character", 137 | "* 'F': factor", 138 | "* 'G': POSIXct", 139 | "* 'H': POSIXct", 140 | "* 'I': IDate", 141 | "* 'J': raw", 142 | "* 'K': ordered factor", 143 | "* 'L': difftime", 144 | "* 'M': difftime", 145 | "* 'N': ITime", 146 | sep = "\n" 147 | )) 148 | } 149 | }) 150 | 151 | 152 | # raw sorting not supported 153 | x$J <- NULL # nolint 154 | 155 | 156 | test_that("Read meta of sorted file", { 157 | z <- copy(x) 158 | setkey(z, B, C) 159 | fstwriteproxy(z, "testdata/meta.fst") 160 | y <- fstmetaproxy("testdata/meta.fst") 161 | 162 | expect_equal(basename(y$path), "meta.fst") 163 | expect_equal(y$nrOfRows, 10) 164 | expect_equal(y$keys, c("B", "C")) 165 | expect_equal(y$columnNames, LETTERS[c(1:9, 11:16)][seq_len(ncol(x))]) 166 | expect_equal(y$columnBaseTypes, c(4, 6, 5, 5, 2, 3, 5, 4, 4, 3, 5, 4, 4, 7, 7)[seq_len(ncol(x))]) 167 | expect_equal(y$columnTypes, c(5, 15, 10, 11, 2, 3, 12, 6, 8, 4, 13, 7, 9, 16, 17)[seq_len(ncol(x))]) 168 | }) 169 | 170 | 171 | test_that("Print meta data with keys", { 172 | z <- copy(x) 173 | setkey(z, D, K, B) 174 | fstwriteproxy(z, "testdata/meta.fst", compress = 100) 175 | y <- fstmetaproxy("testdata/meta.fst") 176 | res <- capture_output(print(fstmetaproxy("testdata/meta.fst"))) 177 | 178 | if (require_extensions()) { 179 | expect_equal(res, paste( 180 | "\n10 rows, 15 columns (meta.fst)\n", 181 | "* 'D': Date (key 1)", 182 | "* 'K': ordered factor (key 2)", 183 | "* 'B': logical (key 3)", 184 | "* 'A': integer", 185 | "* 'C': double", 186 | "* 'E': character", 187 | "* 'F': factor", 188 | "* 'G': POSIXct", 189 | "* 'H': POSIXct", 190 | "* 'I': IDate", 191 | "* 'L': difftime", 192 | "* 'M': difftime", 193 | "* 'N': ITime", 194 | "* 'O': integer64", 195 | "* 'P': nanotime", 196 | sep = "\n" 197 | )) 198 | } else { 199 | expect_equal(res, paste( 200 | "\n10 rows, 13 columns (meta.fst)\n", 201 | "* 'D': Date (key 1)", 202 | "* 'K': ordered factor (key 2)", 203 | "* 'B': logical (key 3)", 204 | "* 'A': integer", 205 | "* 'C': double", 206 | "* 'E': character", 207 | "* 'F': factor", 208 | "* 'G': POSIXct", 209 | "* 'H': POSIXct", 210 | "* 'I': IDate", 211 | "* 'L': difftime", 212 | "* 'M': difftime", 213 | "* 'N': ITime", 214 | sep = "\n" 215 | )) 216 | } 217 | }) 218 | 219 | 220 | test_that("Print meta data with keys and unordered columns", { 221 | skip_if_not(require_extensions()) 222 | 223 | colnames(x) <- LETTERS[seq.int(ncol(x), 1)] 224 | 225 | setkey(x, L, F, N) # nolint 226 | fstwriteproxy(x, "testdata/meta.fst", compress = 100) 227 | y <- fstmetaproxy("testdata/meta.fst") 228 | res <- capture_output(print(fstmetaproxy("testdata/meta.fst"))) 229 | 230 | # note that columns are printed in original order (except keys) 231 | expect_equal(res, paste( 232 | "\n10 rows, 15 columns (meta.fst)\n", 233 | "* 'L': Date (key 1)", 234 | "* 'F': ordered factor (key 2)", 235 | "* 'N': logical (key 3)", 236 | "* 'O': integer", 237 | "* 'M': double", 238 | "* 'K': character", 239 | "* 'J': factor", 240 | "* 'I': POSIXct", 241 | "* 'H': POSIXct", 242 | "* 'G': IDate", 243 | "* 'E': difftime", 244 | "* 'D': difftime", 245 | "* 'C': ITime", 246 | "* 'B': integer64", 247 | "* 'A': nanotime", 248 | sep = "\n" 249 | )) 250 | }) 251 | -------------------------------------------------------------------------------- /tests/testthat/test_fst_table.R: -------------------------------------------------------------------------------- 1 | 2 | context("fst_table") 3 | 4 | 5 | # clean testdata directory 6 | if (!file.exists("testdata")) { 7 | dir.create("testdata") 8 | } else { 9 | file.remove(list.files("testdata", full.names = TRUE)) 10 | } 11 | 12 | 13 | # generate sample data and store 14 | df <- data.frame(X = 1:26, Y = LETTERS, Z = runif(26, 4, 7), stringsAsFactors = FALSE) 15 | test_file <- "testdata/fst_table.fst" 16 | write_fst(df, test_file) 17 | x <- fst(test_file) 18 | 19 | # single column table 20 | df2 <- df["X"] 21 | test_file2 <- "testdata/fst_table2.fst" 22 | write_fst(df2, test_file2) 23 | y <- fst(test_file2) 24 | 25 | 26 | # see issues #175 and #136 27 | test_that("fst_table does throw normalizePath error on non-existing file", { 28 | expect_error(fst("testdata/non_existing.fst"), "Error opening fst file for reading") 29 | }) 30 | 31 | 32 | test_that("fst_table returns a fst_table class object", { 33 | expect_equal(class(x), "fst_table") 34 | 35 | str_object <- unclass(x) 36 | expect_equal(names(str_object), c("meta", "col_selection", "row_selection", "old_format")) 37 | }) 38 | 39 | 40 | test_that("fst_table has basic data.frame interface", { 41 | expect_equal(as.data.frame(x), as.data.frame(df)) 42 | 43 | expect_equal(x[2], df[2]) 44 | 45 | expect_equal(x[2.6], df[2.6]) 46 | 47 | expect_equal(x[TRUE], df[TRUE]) 48 | 49 | expect_equal(x[c(1.1, 2)], df[c(1.1, 2)]) 50 | 51 | expect_equal(x[c(TRUE, FALSE)], df[c(TRUE, FALSE)]) 52 | 53 | expect_equal(x[c(TRUE, FALSE, TRUE)], df[c(TRUE, FALSE, TRUE)]) 54 | 55 | expect_equal(as.data.frame(x, row.names = LETTERS), as.data.frame(df, row.names = LETTERS)) 56 | 57 | expect_equal(as.list(x), as.list(df)) 58 | 59 | expect_equal(x[["Y"]], df[["Y"]]) 60 | 61 | expect_equal(x[["S"]], df[["S"]]) 62 | 63 | expect_equal(x$X, df$X) 64 | 65 | expect_equal(x$S, df$S) 66 | 67 | expect_equal(nrow(x), nrow(df)) 68 | 69 | expect_equal(ncol(x), ncol(df)) 70 | 71 | expect_equal(dim(x), dim(df)) 72 | 73 | expect_equal(dimnames(x), dimnames(df)) 74 | 75 | expect_equal(colnames(x), colnames(df)) 76 | 77 | expect_equal(rownames(x), rownames(df)) 78 | 79 | expect_equal(names(x), names(df)) 80 | 81 | expect_equal(x[[1:2]], df[[1:2]]) 82 | 83 | expect_equal(x[[c(2, 4)]], df[[c(2, 4)]]) 84 | 85 | expect_equal(x[["G"]], df[["G"]]) 86 | }) 87 | 88 | 89 | test_that("fst_table [ generic", { 90 | # '[' generic with 2 arguments 91 | 92 | expect_equal(x[], df[]) 93 | 94 | expect_equal(x[2], df[2]) 95 | 96 | expect_equal(x[i = 2], df[2]) 97 | 98 | expect_equal(x[j = 2], df[2]) 99 | 100 | expect_equal(x[drop = FALSE], df[, ]) 101 | 102 | # '[' generic with 3 arguments 103 | 104 | expect_equal(x[, ], df[, ]) 105 | 106 | expect_equal(x[, 2:3], df[, 2:3]) 107 | 108 | expect_equal(as.list(x[2, ]), as.list(df[2, ])) 109 | 110 | expect_equal(as.list(x[2:10, ]), as.list(df[2:10, ])) 111 | 112 | expect_equal(x[2, drop = FALSE], df[2]) 113 | 114 | expect_equal(as.list(x[2, 1:3]), as.list(df[2, 1:3])) 115 | 116 | # '[' generic with 4 arguments 117 | 118 | expect_equal(x[, , drop = FALSE], df[]) 119 | 120 | expect_equal(x[, , ], df[]) 121 | 122 | expect_equal(x[j = 2, drop = FALSE], df[2]) 123 | }) 124 | 125 | 126 | test_that("fst_table allows for drop argument", { 127 | # fst drops dimensions in same cases as data.frame. Less warnings are given. 128 | 129 | # 3 arguments: 130 | 131 | expect_equal(df[, "X"], x[, "X"]) 132 | expect_equal(df[2, "X"], x[2, "X"]) 133 | expect_equal(df[2:4, "X"], x[2:4, "X"]) 134 | 135 | # 4 arguments: 136 | 137 | expect_equal(df[, "X", drop = TRUE], x[, "X", drop = TRUE]) 138 | expect_equal(df[, "X", ], x[, "X", ]) 139 | expect_equal(df[2, "X", drop = TRUE], x[2, "X", drop = TRUE]) 140 | expect_equal(df[2, "X", ], x[2, "X", ]) 141 | expect_equal(df[2:4, "X", drop = TRUE], x[2:4, "X", drop = TRUE]) 142 | expect_equal(df[2:4, "X", ], x[2:4, "X", ]) 143 | expect_equal(df[2:4, 2, drop = TRUE], x[2:4, 2, drop = TRUE]) 144 | expect_equal(df[2:4, 2, ], x[2:4, 2, ]) 145 | }) 146 | 147 | 148 | test_that("fst_table throws errors on incorrect use of interface", { 149 | expect_error(x[[c("X", 3)]], "Subscript out of bounds") 150 | 151 | expect_error(x[[c("X", 3)]], "Subscript out of bounds") 152 | 153 | expect_error(x[4], "Subscript out of bounds") 154 | 155 | expect_error(x[5.3], "Subscript out of bounds") 156 | 157 | expect_error(x[c(1, NA, 2)], "Subscript out of bounds") 158 | 159 | expect_error(x[c(1.1, NA, 2)], "Subscript out of bounds") 160 | 161 | expect_error(x[c(TRUE, NA)], "Subscript out of bounds") 162 | 163 | expect_error(x[[as.integer(NULL)]], "Please use a length one integer or") 164 | 165 | expect_error(x[[c(2, 0)]], "Second index out of bounds") 166 | 167 | expect_error(x[[c(3, 100)]], "Second index out of bounds") 168 | 169 | expect_error(x[[5]], "Invalid column index 5") 170 | 171 | expect_error(x[[-3]], "Invalid column index -3") 172 | }) 173 | 174 | 175 | test_that("fst_table has correct printing for small single column table", { 176 | df <- data.frame(X = 1) 177 | write_fst(df, test_file) 178 | x <- fst(test_file) 179 | 180 | res <- capture_output(print(x)) 181 | res <- crayon::strip_style(res) 182 | 183 | expect_equal(res, paste( 184 | "", 185 | "1 rows, 1 columns (fst_table.fst)\n", 186 | " X", 187 | " ", 188 | "1 1", 189 | sep = "\n" 190 | )) 191 | }) 192 | 193 | 194 | test_that("fst_table has correct printing for big single column table", { 195 | df <- data.frame(X = 1:100) 196 | write_fst(df, test_file) 197 | x <- fst(test_file) 198 | 199 | res <- capture_output(print(x)) 200 | res <- crayon::strip_style(res) 201 | 202 | expect_equal(res, paste( 203 | "", 204 | "100 rows, 1 columns (fst_table.fst)\n", 205 | " X", 206 | " ", 207 | "1 1", 208 | "2 2", 209 | "3 3", 210 | "4 4", 211 | "5 5", 212 | "-- --", 213 | "96 96", 214 | "97 97", 215 | "98 98", 216 | "99 99", 217 | "100 100", 218 | sep = "\n" 219 | )) 220 | }) 221 | 222 | 223 | test_that("fst_table has correct printing for big multi column table", { 224 | df <- data.frame(X = 1:104, Y = c(LETTERS, LETTERS, LETTERS, LETTERS), stringsAsFactors = TRUE) 225 | write_fst(df, test_file) 226 | x <- fst(test_file) 227 | 228 | res <- capture_output(print(x)) 229 | res <- crayon::strip_style(res) 230 | 231 | expect_equal(res, paste( 232 | "", 233 | "104 rows, 2 columns (fst_table.fst)\n", 234 | " X Y", 235 | " ", 236 | "1 1 A", 237 | "2 2 B", 238 | "3 3 C", 239 | "4 4 D", 240 | "5 5 E", 241 | "-- -- --", 242 | "100 100 V", 243 | "101 101 W", 244 | "102 102 X", 245 | "103 103 Y", 246 | "104 104 Z", 247 | sep = "\n" 248 | )) 249 | }) 250 | 251 | 252 | test_that("fst_table has correct printing for small multi column table", { 253 | df <- data.frame(X = 1:9, Y = LETTERS[10:18], stringsAsFactors = TRUE) 254 | write_fst(df, test_file) 255 | x <- fst(test_file) 256 | 257 | res <- capture_output(print(x)) 258 | res <- crayon::strip_style(res) 259 | 260 | expect_equal(res, paste( 261 | "", 262 | "9 rows, 2 columns (fst_table.fst)\n", 263 | " X Y", 264 | " ", 265 | "1 1 J", 266 | "2 2 K", 267 | "3 3 L", 268 | "4 4 M", 269 | "5 5 N", 270 | "6 6 O", 271 | "7 7 P", 272 | "8 8 Q", 273 | "9 9 R", 274 | sep = "\n" 275 | )) 276 | }) 277 | -------------------------------------------------------------------------------- /tests/testthat/test_fst.R: -------------------------------------------------------------------------------- 1 | 2 | context("subsetting and compression") 3 | 4 | 5 | # some helper functions 6 | source("helper_fstwrite.R") 7 | 8 | 9 | # Clean testdata directory 10 | if (!file.exists("FactorStore")) { 11 | dir.create("FactorStore") 12 | } else { 13 | file.remove(list.files("FactorStore", full.names = TRUE)) 14 | } 15 | 16 | # Create a pool of strings 17 | nroflevels <- 8 18 | 19 | char_vec <- function(nr_of_rows) { 20 | sapply(1:nr_of_rows, function(x) { 21 | paste(sample(LETTERS, sample(1:4, 1)), collapse = "") 22 | }) 23 | } 24 | 25 | 26 | char_veclong <- function(nr_of_rows) { 27 | sapply( 28 | 1:nr_of_rows, 29 | function(x) { 30 | paste(sample(LETTERS, sample(20:25, 1)), collapse = "") 31 | } 32 | ) 33 | } 34 | 35 | 36 | date_vec <- function(nr_of_rows) { 37 | date_vec <- sample(1:nr_of_rows, replace = TRUE) 38 | class(date_vec) <- c("IDate", "Date") 39 | date_vec 40 | } 41 | 42 | 43 | difftime_vec <- function(nr_of_rows, mode = "double") { 44 | vec <- (Sys.time() + 1:nr_of_rows) - Sys.time() 45 | mode(vec) <- mode 46 | vec 47 | } 48 | 49 | 50 | # Sample data 51 | nr_of_rows <- 10000L 52 | char_na <- char_vec(nr_of_rows) 53 | char_na[sample(1:nr_of_rows, 10)] <- NA 54 | datatable <- data.frame( 55 | Xint = 1:nr_of_rows, 56 | Ylog = sample(c(TRUE, FALSE, NA), nr_of_rows, replace = TRUE), 57 | Zdoub = rnorm(nr_of_rows), 58 | Qchar = char_vec(nr_of_rows), 59 | WFact = factor(sample(char_vec(nroflevels), nr_of_rows, replace = TRUE)), 60 | Ordered = ordered(sample(char_vec(nroflevels), nr_of_rows, replace = TRUE)), 61 | char_na = char_na, 62 | CharLong = char_veclong(nr_of_rows), 63 | Date = date_vec(nr_of_rows), 64 | DateDouble = as.Date("2015-01-01") + 1:nr_of_rows, 65 | Raw = as.raw(sample(0:255, nr_of_rows, replace = TRUE)), 66 | Difftime = difftime_vec(nr_of_rows), 67 | DiffTime_int = difftime_vec(nr_of_rows, "integer"), 68 | stringsAsFactors = FALSE 69 | ) 70 | 71 | 72 | # A write / read cylce for a range of columns and rows 73 | test_write_read <- function( 74 | col, from = 1L, to = nr_of_rows, sel_columns = NULL, compress = 0L, 75 | tot_length = nr_of_rows) { 76 | dt <- datatable[1:tot_length, col, drop = FALSE] 77 | 78 | fstwriteproxy(dt, "FactorStore/data1.fst", compress) # use compression 79 | 80 | # Read full dataset 81 | to <- min(to, nr_of_rows) 82 | data <- fstreadproxy("FactorStore/data1.fst", columns = sel_columns, from = from, to = to) 83 | 84 | if (is.null(sel_columns)) { 85 | sub_dt <- dt[from:to, , drop = FALSE] 86 | } else { 87 | sub_dt <- dt[from:to, sel_columns, drop = FALSE] 88 | } 89 | 90 | row.names(sub_dt) <- NULL 91 | 92 | uneq <- sub_dt[, 1] != data[, 1] 93 | difftable <- sub_dt 94 | difftable[, "Row"] <- seq_len(nrow(difftable)) 95 | difftable[, "Other"] <- data[, 1] 96 | 97 | message <- paste( 98 | "args: col:", col, "| from:", from, "| to:", to, "| setColumns:", sel_columns, 99 | "| compress:", compress, "| tot_length", tot_length, " cols sub_dt:", ncol(sub_dt), ", rows sub_dt:", 100 | nrow(sub_dt), "cols data:", ncol(data), ", rows data:", nrow(data), 101 | "head sub_dt:", paste(sub_dt[1:10, 1], collapse = ","), 102 | "head data:", paste(data[1:10, 1], collapse = ","), 103 | "unequals:", sum(uneq), 104 | "uneq rows sub_dt1", paste(difftable[uneq, ][1:min(25, sum(uneq, na.rm = TRUE)), 1], collapse = ","), 105 | "uneq rows sub_dt2", paste(difftable[uneq, ][1:min(25, sum(uneq, na.rm = TRUE)), 2], collapse = ","), 106 | "uneq rows sub_dt3", paste(difftable[uneq, ][1:min(25, sum(uneq, na.rm = TRUE)), 3], collapse = ",") 107 | ) 108 | 109 | expect_equal(sub_dt, data, info = message) 110 | } 111 | 112 | col_names <- colnames(datatable) 113 | 114 | 115 | test_that("Single uncompressed vectors", { 116 | sapply( 117 | col_names, 118 | function(x) { 119 | test_write_read(x) 120 | } 121 | ) 122 | }) 123 | 124 | 125 | test_that("Small uncompressed vectors", { 126 | sapply(col_names, function(x) { 127 | test_write_read(x, to = 30L, tot_length = 30L) 128 | }) 129 | }) 130 | 131 | 132 | test_that("Single weakly compressed vectors", { 133 | sapply( 134 | col_names, 135 | function(x) { 136 | test_write_read(x, compress = 30L) 137 | } 138 | ) 139 | }) 140 | 141 | 142 | test_that("Single small weakly compressed vectors", { 143 | sapply( 144 | col_names, 145 | function(x) { 146 | test_write_read(x, to = 30L, tot_length = 30L, compress = 30L) 147 | } 148 | ) 149 | }) 150 | 151 | 152 | test_that("Single medium sized weakly compressed vectors", { 153 | sapply( 154 | col_names, 155 | function(x) { 156 | test_write_read(x, to = 8193L, tot_length = 8193L, compress = 30L) 157 | } 158 | ) 159 | }) 160 | 161 | 162 | test_that("Single moderate compressed vectors", { 163 | sapply( 164 | col_names, 165 | function(x) { 166 | test_write_read(x, compress = 60L) 167 | } 168 | ) 169 | }) 170 | 171 | 172 | test_that("Single small moderate compressed vectors", { 173 | sapply( 174 | col_names, 175 | function(x) { 176 | test_write_read(x, to = 30L, tot_length = 30L, compress = 60L) 177 | } 178 | ) 179 | }) 180 | 181 | 182 | # Various boundary conditions 183 | 184 | blocktests <- function(col, block_start, block_end, compression) { 185 | last_row <- min(block_end * block_size + block_size - 1L, nr_of_rows) 186 | test_write_read(col, 1L + block_start * block_size, last_row, NULL, compression) # full 187 | test_write_read(col, 1L + block_start * block_size + 4L, last_row, NULL, compression) # offset 188 | test_write_read(col, 1L + block_start * block_size, last_row - 10L, NULL, compression) # remainder 189 | } 190 | 191 | 192 | blocktestsingletype <- function(type) { 193 | # Single first block 194 | blocktests(type, 0, 0, 0L) # uncompressed 195 | blocktests(type, 0, 0, 40L) # algorithm 1 196 | blocktests(type, 0, 0, 80L) # algorithm 2 197 | 198 | # Single middle block 199 | blocktests(type, 1, 1, 0L) # uncompressed 200 | blocktests(type, 1, 1, 40L) # algorithm 1 201 | blocktests(type, 1, 1, 80L) # algorithm 2 202 | 203 | last_block <- as.integer((nr_of_rows - 1) / block_size) ## nolint 204 | 205 | # Single last block 206 | blocktests(type, last_block, last_block, 0L) # uncompressed 207 | blocktests(type, last_block, last_block, 40L) # algorithm 1 208 | blocktests(type, last_block, last_block, 80L) # algorithm 2 209 | 210 | # Multiple blocks 211 | blocktests(type, 0, 1, 0L) # uncompressed 212 | blocktests(type, last_block - 1, last_block, 0L) # uncompressed 213 | blocktests(type, 0, last_block, 0L) # uncompressed 214 | 215 | blocktests(type, 0, 1, 40L) # algorithm 1 216 | blocktests(type, last_block - 1, last_block, 40L) # algorithm 1 217 | blocktests(type, 0, last_block, 40L) # algorithm 1 218 | 219 | blocktests(type, 0, 1, 80L) # algorithm 2 220 | blocktests(type, last_block - 1, last_block, 80L) # algorithm 2 221 | blocktests(type, 0, last_block, 80L) # algorithm 2 222 | } 223 | 224 | 225 | block_size <- 4096 226 | 227 | # Test blocks 228 | test_that("Integer column block tests", { 229 | blocktestsingletype("Xint") 230 | }) 231 | 232 | 233 | test_that("Logical column block tests", { 234 | blocktestsingletype("Ylog") 235 | }) 236 | 237 | 238 | test_that("Date column block tests", { 239 | blocktestsingletype("Date") 240 | }) 241 | 242 | block_size <- 2048 243 | 244 | 245 | # Test blocks 246 | test_that("Real column block tests", { 247 | blocktestsingletype("Zdoub") 248 | }) 249 | 250 | 251 | block_size <- 2047 252 | 253 | test_that("Character column block tests", { 254 | blocktestsingletype("Qchar") 255 | }) 256 | 257 | 258 | test_that("Factor column block tests", { 259 | blocktestsingletype("WFact") 260 | }) 261 | 262 | 263 | test_that("Character column block tests with NA's", { 264 | blocktestsingletype("char_na") 265 | }) 266 | 267 | 268 | test_that("Mixed columns are stored correctly", { 269 | test_write_read(c("Xint", "Ylog", "Zdoub", "Qchar", "WFact", "char_na", "Date")) 270 | }) 271 | 272 | 273 | test_that("From and to row can be set", { 274 | test_write_read(c("Xint", "Ylog", "Zdoub", "Qchar", "WFact", "char_na", "Date"), from = 10) 275 | test_write_read(c("Xint", "Ylog", "Zdoub", "Qchar", "WFact", "char_na", "Date"), to = 8) 276 | test_write_read(c("Xint", "Ylog", "Zdoub", "Qchar", "WFact", "char_na", "Date"), from = 4, to = 13) 277 | }) 278 | 279 | 280 | test_that("Select columns", { 281 | test_write_read(c("Xint", "Ylog", "Zdoub", "Qchar", "WFact", "char_na", "Date"), 282 | sel_columns = "Zdoub" 283 | ) 284 | test_write_read(c("Xint", "Ylog", "Zdoub", "Qchar", "WFact", "char_na", "Date"), 285 | sel_columns = c("Ylog", "WFact") 286 | ) 287 | test_write_read(c("Xint", "Ylog", "Zdoub", "Qchar", "WFact", "char_na", "Date"), 288 | sel_columns = c("WFact", "Ylog") 289 | ) 290 | test_write_read(c("Xint", "Ylog", "Zdoub", "Qchar", "WFact", "char_na", "Date"), 291 | from = 7, to = 13, sel_columns = c("Ylog", "Qchar") 292 | ) 293 | }) 294 | 295 | 296 | test_that("Select unknown column", { 297 | expect_error(data <- fstreadproxy("FactorStore/data1.fds", columns = "bla")) 298 | expect_error(data <- fstreadproxy("FactorStore/data1.fds", columns = c("WFact", "bla"))) 299 | }) 300 | 301 | 302 | test_that("Select out of range row number", { 303 | test_write_read(c("Xint", "Ylog", "Zdoub", "Qchar", "WFact"), from = 4, to = 7000) 304 | test_write_read(c("Xint", "Ylog", "Zdoub", "Qchar", "WFact"), from = 4, to = NULL) 305 | expect_error( 306 | fstreadproxy("FactorStore/data1.fst", from = 12000, to = NULL), 307 | "Row selection is out of range" 308 | ) 309 | expect_error(fstreadproxy("FactorStore/data1.fst", from = 0, to = NULL), "Parameter 'from' should have") 310 | }) 311 | -------------------------------------------------------------------------------- /README.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | output: 3 | github_document 4 | --- 5 | 6 | 7 | 8 | ```{r, echo = FALSE} 9 | knitr::opts_chunk$set( 10 | collapse = TRUE, 11 | comment = "#>", 12 | fig.path = "man/figures/README-" 13 | ) 14 | ``` 15 | 16 | 17 | 18 | [![Build Status](https://github.com/fstpackage/fst/actions/workflows/R-CMD-check.yaml/badge.svg?branch=develop)](https://github.com/fstpackage/fst/actions/workflows/R-CMD-check.yaml) 19 | [![License: AGPL v3](https://img.shields.io/badge/License-AGPL%20v3-blue.svg)](https://www.gnu.org/licenses/agpl-3.0) 20 | [![CRAN_Status_Badge](https://www.r-pkg.org/badges/version/fst)](https://cran.r-project.org/package=fst) 21 | [![fastverse status badge](https://fastverse.r-universe.dev/badges/fst)](https://fastverse.r-universe.dev/ui#package:fastverse) 22 | [![codecov](https://codecov.io/gh/fstpackage/fst/branch/develop/graph/badge.svg)](https://app.codecov.io/gh/fstpackage/fst) 23 | [![downloads](https://cranlogs.r-pkg.org/badges/fst)](http://cran.rstudio.com/web/packages/fst/index.html) 24 | [![total_downloads](https://cranlogs.r-pkg.org/badges/grand-total/fst)](http://cran.rstudio.com/web/packages/fst/index.html) 25 | 26 | ## Overview 27 | 28 | The [_fst_ package][fstRepo] for R provides a fast, easy and flexible way to serialize data frames. With access speeds of multiple GB/s, _fst_ is specifically designed to unlock the potential of high speed solid state disks that can be found in most modern computers. Data frames stored in the _fst_ format have full random access, both in column and rows. 29 | 30 | The figure below compares the read and write performance of the _fst_ package to various alternatives. 31 | 32 | ```{r speedTable, results = 'asis', message = FALSE, echo = FALSE} 33 | require(ggplot2) 34 | require(data.table) 35 | require(fst) 36 | require(knitr) 37 | 38 | speed_results <- read_fst("res_readme.fst", as.data.table = TRUE) 39 | 40 | speeds <- speed_results[NrOfRows == 5e7, list( 41 | `Time (ms)` = as.integer(median(Time)), 42 | `Size (MB)` = format(median(FileSize), digits = 2), 43 | `Speed (MB/s)` = as.integer(median(Speed)), 44 | N = .N), 45 | by = "Package,Mode"] 46 | 47 | speeds[Package == "data.table" & Mode == "Write", Method := "fwrite"] 48 | speeds[Package == "data.table" & Mode == "Read", Method := "fread"] 49 | speeds[Package == "fst" & Mode == "Write", Method := "write_fst"] 50 | speeds[Package == "fst" & Mode == "Read", Method := "read_fst"] 51 | speeds[Package == "baseR" & Mode == "Write", Method := "saveRDS"] 52 | speeds[Package == "baseR" & Mode == "Read", Method := "readRDS"] 53 | speeds[Package == "feather" & Mode == "Write", Method := "write_feather"] 54 | speeds[Package == "feather" & Mode == "Read", Method := "read_feather"] 55 | speeds[, Format := "bin"] 56 | speeds[Package == "data.table", Format := "csv"] 57 | setkey(speeds, Package, Mode) 58 | 59 | display_speeds <- copy(speeds) 60 | for (col in colnames(display_speeds)[2:ncol(display_speeds)]) { 61 | setnames(display_speeds, col, "CurCol") 62 | display_speeds[, CurCol := as.character(CurCol)] 63 | display_speeds[Package == "fst", CurCol := paste0("**", CurCol, "**")] 64 | setnames(display_speeds, "CurCol", col) 65 | } 66 | 67 | kable(display_speeds[, c(7, 8, 3, 4, 5, 6)]) 68 | ``` 69 | 70 | These benchmarks were performed on a laptop (i7 4710HQ @2.5 GHz) with a reasonably fast SSD (M.2 Samsung SM951) using the dataset defined below. Parameter *Speed* was calculated by dividing the in-memory size of the data frame by the measured time. These results are also visualized in the following graph: 71 | 72 | ```{r speed-bench, echo = FALSE, message = FALSE, results = 'hide', fig.width = 8.5, fig.height = 6} 73 | ggplot(speed_results[NrOfRows == 5e7, .(Speed = median(Speed)), by = "Package,Mode"]) + 74 | geom_bar(aes(Mode, Speed, fill = Mode), colour = "darkgrey", stat = "identity") + 75 | facet_wrap(~ Package, 1) + 76 | ylim(0, NA) + 77 | ylab("Read or Write speed (MB/s)") + 78 | xlab("") + 79 | theme(legend.position="none") 80 | ``` 81 | 82 | As can be seen from the figure, the measured speeds for the _fst_ package are very high and even top the maximum drive speed of the SSD used. The package accomplishes this by an effective combination of multi-threading and compression. The on-disk file sizes of _fst_ files are also much smaller than that of the other formats tested. This is an added benefit of _fst_'s use of type-specific compressors on each stored column. 83 | 84 | In addition to methods for data frame serialization, _fst_ also provides methods for multi-threaded in-memory compression with the popular LZ4 and ZSTD compressors and an extremely fast multi-threaded hasher. 85 | 86 | ## Multi-threading 87 | 88 | The _fst_ package relies heavily on multi-threading to boost the read- and write speed of data frames. To maximize throughput, _fst_ compresses and decompresses data _in the background_ and tries to keep the disk busy writing and reading data at the same time. 89 | 90 | ## Installation 91 | 92 | The easiest way to install the package is from CRAN: 93 | 94 | ```{r, eval = FALSE} 95 | install.packages("fst") 96 | ``` 97 | 98 | You can also use the development version from GitHub: 99 | 100 | ```{r, eval = FALSE} 101 | # install.packages("devtools") 102 | devtools::install_github("fstpackage/fst", ref = "develop") 103 | ``` 104 | 105 | ## Basic usage 106 | 107 | ```{r, results = 'hide', echo = FALSE, message = FALSE} 108 | require(fst) 109 | ``` 110 | 111 | Using _fst_ is simple. Data can be stored and retrieved using methods _write\_fst_ and _read\_fst_: 112 | 113 | ```{r} 114 | # Generate some random data frame with 10 million rows and various column types 115 | nr_of_rows <- 1e7 116 | 117 | df <- data.frame( 118 | Logical = sample(c(TRUE, FALSE, NA), prob = c(0.85, 0.1, 0.05), nr_of_rows, replace = TRUE), 119 | Integer = sample(1L:100L, nr_of_rows, replace = TRUE), 120 | Real = sample(sample(1:10000, 20) / 100, nr_of_rows, replace = TRUE), 121 | Factor = as.factor(sample(labels(UScitiesD), nr_of_rows, replace = TRUE)) 122 | ) 123 | 124 | # Store the data frame to disk 125 | write_fst(df, "dataset.fst") 126 | 127 | # Retrieve the data frame again 128 | df <- read_fst("dataset.fst") 129 | ``` 130 | 131 | _Note: the dataset defined in this example code was also used to obtain the benchmark results shown in the introduction._ 132 | 133 | ## Random access 134 | 135 | The _fst_ file format provides full random access to stored datasets. You can retrieve a selection of columns and rows with: 136 | 137 | ```{r, results = 'hide'} 138 | df_subset <- read_fst("dataset.fst", c("Logical", "Factor"), from = 2000, to = 5000) 139 | ``` 140 | 141 | This reads rows 2000 to 5000 from columns _Logical_ and _Factor_ without actually touching any other data in the stored file. That means that a subset can be read from file **without reading the complete file first**. This is different from, say, _readRDS_ or _read\_feather_ where you have to read the complete file or column before you can make a subset. 142 | 143 | ## Compression 144 | 145 | For compression the excellent and speedy [LZ4][lz4Repo] and [ZSTD][zstdRepo] compression algorithms are used. These compressors (in combination with type-specific bit filters), enable _fst_ to achieve high compression speeds at reasonable compression factors. The compression factor can be tuned from 0 (minimum) to 100 (maximum): 146 | 147 | ```{r, results = 'hide'} 148 | write_fst(df, "dataset.fst", 100) # use maximum compression 149 | ``` 150 | 151 | Compression reduces the size of the _fst_ file that holds your data. But because the (de-)compression is done _on background threads_, it can increase the total read- and write speed as well. The graph below shows how the use of multiple threads enhances the read and write speed of our sample dataset. 152 | 153 | ```{r multi-threading, fig.width = 10, fig.height = 8, echo = FALSE} 154 | speed_results[Package %in% c("baseR", "feather"), Threads := 1] 155 | speed_results[, Threads := as.factor(Threads)] 156 | speed_results[, Speed := 0.001 * Speed] 157 | speed_results[, NrOfRows := ifelse(NrOfRows == 1e7, "1 million rows", "10 million rows")] 158 | 159 | 160 | fig_results <- speed_results[, .(Speed = median(Speed)), by = "Package,Mode,NrOfRows,Threads"] 161 | 162 | ggplot(fig_results) + 163 | geom_bar(aes(Package, Speed, fill = Threads), 164 | stat = "identity", position = "dodge", width = 0.8) + 165 | facet_grid(Mode ~ NrOfRows, scales = "free_y") + 166 | scale_fill_manual(values = colorRampPalette(c("#FBE3A5", "#433B54"))(10)[10:3]) + 167 | ylab("Read or write speed in GB/s") + 168 | theme_minimal() 169 | ``` 170 | 171 | The _csv_ format used by the _fread_ and _fwrite_ methods of package _data.table_ is actually a human-readable text format and not a binary format. Normally, binary formats would be much faster than the _csv_ format, because _csv_ takes more space on disk, is row based, uncompressed and needs to be parsed into a computer-native format to have any meaning. So any serializer that's working on _csv_ has an enormous disadvantage as compared to binary formats. Yet, the results show that _data.table_ is on par with binary formats and when more threads are used, it can even be faster. Because of this impressive performance, it was included in the graph for comparison. 172 | 173 | ## Bindings in other languages 174 | 175 | **Julia**: [**`FstFileFormat.jl`**][fstformatRepo] A naive Julia binding using RCall.jl 176 | 177 | > **Note to users**: From CRAN release v0.8.0, the _fst_ format is stable and backwards compatible. That means that all _fst_ files generated with package v0.8.0 or later can be read by future versions of the package. 178 | 179 | ```{r, echo = FALSE, results = 'hide'} 180 | # cleanup 181 | file.remove("dataset.fst") 182 | ``` 183 | 184 | [fstRepo]: https://github.com/fstpackage/fst 185 | [lz4Repo]: https://github.com/lz4/lz4 186 | [zstdRepo]: https://github.com/facebook/zstd 187 | [fstformatRepo]: https://github.com/xiaodaigh/FstFileFormat.jl 188 | -------------------------------------------------------------------------------- /R/fst.R: -------------------------------------------------------------------------------- 1 | # fst - R package for ultra fast storage and retrieval of datasets 2 | # 3 | # Copyright (C) 2017-present, Mark AJ Klik 4 | # 5 | # This file is part of the fst R package. 6 | # 7 | # The fst R package is free software: you can redistribute it and/or modify it 8 | # under the terms of the GNU Affero General Public License version 3 as 9 | # published by the Free Software Foundation. 10 | # 11 | # The fst R package is distributed in the hope that it will be useful, but 12 | # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 14 | # for more details. 15 | # 16 | # You should have received a copy of the GNU Affero General Public License along 17 | # with the fst R package. If not, see . 18 | # 19 | # You can contact the author at: 20 | # - fst R package source repository : https://github.com/fstpackage/fst 21 | 22 | 23 | #' Read and write fst files. 24 | #' 25 | #' Read and write data frames from and to a fast-storage (`fst`) file. 26 | #' Allows for compression and (file level) random access of stored data, even for compressed datasets. 27 | #' Multiple threads are used to obtain high (de-)serialization speeds but all background threads are 28 | #' re-joined before `write_fst` and `read_fst` return (reads and writes are stable). 29 | #' When using a `data.table` object for `x`, the key (if any) is preserved, 30 | #' allowing storage of sorted data. 31 | #' Methods `read_fst` and `write_fst` are equivalent to `read.fst` and `write.fst` (but the 32 | #' former syntax is preferred). 33 | #' 34 | #' @param x a data frame to write to disk 35 | #' @param path path to fst file 36 | #' @param compress value in the range 0 to 100, indicating the amount of compression to use. 37 | #' Lower values mean larger file sizes. The default compression is set to 50. 38 | #' @param uniform_encoding If `TRUE`, all character vectors will be assumed to have elements with equal encoding. 39 | #' The encoding (latin1, UTF8 or native) of the first non-NA element will used as encoding for the whole column. 40 | #' This will be a correct assumption for most use cases. 41 | #' If `uniform.encoding` is set to `FALSE`, no such assumption will be made and all elements will be converted 42 | #' to the same encoding. The latter is a relatively expensive operation and will reduce write performance for 43 | #' character columns. 44 | #' @return `read_fst` returns a data frame with the selected columns and rows. `write_fst` 45 | #' writes `x` to a `fst` file and invisibly returns `x` (so you can use this function in a pipeline). 46 | #' @examples 47 | #' # Sample dataset 48 | #' x <- data.frame(A = 1:10000, B = sample(c(TRUE, FALSE, NA), 10000, replace = TRUE)) 49 | #' 50 | #' # Default compression 51 | #' fst_file <- tempfile(fileext = ".fst") 52 | #' write_fst(x, fst_file) # filesize: 17 KB 53 | #' y <- read_fst(fst_file) # read fst file 54 | 55 | #' # Maximum compression 56 | #' write_fst(x, fst_file, 100) # fileSize: 4 KB 57 | #' y <- read_fst(fst_file) # read fst file 58 | #' 59 | #' # Random access 60 | #' y <- read_fst(fst_file, "B") # read selection of columns 61 | #' y <- read_fst(fst_file, "A", 100, 200) # read selection of columns and rows 62 | #' @export 63 | write_fst <- function(x, path, compress = 50, uniform_encoding = TRUE) { 64 | if (!is.character(path)) stop("Please specify a correct path.") 65 | 66 | if (!is.data.frame(x)) stop("Please make sure 'x' is a data frame.") 67 | 68 | dt <- fststore(normalizePath(path, mustWork = FALSE), x, as.integer(compress), uniform_encoding) 69 | 70 | if (inherits(dt, "fst_error")) { 71 | stop(dt) 72 | } 73 | 74 | return(invisible(x)) 75 | } 76 | 77 | 78 | #' Read metadata from a fst file 79 | #' 80 | #' Method for checking basic properties of the dataset stored in \code{path}. 81 | #' 82 | #' @param path path to fst file 83 | #' @param old_format must be FALSE, the old fst file format is deprecated and can only be read and 84 | #' converted with fst package versions 0.8.0 to 0.8.10. 85 | #' @return Returns a list with meta information on the stored dataset in \code{path}. 86 | #' Has class \code{fstmetadata}. 87 | #' @examples 88 | #' # Sample dataset 89 | #' x <- data.frame( 90 | #' First = 1:10, 91 | #' Second = sample(c(TRUE, FALSE, NA), 10, replace = TRUE), 92 | #' Last = sample(LETTERS, 10) 93 | #' ) 94 | #' 95 | #' # Write to fst file 96 | #' fst_file <- tempfile(fileext = ".fst") 97 | #' write_fst(x, fst_file) 98 | #' 99 | #' # Display meta information 100 | #' metadata_fst(fst_file) 101 | #' @export 102 | metadata_fst <- function(path, old_format = FALSE) { 103 | if (old_format != FALSE) { 104 | stop( 105 | "Parameter old_format is depricated, fst files written with fst package version", 106 | " lower than 0.8.0 should be read (and rewritten) using fst package versions <= 0.8.10." 107 | ) 108 | } 109 | 110 | full_path <- normalizePath(path, mustWork = FALSE) 111 | 112 | metadata <- fstmetadata(full_path) 113 | 114 | if (inherits(metadata, "fst_error")) { 115 | stop(metadata) 116 | } 117 | 118 | col_info <- list( 119 | path = full_path, nrOfRows = metadata$nrOfRows, 120 | keys = metadata$keyNames, columnNames = metadata$colNames, 121 | columnBaseTypes = metadata$colBaseType, keyColIndex = metadata$keyColIndex, 122 | columnTypes = metadata$colType 123 | ) 124 | class(col_info) <- "fstmetadata" 125 | 126 | col_info 127 | } 128 | 129 | 130 | #' @export 131 | print.fstmetadata <- function(x, ...) { 132 | cat("\n") 133 | cat(x$nrOfRows, " rows, ", length(x$columnNames), " columns (", basename(x$path), 134 | ")\n\n", 135 | sep = "" 136 | ) 137 | 138 | types <- c( 139 | "unknown", "character", "factor", "ordered factor", "integer", "POSIXct", "difftime", 140 | "IDate", "ITime", "double", "Date", "POSIXct", "difftime", "ITime", "logical", "integer64", 141 | "nanotime", "raw" 142 | ) 143 | 144 | # table has no key columns 145 | if (is.null(x$keys)) { 146 | column_names <- format(encodeString(x$columnNames, quote = "'")) 147 | cat(paste0("* ", column_names, ": ", types[x$columnTypes], "\n"), sep = "") 148 | return(invisible(NULL)) 149 | } 150 | 151 | # table has key columns 152 | keys <- data.frame( 153 | k = x$keys, 154 | count = seq_along(x$keys), 155 | stringsAsFactors = FALSE 156 | ) 157 | 158 | col_info <- data.frame( 159 | k = x$columnNames, 160 | o = seq_along(x$columnNames), 161 | t = types[x$columnTypes], 162 | stringsAsFactors = FALSE 163 | ) 164 | 165 | # merge keys to correct column 166 | col_info <- merge(col_info, keys, "k", all.x = TRUE, sort = FALSE) 167 | 168 | col_info$k <- format(encodeString(col_info$k, quote = "'")) 169 | col_info$l <- paste0(" (key ", col_info$count, ")") 170 | col_info[is.na(col_info$count), "l"] <- "" 171 | 172 | col_info <- col_info[order(col_info$count, col_info$o), ] # key columns at the top 173 | 174 | cat(paste0("* ", col_info$k, ": ", col_info$t, col_info$l, "\n"), sep = "") 175 | } 176 | 177 | 178 | #' @rdname write_fst 179 | #' @export 180 | write.fst <- function(x, path, compress = 50, uniform_encoding = TRUE) { # nolint 181 | write_fst(x, path, compress, uniform_encoding) 182 | } 183 | 184 | 185 | #' @rdname write_fst 186 | #' 187 | #' @param columns Column names to read. The default is to read all columns. 188 | #' @param from Read data starting from this row number. 189 | #' @param to Read data up until this row number. The default is to read to the last row of the stored dataset. 190 | #' @param as.data.table If TRUE, the result will be returned as a \code{data.table} object. Any keys set on 191 | #' dataset \code{x} before writing will be retained. This allows for storage of sorted datasets. This option 192 | #' requires \code{data.table} package to be installed. 193 | #' @param old_format must be FALSE, the old fst file format is deprecated and can only be read and 194 | #' converted with fst package versions 0.8.0 to 0.8.10. 195 | #' 196 | #' @export 197 | read_fst <- function(path, columns = NULL, from = 1, to = NULL, as.data.table = FALSE, old_format = FALSE) { # nolint 198 | file_name <- normalizePath(path, mustWork = FALSE) 199 | 200 | if (!is.null(columns)) { 201 | if (!is.character(columns)) { 202 | stop("Parameter 'columns' should be a character vector of column names.") 203 | } 204 | } 205 | 206 | if (!is.numeric(from) || from < 1 || length(from) != 1) { 207 | stop("Parameter 'from' should have a numerical value equal or larger than 1.") 208 | } 209 | 210 | from <- as.integer(from) 211 | 212 | if (!is.null(to)) { 213 | if (!is.numeric(to) || length(to) != 1) { 214 | stop("Parameter 'to' should have a numerical value larger than 1 (or NULL).") 215 | } 216 | 217 | to <- as.integer(to) 218 | } 219 | 220 | if (old_format != FALSE) { 221 | stop( 222 | "Parameter old_format is depricated, fst files written with fst package version", 223 | " lower than 0.8.0 should be read (and rewritten) using fst package versions <= 0.8.10." 224 | ) 225 | } 226 | 227 | res <- fstretrieve(file_name, columns, from, to) 228 | 229 | if (inherits(res, "fst_error")) { 230 | stop(res) 231 | } 232 | 233 | nr_of_rows <- 0 234 | if (length(res$resTable) > 0) { # check for NULL tables's 235 | nr_of_rows <- length(res$resTable[[1]]) 236 | } 237 | 238 | # long vectors are not supported yet with data.table, tibble's or data.frame, 239 | # so return a list instead 240 | if (nr_of_rows >= 2^31) { 241 | return(res$resTable) 242 | } 243 | 244 | if (as.data.table) { 245 | if (!requireNamespace("data.table", quietly = TRUE)) { 246 | stop("Please install package data.table when using as.data.table = TRUE") 247 | } 248 | 249 | key_names <- res$keyNames 250 | res <- data.table::setDT(res$resTable) # nolint 251 | if (length(key_names) > 0) data.table::setattr(res, "sorted", key_names) 252 | return(res) 253 | } 254 | 255 | res_table <- res$resTable 256 | 257 | # use setters from data.table to improve performance 258 | if (requireNamespace("data.table", quietly = TRUE)) { 259 | data.table::setattr(res_table, "class", "data.frame") 260 | data.table::setattr(res_table, "row.names", base::.set_row_names(nr_of_rows)) 261 | } else { 262 | class(res_table) <- "data.frame" 263 | attr(res_table, "row.names") <- base::.set_row_names(nr_of_rows) # nolint 264 | } 265 | 266 | res_table 267 | } 268 | 269 | 270 | #' @rdname write_fst 271 | #' @export 272 | read.fst <- function(path, columns = NULL, from = 1, to = NULL, as.data.table = FALSE, old_format = FALSE) { # nolint 273 | read_fst(path, columns, from, to, as.data.table, old_format) 274 | } 275 | 276 | 277 | #' @rdname metadata_fst 278 | #' @export 279 | fst.metadata <- function(path, old_format = FALSE) { # nolint 280 | metadata_fst(path, old_format) 281 | } 282 | -------------------------------------------------------------------------------- /NEWS.md: -------------------------------------------------------------------------------- 1 | 2 | # fst 0.9.9 (in development) 3 | 4 | ## Enhancements 5 | 6 | ## Bugs solved 7 | 8 | ## Library updates 9 | 10 | 11 | # fst 0.9.8 12 | 13 | With this release of `fst`, the `fstlib` library is no longer build with the `fst` package, but 14 | imported from package `fstcore`. This allows for better separation of updates of the C++ code underlying the `fst` 15 | format and the R wrapper package. Also, with this setup, other packages can directly use the C++ interface exported 16 | from the fstcore package. 17 | 18 | ## Bugs solved 19 | 20 | * The package had linking problems on ARM macOS systems, preventing a correct build. These problems originated from 21 | minor differences between the xxHash implementations in the LZ4 and ZSTD libraries and incorrect linker parameters. 22 | 23 | ## Library updates 24 | 25 | * Library LZ4 updated to version 1.9.3 26 | * library ZSTD updated to version 1.5.2 27 | 28 | 29 | # fst 0.9.6 30 | 31 | Version 0.9.6 is a minor update to 'hotfix' an issue with the use of `sample.int()`. All calls to `sample.int()` now 32 | explicitly reference a length one size object. 33 | 34 | # fst 0.9.4 35 | 36 | Version 0.9.4 is a minor update to 'hotfix' an issue with suggested packages as reported by CRAN. 37 | 38 | ## Bugs solved 39 | 40 | * Packages `nanotime`, `bit64` and `lintr` are now used conditionally as is required for packages suggested in DESCRIPTION, see 'Writing R Extensions' 1.1.3.1 (thanks @CRAN for reporting) 41 | 42 | 43 | # fst 0.9.2 44 | 45 | Version 0.9.2 of the `fst` package brings support for zero-row table serialization and compression for long vectors. In addition, `fst` was prepared for the change in the default settings for the stringsAsFactors argument (data.frame) in R 4.0.0. 46 | 47 | ## Library updates 48 | 49 | * Library `fstlib` updated to version 0.1.6 50 | * Library LZ4 updated to version 1.9.2 51 | * library ZSTD updated to version 1.4.4 52 | 53 | ## Enhancements 54 | 55 | * Incorrect column selection gets a more informative error message (issue #138, thanks Jean-Luc and @Moohan for reporting). 56 | * Long raw vectors can be hashed with hash_fst (issue #202) 57 | * Empty tables are serialized correctly using `write_fst()` (issue #99) 58 | 59 | ## Bugs solved 60 | 61 | * Ellipsis is forwarded in method `str.fst_table()` (issue #219, thanks @nbenn for reporting). 62 | * Coloring is turned off for terminals that don't support it or when package `crayon` is not installed (issue #198, thanks @muschellij2 for reporting and the code fix). 63 | * Method `metadata_fst()` correctly displays the key of the data table if column names are not in alphabetical order (issue #199, thanks @renkun-ken for the pull request). 64 | * stringsAsFactors argument defaults to FALSE for upcoming R 4.0.0 (issue #234, thanks @CRAN for reporting) 65 | 66 | 67 | # fst 0.9.0 68 | 69 | Version 0.9.0 of the `fst` package addresses the request from CRAN maintainers to fix issues identified by rchk. These issues result from PROTECT / UNPROTECT pairs called in the constructor / destructor pairs of C++ classes. rchk (rightfully) warns about those because it can't determine from the code if pairs are properly matched. With this submission the relevant SEXP classes are protected by containing them in SEXP classes that are already PROTECTED, which allows for removal of the PROTECT / UNPROTECT pairs in question. 70 | 71 | As of `fst` version 0.9.0, support for fst files generated with `fst` package versions lower than 0.8.0 has been deprecated. This significantly reduces the (C++) code base and prepares `fst` for future code changes. 72 | 73 | ## Library updates 74 | 75 | * Library `fstlib` updated to version 0.1.1 76 | 77 | ## Enhancements 78 | 79 | * Method `setnrofthreads` returns invisible result to avoid printing unwanted output (thanks @renkun-ken for the pull request) 80 | 81 | ## Bugs solved 82 | 83 | * Empty subsets can be selected using `fst::fst` (thanks @renkun-ken for reporting) 84 | 85 | ## Documentation 86 | 87 | Various documentation issues have been fixed (thanks @ginberg and @renkun-ken for the pull requests). 88 | 89 | 90 | # fst 0.8.10 91 | 92 | Version 0.8.10 of the `fst` package is an intermediate release designed to update the incorporated C++ libraries 93 | to their latest versions and to fix reported issues. Also, per request of CRAN maintainers, the OpenMP build option was moved to the correct flag in the Makevars file, resolving a warning in the package check. 94 | 95 | ## Library updates 96 | 97 | * Library `fstlib` updated to version 0.1.0 98 | 99 | * Library `ZSTD` updated to version 1.3.7 100 | 101 | * Library `LZ4` updated to version 1.8.3 102 | 103 | ## Bugs solved 104 | 105 | * Method `compress_fst()` can handle vectors with sizes larger than 4 GB (issue #176, thanks @bwlewis for reporting) 106 | 107 | * A _fst_ file is correctly read from a subfolder on a network drive where the user does not have access to the top-level folder (issues #136 and #175, thanks @xiaodaigh for reporting). 108 | 109 | * The suggested data.table dependency is now properly escaped (issue #181, thanks @jangorecki for the pull request) 110 | 111 | ## Documentation 112 | 113 | * Documentation updates (issue #158, thanks @HughParsonage for submitting) 114 | 115 | 116 | # fst 0.8.8 117 | 118 | Version 0.8.8 of the `fst` package is an intermediate release designed to fix valgrind warnings reported on CRAN builds (per request of CRAN maintainers). These warnings were due to `fst` writing uninitialized data buffers to file, which was done to maximize speed. To fix these warnings (and for safety), all memory blocks are now initialized to zero before being written to disk. 119 | 120 | 121 | # fst 0.8.6 122 | 123 | Version 0.8.6 of the `fst` package brings clearer printing of `fst_table` objects. It also includes optimizations for controlling the number of threads used by the package during reads and writes and after a fork has ended. The `LZ4` and `ZSTD` compression libraries are updated to their latest (and fastest) releases. UTF-8 encoded column names are now correctly stored in the `fst` format. 124 | 125 | ## New features 126 | 127 | * More advanced printing generic of the `fst_table` reference object, showing column types, (possible) keys, and the table header and footer data (issue #131, thanks @renkun-ken for reporting and discussions). 128 | 129 | * User has more control over the number of threads used by fst. Option 'fst_threads' can now be used to initialize the number of threads when the package is first loaded (issue #132, thanks to @karldw for the pull request). 130 | 131 | * Option 'fst_restore_after_fork' can be used to select the threading behavior after a fork has ended. Like the `data.table` package, `fst` switches back to a single thread when a fork is detected (using OpenMP in a fork can lead to problems). Unlike `data.table`, the `fst` package restores the number of threads to it's previous setting when the fork ends. If this leads to unexpected problems, the user can set the 'fst_restore_after_fork' option to FALSE to disable that. 132 | 133 | ## Bugs solved 134 | 135 | * Character encoding of column names correctly stored in the `fst` format (issue #144, thanks @shrektan for reporting and discussions). 136 | 137 | ## Documentation 138 | 139 | * Improved accuracy of fst_table documentation regarding random row access (issue #143, thanks @martinblostein for pointed out the unclarity) 140 | 141 | * Improved documentation on background threads during `write_fst()` and `read_fst()` (issue #121, thanks @krlmlr for suggestions and discussion) 142 | 143 | 144 | # fst 0.8.4 145 | 146 | The v0.8.4 release brings a `data.frame` interface to the `fst` package. Column and row selection can now be done directly from the `[` operator. In addition, it fixes some issues and prepares the package for the next build toolchain of CRAN. 147 | 148 | ## New features 149 | 150 | * A `data.frame` interface was added to the package. The user can create a reference object to a `fst` file with method `fst`. That reference can be used like a `data.frame` and will automatically make column- and row- selections in the referenced `fst` file. 151 | 152 | ## Bugs solved 153 | 154 | * Build issues with the dev build of R have been fixed. In particular, `fst` now builds correctly with the Clang 6.0 toolchain which will be released by CRAN shortly (thanks @kevinushey for reporting the problem and CRAN maintainers for the advance warning. 155 | 156 | * An error was fixed where compressing a short factor column with 128 to 32767 levels but only a single value, returned incorrect results (issue #128, thanks @martinblostein for reporting and help fixing the problem). 157 | 158 | * An error was fixed where columns f type 'ITime' were incorrectly serialized (issue #126, thanks @Giqles for reporting the problem). 159 | 160 | * An error was fixed where using `fst` as a dependency in another package and building that package in RStudio, crashed RStudio. The problem was that RStudio uses a fork to build or document a package. That fork made `fst` use OpenMP library methods, which leads to crashes on macOS. After the fix, no calls to any OpenMP library method are now made from `fst` when it's run from a forked process (issue #100 and issue #109, thanks to @eipi10, @PeteHaitch, @kevinushey, @thierrygosselin, @xiaodaigh and @jzzcutler for reporting the problem and help fix it). 161 | 162 | ## Documentation 163 | 164 | * Documentation for method `write_fst` was improved (issue #123, thanks @krlmlr for reporting and submitting a pull request). 165 | 166 | 167 | # fst 0.8.2 168 | 169 | ## New features 170 | 171 | * Package `fst` has support for multi-threading using OpenMP. Compression, decompression and disk IO have been largely parallelized for (much) improved performance. 172 | 173 | * Many new column types are now supported by the `fst` format (where appropriate, both the `double` and `integer` variants are supported): 174 | 175 | * `raw` 176 | * `DateTime` 177 | * `integer64` 178 | * `nanotime` 179 | * `POSIXct` 180 | * `ordered factors` 181 | * `difftime` 182 | 183 | _Thanks @arunsrinivasan, @derekholmes, @phillc73, @HughParsonage, @statquant, @eddelbuettel, @eipi10, and @verajosemanuel for feature requests and helpful discussions._ 184 | 185 | * Multi-threaded `LZ4` and `ZSTD` compression using methods `compress_fst` and `decompress_fst`. These methods provide a direct API to the `LZ4` and `ZSTD` compressors at speeds of multiple GB/s. A specific block format is used to facilitate parallel processing. For additional stability, hashes can be calculated if required. 186 | 187 | * Method `hash_fst` provides an extremely fast multi-threaded 64-bit hashing algorithm based on `xxHash`. Speeds up to the memory bandwidth can be achieved. 188 | 189 | * Faster conversion to `data.table` in `read_fst`. _Thanks @dselivanov_ 190 | 191 | * Package `data.table` is now an optional dependency. _Thanks @jimhester_. Note that in the near future, a dependency on `data.table` will probably be introduced again, as `fst` will get a `data.table`-like interface. 192 | 193 | * The `fst` format has a _magic number_ to be able to identify a `fst` file without actually opening the file or requiring the `fstlib` library. _Thanks @davidanthoff._ 194 | 195 | * For development versions, the build number is now shown when fst is loaded. _Thanks @skanskan._ 196 | 197 | * Character encodings are preserved for character and factor columns. _Thanks @carioca67 and @adrianadermon_ 198 | 199 | * Naming of fst methods is now consistent. _Thanks @jimhester and @brinkhuis._ 200 | 201 | * The core C++ code with the API to read and write `fst` files, and use compression and hashing now lives in a separate library called [`fstlib`](https://github.com/fstpackage/fstlib). Although not visible to the user, this is a major development allowing `fst` to be implemented for other languages than `R` (with comparable performance). 202 | 203 | ## Bugs solved 204 | 205 | * Tilde-expansion in `write_fst` not correctly processed. _Thanks @HughParsonage, @PoGibas._ 206 | 207 | * Writing more than INT_MAX rows crashes `fst`. _Thanks @wei-wu-nyc_ 208 | 209 | * Incorrect fst file is created when an empty data.table is saved. _Thanks @wei-wu-nyc._ 210 | 211 | * Error/crash when saving factor column with 0 factor levels. _Thanks @martinblostein._ 212 | 213 | * No warning was given when disk runs out of space during a `fstwrite` operation. 214 | 215 | * A data.table warning message was given on modification of columns of a sorted table. _Thanks @martinblostein._ 216 | 217 | * Stack imbalance warnings under certain conditions. _Thanks @ryankennedyio_ 218 | 219 | ## Benchmarks 220 | 221 | Thanks to @mattdowle, @st-pasha, @phillc73 for valuable discussions on `fst` benchmarks and how to accurately perform (and present) them. 222 | 223 | ## Additional credits 224 | 225 | * Special thanks to @arunsrinivasan for a lot of valuable discussions on the future direction of the `fst` package, I hope `fst` may continue to benefit from your experience! 226 | 227 | * Thanks for reporting and discussing various bugs, inconsistencies, instabilities or installation problems to @treysp, @wei-wu-nyc, @khsu15, @PMassicotte, @xiaodaigh, @renkun-ken, @statquant, @tgolden23, @carioca67, @jzzcutler, @MehranMoghtadai. 228 | 229 | * And thanks to @mperone, @kendonB, @xiaodaigh, @derekholmes, @pmakai, @1beb, @BenoitLondon, @skanskan, @petermuller71, @nextpagesoft, @cawthm, @jeroenjanssens, @dselivanov, @Fpadt and @kbroman for helpful (online) discussions and (feature) requests. All the community feedback is much appreciated and tremendously helps to to improve the stability and usability of `fst`! (if I missed anyone, I apologize in advance, please let me know and I will fix this document ASAP) 230 | -------------------------------------------------------------------------------- /R/fst_table.R: -------------------------------------------------------------------------------- 1 | # fst - R package for ultra fast storage and retrieval of datasets 2 | # 3 | # Copyright (C) 2017-present, Mark AJ Klik 4 | # 5 | # This file is part of the fst R package. 6 | # 7 | # The fst R package is free software: you can redistribute it and/or modify it 8 | # under the terms of the GNU Affero General Public License version 3 as 9 | # published by the Free Software Foundation. 10 | # 11 | # The fst R package is distributed in the hope that it will be useful, but 12 | # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 | # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 14 | # for more details. 15 | # 16 | # You should have received a copy of the GNU Affero General Public License along 17 | # with the fst R package. If not, see . 18 | # 19 | # You can contact the author at: 20 | # - fst R package source repository : https://github.com/fstpackage/fst 21 | 22 | 23 | #' Access a fst file like a regular data frame 24 | #' 25 | #' Create a fst_table object that can be accessed like a regular data frame. This object 26 | #' is just a reference to the actual data and requires only a small amount of memory. 27 | #' When data is accessed, only a subset is read from file, depending on the minimum and 28 | #' maximum requested row number. This is possible because the fst file format allows full 29 | #' random access (in columns and rows) to the stored dataset. 30 | #' 31 | #' @inheritParams metadata_fst 32 | #' @return An object of class \code{fst_table} 33 | #' @export 34 | #' @examples 35 | #' \dontrun{ 36 | #' # generate a sample fst file 37 | #' path <- paste0(tempfile(), ".fst") 38 | #' write_fst(iris, path) 39 | #' 40 | #' # create a fst_table object that can be used as a data frame 41 | #' ft <- fst(path) 42 | #' 43 | #' # print head and tail 44 | #' print(ft) 45 | #' 46 | #' # select columns and rows 47 | #' x <- ft[10:14, c("Petal.Width", "Species")] 48 | #' 49 | #' # use the common list interface 50 | #' ft[TRUE] 51 | #' ft[c(TRUE, FALSE)] 52 | #' ft[["Sepal.Length"]] 53 | #' ft$Petal.Length 54 | #' 55 | #' # use data frame generics 56 | #' nrow(ft) 57 | #' ncol(ft) 58 | #' dim(ft) 59 | #' dimnames(ft) 60 | #' colnames(ft) 61 | #' rownames(ft) 62 | #' names(ft) 63 | #' } 64 | fst <- function(path, old_format = FALSE) { 65 | # old format is deprecated as of v0.9.0 66 | if (old_format != FALSE) { 67 | stop( 68 | "Parameter old_format is depricated, fst files written with fst package version", 69 | " lower than 0.8.0 should be read (and rewritten) using fst package versions <= 0.8.10." 70 | ) 71 | } 72 | 73 | # wrap in a list so that additional elements can be added if required 74 | ft <- list( 75 | meta = metadata_fst(path, old_format), 76 | col_selection = NULL, 77 | row_selection = NULL, 78 | old_format = old_format 79 | ) 80 | 81 | # class attribute 82 | class(ft) <- "fst_table" 83 | 84 | ft 85 | } 86 | 87 | 88 | #' @export 89 | row.names.fst_table <- function(x) { 90 | as.character(seq_len(length(.subset2(x, "meta")$columnBaseTypes))) 91 | } 92 | 93 | 94 | #' @export 95 | dim.fst_table <- function(x) { 96 | c(.subset2(x, "meta")$nrOfRows, length(.subset2(x, "meta")$columnBaseTypes)) 97 | } 98 | 99 | 100 | #' @export 101 | dimnames.fst_table <- function(x) { 102 | list( 103 | as.character(seq_len(.subset2(x, "meta")$nrOfRows)), 104 | .subset2(x, "meta")$columnNames 105 | ) 106 | } 107 | 108 | 109 | #' @export 110 | names.fst_table <- function(x) { 111 | .subset2(x, "meta")$columnNames 112 | } 113 | 114 | 115 | #' @export 116 | `[[.fst_table` <- function(x, j, exact = TRUE) { 117 | if (!exact) { 118 | warning("exact ignored", call. = FALSE) 119 | } 120 | 121 | meta_info <- .subset2(x, "meta") 122 | 123 | if (length(j) != 1) { 124 | # select at least one column number 125 | if (length(j) == 0) { 126 | stop("Please use a length one integer or character vector to specify the column", call. = FALSE) 127 | } 128 | 129 | # recursive indexing (up to level 1) 130 | 131 | if (length(j) != 2) { 132 | stop("Recursive indexing is currently only supported up to level 1.", call. = FALSE) 133 | } 134 | 135 | if (is.character(j)) { 136 | stop("Subscript out of bounds.", call. = FALSE) 137 | } 138 | 139 | # check row number 140 | 141 | if (j[2] < 1 || j[2] > meta_info$nrOfRows) { 142 | stop("Second index out of bounds.", call. = FALSE) 143 | } 144 | 145 | col_name <- meta_info$columnNames[as.integer(j[1])] 146 | 147 | return( 148 | read_fst( 149 | meta_info$path, 150 | col_name, 151 | from = j[2], 152 | to = j[2], 153 | old_format = .subset2(x, "old_format") 154 | )[[1]] 155 | ) 156 | } 157 | 158 | if (!(is.numeric(j) || is.character(j))) { 159 | stop("Please use a length 1 integer of character vector to specify the column", call. = FALSE) 160 | } 161 | 162 | # length one integer column selection 163 | if (is.numeric(j)) { 164 | if (j < 1 || j > length(meta_info$columnNames)) { 165 | stop("Invalid column index ", j, call. = FALSE) 166 | } 167 | 168 | j <- meta_info$columnNames[as.integer(j)] 169 | } else { 170 | if (!(j %in% meta_info$columnNames)) { 171 | return(NULL) 172 | } 173 | } 174 | 175 | # determine row selection here from metadata 176 | 177 | read_fst(meta_info$path, j, old_format = .subset2(x, "old_format"))[[1]] 178 | } 179 | 180 | 181 | # override needed to avoid the [[ operator messing up the str output 182 | 183 | #' @export 184 | str.fst_table <- function(object, ...) { 185 | str(unclass(object), ...) 186 | } 187 | 188 | 189 | #' @export 190 | `$.fst_table` <- function(x, j) { 191 | x[[j]] 192 | } 193 | 194 | 195 | #' @export 196 | print.fst_table <- function(x, number_of_rows = 50, ...) { 197 | meta_info <- .subset2(x, "meta") 198 | 199 | cat("\n") 200 | cat(meta_info$nrOfRows, " rows, ", length(meta_info$columnNames), 201 | " columns (", basename(meta_info$path), ")\n\n", 202 | sep = "" 203 | ) 204 | 205 | if (!is.numeric(number_of_rows)) number_of_rows <- 100L 206 | if (!is.infinite(number_of_rows)) number_of_rows <- as.integer(number_of_rows) 207 | if (number_of_rows <= 0L) { 208 | return(invisible()) 209 | } # ability to turn off printing 210 | 211 | table_splitted <- (meta_info$nrOfRows > number_of_rows) && (meta_info$nrOfRows > 10) 212 | 213 | if (table_splitted) { 214 | sample_data_head <- read_fst(meta_info$path, from = 1, to = 5, old_format = .subset2(x, "old_format")) 215 | sample_data_tail <- read_fst(meta_info$path, 216 | from = meta_info$nrOfRows - 4, to = meta_info$nrOfRows, 217 | old_format = .subset2(x, "old_format") 218 | ) 219 | 220 | sample_data <- rbind.data.frame(sample_data_head, sample_data_tail) 221 | } else { 222 | sample_data <- read_fst(meta_info$path, old_format = .subset2(x, "old_format")) 223 | } 224 | 225 | # use bit64 package if available for correct printing 226 | if ((!"bit64" %in% loadedNamespaces()) && any(sapply(sample_data, inherits, "integer64"))) require_bit64() # nolint 227 | if ((!"nanotime" %in% loadedNamespaces()) && any(sapply(sample_data, inherits, "nanotime"))) require_nanotime() # nolint 228 | if ((!"data.table" %in% loadedNamespaces()) && any(sapply(sample_data, inherits, "ITime"))) require_data_table() # nolint 229 | 230 | types <- c( 231 | "unknown", "character", "factor", "ordered factor", "integer", "POSIXct", "difftime", 232 | "IDate", "ITime", "double", "Date", "POSIXct", "difftime", "ITime", "logical", "integer64", 233 | "nanotime", "raw" 234 | ) 235 | 236 | # turn off colored output at default 237 | color_on <- FALSE 238 | 239 | if (requireNamespace("crayon", quietly = TRUE)) { 240 | color_on <- crayon::has_color() # terminal has color 241 | } 242 | 243 | type_row <- matrix(paste("<", types[meta_info$columnTypes], ">", sep = ""), nrow = 1) 244 | colnames(type_row) <- meta_info$columnNames 245 | 246 | # convert to aligned character columns 247 | sample_data_print <- format(sample_data) 248 | 249 | if (table_splitted) { 250 | dot_row <- matrix(rep("--", length(meta_info$columnNames)), nrow = 1) 251 | colnames(dot_row) <- meta_info$columnNames 252 | 253 | sample_data_print <- rbind( 254 | type_row, 255 | sample_data_print[1:5, , drop = FALSE], 256 | dot_row, 257 | sample_data_print[6:10, , drop = FALSE] 258 | ) 259 | 260 | rownames(sample_data_print) <- c(" ", 1:5, "--", (meta_info$nrOfRows - 4):meta_info$nrOfRows) 261 | 262 | y <- capture.output(print(sample_data_print)) 263 | 264 | # the length of y must be a multiple of 13 and color must be permitted 265 | # if not, take defensive action; skip coloring and solve later 266 | if (!color_on || (length(y) %% 13 != 0)) { 267 | print(sample_data_print) 268 | return(invisible(x)) 269 | } 270 | 271 | type_rows <- seq(2, length(y), 13) 272 | gray_rows <- seq(8, length(y), 13) 273 | 274 | y[gray_rows] <- paste0("\033[38;5;248m", y[gray_rows], "\033[39m") 275 | 276 | gray_rows <- c(type_rows, gray_rows) 277 | } else { 278 | # table is not splitted along the row axis 279 | sample_data_print <- rbind( 280 | type_row, 281 | sample_data_print 282 | ) 283 | 284 | rownames(sample_data_print) <- c(" ", seq_len(meta_info$nrOfRows)) 285 | 286 | # no color terminal available 287 | if (!color_on) { 288 | print(sample_data_print) 289 | return(invisible(x)) 290 | } 291 | 292 | y <- capture.output(print(sample_data_print)) 293 | 294 | gray_rows <- type_rows <- seq(2, length(y), 2 + meta_info$nrOfRows) 295 | } 296 | 297 | # type rows are set to italic light grey 298 | y[type_rows] <- paste0("\033[3m\033[38;5;248m", y[type_rows], "\033[39m\033[23m") 299 | 300 | # use light grey color up to width of row name column 301 | row_text_size <- regexpr("^[0-9-]*", tail(y, 1)) 302 | row_text_size <- attr(row_text_size, "match.length") 303 | 304 | y[-gray_rows] <- paste0( 305 | "\033[38;5;248m", substr(y[-gray_rows], 1, row_text_size), 306 | "\033[39m", substr(y[-gray_rows], row_text_size + 1, nchar(y[-gray_rows])) 307 | ) 308 | 309 | cat(y, sep = "\n") 310 | return(invisible(x)) 311 | } 312 | 313 | 314 | #' @export 315 | as.data.frame.fst_table <- function(x, row.names = NULL, optional = FALSE, ...) { # nolint 316 | meta_info <- .subset2(x, "meta") 317 | as.data.frame(read_fst(meta_info$path, old_format = .subset2(x, "old_format")), row.names, optional, ...) 318 | } 319 | 320 | #' @export 321 | as.list.fst_table <- function(x, ...) { 322 | as.list(as.data.frame(x)) 323 | } 324 | 325 | 326 | .column_indexes_fst <- function(meta_info, j) { 327 | # test correct column names 328 | if (is.character(j)) { 329 | wrong <- !(j %in% meta_info$columnNames) 330 | 331 | if (any(wrong)) { 332 | names <- j[wrong] 333 | stop(sprintf("Undefined columns: %s", paste(names, collapse = ", "))) 334 | } 335 | } else if (is.logical(j)) { 336 | if (any(is.na(j))) { 337 | stop("Subscript out of bounds.", call. = FALSE) 338 | } 339 | 340 | j <- meta_info$columnNames[j] 341 | } else if (is.numeric(j)) { 342 | if (any(is.na(j))) { 343 | stop("Subscript out of bounds.", call. = FALSE) 344 | } 345 | 346 | if (any(j <= 0)) { 347 | stop("Only positive column indexes supported.", call. = FALSE) 348 | } 349 | 350 | if (any(j > length(meta_info$columnBaseTypes))) { 351 | stop("Subscript out of bounds.", call. = FALSE) 352 | } 353 | 354 | j <- meta_info$columnNames[j] 355 | } 356 | 357 | j 358 | } 359 | 360 | 361 | # drop to lower dimension when drop = TRUE 362 | return_drop <- function(x, drop) { 363 | if (!drop || ncol(x) > 1) { 364 | return(x) 365 | } 366 | 367 | x[[1]] 368 | } 369 | 370 | 371 | #' @export 372 | `[.fst_table` <- function(x, i, j, drop) { 373 | # check for old_format in case an 'old' fst_table object was deserialized 374 | if (.subset2(x, "old_format") != FALSE) { 375 | stop( 376 | "fst files written with fst package version", 377 | " lower than 0.8.0 should be read (and rewritten) using fst package versions <= 0.8.10." 378 | ) 379 | } 380 | 381 | meta_info <- .subset2(x, "meta") 382 | 383 | # no additional arguments provided 384 | 385 | if (missing(i) && missing(j)) { 386 | # never drop as with data.frame 387 | return(read_fst(meta_info$path)) 388 | } 389 | 390 | 391 | if (nargs() <= 2) { 392 | # result is never dropped with 2 arguments 393 | 394 | if (missing(i)) { 395 | # we have a named argument j 396 | j <- .column_indexes_fst(meta_info, j) 397 | return(read_fst(meta_info$path, j)) 398 | } 399 | 400 | # i is interpreted as j 401 | j <- .column_indexes_fst(meta_info, i) 402 | return(read_fst(meta_info$path, j)) 403 | } 404 | 405 | # drop dimension if single column selected and drop != FALSE 406 | drop_dim <- FALSE 407 | 408 | if (!missing(j) && length(j) == 1) { 409 | if (!(!missing(drop) && drop == FALSE)) { 410 | drop_dim <- TRUE 411 | } 412 | } 413 | 414 | # special case where i is interpreted as j: select all rows, never drop 415 | 416 | if (nargs() == 3 && !missing(drop) && !missing(i)) { 417 | j <- .column_indexes_fst(meta_info, i) 418 | return(read_fst(meta_info$path, j)) 419 | } 420 | 421 | # i and j not reversed 422 | 423 | # full columns 424 | if (missing(i)) { 425 | j <- .column_indexes_fst(meta_info, j) 426 | x <- read_fst(meta_info$path, j) 427 | 428 | if (!drop_dim) { 429 | return(x) 430 | } 431 | return(x[[1]]) 432 | } 433 | 434 | 435 | # determine integer vector from i 436 | if (!(is.numeric(i) || is.logical(i))) { 437 | stop("Row selection should be done using a numeric or logical vector", call. = FALSE) 438 | } 439 | 440 | if (is.logical(i)) { 441 | i <- which(i) 442 | } 443 | 444 | # cast to integer and determine row range 445 | i <- as.integer(i) 446 | 447 | # empty row selection 448 | if (length(i) == 0) { 449 | min_row <- 1 450 | max_row <- 1 451 | } else { 452 | min_row <- min(i) 453 | max_row <- max(i) 454 | 455 | # boundary check 456 | if (min_row < 0) { 457 | stop("Row selection out of range") 458 | } 459 | 460 | if (max_row > meta_info$nrOfRows) { 461 | stop("Row selection out of range") 462 | } 463 | } 464 | 465 | # column subset 466 | 467 | # select all columns 468 | if (missing(j)) { 469 | fst_data <- read_fst(meta_info$path, from = min_row, to = max_row) 470 | x <- fst_data[1 + i - min_row, ] # row selection, no dropping 471 | } else { 472 | j <- .column_indexes_fst(meta_info, j) 473 | fst_data <- read_fst(meta_info$path, j, from = min_row, to = max_row) 474 | x <- fst_data[1 + i - min_row, , drop = FALSE] # row selection, no dropping 475 | } 476 | 477 | if (!drop_dim) { 478 | return(x) 479 | } 480 | return(x[[1]]) 481 | } 482 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------