Compare commits

..

No commits in common. "master" and "2.41.0" have entirely different histories.

1035 changed files with 18965 additions and 31719 deletions

150
.cirrus.yml Normal file
View file

@ -0,0 +1,150 @@
linux_task:
name: "alpine:latest"
container:
image: alpine:latest
cpu: 4
memory: 4G
timeout_in: 15m
script:
- buildtools/install-build-pkgs
- make STATIC=1 LTO=1
linux_task:
name: "alpine-arm:latest"
arm_container:
image: alpine:latest
cpu: 4
memory: 4G
timeout_in: 15m
script:
- buildtools/install-build-pkgs
- make STATIC=1 LTO=1
linux_task:
name: "fedora:41"
container:
image: fedora:41
cpu: 4
memory: 4G
timeout_in: 15m
script:
- buildtools/install-build-pkgs
- make
- make rpm
linux_task:
name: "fedora-arm:41"
arm_container:
image: fedora:41
cpu: 4
memory: 4G
timeout_in: 15m
script:
- buildtools/install-build-pkgs
- make
- make rpm
linux_task:
name: "ubuntu:22.04"
container:
image: ubuntu:22.04
cpu: 4
memory: 4G
timeout_in: 15m
script:
- buildtools/install-build-pkgs
- git fetch
- make deb
- apt-get -y install fuse
- dpkg -i ../*.deb
- mergerfs -v || true
linux_task:
name: "ubuntu:24.04"
container:
image: ubuntu:24.04
cpu: 4
memory: 4G
timeout_in: 15m
script:
- buildtools/install-build-pkgs
- git fetch
- make deb
- apt-get -y install fuse
- dpkg -i ../*.deb
- mergerfs -v || true
linux_task:
name: "ubuntu:latest"
container:
image: ubuntu:latest
cpu: 4
memory: 4G
timeout_in: 15m
script:
- buildtools/install-build-pkgs
- git fetch
- make deb
- apt-get -y install fuse
- dpkg -i ../*.deb
- mergerfs -v || true
linux_task:
name: "ubuntu-arm:latest"
arm_container:
image: ubuntu:latest
cpu: 4
memory: 4G
timeout_in: 15m
script:
- buildtools/install-build-pkgs
- git fetch
- make deb
- apt-get -y install fuse
- dpkg -i ../*.deb
- mergerfs -v || true
linux_task:
name: "debian:12"
container:
image: debian:12
cpu: 4
memory: 4G
timeout_in: 15m
script:
- buildtools/install-build-pkgs
- git fetch
- make deb
- apt-get -y install fuse
- dpkg -i ../*.deb
- mergerfs -v || true
linux_task:
name: "debian:latest"
container:
image: debian:latest
cpu: 4
memory: 4G
timeout_in: 15m
script:
- buildtools/install-build-pkgs
- git fetch
- make deb
- apt-get -y install fuse
- dpkg -i ../*.deb
- mergerfs -v || true
linux_task:
name: "debian-arm:latest"
arm_container:
image: debian:latest
cpu: 4
memory: 4G
timeout_in: 15m
script:
- buildtools/install-build-pkgs
- git fetch
- make deb
- apt-get -y install fuse
- dpkg -i ../*.deb
- mergerfs -v || true

View file

@ -7,31 +7,22 @@ assignees: ''
--- ---
See also https://trapexit.github.io/mergerfs/latest/support
**Describe the bug** **Describe the bug**
A clear and concise description of the unexpected behavior. A clear and concise description of the unexpected behavior.
**Please be sure to use latest release of mergerfs to ensure the issue **Please be sure to use latest release of mergerfs to ensure the issue still exists. Not your distro's latest but the latest official release.**
still exists. Not your distro's latest but the latest official
release. Support will NOT be provided for old versions.**
The `master` branch is **not** to be considered production ready. Feel The master branch is **not** to be considered production ready. Feel free to file bug reports but do so indicating clearly that you are testing unreleased code.
free to file bug reports but do so indicating clearly that you are
testing unreleased code.
**To Reproduce** **To Reproduce**
Provide steps to reproduce the behavior. List **all** steps to Steps to reproduce the behavior. List **all** steps to reproduce. **All** settings.
reproduce. **All** settings. The version of all software involved.
Please simplify the reproduction as much as possible. Please simplify the reproduction as much as possible.
* Unless it is dependenat on multiple branches, use a single branch - Unless it is dependenat on multiple branches, use a single branch
* Reproduce with standard tooling if possible - Reproduce with standard tooling if possible (touch,truncate,rm,rmdir,ln,etc.) Having to install 3rd party software will make debugging more difficult.
(touch,truncate,rm,rmdir,ln,etc.) Having to install 3rd party
software will make debugging more difficult.
**Expected behavior** **Expected behavior**
@ -39,38 +30,19 @@ Please simplify the reproduction as much as possible.
A clear and concise description of the expected behavior. A clear and concise description of the expected behavior.
**Workarounds already tested**
Please list all workarounds attempted and why they were ruled out as
options.
**System information:** **System information:**
* Attach output from - OS, kernel version: `uname -a`
[mergerfs.collect-info](https://trapexit.github.io/mergerfs/latest/tooling/#mergerfscollect-info) - mergerfs version: `mergerfs -V`
tool. - mergerfs settings
* Alternatively: - List of drives, filesystems, & sizes:
* OS: `lsb_release -a` - `df -h`
* kernel version: `uname -a` - `lsblk -f`
* mergerfs version: `mergerfs --version` - A strace of the application having a problem:
* mergerfs settings / arguments: from fstab, systemd unit, command - `strace -fvTtt -s 256 -o /tmp/app.strace.txt <cmd>`
line, OMV plugin, etc. - `strace -fvTtt -s 256 -o /tmp/app.strace.txt -p <appPID>`
* List of drives, filesystems, & sizes: - strace of mergerfs while app tried to do it's thing:
* `df -h` - `strace -fvTtt -s 256 -p <mergerfsPID> -o /tmp/mergerfs.strace.txt`
* `lsblk -o NAME,FSTYPE,FSSIZE,SIZE,MOUNTPOINTS,RM,RO,ROTA`
* All information about the relevant paths and files: permissions,
ownership, etc.
* All information about the application making the requests:
version, uid/gid
* Is mergerfs running within a container or used with container
technologies?
* Are the client apps using mergerfs running in a container?
* A strace of the application having a problem:
* `strace -fvTtt -s 256 -o /tmp/app.strace.txt <cmd>`
* `strace -fvTtt -s 256 -o /tmp/app.strace.txt -p <appPID>`
* strace of mergerfs while app tried to do it's thing:
* `strace -fvTtt -s 256 -p <mergerfsPID> -o /tmp/mergerfs.strace.txt`
**Additional context** **Additional context**

42
.github/workflows/codeql.yml vendored Normal file
View file

@ -0,0 +1,42 @@
name: "CodeQL"
on:
push:
branches: [ "master" ]
pull_request:
branches: [ "master" ]
schedule:
- cron: "7 3 * * 6"
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ python, cpp ]
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
queries: +security-and-quality
- name: Autobuild
uses: github/codeql-action/autobuild@v2
if: ${{ matrix.language == 'python' || matrix.language == 'cpp' }}
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2
with:
category: "/language:${{ matrix.language }}"

49
.github/workflows/mkdocs.yml vendored Normal file
View file

@ -0,0 +1,49 @@
name: "mkdocs"
on:
push:
branches:
- master
tags:
- '*'
permissions:
contents: write
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout repo
uses: actions/checkout@v4
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: '3.x'
- name: Configure Git Credentials
run: |
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
- name: Install dependencies
working-directory: ./mkdocs
run: |
pip install --no-cache-dir mkdocs mkdocs-material pymdown-extensions mike
- name: Deploy docs
working-directory: ./mkdocs
env:
REF_TYPE: ${{ github.ref_type }}
REF_NAME: ${{ github.ref_name }}
run: |
if [ "$REF_TYPE" = "tag" ]; then
mike deploy "$REF_NAME" "latest" --allow-empty --ignore-remote-status --update-aliases
mike set-default "latest"
#git checkout gh-pages
#git push -f origin gh-pages
elif [ "$REF_TYPE" = "branch" ] && [ "$REF_NAME" = "master" ]; then
mike deploy "master" --ignore-remote-status --allow-empty
#git checkout gh-pages
#git push -f origin gh-pages
fi

View file

@ -9,12 +9,8 @@
* scope_guard: https://github.com/Neargye/scope_guard * scope_guard: https://github.com/Neargye/scope_guard
* subprocess: https://github.com/arun11299/cpp-subprocess * subprocess: https://github.com/arun11299/cpp-subprocess
* CLI11: https://github.com/CLIUtils/CLI11 * CLI11: https://github.com/CLIUtils/CLI11
* string-lite: https://github.com/martinmoene/string-lite
* boost * boost
* download boost * download boost
* ./bootstrap.sh * ./bootstrap.sh
* ./b2 tools/bcp * ./b2 tools/bcp
* ./dist/bin/bcp unordered/concurrent_flat_map.hpp <target_dir> * ./dist/bin/bcp unordered/concurrent_flat_map.hpp <target_dir>
* local patch: keep unordered dummy-group storage writable with C++20
`constinit`; ARMv5 atomic loads can write back to memory (#1695).
Preserve this change when updating Boost.

View file

@ -1,7 +1,7 @@
/* /*
ISC License ISC License
Copyright (c) 2026, Antonio SJ Musumeci <trapexit@spawn.link> Copyright (c) 2025, Antonio SJ Musumeci <trapexit@spawn.link>
Permission to use, copy, modify, and/or distribute this software for any Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above purpose with or without fee is hereby granted, provided that the above

View file

@ -29,8 +29,6 @@ MKDIR ?= mkdir
MKTEMP ?= mktemp MKTEMP ?= mktemp
MV ?= mv MV ?= mv
RM ?= rm RM ?= rm
RPMBUILD ?= rpmbuild
RPMBUILD_FLAGS ?=
SED ?= sed SED ?= sed
STRIP ?= strip STRIP ?= strip
TAR ?= tar TAR ?= tar
@ -38,8 +36,7 @@ TOUCH ?= touch
BUILDDIR := build BUILDDIR := build
GITHUB_REPO ?= "https://github.com/trapexit/mergerfs" GITHUB_REPO ?= "https://github.com/trapexit/mergerfs"
RELEASE_SAMPLE ?= "debian:13.amd64"
DEFAULT_TARGET := debian:13.amd64
ifndef GIT_REPO ifndef GIT_REPO
ifneq ($(shell $(GIT) --version 2> /dev/null),) ifneq ($(shell $(GIT) --version 2> /dev/null),)
@ -50,30 +47,27 @@ endif
endif endif
USE_XATTR ?= 1 USE_XATTR ?= 1
UGID_USE_RWLOCK ?= 0
ifdef NDEBUG
OPT_FLAGS := -O2 -DNDEBUG
else
ifdef SANITIZE ifdef SANITIZE
ifeq ($(SANITIZE),1) ifeq ($(SANITIZE),1)
override SANITIZE := -fsanitize=address,undefined,leak override SANITIZE := -fsanitize=address,undefined,leak
else ifeq ($(filter -fsanitize=%,$(SANITIZE)),) else
override SANITIZE := -fsanitize=$(SANITIZE) override SANITIZE := -fsanitize=$(SANITIZE)
endif endif
endif endif
OPT_FLAGS := -O0 \
COMMON_OPT_FLAGS += \ -g \
-fno-omit-frame-pointer \
$(SANITIZE) \
-fstack-protector-strong \ -fstack-protector-strong \
-Wextra \ -Wextra \
-Wno-unused-parameter -Werror \
-Wno-unused-parameter \
DEBUG_OPT_FLAGS += \ -DDEBUG
-O0 \
-g3 \
-fno-omit-frame-pointer \
$(SANITIZE)
ifdef RELEASE
OPT_FLAGS := -O3 $(COMMON_OPT_FLAGS)
else
OPT_FLAGS ?= $(DEBUG_OPT_FLAGS) $(COMMON_OPT_FLAGS)
endif endif
ifdef STATIC ifdef STATIC
@ -101,8 +95,7 @@ TESTS_DEPS += $(DEPS)
MANPAGE := mergerfs.1 MANPAGE := mergerfs.1
CPPFLAGS ?= CPPFLAGS ?=
override CPPFLAGS += \ override CPPFLAGS += \
-D_FILE_OFFSET_BITS=64 \ -D_FILE_OFFSET_BITS=64
-DBOOST_UNORDERED_DISABLE_PARALLEL_ALGORITHMS
CFLAGS ?= \ CFLAGS ?= \
$(OPT_FLAGS) \ $(OPT_FLAGS) \
-Wall \ -Wall \
@ -123,22 +116,20 @@ CXXFLAGS ?= \
-Wno-unused-result \ -Wno-unused-result \
-pipe -pipe
override CXXFLAGS += \ override CXXFLAGS += \
-std=c++20 \ -std=c++17 \
-MMD \ -MMD \
-MP -MP
override INC_FLAGS := \ override INC_FLAGS := \
-Isrc \ -Isrc \
-Ivendored \ -Ilibfuse/include
-Ivendored/libfuse/include
override MFS_FLAGS := \ override MFS_FLAGS := \
-DUSE_XATTR=$(USE_XATTR) -DUSE_XATTR=$(USE_XATTR) \
-DUGID_USE_RWLOCK=$(UGID_USE_RWLOCK)
override TESTS_FLAGS := \ override TESTS_FLAGS := \
-Isrc \ -Isrc \
-Ivendored \
-Ivendored/acutest \
-DTESTS -DTESTS
LIBFUSE := vendored/libfuse/$(BUILDDIR)/libfuse.a LIBFUSE := libfuse/$(BUILDDIR)/libfuse.a
LDFLAGS ?= LDFLAGS ?=
LDLIBS := \ LDLIBS := \
-lrt \ -lrt \
@ -179,8 +170,6 @@ help:
@echo "USE_XATTR=0 - build program without xattrs functionality" @echo "USE_XATTR=0 - build program without xattrs functionality"
@echo "STATIC=1 - build static binary" @echo "STATIC=1 - build static binary"
@echo "LTO=1 - build with link time optimization" @echo "LTO=1 - build with link time optimization"
@echo "SANITIZE=1 - build with sanitizers (address,undefined,leak)"
@echo "SANITIZE=list - build with custom sanitizers (comma separated)"
@echo "CLEANUP=1 - cleanup images between release build process" @echo "CLEANUP=1 - cleanup images between release build process"
@echo "PKGDIR=/dir/ - location for release build pkgs" @echo "PKGDIR=/dir/ - location for release build pkgs"
@echo "GITREF=gitref - gitref to use for release builds" @echo "GITREF=gitref - gitref to use for release builds"
@ -189,21 +178,19 @@ help:
$(BUILDDIR)/mergerfs: $(LIBFUSE) src/version.hpp $(OBJS) $(BUILDDIR)/mergerfs: $(LIBFUSE) src/version.hpp $(OBJS)
$(CXX) $(CXXFLAGS) $(INC_FLAGS) $(MFS_FLAGS) $(CPPFLAGS) $(OBJS) -o $@ $(LDFLAGS) $(LDLIBS) $(CXX) $(CXXFLAGS) $(INC_FLAGS) $(MFS_FLAGS) $(CPPFLAGS) $(OBJS) -o $@ $(LDFLAGS) $(LDLIBS)
$(BUILDDIR)/fsck.mergerfs: $(BUILDDIR)/mergerfs $(BUILDDIR)/fsck.mergerfs:
$(LN) -sf "mergerfs" $@ $(LN) -sf "mergerfs" $@
$(BUILDDIR)/mergerfs.collect-info: $(BUILDDIR)/mergerfs $(BUILDDIR)/mergerfs.collect-info:
$(LN) -sf "mergerfs" $@ $(LN) -sf "mergerfs" $@
$(BUILDDIR)/tests: $(BUILDDIR)/mergerfs $(TESTS_OBJS) $(BUILDDIR)/tests: $(BUILDDIR)/mergerfs $(TESTS_OBJS)
$(CXX) $(CXXFLAGS) $(TESTS_FLAGS) $(INC_FLAGS) $(MFS_FLAGS) $(CPPFLAGS) $(TESTS_OBJS) -o $@ $(LDFLAGS) $(LDLIBS) $(CXX) $(CXXFLAGS) $(TESTS_FLAGS) $(INC_FLAGS) $(MFS_FLAGS) $(CPPFLAGS) $(TESTS_OBJS) -o $@ $(LDFLAGS) $(LDLIBS)
.PHONY: libfuse .PHONY: libfuse
libfuse: $(LIBFUSE)
$(MAKE) -C vendored/libfuse
$(LIBFUSE): $(LIBFUSE):
$(MAKE) -C vendored/libfuse $(BUILDDIR)/libfuse.a RELEASE=$(RELEASE) libfuse:
$(MAKE) -C libfuse
tests: $(BUILDDIR)/tests tests: $(BUILDDIR)/tests
@ -229,7 +216,7 @@ $(BUILDDIR)/stamp:
$(BUILDDIR)/.objs/%.cpp.o: src/%.cpp $(BUILDDIR)/stamp $(BUILDDIR)/.objs/%.cpp.o: src/%.cpp $(BUILDDIR)/stamp
$(CXX) $(CXXFLAGS) $(INC_FLAGS) $(MFS_FLAGS) $(CPPFLAGS) -c $< -o $@ $(CXX) $(CXXFLAGS) $(INC_FLAGS) $(MFS_FLAGS) $(CPPFLAGS) -c $< -o $@
$(BUILDDIR)/.test_objs/%.cpp.o: tests/%.cpp | $(BUILDDIR)/stamp $(BUILDDIR)/.test_objs/%.cpp.o: tests/%.cpp
$(CXX) $(CXXFLAGS) $(TESTS_FLAGS) $(INC_FLAGS) $(MFS_FLAGS) $(CPPFLAGS) -c $< -o $@ $(CXX) $(CXXFLAGS) $(TESTS_FLAGS) $(INC_FLAGS) $(MFS_FLAGS) $(CPPFLAGS) -c $< -o $@
$(BUILDDIR)/preload.so: $(BUILDDIR)/stamp tools/preload.c $(BUILDDIR)/preload.so: $(BUILDDIR)/stamp tools/preload.c
@ -241,7 +228,7 @@ preload: $(BUILDDIR)/preload.so
clean: rpm-clean clean: rpm-clean
$(RM) -rf $(BUILDDIR) $(RM) -rf $(BUILDDIR)
$(FIND) . -name "*~" -delete $(FIND) . -name "*~" -delete
$(MAKE) -C vendored/libfuse clean $(MAKE) -C libfuse clean
.PHONY: distclean .PHONY: distclean
distclean: clean distclean: clean
@ -262,7 +249,7 @@ install-base: all
.PHONY: install-mount-tools .PHONY: install-mount-tools
install-mount-tools: install-base install-mount-tools: install-base
$(MKDIR) -p "$(INSTALLBINDIR)" $(MKDIR) -p "$(INSTALLBINDIR)"
$(MAKE) -C vendored/libfuse install $(MAKE) -C libfuse install
.PHONY: install-man .PHONY: install-man
install-man: man/$(MANPAGE) install-man: man/$(MANPAGE)
@ -279,12 +266,10 @@ install-strip: install-base
$(STRIP) "$(INSTALLBINDIR)/mergerfs" $(STRIP) "$(INSTALLBINDIR)/mergerfs"
.PHONY: uninstall .PHONY: uninstall
uninstall: uninstall-base uninstall-mount.mergerfs uninstall-preload uninstall-man uninstall: uninstall-base uninstall-mount.mergerfs uninstall-man
uninstall-base: uninstall-base:
$(RM) -f "$(INSTALLBINDIR)/mergerfs" $(RM) -f "$(INSTALLBINDIR)/mergerfs"
$(RM) -f "$(INSTALLBINDIR)/fsck.mergerfs"
$(RM) -f "$(INSTALLBINDIR)/mergerfs.collect-info"
uninstall-mount.mergerfs: uninstall-mount.mergerfs:
$(RM) -f "$(INSTALLBINDIR)/mount.mergerfs" $(RM) -f "$(INSTALLBINDIR)/mount.mergerfs"
@ -292,9 +277,6 @@ uninstall-mount.mergerfs:
uninstall-man: uninstall-man:
$(RM) -f "$(INSTALLMAN1DIR)/$(MANPAGE)" $(RM) -f "$(INSTALLMAN1DIR)/$(MANPAGE)"
uninstall-preload:
$(RM) -f "$(INSTALLLIBDIR)/preload.so"
.PHONY: tarball .PHONY: tarball
tarball: changelog version tarball: changelog version
$(eval VERSION := $(shell cat VERSION)) $(eval VERSION := $(shell cat VERSION))
@ -312,10 +294,6 @@ ifdef GIT_REPO
$(GIT2DEBCL) --name mergerfs > debian/changelog $(GIT2DEBCL) --name mergerfs > debian/changelog
else else
$(CP) -v ChangeLog debian/changelog $(CP) -v ChangeLog debian/changelog
$(eval DISTRO := $(shell lsb_release -i -s | tr '[:upper:]' '[:lower:]'))
$(eval CODENAME := $(shell lsb_release -c -s | tr '[:upper:]' '[:lower:]'))
sed -i 's/~unknown-unknown/~$(DISTRO)-$(CODENAME)/g' debian/changelog
sed -i 's/ unknown; / $(CODENAME); /g' debian/changelog
endif endif
.PHONY: signed-deb .PHONY: signed-deb
@ -345,7 +323,7 @@ rpm: tarball
$(SED) 's/__VERSION__/$(VERSION)/g' mergerfs.spec > \ $(SED) 's/__VERSION__/$(VERSION)/g' mergerfs.spec > \
rpmbuild/SOURCES/mergerfs.spec rpmbuild/SOURCES/mergerfs.spec
cp -ar mergerfs-$(VERSION).tar.gz rpmbuild/SOURCES cp -ar mergerfs-$(VERSION).tar.gz rpmbuild/SOURCES
$(RPMBUILD) $(RPMBUILD_FLAGS) -ba rpmbuild/SOURCES/mergerfs.spec \ rpmbuild -ba rpmbuild/SOURCES/mergerfs.spec \
--define "_topdir $(CURDIR)/rpmbuild" --define "_topdir $(CURDIR)/rpmbuild"
.PHONY: install-build-pkgs .PHONY: install-build-pkgs
@ -354,7 +332,7 @@ install-build-pkgs:
.PHONY: install-build-tools .PHONY: install-build-tools
install-build-tools: install-build-tools:
./buildtools/install-build-tools ./bulidtools/install-build-tools
define build_release define build_release
$(eval GITREF ?= $(shell git describe --exact-match --tags HEAD 2>/dev/null || git symbolic-ref --short HEAD 2>/dev/null || git rev-parse --short HEAD)) $(eval GITREF ?= $(shell git describe --exact-match --tags HEAD 2>/dev/null || git symbolic-ref --short HEAD 2>/dev/null || git rev-parse --short HEAD))
@ -367,16 +345,13 @@ define build_release
--branch=$(GITREF) --branch=$(GITREF)
endef endef
.PHONY: release release-all .PHONY: release
.PHONY: release-amd64 release-arm64 release-armhf release-riscv64 .PHONY: release-amd64 release-arm64 release-armhf release-riscv64
.PHONY: release-sample release-static release-tarball release-installer .PHONY: release-sample release-static release-tarball
release: release:
$(MAKE) RELEASE=1 CPPFLAGS="$(CPPFLAGS) -DNDEBUG" all
release-all:
$(call build_release,"all") $(call build_release,"all")
release-sample: release-sample:
$(if $(TARGET),,$(eval TARGET := $(shell ./buildtools/detect-local-target 2>/dev/null))) $(call build_release,$(RELEASE_SAMPLE))
$(call build_release,$(if $(TARGET),$(TARGET),$(DEFAULT_TARGET)))
release-amd64: release-amd64:
$(call build_release,"amd64") $(call build_release,"amd64")
release-arm64: release-arm64:
@ -384,13 +359,11 @@ release-arm64:
release-armhf: release-armhf:
$(call build_release,"armhf") $(call build_release,"armhf")
release-riscv64: release-riscv64:
$(call build_release,"riscv64") $(call build_release,"risc64")
release-static: release-static:
$(call build_release,"static") $(call build_release,"static")
release-tarball: release-tarball:
$(call build_release,"tarball") $(call build_release,"tarball")
release-installer:
$(call build_release,"installer")
container: container:
$(eval GITREF ?= $(shell git describe --exact-match --tags HEAD 2>/dev/null || git symbolic-ref --short HEAD 2>/dev/null || git rev-parse --short HEAD)) $(eval GITREF ?= $(shell git describe --exact-match --tags HEAD 2>/dev/null || git symbolic-ref --short HEAD 2>/dev/null || git rev-parse --short HEAD))

View file

@ -25,7 +25,7 @@ etc.](https://trapexit.github.io/mergerfs/latest/project_comparisons/)
* Works with filesystems of [almost any * Works with filesystems of [almost any
type](https://trapexit.github.io/mergerfs/latest/faq/compatibility_and_integration/#what-filesystems-can-be-used-as-branches) type](https://trapexit.github.io/mergerfs/latest/faq/compatibility_and_integration/#what-filesystems-can-be-used-as-branches)
* Ignore read-only filesystems when creating files * Ignore read-only filesystems when creating files
* [Hard links](https://trapexit.github.io/mergerfs/latest/faq/technical_behavior_and_limitations/#do-hard-links-work) * [Hard links](https://trapexit.github.io/mergerfs/preview/faq/technical_behavior_and_limitations/#do-hard-links-work)
* Hard link [copy-on-write / * Hard link [copy-on-write /
CoW](https://trapexit.github.io/mergerfs/latest/config/link_cow/) CoW](https://trapexit.github.io/mergerfs/latest/config/link_cow/)
* [Runtime configurable](https://trapexit.github.io/mergerfs/latest/runtime_interface/) * [Runtime configurable](https://trapexit.github.io/mergerfs/latest/runtime_interface/)

View file

@ -2,7 +2,6 @@
GIT_BRANCH="${1:-master}" GIT_BRANCH="${1:-master}"
set -x
podman \ podman \
build \ build \
--squash \ --squash \
@ -12,5 +11,5 @@ podman \
--build-arg="BRANCH=${GIT_BRANCH}" \ --build-arg="BRANCH=${GIT_BRANCH}" \
-v "${PWD}":/mnt:ro \ -v "${PWD}":/mnt:ro \
-f "buildtools/containerimage/Containerfile" \ -f "buildtools/containerimage/Containerfile" \
--tag "ghcr.io/trapexit/mergerfs:${GIT_BRANCH}" \ --tag "mergerfs:${GIT_BRANCH}" \
buildtools/ buildtools/

View file

@ -1,19 +1,6 @@
#!/bin/sh #!/bin/sh
set -e set -e
if [ -e /tmp/build-env ]; then
. /tmp/build-env
fi
rpmbuild_flags()
{
case "$(command -v "${CXX:-g++}")" in
/opt/rh/*)
printf '%s' '--undefine _annotated_build'
;;
esac
}
if [ $# -ne 2 ]; then if [ $# -ne 2 ]; then
echo "usage: $0 <branch> <git_repo>" echo "usage: $0 <branch> <git_repo>"
echo "argv: $@" echo "argv: $@"
@ -41,29 +28,22 @@ mkdir "/build"
if [ -e /usr/bin/apt-get ]; then if [ -e /usr/bin/apt-get ]; then
make deb make deb
elif [ -e /usr/bin/dnf ]; then elif [ -e /usr/bin/dnf ]; then
make RPMBUILD_FLAGS="$(rpmbuild_flags)" rpm make rpm
elif [ -e /usr/bin/yum ]; then elif [ -e /usr/bin/yum ]; then
make RPMBUILD_FLAGS="$(rpmbuild_flags)" rpm . /opt/rh/devtoolset-9/enable
make rpm
elif [ -e /sbin/apk ]; then elif [ -e /sbin/apk ]; then
echo "NOT YET SUPPORTED" echo "NOT YET SUPPORTED"
exit 1 exit 1
elif [ -e /usr/sbin/pkg ]; then elif [ -e /usr/sbin/pkg ]; then
echo "NOT YET SUPPORTED" echo "NOT YET SUPPORTED"
exit 1 exit 1
elif [ -e /usr/bin/pacman ]; then
make tarball
else else
echo "NOT YET SUPPORTED" echo "NOT YET SUPPORTED"
exit 1 exit 1
fi fi
echo "Copy packages to host..." echo "Copy packages to host..."
if [ -e /usr/bin/pacman ]; then
find "${BUILDDIR}" \
-type f \
-name "*.tar.gz" \
-exec cp -v {} /build/ \;
else
find "${BUILDDIR}" \ find "${BUILDDIR}" \
-type f \ -type f \
\( -name "*.deb" -or -name "*.rpm" \) \ \( -name "*.deb" -or -name "*.rpm" \) \
@ -71,6 +51,5 @@ else
-not -name "*sym*" \ -not -name "*sym*" \
-not -name "*src.rpm" \ -not -name "*src.rpm" \
-exec cp -v {} /build/ \; -exec cp -v {} /build/ \;
fi
exit 0 exit 0

View file

@ -18,12 +18,10 @@ def build(git_repo,
'--force-rm'] '--force-rm']
if os.path.exists(git_repo): if os.path.exists(git_repo):
git_repo = os.path.realpath(git_repo) git_repo = os.path.realpath(git_repo)
args += ['-v',f'{git_repo}:/tmp/mergerfs.git:ro:z'] args += ['-v',f'{git_repo}:/tmp/mergerfs.git:ro']
args += ['--build-arg=GIT_REPO=file:///tmp/mergerfs.git'] args += ['--build-arg=GIT_REPO=file:///tmp/mergerfs.git']
else: else:
args += [f'--build-arg=GIT_REPO={git_repo}'] args += [f'--build-arg=GIT_REPO={git_repo}']
os.makedirs(pkgdirpath,exist_ok=True)
args += ['-v',f'{os.path.realpath(pkgdirpath)}:/pkgs:ro']
args += ['-o',pkgdirpath, args += ['-o',pkgdirpath,
'-f',containerfile, '-f',containerfile,
f'--build-arg=BRANCH={branch}', f'--build-arg=BRANCH={branch}',
@ -32,6 +30,8 @@ def build(git_repo,
# TODO: Capture output and write to log # TODO: Capture output and write to log
print(args) print(args)
rv = subprocess.run(args) rv = subprocess.run(args)
os.makedirs(pkgdirpath,exist_ok=True)
report_filepath = os.path.join(pkgdirpath,"build-report.txt") report_filepath = os.path.join(pkgdirpath,"build-report.txt")
with open(report_filepath,"a+") as f: with open(report_filepath,"a+") as f:
build = os.path.basename(containerfile) build = os.path.basename(containerfile)
@ -47,49 +47,14 @@ def build(git_repo,
def setup(): def setup():
# Detect distribution
if os.path.exists('/usr/bin/apt-get'):
args = ['sudo', args = ['sudo',
'apt-get', 'apt-get',
'install', 'install',
'-fy', '-fy',
'qemu-user-static', 'qemu-user-static',
'qemu-user-binfmt'] 'qemu-user-binfmt']
elif os.path.exists('/usr/bin/pacman'):
args = ['sudo',
'pacman',
'-Sy',
'--noconfirm',
'qemu-user-static']
else:
print("Unsupported distribution for setup")
sys.exit(1)
print(args) print(args)
subprocess.run(args) subprocess.run(args)
setup_binfmt()
def setup_binfmt():
"""Register qemu-user-static binfmt handlers (needed on Arch, etc.)."""
binfmt_conf = """\
:qemu-aarch64:M::\\x7fELF\\x02\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\xb7\\x00:\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff\\xff:/usr/bin/qemu-aarch64-static:F
:qemu-arm:M::\\x7fELF\\x01\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x28\\x00:\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff\\xff:/usr/bin/qemu-arm-static:F
:qemu-armeb:M::\\x7fELF\\x01\\x02\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x28:\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff:/usr/bin/qemu-armeb-static:F
:qemu-riscv64:M::\\x7fELF\\x02\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\xf3\\x00:\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff\\xff:/usr/bin/qemu-riscv64-static:F
:qemu-i386:M::\\x7fELF\\x01\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x03\\x00:\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff\\xff:/usr/bin/qemu-i386-static:F
"""
conf_path = '/etc/binfmt.d/qemu-static.conf'
print(f"Writing {conf_path}")
try:
with open(conf_path, 'w') as f:
f.write(binfmt_conf)
except PermissionError:
print(f"Permission denied writing {conf_path}; trying with sudo...")
subprocess.run(['sudo', 'tee', conf_path],
input=binfmt_conf.encode(), check=True)
print("Restarting systemd-binfmt...")
subprocess.run(['sudo', 'systemctl', 'restart', 'systemd-binfmt'])
def podman_cleanup(): def podman_cleanup():
@ -116,7 +81,7 @@ def parse_args():
required=False, required=False,
action='store_true') action='store_true')
p.add_argument('--git-repo', p.add_argument('--git-repo',
required=False, required=True,
type=str) type=str)
return p.parse_args() return p.parse_args()
@ -136,10 +101,6 @@ def main():
setup() setup()
sys.exit(0) sys.exit(0)
if not args.git_repo:
print("error: the following arguments are required: --git-repo")
sys.exit(1)
containerfiles = [] containerfiles = []
basepath = 'buildtools/containerfiles' basepath = 'buildtools/containerfiles'
if os.path.exists(f'{basepath}/{args.target}'): if os.path.exists(f'{basepath}/{args.target}'):

View file

@ -1,4 +1,4 @@
FROM --platform=amd64 fedora:44 as build FROM --platform=amd64 debian:11 as build
COPY install-build-pkgs build-mergerfs /tmp/ COPY install-build-pkgs build-mergerfs /tmp/
RUN /tmp/install-build-pkgs RUN /tmp/install-build-pkgs
ARG BUILD_TIMESTAMP=0 ARG BUILD_TIMESTAMP=0

View file

@ -1,4 +1,4 @@
FROM --platform=arm64 fedora:44 as build FROM --platform=arm64 debian:11 as build
COPY install-build-pkgs build-mergerfs /tmp/ COPY install-build-pkgs build-mergerfs /tmp/
RUN /tmp/install-build-pkgs RUN /tmp/install-build-pkgs
ARG BUILD_TIMESTAMP=0 ARG BUILD_TIMESTAMP=0

View file

@ -1,4 +1,4 @@
FROM --platform=amd64 fedora:45 as build FROM --platform=armhf debian:11 as build
COPY install-build-pkgs build-mergerfs /tmp/ COPY install-build-pkgs build-mergerfs /tmp/
RUN /tmp/install-build-pkgs RUN /tmp/install-build-pkgs
ARG BUILD_TIMESTAMP=0 ARG BUILD_TIMESTAMP=0

View file

@ -1,4 +1,4 @@
FROM --platform=arm64 fedora:45 as build FROM --platform=i386 debian:11 as build
COPY install-build-pkgs build-mergerfs /tmp/ COPY install-build-pkgs build-mergerfs /tmp/
RUN /tmp/install-build-pkgs RUN /tmp/install-build-pkgs
ARG BUILD_TIMESTAMP=0 ARG BUILD_TIMESTAMP=0

View file

@ -1,13 +1,9 @@
ARG BUILD_TIMESTAMP=0 ARG BUILD_TIMESTAMP=0
FROM --platform=linux/amd64 ubuntu:latest as build FROM --platform=linux/amd64 ubuntu:latest as build
COPY install-build-pkgs /tmp/ RUN apt-get update && apt-get install -y makeself
RUN /tmp/install-build-pkgs && \
DEBIAN_FRONTEND=noninteractive apt-get -qy --no-install-suggests --no-install-recommends install \
makeself
RUN mkdir -p /tmp/mergerfs/ RUN mkdir -p /tmp/mergerfs/
RUN ls -lhd /pkgs RUN --mount=type=bind,src=pkgs,dst=/pkgs ls -lhd /pkgs
RUN cp -v /pkgs/*static*.gz /tmp/mergerfs/ RUN --mount=type=bind,src=pkgs,dst=/pkgs cp -v /pkg/*static*.gz /tmp/mergerfs/
RUN mkdir -p /build
RUN makeself /tmp/mergerfs/ /build/mergerfs-installer.run "mergerfs" echo "foo" RUN makeself /tmp/mergerfs/ /build/mergerfs-installer.run "mergerfs" echo "foo"
FROM scratch FROM scratch

View file

@ -1,17 +1,13 @@
ARG BUILD_TIMESTAMP=0
FROM alpine:latest as tarball FROM alpine:latest as tarball
COPY install-build-pkgs /tmp/ COPY install-build-pkgs /tmp/
RUN /tmp/install-build-pkgs RUN /tmp/install-build-pkgs
ARG BUILD_TIMESTAMP=0
ARG BRANCH=master ARG BRANCH=master
ARG GIT_REPO RUN git clone --single-branch --depth=1 https://github.com/trapexit/mergerfs /tmp/mergerfs --branch="${BRANCH}"
RUN git clone --single-branch "${GIT_REPO}" /tmp/mergerfs --branch="${BRANCH}"
RUN cd /tmp/mergerfs && make version tarball RUN cd /tmp/mergerfs && make version tarball
RUN mkdir /build RUN mkdir /build
RUN cp -v /tmp/mergerfs/*.tar.gz /build/ RUN cp -v /tmp/mergerfs/*.tar.gz /build/
FROM scratch FROM scratch
COPY --from=tarball /build/ / COPY --from=tarball /build/ /

View file

@ -1,10 +0,0 @@
FROM --platform=amd64 ubuntu:25.10 as build
COPY install-build-pkgs build-mergerfs /tmp/
RUN /tmp/install-build-pkgs
ARG BUILD_TIMESTAMP=0
ARG GIT_REPO
ARG BRANCH
RUN /tmp/build-mergerfs $GIT_REPO $BRANCH
FROM scratch
COPY --from=build /build/ /

View file

@ -1,10 +0,0 @@
FROM --platform=arm64 ubuntu:25.10 as build
COPY install-build-pkgs build-mergerfs /tmp/
RUN /tmp/install-build-pkgs
ARG BUILD_TIMESTAMP=0
ARG GIT_REPO
ARG BRANCH
RUN /tmp/build-mergerfs $GIT_REPO $BRANCH
FROM scratch
COPY --from=build /build/ /

View file

@ -1,10 +0,0 @@
FROM --platform=armhf ubuntu:25.10 as build
COPY install-build-pkgs build-mergerfs /tmp/
RUN /tmp/install-build-pkgs
ARG BUILD_TIMESTAMP=0
ARG GIT_REPO
ARG BRANCH
RUN /tmp/build-mergerfs $GIT_REPO $BRANCH
FROM scratch
COPY --from=build /build/ /

View file

@ -1,10 +0,0 @@
FROM --platform=riscv64 ubuntu:25.10 as build
COPY install-build-pkgs build-mergerfs /tmp/
RUN /tmp/install-build-pkgs
ARG BUILD_TIMESTAMP=0
ARG GIT_REPO
ARG BRANCH
RUN /tmp/build-mergerfs $GIT_REPO $BRANCH
FROM scratch
COPY --from=build /build/ /

View file

@ -1,10 +0,0 @@
FROM --platform=amd64 ubuntu:26.04 as build
COPY install-build-pkgs build-mergerfs /tmp/
RUN /tmp/install-build-pkgs
ARG BUILD_TIMESTAMP=0
ARG GIT_REPO
ARG BRANCH
RUN /tmp/build-mergerfs $GIT_REPO $BRANCH
FROM scratch
COPY --from=build /build/ /

View file

@ -1,10 +0,0 @@
FROM --platform=arm64 ubuntu:26.04 as build
COPY install-build-pkgs build-mergerfs /tmp/
RUN /tmp/install-build-pkgs
ARG BUILD_TIMESTAMP=0
ARG GIT_REPO
ARG BRANCH
RUN /tmp/build-mergerfs $GIT_REPO $BRANCH
FROM scratch
COPY --from=build /build/ /

View file

@ -1,10 +0,0 @@
FROM --platform=armhf ubuntu:26.04 as build
COPY install-build-pkgs build-mergerfs /tmp/
RUN /tmp/install-build-pkgs
ARG BUILD_TIMESTAMP=0
ARG GIT_REPO
ARG BRANCH
RUN /tmp/build-mergerfs $GIT_REPO $BRANCH
FROM scratch
COPY --from=build /build/ /

View file

@ -1,10 +0,0 @@
FROM --platform=riscv64 ubuntu:26.04 as build
COPY install-build-pkgs build-mergerfs /tmp/
RUN /tmp/install-build-pkgs
ARG BUILD_TIMESTAMP=0
ARG GIT_REPO
ARG BRANCH
RUN /tmp/build-mergerfs $GIT_REPO $BRANCH
FROM scratch
COPY --from=build /build/ /

View file

@ -1,10 +0,0 @@
FROM --platform=amd64 ubuntu:26.10 as build
COPY install-build-pkgs build-mergerfs /tmp/
RUN /tmp/install-build-pkgs
ARG BUILD_TIMESTAMP=0
ARG GIT_REPO
ARG BRANCH
RUN /tmp/build-mergerfs $GIT_REPO $BRANCH
FROM scratch
COPY --from=build /build/ /

View file

@ -1,10 +0,0 @@
FROM --platform=arm64 ubuntu:26.10 as build
COPY install-build-pkgs build-mergerfs /tmp/
RUN /tmp/install-build-pkgs
ARG BUILD_TIMESTAMP=0
ARG GIT_REPO
ARG BRANCH
RUN /tmp/build-mergerfs $GIT_REPO $BRANCH
FROM scratch
COPY --from=build /build/ /

View file

@ -1,10 +0,0 @@
FROM --platform=armhf ubuntu:26.10 as build
COPY install-build-pkgs build-mergerfs /tmp/
RUN /tmp/install-build-pkgs
ARG BUILD_TIMESTAMP=0
ARG GIT_REPO
ARG BRANCH
RUN /tmp/build-mergerfs $GIT_REPO $BRANCH
FROM scratch
COPY --from=build /build/ /

View file

@ -1,10 +0,0 @@
FROM --platform=riscv64 ubuntu:26.10 as build
COPY install-build-pkgs build-mergerfs /tmp/
RUN /tmp/install-build-pkgs
ARG BUILD_TIMESTAMP=0
ARG GIT_REPO
ARG BRANCH
RUN /tmp/build-mergerfs $GIT_REPO $BRANCH
FROM scratch
COPY --from=build /build/ /

View file

@ -1,119 +0,0 @@
#!/bin/bash
# Detects local OS and maps to containerfiles target
# Returns target if found in buildtools/containerfiles/, empty string otherwise
set -euo pipefail
CONTAINERFILES_DIR="buildtools/containerfiles"
# Detect system architecture and map to containerfiles format
detect_arch() {
local arch
arch=$(uname -m)
case "$arch" in
x86_64) echo "amd64" ;;
aarch64) echo "arm64" ;;
armv7l) echo "armhf" ;;
i686|i386) echo "i386" ;;
riscv64) echo "riscv64" ;;
*) echo "" ;;
esac
}
# Detect distro and version from os-release
detect_distro() {
local os_release="${1:-}"
if [[ ! -r "$os_release" ]]; then
return 1
fi
# Source the file safely - ID and VERSION_ID are environment variables
. "$os_release"
local distro="$ID"
local version="$VERSION_ID"
# Map distro ID to containerfiles naming convention
case "$distro" in
ubuntu|debian|fedora) ;;
rocky|rhel|centos|almalinux) distro="rockylinux" ;;
*)
# Fallback to ID_LIKE for derivatives
if [[ -n "${ID_LIKE:-}" ]]; then
case "$ID_LIKE" in
*ubuntu*) distro="ubuntu" ;;
*debian*) distro="debian" ;;
*fedora*) distro="fedora" ;;
esac
fi
;;
esac
# Only return if we have valid distro and version
if [[ -n "$distro" && -n "$version" ]]; then
echo "$distro:$version"
else
return 1
fi
}
# Try to find a matching containerfile target
find_containerfile() {
local target="$1"
local containerfile="${CONTAINERFILES_DIR}/${target}"
# Direct match
if [[ -d "$containerfile" || -f "$containerfile" ]]; then
echo "$target"
return 0
fi
return 1
}
# Main detection logic
main() {
local arch
# Detect architecture
arch=$(detect_arch)
if [[ -z "$arch" ]]; then
echo "WARNING: Could not detect system architecture" >&2
exit 1
fi
# Try to detect distro from multiple locations
local distro_ver
distro_ver=$(detect_distro "/etc/os-release") || \
distro_ver=$(detect_distro "/usr/lib/os-release") || {
echo "WARNING: Could not detect distro from os-release" >&2
exit 1
}
# Build target string
local target="${distro_ver}.${arch}"
# Try to find matching containerfile
if find_containerfile "$target"; then
exit 0
fi
# Try with partial version matching (e.g., 25.10 → 25)
local distro="${distro_ver%%:*}"
local version="${distro_ver##*:}"
# Strip last minor version number and try again
local short_version="${version%.*}"
if [[ -n "$short_version" ]]; then
target="${distro}:${short_version}.${arch}"
if find_containerfile "$target"; then
exit 0
fi
fi
# No match found
echo "WARNING: No containerfile found for target: ${distro_ver}.${arch}" >&2
exit 1
}
main "$@"

View file

@ -1,166 +1,37 @@
#!/bin/sh #!/bin/sh
set -e
BUILD_ENV=/tmp/build-env
write_gcc_env()
{
{
printf 'export CC=%s\n' "$1"
printf 'export CXX=%s\n' "$2"
} > "$BUILD_ENV"
}
write_toolset_env()
{
{
printf '. %s\n' "$1"
printf 'export CC=gcc\n'
printf 'export CXX=g++\n'
} > "$BUILD_ENV"
}
latest_apt_gxx()
{
apt-cache --names-only search '^g[+][+]-[0-9]' \
| sed -n 's/^\(g++-[0-9][0-9]*\) .*/\1/p' \
| sort -t- -k2,2V \
| tail -n 1
}
latest_dnf_toolset()
{
dnf -q list --showduplicates 'gcc-toolset-*-gcc-c++' 2>/dev/null \
| sed -n 's/^gcc-toolset-\([0-9][0-9]*\)-gcc-c++\..*/\1/p' \
| sort -V \
| tail -n 1
}
latest_yum_toolset()
{
yum -q list available 'devtoolset-*-gcc-c++' 2>/dev/null \
| sed -n 's/^devtoolset-\([0-9][0-9]*\)-gcc-c++\..*/\1/p' \
| sort -V \
| tail -n 1
}
version_gt()
{
highest="$(printf '%s\n%s\n' "$1" "$2" | sort -V | tail -n 1)"
[ "$highest" = "$1" ] && [ "$1" != "$2" ]
}
check_cxx20()
{
cxx="${CXX:-g++}"
test_src=/tmp/mergerfs-cxx20-check.cpp
test_bin=/tmp/mergerfs-cxx20-check
cat > "$test_src" <<'EOF'
template <typename T>
concept Incrementable = requires(T value) { value + 1; };
static_assert(Incrementable<int>);
int main()
{
return 0;
}
EOF
if ! "$cxx" -std=c++20 "$test_src" -o "$test_bin" >/dev/null 2>&1; then
echo "error: $cxx does not support C++20" >&2
exit 1
fi
rm -f "$test_src" "$test_bin"
}
: > "$BUILD_ENV"
if [ -e /usr/bin/apt-get ]; then if [ -e /usr/bin/apt-get ]; then
export DEBIAN_FRONTEND=noninteractive export DEBIAN_FRONTEND=noninteractive
apt-get -qy update apt-get -qy update
cxx_pkg="$(latest_apt_gxx)"
if [ -n "$cxx_pkg" ]; then
gcc_pkg="gcc-${cxx_pkg#g++-}"
compiler_pkgs="$gcc_pkg $cxx_pkg"
write_gcc_env "$gcc_pkg" "$cxx_pkg"
else
compiler_pkgs="g++"
write_gcc_env gcc g++
fi
apt-get -qy --force-yes --no-install-suggests --no-install-recommends \ apt-get -qy --force-yes --no-install-suggests --no-install-recommends \
install \ install \
ca-certificates \ ca-certificates \
build-essential \ build-essential \
dpkg-dev \ dpkg-dev \
git \ git \
$compiler_pkgs \ g++ \
debhelper \ debhelper \
lsb-release \ lsb-release \
fakeroot fakeroot
. "$BUILD_ENV"
check_cxx20
elif [ -e /usr/bin/dnf ]; then elif [ -e /usr/bin/dnf ]; then
dnf -y update dnf -y update
toolset="$(latest_dnf_toolset)"
dnf -y install \ dnf -y install \
git rpm-build gcc-c++ make which libatomic git rpm-build gcc-c++ make which libatomic
default_gxx_major="$(g++ -dumpversion | cut -f1 -d.)"
if [ -n "$toolset" ] && version_gt "$toolset" "$default_gxx_major"; then
dnf -y install \
"gcc-toolset-${toolset}-gcc" \
"gcc-toolset-${toolset}-gcc-c++"
if [ -f "/usr/lib/gcc-toolset/${toolset}-env.source" ]; then
write_toolset_env "/usr/lib/gcc-toolset/${toolset}-env.source"
else
write_toolset_env "/opt/rh/gcc-toolset-${toolset}/enable"
fi
else
write_gcc_env gcc g++
fi
. "$BUILD_ENV"
check_cxx20
elif [ -e /usr/bin/yum ]; then elif [ -e /usr/bin/yum ]; then
yum -y update yum -y update
yum -y install \ yum -y install \
git rpm-build gcc-c++ make which git rpm-build gcc-c++ make which
yum -y install centos-release-scl || true yum -y install centos-release-scl
yum -y update yum -y install devtoolset-9-gcc\*
toolset="$(latest_yum_toolset)"
default_gxx_major="$(g++ -dumpversion | cut -f1 -d.)"
if [ -n "$toolset" ] && version_gt "$toolset" "$default_gxx_major"; then
yum -y install \
"devtoolset-${toolset}-gcc" \
"devtoolset-${toolset}-gcc-c++"
write_toolset_env "/opt/rh/devtoolset-${toolset}/enable"
else
write_gcc_env gcc g++
fi
. "$BUILD_ENV"
check_cxx20
elif [ -e /usr/bin/zypper ]; then elif [ -e /usr/bin/zypper ]; then
zypper update -y zypper update -y
zypper install -y \ zypper install -y \
git rpm-build gcc-c++ make which git rpm-build gcc-c++ make which
write_gcc_env gcc g++
. "$BUILD_ENV"
check_cxx20
elif [ -e /sbin/apk ]; then elif [ -e /sbin/apk ]; then
apk add \ apk add \
abuild git gcc g++ make \ abuild git gcc g++ make \
linux-headers linux-headers
write_gcc_env gcc g++
. "$BUILD_ENV"
check_cxx20
elif [ -e /usr/sbin/pkg ]; then elif [ -e /usr/sbin/pkg ]; then
pkg install \ pkg install \
git gmake gcc git gmake gcc
elif [ -e /usr/bin/pacman ]; then
pacman -Sy --noconfirm base-devel git fakeroot
write_gcc_env gcc g++
. "$BUILD_ENV"
check_cxx20
fi fi

