]>
git.proxmox.com Git - rustc.git/blob - vendor/rustfix/src/replace.rs
1 //! A small module giving you a simple container that allows easy and cheap
2 //! replacement of parts of its content, with the ability to prevent changing
3 //! the same parts multiple times.
5 use anyhow
::{anyhow, ensure, Error}
;
8 #[derive(Debug, Clone, PartialEq, Eq)]
16 fn is_inserted(&self) -> bool
{
17 matches
!(*self, State
::Inserted(..))
21 #[derive(Debug, Clone, PartialEq, Eq)]
23 /// Start of this span in parent data
25 /// up to end including
30 /// A container that allows easily replacing chunks of its data
31 #[derive(Debug, Clone, Default)]
38 /// Create a new data container from a slice of bytes
39 pub fn new(data
: &[u8]) -> Self {
41 original
: data
.into(),
45 end
: data
.len().saturating_sub(1),
50 /// Render this data as a vector of bytes
51 pub fn to_vec(&self) -> Vec
<u8> {
52 if self.original
.is_empty() {
56 self.parts
.iter().fold(Vec
::new(), |mut acc
, d
| {
58 State
::Initial
=> acc
.extend_from_slice(&self.original
[d
.start
..=d
.end
]),
59 State
::Replaced(ref d
) | State
::Inserted(ref d
) => acc
.extend_from_slice(&d
),
65 /// Replace a chunk of data with the given slice, erroring when this part
66 /// was already changed previously.
70 up_to_and_including
: usize,
72 ) -> Result
<(), Error
> {
73 let exclusive_end
= up_to_and_including
+ 1;
76 from
<= exclusive_end
,
77 "Invalid range {}...{}, start is larger than end",
83 up_to_and_including
<= self.original
.len(),
84 "Invalid range {}...{} given, original data is only {} byte long",
90 let insert_only
= from
== exclusive_end
;
92 // Since we error out when replacing an already replaced chunk of data,
93 // we can take some shortcuts here. For example, there can be no
94 // overlapping replacements -- we _always_ split a chunk of 'initial'
95 // data into three[^empty] parts, and there can't ever be two 'initial'
98 // [^empty]: Leading and trailing ones might be empty if we replace
99 // the whole chunk. As an optimization and without loss of generality we
100 // don't add empty parts.
102 let index_of_part_to_split
= self
106 !p
.data
.is_inserted() && p
.start
<= from
&& p
.end
>= up_to_and_including
109 use log
::Level
::Debug
;
110 if log_enabled
!(Debug
) {
119 State
::Initial
=> "initial",
120 State
::Replaced(..) => "replaced",
121 State
::Inserted(..) => "inserted",
125 .collect
::<Vec
<_
>>();
127 "no single slice covering {}...{}, current slices: {:?}",
128 from
, up_to_and_including
, slices
,
133 "Could not replace range {}...{} in file \
134 -- maybe parts of it were already replaced?",
140 let part_to_split
= &self.parts
[index_of_part_to_split
];
142 // If this replacement matches exactly the part that we would
143 // otherwise split then we ignore this for now. This means that you
144 // can replace the exact same range with the exact same content
145 // multiple times and we'll process and allow it.
147 // This is currently done to alleviate issues like
148 // rust-lang/rust#51211 although this clause likely wants to be
149 // removed if that's fixed deeper in the compiler.
150 if part_to_split
.start
== from
&& part_to_split
.end
== up_to_and_including
{
151 if let State
::Replaced(ref replacement
) = part_to_split
.data
{
152 if &**replacement
== data
{
159 part_to_split
.data
== State
::Initial
,
160 "Cannot replace slice of data that was already replaced"
163 let mut new_parts
= Vec
::with_capacity(self.parts
.len() + 2);
166 if let Some(ps
) = self.parts
.get(..index_of_part_to_split
) {
167 new_parts
.extend_from_slice(&ps
);
170 // Keep initial data on left side of part
171 if from
> part_to_split
.start
{
172 new_parts
.push(Span
{
173 start
: part_to_split
.start
,
174 end
: from
.saturating_sub(1),
175 data
: State
::Initial
,
180 new_parts
.push(Span
{
182 end
: up_to_and_including
,
183 data
: if insert_only
{
184 State
::Inserted(data
.into())
186 State
::Replaced(data
.into())
190 // Keep initial data on right side of part
191 if up_to_and_including
< part_to_split
.end
{
192 new_parts
.push(Span
{
193 start
: up_to_and_including
+ 1,
194 end
: part_to_split
.end
,
195 data
: State
::Initial
,
200 if let Some(ps
) = self.parts
.get(index_of_part_to_split
+ 1..) {
201 new_parts
.extend_from_slice(&ps
);
207 self.parts
= new_parts
;
216 use proptest
::prelude
::*;
218 fn str(i
: &[u8]) -> &str {
219 ::std
::str::from_utf8(i
).unwrap()
223 fn replace_some_stuff() {
224 let mut d
= Data
::new(b
"foo bar baz");
225 d
.replace_range(4, 6, b
"lol").unwrap();
226 assert_eq
!("foo lol baz", str(&d
.to_vec()));
230 fn replace_a_single_char() {
231 let mut d
= Data
::new(b
"let y = true;");
232 d
.replace_range(4, 4, b
"mut y").unwrap();
233 assert_eq
!("let mut y = true;", str(&d
.to_vec()));
237 fn replace_multiple_lines() {
238 let mut d
= Data
::new(b
"lorem\nipsum\ndolor");
240 d
.replace_range(6, 10, b
"lol").unwrap();
241 assert_eq
!("lorem\nlol\ndolor", str(&d
.to_vec()));
243 d
.replace_range(12, 16, b
"lol").unwrap();
244 assert_eq
!("lorem\nlol\nlol", str(&d
.to_vec()));
248 fn replace_multiple_lines_with_insert_only() {
249 let mut d
= Data
::new(b
"foo!");
251 d
.replace_range(3, 2, b
"bar").unwrap();
252 assert_eq
!("foobar!", str(&d
.to_vec()));
254 d
.replace_range(0, 2, b
"baz").unwrap();
255 assert_eq
!("bazbar!", str(&d
.to_vec()));
257 d
.replace_range(3, 3, b
"?").unwrap();
258 assert_eq
!("bazbar?", str(&d
.to_vec()));
262 fn replace_invalid_range() {
263 let mut d
= Data
::new(b
"foo!");
265 assert
!(d
.replace_range(2, 0, b
"bar").is_err());
266 assert
!(d
.replace_range(0, 2, b
"bar").is_ok());
270 fn empty_to_vec_roundtrip() {
272 assert_eq
!(s
.as_bytes(), Data
::new(s
.as_bytes()).to_vec().as_slice());
276 #[should_panic(expected = "Cannot replace slice of data that was already replaced")]
277 fn replace_overlapping_stuff_errs() {
278 let mut d
= Data
::new(b
"foo bar baz");
280 d
.replace_range(4, 6, b
"lol").unwrap();
281 assert_eq
!("foo lol baz", str(&d
.to_vec()));
283 d
.replace_range(4, 6, b
"lol2").unwrap();
287 #[should_panic(expected = "original data is only 3 byte long")]
288 fn broken_replacements() {
289 let mut d
= Data
::new(b
"foo");
290 d
.replace_range(4, 7, b
"lol").unwrap();
294 fn replace_same_twice() {
295 let mut d
= Data
::new(b
"foo");
296 d
.replace_range(0, 0, b
"b").unwrap();
297 d
.replace_range(0, 0, b
"b").unwrap();
298 assert_eq
!("boo", str(&d
.to_vec()));
304 fn new_to_vec_roundtrip(ref s
in "\\PC*") {
305 assert_eq
!(s
.as_bytes(), Data
::new(s
.as_bytes()).to_vec().as_slice());
310 fn replace_random_chunks(
312 ref replacements
in prop
::collection
::vec(
313 (any
::<::std
::ops
::Range
<usize>>(), any
::<Vec
<u8>>()),
317 let mut d
= Data
::new(data
.as_bytes());
318 for &(ref range
, ref bytes
) in replacements
{
319 let _
= d
.replace_range(range
.start
, range
.end
, bytes
);