add a example

This commit is contained in:
biluohc 2018-07-02 23:04:46 +08:00
parent 5287df2fe7
commit 42a6d37c43
5 changed files with 95 additions and 10 deletions

View File

@ -1,2 +1,2 @@
[workspace]
members = ["binding/rust"]
members = ["binding/rust", "binding/rust/example"]

View File

@ -0,0 +1,13 @@
[package]
name = "example"
version = "0.1.0"
authors = ["biluohc <biluohc@qq.com>"]
[dependencies]
[dependencies.ip2region]
path = "../"
# git = "https://github.com/lionsoul2014/ip2region"
# git = "https://github.com/biluohc/ip2region"
version = "*"
features = ["lazy"]

View File

@ -0,0 +1,58 @@
extern crate ip2region;
use ip2region::*;
use std::env;
use std::time::Instant;
// cargo run --release ../../../data/ip2region.db
static IPS: &'static [&'_ str] = &[
"117.136.105.202",
"47.95.47.253",
"127.0.0.1",
"10.0.0.1",
"1.1.1.1",
];
fn main() {
lazy();
overview();
}
fn lazy() {
for ip in IPS {
let start = Instant::now();
let res = memory_search(ip);
let end = start.elapsed().subsec_micros();
println!("lazy__ {:06} microseconds: {:?}", end, res);
}
}
fn overview() {
let args = env::args().skip(1).collect::<Vec<String>>();
let db_path = &args[0];
let mut ip2 = Ip2Region::new(db_path).unwrap();
let ip2o = ip2.to_owned().unwrap();
for ip in IPS {
let start = Instant::now();
let res = ip2o.memory_search(ip);
let end = start.elapsed().subsec_micros();
println!("memory {:06} microseconds: {:?}", end, res);
let start = Instant::now();
let res = ip2.binary_search(ip);
let end = start.elapsed().subsec_micros();
println!("binary {:06} microseconds: {:?}", end, res);
let start = Instant::now();
let res = ip2.btree_search(ip);
let end = start.elapsed().subsec_micros();
println!("btree {:06} microseconds: {:?}", end, res);
println!();
}
}

View File

@ -2,22 +2,33 @@
## 用法
基本都在 `src/main.rs``overview` 函数里,
都在 `src/example`
另外 `cargo doc --features lazy`可以看到所有`API`
另外 `cargo doc --features lazy` 可以看到所有 `API`
## `lazy` feature 直接把DB打包到二进制
### 添加依赖
复制下面的 toml 添加依赖即可使用,其 api 是 `memory_search`
只是目前 DB 足有3.2M,还是有些感人的。
注意 `#` 是 toml格式的注释文件前三行的 `path``git` 是引用包的方式,`path` 是按路径引用包,`git` 是按git项目地址按实际情况选一个。
```toml
[dependencies.ip2region]
git = "https://github.com/lionsoul2014/ip2region"
# git = "https://github.com/biluohc/ip2region"
# path = "../"
version = "*"
features = ["lazy"]
# features = ["lazy"]
```
### 代码
查看 `src/example/src/main.rs`
### `lazy` feature 把 DB 直接打包进二进制
取消上面 toml 的 `# features = ["lazy"]` 行的注释即可使用,其 api 是 `memory_search`
只是目前 DB 足有3.2M,还是有些感人的。
关键的一行是 `features = ["lazy"]` ,不需要则可以注释或者删掉。

View File

@ -11,12 +11,15 @@ mod db;
mod error;
pub use error::{Error, Result};
mod owned;
#[doc(hidden)]
pub use db::DB_PATH;
pub use owned::{OwnedIp2Region, OwnedIpInfo};
#[cfg(feature = "lazy")]
use db::DB_BYTES;
pub use db::DB_PATH;
#[cfg(feature = "lazy")]
pub use owned::memory_search;
pub use owned::{OwnedIp2Region, OwnedIpInfo};
const INDEX_BLOCK_LENGTH: u32 = 12;
const TOTAL_HEADER_LENGTH: usize = 8192;