View file

@ -1,32 +1,19 @@
#!/bin/sh #!/bin/sh
if [ "$(id -u)" -eq 0 ]; then
SUDO=
elif command -v sudo >/dev/null 2>&1; then
SUDO=sudo
elif command -v doas >/dev/null 2>&1; then
SUDO=doas
else
printf '%s\n' "error: need root privileges; run as root or install sudo/doas" >&2
exit 1
fi
if [ -e /usr/bin/apt-get ]; then if [ -e /usr/bin/apt-get ]; then
export DEBIAN_FRONTEND=noninteractive export DEBIAN_FRONTEND=noninteractive
${SUDO} apt-get -qy update apt-get -qy update
${SUDO} apt-get -qy --no-install-suggests --no-install-recommends install \ apt-get -qy --force-yes --no-install-suggests --no-install-recommends install \
qemu-user-static \ qemu-user-static \
podman podman
elif [ -e /usr/bin/dnf ]; then elif [ -e /usr/bin/dnf ]; then
${SUDO} dnf -y update dnf -y update
${SUDO} dnf -y install \ dnf -y install \
qemu-user-static \ qemu-user-static \
podman podman
elif [ -e /sbin/apk ]; then elif [ -e /sbin/apk ]; then
${SUDO} apk add \ apk add \
python3 \ python3 \
qemu-user-static \ qemu-user-static \
podman podman
elif [ -e /usr/bin/pacman ]; then
${SUDO} pacman -Sy --noconfirm qemu-user-static podman
fi fi

View file

@ -1,3 +1,7 @@
debian:11 amd64
debian:11 arm64
debian:11 armhf
debian:11 i386
debian:12 amd64 debian:12 amd64
debian:12 arm64 debian:12 arm64
debian:12 armhf debian:12 armhf
@ -15,10 +19,6 @@ fedora:42 amd64
fedora:42 arm64 fedora:42 arm64
fedora:43 amd64 fedora:43 amd64
fedora:43 arm64 fedora:43 arm64
fedora:44 amd64
fedora:44 arm64
fedora:45 amd64
fedora:45 arm64
quay.io/rockylinux/rockylinux:10 amd64 quay.io/rockylinux/rockylinux:10 amd64
quay.io/rockylinux/rockylinux:10 arm64 quay.io/rockylinux/rockylinux:10 arm64
quay.io/rockylinux/rockylinux:8 amd64 quay.io/rockylinux/rockylinux:8 amd64
@ -37,15 +37,3 @@ ubuntu:25.04 amd64
ubuntu:25.04 arm64 ubuntu:25.04 arm64
ubuntu:25.04 armhf ubuntu:25.04 armhf
ubuntu:25.04 riscv64 ubuntu:25.04 riscv64
ubuntu:25.10 amd64
ubuntu:25.10 arm64
ubuntu:25.10 armhf
ubuntu:25.10 riscv64
ubuntu:26.04 amd64
ubuntu:26.04 arm64
ubuntu:26.04 armhf
ubuntu:26.04 riscv64
ubuntu:26.10 amd64
ubuntu:26.10 arm64
ubuntu:26.10 armhf
ubuntu:26.10 riscv64

3
debian/rules vendored
View file

@ -6,9 +6,6 @@ export DH_VERBOSE=1
%: %:
dh $@ dh $@
override_dh_auto_build:
dh_auto_build --parallel -- release
override_dh_auto_install: override_dh_auto_install:
$(MAKE) \ $(MAKE) \
DESTDIR=$(CURDIR)/debian/mergerfs \ DESTDIR=$(CURDIR)/debian/mergerfs \

View file

@ -32,29 +32,25 @@ UTILS :=
INSTALLUTILS := INSTALLUTILS :=
endif endif
ifeq ($(NDEBUG),1)
OPT_FLAGS := -O2 -DNDEBUG
else
ifdef SANITIZE ifdef SANITIZE
ifeq ($(SANITIZE),1) ifeq ($(SANITIZE),1)
override SANITIZE := -fsanitize=address,undefined,leak override SANITIZE := -fsanitize=address,undefined,leak
else ifeq ($(filter -fsanitize=%,$(SANITIZE)),) else
override SANITIZE := -fsanitize=$(SANITIZE) override SANITIZE := -fsanitize=$(SANITIZE)
endif endif
endif endif
OPT_FLAGS := -O0 \
COMMON_OPT_FLAGS += \ -g \
-fno-omit-frame-pointer \
$(SANITIZE) \
-fstack-protector-strong \ -fstack-protector-strong \
-Wextra \ -Wextra \
-Wno-unused-parameter -Werror \
-Wno-unused-parameter \
DEBUG_OPT_FLAGS += \ -DDEBUG
-O0 \
-g3 \
-fno-omit-frame-pointer \
$(SANITIZE)
ifdef RELEASE
OPT_FLAGS := -O3 $(COMMON_OPT_FLAGS)
else
OPT_FLAGS ?= $(DEBUG_OPT_FLAGS) $(COMMON_OPT_FLAGS)
endif endif
ifeq ($(LTO),1) ifeq ($(LTO),1)
@ -80,7 +76,13 @@ INSTALLMAN1DIR ?= $(DESTDIR)$(MAN1DIR)
BUILDDIR := build BUILDDIR := build
SRC_C = SRC_C = \
lib/crc32b.c \
lib/fuse_opt.c \
lib/fuse_session.c \
lib/fuse_signals.c \
lib/helper.c \
lib/mount.c
SRC_CXX = $(wildcard lib/*.cpp) SRC_CXX = $(wildcard lib/*.cpp)
OBJS := $(SRC_C:lib/%.c=$(BUILDDIR)/.objs/%.c.o) OBJS := $(SRC_C:lib/%.c=$(BUILDDIR)/.objs/%.c.o)
@ -94,9 +96,7 @@ else
STATIC_FLAGS := STATIC_FLAGS :=
endif endif
CPPFLAGS ?= \ CPPFLAGS ?=
-D_FILE_OFFSET_BITS=64 \
-DBOOST_UNORDERED_DISABLE_PARALLEL_ALGORITHMS
CFLAGS ?= \ CFLAGS ?= \
$(OPT_FLAGS) \ $(OPT_FLAGS) \
$(LTO_FLAGS) \ $(LTO_FLAGS) \
@ -114,13 +114,12 @@ CXXFLAGS ?= \
-Wall \ -Wall \
-pipe -pipe
override CXXFLAGS += \ override CXXFLAGS += \
-std=c++20 \ -std=c++17 \
-MMD \ -MMD \
-MP -MP
FUSERMOUNT_DIR := $(BINDIR) FUSERMOUNT_DIR := $(BINDIR)
FUSE_FLAGS := \ FUSE_FLAGS := \
-Iinclude \ -Iinclude \
-I.. \
-I$(BUILDDIR) \ -I$(BUILDDIR) \
-D_REENTRANT \ -D_REENTRANT \
-D_FILE_OFFSET_BITS=64 \ -D_FILE_OFFSET_BITS=64 \
@ -137,28 +136,28 @@ $(BUILDDIR)/stamp:
$(MKDIR) -p $(BUILDDIR)/.objs/ $(MKDIR) -p $(BUILDDIR)/.objs/
$(TOUCH) $@ $(TOUCH) $@
$(BUILDDIR)/libfuse.a: $(OBJS) | $(BUILDDIR)/stamp $(BUILDDIR)/libfuse.a: $(OBJS)
$(AR) rcs $(BUILDDIR)/libfuse.a $(OBJS) $(AR) rcs $(BUILDDIR)/libfuse.a $(OBJS)
.PHONY: utils .PHONY: utils
utils: mergerfs-fusermount mount.mergerfs utils: mergerfs-fusermount mount.mergerfs
$(BUILDDIR)/mergerfs-fusermount: util/fusermount.cpp | $(BUILDDIR)/stamp $(BUILDDIR)/mergerfs-fusermount: util/fusermount.c lib/mount_util.c
$(CXX) $(CXXFLAGS) $(FUSE_FLAGS) -Ilib -o $(BUILDDIR)/mergerfs-fusermount util/fusermount.cpp $(CC) $(CFLAGS) $(FUSE_FLAGS) -Ilib -o $(BUILDDIR)/mergerfs-fusermount util/fusermount.c lib/mount_util.c
mergerfs-fusermount: $(BUILDDIR)/mergerfs-fusermount mergerfs-fusermount: $(BUILDDIR)/mergerfs-fusermount
$(BUILDDIR)/mount.mergerfs: $(BUILDDIR)/libfuse.a util/mount.mergerfs.cpp $(BUILDDIR)/mount.mergerfs: $(BUILDDIR)/libfuse.a util/mount.mergerfs.c
echo STATIC=$(STATIC) $(STATIC_FLAGS) echo STATIC=$(STATIC) $(STATIC_FLAGS)
$(CXX) $(CXXFLAGS) $(FUSE_FLAGS) -o $(BUILDDIR)/mount.mergerfs util/mount.mergerfs.cpp $(BUILDDIR)/libfuse.a $(LDFLAGS) $(CC) $(CFLAGS) $(FUSE_FLAGS) -o $(BUILDDIR)/mount.mergerfs util/mount.mergerfs.c $(BUILDDIR)/libfuse.a $(LDFLAGS)
mount.mergerfs: $(BUILDDIR)/mount.mergerfs mount.mergerfs: $(BUILDDIR)/mount.mergerfs
$(BUILDDIR)/.objs/%.c.o: lib/%.c | $(BUILDDIR)/stamp $(BUILDDIR)/.objs/%.c.o: lib/%.c | $(BUILDDIR)/stamp
$(CC) $(CFLAGS) $(CPPFLAGS) $(FUSE_FLAGS) -c $< -o $@ $(CC) $(CFLAGS) $(FUSE_FLAGS) -c $< -o $@
$(BUILDDIR)/.objs/%.cpp.o: lib/%.cpp | $(BUILDDIR)/stamp $(BUILDDIR)/.objs/%.cpp.o: lib/%.cpp | $(BUILDDIR)/stamp
$(CXX) $(CXXFLAGS) $(CPPFLAGS) $(FUSE_FLAGS) -c $< -o $@ $(CXX) $(CXXFLAGS) $(FUSE_FLAGS) -c $< -o $@
.PHONY: clean .PHONY: clean
clean: clean:
@ -180,10 +179,6 @@ install-utils: mergerfs-fusermount mount.mergerfs strip
install: $(INSTALLUTILS) install: $(INSTALLUTILS)
.PHONY: release
release:
$(MAKE) RELEASE=1 NDEBUG=1 CPPFLAGS="$(CPPFLAGS) -DNDEBUG" all
.PHONY: objects strip utils install install-utils .PHONY: objects strip utils install install-utils
-include $(DEPS) -include $(DEPS)

View file

@ -27,8 +27,7 @@ Because the high-level interface is path based, it is not possible to
delegate looking up by inode to the filesystem. delegate looking up by inode to the filesystem.
To work around this, currently a "noforget" option is provided, which To work around this, currently a "noforget" option is provided, which
makes the library remember nodes until they are unlinked or otherwise makes the library remember nodes forever. This will make the NFS
removed. This will make the NFS server happy, but also results in a server happy, but also results in an ever growing memory footprint for
larger memory footprint for the filesystem. For this reason if the the filesystem. For this reason if the filesystem is large (or the
filesystem is large (or the memory is small), then this option is not memory is small), then this option is not recommended.
recommended.

View file

@ -71,7 +71,7 @@ class dynamic_arg_list {
* It can be implicitly converted into `fmt::basic_format_args` for passing * It can be implicitly converted into `fmt::basic_format_args` for passing
* into type-erased formatting functions such as `fmt::vformat`. * into type-erased formatting functions such as `fmt::vformat`.
*/ */
FMT_EXPORT template <typename Context> class dynamic_format_arg_store { template <typename Context> class dynamic_format_arg_store {
private: private:
using char_type = typename Context::char_type; using char_type = typename Context::char_type;
@ -212,7 +212,7 @@ FMT_EXPORT template <typename Context> class dynamic_format_arg_store {
} }
/// Returns the number of elements in the store. /// Returns the number of elements in the store.
auto size() const noexcept -> size_t { return data_.size(); } size_t size() const noexcept { return data_.size(); }
}; };
FMT_END_NAMESPACE FMT_END_NAMESPACE

View file

