From ea2c3354689c9c977e2d58d872df507ba22e00c8 Mon Sep 17 00:00:00 2001 From: Antonio Scandurra Date: Tue, 15 May 2018 14:02:29 +0200 Subject: [PATCH] Truncate existing file on save --- xray_core/src/buffer.rs | 3 ++- xray_server/src/fs.rs | 34 ++++++++++++++++++++-------------- 2 files changed, 22 insertions(+), 15 deletions(-) diff --git a/xray_core/src/buffer.rs b/xray_core/src/buffer.rs index ca9a9d9a..7bc101e2 100644 --- a/xray_core/src/buffer.rs +++ b/xray_core/src/buffer.rs @@ -1661,7 +1661,8 @@ impl BufferSnapshot { pub fn iter<'a>(&'a self) -> impl 'a + Iterator { self.fragments.iter().filter_map(|fragment| { if fragment.is_visible() { - Some(fragment.insertion.text.code_units.as_ref()) + let range = fragment.start_offset..fragment.end_offset; + Some(&fragment.insertion.text.code_units[range]) } else { None } diff --git a/xray_server/src/fs.rs b/xray_server/src/fs.rs index 5bb4c59b..345faf91 100644 --- a/xray_server/src/fs.rs +++ b/xray_server/src/fs.rs @@ -4,7 +4,7 @@ use parking_lot::Mutex; use std::char::decode_utf16; use std::ffi::OsString; use std::fs; -use std::io::{self, Read, Write}; +use std::io::{self, Read, Seek, SeekFrom, Write}; use std::os::unix::fs::MetadataExt; use std::path::PathBuf; use std::sync::Arc; @@ -196,21 +196,27 @@ impl xray_fs::File for File { let file = self.file.clone(); thread::spawn(move || { fn write(file: &mut fs::File, snapshot: BufferSnapshot) -> Result<(), io::Error> { - let mut buf_writer = io::BufWriter::new(file); - let mut encode_buf = [0_u8; 4]; - for character in snapshot - .iter() - .flat_map(|c| decode_utf16(c.iter().cloned())) + let mut size = 0_u64; { - let character = character.map_err(|_| { - io::Error::new( - io::ErrorKind::InvalidData, - "buffer did not contain valid UTF-8", - ) - })?; - let encoded_char = character.encode_utf8(&mut encode_buf); - buf_writer.write(encoded_char.as_bytes())?; + let mut buf_writer = io::BufWriter::new(&mut *file); + buf_writer.seek(SeekFrom::Start(0))?; + for character in snapshot + .iter() + .flat_map(|c| decode_utf16(c.iter().cloned())) + { + let character = character.map_err(|_| { + io::Error::new( + io::ErrorKind::InvalidData, + "buffer did not contain valid UTF-8", + ) + })?; + let mut encode_buf = [0_u8; 4]; + let encoded_char = character.encode_utf8(&mut encode_buf); + buf_writer.write(encoded_char.as_bytes())?; + size += encoded_char.len() as u64; + } } + file.set_len(size)?; Ok(()) }