1use crate::{
2 Chunk, Error, ExGuid, FileType, PropertySets, Reference, RevisionIndex, Store,
3 op::content::{NATIVE_INDENTS, measurement_bytes},
4 store::crc,
5 write::{append, append_list, fresh_guid, node},
6};
7use std::collections::BTreeMap;
8use web_time::{SystemTime, UNIX_EPOCH};
9
10type Result<T> = std::result::Result<T, Error>;
11
12pub(crate) fn string(value: &str) -> Vec<u8> {
13 value
14 .encode_utf16()
15 .chain([0])
16 .flat_map(u16::to_le_bytes)
17 .collect()
18}
19
20/// An author's initials as OneNote 2010 stores them beside the name (`0x1c001df8`, with
21/// no MS-ONE entry): Office's default, the first letter of each word of the name.
22pub(crate) fn initials(author: &str) -> String {
23 author
24 .split_whitespace()
25 .filter_map(|word| word.chars().next())
26 .flat_map(char::to_uppercase)
27 .collect()
28}
29
30/// An author object's properties as OneNote 2010 writes them: initials, then the name.
31pub(crate) fn author_properties(name: &str) -> Vec<(u32, Vec<u8>)> {
32 vec![
33 (0x1c001df8, string(&initials(name))),
34 (0x1c001d75, string(name)),
35 ]
36}
37
38pub(crate) fn default_text_style() -> Vec<(u32, Vec<u8>)> {
39 vec![
40 (0x14001c3b, 0x409_u32.to_le_bytes().to_vec()),
41 (0x1c001c0a, string("Calibri")),
42 (0x10001c0b, 22_u16.to_le_bytes().to_vec()),
43 ]
44}
45
46/// The page margins MS-ONE requires on every page, in half inches, as OneNote 2010 sets them
47/// on the pages it creates.
48pub(crate) fn page_margins() -> Vec<(u32, Vec<u8>)> {
49 [
50 (0x14001c4c, 1.0_f32),
51 (0x14001c4d, 1.0),
52 (0x14001c4e, 2.0),
53 (0x14001c4f, 2.0),
54 ]
55 .into_iter()
56 .map(|(id, value)| (id, value.to_le_bytes().to_vec()))
57 .collect()
58}
59
60pub(crate) fn properties(values: &[(u32, Vec<u8>)]) -> Result<Vec<u8>> {
61 let mut streams: [Vec<u8>; 3] = std::array::from_fn(|_| Vec::new());
62 let mut fields = Vec::new();
63 for (id, value) in values {
64 let kind = (id >> 26) & 0x1f;
65 match kind {
66 1 | 2 => assert!(value.is_empty()),
67 3..=6 => {
68 assert_eq!(value.len(), 1 << (kind - 3));
69 fields.extend(value);
70 }
71 7 => {
72 if value.len() >= 0x40000000 {
73 return Err(Error {
74 offset: 0,
75 message: "Property data exceeds the format length limit",
76 });
77 }
78 fields.extend_from_slice(&(value.len() as u32).to_le_bytes());
79 fields.extend(value);
80 }
81 8..=13 => {
82 assert!(value.len().is_multiple_of(4));
83 if kind & 1 == 0 {
84 assert_eq!(value.len(), 4);
85 } else {
86 fields
87 .extend_from_slice(&u32::try_from(value.len() / 4).unwrap().to_le_bytes());
88 }
89 streams[((kind - 8) / 2) as usize].extend(value);
90 }
91 _ => unreachable!(),
92 }
93 }
94 let mut data = Vec::new();
95 let extended = !streams[2].is_empty();
96 let last = if extended {
97 2
98 } else if !streams[1].is_empty() {
99 1
100 } else {
101 0
102 };
103 for (index, stream) in streams.iter().enumerate().take(last + 1) {
104 let mut header = u32::try_from(stream.len() / 4).unwrap();
105 assert!(header <= 0xffffff);
106 if index == 0 && last == 0 {
107 header |= 0x80000000;
108 }
109 if index < 2 && extended {
110 header |= 0x40000000;
111 }
112 data.extend_from_slice(&header.to_le_bytes());
113 data.extend(stream);
114 }
115 data.extend_from_slice(&u16::try_from(values.len()).unwrap().to_le_bytes());
116 for (id, _) in values {
117 data.extend_from_slice(&id.to_le_bytes());
118 }
119 data.extend(fields);
120 data.resize(data.len().next_multiple_of(8), 0);
121 PropertySets::parse(&data)?;
122 Ok(data)
123}
124
125struct NewObject {
126 id: u32,
127 jcid: u32,
128 properties: Vec<(u32, Vec<u8>)>,
129}
130
131struct NewSpace {
132 id: u32,
133 roots: Vec<(u32, u32)>,
134 objects: Vec<NewObject>,
135}
136
137/// Header bytes 128..148: `guidAncestor` and `crcName`, which OneNote checks against a
138/// file's location and name; a mismatch makes it re-identify the file.
139pub(crate) fn placement(ancestor: [u8; 16], name: &str) -> [u8; 20] {
140 let mut bytes = [0; 20];
141 bytes[..16].copy_from_slice(&ancestor);
142 bytes[16..].copy_from_slice(&(!crc(u32::MAX, &string(name), FileType::Section)).to_le_bytes());
143 bytes
144}
145
146thread_local! {
147 /// The FILETIME `at` gives writers in place of the system clock.
148 static CLOCK: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
149}
150
151/// Runs `f` with the writers' clock reading `filetime`, as an op's modification time.
152pub(crate) fn at<T>(filetime: u64, f: impl FnOnce() -> T) -> T {
153 struct Restore(Option<u64>);
154 impl Drop for Restore {
155 fn drop(&mut self) {
156 CLOCK.set(self.0);
157 }
158 }
159 let _restore = Restore(CLOCK.replace(Some(filetime)));
160 f()
161}
162
163/// Seconds since 1980 as OneNote's Time32, and FILETIME, of the writers' clock.
164pub(crate) fn current_timestamps() -> Result<(u32, u64)> {
165 let now = match CLOCK.get() {
166 Some(filetime) => (filetime / 10_000_000)
167 .checked_sub(11644473600)
168 .ok_or(Error {
169 offset: 0,
170 message: "An edit time precedes the Unix epoch",
171 })?,
172 None => SystemTime::now()
173 .duration_since(UNIX_EPOCH)
174 .map_err(|_| Error {
175 offset: 0,
176 message: "System time precedes the Unix epoch",
177 })?
178 .as_secs(),
179 };
180 let modified = now
181 .checked_sub(315532800)
182 .and_then(|time| u32::try_from(time).ok())
183 .ok_or(Error {
184 offset: 0,
185 message: "System time exceeds the OneNote Time32 range",
186 })?;
187 Ok((
188 modified,
189 CLOCK.get().unwrap_or((now + 11644473600) * 10000000),
190 ))
191}
192
193/// Creates a section with one page and one plain-text paragraph, without a template.
194/// Text must not contain NUL or line-feed characters.
195pub fn create_section(file_name: &str, text: &str, author: &str) -> Result<Vec<u8>> {
196 if file_name.contains(['/', '\\', '\0'])
197 || !file_name.to_ascii_lowercase().ends_with(".one")
198 || text.contains(['\0', '\n'])
199 || author.contains('\0')
200 {
201 return Err(Error {
202 offset: 0,
203 message: "Invalid section name, paragraph text, or author",
204 });
205 }
206 let (modified, timestamp) = current_timestamps()?;
207 let timestamp = timestamp.to_le_bytes().to_vec();
208 let page_guid = fresh_guid()?;
209 let metadata = vec![
210 (0x1c001c30, page_guid.to_vec()),
211 (0x1c001cf3, string(&crate::edit::automatic_title(text))),
212 (0x14001d82, 40_u32.to_le_bytes().to_vec()),
213 (0x1400348b, 40_u32.to_le_bytes().to_vec()),
214 (0x14001dff, 1_u32.to_le_bytes().to_vec()),
215 (0x18001c65, timestamp.clone()),
216 ];
217 let id = |value: u32| value.to_le_bytes().to_vec();
218 let last_modified = || (0x14001d7a, modified.to_le_bytes().to_vec());
219 let spaces = vec![
220 NewSpace {
221 id: 1,
222 roots: vec![(1, 10), (2, 11)],
223 objects: vec![
224 NewObject {
225 id: 10,
226 jcid: 0x60007,
227 properties: vec![
228 (0x1c001c30, fresh_guid()?.to_vec()),
229 (0x18001c65, timestamp.clone()),
230 (0x24001c20, id(12)),
231 ],
232 },
233 NewObject {
234 id: 11,
235 jcid: 0x20031,
236 properties: vec![
237 (0x14001d82, id(40)),
238 (0x1400348b, id(40)),
239 (0x14001cbe, vec![0x8a, 0xa8, 0xe4, 0]),
240 ],
241 },
242 NewObject {
243 id: 12,
244 jcid: 0x60008,
245 properties: vec![
246 (0x1c001c30, fresh_guid()?.to_vec()),
247 (0x18001c65, timestamp),
248 (0x2c001d63, id(257)),
249 ],
250 },
251 ],
252 },
253 NewSpace {
254 id: 257,
255 roots: vec![(1, 20), (2, 21)],
256 objects: vec![
257 NewObject {
258 id: 20,
259 jcid: 0x60037,
260 properties: vec![(0x24001c1f, id(22))],
261 },
262 NewObject {
263 id: 21,
264 jcid: 0x20030,
265 properties: metadata,
266 },
267 NewObject {
268 id: 22,
269 jcid: 0x6000b,
270 properties: [
271 vec![
272 last_modified(),
273 (0x24001c20, id(23)),
274 (0x1c001d75, string(author)),
275 (0x1c001df8, string(&initials(author))),
276 (0x1c001d3c, string(&crate::edit::automatic_title(text))),
277 ],
278 page_margins(),
279 ]
280 .concat(),
281 },
282 NewObject {
283 id: 23,
284 jcid: 0x6000c,
285 properties: vec![
286 last_modified(),
287 (0x24001c20, id(24)),
288 (0x0c001c03, vec![1]),
289 (0x1c001c12, measurement_bytes(&NATIVE_INDENTS, 4)?),
290 (0x14001c14, 1_f32.to_le_bytes().to_vec()),
291 (0x14001c15, 1_f32.to_le_bytes().to_vec()),
292 (0x14001c1b, 13_f32.to_le_bytes().to_vec()),
293 (0x14001c1c, 0.6_f32.to_le_bytes().to_vec()),
294 ],
295 },
296 NewObject {
297 id: 24,
298 jcid: 0x6000d,
299 properties: vec![
300 last_modified(),
301 (0x24001c1f, id(25)),
302 (0x0c001c03, vec![1]),
303 (0x20001d78, id(26)),
304 (0x20001d79, id(26)),
305 (0x14001d09, modified.to_le_bytes().to_vec()),
306 ],
307 },
308 NewObject {
309 id: 25,
310 jcid: 0x6000e,
311 properties: vec![
312 last_modified(),
313 (0x1c001c22, string(text)),
314 (0x24001e13, id(27)),
315 (0x10001cfe, 0x409_u16.to_le_bytes().to_vec()),
316 ],
317 },
318 NewObject {
319 id: 26,
320 jcid: 0x120001,
321 properties: author_properties(author),
322 },
323 NewObject {
324 id: 27,
325 jcid: 0x12004d,
326 properties: default_text_style(),
327 },
328 ],
329 },
330 ];
331 create(file_name, FileType::Section, spaces)
332}
333
334/// Creates a section without pages, coloured `color` (COLORREF, `None` for no colour), as
335/// OneNote 2010 leaves one whose pages are all deleted: its section node lists no pages.
336/// Pages come as `op::SectionOp::Create` edits.
337pub fn create_empty_section(file_name: &str, color: Option<u32>) -> Result<Vec<u8>> {
338 if file_name.contains(['/', '\\', '\0']) || !file_name.to_ascii_lowercase().ends_with(".one") {
339 return Err(Error {
340 offset: 0,
341 message: "Invalid section name",
342 });
343 }
344 let timestamp = current_timestamps()?.1.to_le_bytes().to_vec();
345 let id = |value: u32| value.to_le_bytes().to_vec();
346 let spaces = vec![NewSpace {
347 id: 1,
348 roots: vec![(1, 10), (2, 11)],
349 objects: vec![
350 NewObject {
351 id: 10,
352 jcid: 0x60007,
353 properties: vec![
354 (0x1c001c30, fresh_guid()?.to_vec()),
355 (0x18001c65, timestamp),
356 ],
357 },
358 NewObject {
359 id: 11,
360 jcid: 0x20031,
361 properties: vec![
362 (0x14001d82, id(40)),
363 (0x1400348b, id(40)),
364 (0x14001cbe, id(color.unwrap_or(0xffff_ffff))),
365 ],
366 },
367 ],
368 }];
369 create(file_name, FileType::Section, spaces)
370}
371
372/// Creates a notebook table of contents from section filenames and file identities.
373pub fn create_table_of_contents(file_name: &str, sections: &[(&str, [u8; 16])]) -> Result<Vec<u8>> {
374 if file_name.contains(['/', '\\', '\0'])
375 || !file_name.to_ascii_lowercase().ends_with(".onetoc2")
376 || sections.len() > 0xfffffe
377 {
378 return Err(Error {
379 offset: 0,
380 message: "Invalid table-of-contents filename or section count",
381 });
382 }
383 let mut objects = Vec::new();
384 let mut children = Vec::new();
385 let mut names = std::collections::BTreeSet::new();
386 let mut identities = std::collections::BTreeSet::new();
387 for (index, (name, identity)) in sections.iter().enumerate() {
388 if name.contains(['/', '\\', '\0'])
389 || !name.to_ascii_lowercase().ends_with(".one")
390 || !names.insert(name.to_lowercase())
391 || *identity == [0; 16]
392 || !identities.insert(*identity)
393 {
394 return Err(Error {
395 offset: 0,
396 message: "Invalid or duplicate section filename or identity",
397 });
398 }
399 let id = (((index + 1) as u32) << 8) | 10;
400 children.extend_from_slice(&id.to_le_bytes());
401 objects.push(NewObject {
402 id,
403 jcid: 0x20001,
404 properties: vec![
405 (0x1c001d94, identity.to_vec()),
406 (0x14001cb9, ((index + 1) as u32).to_le_bytes().to_vec()),
407 (0x1c001d6b, string(name)),
408 (0x14001cbe, vec![0xff; 4]),
409 ],
410 });
411 }
412 objects.push(NewObject {
413 id: 10,
414 jcid: 0x20001,
415 properties: vec![(0x24001cf6, children)],
416 });
417 create(
418 file_name,
419 FileType::TableOfContents,
420 vec![NewSpace {
421 id: 1,
422 roots: vec![(1, 10)],
423 objects,
424 }],
425 )
426}
427
428fn create(file_name: &str, file_type: FileType, spaces: Vec<NewSpace>) -> Result<Vec<u8>> {
429 let is_section = file_type == FileType::Section;
430 let maximum = spaces
431 .iter()
432 .flat_map(|space| {
433 std::iter::once(space.id).chain(space.objects.iter().map(|object| object.id))
434 })
435 .max()
436 .unwrap();
437 let guids = (0..=(maximum >> 8))
438 .map(|_| fresh_guid())
439 .collect::<Result<Vec<_>>>()?;
440 let exguid = |compact: u32| ExGuid {
441 guid: guids[(compact >> 8) as usize],
442 n: compact & 255,
443 };
444 let mut output = vec![0; 1024];
445 let mut root_payload = Vec::new();
446 exguid(spaces[0].id).encode(&mut root_payload);
447 let mut root = Vec::new();
448 let mut log = Vec::new();
449 let mut list_id = 16_u32;
450 let mut hashed = Vec::new();
451 for space in spaces {
452 let mut counts = BTreeMap::<u32, u32>::new();
453 for (_, id) in &space.roots {
454 *counts.entry(*id).or_default() += 1;
455 }
456 for object in &space.objects {
457 for (property, value) in &object.properties {
458 if matches!((property >> 26) & 0x1f, 8 | 9) {
459 for id in value.as_chunks::<4>().0 {
460 *counts.entry(u32::from_le_bytes(*id)).or_default() += 1;
461 }
462 }
463 }
464 }
465 let group_id = ExGuid {
466 guid: fresh_guid()?,
467 n: 1,
468 };
469 let mut group_payload = Vec::new();
470 group_id.encode(&mut group_payload);
471 let mut group = if is_section {
472 vec![node(0xb4, None, &group_payload)?, node(0x22, None, &[])?]
473 } else {
474 vec![node(0x21, None, &[0])?]
475 };
476 for (index, guid) in guids.iter().enumerate() {
477 let mut entry = (index as u32).to_le_bytes().to_vec();
478 entry.extend_from_slice(guid);
479 group.push(node(0x24, None, &entry)?);
480 }
481 group.push(node(0x28, None, &[])?);
482 let mut override_crc = if is_section { u32::MAX } else { 0 };
483 for object in space.objects {
484 let data = properties(&object.properties)?;
485 let chunk = append(&mut output, &data)?;
486 let mut payload = object.id.to_le_bytes().to_vec();
487 let mut flags = 0;
488 for (property, value) in object.properties {
489 if !value.is_empty() {
490 match (property >> 26) & 0x1f {
491 8 | 9 => flags |= 1,
492 10..=13 => flags |= 2,
493 _ => {}
494 }
495 }
496 }
497 if is_section {
498 payload.extend_from_slice(&object.jcid.to_le_bytes());
499 payload.push(flags);
500 } else {
501 let body = 1_u64 | (u64::from(flags & 1) << 16);
502 payload.extend_from_slice(&body.to_le_bytes()[..6]);
503 }
504 let count = counts.get(&object.id).copied().unwrap_or(0).to_le_bytes();
505 payload.extend_from_slice(&count);
506 override_crc = crc(override_crc, &count, file_type);
507 let readonly = object.jcid & 0x100000 != 0;
508 if readonly {
509 let hash = md5::compute(&data).0;
510 payload.extend_from_slice(&hash);
511 hashed.push(node(0xc2, Some(Reference::Data(chunk)), &hash)?);
512 }
513 group.push(node(
514 if !is_section {
515 0x2e
516 } else if readonly {
517 0xc5
518 } else {
519 0xa5
520 },
521 Some(Reference::Data(chunk)),
522 &payload,
523 )?);
524 }
525 let group_chunk = if is_section {
526 group.push(node(0xb8, None, &[])?);
527 Some(append_list(&mut output, list_id, &group)?)
528 } else {
529 None
530 };
531 let group_count = group.len();
532 let mut start = Vec::new();
533 exguid(space.id).encode(&mut start);
534 start.extend_from_slice(&0_u32.to_le_bytes());
535 let mut revision = Vec::new();
536 ExGuid {
537 guid: fresh_guid()?,
538 n: 1,
539 }
540 .encode(&mut revision);
541 ExGuid::default().encode(&mut revision);
542 if !is_section {
543 revision.extend_from_slice(&0_u64.to_le_bytes());
544 }
545 revision.extend_from_slice(&1_u32.to_le_bytes());
546 revision.extend_from_slice(&0_u16.to_le_bytes());
547 let mut manifest = vec![
548 node(0x14, None, &start)?,
549 node(if is_section { 0x1e } else { 0x1b }, None, &revision)?,
550 ];
551 if let Some(chunk) = group_chunk {
552 manifest.push(node(
553 0xb0,
554 Some(Reference::NodeList(chunk)),
555 &group_payload,
556 )?);
557 let mut overrides = vec![0; 8];
558 overrides.extend_from_slice(&(!override_crc).to_le_bytes());
559 manifest.push(node(
560 0x84,
561 Some(Reference::Data(Chunk {
562 offset: u64::MAX,
563 length: 0,
564 })),
565 &overrides,
566 )?);
567 } else {
568 manifest.extend(group);
569 }
570 for (role, oid) in space.roots {
571 let mut payload = Vec::new();
572 if is_section {
573 exguid(oid).encode(&mut payload);
574 } else {
575 payload.extend_from_slice(&oid.to_le_bytes());
576 }
577 payload.extend_from_slice(&role.to_le_bytes());
578 manifest.push(node(if is_section { 0x5a } else { 0x59 }, None, &payload)?);
579 }
580 manifest.push(node(0x1c, None, &[])?);
581 let manifest_chunk = append_list(&mut output, list_id + 1, &manifest)?;
582 let mut space_payload = Vec::new();
583 exguid(space.id).encode(&mut space_payload);
584 let space_nodes = vec![
585 node(0xc, None, &space_payload)?,
586 node(0x10, Some(Reference::NodeList(manifest_chunk)), &[])?,
587 ];
588 let space_chunk = append_list(&mut output, list_id + 2, &space_nodes)?;
589 root.push(node(
590 8,
591 Some(Reference::NodeList(space_chunk)),
592 &space_payload,
593 )?);
594 for (id, count) in [
595 (list_id, group_count),
596 (list_id + 1, manifest.len()),
597 (list_id + 2, space_nodes.len()),
598 ] {
599 if id == list_id && !is_section {
600 continue;
601 }
602 log.extend_from_slice(&id.to_le_bytes());
603 log.extend_from_slice(&u32::try_from(count).unwrap().to_le_bytes());
604 }
605 list_id += 3;
606 }
607 root.push(node(4, None, &root_payload)?);
608 let root_chunk = append_list(&mut output, list_id, &root)?;
609 log.extend_from_slice(&list_id.to_le_bytes());
610 log.extend_from_slice(&u32::try_from(root.len()).unwrap().to_le_bytes());
611 let hashed_chunk = if !hashed.is_empty() {
612 let chunk = append_list(&mut output, list_id + 1, &hashed)?;
613 log.extend_from_slice(&(list_id + 1).to_le_bytes());
614 log.extend_from_slice(&u32::try_from(hashed.len()).unwrap().to_le_bytes());
615 Some(chunk)
616 } else {
617 None
618 };
619 finish(
620 &mut output,
621 file_type,
622 log,
623 hashed_chunk,
624 root_chunk,
625 placement([0; 16], file_name),
626 )?;
627 let store = Store::parse(&output)?;
628 RevisionIndex::parse(&store)?.validate_current()?;
629 Ok(output)
630}
631
632/// Ends an image whose lists `output` holds: the transaction log committing `log`'s
633/// entries, then the header naming it, the root list and the hashed-chunk list.
634fn finish(
635 output: &mut Vec<u8>,
636 file_type: FileType,
637 mut log: Vec<u8>,
638 hashed: Option<Chunk>,
639 root: Chunk,
640 placement: [u8; 20],
641) -> Result<()> {
642 let is_section = file_type == FileType::Section;
643 let checksum = if is_section {
644 !crc(u32::MAX, &log, file_type)
645 } else {
646 crc(0, &log, file_type)
647 };
648 log.extend_from_slice(&1_u32.to_le_bytes());
649 log.extend_from_slice(&checksum.to_le_bytes());
650 log.extend_from_slice(&u64::MAX.to_le_bytes());
651 log.extend_from_slice(&0_u32.to_le_bytes());
652 let log_chunk = append(output, &log)?;
653 output[..16].copy_from_slice(&[
654 0xe4, 0x52, 0x5c, 0x7b, 0x8c, 0xd8, 0xa7, 0x4d, 0xae, 0xb1, 0x53, 0x78, 0xd0, 0x29, 0x96,
655 0xd3,
656 ]);
657 if !is_section {
658 output[..16].copy_from_slice(&[
659 0xa1, 0x2f, 0xff, 0x43, 0xd9, 0xef, 0x76, 0x4c, 0x9e, 0xe2, 0x10, 0xea, 0x57, 0x22,
660 0x76, 0x5f,
661 ]);
662 }
663 output[16..32].copy_from_slice(&fresh_guid()?);
664 output[48..64].copy_from_slice(&[
665 0x3f, 0xdd, 0x9a, 0x10, 0x1b, 0x91, 0xf5, 0x49, 0xa5, 0xd0, 0x17, 0x91, 0xed, 0xc8, 0xae,
666 0xd8,
667 ]);
668 for at in [64, 68, 72, 76] {
669 output[at..at + 4]
670 .copy_from_slice(&(if is_section { 42_u32 } else { 27_u32 }).to_le_bytes());
671 }
672 for at in [88, 112] {
673 output[at..at + 4].copy_from_slice(&u32::MAX.to_le_bytes());
674 }
675 output[96..100].copy_from_slice(&1_u32.to_le_bytes());
676 output[128..148].copy_from_slice(&placement);
677 for (at, chunk) in hashed
678 .map(|chunk| (148, chunk))
679 .into_iter()
680 .chain([(160, log_chunk), (172, root)])
681 {
682 output[at..at + 8].copy_from_slice(&chunk.offset.to_le_bytes());
683 output[at + 8..at + 12].copy_from_slice(&(chunk.length as u32).to_le_bytes());
684 }
685 let length = output.len() as u64;
686 output[196..204].copy_from_slice(&length.to_le_bytes());
687 output[212..228].copy_from_slice(&fresh_guid()?);
688 output[228..236].copy_from_slice(&1_u64.to_le_bytes());
689 output[236..252].copy_from_slice(&fresh_guid()?);
690 Ok(())
691}
692
693/// A new section file declaring only its root object space `root`, which has no revision
694/// yet, placed as `placement`: what a whole section's revisions are appended to.
695pub(crate) fn skeleton(root: ExGuid, placement: [u8; 20]) -> Result<Vec<u8>> {
696 let mut output = vec![0; 1024];
697 let mut payload = Vec::new();
698 root.encode(&mut payload);
699 let mut start = payload.clone();
700 start.extend_from_slice(&0_u32.to_le_bytes());
701 let manifest = append_list(&mut output, 16, &[node(0x14, None, &start)?])?;
702 let space = [
703 node(0xc, None, &payload)?,
704 node(0x10, Some(Reference::NodeList(manifest)), &[])?,
705 ];
706 let space = append_list(&mut output, 17, &space)?;
707 let roots = [
708 node(8, Some(Reference::NodeList(space)), &payload)?,
709 node(4, None, &payload)?,
710 ];
711 let roots = append_list(&mut output, 18, &roots)?;
712 let mut log = Vec::new();
713 for (id, count) in [(16_u32, 1_u32), (17, 2), (18, 2)] {
714 log.extend_from_slice(&id.to_le_bytes());
715 log.extend_from_slice(&count.to_le_bytes());
716 }
717 finish(&mut output, FileType::Section, log, None, roots, placement)?;
718 Ok(output)
719}
720
721#[cfg(test)]
722mod tests {
723 #[test]
724 fn initials_take_each_word_first_letter() {
725 // OneNote 2010 stores "snow" with "S" in the native corpus.
726 assert_eq!(super::initials("snow"), "S");
727 assert_eq!(super::initials("Clover"), "C");
728 assert_eq!(super::initials(" Snowbound Test "), "ST");
729 assert_eq!(super::initials("émile zola"), "ÉZ");
730 assert_eq!(super::initials(""), "");
731 }
732}