@ -21,7 +21,7 @@
#endif #endif
// The fmt library version in the form major * 10000 + minor * 100 + patch. // The fmt library version in the form major * 10000 + minor * 100 + patch.
#define FMT_VERSION 120100 #define FMT_VERSION 110200
// Detect compiler versions. // Detect compiler versions.
#if defined(__clang__) && !defined(__ibmxl__) #if defined(__clang__) && !defined(__ibmxl__)
@ -114,9 +114,7 @@
#endif #endif
// Detect consteval, C++20 constexpr extensions and std::is_constant_evaluated. // Detect consteval, C++20 constexpr extensions and std::is_constant_evaluated.
#ifdef FMT_USE_CONSTEVAL #if !defined(__cpp_lib_is_constant_evaluated)
// Use the provided definition.
#elif !defined(__cpp_lib_is_constant_evaluated)
# define FMT_USE_CONSTEVAL 0 # define FMT_USE_CONSTEVAL 0
#elif FMT_CPLUSPLUS < 201709L #elif FMT_CPLUSPLUS < 201709L
# define FMT_USE_CONSTEVAL 0 # define FMT_USE_CONSTEVAL 0
@ -203,6 +201,14 @@
# define FMT_NODISCARD # define FMT_NODISCARD
#endif #endif
#ifdef FMT_DEPRECATED
// Use the provided definition.
#elif FMT_HAS_CPP14_ATTRIBUTE(deprecated)
# define FMT_DEPRECATED [[deprecated]]
#else
# define FMT_DEPRECATED /* deprecated */
#endif
#if FMT_GCC_VERSION || FMT_CLANG_VERSION #if FMT_GCC_VERSION || FMT_CLANG_VERSION
# define FMT_VISIBILITY(value) __attribute__((visibility(value))) # define FMT_VISIBILITY(value) __attribute__((visibility(value)))
#else #else
@ -236,7 +242,6 @@ FMT_PRAGMA_GCC(optimize("Og"))
# define FMT_GCC_OPTIMIZED # define FMT_GCC_OPTIMIZED
#endif #endif
FMT_PRAGMA_CLANG(diagnostic push) FMT_PRAGMA_CLANG(diagnostic push)
FMT_PRAGMA_GCC(diagnostic push)
#ifdef FMT_ALWAYS_INLINE #ifdef FMT_ALWAYS_INLINE
// Use the provided definition. // Use the provided definition.
@ -255,7 +260,7 @@ FMT_PRAGMA_GCC(diagnostic push)
#ifndef FMT_BEGIN_NAMESPACE #ifndef FMT_BEGIN_NAMESPACE
# define FMT_BEGIN_NAMESPACE \ # define FMT_BEGIN_NAMESPACE \
namespace fmt { \ namespace fmt { \
inline namespace v12 { inline namespace v11 {
# define FMT_END_NAMESPACE \ # define FMT_END_NAMESPACE \
} \ } \
} }
@ -351,9 +356,6 @@ template <typename T> constexpr auto max_of(T a, T b) -> T {
return a > b ? a : b; return a > b ? a : b;
} }
FMT_NORETURN FMT_API void assert_fail(const char* file, int line,
const char* message);
namespace detail { namespace detail {
// Suppresses "unused variable" warnings with the method described in // Suppresses "unused variable" warnings with the method described in
// https://herbsutter.com/2009/10/18/mailbag-shutting-up-compiler-warnings/. // https://herbsutter.com/2009/10/18/mailbag-shutting-up-compiler-warnings/.
@ -394,7 +396,7 @@ FMT_NORETURN FMT_API void assert_fail(const char* file, int line,
# define FMT_ASSERT(condition, message) \ # define FMT_ASSERT(condition, message) \
((condition) /* void() fails with -Winvalid-constexpr on clang 4.0.1 */ \ ((condition) /* void() fails with -Winvalid-constexpr on clang 4.0.1 */ \
? (void)0 \ ? (void)0 \
: ::fmt::assert_fail(__FILE__, __LINE__, (message))) : fmt::detail::assert_fail(__FILE__, __LINE__, (message)))
#endif #endif
#ifdef FMT_USE_INT128 #ifdef FMT_USE_INT128
@ -417,12 +419,8 @@ inline auto map(int128_opt) -> monostate { return {}; }
inline auto map(uint128_opt) -> monostate { return {}; } inline auto map(uint128_opt) -> monostate { return {}; }
#endif #endif
#ifdef FMT_USE_BITINT #ifndef FMT_USE_BITINT
// Use the provided definition. # define FMT_USE_BITINT (FMT_CLANG_VERSION >= 1500)
#elif FMT_CLANG_VERSION >= 1500 && !defined(__CUDACC__)
# define FMT_USE_BITINT 1
#else
# define FMT_USE_BITINT 0
#endif #endif
#if FMT_USE_BITINT #if FMT_USE_BITINT
@ -465,13 +463,12 @@ enum { use_utf8 = !FMT_WIN32 || is_utf8_enabled };
static_assert(!FMT_UNICODE || use_utf8, static_assert(!FMT_UNICODE || use_utf8,
"Unicode support requires compiling with /utf-8"); "Unicode support requires compiling with /utf-8");
template <typename T> constexpr auto narrow(T*) -> char* { return nullptr; } template <typename T> constexpr const char* narrow(const T*) { return nullptr; }
constexpr FMT_ALWAYS_INLINE auto narrow(const char* s) -> const char* { constexpr FMT_ALWAYS_INLINE const char* narrow(const char* s) { return s; }
return s;
}
template <typename Char> template <typename Char>
FMT_CONSTEXPR auto compare(const Char* s1, const Char* s2, size_t n) -> int { FMT_CONSTEXPR auto compare(const Char* s1, const Char* s2, std::size_t n)
-> int {
if (!is_constant_evaluated() && sizeof(Char) == 1) return memcmp(s1, s2, n); if (!is_constant_evaluated() && sizeof(Char) == 1) return memcmp(s1, s2, n);
for (; n != 0; ++s1, ++s2, --n) { for (; n != 0; ++s1, ++s2, --n) {
if (*s1 < *s2) return -1; if (*s1 < *s2) return -1;
@ -543,7 +540,7 @@ template <typename Char> class basic_string_view {
FMT_CONSTEXPR20 basic_string_view(const Char* s) : data_(s) { FMT_CONSTEXPR20 basic_string_view(const Char* s) : data_(s) {
#if FMT_HAS_BUILTIN(__builtin_strlen) || FMT_GCC_VERSION || FMT_CLANG_VERSION #if FMT_HAS_BUILTIN(__builtin_strlen) || FMT_GCC_VERSION || FMT_CLANG_VERSION
if (std::is_same<Char, char>::value && !detail::is_constant_evaluated()) { if (std::is_same<Char, char>::value && !detail::is_constant_evaluated()) {
size_ = __builtin_strlen(detail::narrow(s)); // strlen is not constexpr. size_ = __builtin_strlen(detail::narrow(s)); // strlen is not costexpr.
return; return;
} }
#endif #endif
@ -619,6 +616,19 @@ template <typename Char> class basic_string_view {
using string_view = basic_string_view<char>; using string_view = basic_string_view<char>;
// DEPRECATED! Will be merged with is_char and moved to detail.
template <typename T> struct is_xchar : std::false_type {};
template <> struct is_xchar<wchar_t> : std::true_type {};
template <> struct is_xchar<char16_t> : std::true_type {};
template <> struct is_xchar<char32_t> : std::true_type {};
#ifdef __cpp_char8_t
template <> struct is_xchar<char8_t> : std::true_type {};
#endif
// Specifies if `T` is a character (code unit) type.
template <typename T> struct is_char : is_xchar<T> {};
template <> struct is_char<char> : std::true_type {};
template <typename T> class basic_appender; template <typename T> class basic_appender;
using appender = basic_appender<char>; using appender = basic_appender<char>;
@ -771,7 +781,7 @@ class basic_specs {
(static_cast<unsigned>(p) << precision_shift); (static_cast<unsigned>(p) << precision_shift);
} }
constexpr auto dynamic() const -> bool { constexpr bool dynamic() const {
return (data_ & (width_mask | precision_mask)) != 0; return (data_ & (width_mask | precision_mask)) != 0;
} }
@ -911,50 +921,14 @@ template <typename Char = char> class parse_context {
FMT_CONSTEXPR void check_dynamic_spec(int arg_id); FMT_CONSTEXPR void check_dynamic_spec(int arg_id);
}; };
#ifndef FMT_USE_LOCALE
# define FMT_USE_LOCALE (FMT_OPTIMIZE_SIZE <= 1)
#endif
// A type-erased reference to std::locale to avoid the heavy <locale> include.
class locale_ref {
#if FMT_USE_LOCALE
private:
const void* locale_; // A type-erased pointer to std::locale.
public:
constexpr locale_ref() : locale_(nullptr) {}
template <typename Locale, FMT_ENABLE_IF(sizeof(Locale::collate) != 0)>
locale_ref(const Locale& loc) : locale_(&loc) {
// Check if std::isalpha is found via ADL to reduce the chance of misuse.
isalpha('x', loc);
}
inline explicit operator bool() const noexcept { return locale_ != nullptr; }
#endif // FMT_USE_LOCALE
public:
template <typename Locale> auto get() const -> Locale;
};
FMT_END_EXPORT FMT_END_EXPORT
namespace detail { namespace detail {
// Specifies if `T` is a code unit type.
template <typename T> struct is_code_unit : std::false_type {};
template <> struct is_code_unit<char> : std::true_type {};
template <> struct is_code_unit<wchar_t> : std::true_type {};
template <> struct is_code_unit<char16_t> : std::true_type {};
template <> struct is_code_unit<char32_t> : std::true_type {};
#ifdef __cpp_char8_t
template <> struct is_code_unit<char8_t> : bool_constant<is_utf8_enabled> {};
#endif
// Constructs fmt::basic_string_view<Char> from types implicitly convertible // Constructs fmt::basic_string_view<Char> from types implicitly convertible
// to it, deducing Char. Explicitly convertible types such as the ones returned // to it, deducing Char. Explicitly convertible types such as the ones returned
// from FMT_STRING are intentionally excluded. // from FMT_STRING are intentionally excluded.
template <typename Char, FMT_ENABLE_IF(is_code_unit<Char>::value)> template <typename Char, FMT_ENABLE_IF(is_char<Char>::value)>
constexpr auto to_string_view(const Char* s) -> basic_string_view<Char> { constexpr auto to_string_view(const Char* s) -> basic_string_view<Char> {
return s; return s;
} }
@ -1083,11 +1057,11 @@ template <bool B1, bool B2, bool... Tail> constexpr auto count() -> int {
return (B1 ? 1 : 0) + count<B2, Tail...>(); return (B1 ? 1 : 0) + count<B2, Tail...>();
} }
template <typename... T> constexpr auto count_named_args() -> int { template <typename... Args> constexpr auto count_named_args() -> int {
return count<is_named_arg<T>::value...>(); return count<is_named_arg<Args>::value...>();
} }
template <typename... T> constexpr auto count_static_named_args() -> int { template <typename... Args> constexpr auto count_static_named_args() -> int {
return count<is_static_named_arg<T>::value...>(); return count<is_static_named_arg<Args>::value...>();
} }
template <typename Char> struct named_arg_info { template <typename Char> struct named_arg_info {
@ -1095,7 +1069,7 @@ template <typename Char> struct named_arg_info {
int id; int id;
}; };
// named_args is non-const to suppress a bogus -Wmaybe-uninitialized in gcc 13. // named_args is non-const to suppress a bogus -Wmaybe-uninitalized in gcc 13.
template <typename Char> template <typename Char>
FMT_CONSTEXPR void check_for_duplicate(named_arg_info<Char>* named_args, FMT_CONSTEXPR void check_for_duplicate(named_arg_info<Char>* named_args,
int named_arg_index, int named_arg_index,
@ -1199,7 +1173,7 @@ template <typename Char> struct type_mapper {
static auto map(ubitint<N>) static auto map(ubitint<N>)
-> conditional_t<N <= 64, unsigned long long, void>; -> conditional_t<N <= 64, unsigned long long, void>;
template <typename T, FMT_ENABLE_IF(is_code_unit<T>::value)> template <typename T, FMT_ENABLE_IF(is_char<T>::value)>
static auto map(T) -> conditional_t< static auto map(T) -> conditional_t<
std::is_same<T, char>::value || std::is_same<T, Char>::value, Char, void>; std::is_same<T, char>::value || std::is_same<T, Char>::value, Char, void>;
@ -1705,12 +1679,12 @@ template <typename... T> struct arg_pack {};
template <typename Char, int NUM_ARGS, int NUM_NAMED_ARGS, bool DYNAMIC_NAMES> template <typename Char, int NUM_ARGS, int NUM_NAMED_ARGS, bool DYNAMIC_NAMES>
class format_string_checker { class format_string_checker {
private: private:
type types_[max_of<size_t>(1, NUM_ARGS)]; type types_[max_of(1, NUM_ARGS)];
named_arg_info<Char> named_args_[max_of<size_t>(1, NUM_NAMED_ARGS)]; named_arg_info<Char> named_args_[max_of(1, NUM_NAMED_ARGS)];
compile_parse_context<Char> context_; compile_parse_context<Char> context_;
using parse_func = auto (*)(parse_context<Char>&) -> const Char*; using parse_func = auto (*)(parse_context<Char>&) -> const Char*;
parse_func parse_funcs_[max_of<size_t>(1, NUM_ARGS)]; parse_func parse_funcs_[max_of(1, NUM_ARGS)];
public: public:
template <typename... T> template <typename... T>
@ -1854,17 +1828,12 @@ template <typename T> class buffer {
void void
append(const U* begin, const U* end) { append(const U* begin, const U* end) {
while (begin != end) { while (begin != end) {
auto size = size_;
auto free_cap = capacity_ - size;
auto count = to_unsigned(end - begin); auto count = to_unsigned(end - begin);
if (free_cap < count) { try_reserve(size_ + count);
grow_(*this, size + count); auto free_cap = capacity_ - size_;
size = size_; if (free_cap < count) count = free_cap;
free_cap = capacity_ - size;
count = count < free_cap ? count : free_cap;
}
// A loop is faster than memcpy on small sizes. // A loop is faster than memcpy on small sizes.
T* out = ptr_ + size; T* out = ptr_ + size_;
for (size_t i = 0; i < count; ++i) out[i] = begin[i]; for (size_t i = 0; i < count; ++i) out[i] = begin[i];
size_ += count; size_ += count;
begin += count; begin += count;
@ -2064,17 +2033,6 @@ struct has_back_insert_iterator_container_append<
.append(std::declval<InputIt>(), .append(std::declval<InputIt>(),
std::declval<InputIt>()))>> : std::true_type {}; std::declval<InputIt>()))>> : std::true_type {};
template <typename OutputIt, typename InputIt, typename = void>
struct has_back_insert_iterator_container_insert_at_end : std::false_type {};
template <typename OutputIt, typename InputIt>
struct has_back_insert_iterator_container_insert_at_end<
OutputIt, InputIt,
void_t<decltype(get_container(std::declval<OutputIt>())
.insert(get_container(std::declval<OutputIt>()).end(),
std::declval<InputIt>(),
std::declval<InputIt>()))>> : std::true_type {};
// An optimized version of std::copy with the output value type (T). // An optimized version of std::copy with the output value type (T).
template <typename T, typename InputIt, typename OutputIt, template <typename T, typename InputIt, typename OutputIt,
FMT_ENABLE_IF(is_back_insert_iterator<OutputIt>::value&& FMT_ENABLE_IF(is_back_insert_iterator<OutputIt>::value&&
@ -2089,8 +2047,6 @@ FMT_CONSTEXPR20 auto copy(InputIt begin, InputIt end, OutputIt out)
template <typename T, typename InputIt, typename OutputIt, template <typename T, typename InputIt, typename OutputIt,
FMT_ENABLE_IF(is_back_insert_iterator<OutputIt>::value && FMT_ENABLE_IF(is_back_insert_iterator<OutputIt>::value &&
!has_back_insert_iterator_container_append< !has_back_insert_iterator_container_append<
OutputIt, InputIt>::value &&
has_back_insert_iterator_container_insert_at_end<
OutputIt, InputIt>::value)> OutputIt, InputIt>::value)>
FMT_CONSTEXPR20 auto copy(InputIt begin, InputIt end, OutputIt out) FMT_CONSTEXPR20 auto copy(InputIt begin, InputIt end, OutputIt out)
-> OutputIt { -> OutputIt {
@ -2100,11 +2056,7 @@ FMT_CONSTEXPR20 auto copy(InputIt begin, InputIt end, OutputIt out)
} }
template <typename T, typename InputIt, typename OutputIt, template <typename T, typename InputIt, typename OutputIt,
FMT_ENABLE_IF(!(is_back_insert_iterator<OutputIt>::value && FMT_ENABLE_IF(!is_back_insert_iterator<OutputIt>::value)>
(has_back_insert_iterator_container_append<
OutputIt, InputIt>::value ||
has_back_insert_iterator_container_insert_at_end<
OutputIt, InputIt>::value)))>
FMT_CONSTEXPR auto copy(InputIt begin, InputIt end, OutputIt out) -> OutputIt { FMT_CONSTEXPR auto copy(InputIt begin, InputIt end, OutputIt out) -> OutputIt {
while (begin != end) *out++ = static_cast<T>(*begin++); while (begin != end) *out++ = static_cast<T>(*begin++);
return out; return out;
@ -2224,7 +2176,7 @@ template <typename Context> class value {
static_assert(N <= 64, "unsupported _BitInt"); static_assert(N <= 64, "unsupported _BitInt");
} }
template <typename T, FMT_ENABLE_IF(is_code_unit<T>::value)> template <typename T, FMT_ENABLE_IF(is_char<T>::value)>
constexpr FMT_INLINE value(T x FMT_BUILTIN) : char_value(x) { constexpr FMT_INLINE value(T x FMT_BUILTIN) : char_value(x) {
static_assert( static_assert(
std::is_same<T, char>::value || std::is_same<T, char_type>::value, std::is_same<T, char>::value || std::is_same<T, char_type>::value,
@ -2300,7 +2252,7 @@ template <typename Context> class value {
custom.value = const_cast<value_type*>(&x); custom.value = const_cast<value_type*>(&x);
#endif #endif
} }
custom.format = format_custom<value_type>; custom.format = format_custom<value_type, formatter<value_type, char_type>>;
} }
template <typename T, FMT_ENABLE_IF(!has_formatter<T, char_type>())> template <typename T, FMT_ENABLE_IF(!has_formatter<T, char_type>())>
@ -2311,10 +2263,10 @@ template <typename Context> class value {
} }
// Formats an argument of a custom type, such as a user-defined class. // Formats an argument of a custom type, such as a user-defined class.
template <typename T> template <typename T, typename Formatter>
static void format_custom(void* arg, parse_context<char_type>& parse_ctx, static void format_custom(void* arg, parse_context<char_type>& parse_ctx,
Context& ctx) { Context& ctx) {
auto f = formatter<T, char_type>(); auto f = Formatter();
parse_ctx.advance_to(f.parse(parse_ctx)); parse_ctx.advance_to(f.parse(parse_ctx));
using qualified_type = using qualified_type =
conditional_t<has_formatter<const T, char_type>(), const T, T>; conditional_t<has_formatter<const T, char_type>(), const T, T>;
@ -2341,14 +2293,35 @@ struct is_output_iterator<
enable_if_t<std::is_assignable<decltype(*std::declval<decay_t<It>&>()++), enable_if_t<std::is_assignable<decltype(*std::declval<decay_t<It>&>()++),
T>::value>> : std::true_type {}; T>::value>> : std::true_type {};
#ifndef FMT_USE_LOCALE
# define FMT_USE_LOCALE (FMT_OPTIMIZE_SIZE <= 1)
#endif
// A type-erased reference to an std::locale to avoid a heavy <locale> include.
class locale_ref {
#if FMT_USE_LOCALE
private:
const void* locale_; // A type-erased pointer to std::locale.
public:
constexpr locale_ref() : locale_(nullptr) {}
template <typename Locale> locale_ref(const Locale& loc);
inline explicit operator bool() const noexcept { return locale_ != nullptr; }
#endif // FMT_USE_LOCALE
public:
template <typename Locale> auto get() const -> Locale;
};
template <typename> constexpr auto encode_types() -> unsigned long long { template <typename> constexpr auto encode_types() -> unsigned long long {
return 0; return 0;
} }
template <typename Context, typename First, typename... T> template <typename Context, typename Arg, typename... Args>
constexpr auto encode_types() -> unsigned long long { constexpr auto encode_types() -> unsigned long long {
return static_cast<unsigned>(stored_type_constant<First, Context>::value) | return static_cast<unsigned>(stored_type_constant<Arg, Context>::value) |
(encode_types<Context, T...>() << packed_arg_bits); (encode_types<Context, Args...>() << packed_arg_bits);
} }
template <typename Context, typename... T, size_t NUM_ARGS = sizeof...(T)> template <typename Context, typename... T, size_t NUM_ARGS = sizeof...(T)>
@ -2365,9 +2338,8 @@ template <typename Context, int NUM_ARGS, int NUM_NAMED_ARGS,
unsigned long long DESC> unsigned long long DESC>
struct named_arg_store { struct named_arg_store {
// args_[0].named_args points to named_args to avoid bloating format_args. // args_[0].named_args points to named_args to avoid bloating format_args.
arg_t<Context, NUM_ARGS> args[1u + NUM_ARGS]; arg_t<Context, NUM_ARGS> args[1 + NUM_ARGS];
named_arg_info<typename Context::char_type> named_arg_info<typename Context::char_type> named_args[NUM_NAMED_ARGS];
named_args[static_cast<size_t>(NUM_NAMED_ARGS)];
template <typename... T> template <typename... T>
FMT_CONSTEXPR FMT_ALWAYS_INLINE named_arg_store(T&... values) FMT_CONSTEXPR FMT_ALWAYS_INLINE named_arg_store(T&... values)
@ -2386,8 +2358,8 @@ struct named_arg_store {
} }
named_arg_store(const named_arg_store& rhs) = delete; named_arg_store(const named_arg_store& rhs) = delete;
auto operator=(const named_arg_store& rhs) -> named_arg_store& = delete; named_arg_store& operator=(const named_arg_store& rhs) = delete;
auto operator=(named_arg_store&& rhs) -> named_arg_store& = delete; named_arg_store& operator=(named_arg_store&& rhs) = delete;
operator const arg_t<Context, NUM_ARGS>*() const { return args + 1; } operator const arg_t<Context, NUM_ARGS>*() const { return args + 1; }
}; };
@ -2400,7 +2372,7 @@ struct format_arg_store {
// +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning. // +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning.
using type = using type =
conditional_t<NUM_NAMED_ARGS == 0, conditional_t<NUM_NAMED_ARGS == 0,
arg_t<Context, NUM_ARGS>[max_of<size_t>(1, NUM_ARGS)], arg_t<Context, NUM_ARGS>[max_of(1, NUM_ARGS)],
named_arg_store<Context, NUM_ARGS, NUM_NAMED_ARGS, DESC>>; named_arg_store<Context, NUM_ARGS, NUM_NAMED_ARGS, DESC>>;
type args; type args;
}; };
@ -2684,17 +2656,22 @@ class context {
private: private:
appender out_; appender out_;
format_args args_; format_args args_;
FMT_NO_UNIQUE_ADDRESS locale_ref loc_; FMT_NO_UNIQUE_ADDRESS detail::locale_ref loc_;
public: public:
using char_type = char; ///< The character type for the output. /// The character type for the output.
using char_type = char;
using iterator = appender; using iterator = appender;
using format_arg = basic_format_arg<context>; using format_arg = basic_format_arg<context>;
using parse_context_type FMT_DEPRECATED = parse_context<>;
template <typename T> using formatter_type FMT_DEPRECATED = formatter<T>;
enum { builtin_types = FMT_BUILTIN_TYPES }; enum { builtin_types = FMT_BUILTIN_TYPES };
/// Constructs a `context` object. References to the arguments are stored /// Constructs a `context` object. References to the arguments are stored
/// in the object so make sure they have appropriate lifetimes. /// in the object so make sure they have appropriate lifetimes.
FMT_CONSTEXPR context(iterator out, format_args args, locale_ref loc = {}) FMT_CONSTEXPR context(iterator out, format_args args,
detail::locale_ref loc = {})
: out_(out), args_(args), loc_(loc) {} : out_(out), args_(args), loc_(loc) {}
context(context&&) = default; context(context&&) = default;
context(const context&) = delete; context(const context&) = delete;
@ -2715,7 +2692,7 @@ class context {
// Advances the begin iterator to `it`. // Advances the begin iterator to `it`.
FMT_CONSTEXPR void advance_to(iterator) {} FMT_CONSTEXPR void advance_to(iterator) {}
FMT_CONSTEXPR auto locale() const -> locale_ref { return loc_; } FMT_CONSTEXPR auto locale() const -> detail::locale_ref { return loc_; }
}; };
template <typename Char = char> struct runtime_format_string { template <typename Char = char> struct runtime_format_string {
@ -2802,6 +2779,9 @@ template <typename T, typename Char = char>
concept formattable = is_formattable<remove_reference_t<T>, Char>::value; concept formattable = is_formattable<remove_reference_t<T>, Char>::value;
#endif #endif
template <typename T, typename Char>
using has_formatter FMT_DEPRECATED = std::is_constructible<formatter<T, Char>>;
// A formatter specialization for natively supported types. // A formatter specialization for natively supported types.
template <typename T, typename Char> template <typename T, typename Char>
struct formatter<T, Char, struct formatter<T, Char,
@ -2998,10 +2978,9 @@ FMT_INLINE void println(format_string<T...> fmt, T&&... args) {
return fmt::println(stdout, fmt, static_cast<T&&>(args)...); return fmt::println(stdout, fmt, static_cast<T&&>(args)...);
} }
FMT_PRAGMA_GCC(diagnostic pop) FMT_END_EXPORT
FMT_PRAGMA_CLANG(diagnostic pop) FMT_PRAGMA_CLANG(diagnostic pop)
FMT_PRAGMA_GCC(pop_options) FMT_PRAGMA_GCC(pop_options)
FMT_END_EXPORT
FMT_END_NAMESPACE FMT_END_NAMESPACE
#ifdef FMT_HEADER_ONLY #ifdef FMT_HEADER_ONLY

View file

@ -38,7 +38,6 @@ FMT_BEGIN_NAMESPACE
// Copyright Paul Dreik 2019 // Copyright Paul Dreik 2019
namespace safe_duration_cast { namespace safe_duration_cast {
// DEPRECATED!
template <typename To, typename From, template <typename To, typename From,
FMT_ENABLE_IF(!std::is_same<From, To>::value && FMT_ENABLE_IF(!std::is_same<From, To>::value &&
std::numeric_limits<From>::is_signed == std::numeric_limits<From>::is_signed ==
@ -162,6 +161,17 @@ auto safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from,
int& ec) -> To { int& ec) -> To {
using From = std::chrono::duration<FromRep, FromPeriod>; using From = std::chrono::duration<FromRep, FromPeriod>;
ec = 0; ec = 0;
if (std::isnan(from.count())) {
// nan in, gives nan out. easy.
return To{std::numeric_limits<typename To::rep>::quiet_NaN()};
}
// maybe we should also check if from is denormal, and decide what to do about
// it.
// +-inf should be preserved.
if (std::isinf(from.count())) {
return To{from.count()};
}
// the basic idea is that we need to convert from count() in the from type // the basic idea is that we need to convert from count() in the from type
// to count() in the To type, by multiplying it with this: // to count() in the To type, by multiplying it with this:
@ -272,6 +282,8 @@ namespace detail {
#define FMT_NOMACRO #define FMT_NOMACRO
template <typename T = void> struct null {}; template <typename T = void> struct null {};
inline auto localtime_r FMT_NOMACRO(...) -> null<> { return null<>(); }
inline auto localtime_s(...) -> null<> { return null<>(); }
inline auto gmtime_r(...) -> null<> { return null<>(); } inline auto gmtime_r(...) -> null<> { return null<>(); }
inline auto gmtime_s(...) -> null<> { return null<>(); } inline auto gmtime_s(...) -> null<> { return null<>(); }
@ -314,7 +326,7 @@ inline auto get_classic_locale() -> const std::locale& {
} }
template <typename CodeUnit> struct codecvt_result { template <typename CodeUnit> struct codecvt_result {
static constexpr size_t max_size = 32; static constexpr const size_t max_size = 32;
CodeUnit buf[max_size]; CodeUnit buf[max_size];
CodeUnit* end; CodeUnit* end;
}; };
@ -431,7 +443,11 @@ auto duration_cast(std::chrono::duration<FromRep, FromPeriod> from) -> To {
using common_rep = typename std::common_type<FromRep, typename To::rep, using common_rep = typename std::common_type<FromRep, typename To::rep,
decltype(factor::num)>::type; decltype(factor::num)>::type;
common_rep count = from.count(); // This conversion is lossless.
int ec = 0;
auto count = safe_duration_cast::lossless_integral_conversion<common_rep>(
from.count(), ec);
if (ec) throw_duration_error();
// Multiply from.count() by factor and check for overflow. // Multiply from.count() by factor and check for overflow.
if (const_check(factor::num != 1)) { if (const_check(factor::num != 1)) {
@ -442,7 +458,6 @@ auto duration_cast(std::chrono::duration<FromRep, FromPeriod> from) -> To {
count *= factor::num; count *= factor::num;
} }
if (const_check(factor::den != 1)) count /= factor::den; if (const_check(factor::den != 1)) count /= factor::den;
int ec = 0;
auto to = auto to =
To(safe_duration_cast::lossless_integral_conversion<typename To::rep>( To(safe_duration_cast::lossless_integral_conversion<typename To::rep>(
count, ec)); count, ec));
@ -456,8 +471,6 @@ template <typename To, typename FromRep, typename FromPeriod,
std::is_floating_point<typename To::rep>::value)> std::is_floating_point<typename To::rep>::value)>
auto duration_cast(std::chrono::duration<FromRep, FromPeriod> from) -> To { auto duration_cast(std::chrono::duration<FromRep, FromPeriod> from) -> To {
#if FMT_SAFE_DURATION_CAST #if FMT_SAFE_DURATION_CAST
// Preserve infinity and NaN.
if (!isfinite(from.count())) return static_cast<To>(from.count());
// Throwing version of safe_duration_cast is only available for // Throwing version of safe_duration_cast is only available for
// integer to integer or float to float casts. // integer to integer or float to float casts.
int ec; int ec;
@ -474,7 +487,7 @@ template <typename To, typename FromRep, typename FromPeriod,
FMT_ENABLE_IF( FMT_ENABLE_IF(
!is_similar_arithmetic_type<FromRep, typename To::rep>::value)> !is_similar_arithmetic_type<FromRep, typename To::rep>::value)>
auto duration_cast(std::chrono::duration<FromRep, FromPeriod> from) -> To { auto duration_cast(std::chrono::duration<FromRep, FromPeriod> from) -> To {
// Mixed integer <-> float cast is not supported by safe duration_cast. // Mixed integer <-> float cast is not supported by safe_duration_cast.
return std::chrono::duration_cast<To>(from); return std::chrono::duration_cast<To>(from);
} }
@ -488,10 +501,86 @@ auto to_time_t(sys_time<Duration> time_point) -> std::time_t {
.count(); .count();
} }
namespace tz {
// DEPRECATED!
struct time_zone {
template <typename Duration, typename LocalTime>
auto to_sys(LocalTime) -> sys_time<Duration> {
return {};
}
};
template <typename... T> auto current_zone(T...) -> time_zone* {
return nullptr;
}
template <typename... T> void _tzset(T...) {}
} // namespace tz
// DEPRECATED!
inline void tzset_once() {
static bool init = []() {
using namespace tz;
_tzset();
return false;
}();
ignore_unused(init);
}
} // namespace detail } // namespace detail
FMT_BEGIN_EXPORT FMT_BEGIN_EXPORT
/**
* Converts given time since epoch as `std::time_t` value into calendar time,
* expressed in local time. Unlike `std::localtime`, this function is
* thread-safe on most platforms.
*/
FMT_DEPRECATED inline auto localtime(std::time_t time) -> std::tm {
struct dispatcher {
std::time_t time_;
std::tm tm_;
inline dispatcher(std::time_t t) : time_(t) {}
inline auto run() -> bool {
using namespace fmt::detail;
return handle(localtime_r(&time_, &tm_));
}
inline auto handle(std::tm* tm) -> bool { return tm != nullptr; }
inline auto handle(detail::null<>) -> bool {
using namespace fmt::detail;
return fallback(localtime_s(&tm_, &time_));
}
inline auto fallback(int res) -> bool { return res == 0; }
#if !FMT_MSC_VERSION
inline auto fallback(detail::null<>) -> bool {
using namespace fmt::detail;
std::tm* tm = std::localtime(&time_);
if (tm) tm_ = *tm;
return tm != nullptr;
}
#endif
};
dispatcher lt(time);
// Too big time values may be unsupported.
if (!lt.run()) FMT_THROW(format_error("time_t value out of range"));
return lt.tm_;
}
#if FMT_USE_LOCAL_TIME
template <typename Duration>
FMT_DEPRECATED auto localtime(std::chrono::local_time<Duration> time)
-> std::tm {
using namespace std::chrono;
using namespace detail::tz;
return localtime(detail::to_time_t(current_zone()->to_sys<Duration>(time)));
}
#endif
/** /**
* Converts given time since epoch as `std::time_t` value into calendar time, * Converts given time since epoch as `std::time_t` value into calendar time,
* expressed in Coordinated Universal Time (UTC). Unlike `std::gmtime`, this * expressed in Coordinated Universal Time (UTC). Unlike `std::gmtime`, this
@ -563,7 +652,7 @@ inline void write_digit2_separated(char* buf, unsigned a, unsigned b,
// Add ASCII '0' to each digit byte and insert separators. // Add ASCII '0' to each digit byte and insert separators.
digits |= 0x3030003030003030 | (usep << 16) | (usep << 40); digits |= 0x3030003030003030 | (usep << 16) | (usep << 40);
constexpr size_t len = 8; constexpr const size_t len = 8;
if (const_check(is_big_endian())) { if (const_check(is_big_endian())) {
char tmp[len]; char tmp[len];
std::memcpy(tmp, &digits, len); std::memcpy(tmp, &digits, len);
@ -911,16 +1000,16 @@ template <typename T>
struct has_tm_zone<T, void_t<decltype(T::tm_zone)>> : std::true_type {}; struct has_tm_zone<T, void_t<decltype(T::tm_zone)>> : std::true_type {};
template <typename T, FMT_ENABLE_IF(has_tm_zone<T>::value)> template <typename T, FMT_ENABLE_IF(has_tm_zone<T>::value)>
auto set_tm_zone(T& time, char* tz) -> bool { bool set_tm_zone(T& time, char* tz) {
time.tm_zone = tz; time.tm_zone = tz;
return true; return true;
} }
template <typename T, FMT_ENABLE_IF(!has_tm_zone<T>::value)> template <typename T, FMT_ENABLE_IF(!has_tm_zone<T>::value)>
auto set_tm_zone(T&, char*) -> bool { bool set_tm_zone(T&, char*) {
return false; return false;
} }
inline auto utc() -> char* { inline char* utc() {
static char tz[] = "UTC"; static char tz[] = "UTC";
return tz; return tz;
} }
@ -1594,13 +1683,8 @@ class get_locale {
public: public:
inline get_locale(bool localized, locale_ref loc) : has_locale_(localized) { inline get_locale(bool localized, locale_ref loc) : has_locale_(localized) {
if (!localized) return; if (localized)
ignore_unused(loc); ::new (&locale_) std::locale(loc.template get<std::locale>());
::new (&locale_) std::locale(
#if FMT_USE_LOCALE
loc.template get<std::locale>()
#endif
);
} }
inline ~get_locale() { inline ~get_locale() {
if (has_locale_) locale_.~locale(); if (has_locale_) locale_.~locale();
@ -2146,7 +2230,7 @@ template <typename Char> struct formatter<std::tm, Char> {
detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, width_ref_, detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, width_ref_,
ctx); ctx);
auto loc_ref = specs.localized() ? ctx.locale() : locale_ref(); auto loc_ref = specs.localized() ? ctx.locale() : detail::locale_ref();
detail::get_locale loc(static_cast<bool>(loc_ref), loc_ref); detail::get_locale loc(static_cast<bool>(loc_ref), loc_ref);
auto w = detail::tm_writer<basic_appender<Char>, Char, Duration>( auto w = detail::tm_writer<basic_appender<Char>, Char, Duration>(
loc, out, tm, subsecs); loc, out, tm, subsecs);

View file

@ -375,17 +375,19 @@ template <typename Char> struct ansi_color_escape {
// 10 more. // 10 more.
if (is_background) value += 10u; if (is_background) value += 10u;
buffer[size++] = static_cast<Char>('\x1b'); size_t index = 0;
buffer[size++] = static_cast<Char>('['); buffer[index++] = static_cast<Char>('\x1b');
buffer[index++] = static_cast<Char>('[');
if (value >= 100u) { if (value >= 100u) {
buffer[size++] = static_cast<Char>('1'); buffer[index++] = static_cast<Char>('1');
value %= 100u; value %= 100u;
} }
buffer[size++] = static_cast<Char>('0' + value / 10u); buffer[index++] = static_cast<Char>('0' + value / 10u);
buffer[size++] = static_cast<Char>('0' + value % 10u); buffer[index++] = static_cast<Char>('0' + value % 10u);
buffer[size++] = static_cast<Char>('m'); buffer[index++] = static_cast<Char>('m');
buffer[index++] = static_cast<Char>('\0');
return; return;
} }
@ -396,7 +398,7 @@ template <typename Char> struct ansi_color_escape {
to_esc(color.r, buffer + 7, ';'); to_esc(color.r, buffer + 7, ';');
to_esc(color.g, buffer + 11, ';'); to_esc(color.g, buffer + 11, ';');
to_esc(color.b, buffer + 15, 'm'); to_esc(color.b, buffer + 15, 'm');
size = 19; buffer[19] = static_cast<Char>(0);
} }
FMT_CONSTEXPR ansi_color_escape(emphasis em) noexcept { FMT_CONSTEXPR ansi_color_escape(emphasis em) noexcept {
uint8_t em_codes[num_emphases] = {}; uint8_t em_codes[num_emphases] = {};
@ -409,28 +411,26 @@ template <typename Char> struct ansi_color_escape {
if (has_emphasis(em, emphasis::conceal)) em_codes[6] = 8; if (has_emphasis(em, emphasis::conceal)) em_codes[6] = 8;
if (has_emphasis(em, emphasis::strikethrough)) em_codes[7] = 9; if (has_emphasis(em, emphasis::strikethrough)) em_codes[7] = 9;
buffer[size++] = static_cast<Char>('\x1b'); size_t index = 0;
buffer[size++] = static_cast<Char>('[');
for (size_t i = 0; i < num_emphases; ++i) { for (size_t i = 0; i < num_emphases; ++i) {
if (!em_codes[i]) continue; if (!em_codes[i]) continue;
buffer[size++] = static_cast<Char>('0' + em_codes[i]); buffer[index++] = static_cast<Char>('\x1b');
buffer[size++] = static_cast<Char>(';'); buffer[index++] = static_cast<Char>('[');
buffer[index++] = static_cast<Char>('0' + em_codes[i]);
buffer[index++] = static_cast<Char>('m');
} }
buffer[index++] = static_cast<Char>(0);
buffer[size - 1] = static_cast<Char>('m');
} }
FMT_CONSTEXPR operator const Char*() const noexcept { return buffer; } FMT_CONSTEXPR operator const Char*() const noexcept { return buffer; }
FMT_CONSTEXPR auto begin() const noexcept -> const Char* { return buffer; } FMT_CONSTEXPR auto begin() const noexcept -> const Char* { return buffer; }
FMT_CONSTEXPR auto end() const noexcept -> const Char* { FMT_CONSTEXPR20 auto end() const noexcept -> const Char* {
return buffer + size; return buffer + basic_string_view<Char>(buffer).size();
} }
private: private:
static constexpr size_t num_emphases = 8; static constexpr size_t num_emphases = 8;
Char buffer[7u + 4u * num_emphases] = {}; Char buffer[7u + 3u * num_emphases + 1u];
size_t size = 0;
static FMT_CONSTEXPR void to_esc(uint8_t c, Char* out, static FMT_CONSTEXPR void to_esc(uint8_t c, Char* out,
char delimiter) noexcept { char delimiter) noexcept {

View file

@ -15,14 +15,15 @@
#include "format.h" #include "format.h"
FMT_BEGIN_NAMESPACE FMT_BEGIN_NAMESPACE
FMT_BEGIN_EXPORT
// A compile-time string which is compiled into fast formatting code. // A compile-time string which is compiled into fast formatting code.
class compiled_string {}; FMT_EXPORT class compiled_string {};
template <typename S> template <typename S>
struct is_compiled_string : std::is_base_of<compiled_string, S> {}; struct is_compiled_string : std::is_base_of<compiled_string, S> {};
namespace detail {
/** /**
* Converts a string literal `s` into a format string that will be parsed at * Converts a string literal `s` into a format string that will be parsed at
* compile time and converted into efficient formatting code. Requires C++17 * compile time and converted into efficient formatting code. Requires C++17
@ -40,42 +41,18 @@ struct is_compiled_string : std::is_base_of<compiled_string, S> {};
# define FMT_COMPILE(s) FMT_STRING(s) # define FMT_COMPILE(s) FMT_STRING(s)
#endif #endif
/**
* Converts a string literal into a format string that will be parsed at
* compile time and converted into efficient formatting code. Requires support
* for class types in constant template parameters (a C++20 feature).
*
* **Example**:
*
* // Converts 42 into std::string using the most efficient method and no
* // runtime format string processing.
* using namespace fmt::literals;
* std::string s = fmt::format("{}"_cf, 42);
*/
#if FMT_USE_NONTYPE_TEMPLATE_ARGS
inline namespace literals {
template <detail::fixed_string Str> constexpr auto operator""_cf() {
return FMT_COMPILE(Str.data);
}
} // namespace literals
#endif
FMT_END_EXPORT
namespace detail {
template <typename T, typename... Tail> template <typename T, typename... Tail>
constexpr auto first(const T& value, const Tail&...) -> const T& { auto first(const T& value, const Tail&...) -> const T& {
return value; return value;
} }
#if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction) #if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)
template <typename... T> struct type_list {}; template <typename... Args> struct type_list {};
// Returns a reference to the argument at index N from [first, rest...]. // Returns a reference to the argument at index N from [first, rest...].
template <int N, typename T, typename... Args> template <int N, typename T, typename... Args>
constexpr auto get([[maybe_unused]] const T& first, constexpr const auto& get([[maybe_unused]] const T& first,
[[maybe_unused]] const Args&... rest) -> const auto& { [[maybe_unused]] const Args&... rest) {
static_assert(N < 1 + sizeof...(Args), "index is out of bounds"); static_assert(N < 1 + sizeof...(Args), "index is out of bounds");
if constexpr (N == 0) if constexpr (N == 0)
return first; return first;
@ -107,8 +84,8 @@ FMT_CONSTEXPR auto get_arg_index_by_name(basic_string_view<Char> name) -> int {
} }
template <typename Char, typename... Args> template <typename Char, typename... Args>
constexpr auto get_arg_index_by_name(basic_string_view<Char> name, constexpr int get_arg_index_by_name(basic_string_view<Char> name,
type_list<Args...>) -> int { type_list<Args...>) {
return get_arg_index_by_name<Args...>(name); return get_arg_index_by_name<Args...>(name);
} }
@ -128,8 +105,8 @@ template <typename Char> struct text {
basic_string_view<Char> data; basic_string_view<Char> data;
using char_type = Char; using char_type = Char;
template <typename OutputIt, typename... T> template <typename OutputIt, typename... Args>
constexpr auto format(OutputIt out, const T&...) const -> OutputIt { constexpr OutputIt format(OutputIt out, const Args&...) const {
return write<Char>(out, data); return write<Char>(out, data);
} }
}; };
@ -138,8 +115,8 @@ template <typename Char>
struct is_compiled_format<text<Char>> : std::true_type {}; struct is_compiled_format<text<Char>> : std::true_type {};
template <typename Char> template <typename Char>
constexpr auto make_text(basic_string_view<Char> s, size_t pos, size_t size) constexpr text<Char> make_text(basic_string_view<Char> s, size_t pos,
-> text<Char> { size_t size) {
return {{&s[pos], size}}; return {{&s[pos], size}};
} }
@ -147,8 +124,8 @@ template <typename Char> struct code_unit {
Char value; Char value;
using char_type = Char; using char_type = Char;
template <typename OutputIt, typename... T> template <typename OutputIt, typename... Args>
constexpr auto format(OutputIt out, const T&...) const -> OutputIt { constexpr OutputIt format(OutputIt out, const Args&...) const {
*out++ = value; *out++ = value;
return out; return out;
} }
@ -156,7 +133,7 @@ template <typename Char> struct code_unit {
// This ensures that the argument type is convertible to `const T&`. // This ensures that the argument type is convertible to `const T&`.
template <typename T, int N, typename... Args> template <typename T, int N, typename... Args>
constexpr auto get_arg_checked(const Args&... args) -> const T& { constexpr const T& get_arg_checked(const Args&... args) {
const auto& arg = detail::get<N>(args...); const auto& arg = detail::get<N>(args...);
if constexpr (detail::is_named_arg<remove_cvref_t<decltype(arg)>>()) { if constexpr (detail::is_named_arg<remove_cvref_t<decltype(arg)>>()) {
return arg.value; return arg.value;
@ -169,13 +146,13 @@ template <typename Char>
struct is_compiled_format<code_unit<Char>> : std::true_type {}; struct is_compiled_format<code_unit<Char>> : std::true_type {};
// A replacement field that refers to argument N. // A replacement field that refers to argument N.
template <typename Char, typename V, int N> struct field { template <typename Char, typename T, int N> struct field {
using char_type = Char; using char_type = Char;
template <typename OutputIt, typename... T> template <typename OutputIt, typename... Args>
constexpr auto format(OutputIt out, const T&... args) const -> OutputIt { constexpr OutputIt format(OutputIt out, const Args&... args) const {
const V& arg = get_arg_checked<V, N>(args...); const T& arg = get_arg_checked<T, N>(args...);
if constexpr (std::is_convertible<V, basic_string_view<Char>>::value) { if constexpr (std::is_convertible<T, basic_string_view<Char>>::value) {
auto s = basic_string_view<Char>(arg); auto s = basic_string_view<Char>(arg);
return copy<Char>(s.begin(), s.end(), out); return copy<Char>(s.begin(), s.end(), out);
} else { } else {
@ -193,10 +170,10 @@ template <typename Char> struct runtime_named_field {
basic_string_view<Char> name; basic_string_view<Char> name;
template <typename OutputIt, typename T> template <typename OutputIt, typename T>
constexpr static auto try_format_argument( constexpr static bool try_format_argument(
OutputIt& out, OutputIt& out,
// [[maybe_unused]] due to unused-but-set-parameter warning in GCC 7,8,9 // [[maybe_unused]] due to unused-but-set-parameter warning in GCC 7,8,9
[[maybe_unused]] basic_string_view<Char> arg_name, const T& arg) -> bool { [[maybe_unused]] basic_string_view<Char> arg_name, const T& arg) {
if constexpr (is_named_arg<typename std::remove_cv<T>::type>::value) { if constexpr (is_named_arg<typename std::remove_cv<T>::type>::value) {
if (arg_name == arg.name) { if (arg_name == arg.name) {
out = write<Char>(out, arg.value); out = write<Char>(out, arg.value);
@ -206,8 +183,8 @@ template <typename Char> struct runtime_named_field {
return false; return false;
} }
template <typename OutputIt, typename... T> template <typename OutputIt, typename... Args>
constexpr auto format(OutputIt out, const T&... args) const -> OutputIt { constexpr OutputIt format(OutputIt out, const Args&... args) const {
bool found = (try_format_argument(out, name, args) || ...); bool found = (try_format_argument(out, name, args) || ...);
if (!found) { if (!found) {
FMT_THROW(format_error("argument with specified name is not found")); FMT_THROW(format_error("argument with specified name is not found"));
@ -220,17 +197,17 @@ template <typename Char>
struct is_compiled_format<runtime_named_field<Char>> : std::true_type {}; struct is_compiled_format<runtime_named_field<Char>> : std::true_type {};
// A replacement field that refers to argument N and has format specifiers. // A replacement field that refers to argument N and has format specifiers.
template <typename Char, typename V, int N> struct spec_field { template <typename Char, typename T, int N> struct spec_field {
using char_type = Char; using char_type = Char;
formatter<V, Char> fmt; formatter<T, Char> fmt;
template <typename OutputIt, typename... T> template <typename OutputIt, typename... Args>
constexpr FMT_INLINE auto format(OutputIt out, const T&... args) const constexpr FMT_INLINE OutputIt format(OutputIt out,
-> OutputIt { const Args&... args) const {
const auto& vargs = const auto& vargs =
fmt::make_format_args<basic_format_context<OutputIt, Char>>(args...); fmt::make_format_args<basic_format_context<OutputIt, Char>>(args...);
basic_format_context<OutputIt, Char> ctx(out, vargs); basic_format_context<OutputIt, Char> ctx(out, vargs);
return fmt.format(get_arg_checked<V, N>(args...), ctx); return fmt.format(get_arg_checked<T, N>(args...), ctx);
} }
}; };
@ -242,8 +219,8 @@ template <typename L, typename R> struct concat {
R rhs; R rhs;
using char_type = typename L::char_type; using char_type = typename L::char_type;
template <typename OutputIt, typename... T> template <typename OutputIt, typename... Args>
constexpr auto format(OutputIt out, const T&... args) const -> OutputIt { constexpr OutputIt format(OutputIt out, const Args&... args) const {
out = lhs.format(out, args...); out = lhs.format(out, args...);
return rhs.format(out, args...); return rhs.format(out, args...);
} }
@ -253,14 +230,14 @@ template <typename L, typename R>
struct is_compiled_format<concat<L, R>> : std::true_type {}; struct is_compiled_format<concat<L, R>> : std::true_type {};
template <typename L, typename R> template <typename L, typename R>
constexpr auto make_concat(L lhs, R rhs) -> concat<L, R> { constexpr concat<L, R> make_concat(L lhs, R rhs) {
return {lhs, rhs}; return {lhs, rhs};
} }
struct unknown_format {}; struct unknown_format {};
template <typename Char> template <typename Char>
constexpr auto parse_text(basic_string_view<Char> str, size_t pos) -> size_t { constexpr size_t parse_text(basic_string_view<Char> str, size_t pos) {
for (size_t size = str.size(); pos != size; ++pos) { for (size_t size = str.size(); pos != size; ++pos) {
if (str[pos] == '{' || str[pos] == '}') break; if (str[pos] == '{' || str[pos] == '}') break;
} }
@ -293,8 +270,8 @@ template <typename T, typename Char> struct parse_specs_result {
enum { manual_indexing_id = -1 }; enum { manual_indexing_id = -1 };
template <typename T, typename Char> template <typename T, typename Char>
constexpr auto parse_specs(basic_string_view<Char> str, size_t pos, constexpr parse_specs_result<T, Char> parse_specs(basic_string_view<Char> str,
int next_arg_id) -> parse_specs_result<T, Char> { size_t pos, int next_arg_id) {
str.remove_prefix(pos); str.remove_prefix(pos);
auto ctx = auto ctx =
compile_parse_context<Char>(str, max_value<int>(), nullptr, next_arg_id); compile_parse_context<Char>(str, max_value<int>(), nullptr, next_arg_id);
@ -308,16 +285,16 @@ template <typename Char> struct arg_id_handler {
arg_id_kind kind; arg_id_kind kind;
arg_ref<Char> arg_id; arg_ref<Char> arg_id;
constexpr auto on_auto() -> int { constexpr int on_auto() {
FMT_ASSERT(false, "handler cannot be used with automatic indexing"); FMT_ASSERT(false, "handler cannot be used with automatic indexing");
return 0; return 0;
} }
constexpr auto on_index(int id) -> int { constexpr int on_index(int id) {
kind = arg_id_kind::index; kind = arg_id_kind::index;
arg_id = arg_ref<Char>(id); arg_id = arg_ref<Char>(id);
return 0; return 0;
} }
constexpr auto on_name(basic_string_view<Char> id) -> int { constexpr int on_name(basic_string_view<Char> id) {
kind = arg_id_kind::name; kind = arg_id_kind::name;
arg_id = arg_ref<Char>(id); arg_id = arg_ref<Char>(id);
return 0; return 0;
@ -456,28 +433,27 @@ FMT_BEGIN_EXPORT
#if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction) #if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)
template <typename CompiledFormat, typename... T, template <typename CompiledFormat, typename... Args,
typename Char = typename CompiledFormat::char_type, typename Char = typename CompiledFormat::char_type,
FMT_ENABLE_IF(detail::is_compiled_format<CompiledFormat>::value)> FMT_ENABLE_IF(detail::is_compiled_format<CompiledFormat>::value)>
FMT_INLINE FMT_CONSTEXPR_STRING auto format(const CompiledFormat& cf, FMT_INLINE std::basic_string<Char> format(const CompiledFormat& cf,
const T&... args) const Args&... args) {
-> std::basic_string<Char> {
auto s = std::basic_string<Char>(); auto s = std::basic_string<Char>();
cf.format(std::back_inserter(s), args...); cf.format(std::back_inserter(s), args...);
return s; return s;
} }
template <typename OutputIt, typename CompiledFormat, typename... T, template <typename OutputIt, typename CompiledFormat, typename... Args,
FMT_ENABLE_IF(detail::is_compiled_format<CompiledFormat>::value)> FMT_ENABLE_IF(detail::is_compiled_format<CompiledFormat>::value)>
constexpr FMT_INLINE auto format_to(OutputIt out, const CompiledFormat& cf, constexpr FMT_INLINE OutputIt format_to(OutputIt out, const CompiledFormat& cf,
const T&... args) -> OutputIt { const Args&... args) {
return cf.format(out, args...); return cf.format(out, args...);
} }
template <typename S, typename... T, template <typename S, typename... Args,
FMT_ENABLE_IF(is_compiled_string<S>::value)> FMT_ENABLE_IF(is_compiled_string<S>::value)>
FMT_INLINE FMT_CONSTEXPR_STRING auto format(const S&, T&&... args) FMT_INLINE std::basic_string<typename S::char_type> format(const S&,
-> std::basic_string<typename S::char_type> { Args&&... args) {
if constexpr (std::is_same<typename S::char_type, char>::value) { if constexpr (std::is_same<typename S::char_type, char>::value) {
constexpr auto str = basic_string_view<typename S::char_type>(S()); constexpr auto str = basic_string_view<typename S::char_type>(S());
if constexpr (str.size() == 2 && str[0] == '{' && str[1] == '}') { if constexpr (str.size() == 2 && str[0] == '{' && str[1] == '}') {
@ -490,97 +466,72 @@ FMT_INLINE FMT_CONSTEXPR_STRING auto format(const S&, T&&... args)
} }
} }
} }
constexpr auto compiled = detail::compile<T...>(S()); constexpr auto compiled = detail::compile<Args...>(S());
if constexpr (std::is_same<remove_cvref_t<decltype(compiled)>, if constexpr (std::is_same<remove_cvref_t<decltype(compiled)>,
detail::unknown_format>()) { detail::unknown_format>()) {
return fmt::format( return fmt::format(
static_cast<basic_string_view<typename S::char_type>>(S()), static_cast<basic_string_view<typename S::char_type>>(S()),
std::forward<T>(args)...); std::forward<Args>(args)...);
} else { } else {
return fmt::format(compiled, std::forward<T>(args)...); return fmt::format(compiled, std::forward<Args>(args)...);
} }
} }
template <typename OutputIt, typename S, typename... T, template <typename OutputIt, typename S, typename... Args,
FMT_ENABLE_IF(is_compiled_string<S>::value)> FMT_ENABLE_IF(is_compiled_string<S>::value)>
FMT_CONSTEXPR auto format_to(OutputIt out, const S&, T&&... args) -> OutputIt { FMT_CONSTEXPR OutputIt format_to(OutputIt out, const S&, Args&&... args) {
constexpr auto compiled = detail::compile<T...>(S()); constexpr auto compiled = detail::compile<Args...>(S());
if constexpr (std::is_same<remove_cvref_t<decltype(compiled)>, if constexpr (std::is_same<remove_cvref_t<decltype(compiled)>,
detail::unknown_format>()) { detail::unknown_format>()) {
return fmt::format_to( return fmt::format_to(
out, static_cast<basic_string_view<typename S::char_type>>(S()), out, static_cast<basic_string_view<typename S::char_type>>(S()),
std::forward<T>(args)...); std::forward<Args>(args)...);
} else { } else {
return fmt::format_to(out, compiled, std::forward<T>(args)...); return fmt::format_to(out, compiled, std::forward<Args>(args)...);
} }
} }
#endif #endif
template <typename OutputIt, typename S, typename... T, template <typename OutputIt, typename S, typename... Args,
FMT_ENABLE_IF(is_compiled_string<S>::value)> FMT_ENABLE_IF(is_compiled_string<S>::value)>
auto format_to_n(OutputIt out, size_t n, const S& fmt, T&&... args) auto format_to_n(OutputIt out, size_t n, const S& fmt, Args&&... args)
-> format_to_n_result<OutputIt> { -> format_to_n_result<OutputIt> {
using traits = detail::fixed_buffer_traits; using traits = detail::fixed_buffer_traits;
auto buf = detail::iterator_buffer<OutputIt, char, traits>(out, n); auto buf = detail::iterator_buffer<OutputIt, char, traits>(out, n);
fmt::format_to(std::back_inserter(buf), fmt, std::forward<T>(args)...); fmt::format_to(std::back_inserter(buf), fmt, std::forward<Args>(args)...);
return {buf.out(), buf.count()}; return {buf.out(), buf.count()};
} }
template <typename S, typename... T, template <typename S, typename... Args,
FMT_ENABLE_IF(is_compiled_string<S>::value)> FMT_ENABLE_IF(is_compiled_string<S>::value)>
FMT_CONSTEXPR20 auto formatted_size(const S& fmt, T&&... args) -> size_t { FMT_CONSTEXPR20 auto formatted_size(const S& fmt, const Args&... args)
-> size_t {
auto buf = detail::counting_buffer<>(); auto buf = detail::counting_buffer<>();
fmt::format_to(appender(buf), fmt, std::forward<T>(args)...); fmt::format_to(appender(buf), fmt, args...);
return buf.count(); return buf.count();
} }
template <typename S, typename... T, template <typename S, typename... Args,
FMT_ENABLE_IF(is_compiled_string<S>::value)> FMT_ENABLE_IF(is_compiled_string<S>::value)>
void print(std::FILE* f, const S& fmt, T&&... args) { void print(std::FILE* f, const S& fmt, const Args&... args) {
auto buf = memory_buffer(); auto buf = memory_buffer();
fmt::format_to(appender(buf), fmt, std::forward<T>(args)...); fmt::format_to(appender(buf), fmt, args...);
detail::print(f, {buf.data(), buf.size()}); detail::print(f, {buf.data(), buf.size()});
} }
template <typename S, typename... T, template <typename S, typename... Args,
FMT_ENABLE_IF(is_compiled_string<S>::value)> FMT_ENABLE_IF(is_compiled_string<S>::value)>
void print(const S& fmt, T&&... args) { void print(const S& fmt, const Args&... args) {
print(stdout, fmt, std::forward<T>(args)...); print(stdout, fmt, args...);
} }
template <size_t N> class static_format_result { #if FMT_USE_NONTYPE_TEMPLATE_ARGS
private: inline namespace literals {
char data[N]; template <detail::fixed_string Str> constexpr auto operator""_cf() {
return FMT_COMPILE(Str.data);
public:
template <typename S, typename... T,
FMT_ENABLE_IF(is_compiled_string<S>::value)>
explicit FMT_CONSTEXPR static_format_result(const S& fmt, T&&... args) {
*fmt::format_to(data, fmt, std::forward<T>(args)...) = '\0';
} }
} // namespace literals
auto str() const -> fmt::string_view { return {data, N - 1}; } #endif
auto c_str() const -> const char* { return data; }
};
/**
* Formats arguments according to the format string `fmt_str` and produces
* a string of the exact required size at compile time. Both the format string
* and the arguments must be compile-time expressions.
*
* The resulting string can be accessed as a C string via `c_str()` or as
* a `fmt::string_view` via `str()`.
*
* **Example**:
*
* // Produces the static string "42" at compile time.
* static constexpr auto result = FMT_STATIC_FORMAT("{}", 42);
* const char* s = result.c_str();
*/
#define FMT_STATIC_FORMAT(fmt_str, ...) \
fmt::static_format_result< \
fmt::formatted_size(FMT_COMPILE(fmt_str), __VA_ARGS__) + 1>( \
FMT_COMPILE(fmt_str), __VA_ARGS__)
FMT_END_EXPORT FMT_END_EXPORT
FMT_END_NAMESPACE FMT_END_NAMESPACE

View file

@ -22,7 +22,7 @@
#include "format.h" #include "format.h"
#if FMT_USE_LOCALE && !defined(FMT_MODULE) #if FMT_USE_LOCALE
# include <locale> # include <locale>
#endif #endif
@ -31,44 +31,14 @@
#endif #endif
FMT_BEGIN_NAMESPACE FMT_BEGIN_NAMESPACE
namespace detail {
#ifndef FMT_CUSTOM_ASSERT_FAIL
FMT_FUNC void assert_fail(const char* file, int line, const char* message) { FMT_FUNC void assert_fail(const char* file, int line, const char* message) {
// Use unchecked std::fprintf to avoid triggering another assertion when // Use unchecked std::fprintf to avoid triggering another assertion when
// writing to stderr fails. // writing to stderr fails.
std::fprintf(stderr, "%s:%d: assertion failed: %s", file, line, message); fprintf(stderr, "%s:%d: assertion failed: %s", file, line, message);
abort(); abort();
} }
#endif
#if FMT_USE_LOCALE
namespace detail {
using std::locale;
using std::numpunct;
using std::use_facet;
} // namespace detail
#else
namespace detail {
struct locale {};
template <typename Char> struct numpunct {
auto grouping() const -> std::string { return "\03"; }
auto thousands_sep() const -> Char { return ','; }
auto decimal_point() const -> Char { return '.'; }
};
template <typename Facet> Facet use_facet(locale) { return {}; }
} // namespace detail
#endif // FMT_USE_LOCALE
template <typename Locale> auto locale_ref::get() const -> Locale {
using namespace detail;
static_assert(std::is_same<Locale, locale>::value, "");
#if FMT_USE_LOCALE
if (locale_) return *static_cast<const locale*>(locale_);
#endif
return locale();
}
namespace detail {
FMT_FUNC void format_error_code(detail::buffer<char>& out, int error_code, FMT_FUNC void format_error_code(detail::buffer<char>& out, int error_code,
string_view message) noexcept { string_view message) noexcept {
@ -109,6 +79,33 @@ inline void fwrite_all(const void* ptr, size_t count, FILE* stream) {
FMT_THROW(system_error(errno, FMT_STRING("cannot write to file"))); FMT_THROW(system_error(errno, FMT_STRING("cannot write to file")));
} }
#if FMT_USE_LOCALE
using std::locale;
using std::numpunct;
using std::use_facet;
template <typename Locale>
locale_ref::locale_ref(const Locale& loc) : locale_(&loc) {
static_assert(std::is_same<Locale, locale>::value, "");
}
#else
struct locale {};
template <typename Char> struct numpunct {
auto grouping() const -> std::string { return "\03"; }
auto thousands_sep() const -> Char { return ','; }
auto decimal_point() const -> Char { return '.'; }
};
template <typename Facet> Facet use_facet(locale) { return {}; }
#endif // FMT_USE_LOCALE
template <typename Locale> auto locale_ref::get() const -> Locale {
static_assert(std::is_same<Locale, locale>::value, "");
#if FMT_USE_LOCALE
if (locale_) return *static_cast<const locale*>(locale_);
#endif
return locale();
}
template <typename Char> template <typename Char>
FMT_FUNC auto thousands_sep_impl(locale_ref loc) -> thousands_sep_result<Char> { FMT_FUNC auto thousands_sep_impl(locale_ref loc) -> thousands_sep_result<Char> {
auto&& facet = use_facet<numpunct<Char>>(loc.get<locale>()); auto&& facet = use_facet<numpunct<Char>>(loc.get<locale>());
@ -136,13 +133,14 @@ FMT_FUNC auto write_loc(appender out, loc_value value,
} // namespace detail } // namespace detail
FMT_FUNC void report_error(const char* message) { FMT_FUNC void report_error(const char* message) {
#if FMT_MSC_VERSION || defined(__NVCC__) #if FMT_USE_EXCEPTIONS
// Silence unreachable code warnings in MSVC and NVCC because these // Use FMT_THROW instead of throw to avoid bogus unreachable code warnings
// are nearly impossible to fix in a generic code. // from MSVC.
volatile bool b = true;
if (!b) return;
#endif
FMT_THROW(format_error(message)); FMT_THROW(format_error(message));
#else
fputs(message, stderr);
abort();
#endif
} }
template <typename Locale> typename Locale::id format_facet<Locale>::id; template <typename Locale> typename Locale::id format_facet<Locale>::id;
@ -176,11 +174,11 @@ inline auto operator==(basic_fp<F> x, basic_fp<F> y) -> bool {
} }
// Compilers should be able to optimize this into the ror instruction. // Compilers should be able to optimize this into the ror instruction.
FMT_INLINE auto rotr(uint32_t n, uint32_t r) noexcept -> uint32_t { FMT_CONSTEXPR inline auto rotr(uint32_t n, uint32_t r) noexcept -> uint32_t {
r &= 31; r &= 31;
return (n >> r) | (n << (32 - r)); return (n >> r) | (n << (32 - r));
} }
FMT_INLINE auto rotr(uint64_t n, uint32_t r) noexcept -> uint64_t { FMT_CONSTEXPR inline auto rotr(uint64_t n, uint32_t r) noexcept -> uint64_t {
r &= 63; r &= 63;
return (n >> r) | (n << (64 - r)); return (n >> r) | (n << (64 - r));
} }
@ -277,7 +275,7 @@ template <> struct cache_accessor<float> {
static auto get_cached_power(int k) noexcept -> uint64_t { static auto get_cached_power(int k) noexcept -> uint64_t {
FMT_ASSERT(k >= float_info<float>::min_k && k <= float_info<float>::max_k, FMT_ASSERT(k >= float_info<float>::min_k && k <= float_info<float>::max_k,
"k is out of range"); "k is out of range");
static constexpr uint64_t pow10_significands[] = { static constexpr const uint64_t pow10_significands[] = {
0x81ceb32c4b43fcf5, 0xa2425ff75e14fc32, 0xcad2f7f5359a3b3f, 0x81ceb32c4b43fcf5, 0xa2425ff75e14fc32, 0xcad2f7f5359a3b3f,
0xfd87b5f28300ca0e, 0x9e74d1b791e07e49, 0xc612062576589ddb, 0xfd87b5f28300ca0e, 0x9e74d1b791e07e49, 0xc612062576589ddb,
0xf79687aed3eec552, 0x9abe14cd44753b53, 0xc16d9a0095928a28, 0xf79687aed3eec552, 0x9abe14cd44753b53, 0xc16d9a0095928a28,
@ -372,7 +370,7 @@ template <> struct cache_accessor<double> {
FMT_ASSERT(k >= float_info<double>::min_k && k <= float_info<double>::max_k, FMT_ASSERT(k >= float_info<double>::min_k && k <= float_info<double>::max_k,
"k is out of range"); "k is out of range");
static constexpr uint128_fallback pow10_significands[] = { static constexpr const uint128_fallback pow10_significands[] = {
#if FMT_USE_FULL_CACHE_DRAGONBOX #if FMT_USE_FULL_CACHE_DRAGONBOX
{0xff77b1fcbebcdc4f, 0x25e8e89c13bb0f7b}, {0xff77b1fcbebcdc4f, 0x25e8e89c13bb0f7b},
{0x9faacf3df73609b1, 0x77b191618c54e9ad}, {0x9faacf3df73609b1, 0x77b191618c54e9ad},
@ -1039,7 +1037,7 @@ template <> struct cache_accessor<double> {
#if FMT_USE_FULL_CACHE_DRAGONBOX #if FMT_USE_FULL_CACHE_DRAGONBOX
return pow10_significands[k - float_info<double>::min_k]; return pow10_significands[k - float_info<double>::min_k];
#else #else
static constexpr uint64_t powers_of_5_64[] = { static constexpr const uint64_t powers_of_5_64[] = {
0x0000000000000001, 0x0000000000000005, 0x0000000000000019, 0x0000000000000001, 0x0000000000000005, 0x0000000000000019,
0x000000000000007d, 0x0000000000000271, 0x0000000000000c35, 0x000000000000007d, 0x0000000000000271, 0x0000000000000c35,
0x0000000000003d09, 0x000000000001312d, 0x000000000005f5e1, 0x0000000000003d09, 0x000000000001312d, 0x000000000005f5e1,
@ -1151,8 +1149,8 @@ auto is_left_endpoint_integer_shorter_interval(int exponent) noexcept -> bool {
exponent <= case_shorter_interval_left_endpoint_upper_threshold; exponent <= case_shorter_interval_left_endpoint_upper_threshold;
} }
// Remove trailing zeros from n and return the number of zeros removed (float). // Remove trailing zeros from n and return the number of zeros removed (float)
FMT_INLINE auto remove_trailing_zeros(uint32_t& n, int s = 0) noexcept -> int { FMT_INLINE int remove_trailing_zeros(uint32_t& n, int s = 0) noexcept {
FMT_ASSERT(n != 0, ""); FMT_ASSERT(n != 0, "");
// Modular inverse of 5 (mod 2^32): (mod_inv_5 * 5) mod 2^32 = 1. // Modular inverse of 5 (mod 2^32): (mod_inv_5 * 5) mod 2^32 = 1.
constexpr uint32_t mod_inv_5 = 0xcccccccd; constexpr uint32_t mod_inv_5 = 0xcccccccd;
@ -1172,19 +1170,22 @@ FMT_INLINE auto remove_trailing_zeros(uint32_t& n, int s = 0) noexcept -> int {
return s; return s;
} }
// Removes trailing zeros and returns the number of zeros removed (double). // Removes trailing zeros and returns the number of zeros removed (double)
FMT_INLINE auto remove_trailing_zeros(uint64_t& n) noexcept -> int { FMT_INLINE int remove_trailing_zeros(uint64_t& n) noexcept {
FMT_ASSERT(n != 0, ""); FMT_ASSERT(n != 0, "");
// This magic number is ceil(2^90 / 10^8).
constexpr uint64_t magic_number = 12379400392853802749ull;
auto nm = umul128(n, magic_number);
// Is n is divisible by 10^8? // Is n is divisible by 10^8?
constexpr uint32_t ten_pow_8 = 100000000u; if ((nm.high() & ((1ull << (90 - 64)) - 1)) == 0 && nm.low() < magic_number) {
if ((n % ten_pow_8) == 0) {
// If yes, work with the quotient... // If yes, work with the quotient...
auto n32 = static_cast<uint32_t>(n / ten_pow_8); auto n32 = static_cast<uint32_t>(nm.high() >> (90 - 64));
// ... and use the 32 bit variant of the function // ... and use the 32 bit variant of the function
int num_zeros = remove_trailing_zeros(n32, 8); int s = remove_trailing_zeros(n32, 8);
n = n32; n = n32;
return num_zeros; return s;
} }
// If n is not divisible by 10^8, work with n itself. // If n is not divisible by 10^8, work with n itself.
@ -1209,7 +1210,7 @@ FMT_INLINE auto remove_trailing_zeros(uint64_t& n) noexcept -> int {
// The main algorithm for shorter interval case // The main algorithm for shorter interval case
template <typename T> template <typename T>
FMT_INLINE auto shorter_interval_case(int exponent) noexcept -> decimal_fp<T> { FMT_INLINE decimal_fp<T> shorter_interval_case(int exponent) noexcept {
decimal_fp<T> ret_value; decimal_fp<T> ret_value;
// Compute k and beta // Compute k and beta
const int minus_k = floor_log10_pow2_minus_log10_4_over_3(exponent); const int minus_k = floor_log10_pow2_minus_log10_4_over_3(exponent);
@ -1453,8 +1454,8 @@ FMT_FUNC void vformat_to(buffer<char>& buf, string_view fmt, format_args args,
auto out = appender(buf); auto out = appender(buf);
if (fmt.size() == 2 && equal2(fmt.data(), "{}")) if (fmt.size() == 2 && equal2(fmt.data(), "{}"))
return args.get(0).visit(default_arg_formatter<char>{out}); return args.get(0).visit(default_arg_formatter<char>{out});
parse_format_string(fmt, parse_format_string(
format_handler<>{parse_context<>(fmt), {out, args, loc}}); fmt, format_handler<char>{parse_context<char>(fmt), {out, args, loc}});
} }
template <typename T> struct span { template <typename T> struct span {
@ -1545,11 +1546,10 @@ template <typename F> class glibc_file : public file_base<F> {
void advance_write_buffer(size_t size) { this->file_->_IO_write_ptr += size; } void advance_write_buffer(size_t size) { this->file_->_IO_write_ptr += size; }
auto needs_flush() const -> bool { bool needs_flush() const {
if ((this->file_->_flags & line_buffered) == 0) return false; if ((this->file_->_flags & line_buffered) == 0) return false;
char* end = this->file_->_IO_write_end; char* end = this->file_->_IO_write_end;
auto size = max_of<ptrdiff_t>(this->file_->_IO_write_ptr - end, 0); return memchr(end, '\n', to_unsigned(this->file_->_IO_write_ptr - end));
return memchr(end, '\n', static_cast<size_t>(size));
} }
void flush() { fflush_unlocked(this->file_); } void flush() { fflush_unlocked(this->file_); }
@ -1573,7 +1573,7 @@ template <typename F> class apple_file : public file_base<F> {
void init_buffer() { void init_buffer() {
if (this->file_->_p) return; if (this->file_->_p) return;
// Force buffer initialization by placing and removing a char in a buffer. // Force buffer initialization by placing and removing a char in a buffer.
if (!FMT_CLANG_ANALYZER) putc_unlocked(0, this->file_); putc_unlocked(0, this->file_);
--this->file_->_p; --this->file_->_p;
++this->file_->_w; ++this->file_->_w;
} }
@ -1594,7 +1594,7 @@ template <typename F> class apple_file : public file_base<F> {
this->file_->_w -= size; this->file_->_w -= size;
} }
auto needs_flush() const -> bool { bool needs_flush() const {
if ((this->file_->_flags & line_buffered) == 0) return false; if ((this->file_->_flags & line_buffered) == 0) return false;
return memchr(this->file_->_p + this->file_->_w, '\n', return memchr(this->file_->_p + this->file_->_w, '\n',
to_unsigned(-this->file_->_w)); to_unsigned(-this->file_->_w));

File diff suppressed because it is too large Load diff

View file

@ -29,8 +29,7 @@
# if (FMT_HAS_INCLUDE(<fcntl.h>) || defined(__APPLE__) || \ # if (FMT_HAS_INCLUDE(<fcntl.h>) || defined(__APPLE__) || \
defined(__linux__)) && \ defined(__linux__)) && \
(!defined(WINAPI_FAMILY) || \ (!defined(WINAPI_FAMILY) || \
(WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP)) && \ (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP))
!defined(__wasm__)
# include <fcntl.h> // for O_RDONLY # include <fcntl.h> // for O_RDONLY
# define FMT_USE_FCNTL 1 # define FMT_USE_FCNTL 1
# else # else
@ -136,9 +135,10 @@ FMT_API std::system_error vwindows_error(int error_code, string_view fmt,
* **Example**: * **Example**:
* *
* // This throws a system_error with the description * // This throws a system_error with the description
* // cannot open file 'foo': The system cannot find the file specified. * // cannot open file 'madeup': The system cannot find the file
* // or similar (system message may vary) if the file doesn't exist. * specified.
* const char *filename = "foo"; * // or similar (system message may vary).
* const char *filename = "madeup";
* LPOFSTRUCT of = LPOFSTRUCT(); * LPOFSTRUCT of = LPOFSTRUCT();
* HFILE file = OpenFile(filename, &of, OF_READ); * HFILE file = OpenFile(filename, &of, OF_READ);
* if (file == HFILE_ERROR) { * if (file == HFILE_ERROR) {
@ -364,17 +364,17 @@ FMT_INLINE_VARIABLE constexpr auto buffer_size = detail::buffer_size();
/// A fast buffered output stream for writing from a single thread. Writing from /// A fast buffered output stream for writing from a single thread. Writing from
/// multiple threads without external synchronization may result in a data race. /// multiple threads without external synchronization may result in a data race.
class ostream : private detail::buffer<char> { class FMT_API ostream : private detail::buffer<char> {
private: private:
file file_; file file_;
FMT_API ostream(cstring_view path, const detail::ostream_params& params); ostream(cstring_view path, const detail::ostream_params& params);
FMT_API static void grow(buffer<char>& buf, size_t); static void grow(buffer<char>& buf, size_t);
public: public:
FMT_API ostream(ostream&& other) noexcept; ostream(ostream&& other) noexcept;
FMT_API ~ostream(); ~ostream();
operator writer() { operator writer() {
detail::buffer<char>& buf = *this; detail::buffer<char>& buf = *this;

View file

@ -33,8 +33,8 @@
FMT_BEGIN_NAMESPACE FMT_BEGIN_NAMESPACE
namespace detail { namespace detail {
// Generate a unique explicit instantiation in every translation unit using a // Generate a unique explicit instantion in every translation unit using a tag
// tag type in an anonymous namespace. // type in an anonymous namespace.
namespace { namespace {
struct file_access_tag {}; struct file_access_tag {};
} // namespace } // namespace

View file

@ -9,7 +9,7 @@
#define FMT_PRINTF_H_ #define FMT_PRINTF_H_
#ifndef FMT_MODULE #ifndef FMT_MODULE
# include <algorithm> // std::find # include <algorithm> // std::max
# include <limits> // std::numeric_limits # include <limits> // std::numeric_limits
#endif #endif
@ -18,6 +18,10 @@
FMT_BEGIN_NAMESPACE FMT_BEGIN_NAMESPACE
FMT_BEGIN_EXPORT FMT_BEGIN_EXPORT
template <typename T> struct printf_formatter {
printf_formatter() = delete;
};
template <typename Char> class basic_printf_context { template <typename Char> class basic_printf_context {
private: private:
basic_appender<Char> out_; basic_appender<Char> out_;
@ -29,6 +33,8 @@ template <typename Char> class basic_printf_context {
public: public:
using char_type = Char; using char_type = Char;
using parse_context_type = parse_context<Char>;
template <typename T> using formatter_type = printf_formatter<T>;
enum { builtin_types = 1 }; enum { builtin_types = 1 };
/// Constructs a `printf_context` object. References to the arguments are /// Constructs a `printf_context` object. References to the arguments are
@ -40,7 +46,7 @@ template <typename Char> class basic_printf_context {
auto out() -> basic_appender<Char> { return out_; } auto out() -> basic_appender<Char> { return out_; }
void advance_to(basic_appender<Char>) {} void advance_to(basic_appender<Char>) {}
auto locale() -> locale_ref { return {}; } auto locale() -> detail::locale_ref { return {}; }
auto arg(int id) const -> basic_format_arg<basic_printf_context> { auto arg(int id) const -> basic_format_arg<basic_printf_context> {
return args_.get(id); return args_.get(id);
@ -68,9 +74,10 @@ inline auto find<false, char>(const char* first, const char* last, char value,
// Checks if a value fits in int - used to avoid warnings about comparing // Checks if a value fits in int - used to avoid warnings about comparing
// signed and unsigned integers. // signed and unsigned integers.
template <bool IS_SIGNED> struct int_checker { template <bool IsSigned> struct int_checker {
template <typename T> static auto fits_in_int(T value) -> bool { template <typename T> static auto fits_in_int(T value) -> bool {
return value <= to_unsigned(max_value<int>()); unsigned max = to_unsigned(max_value<int>());
return value <= max;
} }
inline static auto fits_in_int(bool) -> bool { return true; } inline static auto fits_in_int(bool) -> bool { return true; }
}; };
@ -88,7 +95,7 @@ struct printf_precision_handler {
auto operator()(T value) -> int { auto operator()(T value) -> int {
if (!int_checker<std::numeric_limits<T>::is_signed>::fits_in_int(value)) if (!int_checker<std::numeric_limits<T>::is_signed>::fits_in_int(value))
report_error("number is too big"); report_error("number is too big");
return max_of(static_cast<int>(value), 0); return (std::max)(static_cast<int>(value), 0);
} }
template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)> template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
@ -403,9 +410,7 @@ void vprintf(buffer<Char>& buf, basic_string_view<Char> format,
arg_index = parse_ctx.next_arg_id(); arg_index = parse_ctx.next_arg_id();
else else
parse_ctx.check_arg_id(--arg_index); parse_ctx.check_arg_id(--arg_index);
auto arg = context.arg(arg_index); return detail::get_arg(context, arg_index);
if (!arg) report_error("argument not found");
return arg;
}; };
const Char* start = parse_ctx.begin(); const Char* start = parse_ctx.begin();
@ -566,18 +571,14 @@ inline auto vsprintf(basic_string_view<Char> fmt,
* *
* std::string message = fmt::sprintf("The answer is %d", 42); * std::string message = fmt::sprintf("The answer is %d", 42);
*/ */
template <typename... T> template <typename S, typename... T, typename Char = detail::char_t<S>>
inline auto sprintf(string_view fmt, const T&... args) -> std::string { inline auto sprintf(const S& fmt, const T&... args) -> std::basic_string<Char> {
return vsprintf(fmt, make_printf_args(args...)); return vsprintf(detail::to_string_view(fmt),
} fmt::make_format_args<basic_printf_context<Char>>(args...));
template <typename... T>
FMT_DEPRECATED auto sprintf(basic_string_view<wchar_t> fmt, const T&... args)
-> std::wstring {
return vsprintf(fmt, make_printf_args<wchar_t>(args...));
} }
template <typename Char> template <typename Char>
auto vfprintf(std::FILE* f, basic_string_view<Char> fmt, inline auto vfprintf(std::FILE* f, basic_string_view<Char> fmt,
typename vprintf_args<Char>::type args) -> int { typename vprintf_args<Char>::type args) -> int {
auto buf = basic_memory_buffer<Char>(); auto buf = basic_memory_buffer<Char>();
detail::vprintf(buf, fmt, args); detail::vprintf(buf, fmt, args);
@ -595,14 +596,17 @@ auto vfprintf(std::FILE* f, basic_string_view<Char> fmt,
* *
* fmt::fprintf(stderr, "Don't %s!", "panic"); * fmt::fprintf(stderr, "Don't %s!", "panic");
*/ */
template <typename... T> template <typename S, typename... T, typename Char = detail::char_t<S>>
inline auto fprintf(std::FILE* f, string_view fmt, const T&... args) -> int { inline auto fprintf(std::FILE* f, const S& fmt, const T&... args) -> int {
return vfprintf(f, fmt, make_printf_args(args...)); return vfprintf(f, detail::to_string_view(fmt),
make_printf_args<Char>(args...));
} }
template <typename... T>
FMT_DEPRECATED auto fprintf(std::FILE* f, basic_string_view<wchar_t> fmt, template <typename Char>
const T&... args) -> int { FMT_DEPRECATED inline auto vprintf(basic_string_view<Char> fmt,
return vfprintf(f, fmt, make_printf_args<wchar_t>(args...)); typename vprintf_args<Char>::type args)
-> int {
return vfprintf(stdout, fmt, args);
} }
/** /**
@ -617,6 +621,11 @@ template <typename... T>
inline auto printf(string_view fmt, const T&... args) -> int { inline auto printf(string_view fmt, const T&... args) -> int {
return vfprintf(stdout, fmt, make_printf_args(args...)); return vfprintf(stdout, fmt, make_printf_args(args...));
} }
template <typename... T>
FMT_DEPRECATED inline auto printf(basic_string_view<wchar_t> fmt,
const T&... args) -> int {
return vfprintf(stdout, fmt, make_printf_args<wchar_t>(args...));
}
FMT_END_EXPORT FMT_END_EXPORT
FMT_END_NAMESPACE FMT_END_NAMESPACE

View file

@ -11,6 +11,7 @@
#ifndef FMT_MODULE #ifndef FMT_MODULE
# include <initializer_list> # include <initializer_list>
# include <iterator> # include <iterator>
# include <string>
# include <tuple> # include <tuple>
# include <type_traits> # include <type_traits>
# include <utility> # include <utility>
@ -18,13 +19,6 @@
#include "format.h" #include "format.h"
#if FMT_HAS_CPP_ATTRIBUTE(clang::lifetimebound)
# define FMT_LIFETIMEBOUND [[clang::lifetimebound]]
#else
# define FMT_LIFETIMEBOUND
#endif
FMT_PRAGMA_CLANG(diagnostic error "-Wreturn-stack-address")
FMT_BEGIN_NAMESPACE FMT_BEGIN_NAMESPACE
FMT_EXPORT FMT_EXPORT
@ -37,7 +31,7 @@ template <typename T> class is_map {
template <typename> static void check(...); template <typename> static void check(...);
public: public:
static constexpr bool value = static constexpr const bool value =
!std::is_void<decltype(check<T>(nullptr))>::value; !std::is_void<decltype(check<T>(nullptr))>::value;
}; };
@ -46,16 +40,17 @@ template <typename T> class is_set {
template <typename> static void check(...); template <typename> static void check(...);
public: public:
static constexpr bool value = static constexpr const bool value =
!std::is_void<decltype(check<T>(nullptr))>::value && !is_map<T>::value; !std::is_void<decltype(check<T>(nullptr))>::value && !is_map<T>::value;
}; };
// C array overload // C array overload
template <typename T, size_t N> template <typename T, std::size_t N>
auto range_begin(const T (&arr)[N]) -> const T* { auto range_begin(const T (&arr)[N]) -> const T* {
return arr; return arr;
} }
template <typename T, size_t N> auto range_end(const T (&arr)[N]) -> const T* { template <typename T, std::size_t N>
auto range_end(const T (&arr)[N]) -> const T* {
return arr + N; return arr + N;
} }
@ -125,7 +120,7 @@ template <typename T> class is_tuple_like_ {
template <typename> static void check(...); template <typename> static void check(...);
public: public:
static constexpr bool value = static constexpr const bool value =
!std::is_void<decltype(check<T>(nullptr))>::value; !std::is_void<decltype(check<T>(nullptr))>::value;
}; };
@ -159,7 +154,7 @@ using tuple_index_sequence = make_index_sequence<std::tuple_size<T>::value>;
template <typename T, typename C, bool = is_tuple_like_<T>::value> template <typename T, typename C, bool = is_tuple_like_<T>::value>
class is_tuple_formattable_ { class is_tuple_formattable_ {
public: public:
static constexpr bool value = false; static constexpr const bool value = false;
}; };
template <typename T, typename C> class is_tuple_formattable_<T, C, true> { template <typename T, typename C> class is_tuple_formattable_<T, C, true> {
template <size_t... Is> template <size_t... Is>
@ -175,7 +170,7 @@ template <typename T, typename C> class is_tuple_formattable_<T, C, true> {
C>::value)...>{})); C>::value)...>{}));
public: public:
static constexpr bool value = static constexpr const bool value =
decltype(check(tuple_index_sequence<T>{}))::value; decltype(check(tuple_index_sequence<T>{}))::value;
}; };
@ -213,7 +208,7 @@ template <typename Char, typename... T>
using result_t = std::tuple<formatter<remove_cvref_t<T>, Char>...>; using result_t = std::tuple<formatter<remove_cvref_t<T>, Char>...>;
using std::get; using std::get;
template <typename Tuple, typename Char, size_t... Is> template <typename Tuple, typename Char, std::size_t... Is>
auto get_formatters(index_sequence<Is...>) auto get_formatters(index_sequence<Is...>)
-> result_t<Char, decltype(get<Is>(std::declval<Tuple>()))...>; -> result_t<Char, decltype(get<Is>(std::declval<Tuple>()))...>;
} // namespace tuple } // namespace tuple
@ -224,7 +219,7 @@ template <typename R> struct range_reference_type_impl {
using type = decltype(*detail::range_begin(std::declval<R&>())); using type = decltype(*detail::range_begin(std::declval<R&>()));
}; };
template <typename T, size_t N> struct range_reference_type_impl<T[N]> { template <typename T, std::size_t N> struct range_reference_type_impl<T[N]> {
using type = T&; using type = T&;
}; };
@ -241,6 +236,14 @@ using range_reference_type =
template <typename Range> template <typename Range>
using uncvref_type = remove_cvref_t<range_reference_type<Range>>; using uncvref_type = remove_cvref_t<range_reference_type<Range>>;
template <typename Formatter>
FMT_CONSTEXPR auto maybe_set_debug_format(Formatter& f, bool set)
-> decltype(f.set_debug_format(set)) {
f.set_debug_format(set);
}
template <typename Formatter>
FMT_CONSTEXPR void maybe_set_debug_format(Formatter&, ...) {}
template <typename T> template <typename T>
struct range_format_kind_ struct range_format_kind_
: std::integral_constant<range_format, : std::integral_constant<range_format,
@ -278,15 +281,14 @@ template <typename FormatContext> struct format_tuple_element {
} // namespace detail } // namespace detail
FMT_EXPORT
template <typename T> struct is_tuple_like { template <typename T> struct is_tuple_like {
static constexpr bool value = static constexpr const bool value =
detail::is_tuple_like_<T>::value && !detail::is_range_<T>::value; detail::is_tuple_like_<T>::value && !detail::is_range_<T>::value;
}; };
FMT_EXPORT
template <typename T, typename C> struct is_tuple_formattable { template <typename T, typename C> struct is_tuple_formattable {
static constexpr bool value = detail::is_tuple_formattable_<T, C>::value; static constexpr const bool value =
detail::is_tuple_formattable_<T, C>::value;
}; };
template <typename Tuple, typename Char> template <typename Tuple, typename Char>
@ -341,9 +343,8 @@ struct formatter<Tuple, Char,
} }
}; };
FMT_EXPORT
template <typename T, typename Char> struct is_range { template <typename T, typename Char> struct is_range {
static constexpr bool value = static constexpr const bool value =
detail::is_range_<T>::value && !detail::has_to_string_view<T>::value; detail::is_range_<T>::value && !detail::has_to_string_view<T>::value;
}; };
@ -367,7 +368,6 @@ template <typename P1, typename... Pn>
struct conjunction<P1, Pn...> struct conjunction<P1, Pn...>
: conditional_t<bool(P1::value), conjunction<Pn...>, P1> {}; : conditional_t<bool(P1::value), conjunction<Pn...>, P1> {};
FMT_EXPORT
template <typename T, typename Char, typename Enable = void> template <typename T, typename Char, typename Enable = void>
struct range_formatter; struct range_formatter;
@ -670,8 +670,7 @@ struct formatter<join_view<It, Sentinel, Char>, Char> {
} }
}; };
FMT_EXPORT template <typename Char, typename Tuple> struct tuple_join_view : detail::view {
template <typename Tuple, typename Char> struct tuple_join_view : detail::view {
const Tuple& tuple; const Tuple& tuple;
basic_string_view<Char> sep; basic_string_view<Char> sep;
@ -686,15 +685,15 @@ template <typename Tuple, typename Char> struct tuple_join_view : detail::view {
# define FMT_TUPLE_JOIN_SPECIFIERS 0 # define FMT_TUPLE_JOIN_SPECIFIERS 0
#endif #endif
template <typename Tuple, typename Char> template <typename Char, typename Tuple>
struct formatter<tuple_join_view<Tuple, Char>, Char, struct formatter<tuple_join_view<Char, Tuple>, Char,
enable_if_t<is_tuple_like<Tuple>::value>> { enable_if_t<is_tuple_like<Tuple>::value>> {
FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* { FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
return do_parse(ctx, std::tuple_size<Tuple>()); return do_parse(ctx, std::tuple_size<Tuple>());
} }
template <typename FormatContext> template <typename FormatContext>
auto format(const tuple_join_view<Tuple, Char>& value, auto format(const tuple_join_view<Char, Tuple>& value,
FormatContext& ctx) const -> typename FormatContext::iterator { FormatContext& ctx) const -> typename FormatContext::iterator {
return do_format(value, ctx, std::tuple_size<Tuple>()); return do_format(value, ctx, std::tuple_size<Tuple>());
} }
@ -726,14 +725,14 @@ struct formatter<tuple_join_view<Tuple, Char>, Char,
} }
template <typename FormatContext> template <typename FormatContext>
auto do_format(const tuple_join_view<Tuple, Char>&, FormatContext& ctx, auto do_format(const tuple_join_view<Char, Tuple>&, FormatContext& ctx,
std::integral_constant<size_t, 0>) const -> std::integral_constant<size_t, 0>) const ->
typename FormatContext::iterator { typename FormatContext::iterator {
return ctx.out(); return ctx.out();
} }
template <typename FormatContext, size_t N> template <typename FormatContext, size_t N>
auto do_format(const tuple_join_view<Tuple, Char>& value, FormatContext& ctx, auto do_format(const tuple_join_view<Char, Tuple>& value, FormatContext& ctx,
std::integral_constant<size_t, N>) const -> std::integral_constant<size_t, N>) const ->
typename FormatContext::iterator { typename FormatContext::iterator {
using std::get; using std::get;
@ -755,7 +754,7 @@ template <typename T> class is_container_adaptor_like {
template <typename> static void check(...); template <typename> static void check(...);
public: public:
static constexpr bool value = static constexpr const bool value =
!std::is_void<decltype(check<T>(nullptr))>::value; !std::is_void<decltype(check<T>(nullptr))>::value;
}; };
@ -820,13 +819,13 @@ auto join(Range&& r, string_view sep)
* *
* **Example**: * **Example**:
* *
* auto t = std::tuple<int, char>(1, 'a'); * auto t = std::tuple<int, char>{1, 'a'};
* fmt::print("{}", fmt::join(t, ", ")); * fmt::print("{}", fmt::join(t, ", "));
* // Output: 1, a * // Output: 1, a
*/ */
template <typename Tuple, FMT_ENABLE_IF(is_tuple_like<Tuple>::value)> template <typename Tuple, FMT_ENABLE_IF(is_tuple_like<Tuple>::value)>
FMT_CONSTEXPR auto join(const Tuple& tuple FMT_LIFETIMEBOUND, string_view sep) FMT_CONSTEXPR auto join(const Tuple& tuple, string_view sep)
-> tuple_join_view<Tuple, char> { -> tuple_join_view<char, Tuple> {
return {tuple, sep}; return {tuple, sep};
} }

View file

@ -15,13 +15,15 @@
# include <atomic> # include <atomic>
# include <bitset> # include <bitset>
# include <complex> # include <complex>
# include <cstdlib>
# include <exception> # include <exception>
# include <functional> // std::reference_wrapper # include <functional>
# include <memory> # include <memory>
# include <thread> # include <thread>
# include <type_traits> # include <type_traits>
# include <typeinfo> // std::type_info # include <typeinfo>
# include <utility> // std::make_index_sequence # include <utility>
# include <vector>
// Check FMT_CPLUSPLUS to suppress a bogus warning in MSVC. // Check FMT_CPLUSPLUS to suppress a bogus warning in MSVC.
# if FMT_CPLUSPLUS >= 201703L # if FMT_CPLUSPLUS >= 201703L
@ -60,26 +62,27 @@
# endif # endif
#endif #endif
#ifdef FMT_CPP_LIB_FILESYSTEM // For older Xcode versions, __cpp_lib_xxx flags are inaccurately defined.
// Use the provided definition. #ifndef FMT_CPP_LIB_FILESYSTEM
#elif defined(__cpp_lib_filesystem) # ifdef __cpp_lib_filesystem
# define FMT_CPP_LIB_FILESYSTEM __cpp_lib_filesystem # define FMT_CPP_LIB_FILESYSTEM __cpp_lib_filesystem
# else # else
# define FMT_CPP_LIB_FILESYSTEM 0 # define FMT_CPP_LIB_FILESYSTEM 0
# endif # endif
#endif
#ifdef FMT_CPP_LIB_VARIANT #ifndef FMT_CPP_LIB_VARIANT
// Use the provided definition. # ifdef __cpp_lib_variant
#elif defined(__cpp_lib_variant)
# define FMT_CPP_LIB_VARIANT __cpp_lib_variant # define FMT_CPP_LIB_VARIANT __cpp_lib_variant
# else # else
# define FMT_CPP_LIB_VARIANT 0 # define FMT_CPP_LIB_VARIANT 0
# endif # endif
#endif
FMT_BEGIN_NAMESPACE
namespace detail {
#if FMT_CPP_LIB_FILESYSTEM #if FMT_CPP_LIB_FILESYSTEM
FMT_BEGIN_NAMESPACE
namespace detail {
template <typename Char, typename PathChar> template <typename Char, typename PathChar>
auto get_path_string(const std::filesystem::path& p, auto get_path_string(const std::filesystem::path& p,
@ -108,180 +111,8 @@ void write_escaped_path(basic_memory_buffer<Char>& quoted,
} }
} }
#endif // FMT_CPP_LIB_FILESYSTEM
#if defined(__cpp_lib_expected) || FMT_CPP_LIB_VARIANT
template <typename Char, typename OutputIt, typename T, typename FormatContext>
auto write_escaped_alternative(OutputIt out, const T& v, FormatContext& ctx)
-> OutputIt {
if constexpr (has_to_string_view<T>::value)
return write_escaped_string<Char>(out, detail::to_string_view(v));
if constexpr (std::is_same_v<T, Char>) return write_escaped_char(out, v);
formatter<std::remove_cv_t<T>, Char> underlying;
maybe_set_debug_format(underlying, true);
return underlying.format(v, ctx);
}
#endif
#if FMT_CPP_LIB_VARIANT
template <typename> struct is_variant_like_ : std::false_type {};
template <typename... Types>
struct is_variant_like_<std::variant<Types...>> : std::true_type {};
template <typename Variant, typename Char> class is_variant_formattable {
template <size_t... Is>
static auto check(std::index_sequence<Is...>) -> std::conjunction<
is_formattable<std::variant_alternative_t<Is, Variant>, Char>...>;
public:
static constexpr bool value = decltype(check(
std::make_index_sequence<std::variant_size<Variant>::value>()))::value;
};
#endif // FMT_CPP_LIB_VARIANT
#if FMT_USE_RTTI
inline auto normalize_libcxx_inline_namespaces(string_view demangled_name_view,
char* begin) -> string_view {
// Normalization of stdlib inline namespace names.
// libc++ inline namespaces.
// std::__1::* -> std::*
// std::__1::__fs::* -> std::*
// libstdc++ inline namespaces.
// std::__cxx11::* -> std::*
// std::filesystem::__cxx11::* -> std::filesystem::*
if (demangled_name_view.starts_with("std::")) {
char* to = begin + 5; // std::
for (const char *from = to, *end = begin + demangled_name_view.size();
from < end;) {
// This is safe, because demangled_name is NUL-terminated.
if (from[0] == '_' && from[1] == '_') {
const char* next = from + 1;
while (next < end && *next != ':') next++;
if (next[0] == ':' && next[1] == ':') {
from = next + 2;
continue;
}
}
*to++ = *from++;
}
demangled_name_view = {begin, detail::to_unsigned(to - begin)};
}
return demangled_name_view;
}
template <class OutputIt>
auto normalize_msvc_abi_name(string_view abi_name_view, OutputIt out)
-> OutputIt {
const string_view demangled_name(abi_name_view);
for (size_t i = 0; i < demangled_name.size(); ++i) {
auto sub = demangled_name;
sub.remove_prefix(i);
if (sub.starts_with("enum ")) {
i += 4;
continue;
}
if (sub.starts_with("class ") || sub.starts_with("union ")) {
i += 5;
continue;
}
if (sub.starts_with("struct ")) {
i += 6;
continue;
}
if (*sub.begin() != ' ') *out++ = *sub.begin();
}
return out;
}
template <typename OutputIt>
auto write_demangled_name(OutputIt out, const std::type_info& ti) -> OutputIt {
# ifdef FMT_HAS_ABI_CXA_DEMANGLE
int status = 0;
size_t size = 0;
std::unique_ptr<char, void (*)(void*)> demangled_name_ptr(
abi::__cxa_demangle(ti.name(), nullptr, &size, &status), &free);
string_view demangled_name_view;
if (demangled_name_ptr) {
demangled_name_view = normalize_libcxx_inline_namespaces(
demangled_name_ptr.get(), demangled_name_ptr.get());
} else {
demangled_name_view = string_view(ti.name());
}
return detail::write_bytes<char>(out, demangled_name_view);
# elif FMT_MSC_VERSION && defined(_MSVC_STL_UPDATE)
return normalize_msvc_abi_name(ti.name(), out);
# elif FMT_MSC_VERSION && defined(_LIBCPP_VERSION)
const string_view demangled_name = ti.name();
std::string name_copy(demangled_name.size(), '\0');
// normalize_msvc_abi_name removes class, struct, union etc that MSVC has in
// front of types
name_copy.erase(normalize_msvc_abi_name(demangled_name, name_copy.begin()),
name_copy.end());
// normalize_libcxx_inline_namespaces removes the inline __1, __2, etc
// namespaces libc++ uses for ABI versioning On MSVC ABI + libc++
// environments, we need to eliminate both of them.
const string_view normalized_name =
normalize_libcxx_inline_namespaces(name_copy, name_copy.data());
return detail::write_bytes<char>(out, normalized_name);
# else
return detail::write_bytes<char>(out, string_view(ti.name()));
# endif
}
#endif // FMT_USE_RTTI
template <typename T, typename Enable = void>
struct has_flip : std::false_type {};
template <typename T>
struct has_flip<T, void_t<decltype(std::declval<T>().flip())>>
: std::true_type {};
template <typename T> struct is_bit_reference_like {
static constexpr bool value = std::is_convertible<T, bool>::value &&
std::is_nothrow_assignable<T, bool>::value &&
has_flip<T>::value;
};
// Workaround for libc++ incompatibility with C++ standard.
// According to the Standard, `bitset::operator[] const` returns bool.
#if defined(_LIBCPP_VERSION) && !defined(FMT_IMPORT_STD)
template <typename C>
struct is_bit_reference_like<std::__bit_const_reference<C>> {
static constexpr bool value = true;
};
#endif
template <typename T, typename Enable = void>
struct has_format_as : std::false_type {};
template <typename T>
struct has_format_as<T, void_t<decltype(format_as(std::declval<const T&>()))>>
: std::true_type {};
template <typename T, typename Enable = void>
struct has_format_as_member : std::false_type {};
template <typename T>
struct has_format_as_member<
T, void_t<decltype(formatter<T>::format_as(std::declval<const T&>()))>>
: std::true_type {};
} // namespace detail } // namespace detail
template <typename T, typename Deleter>
auto ptr(const std::unique_ptr<T, Deleter>& p) -> const void* {
return p.get();
}
template <typename T> auto ptr(const std::shared_ptr<T>& p) -> const void* {
return p.get();
}
#if FMT_CPP_LIB_FILESYSTEM
template <typename Char> struct formatter<std::filesystem::path, Char> { template <typename Char> struct formatter<std::filesystem::path, Char> {
private: private:
format_specs specs_; format_specs specs_;
@ -346,20 +177,24 @@ class path : public std::filesystem::path {
auto generic_system_string() const -> std::string { return generic_string(); } auto generic_system_string() const -> std::string { return generic_string(); }
}; };
FMT_END_NAMESPACE
#endif // FMT_CPP_LIB_FILESYSTEM #endif // FMT_CPP_LIB_FILESYSTEM
template <size_t N, typename Char> FMT_BEGIN_NAMESPACE
template <std::size_t N, typename Char>
struct formatter<std::bitset<N>, Char> struct formatter<std::bitset<N>, Char>
: nested_formatter<basic_string_view<Char>, Char> { : nested_formatter<basic_string_view<Char>, Char> {
private: private:
// This is a functor because C++11 doesn't support generic lambdas. // Functor because C++11 doesn't support generic lambdas.
struct writer { struct writer {
const std::bitset<N>& bs; const std::bitset<N>& bs;
template <typename OutputIt> template <typename OutputIt>
FMT_CONSTEXPR auto operator()(OutputIt out) -> OutputIt { FMT_CONSTEXPR auto operator()(OutputIt out) -> OutputIt {
for (auto pos = N; pos > 0; --pos) for (auto pos = N; pos > 0; --pos) {
out = detail::write<Char>(out, bs[pos - 1] ? Char('1') : Char('0')); out = detail::write<Char>(out, bs[pos - 1] ? Char('1') : Char('0'));
}
return out; return out;
} }
}; };
@ -374,22 +209,33 @@ struct formatter<std::bitset<N>, Char>
template <typename Char> template <typename Char>
struct formatter<std::thread::id, Char> : basic_ostream_formatter<Char> {}; struct formatter<std::thread::id, Char> : basic_ostream_formatter<Char> {};
FMT_END_NAMESPACE
#ifdef __cpp_lib_optional #ifdef __cpp_lib_optional
FMT_BEGIN_NAMESPACE
template <typename T, typename Char> template <typename T, typename Char>
struct formatter<std::optional<T>, Char, struct formatter<std::optional<T>, Char,
std::enable_if_t<is_formattable<T, Char>::value>> { std::enable_if_t<is_formattable<T, Char>::value>> {
private: private:
formatter<std::remove_cv_t<T>, Char> underlying_; formatter<T, Char> underlying_;
static constexpr basic_string_view<Char> optional = static constexpr basic_string_view<Char> optional =
detail::string_literal<Char, 'o', 'p', 't', 'i', 'o', 'n', 'a', 'l', detail::string_literal<Char, 'o', 'p', 't', 'i', 'o', 'n', 'a', 'l',
'('>{}; '('>{};
static constexpr basic_string_view<Char> none = static constexpr basic_string_view<Char> none =
detail::string_literal<Char, 'n', 'o', 'n', 'e'>{}; detail::string_literal<Char, 'n', 'o', 'n', 'e'>{};
template <class U>
FMT_CONSTEXPR static auto maybe_set_debug_format(U& u, bool set)
-> decltype(u.set_debug_format(set)) {
u.set_debug_format(set);
}
template <class U>
FMT_CONSTEXPR static void maybe_set_debug_format(U&, ...) {}
public: public:
FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) { FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) {
detail::maybe_set_debug_format(underlying_, true); maybe_set_debug_format(underlying_, true);
return underlying_.parse(ctx); return underlying_.parse(ctx);
} }
@ -405,9 +251,30 @@ struct formatter<std::optional<T>, Char,
return detail::write(out, ')'); return detail::write(out, ')');
} }
}; };
FMT_END_NAMESPACE
#endif // __cpp_lib_optional #endif // __cpp_lib_optional
#if defined(__cpp_lib_expected) || FMT_CPP_LIB_VARIANT
FMT_BEGIN_NAMESPACE
namespace detail {
template <typename Char, typename OutputIt, typename T>
auto write_escaped_alternative(OutputIt out, const T& v) -> OutputIt {
if constexpr (has_to_string_view<T>::value)
return write_escaped_string<Char>(out, detail::to_string_view(v));
if constexpr (std::is_same_v<T, Char>) return write_escaped_char(out, v);
return write<Char>(out, v);
}
} // namespace detail
FMT_END_NAMESPACE
#endif
#ifdef __cpp_lib_expected #ifdef __cpp_lib_expected
FMT_BEGIN_NAMESPACE
template <typename T, typename E, typename Char> template <typename T, typename E, typename Char>
struct formatter<std::expected<T, E>, Char, struct formatter<std::expected<T, E>, Char,
std::enable_if_t<(std::is_void<T>::value || std::enable_if_t<(std::is_void<T>::value ||
@ -425,18 +292,20 @@ struct formatter<std::expected<T, E>, Char,
if (value.has_value()) { if (value.has_value()) {
out = detail::write<Char>(out, "expected("); out = detail::write<Char>(out, "expected(");
if constexpr (!std::is_void<T>::value) if constexpr (!std::is_void<T>::value)
out = detail::write_escaped_alternative<Char>(out, *value, ctx); out = detail::write_escaped_alternative<Char>(out, *value);
} else { } else {
out = detail::write<Char>(out, "unexpected("); out = detail::write<Char>(out, "unexpected(");
out = detail::write_escaped_alternative<Char>(out, value.error(), ctx); out = detail::write_escaped_alternative<Char>(out, value.error());
} }
*out++ = ')'; *out++ = ')';
return out; return out;
} }
}; };
FMT_END_NAMESPACE
#endif // __cpp_lib_expected #endif // __cpp_lib_expected
#ifdef __cpp_lib_source_location #ifdef __cpp_lib_source_location
FMT_BEGIN_NAMESPACE
template <> struct formatter<std::source_location> { template <> struct formatter<std::source_location> {
FMT_CONSTEXPR auto parse(parse_context<>& ctx) { return ctx.begin(); } FMT_CONSTEXPR auto parse(parse_context<>& ctx) { return ctx.begin(); }
@ -454,12 +323,42 @@ template <> struct formatter<std::source_location> {
return out; return out;
} }
}; };
FMT_END_NAMESPACE
#endif #endif
#if FMT_CPP_LIB_VARIANT #if FMT_CPP_LIB_VARIANT
FMT_BEGIN_NAMESPACE
namespace detail {
template <typename T>
using variant_index_sequence =
std::make_index_sequence<std::variant_size<T>::value>;
template <typename> struct is_variant_like_ : std::false_type {};
template <typename... Types>
struct is_variant_like_<std::variant<Types...>> : std::true_type {};
// formattable element check.
template <typename T, typename C> class is_variant_formattable_ {
template <std::size_t... Is>
static std::conjunction<
is_formattable<std::variant_alternative_t<Is, T>, C>...>
check(std::index_sequence<Is...>);
public:
static constexpr const bool value =
decltype(check(variant_index_sequence<T>{}))::value;
};
} // namespace detail
template <typename T> struct is_variant_like { template <typename T> struct is_variant_like {
static constexpr bool value = detail::is_variant_like_<T>::value; static constexpr const bool value = detail::is_variant_like_<T>::value;
};
template <typename T, typename C> struct is_variant_formattable {
static constexpr const bool value =
detail::is_variant_formattable_<T, C>::value;
}; };
template <typename Char> struct formatter<std::monostate, Char> { template <typename Char> struct formatter<std::monostate, Char> {
@ -475,10 +374,10 @@ template <typename Char> struct formatter<std::monostate, Char> {
}; };
template <typename Variant, typename Char> template <typename Variant, typename Char>
struct formatter<Variant, Char, struct formatter<
Variant, Char,
std::enable_if_t<std::conjunction_v< std::enable_if_t<std::conjunction_v<
is_variant_like<Variant>, is_variant_like<Variant>, is_variant_formattable<Variant, Char>>>> {
detail::is_variant_formattable<Variant, Char>>>> {
FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* { FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
return ctx.begin(); return ctx.begin();
} }
@ -492,7 +391,7 @@ struct formatter<Variant, Char,
FMT_TRY { FMT_TRY {
std::visit( std::visit(
[&](const auto& v) { [&](const auto& v) {
out = detail::write_escaped_alternative<Char>(out, v, ctx); out = detail::write_escaped_alternative<Char>(out, v);
}, },
value); value);
} }
@ -503,9 +402,10 @@ struct formatter<Variant, Char,
return out; return out;
} }
}; };
FMT_END_NAMESPACE
#endif // FMT_CPP_LIB_VARIANT #endif // FMT_CPP_LIB_VARIANT
FMT_BEGIN_NAMESPACE
template <> struct formatter<std::error_code> { template <> struct formatter<std::error_code> {
private: private:
format_specs specs_; format_specs specs_;
@ -513,8 +413,6 @@ template <> struct formatter<std::error_code> {
bool debug_ = false; bool debug_ = false;
public: public:
FMT_CONSTEXPR void set_debug_format(bool set = true) { debug_ = set; }
FMT_CONSTEXPR auto parse(parse_context<>& ctx) -> const char* { FMT_CONSTEXPR auto parse(parse_context<>& ctx) -> const char* {
auto it = ctx.begin(), end = ctx.end(); auto it = ctx.begin(), end = ctx.end();
if (it == end) return it; if (it == end) return it;
@ -561,29 +459,101 @@ template <> struct formatter<std::error_code> {
}; };
#if FMT_USE_RTTI #if FMT_USE_RTTI
template <> struct formatter<std::type_info> { namespace detail {
template <typename Char, typename OutputIt>
auto write_demangled_name(OutputIt out, const std::type_info& ti) -> OutputIt {
# ifdef FMT_HAS_ABI_CXA_DEMANGLE
int status = 0;
std::size_t size = 0;
std::unique_ptr<char, void (*)(void*)> demangled_name_ptr(
abi::__cxa_demangle(ti.name(), nullptr, &size, &status), &std::free);
string_view demangled_name_view;
if (demangled_name_ptr) {
demangled_name_view = demangled_name_ptr.get();
// Normalization of stdlib inline namespace names.
// libc++ inline namespaces.
// std::__1::* -> std::*
// std::__1::__fs::* -> std::*
// libstdc++ inline namespaces.
// std::__cxx11::* -> std::*
// std::filesystem::__cxx11::* -> std::filesystem::*
if (demangled_name_view.starts_with("std::")) {
char* begin = demangled_name_ptr.get();
char* to = begin + 5; // std::
for (char *from = to, *end = begin + demangled_name_view.size();
from < end;) {
// This is safe, because demangled_name is NUL-terminated.
if (from[0] == '_' && from[1] == '_') {
char* next = from + 1;
while (next < end && *next != ':') next++;
if (next[0] == ':' && next[1] == ':') {
from = next + 2;
continue;
}
}
*to++ = *from++;
}
demangled_name_view = {begin, detail::to_unsigned(to - begin)};
}
} else {
demangled_name_view = string_view(ti.name());
}
return detail::write_bytes<Char>(out, demangled_name_view);
# elif FMT_MSC_VERSION
const string_view demangled_name(ti.name());
for (std::size_t i = 0; i < demangled_name.size(); ++i) {
auto sub = demangled_name;
sub.remove_prefix(i);
if (sub.starts_with("enum ")) {
i += 4;
continue;
}
if (sub.starts_with("class ") || sub.starts_with("union ")) {
i += 5;
continue;
}
if (sub.starts_with("struct ")) {
i += 6;
continue;
}
if (*sub.begin() != ' ') *out++ = *sub.begin();
}
return out;
# else
return detail::write_bytes<Char>(out, string_view(ti.name()));
# endif
}
} // namespace detail
template <typename Char>
struct formatter<std::type_info, Char // DEPRECATED! Mixing code unit types.
> {
public: public:
FMT_CONSTEXPR auto parse(parse_context<>& ctx) -> const char* { FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
return ctx.begin(); return ctx.begin();
} }
template <typename Context> template <typename Context>
auto format(const std::type_info& ti, Context& ctx) const auto format(const std::type_info& ti, Context& ctx) const
-> decltype(ctx.out()) { -> decltype(ctx.out()) {
return detail::write_demangled_name(ctx.out(), ti); return detail::write_demangled_name<Char>(ctx.out(), ti);
} }
}; };
#endif // FMT_USE_RTTI #endif
template <typename T> template <typename T, typename Char>
struct formatter< struct formatter<
T, char, T, Char, // DEPRECATED! Mixing code unit types.
typename std::enable_if<std::is_base_of<std::exception, T>::value>::type> { typename std::enable_if<std::is_base_of<std::exception, T>::value>::type> {
private: private:
bool with_typename_ = false; bool with_typename_ = false;
public: public:
FMT_CONSTEXPR auto parse(parse_context<>& ctx) -> const char* { FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
auto it = ctx.begin(); auto it = ctx.begin();
auto end = ctx.end(); auto end = ctx.end();
if (it == end || *it == '}') return it; if (it == end || *it == '}') return it;
@ -600,15 +570,43 @@ struct formatter<
auto out = ctx.out(); auto out = ctx.out();
#if FMT_USE_RTTI #if FMT_USE_RTTI
if (with_typename_) { if (with_typename_) {
out = detail::write_demangled_name(out, typeid(ex)); out = detail::write_demangled_name<Char>(out, typeid(ex));
*out++ = ':'; *out++ = ':';
*out++ = ' '; *out++ = ' ';
} }
#endif #endif
return detail::write_bytes<char>(out, string_view(ex.what())); return detail::write_bytes<Char>(out, string_view(ex.what()));
} }
}; };
namespace detail {
template <typename T, typename Enable = void>
struct has_flip : std::false_type {};
template <typename T>
struct has_flip<T, void_t<decltype(std::declval<T>().flip())>>
: std::true_type {};
template <typename T> struct is_bit_reference_like {
static constexpr const bool value =
std::is_convertible<T, bool>::value &&
std::is_nothrow_assignable<T, bool>::value && has_flip<T>::value;
};
#ifdef _LIBCPP_VERSION
// Workaround for libc++ incompatibility with C++ standard.
// According to the Standard, `bitset::operator[] const` returns bool.
template <typename C>
struct is_bit_reference_like<std::__bit_const_reference<C>> {
static constexpr const bool value = true;
};
#endif
} // namespace detail
// We can't use std::vector<bool, Allocator>::reference and // We can't use std::vector<bool, Allocator>::reference and
// std::bitset<N>::reference because the compiler can't deduce Allocator and N // std::bitset<N>::reference because the compiler can't deduce Allocator and N
// in partial specialization. // in partial specialization.
@ -623,6 +621,14 @@ struct formatter<BitRef, Char,
} }
}; };
template <typename T, typename Deleter>
auto ptr(const std::unique_ptr<T, Deleter>& p) -> const void* {
return p.get();
}
template <typename T> auto ptr(const std::shared_ptr<T>& p) -> const void* {
return p.get();
}
template <typename T, typename Char> template <typename T, typename Char>
struct formatter<std::atomic<T>, Char, struct formatter<std::atomic<T>, Char,
enable_if_t<is_formattable<T, Char>::value>> enable_if_t<is_formattable<T, Char>::value>>
@ -709,11 +715,7 @@ template <typename T, typename Char> struct formatter<std::complex<T>, Char> {
template <typename T, typename Char> template <typename T, typename Char>
struct formatter<std::reference_wrapper<T>, Char, struct formatter<std::reference_wrapper<T>, Char,
// Guard against format_as because reference_wrapper is enable_if_t<is_formattable<remove_cvref_t<T>, Char>::value>>
// implicitly convertible to T&.
enable_if_t<is_formattable<remove_cvref_t<T>, Char>::value &&
!detail::has_format_as<T>::value &&
!detail::has_format_as_member<T>::value>>
: formatter<remove_cvref_t<T>, Char> { : formatter<remove_cvref_t<T>, Char> {
template <typename FormatContext> template <typename FormatContext>
auto format(std::reference_wrapper<T> ref, FormatContext& ctx) const auto format(std::reference_wrapper<T> ref, FormatContext& ctx) const
@ -723,5 +725,4 @@ struct formatter<std::reference_wrapper<T>, Char,
}; };
FMT_END_NAMESPACE FMT_END_NAMESPACE
#endif // FMT_STD_H_ #endif // FMT_STD_H_

View file

@ -55,16 +55,6 @@ inline auto write_loc(basic_appender<wchar_t> out, loc_value value,
#endif #endif
return false; return false;
} }
template <typename Char>
void vformat_to(buffer<Char>& buf, basic_string_view<Char> fmt,
basic_format_args<buffered_context<Char>> args,
locale_ref loc = {}) {
static_assert(!std::is_same<Char, char>::value, "");
auto out = basic_appender<Char>(buf);
parse_format_string(
fmt, format_handler<Char>{parse_context<Char>(fmt), {out, args, loc}});
}
} // namespace detail } // namespace detail
FMT_BEGIN_EXPORT FMT_BEGIN_EXPORT
@ -122,6 +112,10 @@ inline auto runtime(wstring_view s) -> runtime_format_string<wchar_t> {
return {{s}}; return {{s}};
} }
#ifdef __cpp_char8_t
template <> struct is_char<char8_t> : bool_constant<detail::is_utf8_enabled> {};
#endif
template <typename... T> template <typename... T>
constexpr auto make_wformat_args(T&... args) constexpr auto make_wformat_args(T&... args)
-> decltype(fmt::make_format_args<wformat_context>(args...)) { -> decltype(fmt::make_format_args<wformat_context>(args...)) {
@ -157,13 +151,13 @@ auto join(std::initializer_list<T> list, wstring_view sep)
template <typename Tuple, FMT_ENABLE_IF(is_tuple_like<Tuple>::value)> template <typename Tuple, FMT_ENABLE_IF(is_tuple_like<Tuple>::value)>
auto join(const Tuple& tuple, basic_string_view<wchar_t> sep) auto join(const Tuple& tuple, basic_string_view<wchar_t> sep)
-> tuple_join_view<Tuple, wchar_t> { -> tuple_join_view<wchar_t, Tuple> {
return {tuple, sep}; return {tuple, sep};
} }
template <typename Char, FMT_ENABLE_IF(!std::is_same<Char, char>::value)> template <typename Char, FMT_ENABLE_IF(!std::is_same<Char, char>::value)>
auto vformat(basic_string_view<Char> fmt, auto vformat(basic_string_view<Char> fmt,
basic_format_args<buffered_context<Char>> args) typename detail::vformat_args<Char>::type args)
-> std::basic_string<Char> { -> std::basic_string<Char> {
auto buf = basic_memory_buffer<Char>(); auto buf = basic_memory_buffer<Char>();
detail::vformat_to(buf, fmt, args); detail::vformat_to(buf, fmt, args);
@ -193,20 +187,24 @@ auto format(const S& fmt, T&&... args) -> std::basic_string<Char> {
fmt::make_format_args<buffered_context<Char>>(args...)); fmt::make_format_args<buffered_context<Char>>(args...));
} }
template <typename S, typename Char = detail::format_string_char_t<S>, template <typename Locale, typename S,
FMT_ENABLE_IF(detail::is_exotic_char<Char>::value)> typename Char = detail::format_string_char_t<S>,
inline auto vformat(locale_ref loc, const S& fmt, FMT_ENABLE_IF(detail::is_locale<Locale>::value&&
basic_format_args<buffered_context<Char>> args) detail::is_exotic_char<Char>::value)>
inline auto vformat(const Locale& loc, const S& fmt,
typename detail::vformat_args<Char>::type args)
-> std::basic_string<Char> { -> std::basic_string<Char> {
auto buf = basic_memory_buffer<Char>(); auto buf = basic_memory_buffer<Char>();
detail::vformat_to(buf, detail::to_string_view(fmt), args, loc); detail::vformat_to(buf, detail::to_string_view(fmt), args,
detail::locale_ref(loc));
return {buf.data(), buf.size()}; return {buf.data(), buf.size()};
} }
template <typename S, typename... T, template <typename Locale, typename S, typename... T,
typename Char = detail::format_string_char_t<S>, typename Char = detail::format_string_char_t<S>,
FMT_ENABLE_IF(detail::is_exotic_char<Char>::value)> FMT_ENABLE_IF(detail::is_locale<Locale>::value&&
inline auto format(locale_ref loc, const S& fmt, T&&... args) detail::is_exotic_char<Char>::value)>
inline auto format(const Locale& loc, const S& fmt, T&&... args)
-> std::basic_string<Char> { -> std::basic_string<Char> {
return vformat(loc, detail::to_string_view(fmt), return vformat(loc, detail::to_string_view(fmt),
fmt::make_format_args<buffered_context<Char>>(args...)); fmt::make_format_args<buffered_context<Char>>(args...));
@ -217,7 +215,7 @@ template <typename OutputIt, typename S,
FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value&& FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value&&
detail::is_exotic_char<Char>::value)> detail::is_exotic_char<Char>::value)>
auto vformat_to(OutputIt out, const S& fmt, auto vformat_to(OutputIt out, const S& fmt,
basic_format_args<buffered_context<Char>> args) -> OutputIt { typename detail::vformat_args<Char>::type args) -> OutputIt {
auto&& buf = detail::get_buffer<Char>(out); auto&& buf = detail::get_buffer<Char>(out);
detail::vformat_to(buf, detail::to_string_view(fmt), args); detail::vformat_to(buf, detail::to_string_view(fmt), args);
return detail::get_iterator(buf, out); return detail::get_iterator(buf, out);
@ -233,24 +231,27 @@ inline auto format_to(OutputIt out, const S& fmt, T&&... args) -> OutputIt {
fmt::make_format_args<buffered_context<Char>>(args...)); fmt::make_format_args<buffered_context<Char>>(args...));
} }
template <typename S, typename OutputIt, typename... Args, template <typename Locale, typename S, typename OutputIt, typename... Args,
typename Char = detail::format_string_char_t<S>, typename Char = detail::format_string_char_t<S>,
FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value&& FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value&&
detail::is_locale<Locale>::value&&
detail::is_exotic_char<Char>::value)> detail::is_exotic_char<Char>::value)>
inline auto vformat_to(OutputIt out, locale_ref loc, const S& fmt, inline auto vformat_to(OutputIt out, const Locale& loc, const S& fmt,
basic_format_args<buffered_context<Char>> args) typename detail::vformat_args<Char>::type args)
-> OutputIt { -> OutputIt {
auto&& buf = detail::get_buffer<Char>(out); auto&& buf = detail::get_buffer<Char>(out);
vformat_to(buf, detail::to_string_view(fmt), args, loc); vformat_to(buf, detail::to_string_view(fmt), args, detail::locale_ref(loc));
return detail::get_iterator(buf, out); return detail::get_iterator(buf, out);
} }
template <typename OutputIt, typename S, typename... T, template <typename Locale, typename OutputIt, typename S, typename... T,
typename Char = detail::format_string_char_t<S>, typename Char = detail::format_string_char_t<S>,
bool enable = detail::is_output_iterator<OutputIt, Char>::value && bool enable = detail::is_output_iterator<OutputIt, Char>::value &&
detail::is_locale<Locale>::value &&
detail::is_exotic_char<Char>::value> detail::is_exotic_char<Char>::value>
inline auto format_to(OutputIt out, locale_ref loc, const S& fmt, T&&... args) inline auto format_to(OutputIt out, const Locale& loc, const S& fmt,
-> typename std::enable_if<enable, OutputIt>::type { T&&... args) ->
typename std::enable_if<enable, OutputIt>::type {
return vformat_to(out, loc, detail::to_string_view(fmt), return vformat_to(out, loc, detail::to_string_view(fmt),
fmt::make_format_args<buffered_context<Char>>(args...)); fmt::make_format_args<buffered_context<Char>>(args...));
} }
@ -259,7 +260,7 @@ template <typename OutputIt, typename Char, typename... Args,
FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value&& FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value&&
detail::is_exotic_char<Char>::value)> detail::is_exotic_char<Char>::value)>
inline auto vformat_to_n(OutputIt out, size_t n, basic_string_view<Char> fmt, inline auto vformat_to_n(OutputIt out, size_t n, basic_string_view<Char> fmt,
basic_format_args<buffered_context<Char>> args) typename detail::vformat_args<Char>::type args)
-> format_to_n_result<OutputIt> { -> format_to_n_result<OutputIt> {
using traits = detail::fixed_buffer_traits; using traits = detail::fixed_buffer_traits;
auto buf = detail::iterator_buffer<OutputIt, Char, traits>(out, n); auto buf = detail::iterator_buffer<OutputIt, Char, traits>(out, n);
@ -330,6 +331,18 @@ inline auto format(text_style ts, wformat_string<T...> fmt, T&&... args)
return fmt::vformat(ts, fmt, fmt::make_wformat_args(args...)); return fmt::vformat(ts, fmt, fmt::make_wformat_args(args...));
} }
template <typename... T>
FMT_DEPRECATED void print(std::FILE* f, text_style ts, wformat_string<T...> fmt,
const T&... args) {
vprint(f, ts, fmt, fmt::make_wformat_args(args...));
}
template <typename... T>
FMT_DEPRECATED void print(text_style ts, wformat_string<T...> fmt,
const T&... args) {
return print(stdout, ts, fmt, args...);
}
inline void vprint(std::wostream& os, wstring_view fmt, wformat_args args) { inline void vprint(std::wostream& os, wstring_view fmt, wformat_args args) {
auto buffer = basic_memory_buffer<wchar_t>(); auto buffer = basic_memory_buffer<wchar_t>();
detail::vformat_to(buffer, fmt, args); detail::vformat_to(buffer, fmt, args);

View file

@ -14,6 +14,7 @@
#include "fuse_kernel.h" #include "fuse_kernel.h"
#include "fuse_req_ctx.h" #include "fuse_req_ctx.h"
#include <fcntl.h>
#include <time.h> #include <time.h>
#include <utime.h> #include <utime.h>
#include <sys/types.h> #include <sys/types.h>
@ -28,16 +29,6 @@ EXTERN_C_BEGIN
* Basic FUSE API * * Basic FUSE API *
* ----------------------------------------------------------- */ * ----------------------------------------------------------- */
#define INVALID_BACKING_ID (0)
static
inline
int
fuse_backing_id_is_valid(const int backing_id_)
{
return (backing_id_ > INVALID_BACKING_ID);
}
struct fuse_dirents_t; struct fuse_dirents_t;
typedef struct fuse_dirents_t fuse_dirents_t; typedef struct fuse_dirents_t fuse_dirents_t;
@ -69,7 +60,7 @@ struct fuse_operations
const char *, const char *,
struct stat *, struct stat *,
fuse_timeouts_t *); fuse_timeouts_t *);
ssize_t (*readlink)(const fuse_req_ctx_t *, int (*readlink)(const fuse_req_ctx_t *,
const char *, const char *,
char *, char *,
size_t); size_t);
@ -159,7 +150,7 @@ struct fuse_operations
int (*fsyncdir)(const fuse_req_ctx_t *, int (*fsyncdir)(const fuse_req_ctx_t *,
const fuse_file_info_t *, const fuse_file_info_t *,
int); int);
void *(*init)(fuse_conn_info_t *conn); void *(*init)(struct fuse_conn_info *conn);
void (*destroy)(void); void (*destroy)(void);
int (*access)(const fuse_req_ctx_t *, int (*access)(const fuse_req_ctx_t *,
const char *, const char *,
@ -171,22 +162,14 @@ struct fuse_operations
int (*ftruncate)(const fuse_req_ctx_t *, int (*ftruncate)(const fuse_req_ctx_t *,
const uint64_t, const uint64_t,
off_t); off_t);
// libfuse calls the fh based ops (fgetattr, statx_fh, fchmod,
// fchown, ftruncate, futimens) with fh=0 when the node has no path,
// so the filesystem can use a file it has open for ctx->nodeid.
// With none the node was removed (unlink, rmdir, rename over it)
// while the kernel still held it: a dirfd, a cwd, an O_PATH fd, or
// a dentry resolved just before the removal. Return ENOENT, not
// EBADF, as the caller may not have used a descriptor at all: the
// kernel sends GETATTR in permission checks of path walks too.
// ENOENT is what a local filesystem gives *at() calls in a removed
// directory, and what rm -f ignores. ESTALE would make the kernel
// redo the lookup, but a call through a dirfd or cwd of a removed
// directory meets the same node again and gets ESTALE. See #1693.
int (*fgetattr)(const fuse_req_ctx_t *, int (*fgetattr)(const fuse_req_ctx_t *,
const uint64_t, const uint64_t,
struct stat *, struct stat *,
fuse_timeouts_t *); fuse_timeouts_t *);
int (*lock)(const fuse_req_ctx_t *,
const fuse_file_info_t *,
int cmd,
struct flock *);
int (*utimens)(const fuse_req_ctx_t *, int (*utimens)(const fuse_req_ctx_t *,
const char *, const char *,
const struct timespec tv[2]); const struct timespec tv[2]);
@ -218,6 +201,9 @@ struct fuse_operations
char *buf, char *buf,
size_t size, size_t size,
off_t off); off_t off);
int (*flock)(const fuse_req_ctx_t *,
const fuse_file_info_t *,
int op);
int (*fallocate)(const fuse_req_ctx_t *, int (*fallocate)(const fuse_req_ctx_t *,
const uint64_t, const uint64_t,
int, int,
@ -287,14 +273,12 @@ struct fuse_operations
* Create a new FUSE filesystem. * Create a new FUSE filesystem.
* *
* @param ch the communication channel * @param ch the communication channel
* @param fd the /dev/fuse file descriptor
* @param bufsize the buffer size for FUSE communication
* @param args argument vector * @param args argument vector
* @param op the filesystem operations * @param op the filesystem operations
* @param op_size the size of the fuse_operations structure
* @return the created FUSE handle * @return the created FUSE handle
*/ */
struct fuse *fuse_new(int fd, struct fuse *fuse_new(struct fuse_chan *ch,
size_t bufsize,
struct fuse_args *args, struct fuse_args *args,
const struct fuse_operations *op); const struct fuse_operations *op);
@ -375,14 +359,18 @@ int fuse_main(int argc,
void fuse_populate_maintenance_thread(struct fuse *fuse); void fuse_populate_maintenance_thread(struct fuse *fuse);
int fuse_log_metrics_get(void);
void fuse_log_metrics_set(int enabled);
/** /**
* Legacy cache cleanup entry point. * Iterate over cache removing stale entries
* use in conjunction with "-oremember"
* *
* NOTE: This is already done for the standard sessions * NOTE: This is already done for the standard sessions
* *
* @param fuse struct fuse pointer for fuse instance * @param fuse struct fuse pointer for fuse instance
* @return 0 * @return the number of seconds until the next cleanup
*/ */
int fuse_clean_cache(struct fuse *fuse); int fuse_clean_cache(struct fuse *fuse);

View file

@ -1,11 +1,8 @@
#pragma once #pragma once
#include "base_types.h" #include "int_types.h"
#include <climits> #include <climits>
#include <cstdio>
#include <memory>
#include <shared_mutex>
#include <string> #include <string>
#define FUSE_CFG_INVALID_ID -1 #define FUSE_CFG_INVALID_ID -1
@ -14,9 +11,6 @@
struct fuse_cfg_t struct fuse_cfg_t
{ {
template<typename T>
using sp = std::shared_ptr<T>;
s64 uid = FUSE_CFG_INVALID_ID; s64 uid = FUSE_CFG_INVALID_ID;
bool valid_uid() const; bool valid_uid() const;
@ -26,19 +20,10 @@ struct fuse_cfg_t
s64 umask = FUSE_CFG_INVALID_UMASK; s64 umask = FUSE_CFG_INVALID_UMASK;
bool valid_umask() const; bool valid_umask() const;
bool remember_nodes = false; s64 remember_nodes = 0;
bool debug = false; bool debug = false;
std::shared_ptr<FILE> log_file() const;
void log_file(std::shared_ptr<FILE>);
std::shared_ptr<std::string> log_filepath() const;
void log_filepath(const std::string &);
private:
mutable std::shared_mutex _log_mutex;
std::shared_ptr<FILE> _log_file = sp<FILE>(stderr,[](FILE*){});
std::shared_ptr<std::string> _log_filepath = sp<std::string>();
public:
int max_background = 0; int max_background = 0;
int congestion_threshold = 0; int congestion_threshold = 0;
u32 max_pages = 32; u32 max_pages = 32;
@ -48,8 +33,6 @@ public:
int process_thread_count = -1; int process_thread_count = -1;
int process_thread_queue_depth = 2; int process_thread_queue_depth = 2;
std::string pin_threads = "false"; std::string pin_threads = "false";
u16 request_timeout = 0;
}; };
extern fuse_cfg_t fuse_cfg; extern fuse_cfg_t fuse_cfg;

View file

@ -1,7 +1,6 @@
#pragma once #pragma once
#include "extern_c.h" #include "extern_c.h"
#include "fuse_conn_info.hpp"
#include "fuse_opt.h" #include "fuse_opt.h"
#include "fuse_timeouts.h" #include "fuse_timeouts.h"
@ -77,7 +76,7 @@ struct fuse_file_info_t
}; };
/** /**
* Capability bits for 'fuse_conn_info_t.capable' and 'fuse_conn_info_t.want' * Capability bits for 'fuse_conn_info.capable' and 'fuse_conn_info.want'
* *
* FUSE_CAP_ASYNC_READ: filesystem supports asynchronous read requests * FUSE_CAP_ASYNC_READ: filesystem supports asynchronous read requests
* FUSE_CAP_POSIX_LOCKS: filesystem supports "remote" locking * FUSE_CAP_POSIX_LOCKS: filesystem supports "remote" locking
@ -129,30 +128,46 @@ struct fuse_file_info_t
#define FUSE_IOCTL_MAX_IOV 256 #define FUSE_IOCTL_MAX_IOV 256
/**
* Connection information, passed to the ->init() method
*
* Some of the elements are read-write, these can be changed to
* indicate the value requested by the filesystem. The requested
* value must usually be smaller than the indicated value.
*/
struct fuse_conn_info
{
unsigned proto_major;
unsigned proto_minor;
uint64_t capable;
uint64_t want;
};
struct fuse_session; struct fuse_session;
struct fuse_chan; struct fuse_chan;
struct fuse_pollhandle_t; struct fuse_pollhandle_t;
typedef struct fuse_pollhandle_t fuse_pollhandle_t; typedef struct fuse_pollhandle_t fuse_pollhandle_t;
/** /**
* Mount a FUSE filesystem. * Create a FUSE mountpoint
* *
* This function creates a FUSE mount and returns the /dev/fuse file descriptor. * Returns a control file descriptor suitable for passing to
* The file descriptor is stored in the session for internal use. * fuse_new()
* *
* @param mountpoint the mount point path * @param mountpoint the mount point path
* @param args argument vector * @param args argument vector
* @return the /dev/fuse file descriptor on success, -1 on failure * @return the communication channel on success, NULL on failure
*/ */
int fuse_mount(const char *mountpoint, struct fuse_args *args); struct fuse_chan *fuse_mount(const char *mountpoint,
struct fuse_args *args);
/** /**
* Umount a FUSE mountpoint * Umount a FUSE mountpoint
* *
* @param mountpoint the mount point path * @param mountpoint the mount point path
* @param fd the /dev/fuse file descriptor (or -1 if already closed) * @param ch the communication channel
*/ */
void fuse_unmount(const char *mountpoint, int fd); void fuse_unmount(const char *mountpoint, struct fuse_chan *ch);
/** /**
* Parse common options * Parse common options

View file

@ -229,17 +229,6 @@
* - FUSE_URING_IN_OUT_HEADER_SZ * - FUSE_URING_IN_OUT_HEADER_SZ
* - FUSE_URING_OP_IN_OUT_SZ * - FUSE_URING_OP_IN_OUT_SZ
* - enum fuse_uring_cmd * - enum fuse_uring_cmd
*
* 7.43
* - add FUSE_REQUEST_TIMEOUT
*
* 7.44
* - add FUSE_NOTIFY_INC_EPOCH
*
* 7.45
* - add FUSE_COPY_FILE_RANGE_64
* - add struct fuse_copy_file_range_out
* - add FUSE_NOTIFY_PRUNE
*/ */
#ifndef _LINUX_FUSE_H #ifndef _LINUX_FUSE_H
@ -275,7 +264,7 @@
#define FUSE_KERNEL_VERSION 7 #define FUSE_KERNEL_VERSION 7
/** Minor version number of this interface */ /** Minor version number of this interface */
#define FUSE_KERNEL_MINOR_VERSION 45 #define FUSE_KERNEL_MINOR_VERSION 42
/** The node ID of the root inode */ /** The node ID of the root inode */
#define FUSE_ROOT_ID 1 #define FUSE_ROOT_ID 1
@ -446,41 +435,39 @@ struct fuse_file_lock {
* of the request ID indicates resend requests * of the request ID indicates resend requests
* FUSE_ALLOW_IDMAP: allow creation of idmapped mounts * FUSE_ALLOW_IDMAP: allow creation of idmapped mounts
* FUSE_OVER_IO_URING: Indicate that client supports io-uring * FUSE_OVER_IO_URING: Indicate that client supports io-uring
* FUSE_REQUEST_TIMEOUT: kernel supports timing out requests.
* init_out.request_timeout contains the timeout (in secs)
*/ */
#define FUSE_ASYNC_READ (1 << 0) #define FUSE_ASYNC_READ (1ULL << 0)
#define FUSE_POSIX_LOCKS (1 << 1) #define FUSE_POSIX_LOCKS (1ULL << 1)
#define FUSE_FILE_OPS (1 << 2) #define FUSE_FILE_OPS (1ULL << 2)
#define FUSE_ATOMIC_O_TRUNC (1 << 3) #define FUSE_ATOMIC_O_TRUNC (1ULL << 3)
#define FUSE_EXPORT_SUPPORT (1 << 4) #define FUSE_EXPORT_SUPPORT (1ULL << 4)
#define FUSE_BIG_WRITES (1 << 5) #define FUSE_BIG_WRITES (1ULL << 5)
#define FUSE_DONT_MASK (1 << 6) #define FUSE_DONT_MASK (1ULL << 6)
#define FUSE_SPLICE_WRITE (1 << 7) #define FUSE_SPLICE_WRITE (1ULL << 7)
#define FUSE_SPLICE_MOVE (1 << 8) #define FUSE_SPLICE_MOVE (1ULL << 8)
#define FUSE_SPLICE_READ (1 << 9) #define FUSE_SPLICE_READ (1ULL << 9)
#define FUSE_FLOCK_LOCKS (1 << 10) #define FUSE_FLOCK_LOCKS (1ULL << 10)
#define FUSE_HAS_IOCTL_DIR (1 << 11) #define FUSE_HAS_IOCTL_DIR (1ULL << 11)
#define FUSE_AUTO_INVAL_DATA (1 << 12) #define FUSE_AUTO_INVAL_DATA (1ULL << 12)
#define FUSE_DO_READDIRPLUS (1 << 13) #define FUSE_DO_READDIRPLUS (1ULL << 13)
#define FUSE_READDIRPLUS_AUTO (1 << 14) #define FUSE_READDIRPLUS_AUTO (1ULL << 14)
#define FUSE_ASYNC_DIO (1 << 15) #define FUSE_ASYNC_DIO (1ULL << 15)
#define FUSE_WRITEBACK_CACHE (1 << 16) #define FUSE_WRITEBACK_CACHE (1ULL << 16)
#define FUSE_NO_OPEN_SUPPORT (1 << 17) #define FUSE_NO_OPEN_SUPPORT (1ULL << 17)
#define FUSE_PARALLEL_DIROPS (1 << 18) #define FUSE_PARALLEL_DIROPS (1ULL << 18)
#define FUSE_HANDLE_KILLPRIV (1 << 19) #define FUSE_HANDLE_KILLPRIV (1ULL << 19)
#define FUSE_POSIX_ACL (1 << 20) #define FUSE_POSIX_ACL (1ULL << 20)
#define FUSE_ABORT_ERROR (1 << 21) #define FUSE_ABORT_ERROR (1ULL << 21)
#define FUSE_MAX_PAGES (1 << 22) #define FUSE_MAX_PAGES (1ULL << 22)
#define FUSE_CACHE_SYMLINKS (1 << 23) #define FUSE_CACHE_SYMLINKS (1ULL << 23)
#define FUSE_NO_OPENDIR_SUPPORT (1 << 24) #define FUSE_NO_OPENDIR_SUPPORT (1ULL << 24)
#define FUSE_EXPLICIT_INVAL_DATA (1 << 25) #define FUSE_EXPLICIT_INVAL_DATA (1ULL << 25)
#define FUSE_MAP_ALIGNMENT (1 << 26) #define FUSE_MAP_ALIGNMENT (1ULL << 26)
#define FUSE_SUBMOUNTS (1 << 27) #define FUSE_SUBMOUNTS (1ULL << 27)
#define FUSE_HANDLE_KILLPRIV_V2 (1 << 28) #define FUSE_HANDLE_KILLPRIV_V2 (1ULL << 28)
#define FUSE_SETXATTR_EXT (1 << 29) #define FUSE_SETXATTR_EXT (1ULL << 29)
#define FUSE_INIT_EXT (1 << 30) #define FUSE_INIT_EXT (1ULL << 30)
#define FUSE_INIT_RESERVED (1U << 31) #define FUSE_INIT_RESERVED (1ULL << 31)
/* bits 32..63 get shifted down 32 bits into the flags2 field */ /* bits 32..63 get shifted down 32 bits into the flags2 field */
#define FUSE_SECURITY_CTX (1ULL << 32) #define FUSE_SECURITY_CTX (1ULL << 32)
#define FUSE_HAS_INODE_DAX (1ULL << 33) #define FUSE_HAS_INODE_DAX (1ULL << 33)
@ -490,11 +477,11 @@ struct fuse_file_lock {
#define FUSE_PASSTHROUGH (1ULL << 37) #define FUSE_PASSTHROUGH (1ULL << 37)
#define FUSE_NO_EXPORT_SUPPORT (1ULL << 38) #define FUSE_NO_EXPORT_SUPPORT (1ULL << 38)
#define FUSE_HAS_RESEND (1ULL << 39) #define FUSE_HAS_RESEND (1ULL << 39)
/* Obsolete alias for FUSE_DIRECT_IO_ALLOW_MMAP */ /* Obsolete alias for FUSE_DIRECT_IO_ALLOW_MMAP */
#define FUSE_DIRECT_IO_RELAX FUSE_DIRECT_IO_ALLOW_MMAP #define FUSE_DIRECT_IO_RELAX FUSE_DIRECT_IO_ALLOW_MMAP
#define FUSE_ALLOW_IDMAP (1ULL << 40) #define FUSE_ALLOW_IDMAP (1ULL << 40)
#define FUSE_OVER_IO_URING (1ULL << 41) #define FUSE_OVER_IO_URING (1ULL << 41)
#define FUSE_REQUEST_TIMEOUT (1ULL << 42)
/** /**
* CUSE INIT request/reply flags * CUSE INIT request/reply flags
@ -662,7 +649,6 @@ enum fuse_opcode {
FUSE_SYNCFS = 50, FUSE_SYNCFS = 50,
FUSE_TMPFILE = 51, FUSE_TMPFILE = 51,
FUSE_STATX = 52, FUSE_STATX = 52,
FUSE_COPY_FILE_RANGE_64 = 53,
/* CUSE specific operations */ /* CUSE specific operations */
CUSE_INIT = 4096, CUSE_INIT = 4096,
@ -680,8 +666,7 @@ enum fuse_notify_code {
FUSE_NOTIFY_RETRIEVE = 5, FUSE_NOTIFY_RETRIEVE = 5,
FUSE_NOTIFY_DELETE = 6, FUSE_NOTIFY_DELETE = 6,
FUSE_NOTIFY_RESEND = 7, FUSE_NOTIFY_RESEND = 7,
FUSE_NOTIFY_INC_EPOCH = 8, FUSE_NOTIFY_CODE_MAX,
FUSE_NOTIFY_PRUNE = 9,
}; };
/* The read buffer is required to be at least 8k, but may be much larger */ /* The read buffer is required to be at least 8k, but may be much larger */
@ -924,8 +909,7 @@ struct fuse_init_out {
uint16_t map_alignment; uint16_t map_alignment;
uint32_t flags2; uint32_t flags2;
uint32_t max_stack_depth; uint32_t max_stack_depth;
uint16_t request_timeout; uint32_t unused[6];
uint16_t unused[11];
}; };
#define CUSE_INIT_INFO_MAX 4096 #define CUSE_INIT_INFO_MAX 4096
@ -1120,12 +1104,6 @@ struct fuse_notify_retrieve_in {
uint64_t dummy4; uint64_t dummy4;
}; };
struct fuse_notify_prune_out {
uint32_t count;
uint32_t padding;
uint64_t spare;
};
struct fuse_backing_map { struct fuse_backing_map {
int32_t fd; int32_t fd;
uint32_t flags; uint32_t flags;
@ -1138,7 +1116,6 @@ struct fuse_backing_map {
#define FUSE_DEV_IOC_BACKING_OPEN _IOW(FUSE_DEV_IOC_MAGIC, 1, \ #define FUSE_DEV_IOC_BACKING_OPEN _IOW(FUSE_DEV_IOC_MAGIC, 1, \
struct fuse_backing_map) struct fuse_backing_map)
#define FUSE_DEV_IOC_BACKING_CLOSE _IOW(FUSE_DEV_IOC_MAGIC, 2, uint32_t) #define FUSE_DEV_IOC_BACKING_CLOSE _IOW(FUSE_DEV_IOC_MAGIC, 2, uint32_t)
#define FUSE_DEV_IOC_SYNC_INIT _IO(FUSE_DEV_IOC_MAGIC, 3)
struct fuse_lseek_in { struct fuse_lseek_in {
uint64_t fh; uint64_t fh;
@ -1161,11 +1138,6 @@ struct fuse_copy_file_range_in {
uint64_t flags; uint64_t flags;
}; };
/* For FUSE_COPY_FILE_RANGE_64 */
struct fuse_copy_file_range_out {
uint64_t bytes_copied;
};
#define FUSE_SETUPMAPPING_FLAG_WRITE (1ull << 0) #define FUSE_SETUPMAPPING_FLAG_WRITE (1ull << 0)
#define FUSE_SETUPMAPPING_FLAG_READ (1ull << 1) #define FUSE_SETUPMAPPING_FLAG_READ (1ull << 1)
struct fuse_setupmapping_in { struct fuse_setupmapping_in {

View file

@ -3,8 +3,9 @@
#include "extern_c.h" #include "extern_c.h"
#include "fuse_common.h" #include "fuse_common.h"
#include "fuse_kernel.h" #include "fuse_kernel.h"
#include "fuse_req.hpp" #include "fuse_req.h"
#include <fcntl.h>
#include <stdint.h> #include <stdint.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <sys/statvfs.h> #include <sys/statvfs.h>
@ -28,7 +29,13 @@ EXTERN_C_BEGIN
*/ */
struct fuse_session; struct fuse_session;
/**
* Channel
*
* A communication channel, providing hooks for sending and receiving
* messages
*/
struct fuse_chan;
/** Directory entry parameters supplied to fuse_reply_entry() */ /** Directory entry parameters supplied to fuse_reply_entry() */
struct fuse_entry_param struct fuse_entry_param
@ -101,16 +108,18 @@ struct fuse_lowlevel_ops
void (*bmap)(fuse_req_t *req, const struct fuse_in_header *hdr); void (*bmap)(fuse_req_t *req, const struct fuse_in_header *hdr);
void (*copy_file_range)(fuse_req_t *req, const struct fuse_in_header *hdr); void (*copy_file_range)(fuse_req_t *req, const struct fuse_in_header *hdr);
void (*create)(fuse_req_t *req, struct fuse_in_header *hdr); void (*create)(fuse_req_t *req, struct fuse_in_header *hdr);
void (*destroy)(); void (*destroy)(void *userdata);
void (*fallocate)(fuse_req_t *req, const struct fuse_in_header *hdr); void (*fallocate)(fuse_req_t *req, const struct fuse_in_header *hdr);
void (*flock)(fuse_req_t *req, uint64_t ino, fuse_file_info_t *fi, int op);
void (*flush)(fuse_req_t *req, struct fuse_in_header *hdr); void (*flush)(fuse_req_t *req, struct fuse_in_header *hdr);
void (*forget)(fuse_req_t *req, struct fuse_in_header *hdr); void (*forget)(fuse_req_t *req, struct fuse_in_header *hdr);
void (*forget_multi)(fuse_req_t *req, struct fuse_in_header *hdr); void (*forget_multi)(fuse_req_t *req, struct fuse_in_header *hdr);
void (*fsync)(fuse_req_t *req, struct fuse_in_header *hdr); void (*fsync)(fuse_req_t *req, struct fuse_in_header *hdr);
void (*fsyncdir)(fuse_req_t *req, struct fuse_in_header *hdr); void (*fsyncdir)(fuse_req_t *req, struct fuse_in_header *hdr);
void (*getattr)(fuse_req_t *req, struct fuse_in_header *hdr); void (*getattr)(fuse_req_t *req, struct fuse_in_header *hdr);
void (*getlk)(fuse_req_t *req, const struct fuse_in_header *hdr);
void (*getxattr)(fuse_req_t *req, struct fuse_in_header *hdr); void (*getxattr)(fuse_req_t *req, struct fuse_in_header *hdr);
void (*init)(fuse_conn_info_t *conn); void (*init)(void *userdata, struct fuse_conn_info *conn);
void (*ioctl)(fuse_req_t *req, const struct fuse_in_header *hdr); void (*ioctl)(fuse_req_t *req, const struct fuse_in_header *hdr);
void (*link)(fuse_req_t *req, struct fuse_in_header *hdr); void (*link)(fuse_req_t *req, struct fuse_in_header *hdr);
void (*listxattr)(fuse_req_t *req, struct fuse_in_header *hdr); void (*listxattr)(fuse_req_t *req, struct fuse_in_header *hdr);
@ -134,6 +143,7 @@ struct fuse_lowlevel_ops
void (*retrieve_reply)(fuse_req_t *req, void *cookie, uint64_t ino, off_t offset); void (*retrieve_reply)(fuse_req_t *req, void *cookie, uint64_t ino, off_t offset);
void (*rmdir)(fuse_req_t *req, struct fuse_in_header *hdr); void (*rmdir)(fuse_req_t *req, struct fuse_in_header *hdr);
void (*setattr)(fuse_req_t *req, struct fuse_in_header *hdr); void (*setattr)(fuse_req_t *req, struct fuse_in_header *hdr);
void (*setlk)(fuse_req_t *req, uint64_t ino, fuse_file_info_t *fi, struct flock *lock, int sleep);
void (*setupmapping)(fuse_req_t *req, const struct fuse_in_header *hdr); void (*setupmapping)(fuse_req_t *req, const struct fuse_in_header *hdr);
void (*setxattr)(fuse_req_t *req, struct fuse_in_header *hdr); void (*setxattr)(fuse_req_t *req, struct fuse_in_header *hdr);
void (*statfs)(fuse_req_t *req, struct fuse_in_header *hdr); void (*statfs)(fuse_req_t *req, struct fuse_in_header *hdr);
@ -152,7 +162,7 @@ struct fuse_lowlevel_ops
* all except forget * all except forget
* *
* unlink, rmdir, rename, flush, release, fsync, fsyncdir, setxattr, * unlink, rmdir, rename, flush, release, fsync, fsyncdir, setxattr,
* removexattr may send a zero code * removexattr and setlk may send a zero code
* *
* @param req request handle * @param req request handle
* @param err the positive error value, or zero for success * @param err the positive error value, or zero for success
@ -237,9 +247,7 @@ int fuse_reply_statx(fuse_req_t *req,
* @param link symbolic link contents * @param link symbolic link contents
* @return zero for success, -errno for failure to send reply * @return zero for success, -errno for failure to send reply
*/ */
int fuse_reply_readlink(fuse_req_t *req, int fuse_reply_readlink(fuse_req_t *req, const char *link);
const char *linkname,
const size_t linkname_len);
/** /**
* Reply with open parameters * Reply with open parameters
@ -269,8 +277,6 @@ int fuse_reply_open(fuse_req_t *req,
*/ */
int fuse_reply_write(fuse_req_t *req, size_t count); int fuse_reply_write(fuse_req_t *req, size_t count);
int fuse_reply_copy_file_range_64(fuse_req_t *req, size_t count);
/** /**
* Reply with data * Reply with data
* *
@ -325,6 +331,18 @@ int fuse_reply_statfs(fuse_req_t *req, const struct statvfs *stbuf);
*/ */
int fuse_reply_xattr(fuse_req_t *req, size_t count); int fuse_reply_xattr(fuse_req_t *req, size_t count);
/**
* Reply with file lock information
*
* Possible requests:
* getlk
*
* @param req request handle
* @param lock the lock information
* @return zero for success, -errno for failure to send reply
*/
int fuse_reply_lock(fuse_req_t *req, const struct flock *lock);
/** /**
* Reply with block index * Reply with block index
* *
@ -369,6 +387,20 @@ int fuse_reply_ioctl_retry(fuse_req_t *req,
*/ */
int fuse_reply_ioctl(fuse_req_t *req, int result, const void *buf, uint32_t size); int fuse_reply_ioctl(fuse_req_t *req, int result, const void *buf, uint32_t size);
/**
* Reply to finish ioctl with iov buffer
*
* Possible requests:
* ioctl
*
* @param req request handle
* @param result result to be passed to the caller
* @param iov the vector containing the data
* @param count the size of vector
*/
int fuse_reply_ioctl_iov(fuse_req_t *req, int result, const struct iovec *iov,
int count);
/** /**
* Reply with poll result event mask * Reply with poll result event mask
* *
@ -393,14 +425,14 @@ int fuse_lowlevel_notify_poll(fuse_pollhandle_t *ph);
/** /**
* Notify to invalidate cache for an inode * Notify to invalidate cache for an inode
* *
* @param se the session through which to send the invalidation * @param ch the channel through which to send the invalidation
* @param ino the inode number * @param ino the inode number
* @param off the offset in the inode where to start invalidating * @param off the offset in the inode where to start invalidating
* or negative to invalidate attributes only * or negative to invalidate attributes only
* @param len the amount of cache to invalidate or 0 for all * @param len the amount of cache to invalidate or 0 for all
* @return zero for success, -errno for failure * @return zero for success, -errno for failure
*/ */
int fuse_lowlevel_notify_inval_inode(struct fuse_session *se, uint64_t ino, int fuse_lowlevel_notify_inval_inode(struct fuse_chan *ch, uint64_t ino,
off_t off, off_t len); off_t off, off_t len);
/** /**
@ -411,13 +443,13 @@ int fuse_lowlevel_notify_inval_inode(struct fuse_session *se, uint64_t ino,
* don't call it with a lock held that can also be held by a filesystem * don't call it with a lock held that can also be held by a filesystem
* operation. * operation.
* *
* @param se the session through which to send the invalidation * @param ch the channel through which to send the invalidation
* @param parent inode number * @param parent inode number
* @param name file name * @param name file name
* @param namelen strlen() of file name * @param namelen strlen() of file name
* @return zero for success, -errno for failure * @return zero for success, -errno for failure
*/ */
int fuse_lowlevel_notify_inval_entry(struct fuse_session *se, uint64_t parent, int fuse_lowlevel_notify_inval_entry(struct fuse_chan *ch, uint64_t parent,
const char *name, size_t namelen); const char *name, size_t namelen);
/** /**
@ -429,14 +461,14 @@ int fuse_lowlevel_notify_inval_entry(struct fuse_session *se, uint64_t parent,
* don't call it with a lock held that can also be held by a filesystem * don't call it with a lock held that can also be held by a filesystem
* operation. * operation.
* *
* @param se the session through which to send the notification * @param ch the channel through which to send the notification
* @param parent inode number * @param parent inode number
* @param child inode number * @param child inode number
* @param name file name * @param name file name
* @param namelen strlen() of file name * @param namelen strlen() of file name
* @return zero for success, -errno for failure * @return zero for success, -errno for failure
*/ */
int fuse_lowlevel_notify_delete(struct fuse_session *se, int fuse_lowlevel_notify_delete(struct fuse_chan *ch,
uint64_t parent, uint64_t child, uint64_t parent, uint64_t child,
const char *name, size_t namelen); const char *name, size_t namelen);
@ -458,14 +490,14 @@ int fuse_lowlevel_notify_delete(struct fuse_session *se,
* buffer. For dirty pages the write() method will be called * buffer. For dirty pages the write() method will be called
* regardless of having been retrieved previously. * regardless of having been retrieved previously.
* *
* @param se the session through which to send the invalidation * @param ch the channel through which to send the invalidation
* @param ino the inode number * @param ino the inode number
* @param size the number of bytes to retrieve * @param size the number of bytes to retrieve
* @param offset the starting offset into the file to retrieve from * @param offset the starting offset into the file to retrieve from
* @param cookie user data to supply to the reply callback * @param cookie user data to supply to the reply callback
* @return zero for success, -errno for failure * @return zero for success, -errno for failure
*/ */
int fuse_lowlevel_notify_retrieve(struct fuse_session *se, uint64_t ino, int fuse_lowlevel_notify_retrieve(struct fuse_chan *ch, uint64_t ino,
size_t size, off_t offset, void *cookie); size_t size, off_t offset, void *cookie);
@ -507,11 +539,12 @@ int fuse_lowlevel_is_lib_option(const char *opt);
* @param args argument vector * @param args argument vector
* @param op the low level filesystem operations * @param op the low level filesystem operations
* @param op_size sizeof(struct fuse_lowlevel_ops) * @param op_size sizeof(struct fuse_lowlevel_ops)
* @param userdata user data
* @return the created session object, or NULL on failure * @return the created session object, or NULL on failure
*/ */
struct fuse_session *fuse_lowlevel_new(struct fuse_args *args, struct fuse_session *fuse_lowlevel_new(struct fuse_args *args,
const struct fuse_lowlevel_ops *op, const struct fuse_lowlevel_ops *op,
size_t op_size); size_t op_size, void *userdata);
/* ----------------------------------------------------------- * /* ----------------------------------------------------------- *
* Session interface * * Session interface *
@ -521,6 +554,8 @@ struct fuse_session *fuse_session_new(void *data,
void *receive_buf, void *receive_buf,
void *process_buf, void *process_buf,
void *destroy); void *destroy);
void fuse_session_add_chan(struct fuse_session *se, struct fuse_chan *ch);
void fuse_session_remove_chan(struct fuse_chan *ch);
void fuse_session_destroy(struct fuse_session *se); void fuse_session_destroy(struct fuse_session *se);
void fuse_session_exit(struct fuse_session *se); void fuse_session_exit(struct fuse_session *se);
int fuse_session_exited(struct fuse_session *se); int fuse_session_exited(struct fuse_session *se);
@ -538,12 +573,44 @@ int fuse_session_loop_mt(struct fuse_session *se,
const int process_thread_queue_depth, const int process_thread_queue_depth,
const char *pin_threads_type); const char *pin_threads_type);
/* Direct file descriptor and buffer size accessors /* ----------------------------------------------------------- *
* (channel fields inlined into session for single-mount simplicity) */ * Channel interface *
int fuse_session_fd(struct fuse_session *se); * ----------------------------------------------------------- */
size_t fuse_session_bufsize(struct fuse_session *se);
int fuse_session_clearfd(struct fuse_session *se); struct fuse_chan *fuse_chan_new(int fd, size_t bufsize);
void fuse_session_setfd(struct fuse_session *se, int fd);
void fuse_session_setbufsize(struct fuse_session *se, size_t bufsize); /**
* Query the file descriptor of the channel
*
* @param ch the channel
* @return the file descriptor passed to fuse_chan_new()
*/
int fuse_chan_fd(struct fuse_chan *ch);
/**
* Query the minimal receive buffer size
*
* @param ch the channel
* @return the buffer size passed to fuse_chan_new()
*/
size_t fuse_chan_bufsize(struct fuse_chan *ch);
/**
* Query the user data
*
* @param ch the channel
* @return the user data passed to fuse_chan_new()
*/
void *fuse_chan_data(struct fuse_chan *ch);
/**
* Query the session to which this channel is assigned
*
* @param ch the channel
* @return the session, or NULL if the channel is not assigned
*/
struct fuse_session *fuse_chan_session(struct fuse_chan *ch);
void fuse_chan_destroy(struct fuse_chan *ch);
EXTERN_C_END EXTERN_C_END

View file

@ -18,18 +18,19 @@
#pragma once #pragma once
#include "base_types.h" #include "int_types.h"
#include "fuse_msgbuf_t.h" #include "fuse_msgbuf_t.h"
u32 msgbuf_get_pagesize(); u32 msgbuf_get_pagesize();
void msgbuf_set_bufsize(const u64 size); void msgbuf_set_bufsize(const uint32_t size);
u64 msgbuf_get_bufsize(); uint64_t msgbuf_get_bufsize();
fuse_msgbuf_t *msgbuf_alloc(); fuse_msgbuf_t *msgbuf_alloc();
fuse_msgbuf_t *msgbuf_alloc_page_aligned(); fuse_msgbuf_t *msgbuf_alloc_page_aligned();
void msgbuf_free(fuse_msgbuf_t *msgbuf); void msgbuf_free(fuse_msgbuf_t *msgbuf);
void msgbuf_clear();
void msgbuf_gc(); void msgbuf_gc();
void msgbuf_gc_10percent();
u64 msgbuf_alloc_count(); uint64_t msgbuf_alloc_count();
uint64_t msgbuf_avail_count();

View file

@ -2,11 +2,13 @@
#include <stdint.h> #include <stdint.h>
struct fuse_session; struct fuse_chan;
struct fuse_ll;
typedef struct fuse_pollhandle_t fuse_pollhandle_t; typedef struct fuse_pollhandle_t fuse_pollhandle_t;
struct fuse_pollhandle_t struct fuse_pollhandle_t
{ {
uint64_t kh; uint64_t kh;
struct fuse_session *se; struct fuse_chan *ch;
struct fuse_ll *f;
}; };

View file

@ -0,0 +1,15 @@
#pragma once
#include "fuse_req_ctx.h"
struct fuse_ll;
struct fuse_chan;
typedef struct fuse_req_t fuse_req_t;
struct fuse_req_t
{
fuse_req_ctx_t ctx;
struct fuse_ll *f;
struct fuse_chan *ch;
unsigned int ioctl_64bit : 1;
};

View file

@ -0,0 +1,13 @@
#pragma once
#include <stdint.h>
typedef uint64_t u32;
typedef int64_t s32;
typedef uint64_t u64;
typedef int64_t s64;
typedef const uint64_t cu32;
typedef const int64_t cs32;
typedef const uint64_t cu64;
typedef const int64_t cs64;

View file

@ -1,7 +1,5 @@
#pragma once #pragma once
#include "base_types.h"
#include <functional> #include <functional>
#include <vector> #include <vector>
@ -11,5 +9,5 @@ class MaintenanceThread
public: public:
static void setup(); static void setup();
static void stop(); static void stop();
static void push_job(const std::function<void(u64)> &func); static void push_job(const std::function<void(int)> &func);
}; };

View file

@ -56,18 +56,18 @@ public:
// includes making the memory effects of construction visible, possibly with a // includes making the memory effects of construction visible, possibly with a
// memory barrier). // memory barrier).
explicit BlockingConcurrentQueue(size_t capacity = 6 * BLOCK_SIZE) explicit BlockingConcurrentQueue(size_t capacity = 6 * BLOCK_SIZE)
: inner(capacity), sema(create<LightweightSemaphore, ssize_t, int>(0, static_cast<int>(Traits::MAX_SEMA_SPINS)), &BlockingConcurrentQueue::template destroy<LightweightSemaphore>) : inner(capacity), sema(create<LightweightSemaphore, ssize_t, int>(0, (int)Traits::MAX_SEMA_SPINS), &BlockingConcurrentQueue::template destroy<LightweightSemaphore>)
{ {
assert(reinterpret_cast<ConcurrentQueue*>(reinterpret_cast<BlockingConcurrentQueue*>(1)) == &(reinterpret_cast<BlockingConcurrentQueue*>(1))->inner && "BlockingConcurrentQueue must have ConcurrentQueue as its first member"); assert(reinterpret_cast<ConcurrentQueue*>((BlockingConcurrentQueue*)1) == &((BlockingConcurrentQueue*)1)->inner && "BlockingConcurrentQueue must have ConcurrentQueue as its first member");
if (!sema) { if (!sema) {
MOODYCAMEL_THROW(std::bad_alloc()); MOODYCAMEL_THROW(std::bad_alloc());
} }
} }
BlockingConcurrentQueue(size_t minCapacity, size_t maxExplicitProducers, size_t maxImplicitProducers) BlockingConcurrentQueue(size_t minCapacity, size_t maxExplicitProducers, size_t maxImplicitProducers)
: inner(minCapacity, maxExplicitProducers, maxImplicitProducers), sema(create<LightweightSemaphore, ssize_t, int>(0, static_cast<int>(Traits::MAX_SEMA_SPINS)), &BlockingConcurrentQueue::template destroy<LightweightSemaphore>) : inner(minCapacity, maxExplicitProducers, maxImplicitProducers), sema(create<LightweightSemaphore, ssize_t, int>(0, (int)Traits::MAX_SEMA_SPINS), &BlockingConcurrentQueue::template destroy<LightweightSemaphore>)
{ {
assert(reinterpret_cast<ConcurrentQueue*>(reinterpret_cast<BlockingConcurrentQueue*>(1)) == &(reinterpret_cast<BlockingConcurrentQueue*>(1))->inner && "BlockingConcurrentQueue must have ConcurrentQueue as its first member"); assert(reinterpret_cast<ConcurrentQueue*>((BlockingConcurrentQueue*)1) == &((BlockingConcurrentQueue*)1)->inner && "BlockingConcurrentQueue must have ConcurrentQueue as its first member");
if (!sema) { if (!sema) {
MOODYCAMEL_THROW(std::bad_alloc()); MOODYCAMEL_THROW(std::bad_alloc());
} }
@ -179,8 +179,7 @@ public:
inline bool enqueue_bulk(It itemFirst, size_t count) inline bool enqueue_bulk(It itemFirst, size_t count)
{ {
if ((details::likely)(inner.enqueue_bulk(std::forward<It>(itemFirst), count))) { if ((details::likely)(inner.enqueue_bulk(std::forward<It>(itemFirst), count))) {
assert(static_cast<ssize_t>(count) >= 0); sema->signal((LightweightSemaphore::ssize_t)(ssize_t)count);
sema->signal(static_cast<LightweightSemaphore::ssize_t>(static_cast<ssize_t>(count)));
return true; return true;
} }
return false; return false;
@ -196,8 +195,7 @@ public:
inline bool enqueue_bulk(producer_token_t const& token, It itemFirst, size_t count) inline bool enqueue_bulk(producer_token_t const& token, It itemFirst, size_t count)
{ {
if ((details::likely)(inner.enqueue_bulk(token, std::forward<It>(itemFirst), count))) { if ((details::likely)(inner.enqueue_bulk(token, std::forward<It>(itemFirst), count))) {
assert(static_cast<ssize_t>(count) >= 0); sema->signal((LightweightSemaphore::ssize_t)(ssize_t)count);
sema->signal(static_cast<LightweightSemaphore::ssize_t>(static_cast<ssize_t>(count)));
return true; return true;
} }
return false; return false;
@ -266,8 +264,7 @@ public:
inline bool try_enqueue_bulk(It itemFirst, size_t count) inline bool try_enqueue_bulk(It itemFirst, size_t count)
{ {
if (inner.try_enqueue_bulk(std::forward<It>(itemFirst), count)) { if (inner.try_enqueue_bulk(std::forward<It>(itemFirst), count)) {
assert(static_cast<ssize_t>(count) >= 0); sema->signal((LightweightSemaphore::ssize_t)(ssize_t)count);
sema->signal(static_cast<LightweightSemaphore::ssize_t>(static_cast<ssize_t>(count)));
return true; return true;
} }
return false; return false;
@ -282,8 +279,7 @@ public:
inline bool try_enqueue_bulk(producer_token_t const& token, It itemFirst, size_t count) inline bool try_enqueue_bulk(producer_token_t const& token, It itemFirst, size_t count)
{ {
if (inner.try_enqueue_bulk(token, std::forward<It>(itemFirst), count)) { if (inner.try_enqueue_bulk(token, std::forward<It>(itemFirst), count)) {
assert(static_cast<ssize_t>(count) >= 0); sema->signal((LightweightSemaphore::ssize_t)(ssize_t)count);
sema->signal(static_cast<LightweightSemaphore::ssize_t>(static_cast<ssize_t>(count)));
return true; return true;
} }
return false; return false;
@ -331,8 +327,7 @@ public:
inline size_t try_dequeue_bulk(It itemFirst, size_t max) inline size_t try_dequeue_bulk(It itemFirst, size_t max)
{ {
size_t count = 0; size_t count = 0;
assert(static_cast<ssize_t>(max) >= 0); max = (size_t)sema->tryWaitMany((LightweightSemaphore::ssize_t)(ssize_t)max);
max = static_cast<size_t>(sema->tryWaitMany(static_cast<LightweightSemaphore::ssize_t>(static_cast<ssize_t>(max))));
while (count != max) { while (count != max) {
count += inner.template try_dequeue_bulk<It&>(itemFirst, max - count); count += inner.template try_dequeue_bulk<It&>(itemFirst, max - count);
} }
@ -348,8 +343,7 @@ public:
inline size_t try_dequeue_bulk(consumer_token_t& token, It itemFirst, size_t max) inline size_t try_dequeue_bulk(consumer_token_t& token, It itemFirst, size_t max)
{ {
size_t count = 0; size_t count = 0;
assert(static_cast<ssize_t>(max) >= 0); max = (size_t)sema->tryWaitMany((LightweightSemaphore::ssize_t)(ssize_t)max);
max = static_cast<size_t>(sema->tryWaitMany(static_cast<LightweightSemaphore::ssize_t>(static_cast<ssize_t>(max))));
while (count != max) { while (count != max) {
count += inner.template try_dequeue_bulk<It&>(token, itemFirst, max - count); count += inner.template try_dequeue_bulk<It&>(token, itemFirst, max - count);
} }
@ -453,8 +447,7 @@ public:
inline size_t wait_dequeue_bulk(It itemFirst, size_t max) inline size_t wait_dequeue_bulk(It itemFirst, size_t max)
{ {
size_t count = 0; size_t count = 0;
assert(static_cast<ssize_t>(max) >= 0); max = (size_t)sema->waitMany((LightweightSemaphore::ssize_t)(ssize_t)max);
max = static_cast<size_t>(sema->waitMany(static_cast<LightweightSemaphore::ssize_t>(static_cast<ssize_t>(max))));
while (count != max) { while (count != max) {
count += inner.template try_dequeue_bulk<It&>(itemFirst, max - count); count += inner.template try_dequeue_bulk<It&>(itemFirst, max - count);
} }
@ -472,8 +465,7 @@ public:
inline size_t wait_dequeue_bulk_timed(It itemFirst, size_t max, std::int64_t timeout_usecs) inline size_t wait_dequeue_bulk_timed(It itemFirst, size_t max, std::int64_t timeout_usecs)
{ {
size_t count = 0; size_t count = 0;
assert(static_cast<ssize_t>(max) >= 0); max = (size_t)sema->waitMany((LightweightSemaphore::ssize_t)(ssize_t)max, timeout_usecs);
max = static_cast<size_t>(sema->waitMany(static_cast<LightweightSemaphore::ssize_t>(static_cast<ssize_t>(max)), timeout_usecs));
while (count != max) { while (count != max) {
count += inner.template try_dequeue_bulk<It&>(itemFirst, max - count); count += inner.template try_dequeue_bulk<It&>(itemFirst, max - count);
} }
@ -500,8 +492,7 @@ public:
inline size_t wait_dequeue_bulk(consumer_token_t& token, It itemFirst, size_t max) inline size_t wait_dequeue_bulk(consumer_token_t& token, It itemFirst, size_t max)
{ {
size_t count = 0; size_t count = 0;
assert(static_cast<ssize_t>(max) >= 0); max = (size_t)sema->waitMany((LightweightSemaphore::ssize_t)(ssize_t)max);
max = static_cast<size_t>(sema->waitMany(static_cast<LightweightSemaphore::ssize_t>(static_cast<ssize_t>(max))));
while (count != max) { while (count != max) {
count += inner.template try_dequeue_bulk<It&>(token, itemFirst, max - count); count += inner.template try_dequeue_bulk<It&>(token, itemFirst, max - count);
} }
@ -519,8 +510,7 @@ public:
inline size_t wait_dequeue_bulk_timed(consumer_token_t& token, It itemFirst, size_t max, std::int64_t timeout_usecs) inline size_t wait_dequeue_bulk_timed(consumer_token_t& token, It itemFirst, size_t max, std::int64_t timeout_usecs)
{ {
size_t count = 0; size_t count = 0;
assert(static_cast<ssize_t>(max) >= 0); max = (size_t)sema->waitMany((LightweightSemaphore::ssize_t)(ssize_t)max, timeout_usecs);
max = static_cast<size_t>(sema->waitMany(static_cast<LightweightSemaphore::ssize_t>(static_cast<ssize_t>(max)), timeout_usecs));
while (count != max) { while (count != max) {
count += inner.template try_dequeue_bulk<It&>(token, itemFirst, max - count); count += inner.template try_dequeue_bulk<It&>(token, itemFirst, max - count);
} }
@ -547,7 +537,7 @@ public:
// Thread-safe. // Thread-safe.
inline size_t size_approx() const inline size_t size_approx() const
{ {
return static_cast<size_t>(sema->availableApprox()); return (size_t)sema->availableApprox();
} }

View file

@ -217,7 +217,7 @@ namespace moodycamel { namespace details {
// VS2013 doesn't support `thread_local`, and MinGW-w64 w/ POSIX threading has a crippling bug: http://sourceforge.net/p/mingw-w64/bugs/445 // VS2013 doesn't support `thread_local`, and MinGW-w64 w/ POSIX threading has a crippling bug: http://sourceforge.net/p/mingw-w64/bugs/445
// g++ <=4.7 doesn't support thread_local either. // g++ <=4.7 doesn't support thread_local either.
// Finally, iOS/ARM doesn't have support for it either, and g++/ARM allows it to compile but it's unconfirmed to actually work // Finally, iOS/ARM doesn't have support for it either, and g++/ARM allows it to compile but it's unconfirmed to actually work
#if (!defined(_MSC_VER) || _MSC_VER >= 1900) && (!defined(__MINGW32__) && !defined(__MINGW64__) || !defined(__WINPTHREADS_VERSION)) && (!defined(__GNUC__) || __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)) && (!defined(__APPLE__) || !TARGET_OS_IPHONE) && !defined(__arm__) && !defined(_M_ARM) && !defined(__aarch64__) && !defined(__MVS__) && !defined(MOODYCAMEL_NO_THREAD_LOCAL) #if (!defined(_MSC_VER) || _MSC_VER >= 1900) && (!defined(__MINGW32__) && !defined(__MINGW64__) || !defined(__WINPTHREADS_VERSION)) && (!defined(__GNUC__) || __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)) && (!defined(__APPLE__) || !TARGET_OS_IPHONE) && !defined(__arm__) && !defined(_M_ARM) && !defined(__aarch64__) && !defined(__MVS__)
// Assume `thread_local` is fully supported in all other C++11 compilers/platforms // Assume `thread_local` is fully supported in all other C++11 compilers/platforms
#define MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED // tentatively enabled for now; years ago several users report having problems with it on #define MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED // tentatively enabled for now; years ago several users report having problems with it on
#endif #endif
@ -355,12 +355,6 @@ struct ConcurrentQueueDefaultTraits
// How many full blocks can be expected for a single implicit producer? This should // How many full blocks can be expected for a single implicit producer? This should
// reflect that number's maximum for optimal performance. Must be a power of 2. // reflect that number's maximum for optimal performance. Must be a power of 2.
// Note: This impacts the maximum number of elements that can be enqueued by a
// single implicit producer when using try_enqueue/try_enqeue_bulk exclusively (which
// cannot allocate), since it limits the number of blocks that the producer can hold to
// store elements. When pre-allocating blocks for use with try-enqueueing, configure
// this initial size to the desired maximum number of blocks per implicit producer.
// Alternately, use the regular enqueue methods, which can grow the index as needed.
static const size_t IMPLICIT_INITIAL_INDEX_SIZE = 32; static const size_t IMPLICIT_INITIAL_INDEX_SIZE = 32;
// The initial size of the hash table mapping thread IDs to implicit producers. // The initial size of the hash table mapping thread IDs to implicit producers.
@ -475,15 +469,8 @@ namespace details
static inline size_t hash_thread_id(thread_id_t id) static inline size_t hash_thread_id(thread_id_t id)
{ {
static_assert(sizeof(thread_id_t) <= 8, "Expected a platform where thread IDs are at most 64-bit values"); static_assert(sizeof(thread_id_t) <= 8, "Expected a platform where thread IDs are at most 64-bit values");
#if defined(__GNUC__) && !defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wuseless-cast"
#endif
return static_cast<size_t>(hash_32_or_64<sizeof(thread_id_converter<thread_id_t>::thread_id_hash_t)>::hash( return static_cast<size_t>(hash_32_or_64<sizeof(thread_id_converter<thread_id_t>::thread_id_hash_t)>::hash(
thread_id_converter<thread_id_t>::prehash(id))); thread_id_converter<thread_id_t>::prehash(id)));
#if defined(__GNUC__) && !defined(__clang__)
#pragma GCC diagnostic pop
#endif
} }
template<typename T> template<typename T>
@ -522,9 +509,9 @@ namespace details
template<typename T> template<typename T>
static inline void swap_relaxed(std::atomic<T>& left, std::atomic<T>& right) static inline void swap_relaxed(std::atomic<T>& left, std::atomic<T>& right)
{ {
T temp = left.load(std::memory_order_relaxed); T temp = std::move(left.load(std::memory_order_relaxed));
left.store(right.load(std::memory_order_relaxed), std::memory_order_relaxed); left.store(std::move(right.load(std::memory_order_relaxed)), std::memory_order_relaxed);
right.store(temp, std::memory_order_relaxed); right.store(std::move(temp), std::memory_order_relaxed);
} }
template<typename T> template<typename T>
@ -1069,9 +1056,6 @@ public:
// Does not allocate memory. Fails if not enough room to enqueue (or implicit // Does not allocate memory. Fails if not enough room to enqueue (or implicit
// production is disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE // production is disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE
// is 0). // is 0).
// Note: If using only try_enqueue/try_enqueue_bulk with pre-allocated blocks, configure
// Traits::IMPLICIT_INITIAL_INDEX_SIZE appropriately to ensure the index has sufficient
// capacity for the number of blocks each producer may need.
// Thread-safe. // Thread-safe.
inline bool try_enqueue(T const& item) inline bool try_enqueue(T const& item)
{ {
@ -1083,9 +1067,6 @@ public:
// Does not allocate memory (except for one-time implicit producer). // Does not allocate memory (except for one-time implicit producer).
// Fails if not enough room to enqueue (or implicit production is // Fails if not enough room to enqueue (or implicit production is
// disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE is 0). // disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE is 0).
// Note: If using only try_enqueue/try_enqueue_bulk with pre-allocated blocks, configure
// Traits::IMPLICIT_INITIAL_INDEX_SIZE appropriately to ensure the index has sufficient
// capacity for the number of blocks each producer may need.
// Thread-safe. // Thread-safe.
inline bool try_enqueue(T&& item) inline bool try_enqueue(T&& item)
{ {
@ -1113,9 +1094,6 @@ public:
// Does not allocate memory (except for one-time implicit producer). // Does not allocate memory (except for one-time implicit producer).
// Fails if not enough room to enqueue (or implicit production is // Fails if not enough room to enqueue (or implicit production is
// disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE is 0). // disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE is 0).
// Note: If using only try_enqueue/try_enqueue_bulk with pre-allocated blocks, configure
// Traits::IMPLICIT_INITIAL_INDEX_SIZE appropriately to ensure the index has sufficient
// capacity for the number of blocks each producer may need.
// Note: Use std::make_move_iterator if the elements should be moved // Note: Use std::make_move_iterator if the elements should be moved
// instead of copied. // instead of copied.
// Thread-safe. // Thread-safe.
@ -1501,7 +1479,7 @@ private:
while (head != nullptr) { while (head != nullptr) {
auto prevHead = head; auto prevHead = head;
auto refs = head->freeListRefs.load(std::memory_order_relaxed); auto refs = head->freeListRefs.load(std::memory_order_relaxed);
if ((refs & REFS_MASK) == 0 || !head->freeListRefs.compare_exchange_strong(refs, refs + 1, std::memory_order_acquire)) { if ((refs & REFS_MASK) == 0 || !head->freeListRefs.compare_exchange_strong(refs, refs + 1, std::memory_order_acquire, std::memory_order_relaxed)) {
head = freeListHead.load(std::memory_order_acquire); head = freeListHead.load(std::memory_order_acquire);
continue; continue;
} }
@ -1551,7 +1529,7 @@ private:
node->freeListRefs.store(1, std::memory_order_release); node->freeListRefs.store(1, std::memory_order_release);
if (!freeListHead.compare_exchange_strong(head, node, std::memory_order_release, std::memory_order_relaxed)) { if (!freeListHead.compare_exchange_strong(head, node, std::memory_order_release, std::memory_order_relaxed)) {
// Hmm, the add failed, but we can only try again when the refcount goes back to zero // Hmm, the add failed, but we can only try again when the refcount goes back to zero
if (node->freeListRefs.fetch_add(SHOULD_BE_ON_FREELIST - 1, std::memory_order_acq_rel) == 1) { if (node->freeListRefs.fetch_add(SHOULD_BE_ON_FREELIST - 1, std::memory_order_release) == 1) {
continue; continue;
} }
} }
@ -1626,7 +1604,7 @@ private:
} }
else { else {
// Increment counter // Increment counter
auto prevVal = elementsCompletelyDequeued.fetch_add(1, std::memory_order_acq_rel); auto prevVal = elementsCompletelyDequeued.fetch_add(1, std::memory_order_release);
assert(prevVal < BLOCK_SIZE); assert(prevVal < BLOCK_SIZE);
return prevVal == BLOCK_SIZE - 1; return prevVal == BLOCK_SIZE - 1;
} }
@ -1649,7 +1627,7 @@ private:
} }
else { else {
// Increment counter // Increment counter
auto prevVal = elementsCompletelyDequeued.fetch_add(count, std::memory_order_acq_rel); auto prevVal = elementsCompletelyDequeued.fetch_add(count, std::memory_order_release);
assert(prevVal + count <= BLOCK_SIZE); assert(prevVal + count <= BLOCK_SIZE);
return prevVal + count == BLOCK_SIZE; return prevVal + count == BLOCK_SIZE;
} }

View file

@ -5,12 +5,8 @@
#pragma once #pragma once
#include <atomic>
#include <cassert> // assert
#include <cerrno> // For EINTR
#include <cstddef> // For std::size_t #include <cstddef> // For std::size_t
#include <cstdint> // For std::uint64_t #include <atomic>
#include <ctime> // For clock_gettime
#include <type_traits> // For std::make_signed<T> #include <type_traits> // For std::make_signed<T>
#if defined(_WIN32) #if defined(_WIN32)
@ -40,14 +36,6 @@ extern "C" {
#endif #endif
#endif #endif
#ifndef MOODYCAMEL_DELETE_FUNCTION
#if __cplusplus >= 201103L || _MSC_VER >= 1900
#define MOODYCAMEL_DELETE_FUNCTION = delete
#else
#define MOODYCAMEL_DELETE_FUNCTION
#endif
#endif
namespace moodycamel namespace moodycamel
{ {
namespace details namespace details
@ -234,8 +222,8 @@ public:
#else #else
clock_gettime(CLOCK_REALTIME, &ts); clock_gettime(CLOCK_REALTIME, &ts);
#endif #endif
ts.tv_sec += static_cast<time_t>(usecs / usecs_in_1_sec); ts.tv_sec += (time_t)(usecs / usecs_in_1_sec);
ts.tv_nsec += static_cast<long>(usecs % usecs_in_1_sec) * 1000; ts.tv_nsec += (long)(usecs % usecs_in_1_sec) * 1000;
// sem_timedwait bombs if you have more than 1e9 in tv_nsec // sem_timedwait bombs if you have more than 1e9 in tv_nsec
// so we have to clean things up before passing it in // so we have to clean things up before passing it in
if (ts.tv_nsec >= nsecs_in_1_sec) { if (ts.tv_nsec >= nsecs_in_1_sec) {
@ -306,7 +294,7 @@ private:
if (m_sema.wait()) if (m_sema.wait())
return true; return true;
} }
if (timeout_usecs > 0 && m_sema.timed_wait(static_cast<std::uint64_t>(timeout_usecs))) if (timeout_usecs > 0 && m_sema.timed_wait((std::uint64_t)timeout_usecs))
return true; return true;
// At this point, we've timed out waiting for the semaphore, but the // At this point, we've timed out waiting for the semaphore, but the
// count is still decremented indicating we may still be waiting on // count is still decremented indicating we may still be waiting on
@ -342,7 +330,7 @@ private:
oldCount = m_count.fetch_sub(1, std::memory_order_acquire); oldCount = m_count.fetch_sub(1, std::memory_order_acquire);
if (oldCount <= 0) if (oldCount <= 0)
{ {
if ((timeout_usecs == 0) || (timeout_usecs < 0 && !m_sema.wait()) || (timeout_usecs > 0 && !m_sema.timed_wait(static_cast<std::uint64_t>(timeout_usecs)))) if ((timeout_usecs == 0) || (timeout_usecs < 0 && !m_sema.wait()) || (timeout_usecs > 0 && !m_sema.timed_wait((std::uint64_t)timeout_usecs)))
{ {
while (true) while (true)
{ {
@ -425,7 +413,7 @@ public:
ssize_t toRelease = -oldCount < count ? -oldCount : count; ssize_t toRelease = -oldCount < count ? -oldCount : count;
if (toRelease > 0) if (toRelease > 0)
{ {
m_sema.signal(static_cast<int>(toRelease)); m_sema.signal((int)toRelease);
} }
} }

View file

@ -0,0 +1,7 @@
#pragma once
#ifdef DEBUG
#include "mutex_debug.hpp"
#else
#include "mutex_ndebug.hpp"
#endif

View file

@ -2,19 +2,19 @@
#include "fmt/core.h" #include "fmt/core.h"
#include <ctime>
#include <cstdlib> #include <cstdlib>
#include <pthread.h> #include <pthread.h>
#include <time.h>
#ifndef PTHREAD_MUTEX_ADAPTIVE_NP #ifndef PTHREAD_MUTEX_ADAPTIVE_NP
# define PTHREAD_MUTEX_ADAPTIVE_NP PTHREAD_MUTEX_NORMAL # define PTHREAD_MUTEX_ADAPTIVE_NP PTHREAD_MUTEX_NORMAL
#endif #endif
#define mutex_init(M) _mutex_init((M),__FILE__,__func__,__LINE__) #define mutex_init(M) _mutex_init(M,__FILE__,__func__,__LINE__)
#define mutex_destroy(M) _mutex_destroy((M),__FILE__,__func__,__LINE__) #define mutex_destroy(M) _mutex_destroy(M,__FILE__,__func__,__LINE__)
#define mutex_lock(M) _mutex_lock((M),__FILE__,__func__,__LINE__) #define mutex_lock(M) _mutex_lock(M,__FILE__,__func__,__LINE__)
#define mutex_unlock(M) _mutex_unlock((M),__FILE__,__func__,__LINE__) #define mutex_unlock(M) _mutex_unlock(M,__FILE__,__func__,__LINE__)
static static
@ -34,13 +34,13 @@ _print_error_and_abort(const char *func1_,
file_, file_,
func2_, func2_,
linenum_); linenum_);
std::abort(); abort();
} }
static static
inline inline
void void
_mutex_init(pthread_mutex_t &mutex_, _mutex_init(pthread_mutex_t *mutex_,
const char *file_, const char *file_,
const char *func_, const char *func_,
const int linenum_) const int linenum_)
@ -51,7 +51,7 @@ _mutex_init(pthread_mutex_t &mutex_,
pthread_mutexattr_init(&attr); pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_ADAPTIVE_NP); pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_ADAPTIVE_NP);
rv = pthread_mutex_init(&mutex_,&attr); rv = pthread_mutex_init(mutex_,&attr);
if(rv != 0) if(rv != 0)
_print_error_and_abort(__func__,rv,file_,func_,linenum_); _print_error_and_abort(__func__,rv,file_,func_,linenum_);
@ -61,14 +61,14 @@ _mutex_init(pthread_mutex_t &mutex_,
static static
inline inline
void void
_mutex_destroy(pthread_mutex_t &mutex_, _mutex_destroy(pthread_mutex_t *mutex_,
const char *file_, const char *file_,
const char *func_, const char *func_,
const int linenum_) const int linenum_)
{ {
int rv; int rv;
rv = pthread_mutex_destroy(&mutex_); rv = pthread_mutex_destroy(mutex_);
if(rv != 0) if(rv != 0)
_print_error_and_abort(__func__,rv,file_,func_,linenum_); _print_error_and_abort(__func__,rv,file_,func_,linenum_);
} }
@ -76,7 +76,7 @@ _mutex_destroy(pthread_mutex_t &mutex_,
static static
inline inline
void void
_mutex_lock(pthread_mutex_t &mutex_, _mutex_lock(pthread_mutex_t *mutex_,
const char *file_, const char *file_,
const char *func_, const char *func_,
const int linenum_) const int linenum_)
@ -95,7 +95,7 @@ _mutex_lock(pthread_mutex_t &mutex_,
timeout.tv_nsec -= 1000000000; timeout.tv_nsec -= 1000000000;
} }
rv = pthread_mutex_timedlock(&mutex_,&timeout); rv = pthread_mutex_timedlock(mutex_,&timeout);
switch(rv) switch(rv)
{ {
case 0: case 0:
@ -119,14 +119,14 @@ _mutex_lock(pthread_mutex_t &mutex_,
static static
inline inline
void void
_mutex_unlock(pthread_mutex_t &mutex_, _mutex_unlock(pthread_mutex_t *mutex_,
const char *file_, const char *file_,
const char *func_, const char *func_,
const int linenum_) const int linenum_)
{ {
int rv; int rv;
rv = pthread_mutex_unlock(&mutex_); rv = pthread_mutex_unlock(mutex_);
if(rv != 0) if(rv != 0)
_print_error_and_abort(__func__,rv,file_,func_,linenum_); _print_error_and_abort(__func__,rv,file_,func_,linenum_);
} }

View file

@ -12,7 +12,7 @@
static static
inline inline
void void
mutex_init(pthread_mutex_t &mutex_) mutex_init(pthread_mutex_t *mutex_)
{ {
int rv; int rv;
pthread_mutexattr_t attr; pthread_mutexattr_t attr;
@ -20,9 +20,9 @@ mutex_init(pthread_mutex_t &mutex_)
pthread_mutexattr_init(&attr); pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_ADAPTIVE_NP); pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_ADAPTIVE_NP);
rv = pthread_mutex_init(&mutex_,&attr); rv = pthread_mutex_init(mutex_,&attr);
if(rv != 0) if(rv != 0)
std::abort(); abort();
pthread_mutexattr_destroy(&attr); pthread_mutexattr_destroy(&attr);
} }
@ -30,35 +30,35 @@ mutex_init(pthread_mutex_t &mutex_)
static static
inline inline
void void
mutex_lock(pthread_mutex_t &mutex_) mutex_lock(pthread_mutex_t *mutex_)
{ {
int rv; int rv;
rv = pthread_mutex_lock(&mutex_); rv = pthread_mutex_lock(mutex_);
if(rv != 0) if(rv != 0)
std::abort(); abort();
} }
static static
inline inline
void void
mutex_unlock(pthread_mutex_t &mutex_) mutex_unlock(pthread_mutex_t *mutex_)
{ {
int rv; int rv;
rv = pthread_mutex_unlock(&mutex_); rv = pthread_mutex_unlock(mutex_);
if(rv != 0) if(rv != 0)
std::abort(); abort();
} }
static static
inline inline
void void
mutex_destroy(pthread_mutex_t &mutex_) mutex_destroy(pthread_mutex_t *mutex_)
{ {
int rv; int rv;
rv = pthread_mutex_destroy(&mutex_); rv = pthread_mutex_destroy(mutex_);
if(rv != 0) if(rv != 0)
std::abort(); abort();
} }

View file

@ -0,0 +1,389 @@
#pragma once
#include "moodycamel/blockingconcurrentqueue.h"
#include "moodycamel/lightweightsemaphore.h"
#include "invocable.h"
#include <algorithm>
#include <atomic>
#include <csignal>
#include <cstring>
#include <future>
#include <memory>
#include <mutex>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
#include <utility>
#include <pthread.h>
#include <syslog.h>
#define SEM
//#undef SEM
#ifdef SEM
#define SEMA_WAIT(S) (S.wait())
#define SEMA_SIGNAL(S) (S.signal())
#else
#define SEMA_WAIT(S)
#define SEMA_SIGNAL(S)
#endif
struct ThreadPoolTraits : public moodycamel::ConcurrentQueueDefaultTraits
{
static const int MAX_SEMA_SPINS = 1;
};
class ThreadPool
{
public:
using PToken = moodycamel::ProducerToken;
using CToken = moodycamel::ConsumerToken;
private:
using Func = ofats::any_invocable<void()>;
using Queue = moodycamel::BlockingConcurrentQueue<Func,ThreadPoolTraits>;
public:
explicit
ThreadPool(const unsigned thread_count_ = std::thread::hardware_concurrency(),
const unsigned max_queue_depth_ = std::thread::hardware_concurrency(),
std::string const name_ = {});
~ThreadPool();
private:
static void *start_routine(void *arg_);
public:
int add_thread(std::string const name = {});
int remove_thread(void);
int set_threads(const std::size_t count);
void shutdown(void);
public:
template<typename FuncType>
void
enqueue_work(ThreadPool::PToken &ptok_,
FuncType &&func_);
template<typename FuncType>
void
enqueue_work(FuncType &&func_);
template<typename FuncType>
[[nodiscard]]
std::future<std::invoke_result_t<FuncType>>
enqueue_task(FuncType&& func_);
public:
std::vector<pthread_t> threads() const;
ThreadPool::PToken ptoken();
private:
Queue _queue;
moodycamel::LightweightSemaphore _sema;
private:
std::string const _name;
std::vector<pthread_t> _threads;
mutable std::mutex _threads_mutex;
};
inline
ThreadPool::ThreadPool(const unsigned thread_count_,
const unsigned max_queue_depth_,
const std::string name_)
: _queue(),
_sema(max_queue_depth_),
_name(name_)
{
sigset_t oldset;
sigset_t newset;
sigfillset(&newset);
pthread_sigmask(SIG_BLOCK,&newset,&oldset);
_threads.reserve(thread_count_);
for(std::size_t i = 0; i < thread_count_; ++i)
{
int rv;
pthread_t t;
rv = pthread_create(&t,NULL,ThreadPool::start_routine,this);
if(rv != 0)
{
syslog(LOG_WARNING,
"threadpool (%s): error spawning thread - %d (%s)",
_name.c_str(),
rv,
strerror(rv));
continue;
}
if(!_name.empty())
pthread_setname_np(t,_name.c_str());
_threads.push_back(t);
}
pthread_sigmask(SIG_SETMASK,&oldset,NULL);
if(_threads.empty())
throw std::runtime_error("threadpool: failed to spawn any threads");
syslog(LOG_DEBUG,
"threadpool (%s): spawned %zu threads w/ max queue depth %u",
_name.c_str(),
_threads.size(),
max_queue_depth_);
}
inline
ThreadPool::~ThreadPool()
{
syslog(LOG_DEBUG,
"threadpool (%s): destroying %zu threads",
_name.c_str(),
_threads.size());
for(auto t : _threads)
pthread_cancel(t);
for(auto t : _threads)
pthread_join(t,NULL);
}
inline
void*
ThreadPool::start_routine(void *arg_)
{
ThreadPool *btp = static_cast<ThreadPool*>(arg_);
bool done;
ThreadPool::Func func;
ThreadPool::Queue &q = btp->_queue;
moodycamel::LightweightSemaphore &sema = btp->_sema;
ThreadPool::CToken ctok(btp->_queue);
done = false;
while(!done)
{
q.wait_dequeue(ctok,func);
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,NULL);
try
{
func();
}
catch(std::exception &e)
{
done = true;
}
SEMA_SIGNAL(sema);
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);
}
return nullptr;
}
inline
int
ThreadPool::add_thread(const std::string name_)
{
int rv;
pthread_t t;
sigset_t oldset;
sigset_t newset;
std::string name;
name = (name_.empty() ? _name : name_);
sigfillset(&newset);
pthread_sigmask(SIG_BLOCK,&newset,&oldset);
rv = pthread_create(&t,NULL,ThreadPool::start_routine,this);
pthread_sigmask(SIG_SETMASK,&oldset,NULL);
if(rv != 0)
{
syslog(LOG_WARNING,
"threadpool (%s): error spawning thread - %d (%s)",
_name.c_str(),
rv,
strerror(rv));
return -rv;
}
if(!name.empty())
pthread_setname_np(t,name.c_str());
{
std::lock_guard<std::mutex> lg(_threads_mutex);
_threads.push_back(t);
}
return 0;
}
inline
int
ThreadPool::remove_thread(void)
{
{
std::lock_guard<std::mutex> lg(_threads_mutex);
if(_threads.size() <= 1)
return -EINVAL;
}
std::promise<pthread_t> promise;
auto func =
[this,&promise]()
{
pthread_t t;
t = pthread_self();
promise.set_value(t);
{
std::lock_guard<std::mutex> lg(_threads_mutex);
for(auto i = _threads.begin(); i != _threads.end(); ++i)
{
if(*i != t)
continue;
_threads.erase(i);
break;
}
}
pthread_exit(NULL);
};
enqueue_work(std::move(func));
pthread_join(promise.get_future().get(),NULL);
return 0;
}
inline
int
ThreadPool::set_threads(std::size_t const count_)
{
int diff;
{
std::lock_guard<std::mutex> lg(_threads_mutex);
diff = ((int)count_ - (int)_threads.size());
}
for(auto i = diff; i > 0; --i)
add_thread();
for(auto i = diff; i < 0; ++i)
remove_thread();
return diff;
}
inline
void
ThreadPool::shutdown(void)
{
std::lock_guard<std::mutex> lg(_threads_mutex);
for(pthread_t tid : _threads)
pthread_cancel(tid);
for(pthread_t tid : _threads)
pthread_join(tid,NULL);
_threads.clear();
}
template<typename FuncType>
inline
void
ThreadPool::enqueue_work(ThreadPool::PToken &ptok_,
FuncType &&func_)
{
SEMA_WAIT(_sema);
_queue.enqueue(ptok_,
std::forward<FuncType>(func_));
}
template<typename FuncType>
inline
void
ThreadPool::enqueue_work(FuncType &&func_)
{
SEMA_WAIT(_sema);
_queue.enqueue(std::forward<FuncType>(func_));
}
template<typename FuncType>
[[nodiscard]]
inline
std::future<std::invoke_result_t<FuncType>>
ThreadPool::enqueue_task(FuncType&& func_)
{
using TaskReturnType = std::invoke_result_t<FuncType>;
using Promise = std::promise<TaskReturnType>;
Promise promise;
auto future = promise.get_future();
auto work =
[promise_ = std::move(promise),
func_ = std::forward<FuncType>(func_)]() mutable
{
try
{
auto rv = func_();
promise_.set_value(std::move(rv));
}
catch(...)
{
promise_.set_exception(std::current_exception());
}
};
SEMA_WAIT(_sema);
_queue.enqueue(std::move(work));
return future;
}
inline
std::vector<pthread_t>
ThreadPool::threads() const
{
std::lock_guard<std::mutex> lg(_threads_mutex);
return _threads;
}
inline
ThreadPool::PToken
ThreadPool::ptoken()
{
return ThreadPool::PToken(_queue);
}

View file

@ -136,12 +136,6 @@ CPU::cpu2core()
ifs >> core_id; ifs >> core_id;
if(!ifs)
{
ifs.close();
continue;
}
c2c[i] = core_id; c2c[i] = core_id;
ifs.close(); ifs.close();
@ -175,12 +169,6 @@ CPU::core2cpus()
ifs >> core_id; ifs >> core_id;
if(!ifs)
{
ifs.close();
continue;
}
c2c[core_id].insert(i); c2c[core_id].insert(i);
ifs.close(); ifs.close();

View file

@ -78,12 +78,12 @@ crc32b_continue(const void *buf_,
const crc32b_t len_, const crc32b_t len_,
const crc32b_t crc_) const crc32b_t crc_)
{ {
const char *buf; char *buf;
crc32b_t i; crc32b_t i;
crc32b_t crc; crc32b_t crc;
crc = crc_; crc = crc_;
buf = static_cast<const char*>(buf_); buf = (char*)buf_;
for(i = 0; i < len_; i++) for(i = 0; i < len_; i++)
{ {
crc = (CRC32BTABLE[(crc ^ buf[i]) & 0xFFL] ^ (crc >> 8)); crc = (CRC32BTABLE[(crc ^ buf[i]) & 0xFFL] ^ (crc >> 8));

1433
libfuse/lib/debug.cpp Normal file

File diff suppressed because it is too large Load diff

View file

@ -18,53 +18,39 @@
#pragma once #pragma once
#include "fuse_kernel.h"
#include <memory>
#include <string> #include <string>
#include "fuse_kernel.h"
int fuse_debug_set_output(const std::string &filepath); void debug_fuse_open_out(const uint64_t unique,
void fuse_debug_open_out(const uint64_t unique,
const struct fuse_open_out *arg, const struct fuse_open_out *arg,
const uint64_t argsize); const uint64_t argsize);
void fuse_debug_init_in(const struct fuse_init_in *arg); void debug_fuse_init_in(const struct fuse_init_in *arg);
void fuse_debug_init_out(const uint64_t unique, void debug_fuse_init_out(const uint64_t unique,
const struct fuse_init_out *arg, const struct fuse_init_out *arg,
const uint64_t argsize); const uint64_t argsize);
void fuse_debug_entry_out(const uint64_t unique, void debug_fuse_entry_out(const uint64_t unique,
const struct fuse_entry_out *arg, const struct fuse_entry_out *arg,
const uint64_t argsize); const uint64_t argsize);
void fuse_debug_attr_out(const uint64_t unique, void debug_fuse_attr_out(const uint64_t unique,
const struct fuse_attr_out *arg, const struct fuse_attr_out *arg,
const uint64_t argsize); const uint64_t argsize);
void fuse_debug_entry_open_out(const uint64_t unique, void debug_fuse_entry_open_out(const uint64_t unique,
const struct fuse_entry_out *earg, const struct fuse_entry_out *earg,
const struct fuse_open_out *oarg); const struct fuse_open_out *oarg);
void fuse_debug_readlink(const uint64_t unique, void debug_fuse_readlink(const uint64_t unique,
const char *linkname, const char *linkname);
const size_t linkname_len); void debug_fuse_write_out(const uint64_t unique,
void fuse_debug_write_out(const uint64_t unique,
const struct fuse_write_out *arg); const struct fuse_write_out *arg);
void fuse_debug_statfs_out(const uint64_t unique, void debug_fuse_statfs_out(const uint64_t unique,
const struct fuse_statfs_out *arg); const struct fuse_statfs_out *arg);
void fuse_debug_getxattr_out(const uint64_t unique, void debug_fuse_getxattr_out(const uint64_t unique,
const struct fuse_getxattr_out *arg); const struct fuse_getxattr_out *arg);
void fuse_debug_lk_out(const uint64_t unique, void debug_fuse_lk_out(const uint64_t unique,
const struct fuse_lk_out *arg); const struct fuse_lk_out *arg);
void fuse_debug_bmap_out(const uint64_t unique, void debug_fuse_bmap_out(const uint64_t unique,
const struct fuse_bmap_out *arg); const struct fuse_bmap_out *arg);
void fuse_debug_statx_out(const uint64_t unique, void debug_fuse_in_header(const struct fuse_in_header *hdr);
const struct fuse_statx_out *arg);
void fuse_debug_data_out(const uint64_t unique,
const size_t size);
void fuse_debug_ioctl_out(const uint64_t unique,
const struct fuse_ioctl_out *arg);
void fuse_debug_poll_out(const uint64_t unique,
const struct fuse_poll_out *arg);
void fuse_debug_in_header(const struct fuse_in_header *hdr);
void fuse_debug_out_header(const struct fuse_out_header *hdr);
std::string fuse_debug_init_flag_name(const uint64_t); std::string fuse_debug_init_flag_name(const uint64_t);

380
libfuse/lib/fmp.h Normal file
View file

@ -0,0 +1,380 @@
/*
ISC License
Copyright (c) 2021, Antonio SJ Musumeci <trapexit@spawn.link>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#pragma once
#include "kvec.h"
#include <errno.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#define ROUND_UP(N,S) ((((N) + (S) - 1) / (S)) * (S))
typedef kvec_t(void*) slab_kvec_t;
typedef struct mem_stack_t mem_stack_t;
struct mem_stack_t
{
mem_stack_t *next;
};
typedef struct fmp_t fmp_t;
struct fmp_t
{
mem_stack_t *objs;
slab_kvec_t slabs;
uint64_t avail_objs;
uint64_t obj_size;
uint64_t page_size;
uint64_t slab_size;
};
static
inline
uint64_t
fmp_page_size()
{
return sysconf(_SC_PAGESIZE);
}
static
inline
void
fmp_init(fmp_t *fmp_,
const uint64_t obj_size_,
const uint64_t page_multiple_)
{
kv_init(fmp_->slabs);
fmp_->objs = NULL;
fmp_->avail_objs = 0;
fmp_->obj_size = ROUND_UP(obj_size_,sizeof(void*));
fmp_->page_size = fmp_page_size();
fmp_->slab_size = (fmp_->page_size * page_multiple_);
}
static
inline
uint64_t
fmp_slab_count(fmp_t *fmp_)
{
return kv_size(fmp_->slabs);
}
static
inline
void*
fmp_slab_alloc_posix_memalign(fmp_t *fmp_)
{
int rv;
void *mem;
const size_t alignment = fmp_->page_size;
const size_t size = fmp_->slab_size;
rv = posix_memalign(&mem,alignment,size);
if(rv != 0)
return NULL;
return NULL;
}
static
inline
void*
fmp_slab_alloc_mmap(fmp_t *fmp_)
{
void *mem;
void *address = NULL;
const size_t length = fmp_->slab_size;
const int protect = PROT_READ|PROT_WRITE;
const int flags = MAP_PRIVATE|MAP_ANONYMOUS;
const int filedes = -1;
const off_t offset = 0;
mem = mmap(address,length,protect,flags,filedes,offset);
if(mem == MAP_FAILED)
return NULL;
return mem;
}
static
inline
void
fmp_slab_free_posix_memalign(fmp_t* fmp_,
void *mem_)
{
(void)fmp_;
free(mem_);
}
static
inline
void
fmp_slab_free_mmap(fmp_t* fmp_,
void *mem_)
{
void *addr = mem_;
size_t length = fmp_->slab_size;
(void)munmap(addr,length);
}
static
inline
int
fmp_slab_alloc(fmp_t *fmp_)
{
char *i;
void *mem;
mem = fmp_slab_alloc_mmap(fmp_);
if(mem == NULL)
return -ENOMEM;
kv_push(void*,fmp_->slabs,mem);
i = ((char*)mem + fmp_->slab_size - fmp_->obj_size);
while(i >= (char*)mem)
{
mem_stack_t *obj = (mem_stack_t*)i;
obj->next = fmp_->objs;
fmp_->objs = obj;
fmp_->avail_objs++;
i -= fmp_->obj_size;
}
return 0;
}
static
inline
void*
fmp_alloc(fmp_t *fmp_)
{
void *rv;
if(fmp_->objs == NULL)
fmp_slab_alloc(fmp_);
if(fmp_->objs == NULL)
return NULL;
rv = fmp_->objs;
fmp_->objs = fmp_->objs->next;
fmp_->avail_objs--;
return rv;
}
static
inline
void*
fmp_calloc(fmp_t *fmp_)
{
void *obj;
obj = fmp_alloc(fmp_);
if(obj == NULL)
return NULL;
memset(obj,0,fmp_->obj_size);
return obj;
}
static
inline
void
fmp_free(fmp_t *fmp_,
void *obj_)
{
mem_stack_t *obj = (mem_stack_t*)obj_;
obj->next = fmp_->objs;
fmp_->objs = obj;
fmp_->avail_objs++;
}
static
inline
void
fmp_clear(fmp_t *fmp_)
{
while(kv_size(fmp_->slabs))
{
void *slab = kv_pop(fmp_->slabs);
fmp_slab_free_mmap(fmp_,slab);
}
fmp_->objs = NULL;
fmp_->avail_objs = 0;
}
static
inline
void
fmp_destroy(fmp_t *fmp_)
{
fmp_clear(fmp_);
kv_destroy(fmp_->slabs);
}
static
inline
uint64_t
fmp_avail_objs(fmp_t *fmp_)
{
return fmp_->avail_objs;
}
static
inline
uint64_t
fmp_objs_per_slab(fmp_t *fmp_)
{
return (fmp_->slab_size / fmp_->obj_size);
}
static
inline
uint64_t
fmp_objs_in_slab(fmp_t *fmp_,
void *slab_)
{
char *slab;
uint64_t objs_per_slab;
uint64_t objs_in_slab;
slab = (char*)slab_;
objs_in_slab = 0;
objs_per_slab = fmp_objs_per_slab(fmp_);
for(mem_stack_t *stack = fmp_->objs; stack != NULL; stack = stack->next)
{
char *obj = (char*)stack;
if((obj >= slab) && (obj < (slab + fmp_->slab_size)))
objs_in_slab++;
if(objs_in_slab >= objs_per_slab)
break;
}
return objs_in_slab;
}
static
inline
void
fmp_remove_objs_in_slab(fmp_t *fmp_,
void *slab_)
{
char *slab;
uint64_t objs_per_slab;
uint64_t objs_in_slab;
mem_stack_t **p;
p = &fmp_->objs;
slab = (char*)slab_;
objs_in_slab = 0;
objs_per_slab = fmp_objs_per_slab(fmp_);
while((*p) != NULL)
{
char *obj = (char*)*p;
if((obj >= slab) && (obj < (slab + fmp_->slab_size)))
{
objs_in_slab++;
*p = (*p)->next;
fmp_->avail_objs--;
if(objs_in_slab >= objs_per_slab)
break;
continue;
}
p = &(*p)->next;
}
}
static
inline
int
fmp_gc_slab(fmp_t *fmp_,
uint64_t slab_idx_)
{
char *slab;
uint64_t objs_in_slab;
uint64_t objs_per_slab;
slab_idx_ = (slab_idx_ % kv_size(fmp_->slabs));
slab = (char*)kv_A(fmp_->slabs,slab_idx_);
objs_per_slab = fmp_objs_per_slab(fmp_);
objs_in_slab = fmp_objs_in_slab(fmp_,slab);
if(objs_in_slab != objs_per_slab)
return 0;
fmp_remove_objs_in_slab(fmp_,slab);
kv_delete(fmp_->slabs,slab_idx_);
fmp_slab_free_mmap(fmp_,slab);
return 1;
}
static
inline
int
fmp_gc(fmp_t *fmp_)
{
uint64_t slab_idx;
slab_idx = rand();
return fmp_gc_slab(fmp_,slab_idx);
}
static
inline
double
fmp_slab_usage_ratio(fmp_t *fmp_)
{
double avail_objs;
double objs_per_slab;
double nums_of_slabs;
avail_objs = fmp_->avail_objs;
objs_per_slab = fmp_objs_per_slab(fmp_);
nums_of_slabs = kv_size(fmp_->slabs);
return (avail_objs / (objs_per_slab * nums_of_slabs));
}
static
inline
uint64_t
fmp_total_allocated_memory(fmp_t *fmp_)
{
return (fmp_->slab_size * kv_size(fmp_->slabs));
}

View file

@ -8,12 +8,6 @@
#include "fmt/format-inl.h" #include "fmt/format-inl.h"
FMT_BEGIN_NAMESPACE FMT_BEGIN_NAMESPACE
#if FMT_USE_LOCALE
template FMT_API locale_ref::locale_ref(const std::locale& loc); // DEPRECATED!
template FMT_API auto locale_ref::get<std::locale>() const -> std::locale;
#endif
namespace detail { namespace detail {
template FMT_API auto dragonbox::to_decimal(float x) noexcept template FMT_API auto dragonbox::to_decimal(float x) noexcept
@ -21,6 +15,12 @@ template FMT_API auto dragonbox::to_decimal(float x) noexcept
template FMT_API auto dragonbox::to_decimal(double x) noexcept template FMT_API auto dragonbox::to_decimal(double x) noexcept
-> dragonbox::decimal_fp<double>; -> dragonbox::decimal_fp<double>;
#if FMT_USE_LOCALE
// DEPRECATED! locale_ref in the detail namespace
template FMT_API locale_ref::locale_ref(const std::locale& loc);
template FMT_API auto locale_ref::get<std::locale>() const -> std::locale;
#endif
// Explicit instantiations for char. // Explicit instantiations for char.
template FMT_API auto thousands_sep_impl(locale_ref) template FMT_API auto thousands_sep_impl(locale_ref)
@ -30,13 +30,16 @@ template FMT_API auto decimal_point_impl(locale_ref) -> char;
// DEPRECATED! // DEPRECATED!
template FMT_API void buffer<char>::append(const char*, const char*); template FMT_API void buffer<char>::append(const char*, const char*);
// DEPRECATED!
template FMT_API void vformat_to(buffer<char>&, string_view,
typename vformat_args<>::type, locale_ref);
// Explicit instantiations for wchar_t. // Explicit instantiations for wchar_t.
template FMT_API auto thousands_sep_impl(locale_ref) template FMT_API auto thousands_sep_impl(locale_ref)
-> thousands_sep_result<wchar_t>; -> thousands_sep_result<wchar_t>;
template FMT_API auto decimal_point_impl(locale_ref) -> wchar_t; template FMT_API auto decimal_point_impl(locale_ref) -> wchar_t;
// DEPRECATED!
template FMT_API void buffer<wchar_t>::append(const wchar_t*, const wchar_t*); template FMT_API void buffer<wchar_t>::append(const wchar_t*, const wchar_t*);
} // namespace detail } // namespace detail

File diff suppressed because it is too large Load diff

21
libfuse/lib/fuse_cfg.cpp Normal file
View file

@ -0,0 +1,21 @@
#include "fuse_cfg.hpp"
fuse_cfg_t fuse_cfg;
bool
fuse_cfg_t::valid_uid() const
{
return (uid != FUSE_CFG_INVALID_ID);
}
bool
fuse_cfg_t::valid_gid() const
{
return (gid != FUSE_CFG_INVALID_ID);
}
bool
fuse_cfg_t::valid_umask() const
{
return (umask != FUSE_CFG_INVALID_UMASK);
}

View file

@ -20,9 +20,6 @@
/* 32KB - same as glibc getdents buffer size */ /* 32KB - same as glibc getdents buffer size */
#define DENTS_BUF_EXPAND_SIZE (1024 * 32) #define DENTS_BUF_EXPAND_SIZE (1024 * 32)
/* Initial pre-allocated capacity for directory-entry offset vector */
#define DENTS_OFFS_INITIAL_CAPACITY 64
static static
uint64_t uint64_t
_round_up(const uint64_t number_, _round_up(const uint64_t number_,
@ -149,7 +146,7 @@ fuse_dirents_init(fuse_dirents_t *d_)
return -ENOMEM; return -ENOMEM;
kv_init(d_->offs); kv_init(d_->offs);
kv_resize(uint32_t,d_->offs,DENTS_OFFS_INITIAL_CAPACITY); kv_resize(uint32_t,d_->offs,64);
kv_push(uint32_t,d_->offs,0); kv_push(uint32_t,d_->offs,0);
return 0; return 0;

98
libfuse/lib/fuse_i.h Normal file
View file

@ -0,0 +1,98 @@
/*
FUSE: Filesystem in Userspace
Copyright (C) 2001-2007 Miklos Szeredi <miklos@szeredi.hu>
This program can be distributed under the terms of the GNU LGPLv2.
See the file COPYING.LIB
*/
#pragma once
#include "fuse.h"
#include "fuse_lowlevel.h"
#include "fuse_msgbuf_t.h"
#include "extern_c.h"
struct fuse_chan;
struct fuse_ll;
struct fuse_session
{
int (*receive_buf)(struct fuse_session *se,
fuse_msgbuf_t *msgbuf);
void (*process_buf)(struct fuse_session *se,
const fuse_msgbuf_t *msgbuf);
void (*destroy)(void *data);
struct fuse_ll *f;
volatile int exited;
struct fuse_chan *ch;
};
struct fuse_notify_req
{
uint64_t unique;
void (*reply)(struct fuse_notify_req *,
fuse_req_t*,
uint64_t,
const void *);
struct fuse_notify_req *next;
struct fuse_notify_req *prev;
};
struct fuse_ll
{
struct fuse_lowlevel_ops op;
void *userdata;
uid_t owner;
struct fuse_conn_info conn;
pthread_mutex_t lock;
int got_init;
int got_destroy;
pthread_key_t pipe_key;
int broken_splice_nonblock;
uint64_t notify_ctr;
struct fuse_notify_req notify_list;
};
struct fuse_cmd
{
char *buf;
size_t buflen;
struct fuse_chan *ch;
};
EXTERN_C_BEGIN
struct fuse *fuse_new_common(struct fuse_chan *ch,
struct fuse_args *args,
const struct fuse_operations *op);
struct fuse_chan *fuse_kern_chan_new(int fd);
struct fuse_session *fuse_lowlevel_new_common(struct fuse_args *args,
const struct fuse_lowlevel_ops *op,
size_t op_size, void *userdata);
int fuse_chan_clearfd(struct fuse_chan *ch);
void fuse_kern_unmount(const char *mountpoint, int fd);
int fuse_kern_mount(const char *mountpoint, struct fuse_args *args);
int fuse_send_reply_iov_nofree(fuse_req_t req, int error, struct iovec *iov,
int count);
void fuse_free_req(fuse_req_t req);
struct fuse *fuse_setup_common(int argc,
char *argv[],
const struct fuse_operations *op,
char **mountpoint,
int *fd);
int fuse_start_thread(pthread_t *thread_id, void *(*func)(void *), void *arg);
EXTERN_C_END

9
libfuse/lib/fuse_ll.hpp Normal file
View file

@ -0,0 +1,9 @@
#pragma once
#include "fuse_msgbuf_t.h"
int fuse_receive_buf(struct fuse_session *se,
fuse_msgbuf_t *msgbuf);
void fuse_process_buf(void *data,
const fuse_msgbuf_t *msgbuf,
struct fuse_chan *ch);

Some files were not shown because too many files have changed in this diff Show more