Last active: a year ago
useScrollLoading
import { useEffect, useRef } from 'react';
/**
* 利用 IntersectionObserver 实现滚动加载新数据的 hooks
*
* @param intersectedCallback 对应 anchor 相交时执行的回调
* @param option 判断条件,任意字段为 truthy 时不执行回调
*
* option 的变化才会使得重新 observe target
*
* @usage
* ```ts
* const { ref } = useScrollLoading(
* () => {
* setPage((d) => {
* d.page++;
* });
* },
* {
* loading,
Last active: a year ago
Rust RefCell and Rc stack overflow
use anyhow::Result;
use std::{cell::RefCell, rc::Rc};
#[derive(Debug)]
enum List {
Cons(i32, RefCell<Rc<List>>),
Nil,
}
impl List {
fn tail(&self) -> Option<&RefCell<Rc<List>>> {
match self {
List::Cons(_, item) => Some(item),
List::Nil => None,
}
}
}
fn main() -> Result<()> {
use List::*;
Last active: a year ago
Rust RefCell and Rc stack overflow
use anyhow::Result;
use std::{
cell::RefCell,
rc::{Rc, Weak},
};
#[derive(Debug)]
enum List {
Cons(i32, RefCell<Weak<List>>),
Nil,
}
impl List {
fn tail(&self) -> Option<&RefCell<Weak<List>>> {
match self {
List::Cons(_, item) => Some(item),
List::Nil => None,
}
}
}
Last active: a year ago
use anyhow::Result;
fn main() -> Result<()> {
let v = vec![1, 2, 3];
let p = &v;
let raw_p = p as *const Vec<i32>;
println!("{:?} ptr {:?}", p, raw_p);
let box_p = Box::new(raw_p);
let raw_box = &box_p as *const Box<_>;
println!("{:?} ptr {:?}", box_p, raw_box);
Ok(())
}
Last active: a year ago
rust optimize profile
[profile.release]
lto = true
panic = "abort" # Strip expensive panic clean-up logic
codegen-units = 1 # Compile crates one after another so the compiler can optimize better
opt-level = "s" # Optimize for binary size
strip = true # Remove debug symbols
Last active: a year ago
Use question mark handle error in map function
pub fn process(&self) -> Result<()> {
match self.mode {
Mode::Format => {
self.file_list
.iter()
.map(|file| self.format_process(file))
.collect::<Result<Vec<_>>>()?;
}
Mode::Compress => {
if self.output.exists() {
fs::remove_dir_all(&self.output)?;
}
fs::create_dir_all(&self.output)?;
self.file_list
.iter()
.map(|path| self.compress_process(path))
.collect::<Result<Vec<_>>>()?;
}
}
Ok(())
Last active: a year ago
/**
* 图片压缩
* @param base64 被压缩图片的 base64
* @param quality 压缩质量,0 ~ 1 之间,默认 0.2
* @returns
*/
const compressImage = async (
base64: string,
quality = 0.2,
): Promise<string> => {
const img = document.createElement('img');
img.src = base64;
const p = new Promise<string>((resolve, reject) => {
img.addEventListener('load', () => {
const canvas = document.createElement('canvas');
canvas.height = img.height;
canvas.width = img.width;
const ctx = canvas.getContext('2d');
if (!ctx) {
// throw new Error('cannot create canvas context');
Last active: a year ago
use futures::future::join_all;
use tokio::sync::broadcast;
#[tokio::main]
async fn main() {
let (tx, mut rx1) = broadcast::channel(16);
let mut rx2 = tx.subscribe();
let mut handles = vec![];
let h1 = tokio::spawn(async move {
while let Ok(res) = rx1.recv().await {
dbg!(&res);
}
dbg!("done");
});
handles.push(h1);
let h1 = tokio::spawn(async move {
assert_eq!(rx2.recv().await.unwrap(), 10);
Last active: a year ago
use anyhow::Result;
use tokio::time::Instant;
#[tokio::main]
async fn main() -> Result<()> {
let start = Instant::now();
let client = reqwest::Client::new();
let mut res = client
.get("https://speed.hetzner.de/100MB.bin")
.send()
.await?;
let latency: u128 = start.elapsed().as_millis();
println!("latency: {latency}ms");
let download_start = Instant::now();
// let len = res.content_length().unwrap();
// res.bytes().await?;
// let time = download_start.elapsed().as_nanos() as f64 / 1_000_000_000 as f64;
// let bytes_per_second = len / time as u64;
// println!("bytes per second: {}", bytes_per_second);
Last active: a year ago
#[derive(Debug, Clone, PartialEq)]
pub enum NodeType {
VMESS,
VLESS,
SS,
SSR,
TROJAN,
TROJANGO,
HTTPPROXY,
HTTPSPROXY,
SOCKS5,
HTTP2,
UNKNOWN,
}
impl From<&str> for NodeType {
fn from(value: &str) -> Self {
use NodeType::*;
match value {
"vmess" => VMESS,
"vless" => VLESS,
Last active: a year ago
import { useCallback, useMemo } from 'react';
import useStore from 'store';
import { UI } from 'store/ui-store';
/**
* Use global loading state
*
* @param key The key of loading state
* @param subUrl The key of subscriptions card array.
* If key param is `'subCard'` this param must be has value
*
* @usage
* ```ts
* const [loading, setLoading] = useLoading('subCrad', sub.url);
* setLoading.setTrue();
* ```
*
* ```ts
* const [loading, setLoading] = useLoading('updateAll');
* setLoading.setTrue();