Skip to content

Commit c676f64

Browse files
committed
ntex optimizations
1 parent 9147d8f commit c676f64

File tree

7 files changed

+85
-49
lines changed

7 files changed

+85
-49
lines changed

frameworks/Rust/ntex/src/db.rs

Lines changed: 31 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,28 @@ use ntex::util::{BufMut, Bytes, BytesMut};
66
use smallvec::SmallVec;
77
use tokio_postgres::types::ToSql;
88
use tokio_postgres::{connect, Client, Statement};
9-
use yarte::{ywrite_html, Serialize};
9+
use yarte::TemplateBytesTrait;
1010

1111
use super::utils;
1212

13-
#[derive(Copy, Clone, Serialize, Debug)]
13+
#[derive(Copy, Clone, Debug, sonic_rs::Serialize)]
1414
pub struct World {
1515
pub id: i32,
1616
pub randomnumber: i32,
1717
}
1818

19-
#[derive(Serialize, Debug)]
19+
#[derive(Debug, sonic_rs::Serialize)]
2020
pub struct Fortune {
2121
pub id: i32,
2222
pub message: Cow<'static, str>,
2323
}
2424

25+
#[derive(yarte::TemplateBytes)]
26+
#[template(path = "fortune.hbs")]
27+
pub struct FortunesTemplate<'a> {
28+
pub fortunes: &'a Vec<Fortune>,
29+
}
30+
2531
/// Postgres interface
2632
pub struct PgConnection {
2733
cl: Client,
@@ -30,6 +36,7 @@ pub struct PgConnection {
3036
rng: WyRand,
3137
updates: Vec<Statement>,
3238
buf: RefCell<BytesMut>,
39+
fbuf: RefCell<Vec<Fortune>>,
3340
}
3441

3542
impl PgConnection {
@@ -69,6 +76,7 @@ impl PgConnection {
6976
updates,
7077
rng: WyRand::new(),
7178
buf: RefCell::new(BytesMut::with_capacity(10 * 1024 * 1024)),
79+
fbuf: RefCell::new(Vec::with_capacity(64)),
7280
}
7381
}
7482
}
@@ -81,11 +89,14 @@ impl PgConnection {
8189

8290
let mut body = self.buf.borrow_mut();
8391
utils::reserve(&mut body, 1024);
84-
World {
85-
id: row.get(0),
86-
randomnumber: row.get(1),
87-
}
88-
.to_bytes_mut(&mut *body);
92+
sonic_rs::to_writer(
93+
utils::BytesWriter(&mut body),
94+
&World {
95+
id: row.get(0),
96+
randomnumber: row.get(1),
97+
},
98+
)
99+
.unwrap();
89100
body.split().freeze()
90101
}
91102

