Skip to content

Commit

Permalink
perf: accelerate kitty graphics protocol encoding by avoiding string …
Browse files Browse the repository at this point in the history
…reallocation (#837)
  • Loading branch information
sxyazi authored Mar 23, 2024
1 parent 9ba4714 commit f8e0aee
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 6 deletions.
7 changes: 4 additions & 3 deletions yazi-adaptor/src/kitty.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use core::str;
use std::{io::{stderr, BufWriter, Write}, path::Path};

use anyhow::Result;
Expand Down Expand Up @@ -344,7 +345,7 @@ impl Kitty {

async fn encode(img: DynamicImage) -> Result<Vec<u8>> {
fn output(raw: &[u8], format: u8, size: (u32, u32)) -> Result<Vec<u8>> {
let b64: Vec<_> = general_purpose::STANDARD.encode(raw).chars().collect();
let b64 = general_purpose::STANDARD.encode(raw).into_bytes();

let mut it = b64.chunks(4096).peekable();
let mut buf = Vec::with_capacity(b64.len() + it.len() * 50);
Expand All @@ -357,7 +358,7 @@ impl Kitty {
size.0,
size.1,
it.peek().is_some() as u8,
first.iter().collect::<String>(),
unsafe { str::from_utf8_unchecked(first) },
ESCAPE,
CLOSE
)?;
Expand All @@ -369,7 +370,7 @@ impl Kitty {
"{}_Gm={};{}{}\\{}",
START,
it.peek().is_some() as u8,
chunk.iter().collect::<String>(),
unsafe { str::from_utf8_unchecked(chunk) },
ESCAPE,
CLOSE
)?;
Expand Down
7 changes: 4 additions & 3 deletions yazi-adaptor/src/kitty_old.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use core::str;
use std::{io::{stderr, Write}, path::Path};

use anyhow::Result;
Expand Down Expand Up @@ -35,7 +36,7 @@ impl KittyOld {

async fn encode(img: DynamicImage) -> Result<Vec<u8>> {
fn output(raw: &[u8], format: u8, size: (u32, u32)) -> Result<Vec<u8>> {
let b64: Vec<_> = general_purpose::STANDARD.encode(raw).chars().collect();
let b64 = general_purpose::STANDARD.encode(raw).into_bytes();

let mut it = b64.chunks(4096).peekable();
let mut buf = Vec::with_capacity(b64.len() + it.len() * 50);
Expand All @@ -48,7 +49,7 @@ impl KittyOld {
size.0,
size.1,
it.peek().is_some() as u8,
first.iter().collect::<String>(),
unsafe { str::from_utf8_unchecked(first) },
ESCAPE,
CLOSE
)?;
Expand All @@ -60,7 +61,7 @@ impl KittyOld {
"{}_Gm={};{}{}\\{}",
START,
it.peek().is_some() as u8,
chunk.iter().collect::<String>(),
unsafe { str::from_utf8_unchecked(chunk) },
ESCAPE,
CLOSE
)?;
Expand Down

0 comments on commit f8e0aee

Please sign in to comment.