tokyodoves 1.0.2

A library of an efficient board of Tokyo Doves and associated toolkits
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
use crate::{
    collections::board_set::{BoardSet, RawBoardSet},
    prelude::{Board, BoardBuilder},
};
use std::{
    collections::HashSet,
    io::{BufReader, Read},
};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum Fragment {
    Top(u32),
    Bottom(u32),
    Delimiter,
}

#[derive(Debug)]
pub(crate) struct FragmentIter<R>
where
    R: Read,
{
    reader: BufReader<R>,
    next_is_top: bool,
}

impl<R> FragmentIter<R>
where
    R: Read,
{
    pub fn new(reader: R) -> Self {
        Self {
            reader: BufReader::new(reader),
            next_is_top: true,
        }
    }

    pub fn try_next(&mut self) -> std::io::Result<Option<Fragment>> {
        let mut buf = [0u8; 4];
        let num_read = self.reader.read(&mut buf)?;
        if num_read != 4 {
            return Ok(None);
        }

        let n = u32::from_be_bytes(buf);
        if n == u32::MAX {
            self.next_is_top = true;
            return Ok(Some(Fragment::Delimiter));
        }

        let ret = if self.next_is_top {
            Fragment::Top(n)
        } else {
            Fragment::Bottom(n)
        };
        self.next_is_top = false;
        Ok(Some(ret))
    }
}

impl<R> Iterator for FragmentIter<R>
where
    R: Read,
{
    type Item = Fragment;
    fn next(&mut self) -> Option<Self::Item> {
        self.try_next().unwrap()
    }
}

// ***********************************************************************
//  LazyLoader for Board
// ***********************************************************************
/// A utility to load [`Board`]s in a lazy way from the binary file
/// saved by the [`save`](`BoardSet::save`) method of [`BoardSet`].
///
/// This struct has an internal [`LazyRawBoardLoader`],
/// which is an iterator of `u64`s.
/// The relation between two structs are similar to the one
/// between [`BoardSet`] and [`RawBoardSet`].
///
/// It panics on iteration if some io error occurs in the process.
/// To handle those errors,
/// call the [`try_next`](`LazyBoardLoader::try_next`) method in a loop block.
#[derive(Debug)]
pub struct LazyBoardLoader<R>
where
    R: Read,
{
    raw: LazyRawBoardLoader<R>,
}

impl<R> From<LazyRawBoardLoader<R>> for LazyBoardLoader<R>
where
    R: Read,
{
    fn from(raw: LazyRawBoardLoader<R>) -> Self {
        Self { raw }
    }
}

