allow cards to shuffle out of rotation
[sispare-qt.git] / card.cc
blob4d849d13f0a5678ac452d635ede51ddae7c7cff8
1 /*
2 * Copyright (c) 2021, S. Gilles <sgilles@sgilles.net>
4 * Permission to use, copy, modify, and/or distribute this software
5 * for any purpose with or without fee is hereby granted, provided
6 * that the above copyright notice and this permission notice appear
7 * in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
10 * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
11 * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
12 * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
13 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
14 * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
15 * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
16 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 #include "card.hh"
20 #include <fstream>
21 #include <string>
23 #include "session.hh"
24 #include "util.hh"
26 /* Constructor. */
27 Card::Card(const std::filesystem::path& path, const std::string& a, const std::string& b, int level) :
28 path(path),
29 a(a),
30 b(b),
31 hash(std::hash<std::string>{}(Session::salt + path.string())), level(level)
35 /* Cards should be completely determined by the full path to their base dir */
36 bool
37 Card::operator==(const Card& that) const
39 return this->path == that.path;
42 /* We actually want these cards shuffled */
43 std::weak_ordering
44 Card::operator<=>(const Card& that) const
46 return this->hash <=> that.hash;
49 /* Builder method, throwing errors if any of the files are unreadable/malformed */
50 Card
51 Card::mk(const std::filesystem::path& dir)
53 try {
54 std::string a_str = Util::slurp(dir / "side_A");
55 std::string b_str = Util::slurp(dir / "side_B");
56 std::string level_str = Util::slurp(dir / "level");
57 int level_int = 0;
59 try {
60 level_int = std::stoi(level_str);
61 } catch (const std::exception& e) {
62 std::ostringstream err;
64 err << "Invalid level `" << level_str << "' for card " << dir.stem();
65 std::throw_with_nested(std::runtime_error(err.str()));
68 return Card(dir, a_str, b_str, level_int);
69 } catch (...) {
70 std::ostringstream err;
72 err << "Cannot parse card " << dir.stem();
73 std::throw_with_nested(std::runtime_error(err.str()));
77 /* For debugging */
78 std::ostream&
79 operator<< (std::ostream &out, const Card& us)
81 return out << us.path;