@@ -110,7 +121,7 @@ impl PgConnection {
110121
utils::reserve(&mut body, 2 * 1024);
111122
body.put_u8(b'[');
112123
worlds.iter().for_each(|w| {
113-
w.to_bytes_mut(&mut *body);
124+
sonic_rs::to_writer(utils::BytesWriter(&mut body), w).unwrap();
114125
body.put_u8(b',');
115126
});
116127
let idx = body.len() - 1;
@@ -149,7 +160,7 @@ impl PgConnection {
149160
utils::reserve(&mut body, 2 * 1024);
150161
body.put_u8(b'[');
151162
worlds.iter().for_each(|w| {
152-
w.to_bytes_mut(&mut *body);
163+
sonic_rs::to_writer(utils::BytesWriter(&mut body), w).unwrap();
153164
body.put_u8(b',');
154165
});
155166
let idx = body.len() - 1;
@@ -160,10 +171,11 @@ impl PgConnection {
160171
pub async fn tell_fortune(&self) -> Bytes {
161172
let rows = self.cl.query_raw(&self.fortune, &[]).await.unwrap();
162173

163-
let mut fortunes: SmallVec<[_; 32]> = smallvec::smallvec![Fortune {
174+
let mut fortunes = self.fbuf.borrow_mut();
175+
fortunes.push(Fortune {
164176
id: 0,
165177
message: Cow::Borrowed("Additional fortune added at request time."),
166-
}];
178+
});
167179
fortunes.extend(rows.iter().map(|row| Fortune {
168180
id: row.get(0),
169181
message: Cow::Owned(row.get(1)),
@@ -172,7 +184,13 @@ impl PgConnection {
172184

173185
let mut body = std::mem::replace(&mut *self.buf.borrow_mut(), BytesMut::new());
174186
utils::reserve(&mut body, 4 * 1024);
175-
ywrite_html!(body, "{{> fortune }}");
187+
188+
FortunesTemplate {
189+
fortunes: &*fortunes,
190+
}
191+
.write_call(&mut body);
192+
fortunes.clear();
193+
176194
let result = body.split().freeze();
177195
let _ = std::mem::replace(&mut *self.buf.borrow_mut(), body);
178196
result

frameworks/Rust/ntex/src/main.rs

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
33

44
use ntex::http::header::{CONTENT_TYPE, SERVER};
55
use ntex::{http, time::Seconds, util::BytesMut, util::PoolId, util::Ready, web};
6-
use yarte::Serialize;
6+
use sonic_rs::Serialize;
77

88
mod utils;
99

@@ -15,10 +15,13 @@ pub struct Message {
1515
#[web::get("/json")]
1616
async fn json() -> web::HttpResponse {
1717
let mut body = BytesMut::with_capacity(utils::SIZE);
18-
Message {
19-
message: "Hello, World!",
20-
}
21-
.to_bytes_mut(&mut body);
18+
sonic_rs::to_writer(
19+
utils::BytesWriter(&mut body),
20+
&Message {
21+
message: "Hello, World!",
22+
},
23+
)
24+
.unwrap();
2225

2326
let mut response = web::HttpResponse::with_body(http::StatusCode::OK, body.into());
2427
response.headers_mut().insert(SERVER, utils::HDR_SERVER);

frameworks/Rust/ntex/src/main_plt.rs

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use std::{future::Future, io, pin::Pin, task::Context, task::Poll};
55

66
use ntex::util::{ready, PoolId, Ready};
77
use ntex::{fn_service, http::h1, io::Io, io::RecvError};
8-
use yarte::Serialize;
8+
use sonic_rs::Serialize;
99

1010
mod utils;
1111

@@ -43,10 +43,13 @@ impl Future for App {
4343
buf.extend_from_slice(JSON);
4444
this.codec.set_date_header(buf);
4545

46-
Message {
47-
message: "Hello, World!",
48-
}
49-
.to_bytes_mut(buf);
46+
sonic_rs::to_writer(
47+
utils::BytesWriter(buf),
48+
&Message {
49+
message: "Hello, World!",
50+
},
51+
)
52+
.unwrap();
5053
}
5154
"/plaintext" => {
5255
buf.extend_from_slice(PLAIN);

frameworks/Rust/ntex/src/utils.rs

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
#![allow(dead_code)]
2-
use std::cmp;
2+
use std::{cmp, io, io::Write, mem::MaybeUninit, slice::from_raw_parts_mut};
33

44
use atoi::FromRadix10;
55
use ntex::{http::header::HeaderValue, util::BufMut, util::Bytes, util::BytesMut};
6+
use sonic_rs::writer::WriteExt;
67

78
pub const HDR_SERVER: HeaderValue = HeaderValue::from_static("N");
89
pub const HDR_JSON_CONTENT_TYPE: HeaderValue = HeaderValue::from_static("application/json");
@@ -30,3 +31,36 @@ pub fn reserve(buf: &mut BytesMut, lw: usize) {
3031
buf.reserve(HW);
3132
}
3233
}
34+
35+
pub struct BytesWriter<'a>(pub &'a mut BytesMut);
36+
37+
impl<'a> Write for BytesWriter<'a> {
38+
fn write(&mut self, src: &[u8]) -> Result<usize, io::Error> {
39+
self.0.extend_from_slice(src);
40+
Ok(src.len())
41+
}
42+
43+
fn flush(&mut self) -> Result<(), io::Error> {
44+
Ok(())
45+
}
46+
}
47+
48+
impl<'a> WriteExt for BytesWriter<'a> {
49+
#[inline(always)]
50+
fn reserve_with(&mut self, additional: usize) -> Result<&mut [MaybeUninit<u8>], io::Error> {
51+
self.0.reserve(additional);
52+
53+
unsafe {
54+
let ptr = self.0.as_mut_ptr().add(self.0.len()) as *mut MaybeUninit<u8>;
55+
Ok(from_raw_parts_mut(ptr, additional))
56+
}
57+
}
58+
59+
#[inline(always)]
60+
unsafe fn flush_len(&mut self, additional: usize) {
61+
unsafe {
62+
let new_len = self.0.len() + additional;
63+
self.0.set_len(new_len);
64+
}
65+
}
66+
}
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>
2-
{{~# each fortunes ~}}
3-
<tr><td>{{id}}</td><td>{{message}}</td></tr>
4-
{{~/each ~}}
2+
{{~# each fortunes ~}}
3+
<tr><td>{{id}}</td><td>{{message}}</td></tr>
4+
{{~/each ~}}
55
</table></body></html>

frameworks/Rust/ntex/templates/fortune.html

Lines changed: 0 additions & 12 deletions
This file was deleted.

frameworks/Rust/ntex/templates/fortune.stpl

Lines changed: 0 additions & 10 deletions
This file was deleted.

0 commit comments

Comments
 (0)