impl<R> LazyBoardLoader<R>
where
    R: Read,
{
    /// Creates an lazy loader.
    ///
    /// # Examples
    /// ``` ignore
    /// use std::fs::File;
    /// use tokyodoves::collections::LazyBoardLoader;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let path = "/some/path.tdl";
    /// for board in LazyBoardLoader::new(File::open(path)?) {
    ///     println!("{board}");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(reader: R) -> Self {
        Self {
            raw: LazyRawBoardLoader::new(reader),
        }
    }

    /// Returns a reference to the internal [`LazyRawBoardLoader`].
    ///
    /// # Examples
    /// ``` ignore
    /// use std::fs::File;
    /// use tokyodoves::collections::LazyBoardLoader;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let path = "/some/path.tdl";
    /// let lazy_loader = LazyBoardLoader::new(File::open(path)?);
    /// let raw_loader = lazy_loader.raw();
    /// # Ok(())
    /// # }
    /// ```
    pub fn raw(&self) -> &LazyRawBoardLoader<R> {
        &self.raw
    }

    /// Returns a reference to the internal [`LazyRawBoardLoader`].
    ///
    /// # Examples
    /// ``` ignore
    /// use std::fs::File;
    /// use tokyodoves::collections::LazyBoardLoader;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let path = "/some/path.tdl";
    /// let lazy_loader = LazyBoardLoader::new(File::open(path)?);
    /// for hash in lazy_loader.raw_mut() {
    ///     println!("{hash}");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn raw_mut(&mut self) -> &mut LazyRawBoardLoader<R> {
        &mut self.raw
    }

    /// Returns the internal [`LazyRawBoardLoader`].
    ///
    /// # Examples
    /// ``` ignore
    /// use std::fs::File;
    /// use tokyodoves::collections::LazyBoardLoader;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let path = "/some/path.tdl";
    /// let lazy_loader = LazyBoardLoader::new(File::open(path)?);
    /// for hash in lazy_loader.into_raw() {
    ///     println!("{hash}");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn into_raw(self) -> LazyRawBoardLoader<R> {
        self.raw
    }

    /// Returns the next item on iteration.
    ///
    /// # Errors
    /// It returns `Err` if some io error occurs.
    ///
    /// # Examples
    /// ``` ignore
    /// use std::fs::File;
    /// use tokyodoves::collections::LazyBoardLoader;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let path = "/some/path.tdl";
    /// let mut lazy_loader = LazyBoardLoader::new(File::open(path)?);
    /// let next_item = lazy_loader.try_next();
    /// # Ok(())
    /// # }
    /// ```
    pub fn try_next(&mut self) -> std::io::Result<Option<Board>> {
        self.raw
            .try_next()
            .map(|x| x.map(|h| BoardBuilder::from(h).build_unchecked()))
    }

    /// Checks if the specified board is contained in a lazy way.
    ///
    /// This method consumes `self`.
    ///
    /// # Example
    /// ``` ignore
    /// use std::fs::File;
    /// use tokyodoves::Board;
    /// use tokyodoves::collections::LazyBoardLoader;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let path = "/some/path.tdl";
    /// let lazy_loader = LazyBoardLoader::new(File::open(path)?);
    /// println!("{:?}", lazy_loader.contains(Board::new()));
    /// # Ok(())
    /// # }
    /// ```
    pub fn contains(self, board: Board) -> std::io::Result<bool> {
        self.into_raw().contains(board.to_u64())
    }

    /// Checks if all boards in the set are contained in a lazy way.
    ///
    /// This method consumes `self`.
    ///
    /// # Errors
    /// It returns `Err` if some io error occurs.
    ///
    /// # Example
    /// ``` ignore
    /// use std::fs::File;
    /// use tokyodoves::Board;
    /// use tokyodoves::collections::{LazyBoardLoader, BoardSet};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let path = "/some/path.tdl";
    /// let lazy_loader = LazyBoardLoader::new(File::open(path)?);
    /// let mut set = BoardSet::new();
    /// set.insert(Board::new());
    /// println!("{:?}", lazy_loader.contains_all(&set));
    /// # Ok(())
    /// # }
    /// ```
    pub fn contains_all(self, set: &BoardSet) -> std::io::Result<bool> {
        self.into_raw().contains_all(set.raw())
    }
}

impl<R> Iterator for LazyBoardLoader<R>
where
    R: Read,
{
    type Item = Board;
    fn next(&mut self) -> Option<Self::Item> {
        self.try_next().unwrap()
    }
}

// ***********************************************************************
//  LazyLoader for u64
// ***********************************************************************
/// A struct almost the same as [`LazyBoardLoader`],
/// except that it loads `u64` expressions of [`Board`]s instead.
///
/// It panics on iteration if some io error occurs in the process.
/// To handle those errors,
/// call the [`try_next`](`LazyRawBoardLoader::try_next`) method in a loop block.
#[derive(Debug)]
pub struct LazyRawBoardLoader<R>
where
    R: Read,
{
    fragment_iter: FragmentIter<R>,
    top: u64,
}

impl<R> From<LazyBoardLoader<R>> for LazyRawBoardLoader<R>
where
    R: Read,
{
    fn from(value: LazyBoardLoader<R>) -> Self {
        value.into_raw()
    }
}

