Skip to content

Commit ed0350e

Browse files
committed
Auto merge of #51356 - Zoxc:encode-cleanup, r=michaelwoerister
Make opaque::Encoder append-only and make it infallible
2 parents 142c98d + 14d3c6e commit ed0350e

File tree

12 files changed

+80
-118
lines changed

12 files changed

+80
-118
lines changed

src/librustc/ich/fingerprint.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,8 @@ impl Fingerprint {
5252
pub fn encode_opaque(&self, encoder: &mut Encoder) -> EncodeResult {
5353
let bytes: [u8; 16] = unsafe { mem::transmute([self.0.to_le(), self.1.to_le()]) };
5454

55-
encoder.emit_raw_bytes(&bytes)
55+
encoder.emit_raw_bytes(&bytes);
56+
Ok(())
5657
}
5758

5859
pub fn decode_opaque<'a>(decoder: &mut Decoder<'a>) -> Result<Fingerprint, String> {
@@ -92,7 +93,7 @@ impl serialize::UseSpecializedEncodable for Fingerprint { }
9293

9394
impl serialize::UseSpecializedDecodable for Fingerprint { }
9495

95-
impl<'a> serialize::SpecializedEncoder<Fingerprint> for serialize::opaque::Encoder<'a> {
96+
impl serialize::SpecializedEncoder<Fingerprint> for serialize::opaque::Encoder {
9697
fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
9798
f.encode_opaque(self)
9899
}

src/librustc/ty/codec.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ pub trait TyEncoder: Encoder {
5454
fn position(&self) -> usize;
5555
}
5656

57-
impl<'buf> TyEncoder for opaque::Encoder<'buf> {
57+
impl TyEncoder for opaque::Encoder {
5858
#[inline]
5959
fn position(&self) -> usize {
6060
self.position()

src/librustc/ty/query/on_disk_cache.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -979,7 +979,7 @@ impl<'enc, 'a, 'tcx, E> SpecializedEncoder<NodeId> for CacheEncoder<'enc, 'a, 't
979979
}
980980

981981
impl<'enc, 'a, 'tcx> SpecializedEncoder<Fingerprint>
982-
for CacheEncoder<'enc, 'a, 'tcx, opaque::Encoder<'enc>>
982+
for CacheEncoder<'enc, 'a, 'tcx, opaque::Encoder>
983983
{
984984
fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
985985
f.encode_opaque(&mut self.encoder)
@@ -1057,7 +1057,7 @@ impl IntEncodedWithFixedSize {
10571057
impl UseSpecializedEncodable for IntEncodedWithFixedSize {}
10581058
impl UseSpecializedDecodable for IntEncodedWithFixedSize {}
10591059

1060-
impl<'enc> SpecializedEncoder<IntEncodedWithFixedSize> for opaque::Encoder<'enc> {
1060+
impl SpecializedEncoder<IntEncodedWithFixedSize> for opaque::Encoder {
10611061
fn specialized_encode(&mut self, x: &IntEncodedWithFixedSize) -> Result<(), Self::Error> {
10621062
let start_pos = self.position();
10631063
for i in 0 .. IntEncodedWithFixedSize::ENCODED_SIZE {

src/librustc_codegen_llvm/back/wasm.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -230,8 +230,7 @@ impl WasmEncoder {
230230
}
231231

232232
fn u32(&mut self, val: u32) {
233-
let at = self.data.len();
234-
leb128::write_u32_leb128(&mut self.data, at, val);
233+
leb128::write_u32_leb128(&mut self.data, val);
235234
}
236235

237236
fn byte(&mut self, val: u8) {

src/librustc_incremental/persist/file_format.rs

+7-8
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ use std::fs;
2525
use std::env;
2626

2727
use rustc::session::config::nightly_options;
28+
use rustc_serialize::opaque::Encoder;
2829

2930
/// The first few bytes of files generated by incremental compilation
3031
const FILE_MAGIC: &'static [u8] = b"RSIC";
@@ -37,17 +38,15 @@ const HEADER_FORMAT_VERSION: u16 = 0;
3738
/// the git commit hash.
3839
const RUSTC_VERSION: Option<&'static str> = option_env!("CFG_VERSION");
3940

40-
pub fn write_file_header<W: io::Write>(stream: &mut W) -> io::Result<()> {
41-
stream.write_all(FILE_MAGIC)?;
42-
stream.write_all(&[(HEADER_FORMAT_VERSION >> 0) as u8,
43-
(HEADER_FORMAT_VERSION >> 8) as u8])?;
41+
pub fn write_file_header(stream: &mut Encoder) {
42+
stream.emit_raw_bytes(FILE_MAGIC);
43+
stream.emit_raw_bytes(&[(HEADER_FORMAT_VERSION >> 0) as u8,
44+
(HEADER_FORMAT_VERSION >> 8) as u8]);
4445

4546
let rustc_version = rustc_version();
4647
assert_eq!(rustc_version.len(), (rustc_version.len() as u8) as usize);
47-
stream.write_all(&[rustc_version.len() as u8])?;
48-
stream.write_all(rustc_version.as_bytes())?;
49-
50-
Ok(())
48+
stream.emit_raw_bytes(&[rustc_version.len() as u8]);
49+
stream.emit_raw_bytes(rustc_version.as_bytes());
5150
}
5251

5352
/// Reads the contents of a file with a file header as defined in this module.

src/librustc_incremental/persist/save.rs

+13-26
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ use rustc_data_structures::fx::FxHashMap;
1616
use rustc_data_structures::sync::join;
1717
use rustc_serialize::Encodable as RustcEncodable;
1818
use rustc_serialize::opaque::Encoder;
19-
use std::io::{self, Cursor};
2019
use std::fs;
2120
use std::path::PathBuf;
2221

@@ -98,7 +97,7 @@ pub fn save_work_product_index(sess: &Session,
9897
}
9998

10099
fn save_in<F>(sess: &Session, path_buf: PathBuf, encode: F)
101-
where F: FnOnce(&mut Encoder) -> io::Result<()>
100+
where F: FnOnce(&mut Encoder)
102101
{
103102
debug!("save: storing data in {}", path_buf.display());
104103

@@ -121,20 +120,12 @@ fn save_in<F>(sess: &Session, path_buf: PathBuf, encode: F)
121120
}
122121

123122
// generate the data in a memory buffer
124-
let mut wr = Cursor::new(Vec::new());
125-
file_format::write_file_header(&mut wr).unwrap();
126-
match encode(&mut Encoder::new(&mut wr)) {
127-
Ok(()) => {}
128-
Err(err) => {
129-
sess.err(&format!("could not encode dep-graph to `{}`: {}",
130-
path_buf.display(),
131-
err));
132-
return;
133-
}
134-
}
123+
let mut encoder = Encoder::new(Vec::new());
124+
file_format::write_file_header(&mut encoder);
125+
encode(&mut encoder);
135126

136127
// write the data out
137-
let data = wr.into_inner();
128+
let data = encoder.into_inner();
138129
match fs::write(&path_buf, data) {
139130
Ok(_) => {
140131
debug!("save: data written to disk successfully");
@@ -149,10 +140,9 @@ fn save_in<F>(sess: &Session, path_buf: PathBuf, encode: F)
149140
}
150141

151142
fn encode_dep_graph(tcx: TyCtxt,
152-
encoder: &mut Encoder)
153-
-> io::Result<()> {
143+
encoder: &mut Encoder) {
154144
// First encode the commandline arguments hash
155-
tcx.sess.opts.dep_tracking_hash().encode(encoder)?;
145+
tcx.sess.opts.dep_tracking_hash().encode(encoder).unwrap();
156146

157147
// Encode the graph data.
158148
let serialized_graph = time(tcx.sess, "getting serialized graph", || {
@@ -234,14 +224,12 @@ fn encode_dep_graph(tcx: TyCtxt,
234224
}
235225

236226
time(tcx.sess, "encoding serialized graph", || {
237-
serialized_graph.encode(encoder)
238-
})?;
239-
240-
Ok(())
227+
serialized_graph.encode(encoder).unwrap();
228+
});
241229
}
242230

243231
fn encode_work_product_index(work_products: &FxHashMap<WorkProductId, WorkProduct>,
244-
encoder: &mut Encoder) -> io::Result<()> {
232+
encoder: &mut Encoder) {
245233
let serialized_products: Vec<_> = work_products
246234
.iter()
247235
.map(|(id, work_product)| {
@@ -252,13 +240,12 @@ fn encode_work_product_index(work_products: &FxHashMap<WorkProductId, WorkProduc
252240
})
253241
.collect();
254242

255-
serialized_products.encode(encoder)
243+
serialized_products.encode(encoder).unwrap();
256244
}
257245

258246
fn encode_query_cache(tcx: TyCtxt,
259-
encoder: &mut Encoder)
260-
-> io::Result<()> {
247+
encoder: &mut Encoder) {
261248
time(tcx.sess, "serialize query result cache", || {
262-
tcx.serialize_query_result_cache(encoder)
249+
tcx.serialize_query_result_cache(encoder).unwrap();
263250
})
264251
}

src/librustc_metadata/encoder.rs

+11-13
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,6 @@ use rustc_data_structures::stable_hasher::StableHasher;
3535
use rustc_serialize::{Encodable, Encoder, SpecializedEncoder, opaque};
3636

3737
use std::hash::Hash;
38-
use std::io::prelude::*;
39-
use std::io::Cursor;
4038
use std::path::Path;
4139
use rustc_data_structures::sync::Lrc;
4240
use std::u32;
@@ -52,7 +50,7 @@ use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
5250
use rustc::hir::intravisit;
5351

5452
pub struct EncodeContext<'a, 'tcx: 'a> {
55-
opaque: opaque::Encoder<'a>,
53+
opaque: opaque::Encoder,
5654
pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
5755
link_meta: &'a LinkMeta,
5856

@@ -76,7 +74,7 @@ macro_rules! encoder_methods {
7674
}
7775

7876
impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
79-
type Error = <opaque::Encoder<'a> as Encoder>::Error;
77+
type Error = <opaque::Encoder as Encoder>::Error;
8078

8179
fn emit_nil(&mut self) -> Result<(), Self::Error> {
8280
Ok(())
@@ -480,7 +478,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
480478

481479
// Index the items
482480
i = self.position();
483-
let index = items.write_index(&mut self.opaque.cursor);
481+
let index = items.write_index(&mut self.opaque);
484482
let index_bytes = self.position() - i;
485483

486484
let attrs = tcx.hir.krate_attrs();
@@ -537,7 +535,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
537535

538536
if self.tcx.sess.meta_stats() {
539537
let mut zero_bytes = 0;
540-
for e in self.opaque.cursor.get_ref() {
538+
for e in self.opaque.data.iter() {
541539
if *e == 0 {
542540
zero_bytes += 1;
543541
}
@@ -1797,15 +1795,15 @@ pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
17971795
link_meta: &LinkMeta)
17981796
-> EncodedMetadata
17991797
{
1800-
let mut cursor = Cursor::new(vec![]);
1801-
cursor.write_all(METADATA_HEADER).unwrap();
1798+
let mut encoder = opaque::Encoder::new(vec![]);
1799+
encoder.emit_raw_bytes(METADATA_HEADER);
18021800

18031801
// Will be filled with the root position after encoding everything.
1804-
cursor.write_all(&[0, 0, 0, 0]).unwrap();
1802+
encoder.emit_raw_bytes(&[0, 0, 0, 0]);
18051803

1806-
let root = {
1804+
let (root, mut result) = {
18071805
let mut ecx = EncodeContext {
1808-
opaque: opaque::Encoder::new(&mut cursor),
1806+
opaque: encoder,
18091807
tcx,
18101808
link_meta,
18111809
lazy_state: LazyState::NoNode,
@@ -1821,9 +1819,9 @@ pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
18211819

18221820
// Encode all the entries and extra information in the crate,
18231821
// culminating in the `CrateRoot` which points to all of it.
1824-
ecx.encode_crate_root()
1822+
let root = ecx.encode_crate_root();
1823+
(root, ecx.opaque.into_inner())
18251824
};
1826-
let mut result = cursor.into_inner();
18271825

18281826
// Encode the root position.
18291827
let header = METADATA_HEADER.len();

src/librustc_metadata/index.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
use schema::*;
1212

1313
use rustc::hir::def_id::{DefId, DefIndex, DefIndexAddressSpace};
14-
use std::io::{Cursor, Write};
14+
use rustc_serialize::opaque::Encoder;
1515
use std::slice;
1616
use std::u32;
1717

@@ -54,15 +54,15 @@ impl Index {
5454
self.positions[space_index][array_index] = position.to_le();
5555
}
5656

57-
pub fn write_index(&self, buf: &mut Cursor<Vec<u8>>) -> LazySeq<Index> {
57+
pub fn write_index(&self, buf: &mut Encoder) -> LazySeq<Index> {
5858
let pos = buf.position();
5959

6060
// First we write the length of the lower range ...
61-
buf.write_all(words_to_bytes(&[(self.positions[0].len() as u32).to_le()])).unwrap();
61+
buf.emit_raw_bytes(words_to_bytes(&[(self.positions[0].len() as u32).to_le()]));
6262
// ... then the values in the lower range ...
63-
buf.write_all(words_to_bytes(&self.positions[0][..])).unwrap();
63+
buf.emit_raw_bytes(words_to_bytes(&self.positions[0][..]));
6464
// ... then the values in the higher range.
65-
buf.write_all(words_to_bytes(&self.positions[1][..])).unwrap();
65+
buf.emit_raw_bytes(words_to_bytes(&self.positions[1][..]));
6666
LazySeq::with_position_and_length(pos as usize,
6767
self.positions[0].len() + self.positions[1].len() + 1)
6868
}

src/libserialize/leb128.rs

+11-27
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,8 @@
99
// except according to those terms.
1010

1111
#[inline]
12-
pub fn write_to_vec(vec: &mut Vec<u8>, position: usize, byte: u8) {
13-
if position == vec.len() {
14-
vec.push(byte);
15-
} else {
16-
vec[position] = byte;
17-
}
12+
pub fn write_to_vec(vec: &mut Vec<u8>, byte: u8) {
13+
vec.push(byte);
1814
}
1915

2016
#[cfg(target_pointer_width = "32")]
@@ -33,24 +29,20 @@ macro_rules! leb128_size {
3329
macro_rules! impl_write_unsigned_leb128 {
3430
($fn_name:ident, $int_ty:ident) => (
3531
#[inline]
36-
pub fn $fn_name(out: &mut Vec<u8>, start_position: usize, mut value: $int_ty) -> usize {
37-
let mut position = start_position;
32+
pub fn $fn_name(out: &mut Vec<u8>, mut value: $int_ty) {
3833
for _ in 0 .. leb128_size!($int_ty) {
3934
let mut byte = (value & 0x7F) as u8;
4035
value >>= 7;
4136
if value != 0 {
4237
byte |= 0x80;
4338
}
4439

45-
write_to_vec(out, position, byte);
46-
position += 1;
40+
write_to_vec(out, byte);
4741

4842
if value == 0 {
4943
break;
5044
}
5145
}
52-
53-
position - start_position
5446
}
5547
)
5648
}
@@ -105,11 +97,9 @@ impl_read_unsigned_leb128!(read_usize_leb128, usize);
10597
/// The callback `write` is called once for each position
10698
/// that is to be written to with the byte to be encoded
10799
/// at that position.
108-
pub fn write_signed_leb128_to<W>(mut value: i128, mut write: W) -> usize
109-
where W: FnMut(usize, u8)
100+
pub fn write_signed_leb128_to<W>(mut value: i128, mut write: W)
101+
where W: FnMut(u8)
110102
{
111-
let mut position = 0;
112-
113103
loop {
114104
let mut byte = (value as u8) & 0x7f;
115105
value >>= 7;
@@ -120,18 +110,16 @@ pub fn write_signed_leb128_to<W>(mut value: i128, mut write: W) -> usize
120110
byte |= 0x80; // Mark this byte to show that more bytes will follow.
121111
}
122112

123-
write(position, byte);
124-
position += 1;
113+
write(byte);
125114

126115
if !more {
127116
break;
128117
}
129118
}
130-
position
131119
}
132120

133-
pub fn write_signed_leb128(out: &mut Vec<u8>, start_position: usize, value: i128) -> usize {
134-
write_signed_leb128_to(value, |i, v| write_to_vec(out, start_position+i, v))
121+
pub fn write_signed_leb128(out: &mut Vec<u8>, value: i128) {
122+
write_signed_leb128_to(value, |v| write_to_vec(out, v))
135123
}
136124

137125
#[inline]
@@ -167,9 +155,7 @@ macro_rules! impl_test_unsigned_leb128 {
167155
let mut stream = Vec::new();
168156

169157
for x in 0..62 {
170-
let pos = stream.len();
171-
let bytes_written = $write_fn_name(&mut stream, pos, (3u64 << x) as $int_ty);
172-
assert_eq!(stream.len(), pos + bytes_written);
158+
$write_fn_name(&mut stream, (3u64 << x) as $int_ty);
173159
}
174160

175161
let mut position = 0;
@@ -195,9 +181,7 @@ fn test_signed_leb128() {
195181
let values: Vec<_> = (-500..500).map(|i| i * 0x12345789ABCDEF).collect();
196182
let mut stream = Vec::new();
197183
for &x in &values {
198-
let pos = stream.len();
199-
let bytes_written = write_signed_leb128(&mut stream, pos, x);
200-
assert_eq!(stream.len(), pos + bytes_written);
184+
write_signed_leb128(&mut stream, x);
201185
}
202186
let mut pos = 0;
203187
for &x in &values {

src/libserialize/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ Core encoding and decoding interfaces.
2323
#![feature(box_syntax)]
2424
#![feature(core_intrinsics)]
2525
#![feature(specialization)]
26+
#![feature(never_type)]
2627
#![cfg_attr(test, feature(test))]
2728

2829
pub use self::serialize::{Decoder, Encoder, Decodable, Encodable};

0 commit comments

Comments
 (0)