tree.rs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  1. use std::fmt::{self, Debug};
  2. use std::num::{NonZeroUsize};
  3. use std::sync::atomic::{self};
  4. use diff;
  5. use frag;
  6. // Traits
  7. /// Trait for "abstract" nodes of the tree that do not correspond directly to underlying fragtree.
  8. pub trait Abstract: Sized {
  9. type State;
  10. type Context: NodeContext;
  11. fn initial_state(&self, ctx: &mut Self::Context) -> Self::State;
  12. fn render(&self, ctx: &mut Self::Context, state: &Self::State) -> Virt<Self>;
  13. fn compatible(&self, other: &Self) -> bool;
  14. fn should_update(&self,
  15. state: &Self::State,
  16. next_cfg: &Self,
  17. next_state: &Self::State) -> bool;
  18. }
  19. /// Trait for context info passed along to all nodes.
  20. pub trait NodeContext {
  21. fn push_path(&mut self, el: PathElem);
  22. fn pop_path(&mut self);
  23. fn push_new_uid(&mut self, uid_gen: &mut UidGen) -> Uid {
  24. let uid = uid_gen.next();
  25. self.push_path(PathElem::ByUid(uid));
  26. uid
  27. }
  28. }
  29. ////////////////////////////////////////////////////////////////////////////////////////////////////
  30. // Data types
  31. ///
  32. /// Virtual node -- specifies the desired shape of a node. Virtual nodes can be "imposed" onto live
  33. /// nodes, which updates the live node to conform to the specification given by the virtual node.
  34. #[derive(Clone, PartialEq, Eq)]
  35. pub enum Virt<P> {
  36. Frag(frag::Frag),
  37. Abstract(P),
  38. Branch(VirtBranch<P>),
  39. }
  40. #[derive(Clone, PartialEq, Eq)]
  41. pub struct VirtBranch<P> {
  42. spine: frag::FragSpine,
  43. info: frag::FragInfo,
  44. arms: Vec<Virt<P>>,
  45. }
  46. ///
  47. /// Live node -- specifies the current shape of a node with some additional state attached to nodes.
  48. #[derive(Debug, PartialEq, Eq)]
  49. pub enum Live<P, S> {
  50. Frag,
  51. Abstract(Box<AbstractState<P, S>>),
  52. Branch(LiveBranch<P, S>),
  53. }
  54. #[derive(Debug)]
  55. pub struct LiveBranch<P, S> {
  56. spine: frag::FragSpine,
  57. arms: Vec<Live<P, S>>,
  58. arm_uids: Vec<Uid>,
  59. uid_gen: UidGen,
  60. }
  61. #[derive(Debug, PartialEq, Eq)]
  62. pub struct AbstractState<P, S> {
  63. props: P,
  64. state: S,
  65. rendered: Live<P, S>,
  66. }
  67. /// Unique identifiers for tagging arms of `Live::Branch`.
  68. #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
  69. pub struct Uid(NonZeroUsize);
  70. /// `Uid` generator.
  71. pub struct UidGen(atomic::AtomicUsize);
  72. /// Generic structure for result of comparing trees. The reason it has so many type parameters is
  73. /// that the values within differ greatly based on if the comparison takes ownership or not. See the
  74. /// `LiveVirtCmp` and `LiveVirtCmpMut` variations below.
  75. #[derive(Debug, Clone, Eq, PartialEq)]
  76. enum Cmp<D, F, B1, B2, A1, A2> {
  77. Different(D), // different spines
  78. Frag(F), // both trees are Frag; RHS has fragment F
  79. Branch(B1, B2), // both trees are Branch; RHS has info I
  80. Abstract(A1, A2), // both trees are Abstract
  81. }
  82. type LiveVirtCmp<'a, P, S> =
  83. Cmp<(), // different
  84. &'a frag::Frag, // frag
  85. &'a LiveBranch<P, S>, // branch
  86. &'a VirtBranch<P>, // ... (branch)
  87. &'a AbstractState<P, S>, // abstract
  88. &'a P>; // ... (abstract)
  89. type LiveVirtCmpMut<'a, P, S> =
  90. Cmp<Virt<P>, // different
  91. frag::Frag, // frag
  92. &'a mut LiveBranch<P, S>, // branch
  93. VirtBranch<P>, // ... (branch)
  94. &'a mut AbstractState<P, S>, // abstract
  95. P>; // ... (abstract)
  96. /// Paths used for locating `Abstract` nodes given by instructions on which arms to crawl in order
  97. /// to reach the desired node.
  98. #[derive(Debug, Copy, Clone, Eq, PartialEq)]
  99. pub enum PathElem {
  100. Direct,
  101. ByUid(Uid),
  102. }
  103. pub type PathBuf = Vec<PathElem>;
  104. pub type Path = [PathElem];
  105. #[derive(Debug, Clone, Eq, PartialEq)]
  106. pub enum FollowFailed {
  107. UidNotPresent,
  108. WrongElemType,
  109. WrongNodeType,
  110. }
  111. impl fmt::Display for FollowFailed {
  112. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  113. write!(f, "path does not match any node in the tree")
  114. }
  115. }
  116. impl std::error::Error for FollowFailed {}
  117. ////////////////////////////////////////////////////////////////////////////////////////////////////
  118. // ! (never type) and () (unit type) can be used for trees without abstract nodes.
  119. impl Abstract for ! {
  120. type State = ();
  121. type Context = ();
  122. fn initial_state(&self, _: &mut ()) {}
  123. fn render(&self, _: &mut (), _state: &()) -> Virt<!> { *self }
  124. fn compatible(&self, _other: &Self) -> bool { *self }
  125. fn should_update(&self, _: &(), _: &Self, _: &()) -> bool { false }
  126. }
  127. impl NodeContext for () {
  128. fn push_path(&mut self, _: PathElem) {}
  129. fn pop_path(&mut self) {}
  130. }
  131. // Uid and UidGen
  132. impl Debug for UidGen {
  133. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "UidGen(..)") }
  134. }
  135. impl Uid {
  136. pub fn dummy() -> Self {
  137. Uid(unsafe { NonZeroUsize::new_unchecked(1) })
  138. }
  139. }
  140. impl UidGen {
  141. pub fn new() -> Self {
  142. UidGen(atomic::AtomicUsize::new(2))
  143. }
  144. fn next(&mut self) -> Uid {
  145. let n = self.0.fetch_add(1, atomic::Ordering::Relaxed);
  146. Uid(unsafe { NonZeroUsize::new_unchecked(n) })
  147. }
  148. }
  149. // TODO: remove this -- it (was) only used for hardcoding paths for debugging
  150. impl From<usize> for PathElem {
  151. fn from(x: usize) -> PathElem {
  152. PathElem::ByUid(Uid(NonZeroUsize::new(x).expect("Uid(0) is invalid")))
  153. }
  154. }
  155. // ignore uids when comparing Live nodes
  156. impl<P, S> PartialEq for LiveBranch<P, S>
  157. where P: PartialEq, S: PartialEq {
  158. fn eq(&self, rhs: &Self) -> bool {
  159. self.spine == rhs.spine
  160. && self.arms == rhs.arms
  161. }
  162. }
  163. impl<P, S> Eq for LiveBranch<P, S> where P: Eq, S: Eq {}
  164. ////////////////////////////////////////////////////////////////////////////////////////////////////
  165. // Constructors
  166. impl<P> Virt<P> {
  167. pub fn frag(frg: frag::Frag) -> Self {
  168. Virt::Frag(frg)
  169. }
  170. pub fn branch(spine: frag::FragSpine,
  171. info: frag::FragInfo,
  172. arms: Vec<Virt<P>>) -> Self {
  173. Virt::Branch(VirtBranch { spine, arms, info })
  174. }
  175. pub fn abs_props(props: P) -> Self {
  176. Virt::Abstract(props)
  177. }
  178. pub fn info_mut(&mut self) -> Option<&mut frag::FragInfo> {
  179. match *self {
  180. Virt::Branch(VirtBranch { ref mut info, .. }) => Some(info),
  181. _ => None,
  182. }
  183. }
  184. }
  185. impl<P, S> Live<P, S> {
  186. pub fn frag() -> Self {
  187. Live::Frag
  188. }
  189. }
  190. // Querying Live nodes: follow, compare
  191. impl<P, S> Live<P, S> {
  192. /// Follow the given path to find a live node, and the underlying node it corresponds to.
  193. pub fn follow_underlying_mut<'s, 'p, 'u>
  194. (&'s mut self, path: &'p Path, underly: &'u mut frag::Frag)
  195. -> Result<(&'s mut Live<P, S>, &'u mut frag::Frag), FollowFailed> {
  196. let mut cur_underly = underly;
  197. let mut cur_live = self;
  198. for &path_el in path.iter() {
  199. match path_el {
  200. PathElem::Direct =>
  201. match *cur_live {
  202. Live::Abstract(ref mut abs) => cur_live = &mut abs.rendered,
  203. _ => return Err(FollowFailed::WrongElemType),
  204. }
  205. PathElem::ByUid(uid) =>
  206. match *cur_live {
  207. Live::Branch(ref mut branch) => {
  208. let idx = branch.find_arm_index(uid)?;
  209. cur_live = &mut branch.arms[idx];
  210. cur_underly = &mut cur_underly[idx];
  211. }
  212. _ => return Err(FollowFailed::WrongElemType),
  213. }
  214. }
  215. }
  216. Ok((cur_live, cur_underly))
  217. }
  218. /// Follow the given path to find a live node.
  219. pub fn follow(&self, path: &Path) -> Result<&Live<P, S>, FollowFailed> {
  220. let mut cur_live = self;
  221. for &path_el in path.iter() {
  222. match path_el {
  223. PathElem::Direct =>
  224. match *cur_live {
  225. Live::Abstract(ref abs) => cur_live = &abs.rendered,
  226. _ => return Err(FollowFailed::WrongElemType),
  227. }
  228. PathElem::ByUid(uid) =>
  229. match *cur_live {
  230. Live::Branch(ref branch) => {
  231. let idx = branch.find_arm_index(uid)?;
  232. cur_live = &branch.arms[idx];
  233. }
  234. _ => return Err(FollowFailed::WrongElemType),
  235. }
  236. }
  237. }
  238. Ok(cur_live)
  239. }
  240. /// Follow the given path to find an abstract live node.
  241. pub fn follow_abstract(&self, path: &Path) -> Result<&AbstractState<P, S>, FollowFailed> {
  242. match self.follow(path)? {
  243. Live::Abstract(ref abs) => Ok(abs),
  244. _ => Err(FollowFailed::WrongNodeType),
  245. }
  246. }
  247. /// Compare trees shallowly.
  248. fn compare<'a>(&'a self, virt: &'a Virt<P>) -> LiveVirtCmp<'a, P, S> {
  249. match *self {
  250. Live::Branch(ref b) =>
  251. match *virt {
  252. Virt::Branch(ref vb) => Cmp::Branch(b, vb),
  253. _ => Cmp::Different(()),
  254. }
  255. Live::Frag =>
  256. match *virt {
  257. Virt::Frag(ref u) => Cmp::Frag(u),
  258. _ => Cmp::Different(()),
  259. }
  260. Live::Abstract(ref abs) =>
  261. match *virt {
  262. Virt::Abstract(ref abs_node) => Cmp::Abstract(abs, abs_node),
  263. _ => Cmp::Different(()),
  264. }
  265. }
  266. }
  267. /// Compare trees shallowly (mutable; takes ownership of RHS).
  268. fn compare_mut(&mut self, virt: Virt<P>) -> LiveVirtCmpMut<P, S> {
  269. match *self {
  270. Live::Branch(ref mut b) =>
  271. match virt {
  272. Virt::Branch(vb) => Cmp::Branch(b, vb),
  273. _ => Cmp::Different(virt),
  274. }
  275. Live::Frag =>
  276. match virt {
  277. Virt::Frag(u) => Cmp::Frag(u),
  278. _ => Cmp::Different(virt),
  279. }
  280. Live::Abstract(ref mut abs) =>
  281. match virt {
  282. Virt::Abstract(abs_node) => Cmp::Abstract(abs, abs_node),
  283. _ => Cmp::Different(virt),
  284. }
  285. }
  286. }
  287. }
  288. impl<P, S> LiveBranch<P, S> {
  289. pub fn find_arm_index(&self, uid: Uid) -> Result<usize, FollowFailed> {
  290. self.arm_uids
  291. .iter()
  292. .position(|&arm_uid| arm_uid == uid)
  293. .ok_or(FollowFailed::UidNotPresent)
  294. }
  295. }
  296. // Imposing virtual tree onto live tree + fragtree.
  297. impl<P, S> Live<P, S> where P: Abstract<State=S> {
  298. /// Impose a virtual tree onto this live tree, updating this tree's structure, and the given
  299. /// underlying tree's structure, so that it matches the virtual tree.
  300. pub fn impose(&mut self,
  301. virt: Virt<P>,
  302. underly: &mut frag::Frag,
  303. ctx: &mut P::Context) {
  304. match self.compare_mut(virt) {
  305. Cmp::Branch(mut b, vb) =>
  306. diff_branches(&mut b, vb, underly, ctx),
  307. Cmp::Abstract(abs, props) =>
  308. if abs.props.compatible(&props) {
  309. abs.set_props(props, underly, ctx);
  310. } else {
  311. self.impose_overwrite(Virt::Abstract(props), underly, ctx);
  312. }
  313. Cmp::Frag(frg) =>
  314. self.impose_overwrite(Virt::Frag(frg), underly, ctx),
  315. Cmp::Different(virt) =>
  316. self.impose_overwrite(virt, underly, ctx),
  317. }
  318. }
  319. fn impose_overwrite(&mut self,
  320. virt: Virt<P>,
  321. underly: &mut frag::Frag,
  322. ctx: &mut P::Context) {
  323. // TODO: unmount() logic here, in the future
  324. let (new_live, new_underly) = virt.build(ctx);
  325. *self = new_live;
  326. *underly = new_underly;
  327. }
  328. }
  329. fn diff_branches<'a, 'c, P, S>(branch: &'a mut LiveBranch<P, S>,
  330. v_branch: VirtBranch<P>,
  331. base_underlying: &'a mut frag::Frag,
  332. context: &'c mut P::Context)
  333. where P: Abstract<State=S> {
  334. // update branch spines and underlying branch info
  335. if branch.spine != v_branch.spine {
  336. branch.spine = v_branch.spine.clone();
  337. base_underlying.set_spine(v_branch.spine);
  338. }
  339. base_underlying.set_info(v_branch.info);
  340. // perform diff algorithm on the branch arms (live vs. virt), yielding a "patch"
  341. let patch = diff::gen(&mut branch.arms, v_branch.arms);
  342. // apply the patch to both the live branch and underlying node
  343. diff::ApplyPatch::apply_patch(
  344. &mut TreeApplyPatch { branch, base_underlying, context },
  345. patch,
  346. ).unwrap()
  347. // there's no reason this should unwrap() fail -- the patch is applied to the same data that
  348. // generated it.
  349. }
  350. impl<P> diff::Cmp<Virt<P>> for Live<P, P::State> where P: Abstract {
  351. fn similar(&self, virt: &Virt<P>) -> bool {
  352. match self.compare(virt) {
  353. Cmp::Frag(_) => true,
  354. Cmp::Branch(b1, b2) => b1.spine == b2.spine,
  355. Cmp::Abstract(abs, n) => abs.props.compatible(n),
  356. Cmp::Different(()) => false,
  357. }
  358. }
  359. }
  360. /// Helper struct for implementing diff::ApplyPatch. Patches applied to this structure will be
  361. /// applied to both the live branch and the underlying tree. In particular, `overwrite()` will call
  362. /// `.impose()` rather than naively overwriting nodes in the tree.
  363. struct TreeApplyPatch<'a, 'c, P, S, CTX> {
  364. branch: &'a mut LiveBranch<P, S>,
  365. base_underlying: &'a mut frag::Frag,
  366. context: &'c mut CTX,
  367. }
  368. impl<'a, 'c, P> diff::ApplyPatch<Virt<P>> for TreeApplyPatch<'a, 'c, P, P::State, P::Context>
  369. where P: Abstract {
  370. fn len(&self) -> usize {
  371. self.branch.arms.len()
  372. }
  373. fn remove(&mut self, i: usize) {
  374. // TODO: keep track of arms/arm_uids invariants somewhere else, e.g. a LiveBranch<> impl.
  375. self.branch.arms.remove(i);
  376. self.branch.arm_uids.remove(i);
  377. self.base_underlying.remove(i);
  378. }
  379. fn insert(&mut self, i: usize, v: Virt<P>) {
  380. let uid = self.context.push_new_uid(&mut self.branch.uid_gen);
  381. let (live, under) = v.build(self.context);
  382. self.context.pop_path();
  383. self.branch.arms.insert(i, live);
  384. self.branch.arm_uids.insert(i, uid);
  385. self.base_underlying.insert(i, under);
  386. }
  387. fn overwrite(&mut self, i: usize, v: Virt<P>) -> bool {
  388. let uid = self.branch.arm_uids[i];
  389. let live = &mut self.branch.arms[i];
  390. self.context.push_path(PathElem::ByUid(uid));
  391. live.impose(v, &mut self.base_underlying[i], self.context);
  392. self.context.pop_path();
  393. true
  394. }
  395. }
  396. impl<P> Virt<P> where P: Abstract {
  397. /// Build an actual tree (live and underlying) from this virtual tree. The resulting
  398. /// trees are in sync.
  399. fn build(self, ctx: &mut P::Context) -> (Live<P, P::State>, frag::Frag) {
  400. match self {
  401. Virt::Frag(frg) =>
  402. (Live::Frag, frg),
  403. Virt::Branch(VirtBranch { spine, arms, info }) => {
  404. let mut underlying_arms = Vec::with_capacity(arms.len());
  405. let mut branch = LiveBranch {
  406. spine: spine.clone(),
  407. arms: Vec::with_capacity(arms.len()),
  408. arm_uids: Vec::with_capacity(arms.len()),
  409. uid_gen: UidGen::new(),
  410. };
  411. for v_arm in arms {
  412. let uid = ctx.push_new_uid(&mut branch.uid_gen);
  413. let (live, under) = v_arm.build(ctx);
  414. ctx.pop_path();
  415. branch.arms.push(live);
  416. branch.arm_uids.push(uid);
  417. underlying_arms.push(under);
  418. }
  419. (Live::Branch(branch),
  420. frag::Frag::new(spine, info, underlying_arms))
  421. }
  422. Virt::Abstract(props) => {
  423. let state = props.initial_state(ctx);
  424. let virt = props.render(ctx, &state);
  425. ctx.push_path(PathElem::Direct);
  426. let (rendered, under) = virt.build(ctx);
  427. ctx.pop_path();
  428. (Live::Abstract(Box::new(AbstractState { props, state, rendered })),
  429. under)
  430. }
  431. }
  432. }
  433. }
  434. // Manipulating abstract node state
  435. impl<P, S> AbstractState<P, S> {
  436. pub fn props(&self) -> &P { &self.props }
  437. pub fn state(&self) -> &S { &self.state }
  438. }
  439. impl<P> AbstractState<P, P::State>
  440. where P: Abstract {
  441. pub fn set_props(&mut self, props: P, underly: &mut frag::Frag, ctx: &mut P::Context) {
  442. if self.props.should_update(&self.state, &props, &self.state) {
  443. self.props = props;
  444. self.rerender(underly, ctx)
  445. }
  446. }
  447. /*
  448. pub fn set_state(&mut self, next_state: A::State, underly: &mut U) {
  449. if self.node.should_update(&self.state, &self.node, &next_state) {
  450. self.state = next_state;
  451. self.rerender(underly);
  452. }
  453. }
  454. */
  455. pub fn rerender(&mut self, underly: &mut frag::Frag, ctx: &mut P::Context) {
  456. let virt_rendered = self.props.render(ctx, &self.state);
  457. ctx.push_path(PathElem::Direct);
  458. self.rendered.impose(virt_rendered, underly, ctx);
  459. ctx.pop_path();
  460. }
  461. }
  462. ////////////////////////////////////////////////////////////////////////////////////////////////////
  463. // debugging
  464. impl<P, S> Live<P, S> where S: Debug {
  465. pub fn print_structure(&self) {
  466. self.print_structure_aux(0, "".into())
  467. }
  468. fn print_structure_aux(&self, indent: usize, prefix: String) {
  469. for _ in 0..indent { print!(" "); }
  470. print!("{}", prefix);
  471. match *self {
  472. Live::Frag =>
  473. print!("frag\n"),
  474. Live::Branch(ref b) => {
  475. print!("branch {:?}\n", b.spine);
  476. for (l, uid) in b.arms.iter().zip(b.arm_uids.iter()) {
  477. l.print_structure_aux(2 + indent, format!("[{:?}] ", uid));
  478. }
  479. }
  480. Live::Abstract(ref a) => {
  481. print!("abstract (state={:?})\n", a.state);
  482. a.rendered.print_structure_aux(2 + indent, "".into());
  483. }
  484. }
  485. }
  486. }
  487. ////////////////////////////////////////////////////////////////////////////////////////////////////
  488. /*
  489. #[cfg(test)]
  490. mod test {
  491. use super::*;
  492. use diff;
  493. use std::ops::{Index, IndexMut};
  494. #[derive(Clone, Eq, PartialEq, Debug)]
  495. struct StrT {
  496. spine: String,
  497. children: Vec<StrT>,
  498. }
  499. type L = Live<StrT, !>;
  500. type V = Virt<StrT, !>;
  501. /// Helper to succinctly create trees.
  502. fn parse<B, A, I, T>(i: &mut I, build: &B, alt: &A) -> Option<T>
  503. where I: Iterator<Item=char>,
  504. B: Fn(String, Vec<T>) -> T,
  505. A: Fn() -> T {
  506. let mut spine = String::from("");
  507. loop {
  508. match i.next().unwrap() {
  509. ')' => return None,
  510. '*' => return Some(alt()),
  511. '(' => break,
  512. c => spine.push(c),
  513. }
  514. }
  515. let mut arms = Vec::new();
  516. loop {
  517. match parse(i, build, alt) {
  518. Some(e) => arms.push(e),
  519. None => return Some(build(spine, arms)),
  520. }
  521. }
  522. }
  523. fn tree(s: &str) -> StrT {
  524. parse(&mut s.chars(), &|spine, children| StrT { spine, children }, &|| panic!(".")).unwrap()
  525. }
  526. fn live(s: &str) -> L {
  527. parse(&mut s.chars(), &|spine, arms| Branch { spine, arms }.into(), &|| Live::Frag).unwrap()
  528. }
  529. fn virt(s: &str) -> V {
  530. parse(&mut s.chars(),
  531. &|spine, arms| Virt::branch(spine, (), arms),
  532. &|| Virt::Frag(tree("alt()"))).unwrap()
  533. }
  534. #[test]
  535. fn test_parse() {
  536. assert_eq!(tree("3(1()2())"),
  537. StrT { spine: "3".into(),
  538. children: vec![
  539. StrT { spine: "1".into(), children: vec![] },
  540. StrT { spine: "2".into(), children: vec![] },
  541. ] });
  542. assert_eq!(live("3(1()*)"),
  543. Branch { spine: "3".into(),
  544. arms: vec![
  545. Branch { spine: "1".into(), arms: vec![] }.into(),
  546. Live::Frag,
  547. ] }.into());
  548. }
  549. impl Index<usize> for StrT {
  550. type Output = StrT;
  551. fn index(&self, i: usize) -> &StrT {
  552. &self.children[i]
  553. }
  554. }
  555. impl IndexMut<usize> for StrT {
  556. fn index_mut(&mut self, i: usize) -> &mut StrT {
  557. &mut self.children[i]
  558. }
  559. }
  560. impl Default for StrT {
  561. fn default() -> Self {
  562. StrT { spine: "".into(), children: vec![] }
  563. }
  564. }
  565. impl Underlying for StrT {
  566. type Spine = String;
  567. type Info = ();
  568. fn create(spine: String, _: (), children: Vec<StrT>) -> Self {
  569. StrT { spine, children }
  570. }
  571. fn set_spine(&mut self, spine: String) {
  572. self.spine = spine;
  573. }
  574. fn set_info(&mut self, _: ()) {}
  575. }
  576. impl diff::ApplyPatch<StrT> for StrT {
  577. fn len(&self) -> usize {
  578. self.children.len()
  579. }
  580. fn remove(&mut self, i: usize) {
  581. self.children.remove(i);
  582. }
  583. fn insert(&mut self, i: usize, c: StrT) {
  584. self.children.insert(i, c);
  585. }
  586. }
  587. //////////////////////////////////////////////////////////////////////////////////////////////////
  588. #[test]
  589. fn test_impose_frag_mut_underlying() {
  590. let mut u = tree("1()");
  591. Live::Frag.impose(virt("2()"), &mut u);
  592. assert_eq!(u, tree("2()"));
  593. }
  594. #[test]
  595. fn test_impose_new_branch() {
  596. let mut l = live("*");
  597. let mut u = tree("alt()");
  598. l.impose(virt("3(1()2())"), &mut u);
  599. assert_eq!(u, tree("3(1()2())"));
  600. }
  601. #[test]
  602. fn test_impose_update_spine() {
  603. let mut l = live("1()");
  604. let mut u = tree("1()");
  605. l.impose(virt("2()"), &mut u);
  606. assert_eq!(l, live("2()"));
  607. assert_eq!(u, tree("2()"));
  608. }
  609. #[test]
  610. fn test_impose_add_arm() {
  611. let mut l = live("4()");
  612. let mut u = tree("4()");
  613. l.impose(Virt::Branch(
  614. Branch { spine: "4".into(), arms: vec![Virt::Frag(tree("alt()"))] },
  615. ()
  616. ), &mut u);
  617. assert_eq!(l, live("4(*)"));
  618. assert_eq!(u, tree("4(alt())"));
  619. }
  620. #[test]
  621. fn test_impose_remove_arm() {
  622. let mut l = live("4(*)");
  623. let mut u = tree("4(alt())");
  624. l.impose(virt("4()"), &mut u);
  625. assert_eq!(l, live("4()"));
  626. assert_eq!(u, tree("4()"));
  627. }
  628. #[test]
  629. fn test_impose_update_child() {
  630. let mut l = live("4(3())");
  631. let mut u = tree("4(3())");
  632. l.impose(virt("4(2())"), &mut u);
  633. assert_eq!(l, live("4(2())"));
  634. assert_eq!(u, tree("4(2())"));
  635. }
  636. #[test]
  637. fn test_impose_rec_update_no_changes() {
  638. let mut l = live("4(3())");
  639. let mut u = tree("4(3())");
  640. l.impose(virt("4(3())"), &mut u);
  641. assert_eq!(l, live("4(3())"));
  642. assert_eq!(u, tree("4(3())"));
  643. }
  644. }
  645. */