Skip to content

Commit 27fa37e

Browse files
committed
Merge branch 'master' of D:\github\other\zz_urlencoder
2 parents 6f38233 + 10d68f3 commit 27fa37e

4 files changed

Lines changed: 54 additions & 0 deletions

File tree

.cargo/config

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
[build]
2+
rustflags = ["-Ctarget-feature=+crt-static", "-Zunstable-options"]

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
target
2+
Cargo.lock

Cargo.toml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
[package]
2+
authors = ["Liigo Zhuang <liigo@qq.com>"]
3+
name = "zz_urlencoder"
4+
version = "0.1.0"
5+
6+
[dependencies]
7+
url = "1.4.0"
8+
9+
[lib]
10+
crate-type = ["cdylib"]

src/lib.rs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
extern crate url;
2+
3+
use std::slice;
4+
use std::ptr;
5+
use url::form_urlencoded;
6+
7+
/// 对input文本执行`application/x-www-form-urlencoded`编码,结果写入buf缓冲区
8+
///
9+
/// 参数input为UTF-8格式的文本数据地址,inputlen是其字节数
10+
/// 参数buf为结果缓冲区,buflen是其字节数
11+
///
12+
/// 如果缓冲区长度不足以存放编码结果文本,将返回实际所需缓冲区字节数的负值,保持缓冲区内容不变
13+
/// 如果缓冲区长度足够,将向其写入编码结果文本和结尾'\0'字符,并返回写入的字节数(正值)
14+
///
15+
/// by Liigo, 20170207.
16+
#[no_mangle]
17+
pub extern fn form_urlencode(input: i32, inputlen: i32, buf: i32, buflen: i32) -> i32 {
18+
let utf8 = unsafe {
19+
slice::from_raw_parts_mut(input as *mut u8, inputlen as usize)
20+
};
21+
22+
let ss: Vec<&str> = form_urlencoded::byte_serialize(utf8).collect();
23+
let required_buflen = (ss.iter().map(|s| s.len()).sum::<usize>() + 1) as i32;
24+
25+
if buflen < required_buflen {
26+
return 0 - required_buflen;
27+
}
28+
29+
let mut pbuf = buf as *mut u8;
30+
for s in ss {
31+
unsafe {
32+
ptr::copy_nonoverlapping(s.as_ptr(), pbuf, s.len());
33+
pbuf = pbuf.offset(s.len() as isize);
34+
}
35+
}
36+
unsafe {
37+
ptr::write(pbuf, 0); // write the ending '\0'
38+
}
39+
required_buflen
40+
}

0 commit comments

Comments
 (0)