impl<R> LazyRawBoardLoader<R>
where
    R: Read,
{
    /// Creates an lazy loader.
    ///
    /// # Examples
    /// ``` ignore
    /// use std::fs::File;
    /// use tokyodoves::collections::LazyRawBoardLoader;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let path = "/some/path.tdl";
    /// for hash in LazyRawBoardLoader::new(File::open(path)?) {
    ///     println!("{hash}");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(reader: R) -> Self {
        Self {
            fragment_iter: FragmentIter::new(reader),
            top: 0,
        }
    }

    /// Returns the next item on iteration.
    ///
    /// # Errors
    /// It returns `Err` if some io error occurs.
    ///
    /// # Examples
    /// ``` ignore
    /// use std::fs::File;
    /// use tokyodoves::collections::LazyRawBoardLoader;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let path = "/some/path.tdl";
    /// let mut lazy_loader = LazyRawBoardLoader::new(File::open(path)?);
    /// let next_item = lazy_loader.try_next();
    /// # Ok(())
    /// # }
    /// ```
    pub fn try_next(&mut self) -> std::io::Result<Option<u64>> {
        let Some(next) = self.fragment_iter.try_next()? else {
            return Ok(None);
        };

        use Fragment::*;
        match next {
            Delimiter => self.try_next(),
            Top(top) => {
                self.top = (top as u64) << 32;
                self.try_next()
            }
            Bottom(bottom) => Ok(Some(self.top | (bottom as u64))),
        }
    }

    /// Checks if the specified `u64` is contained in a lazy way.
    ///
    /// This method consumes `self`.
    ///
    /// # Example
    /// ``` ignore
    /// use std::fs::File;
    /// use tokyodoves::Board;
    /// use tokyodoves::collections::LazyBoardLoader;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let path = "/some/path.tdl";
    /// let lazy_loader = LazyRawBoardLoader::new(File::open(path)?);
    /// println!("{:?}", lazy_loader.contains(Board::new().to_u64()));
    /// # Ok(())
    /// # }
    /// ```
    pub fn contains(self, hash: u64) -> std::io::Result<bool> {
        let boards = RawBoardSet::from_iter([hash]);
        self.contains_all(&boards)
    }

    /// Checks if all `u64`s in the set are contained in a lazy way.
    ///
    /// This method consumes `self`.
    ///
    /// # Errors
    /// It returns `Err` if some io error occurs.
    ///
    /// # Example
    /// ``` ignore
    /// use std::fs::File;
    /// use tokyodoves::Board;
    /// use tokyodoves::collections::{LazyRawBoardLoader, RawBoardSet};
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let path = "/some/path.tdl";
    /// let lazy_loader = LazyRawBoardLoader::new(File::open(path)?);
    /// let mut set = RawBoardSet::new();
    /// set.insert(Board::new().to_u64());
    /// println!("{:?}", lazy_loader.contains_all(&set));
    /// # Ok(())
    /// # }
    /// ```
    pub fn contains_all(mut self, set: &RawBoardSet) -> std::io::Result<bool> {
        if set.is_empty() {
            return Ok(true);
        }

        let mut tops: HashSet<u32> = set.top2bottoms.keys().cloned().collect();
        let mut bottoms_pool = HashSet::new();

        let dummy_set = HashSet::new();
        let mut bottoms_considering = &dummy_set;
        let dummy_top = 0;
        let mut top_considering = dummy_top;

        loop {
            let Some(next_fragment) = self.fragment_iter.try_next()? else {
                return Ok(tops.is_empty() && bottoms_considering.is_empty());
            };

            use Fragment::*;
            match next_fragment {
                Delimiter => {
                    if !bottoms_considering.is_empty() {
                        return Ok(false);
                    }
                    bottoms_considering = &dummy_set;
                    top_considering = dummy_top;
                    bottoms_pool.clear();
                }
                Top(top) => {
                    top_considering = dummy_top;
                    bottoms_considering = &dummy_set;

                    if let Some(bottoms) = set.top2bottoms.get(&top) {
                        if bottoms.is_empty() {
                            continue;
                        }
                        bottoms_considering = bottoms;
                        top_considering = top;
                        tops.remove(&top);
                    }
                }
                Bottom(bottom) => {
                    if top_considering == dummy_top {
                        continue;
                    }
                    if bottoms_considering.contains(&bottom) {
                        bottoms_pool.insert(bottom);
                    }
                    if bottoms_considering.len() != bottoms_pool.len() {
                        continue;
                    }
                    bottoms_considering = &dummy_set;
                    top_considering = dummy_top;
                    bottoms_pool.clear();
                    if tops.is_empty() {
                        return Ok(true);
                    }
                }
            }
        }
    }
}

impl<R> Iterator for LazyRawBoardLoader<R>
where
    R: Read,
{
    type Item = u64;
    fn next(&mut self) -> Option<Self::Item> {
        self.try_next().unwrap()
    }
}