+# Go
+export GOARCH
+export GOOS = linux
+export GOPATH = $(HOME)/gopath
+
+ifeq "$(BUILD_ARCH)" "x86_64"
+ GOARCH = amd64
+endif
+
+ifeq "$(BUILD_ARCH)" "aarch64"
+ GOARCH = arm64
+endif
+
+# Rust
+ifeq "$(BUILD_ARCH)" "riscv64"
+ RUST_ARCH = riscv64gc
+else
+ RUST_ARCH = $(BUILD_ARCH)
+endif
+
+RUST_PLATFORM = $(RUST_ARCH)-unknown-linux-gnu
+
+CARGO_PATH = $(DIR_APP)/.cargo
+CARGO_REGISTRY = /usr/share/cargo/registry
+
+CRATE_NAME = $(patsubst rust-%,%,$(firstword $(MAKEFILE_LIST)))
+CRATE_VER = $(VER)
+CRATE_PATH = $(CARGO_REGISTRY)/$(CRATE_NAME)-$(CRATE_VER)
+
+define CARGO_CONFIG
+[build]
+rustflags = [$(call join-with,$(COMMA)$(SPACE),$(foreach flag,$(RUSTFLAGS),"$(flag)"))]
+
+[env]
+CFLAGS = "$(CFLAGS)"
+CXXFLAGS = "$(CXXFLAGS)"
+LDFLAGS = "$(LDFLAGS)"
+
+[term]
+verbose = true
+
+[source]
+
+[source.local-registry]
+directory = "$(CARGO_REGISTRY)"
+
+[source.crates-io]
+registry = "https://crates.io"
+replace-with = "local-registry"
+endef
+export CARGO_CONFIG
+
+# Set to false if you want to skip the binary install step
+CARGO_HAS_BIN = true
+
+CARGO = \
+ CARGOPATH=$(CARGO_PATH) \
+ RUSTC_BOOTSTRAP=1 \
+ cargo \
+ --offline
+
+CARGO_OPTIONS = \
+ -Z avoid-dev-deps
+
+# Cargo dealocks on riscv64 when building on multiple cores at the same time
+ifeq "$(BUILD_ARCH)" "riscv64"
+ CARGO_OPTIONS += -j1
+else
+ CARGO_OPTIONS += $(MAKETUNING)
+endif
+
+define CARGO_PREPARE
+ mkdir -p $(CARGO_PATH) && \
+ echo "$${CARGO_CONFIG}" > $(CARGO_PATH)/config && \
+ rm -f Cargo.lock
+endef
+
+CARGO_BUILD = \
+ $(CARGO) \
+ build \
+ --release \
+ $(CARGO_OPTIONS)
+
+# Checks whether this crate has a right taregt
+CARGO_TARGET_CHECK = $(CARGO) metadata --format-version 1 --no-deps | \
+ jq -e ".packages[].targets[].kind | any(. == \"$(1)\")" | grep -q "true"
+
+define CARGO_INSTALL
+ mkdir -pv "$(CRATE_PATH)" && \
+ if $(call CARGO_TARGET_CHECK,lib) || $(call CARGO_TARGET_CHECK,rlib) || $(call CARGO_TARGET_CHECK,proc-macro); then \
+ awk \
+ '/^\\\[((.+\\\.)?((dev|build)-)?dependencies|features)/{f=1;next} /^\\\[/{f=0}; !f' \
+ < Cargo.toml > Cargo.toml.deps && \
+ $(CARGO) package -l | grep -wEv "Cargo.(lock|toml.orig)" \
+ | xargs -d "\n" cp -v --parents -a -t $(CRATE_PATH) && \
+ install -v -m 644 Cargo.toml.deps $(CRATE_PATH)/Cargo.toml && \
+ echo "{\"files\":{},\"package\":\"\"}" > $(CRATE_PATH)/.cargo-checksum.json; \
+ fi && \
+ if $(CARGO_HAS_BIN) && $(call CARGO_TARGET_CHECK,bin); then \
+ $(CARGO) install $(CARGO_OPTIONS) --no-track --path .; \
+ fi
+endef
+