text
stringlengths
8
4.13M
/// An enum to represent all characters in the HangulJamo block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum HangulJamo { /// \u{1100}: 'แ„€' HangulChoseongKiyeok, /// \u{1101}: 'แ„' HangulChoseongSsangkiyeok, /// \u{1102}: 'แ„‚' HangulChoseongNieun, /// \u{1103}: 'แ„ƒ' HangulChoseongTikeut, /// \u{1104}: 'แ„„' HangulChoseongSsangtikeut, /// \u{1105}: 'แ„…' HangulChoseongRieul, /// \u{1106}: 'แ„†' HangulChoseongMieum, /// \u{1107}: 'แ„‡' HangulChoseongPieup, /// \u{1108}: 'แ„ˆ' HangulChoseongSsangpieup, /// \u{1109}: 'แ„‰' HangulChoseongSios, /// \u{110a}: 'แ„Š' HangulChoseongSsangsios, /// \u{110b}: 'แ„‹' HangulChoseongIeung, /// \u{110c}: 'แ„Œ' HangulChoseongCieuc, /// \u{110d}: 'แ„' HangulChoseongSsangcieuc, /// \u{110e}: 'แ„Ž' HangulChoseongChieuch, /// \u{110f}: 'แ„' HangulChoseongKhieukh, /// \u{1110}: 'แ„' HangulChoseongThieuth, /// \u{1111}: 'แ„‘' HangulChoseongPhieuph, /// \u{1112}: 'แ„’' HangulChoseongHieuh, /// \u{1113}: 'แ„“' HangulChoseongNieunDashKiyeok, /// \u{1114}: 'แ„”' HangulChoseongSsangnieun, /// \u{1115}: 'แ„•' HangulChoseongNieunDashTikeut, /// \u{1116}: 'แ„–' HangulChoseongNieunDashPieup, /// \u{1117}: 'แ„—' HangulChoseongTikeutDashKiyeok, /// \u{1118}: 'แ„˜' HangulChoseongRieulDashNieun, /// \u{1119}: 'แ„™' HangulChoseongSsangrieul, /// \u{111a}: 'แ„š' HangulChoseongRieulDashHieuh, /// \u{111b}: 'แ„›' HangulChoseongKapyeounrieul, /// \u{111c}: 'แ„œ' HangulChoseongMieumDashPieup, /// \u{111d}: 'แ„' HangulChoseongKapyeounmieum, /// \u{111e}: 'แ„ž' HangulChoseongPieupDashKiyeok, /// \u{111f}: 'แ„Ÿ' HangulChoseongPieupDashNieun, /// \u{1120}: 'แ„ ' HangulChoseongPieupDashTikeut, /// \u{1121}: 'แ„ก' HangulChoseongPieupDashSios, /// \u{1122}: 'แ„ข' HangulChoseongPieupDashSiosDashKiyeok, /// \u{1123}: 'แ„ฃ' HangulChoseongPieupDashSiosDashTikeut, /// \u{1124}: 'แ„ค' HangulChoseongPieupDashSiosDashPieup, /// \u{1125}: 'แ„ฅ' HangulChoseongPieupDashSsangsios, /// \u{1126}: 'แ„ฆ' HangulChoseongPieupDashSiosDashCieuc, /// \u{1127}: 'แ„ง' HangulChoseongPieupDashCieuc, /// \u{1128}: 'แ„จ' HangulChoseongPieupDashChieuch, /// \u{1129}: 'แ„ฉ' HangulChoseongPieupDashThieuth, /// \u{112a}: 'แ„ช' HangulChoseongPieupDashPhieuph, /// \u{112b}: 'แ„ซ' HangulChoseongKapyeounpieup, /// \u{112c}: 'แ„ฌ' HangulChoseongKapyeounssangpieup, /// \u{112d}: 'แ„ญ' HangulChoseongSiosDashKiyeok, /// \u{112e}: 'แ„ฎ' HangulChoseongSiosDashNieun, /// \u{112f}: 'แ„ฏ' HangulChoseongSiosDashTikeut, /// \u{1130}: 'แ„ฐ' HangulChoseongSiosDashRieul, /// \u{1131}: 'แ„ฑ' HangulChoseongSiosDashMieum, /// \u{1132}: 'แ„ฒ' HangulChoseongSiosDashPieup, /// \u{1133}: 'แ„ณ' HangulChoseongSiosDashPieupDashKiyeok, /// \u{1134}: 'แ„ด' HangulChoseongSiosDashSsangsios, /// \u{1135}: 'แ„ต' HangulChoseongSiosDashIeung, /// \u{1136}: 'แ„ถ' HangulChoseongSiosDashCieuc, /// \u{1137}: 'แ„ท' HangulChoseongSiosDashChieuch, /// \u{1138}: 'แ„ธ' HangulChoseongSiosDashKhieukh, /// \u{1139}: 'แ„น' HangulChoseongSiosDashThieuth, /// \u{113a}: 'แ„บ' HangulChoseongSiosDashPhieuph, /// \u{113b}: 'แ„ป' HangulChoseongSiosDashHieuh, /// \u{113c}: 'แ„ผ' HangulChoseongChitueumsios, /// \u{113d}: 'แ„ฝ' HangulChoseongChitueumssangsios, /// \u{113e}: 'แ„พ' HangulChoseongCeongchieumsios, /// \u{113f}: 'แ„ฟ' HangulChoseongCeongchieumssangsios, /// \u{1140}: 'แ…€' HangulChoseongPansios, /// \u{1141}: 'แ…' HangulChoseongIeungDashKiyeok, /// \u{1142}: 'แ…‚' HangulChoseongIeungDashTikeut, /// \u{1143}: 'แ…ƒ' HangulChoseongIeungDashMieum, /// \u{1144}: 'แ…„' HangulChoseongIeungDashPieup, /// \u{1145}: 'แ……' HangulChoseongIeungDashSios, /// \u{1146}: 'แ…†' HangulChoseongIeungDashPansios, /// \u{1147}: 'แ…‡' HangulChoseongSsangieung, /// \u{1148}: 'แ…ˆ' HangulChoseongIeungDashCieuc, /// \u{1149}: 'แ…‰' HangulChoseongIeungDashChieuch, /// \u{114a}: 'แ…Š' HangulChoseongIeungDashThieuth, /// \u{114b}: 'แ…‹' HangulChoseongIeungDashPhieuph, /// \u{114c}: 'แ…Œ' HangulChoseongYesieung, /// \u{114d}: 'แ…' HangulChoseongCieucDashIeung, /// \u{114e}: 'แ…Ž' HangulChoseongChitueumcieuc, /// \u{114f}: 'แ…' HangulChoseongChitueumssangcieuc, /// \u{1150}: 'แ…' HangulChoseongCeongchieumcieuc, /// \u{1151}: 'แ…‘' HangulChoseongCeongchieumssangcieuc, /// \u{1152}: 'แ…’' HangulChoseongChieuchDashKhieukh, /// \u{1153}: 'แ…“' HangulChoseongChieuchDashHieuh, /// \u{1154}: 'แ…”' HangulChoseongChitueumchieuch, /// \u{1155}: 'แ…•' HangulChoseongCeongchieumchieuch, /// \u{1156}: 'แ…–' HangulChoseongPhieuphDashPieup, /// \u{1157}: 'แ…—' HangulChoseongKapyeounphieuph, /// \u{1158}: 'แ…˜' HangulChoseongSsanghieuh, /// \u{1159}: 'แ…™' HangulChoseongYeorinhieuh, /// \u{115a}: 'แ…š' HangulChoseongKiyeokDashTikeut, /// \u{115b}: 'แ…›' HangulChoseongNieunDashSios, /// \u{115c}: 'แ…œ' HangulChoseongNieunDashCieuc, /// \u{115d}: 'แ…' HangulChoseongNieunDashHieuh, /// \u{115e}: 'แ…ž' HangulChoseongTikeutDashRieul, /// \u{115f}: 'แ…Ÿ' HangulChoseongFiller, /// \u{1160}: 'แ… ' HangulJungseongFiller, /// \u{1161}: 'แ…ก' HangulJungseongA, /// \u{1162}: 'แ…ข' HangulJungseongAe, /// \u{1163}: 'แ…ฃ' HangulJungseongYa, /// \u{1164}: 'แ…ค' HangulJungseongYae, /// \u{1165}: 'แ…ฅ' HangulJungseongEo, /// \u{1166}: 'แ…ฆ' HangulJungseongE, /// \u{1167}: 'แ…ง' HangulJungseongYeo, /// \u{1168}: 'แ…จ' HangulJungseongYe, /// \u{1169}: 'แ…ฉ' HangulJungseongO, /// \u{116a}: 'แ…ช' HangulJungseongWa, /// \u{116b}: 'แ…ซ' HangulJungseongWae, /// \u{116c}: 'แ…ฌ' HangulJungseongOe, /// \u{116d}: 'แ…ญ' HangulJungseongYo, /// \u{116e}: 'แ…ฎ' HangulJungseongU, /// \u{116f}: 'แ…ฏ' HangulJungseongWeo, /// \u{1170}: 'แ…ฐ' HangulJungseongWe, /// \u{1171}: 'แ…ฑ' HangulJungseongWi, /// \u{1172}: 'แ…ฒ' HangulJungseongYu, /// \u{1173}: 'แ…ณ' HangulJungseongEu, /// \u{1174}: 'แ…ด' HangulJungseongYi, /// \u{1175}: 'แ…ต' HangulJungseongI, /// \u{1176}: 'แ…ถ' HangulJungseongADashO, /// \u{1177}: 'แ…ท' HangulJungseongADashU, /// \u{1178}: 'แ…ธ' HangulJungseongYaDashO, /// \u{1179}: 'แ…น' HangulJungseongYaDashYo, /// \u{117a}: 'แ…บ' HangulJungseongEoDashO, /// \u{117b}: 'แ…ป' HangulJungseongEoDashU, /// \u{117c}: 'แ…ผ' HangulJungseongEoDashEu, /// \u{117d}: 'แ…ฝ' HangulJungseongYeoDashO, /// \u{117e}: 'แ…พ' HangulJungseongYeoDashU, /// \u{117f}: 'แ…ฟ' HangulJungseongODashEo, /// \u{1180}: 'แ†€' HangulJungseongODashE, /// \u{1181}: 'แ†' HangulJungseongODashYe, /// \u{1182}: 'แ†‚' HangulJungseongODashO, /// \u{1183}: 'แ†ƒ' HangulJungseongODashU, /// \u{1184}: 'แ†„' HangulJungseongYoDashYa, /// \u{1185}: 'แ†…' HangulJungseongYoDashYae, /// \u{1186}: 'แ††' HangulJungseongYoDashYeo, /// \u{1187}: 'แ†‡' HangulJungseongYoDashO, /// \u{1188}: 'แ†ˆ' HangulJungseongYoDashI, /// \u{1189}: 'แ†‰' HangulJungseongUDashA, /// \u{118a}: 'แ†Š' HangulJungseongUDashAe, /// \u{118b}: 'แ†‹' HangulJungseongUDashEoDashEu, /// \u{118c}: 'แ†Œ' HangulJungseongUDashYe, /// \u{118d}: 'แ†' HangulJungseongUDashU, /// \u{118e}: 'แ†Ž' HangulJungseongYuDashA, /// \u{118f}: 'แ†' HangulJungseongYuDashEo, /// \u{1190}: 'แ†' HangulJungseongYuDashE, /// \u{1191}: 'แ†‘' HangulJungseongYuDashYeo, /// \u{1192}: 'แ†’' HangulJungseongYuDashYe, /// \u{1193}: 'แ†“' HangulJungseongYuDashU, /// \u{1194}: 'แ†”' HangulJungseongYuDashI, /// \u{1195}: 'แ†•' HangulJungseongEuDashU, /// \u{1196}: 'แ†–' HangulJungseongEuDashEu, /// \u{1197}: 'แ†—' HangulJungseongYiDashU, /// \u{1198}: 'แ†˜' HangulJungseongIDashA, /// \u{1199}: 'แ†™' HangulJungseongIDashYa, /// \u{119a}: 'แ†š' HangulJungseongIDashO, /// \u{119b}: 'แ†›' HangulJungseongIDashU, /// \u{119c}: 'แ†œ' HangulJungseongIDashEu, /// \u{119d}: 'แ†' HangulJungseongIDashAraea, /// \u{119e}: 'แ†ž' HangulJungseongAraea, /// \u{119f}: 'แ†Ÿ' HangulJungseongAraeaDashEo, /// \u{11a0}: 'แ† ' HangulJungseongAraeaDashU, /// \u{11a1}: 'แ†ก' HangulJungseongAraeaDashI, /// \u{11a2}: 'แ†ข' HangulJungseongSsangaraea, /// \u{11a3}: 'แ†ฃ' HangulJungseongADashEu, /// \u{11a4}: 'แ†ค' HangulJungseongYaDashU, /// \u{11a5}: 'แ†ฅ' HangulJungseongYeoDashYa, /// \u{11a6}: 'แ†ฆ' HangulJungseongODashYa, /// \u{11a7}: 'แ†ง' HangulJungseongODashYae, /// \u{11a8}: 'แ†จ' HangulJongseongKiyeok, /// \u{11a9}: 'แ†ฉ' HangulJongseongSsangkiyeok, /// \u{11aa}: 'แ†ช' HangulJongseongKiyeokDashSios, /// \u{11ab}: 'แ†ซ' HangulJongseongNieun, /// \u{11ac}: 'แ†ฌ' HangulJongseongNieunDashCieuc, /// \u{11ad}: 'แ†ญ' HangulJongseongNieunDashHieuh, /// \u{11ae}: 'แ†ฎ' HangulJongseongTikeut, /// \u{11af}: 'แ†ฏ' HangulJongseongRieul, /// \u{11b0}: 'แ†ฐ' HangulJongseongRieulDashKiyeok, /// \u{11b1}: 'แ†ฑ' HangulJongseongRieulDashMieum, /// \u{11b2}: 'แ†ฒ' HangulJongseongRieulDashPieup, /// \u{11b3}: 'แ†ณ' HangulJongseongRieulDashSios, /// \u{11b4}: 'แ†ด' HangulJongseongRieulDashThieuth, /// \u{11b5}: 'แ†ต' HangulJongseongRieulDashPhieuph, /// \u{11b6}: 'แ†ถ' HangulJongseongRieulDashHieuh, /// \u{11b7}: 'แ†ท' HangulJongseongMieum, /// \u{11b8}: 'แ†ธ' HangulJongseongPieup, /// \u{11b9}: 'แ†น' HangulJongseongPieupDashSios, /// \u{11ba}: 'แ†บ' HangulJongseongSios, /// \u{11bb}: 'แ†ป' HangulJongseongSsangsios, /// \u{11bc}: 'แ†ผ' HangulJongseongIeung, /// \u{11bd}: 'แ†ฝ' HangulJongseongCieuc, /// \u{11be}: 'แ†พ' HangulJongseongChieuch, /// \u{11bf}: 'แ†ฟ' HangulJongseongKhieukh, /// \u{11c0}: 'แ‡€' HangulJongseongThieuth, /// \u{11c1}: 'แ‡' HangulJongseongPhieuph, /// \u{11c2}: 'แ‡‚' HangulJongseongHieuh, /// \u{11c3}: 'แ‡ƒ' HangulJongseongKiyeokDashRieul, /// \u{11c4}: 'แ‡„' HangulJongseongKiyeokDashSiosDashKiyeok, /// \u{11c5}: 'แ‡…' HangulJongseongNieunDashKiyeok, /// \u{11c6}: 'แ‡†' HangulJongseongNieunDashTikeut, /// \u{11c7}: 'แ‡‡' HangulJongseongNieunDashSios, /// \u{11c8}: 'แ‡ˆ' HangulJongseongNieunDashPansios, /// \u{11c9}: 'แ‡‰' HangulJongseongNieunDashThieuth, /// \u{11ca}: 'แ‡Š' HangulJongseongTikeutDashKiyeok, /// \u{11cb}: 'แ‡‹' HangulJongseongTikeutDashRieul, /// \u{11cc}: 'แ‡Œ' HangulJongseongRieulDashKiyeokDashSios, /// \u{11cd}: 'แ‡' HangulJongseongRieulDashNieun, /// \u{11ce}: 'แ‡Ž' HangulJongseongRieulDashTikeut, /// \u{11cf}: 'แ‡' HangulJongseongRieulDashTikeutDashHieuh, /// \u{11d0}: 'แ‡' HangulJongseongSsangrieul, /// \u{11d1}: 'แ‡‘' HangulJongseongRieulDashMieumDashKiyeok, /// \u{11d2}: 'แ‡’' HangulJongseongRieulDashMieumDashSios, /// \u{11d3}: 'แ‡“' HangulJongseongRieulDashPieupDashSios, /// \u{11d4}: 'แ‡”' HangulJongseongRieulDashPieupDashHieuh, /// \u{11d5}: 'แ‡•' HangulJongseongRieulDashKapyeounpieup, /// \u{11d6}: 'แ‡–' HangulJongseongRieulDashSsangsios, /// \u{11d7}: 'แ‡—' HangulJongseongRieulDashPansios, /// \u{11d8}: 'แ‡˜' HangulJongseongRieulDashKhieukh, /// \u{11d9}: 'แ‡™' HangulJongseongRieulDashYeorinhieuh, /// \u{11da}: 'แ‡š' HangulJongseongMieumDashKiyeok, /// \u{11db}: 'แ‡›' HangulJongseongMieumDashRieul, /// \u{11dc}: 'แ‡œ' HangulJongseongMieumDashPieup, /// \u{11dd}: 'แ‡' HangulJongseongMieumDashSios, /// \u{11de}: 'แ‡ž' HangulJongseongMieumDashSsangsios, /// \u{11df}: 'แ‡Ÿ' HangulJongseongMieumDashPansios, /// \u{11e0}: 'แ‡ ' HangulJongseongMieumDashChieuch, /// \u{11e1}: 'แ‡ก' HangulJongseongMieumDashHieuh, /// \u{11e2}: 'แ‡ข' HangulJongseongKapyeounmieum, /// \u{11e3}: 'แ‡ฃ' HangulJongseongPieupDashRieul, /// \u{11e4}: 'แ‡ค' HangulJongseongPieupDashPhieuph, /// \u{11e5}: 'แ‡ฅ' HangulJongseongPieupDashHieuh, /// \u{11e6}: 'แ‡ฆ' HangulJongseongKapyeounpieup, /// \u{11e7}: 'แ‡ง' HangulJongseongSiosDashKiyeok, /// \u{11e8}: 'แ‡จ' HangulJongseongSiosDashTikeut, /// \u{11e9}: 'แ‡ฉ' HangulJongseongSiosDashRieul, /// \u{11ea}: 'แ‡ช' HangulJongseongSiosDashPieup, /// \u{11eb}: 'แ‡ซ' HangulJongseongPansios, /// \u{11ec}: 'แ‡ฌ' HangulJongseongIeungDashKiyeok, /// \u{11ed}: 'แ‡ญ' HangulJongseongIeungDashSsangkiyeok, /// \u{11ee}: 'แ‡ฎ' HangulJongseongSsangieung, /// \u{11ef}: 'แ‡ฏ' HangulJongseongIeungDashKhieukh, /// \u{11f0}: 'แ‡ฐ' HangulJongseongYesieung, /// \u{11f1}: 'แ‡ฑ' HangulJongseongYesieungDashSios, /// \u{11f2}: 'แ‡ฒ' HangulJongseongYesieungDashPansios, /// \u{11f3}: 'แ‡ณ' HangulJongseongPhieuphDashPieup, /// \u{11f4}: 'แ‡ด' HangulJongseongKapyeounphieuph, /// \u{11f5}: 'แ‡ต' HangulJongseongHieuhDashNieun, /// \u{11f6}: 'แ‡ถ' HangulJongseongHieuhDashRieul, /// \u{11f7}: 'แ‡ท' HangulJongseongHieuhDashMieum, /// \u{11f8}: 'แ‡ธ' HangulJongseongHieuhDashPieup, /// \u{11f9}: 'แ‡น' HangulJongseongYeorinhieuh, /// \u{11fa}: 'แ‡บ' HangulJongseongKiyeokDashNieun, /// \u{11fb}: 'แ‡ป' HangulJongseongKiyeokDashPieup, /// \u{11fc}: 'แ‡ผ' HangulJongseongKiyeokDashChieuch, /// \u{11fd}: 'แ‡ฝ' HangulJongseongKiyeokDashKhieukh, /// \u{11fe}: 'แ‡พ' HangulJongseongKiyeokDashHieuh, } impl Into<char> for HangulJamo { fn into(self) -> char { match self { HangulJamo::HangulChoseongKiyeok => 'แ„€', HangulJamo::HangulChoseongSsangkiyeok => 'แ„', HangulJamo::HangulChoseongNieun => 'แ„‚', HangulJamo::HangulChoseongTikeut => 'แ„ƒ', HangulJamo::HangulChoseongSsangtikeut => 'แ„„', HangulJamo::HangulChoseongRieul => 'แ„…', HangulJamo::HangulChoseongMieum => 'แ„†', HangulJamo::HangulChoseongPieup => 'แ„‡', HangulJamo::HangulChoseongSsangpieup => 'แ„ˆ', HangulJamo::HangulChoseongSios => 'แ„‰', HangulJamo::HangulChoseongSsangsios => 'แ„Š', HangulJamo::HangulChoseongIeung => 'แ„‹', HangulJamo::HangulChoseongCieuc => 'แ„Œ', HangulJamo::HangulChoseongSsangcieuc => 'แ„', HangulJamo::HangulChoseongChieuch => 'แ„Ž', HangulJamo::HangulChoseongKhieukh => 'แ„', HangulJamo::HangulChoseongThieuth => 'แ„', HangulJamo::HangulChoseongPhieuph => 'แ„‘', HangulJamo::HangulChoseongHieuh => 'แ„’', HangulJamo::HangulChoseongNieunDashKiyeok => 'แ„“', HangulJamo::HangulChoseongSsangnieun => 'แ„”', HangulJamo::HangulChoseongNieunDashTikeut => 'แ„•', HangulJamo::HangulChoseongNieunDashPieup => 'แ„–', HangulJamo::HangulChoseongTikeutDashKiyeok => 'แ„—', HangulJamo::HangulChoseongRieulDashNieun => 'แ„˜', HangulJamo::HangulChoseongSsangrieul => 'แ„™', HangulJamo::HangulChoseongRieulDashHieuh => 'แ„š', HangulJamo::HangulChoseongKapyeounrieul => 'แ„›', HangulJamo::HangulChoseongMieumDashPieup => 'แ„œ', HangulJamo::HangulChoseongKapyeounmieum => 'แ„', HangulJamo::HangulChoseongPieupDashKiyeok => 'แ„ž', HangulJamo::HangulChoseongPieupDashNieun => 'แ„Ÿ', HangulJamo::HangulChoseongPieupDashTikeut => 'แ„ ', HangulJamo::HangulChoseongPieupDashSios => 'แ„ก', HangulJamo::HangulChoseongPieupDashSiosDashKiyeok => 'แ„ข', HangulJamo::HangulChoseongPieupDashSiosDashTikeut => 'แ„ฃ', HangulJamo::HangulChoseongPieupDashSiosDashPieup => 'แ„ค', HangulJamo::HangulChoseongPieupDashSsangsios => 'แ„ฅ', HangulJamo::HangulChoseongPieupDashSiosDashCieuc => 'แ„ฆ', HangulJamo::HangulChoseongPieupDashCieuc => 'แ„ง', HangulJamo::HangulChoseongPieupDashChieuch => 'แ„จ', HangulJamo::HangulChoseongPieupDashThieuth => 'แ„ฉ', HangulJamo::HangulChoseongPieupDashPhieuph => 'แ„ช', HangulJamo::HangulChoseongKapyeounpieup => 'แ„ซ', HangulJamo::HangulChoseongKapyeounssangpieup => 'แ„ฌ', HangulJamo::HangulChoseongSiosDashKiyeok => 'แ„ญ', HangulJamo::HangulChoseongSiosDashNieun => 'แ„ฎ', HangulJamo::HangulChoseongSiosDashTikeut => 'แ„ฏ', HangulJamo::HangulChoseongSiosDashRieul => 'แ„ฐ', HangulJamo::HangulChoseongSiosDashMieum => 'แ„ฑ', HangulJamo::HangulChoseongSiosDashPieup => 'แ„ฒ', HangulJamo::HangulChoseongSiosDashPieupDashKiyeok => 'แ„ณ', HangulJamo::HangulChoseongSiosDashSsangsios => 'แ„ด', HangulJamo::HangulChoseongSiosDashIeung => 'แ„ต', HangulJamo::HangulChoseongSiosDashCieuc => 'แ„ถ', HangulJamo::HangulChoseongSiosDashChieuch => 'แ„ท', HangulJamo::HangulChoseongSiosDashKhieukh => 'แ„ธ', HangulJamo::HangulChoseongSiosDashThieuth => 'แ„น', HangulJamo::HangulChoseongSiosDashPhieuph => 'แ„บ', HangulJamo::HangulChoseongSiosDashHieuh => 'แ„ป', HangulJamo::HangulChoseongChitueumsios => 'แ„ผ', HangulJamo::HangulChoseongChitueumssangsios => 'แ„ฝ', HangulJamo::HangulChoseongCeongchieumsios => 'แ„พ', HangulJamo::HangulChoseongCeongchieumssangsios => 'แ„ฟ', HangulJamo::HangulChoseongPansios => 'แ…€', HangulJamo::HangulChoseongIeungDashKiyeok => 'แ…', HangulJamo::HangulChoseongIeungDashTikeut => 'แ…‚', HangulJamo::HangulChoseongIeungDashMieum => 'แ…ƒ', HangulJamo::HangulChoseongIeungDashPieup => 'แ…„', HangulJamo::HangulChoseongIeungDashSios => 'แ……', HangulJamo::HangulChoseongIeungDashPansios => 'แ…†', HangulJamo::HangulChoseongSsangieung => 'แ…‡', HangulJamo::HangulChoseongIeungDashCieuc => 'แ…ˆ', HangulJamo::HangulChoseongIeungDashChieuch => 'แ…‰', HangulJamo::HangulChoseongIeungDashThieuth => 'แ…Š', HangulJamo::HangulChoseongIeungDashPhieuph => 'แ…‹', HangulJamo::HangulChoseongYesieung => 'แ…Œ', HangulJamo::HangulChoseongCieucDashIeung => 'แ…', HangulJamo::HangulChoseongChitueumcieuc => 'แ…Ž', HangulJamo::HangulChoseongChitueumssangcieuc => 'แ…', HangulJamo::HangulChoseongCeongchieumcieuc => 'แ…', HangulJamo::HangulChoseongCeongchieumssangcieuc => 'แ…‘', HangulJamo::HangulChoseongChieuchDashKhieukh => 'แ…’', HangulJamo::HangulChoseongChieuchDashHieuh => 'แ…“', HangulJamo::HangulChoseongChitueumchieuch => 'แ…”', HangulJamo::HangulChoseongCeongchieumchieuch => 'แ…•', HangulJamo::HangulChoseongPhieuphDashPieup => 'แ…–', HangulJamo::HangulChoseongKapyeounphieuph => 'แ…—', HangulJamo::HangulChoseongSsanghieuh => 'แ…˜', HangulJamo::HangulChoseongYeorinhieuh => 'แ…™', HangulJamo::HangulChoseongKiyeokDashTikeut => 'แ…š', HangulJamo::HangulChoseongNieunDashSios => 'แ…›', HangulJamo::HangulChoseongNieunDashCieuc => 'แ…œ', HangulJamo::HangulChoseongNieunDashHieuh => 'แ…', HangulJamo::HangulChoseongTikeutDashRieul => 'แ…ž', HangulJamo::HangulChoseongFiller => 'แ…Ÿ', HangulJamo::HangulJungseongFiller => 'แ… ', HangulJamo::HangulJungseongA => 'แ…ก', HangulJamo::HangulJungseongAe => 'แ…ข', HangulJamo::HangulJungseongYa => 'แ…ฃ', HangulJamo::HangulJungseongYae => 'แ…ค', HangulJamo::HangulJungseongEo => 'แ…ฅ', HangulJamo::HangulJungseongE => 'แ…ฆ', HangulJamo::HangulJungseongYeo => 'แ…ง', HangulJamo::HangulJungseongYe => 'แ…จ', HangulJamo::HangulJungseongO => 'แ…ฉ', HangulJamo::HangulJungseongWa => 'แ…ช', HangulJamo::HangulJungseongWae => 'แ…ซ', HangulJamo::HangulJungseongOe => 'แ…ฌ', HangulJamo::HangulJungseongYo => 'แ…ญ', HangulJamo::HangulJungseongU => 'แ…ฎ', HangulJamo::HangulJungseongWeo => 'แ…ฏ', HangulJamo::HangulJungseongWe => 'แ…ฐ', HangulJamo::HangulJungseongWi => 'แ…ฑ', HangulJamo::HangulJungseongYu => 'แ…ฒ', HangulJamo::HangulJungseongEu => 'แ…ณ', HangulJamo::HangulJungseongYi => 'แ…ด', HangulJamo::HangulJungseongI => 'แ…ต', HangulJamo::HangulJungseongADashO => 'แ…ถ', HangulJamo::HangulJungseongADashU => 'แ…ท', HangulJamo::HangulJungseongYaDashO => 'แ…ธ', HangulJamo::HangulJungseongYaDashYo => 'แ…น', HangulJamo::HangulJungseongEoDashO => 'แ…บ', HangulJamo::HangulJungseongEoDashU => 'แ…ป', HangulJamo::HangulJungseongEoDashEu => 'แ…ผ', HangulJamo::HangulJungseongYeoDashO => 'แ…ฝ', HangulJamo::HangulJungseongYeoDashU => 'แ…พ', HangulJamo::HangulJungseongODashEo => 'แ…ฟ', HangulJamo::HangulJungseongODashE => 'แ†€', HangulJamo::HangulJungseongODashYe => 'แ†', HangulJamo::HangulJungseongODashO => 'แ†‚', HangulJamo::HangulJungseongODashU => 'แ†ƒ', HangulJamo::HangulJungseongYoDashYa => 'แ†„', HangulJamo::HangulJungseongYoDashYae => 'แ†…', HangulJamo::HangulJungseongYoDashYeo => 'แ††', HangulJamo::HangulJungseongYoDashO => 'แ†‡', HangulJamo::HangulJungseongYoDashI => 'แ†ˆ', HangulJamo::HangulJungseongUDashA => 'แ†‰', HangulJamo::HangulJungseongUDashAe => 'แ†Š', HangulJamo::HangulJungseongUDashEoDashEu => 'แ†‹', HangulJamo::HangulJungseongUDashYe => 'แ†Œ', HangulJamo::HangulJungseongUDashU => 'แ†', HangulJamo::HangulJungseongYuDashA => 'แ†Ž', HangulJamo::HangulJungseongYuDashEo => 'แ†', HangulJamo::HangulJungseongYuDashE => 'แ†', HangulJamo::HangulJungseongYuDashYeo => 'แ†‘', HangulJamo::HangulJungseongYuDashYe => 'แ†’', HangulJamo::HangulJungseongYuDashU => 'แ†“', HangulJamo::HangulJungseongYuDashI => 'แ†”', HangulJamo::HangulJungseongEuDashU => 'แ†•', HangulJamo::HangulJungseongEuDashEu => 'แ†–', HangulJamo::HangulJungseongYiDashU => 'แ†—', HangulJamo::HangulJungseongIDashA => 'แ†˜', HangulJamo::HangulJungseongIDashYa => 'แ†™', HangulJamo::HangulJungseongIDashO => 'แ†š', HangulJamo::HangulJungseongIDashU => 'แ†›', HangulJamo::HangulJungseongIDashEu => 'แ†œ', HangulJamo::HangulJungseongIDashAraea => 'แ†', HangulJamo::HangulJungseongAraea => 'แ†ž', HangulJamo::HangulJungseongAraeaDashEo => 'แ†Ÿ', HangulJamo::HangulJungseongAraeaDashU => 'แ† ', HangulJamo::HangulJungseongAraeaDashI => 'แ†ก', HangulJamo::HangulJungseongSsangaraea => 'แ†ข', HangulJamo::HangulJungseongADashEu => 'แ†ฃ', HangulJamo::HangulJungseongYaDashU => 'แ†ค', HangulJamo::HangulJungseongYeoDashYa => 'แ†ฅ', HangulJamo::HangulJungseongODashYa => 'แ†ฆ', HangulJamo::HangulJungseongODashYae => 'แ†ง', HangulJamo::HangulJongseongKiyeok => 'แ†จ', HangulJamo::HangulJongseongSsangkiyeok => 'แ†ฉ', HangulJamo::HangulJongseongKiyeokDashSios => 'แ†ช', HangulJamo::HangulJongseongNieun => 'แ†ซ', HangulJamo::HangulJongseongNieunDashCieuc => 'แ†ฌ', HangulJamo::HangulJongseongNieunDashHieuh => 'แ†ญ', HangulJamo::HangulJongseongTikeut => 'แ†ฎ', HangulJamo::HangulJongseongRieul => 'แ†ฏ', HangulJamo::HangulJongseongRieulDashKiyeok => 'แ†ฐ', HangulJamo::HangulJongseongRieulDashMieum => 'แ†ฑ', HangulJamo::HangulJongseongRieulDashPieup => 'แ†ฒ', HangulJamo::HangulJongseongRieulDashSios => 'แ†ณ', HangulJamo::HangulJongseongRieulDashThieuth => 'แ†ด', HangulJamo::HangulJongseongRieulDashPhieuph => 'แ†ต', HangulJamo::HangulJongseongRieulDashHieuh => 'แ†ถ', HangulJamo::HangulJongseongMieum => 'แ†ท', HangulJamo::HangulJongseongPieup => 'แ†ธ', HangulJamo::HangulJongseongPieupDashSios => 'แ†น', HangulJamo::HangulJongseongSios => 'แ†บ', HangulJamo::HangulJongseongSsangsios => 'แ†ป', HangulJamo::HangulJongseongIeung => 'แ†ผ', HangulJamo::HangulJongseongCieuc => 'แ†ฝ', HangulJamo::HangulJongseongChieuch => 'แ†พ', HangulJamo::HangulJongseongKhieukh => 'แ†ฟ', HangulJamo::HangulJongseongThieuth => 'แ‡€', HangulJamo::HangulJongseongPhieuph => 'แ‡', HangulJamo::HangulJongseongHieuh => 'แ‡‚', HangulJamo::HangulJongseongKiyeokDashRieul => 'แ‡ƒ', HangulJamo::HangulJongseongKiyeokDashSiosDashKiyeok => 'แ‡„', HangulJamo::HangulJongseongNieunDashKiyeok => 'แ‡…', HangulJamo::HangulJongseongNieunDashTikeut => 'แ‡†', HangulJamo::HangulJongseongNieunDashSios => 'แ‡‡', HangulJamo::HangulJongseongNieunDashPansios => 'แ‡ˆ', HangulJamo::HangulJongseongNieunDashThieuth => 'แ‡‰', HangulJamo::HangulJongseongTikeutDashKiyeok => 'แ‡Š', HangulJamo::HangulJongseongTikeutDashRieul => 'แ‡‹', HangulJamo::HangulJongseongRieulDashKiyeokDashSios => 'แ‡Œ', HangulJamo::HangulJongseongRieulDashNieun => 'แ‡', HangulJamo::HangulJongseongRieulDashTikeut => 'แ‡Ž', HangulJamo::HangulJongseongRieulDashTikeutDashHieuh => 'แ‡', HangulJamo::HangulJongseongSsangrieul => 'แ‡', HangulJamo::HangulJongseongRieulDashMieumDashKiyeok => 'แ‡‘', HangulJamo::HangulJongseongRieulDashMieumDashSios => 'แ‡’', HangulJamo::HangulJongseongRieulDashPieupDashSios => 'แ‡“', HangulJamo::HangulJongseongRieulDashPieupDashHieuh => 'แ‡”', HangulJamo::HangulJongseongRieulDashKapyeounpieup => 'แ‡•', HangulJamo::HangulJongseongRieulDashSsangsios => 'แ‡–', HangulJamo::HangulJongseongRieulDashPansios => 'แ‡—', HangulJamo::HangulJongseongRieulDashKhieukh => 'แ‡˜', HangulJamo::HangulJongseongRieulDashYeorinhieuh => 'แ‡™', HangulJamo::HangulJongseongMieumDashKiyeok => 'แ‡š', HangulJamo::HangulJongseongMieumDashRieul => 'แ‡›', HangulJamo::HangulJongseongMieumDashPieup => 'แ‡œ', HangulJamo::HangulJongseongMieumDashSios => 'แ‡', HangulJamo::HangulJongseongMieumDashSsangsios => 'แ‡ž', HangulJamo::HangulJongseongMieumDashPansios => 'แ‡Ÿ', HangulJamo::HangulJongseongMieumDashChieuch => 'แ‡ ', HangulJamo::HangulJongseongMieumDashHieuh => 'แ‡ก', HangulJamo::HangulJongseongKapyeounmieum => 'แ‡ข', HangulJamo::HangulJongseongPieupDashRieul => 'แ‡ฃ', HangulJamo::HangulJongseongPieupDashPhieuph => 'แ‡ค', HangulJamo::HangulJongseongPieupDashHieuh => 'แ‡ฅ', HangulJamo::HangulJongseongKapyeounpieup => 'แ‡ฆ', HangulJamo::HangulJongseongSiosDashKiyeok => 'แ‡ง', HangulJamo::HangulJongseongSiosDashTikeut => 'แ‡จ', HangulJamo::HangulJongseongSiosDashRieul => 'แ‡ฉ', HangulJamo::HangulJongseongSiosDashPieup => 'แ‡ช', HangulJamo::HangulJongseongPansios => 'แ‡ซ', HangulJamo::HangulJongseongIeungDashKiyeok => 'แ‡ฌ', HangulJamo::HangulJongseongIeungDashSsangkiyeok => 'แ‡ญ', HangulJamo::HangulJongseongSsangieung => 'แ‡ฎ', HangulJamo::HangulJongseongIeungDashKhieukh => 'แ‡ฏ', HangulJamo::HangulJongseongYesieung => 'แ‡ฐ', HangulJamo::HangulJongseongYesieungDashSios => 'แ‡ฑ', HangulJamo::HangulJongseongYesieungDashPansios => 'แ‡ฒ', HangulJamo::HangulJongseongPhieuphDashPieup => 'แ‡ณ', HangulJamo::HangulJongseongKapyeounphieuph => 'แ‡ด', HangulJamo::HangulJongseongHieuhDashNieun => 'แ‡ต', HangulJamo::HangulJongseongHieuhDashRieul => 'แ‡ถ', HangulJamo::HangulJongseongHieuhDashMieum => 'แ‡ท', HangulJamo::HangulJongseongHieuhDashPieup => 'แ‡ธ', HangulJamo::HangulJongseongYeorinhieuh => 'แ‡น', HangulJamo::HangulJongseongKiyeokDashNieun => 'แ‡บ', HangulJamo::HangulJongseongKiyeokDashPieup => 'แ‡ป', HangulJamo::HangulJongseongKiyeokDashChieuch => 'แ‡ผ', HangulJamo::HangulJongseongKiyeokDashKhieukh => 'แ‡ฝ', HangulJamo::HangulJongseongKiyeokDashHieuh => 'แ‡พ', } } } impl std::convert::TryFrom<char> for HangulJamo { type Error = (); fn try_from(c: char) -> Result<Self, Self::Error> { match c { 'แ„€' => Ok(HangulJamo::HangulChoseongKiyeok), 'แ„' => Ok(HangulJamo::HangulChoseongSsangkiyeok), 'แ„‚' => Ok(HangulJamo::HangulChoseongNieun), 'แ„ƒ' => Ok(HangulJamo::HangulChoseongTikeut), 'แ„„' => Ok(HangulJamo::HangulChoseongSsangtikeut), 'แ„…' => Ok(HangulJamo::HangulChoseongRieul), 'แ„†' => Ok(HangulJamo::HangulChoseongMieum), 'แ„‡' => Ok(HangulJamo::HangulChoseongPieup), 'แ„ˆ' => Ok(HangulJamo::HangulChoseongSsangpieup), 'แ„‰' => Ok(HangulJamo::HangulChoseongSios), 'แ„Š' => Ok(HangulJamo::HangulChoseongSsangsios), 'แ„‹' => Ok(HangulJamo::HangulChoseongIeung), 'แ„Œ' => Ok(HangulJamo::HangulChoseongCieuc), 'แ„' => Ok(HangulJamo::HangulChoseongSsangcieuc), 'แ„Ž' => Ok(HangulJamo::HangulChoseongChieuch), 'แ„' => Ok(HangulJamo::HangulChoseongKhieukh), 'แ„' => Ok(HangulJamo::HangulChoseongThieuth), 'แ„‘' => Ok(HangulJamo::HangulChoseongPhieuph), 'แ„’' => Ok(HangulJamo::HangulChoseongHieuh), 'แ„“' => Ok(HangulJamo::HangulChoseongNieunDashKiyeok), 'แ„”' => Ok(HangulJamo::HangulChoseongSsangnieun), 'แ„•' => Ok(HangulJamo::HangulChoseongNieunDashTikeut), 'แ„–' => Ok(HangulJamo::HangulChoseongNieunDashPieup), 'แ„—' => Ok(HangulJamo::HangulChoseongTikeutDashKiyeok), 'แ„˜' => Ok(HangulJamo::HangulChoseongRieulDashNieun), 'แ„™' => Ok(HangulJamo::HangulChoseongSsangrieul), 'แ„š' => Ok(HangulJamo::HangulChoseongRieulDashHieuh), 'แ„›' => Ok(HangulJamo::HangulChoseongKapyeounrieul), 'แ„œ' => Ok(HangulJamo::HangulChoseongMieumDashPieup), 'แ„' => Ok(HangulJamo::HangulChoseongKapyeounmieum), 'แ„ž' => Ok(HangulJamo::HangulChoseongPieupDashKiyeok), 'แ„Ÿ' => Ok(HangulJamo::HangulChoseongPieupDashNieun), 'แ„ ' => Ok(HangulJamo::HangulChoseongPieupDashTikeut), 'แ„ก' => Ok(HangulJamo::HangulChoseongPieupDashSios), 'แ„ข' => Ok(HangulJamo::HangulChoseongPieupDashSiosDashKiyeok), 'แ„ฃ' => Ok(HangulJamo::HangulChoseongPieupDashSiosDashTikeut), 'แ„ค' => Ok(HangulJamo::HangulChoseongPieupDashSiosDashPieup), 'แ„ฅ' => Ok(HangulJamo::HangulChoseongPieupDashSsangsios), 'แ„ฆ' => Ok(HangulJamo::HangulChoseongPieupDashSiosDashCieuc), 'แ„ง' => Ok(HangulJamo::HangulChoseongPieupDashCieuc), 'แ„จ' => Ok(HangulJamo::HangulChoseongPieupDashChieuch), 'แ„ฉ' => Ok(HangulJamo::HangulChoseongPieupDashThieuth), 'แ„ช' => Ok(HangulJamo::HangulChoseongPieupDashPhieuph), 'แ„ซ' => Ok(HangulJamo::HangulChoseongKapyeounpieup), 'แ„ฌ' => Ok(HangulJamo::HangulChoseongKapyeounssangpieup), 'แ„ญ' => Ok(HangulJamo::HangulChoseongSiosDashKiyeok), 'แ„ฎ' => Ok(HangulJamo::HangulChoseongSiosDashNieun), 'แ„ฏ' => Ok(HangulJamo::HangulChoseongSiosDashTikeut), 'แ„ฐ' => Ok(HangulJamo::HangulChoseongSiosDashRieul), 'แ„ฑ' => Ok(HangulJamo::HangulChoseongSiosDashMieum), 'แ„ฒ' => Ok(HangulJamo::HangulChoseongSiosDashPieup), 'แ„ณ' => Ok(HangulJamo::HangulChoseongSiosDashPieupDashKiyeok), 'แ„ด' => Ok(HangulJamo::HangulChoseongSiosDashSsangsios), 'แ„ต' => Ok(HangulJamo::HangulChoseongSiosDashIeung), 'แ„ถ' => Ok(HangulJamo::HangulChoseongSiosDashCieuc), 'แ„ท' => Ok(HangulJamo::HangulChoseongSiosDashChieuch), 'แ„ธ' => Ok(HangulJamo::HangulChoseongSiosDashKhieukh), 'แ„น' => Ok(HangulJamo::HangulChoseongSiosDashThieuth), 'แ„บ' => Ok(HangulJamo::HangulChoseongSiosDashPhieuph), 'แ„ป' => Ok(HangulJamo::HangulChoseongSiosDashHieuh), 'แ„ผ' => Ok(HangulJamo::HangulChoseongChitueumsios), 'แ„ฝ' => Ok(HangulJamo::HangulChoseongChitueumssangsios), 'แ„พ' => Ok(HangulJamo::HangulChoseongCeongchieumsios), 'แ„ฟ' => Ok(HangulJamo::HangulChoseongCeongchieumssangsios), 'แ…€' => Ok(HangulJamo::HangulChoseongPansios), 'แ…' => Ok(HangulJamo::HangulChoseongIeungDashKiyeok), 'แ…‚' => Ok(HangulJamo::HangulChoseongIeungDashTikeut), 'แ…ƒ' => Ok(HangulJamo::HangulChoseongIeungDashMieum), 'แ…„' => Ok(HangulJamo::HangulChoseongIeungDashPieup), 'แ……' => Ok(HangulJamo::HangulChoseongIeungDashSios), 'แ…†' => Ok(HangulJamo::HangulChoseongIeungDashPansios), 'แ…‡' => Ok(HangulJamo::HangulChoseongSsangieung), 'แ…ˆ' => Ok(HangulJamo::HangulChoseongIeungDashCieuc), 'แ…‰' => Ok(HangulJamo::HangulChoseongIeungDashChieuch), 'แ…Š' => Ok(HangulJamo::HangulChoseongIeungDashThieuth), 'แ…‹' => Ok(HangulJamo::HangulChoseongIeungDashPhieuph), 'แ…Œ' => Ok(HangulJamo::HangulChoseongYesieung), 'แ…' => Ok(HangulJamo::HangulChoseongCieucDashIeung), 'แ…Ž' => Ok(HangulJamo::HangulChoseongChitueumcieuc), 'แ…' => Ok(HangulJamo::HangulChoseongChitueumssangcieuc), 'แ…' => Ok(HangulJamo::HangulChoseongCeongchieumcieuc), 'แ…‘' => Ok(HangulJamo::HangulChoseongCeongchieumssangcieuc), 'แ…’' => Ok(HangulJamo::HangulChoseongChieuchDashKhieukh), 'แ…“' => Ok(HangulJamo::HangulChoseongChieuchDashHieuh), 'แ…”' => Ok(HangulJamo::HangulChoseongChitueumchieuch), 'แ…•' => Ok(HangulJamo::HangulChoseongCeongchieumchieuch), 'แ…–' => Ok(HangulJamo::HangulChoseongPhieuphDashPieup), 'แ…—' => Ok(HangulJamo::HangulChoseongKapyeounphieuph), 'แ…˜' => Ok(HangulJamo::HangulChoseongSsanghieuh), 'แ…™' => Ok(HangulJamo::HangulChoseongYeorinhieuh), 'แ…š' => Ok(HangulJamo::HangulChoseongKiyeokDashTikeut), 'แ…›' => Ok(HangulJamo::HangulChoseongNieunDashSios), 'แ…œ' => Ok(HangulJamo::HangulChoseongNieunDashCieuc), 'แ…' => Ok(HangulJamo::HangulChoseongNieunDashHieuh), 'แ…ž' => Ok(HangulJamo::HangulChoseongTikeutDashRieul), 'แ…Ÿ' => Ok(HangulJamo::HangulChoseongFiller), 'แ… ' => Ok(HangulJamo::HangulJungseongFiller), 'แ…ก' => Ok(HangulJamo::HangulJungseongA), 'แ…ข' => Ok(HangulJamo::HangulJungseongAe), 'แ…ฃ' => Ok(HangulJamo::HangulJungseongYa), 'แ…ค' => Ok(HangulJamo::HangulJungseongYae), 'แ…ฅ' => Ok(HangulJamo::HangulJungseongEo), 'แ…ฆ' => Ok(HangulJamo::HangulJungseongE), 'แ…ง' => Ok(HangulJamo::HangulJungseongYeo), 'แ…จ' => Ok(HangulJamo::HangulJungseongYe), 'แ…ฉ' => Ok(HangulJamo::HangulJungseongO), 'แ…ช' => Ok(HangulJamo::HangulJungseongWa), 'แ…ซ' => Ok(HangulJamo::HangulJungseongWae), 'แ…ฌ' => Ok(HangulJamo::HangulJungseongOe), 'แ…ญ' => Ok(HangulJamo::HangulJungseongYo), 'แ…ฎ' => Ok(HangulJamo::HangulJungseongU), 'แ…ฏ' => Ok(HangulJamo::HangulJungseongWeo), 'แ…ฐ' => Ok(HangulJamo::HangulJungseongWe), 'แ…ฑ' => Ok(HangulJamo::HangulJungseongWi), 'แ…ฒ' => Ok(HangulJamo::HangulJungseongYu), 'แ…ณ' => Ok(HangulJamo::HangulJungseongEu), 'แ…ด' => Ok(HangulJamo::HangulJungseongYi), 'แ…ต' => Ok(HangulJamo::HangulJungseongI), 'แ…ถ' => Ok(HangulJamo::HangulJungseongADashO), 'แ…ท' => Ok(HangulJamo::HangulJungseongADashU), 'แ…ธ' => Ok(HangulJamo::HangulJungseongYaDashO), 'แ…น' => Ok(HangulJamo::HangulJungseongYaDashYo), 'แ…บ' => Ok(HangulJamo::HangulJungseongEoDashO), 'แ…ป' => Ok(HangulJamo::HangulJungseongEoDashU), 'แ…ผ' => Ok(HangulJamo::HangulJungseongEoDashEu), 'แ…ฝ' => Ok(HangulJamo::HangulJungseongYeoDashO), 'แ…พ' => Ok(HangulJamo::HangulJungseongYeoDashU), 'แ…ฟ' => Ok(HangulJamo::HangulJungseongODashEo), 'แ†€' => Ok(HangulJamo::HangulJungseongODashE), 'แ†' => Ok(HangulJamo::HangulJungseongODashYe), 'แ†‚' => Ok(HangulJamo::HangulJungseongODashO), 'แ†ƒ' => Ok(HangulJamo::HangulJungseongODashU), 'แ†„' => Ok(HangulJamo::HangulJungseongYoDashYa), 'แ†…' => Ok(HangulJamo::HangulJungseongYoDashYae), 'แ††' => Ok(HangulJamo::HangulJungseongYoDashYeo), 'แ†‡' => Ok(HangulJamo::HangulJungseongYoDashO), 'แ†ˆ' => Ok(HangulJamo::HangulJungseongYoDashI), 'แ†‰' => Ok(HangulJamo::HangulJungseongUDashA), 'แ†Š' => Ok(HangulJamo::HangulJungseongUDashAe), 'แ†‹' => Ok(HangulJamo::HangulJungseongUDashEoDashEu), 'แ†Œ' => Ok(HangulJamo::HangulJungseongUDashYe), 'แ†' => Ok(HangulJamo::HangulJungseongUDashU), 'แ†Ž' => Ok(HangulJamo::HangulJungseongYuDashA), 'แ†' => Ok(HangulJamo::HangulJungseongYuDashEo), 'แ†' => Ok(HangulJamo::HangulJungseongYuDashE), 'แ†‘' => Ok(HangulJamo::HangulJungseongYuDashYeo), 'แ†’' => Ok(HangulJamo::HangulJungseongYuDashYe), 'แ†“' => Ok(HangulJamo::HangulJungseongYuDashU), 'แ†”' => Ok(HangulJamo::HangulJungseongYuDashI), 'แ†•' => Ok(HangulJamo::HangulJungseongEuDashU), 'แ†–' => Ok(HangulJamo::HangulJungseongEuDashEu), 'แ†—' => Ok(HangulJamo::HangulJungseongYiDashU), 'แ†˜' => Ok(HangulJamo::HangulJungseongIDashA), 'แ†™' => Ok(HangulJamo::HangulJungseongIDashYa), 'แ†š' => Ok(HangulJamo::HangulJungseongIDashO), 'แ†›' => Ok(HangulJamo::HangulJungseongIDashU), 'แ†œ' => Ok(HangulJamo::HangulJungseongIDashEu), 'แ†' => Ok(HangulJamo::HangulJungseongIDashAraea), 'แ†ž' => Ok(HangulJamo::HangulJungseongAraea), 'แ†Ÿ' => Ok(HangulJamo::HangulJungseongAraeaDashEo), 'แ† ' => Ok(HangulJamo::HangulJungseongAraeaDashU), 'แ†ก' => Ok(HangulJamo::HangulJungseongAraeaDashI), 'แ†ข' => Ok(HangulJamo::HangulJungseongSsangaraea), 'แ†ฃ' => Ok(HangulJamo::HangulJungseongADashEu), 'แ†ค' => Ok(HangulJamo::HangulJungseongYaDashU), 'แ†ฅ' => Ok(HangulJamo::HangulJungseongYeoDashYa), 'แ†ฆ' => Ok(HangulJamo::HangulJungseongODashYa), 'แ†ง' => Ok(HangulJamo::HangulJungseongODashYae), 'แ†จ' => Ok(HangulJamo::HangulJongseongKiyeok), 'แ†ฉ' => Ok(HangulJamo::HangulJongseongSsangkiyeok), 'แ†ช' => Ok(HangulJamo::HangulJongseongKiyeokDashSios), 'แ†ซ' => Ok(HangulJamo::HangulJongseongNieun), 'แ†ฌ' => Ok(HangulJamo::HangulJongseongNieunDashCieuc), 'แ†ญ' => Ok(HangulJamo::HangulJongseongNieunDashHieuh), 'แ†ฎ' => Ok(HangulJamo::HangulJongseongTikeut), 'แ†ฏ' => Ok(HangulJamo::HangulJongseongRieul), 'แ†ฐ' => Ok(HangulJamo::HangulJongseongRieulDashKiyeok), 'แ†ฑ' => Ok(HangulJamo::HangulJongseongRieulDashMieum), 'แ†ฒ' => Ok(HangulJamo::HangulJongseongRieulDashPieup), 'แ†ณ' => Ok(HangulJamo::HangulJongseongRieulDashSios), 'แ†ด' => Ok(HangulJamo::HangulJongseongRieulDashThieuth), 'แ†ต' => Ok(HangulJamo::HangulJongseongRieulDashPhieuph), 'แ†ถ' => Ok(HangulJamo::HangulJongseongRieulDashHieuh), 'แ†ท' => Ok(HangulJamo::HangulJongseongMieum), 'แ†ธ' => Ok(HangulJamo::HangulJongseongPieup), 'แ†น' => Ok(HangulJamo::HangulJongseongPieupDashSios), 'แ†บ' => Ok(HangulJamo::HangulJongseongSios), 'แ†ป' => Ok(HangulJamo::HangulJongseongSsangsios), 'แ†ผ' => Ok(HangulJamo::HangulJongseongIeung), 'แ†ฝ' => Ok(HangulJamo::HangulJongseongCieuc), 'แ†พ' => Ok(HangulJamo::HangulJongseongChieuch), 'แ†ฟ' => Ok(HangulJamo::HangulJongseongKhieukh), 'แ‡€' => Ok(HangulJamo::HangulJongseongThieuth), 'แ‡' => Ok(HangulJamo::HangulJongseongPhieuph), 'แ‡‚' => Ok(HangulJamo::HangulJongseongHieuh), 'แ‡ƒ' => Ok(HangulJamo::HangulJongseongKiyeokDashRieul), 'แ‡„' => Ok(HangulJamo::HangulJongseongKiyeokDashSiosDashKiyeok), 'แ‡…' => Ok(HangulJamo::HangulJongseongNieunDashKiyeok), 'แ‡†' => Ok(HangulJamo::HangulJongseongNieunDashTikeut), 'แ‡‡' => Ok(HangulJamo::HangulJongseongNieunDashSios), 'แ‡ˆ' => Ok(HangulJamo::HangulJongseongNieunDashPansios), 'แ‡‰' => Ok(HangulJamo::HangulJongseongNieunDashThieuth), 'แ‡Š' => Ok(HangulJamo::HangulJongseongTikeutDashKiyeok), 'แ‡‹' => Ok(HangulJamo::HangulJongseongTikeutDashRieul), 'แ‡Œ' => Ok(HangulJamo::HangulJongseongRieulDashKiyeokDashSios), 'แ‡' => Ok(HangulJamo::HangulJongseongRieulDashNieun), 'แ‡Ž' => Ok(HangulJamo::HangulJongseongRieulDashTikeut), 'แ‡' => Ok(HangulJamo::HangulJongseongRieulDashTikeutDashHieuh), 'แ‡' => Ok(HangulJamo::HangulJongseongSsangrieul), 'แ‡‘' => Ok(HangulJamo::HangulJongseongRieulDashMieumDashKiyeok), 'แ‡’' => Ok(HangulJamo::HangulJongseongRieulDashMieumDashSios), 'แ‡“' => Ok(HangulJamo::HangulJongseongRieulDashPieupDashSios), 'แ‡”' => Ok(HangulJamo::HangulJongseongRieulDashPieupDashHieuh), 'แ‡•' => Ok(HangulJamo::HangulJongseongRieulDashKapyeounpieup), 'แ‡–' => Ok(HangulJamo::HangulJongseongRieulDashSsangsios), 'แ‡—' => Ok(HangulJamo::HangulJongseongRieulDashPansios), 'แ‡˜' => Ok(HangulJamo::HangulJongseongRieulDashKhieukh), 'แ‡™' => Ok(HangulJamo::HangulJongseongRieulDashYeorinhieuh), 'แ‡š' => Ok(HangulJamo::HangulJongseongMieumDashKiyeok), 'แ‡›' => Ok(HangulJamo::HangulJongseongMieumDashRieul), 'แ‡œ' => Ok(HangulJamo::HangulJongseongMieumDashPieup), 'แ‡' => Ok(HangulJamo::HangulJongseongMieumDashSios), 'แ‡ž' => Ok(HangulJamo::HangulJongseongMieumDashSsangsios), 'แ‡Ÿ' => Ok(HangulJamo::HangulJongseongMieumDashPansios), 'แ‡ ' => Ok(HangulJamo::HangulJongseongMieumDashChieuch), 'แ‡ก' => Ok(HangulJamo::HangulJongseongMieumDashHieuh), 'แ‡ข' => Ok(HangulJamo::HangulJongseongKapyeounmieum), 'แ‡ฃ' => Ok(HangulJamo::HangulJongseongPieupDashRieul), 'แ‡ค' => Ok(HangulJamo::HangulJongseongPieupDashPhieuph), 'แ‡ฅ' => Ok(HangulJamo::HangulJongseongPieupDashHieuh), 'แ‡ฆ' => Ok(HangulJamo::HangulJongseongKapyeounpieup), 'แ‡ง' => Ok(HangulJamo::HangulJongseongSiosDashKiyeok), 'แ‡จ' => Ok(HangulJamo::HangulJongseongSiosDashTikeut), 'แ‡ฉ' => Ok(HangulJamo::HangulJongseongSiosDashRieul), 'แ‡ช' => Ok(HangulJamo::HangulJongseongSiosDashPieup), 'แ‡ซ' => Ok(HangulJamo::HangulJongseongPansios), 'แ‡ฌ' => Ok(HangulJamo::HangulJongseongIeungDashKiyeok), 'แ‡ญ' => Ok(HangulJamo::HangulJongseongIeungDashSsangkiyeok), 'แ‡ฎ' => Ok(HangulJamo::HangulJongseongSsangieung), 'แ‡ฏ' => Ok(HangulJamo::HangulJongseongIeungDashKhieukh), 'แ‡ฐ' => Ok(HangulJamo::HangulJongseongYesieung), 'แ‡ฑ' => Ok(HangulJamo::HangulJongseongYesieungDashSios), 'แ‡ฒ' => Ok(HangulJamo::HangulJongseongYesieungDashPansios), 'แ‡ณ' => Ok(HangulJamo::HangulJongseongPhieuphDashPieup), 'แ‡ด' => Ok(HangulJamo::HangulJongseongKapyeounphieuph), 'แ‡ต' => Ok(HangulJamo::HangulJongseongHieuhDashNieun), 'แ‡ถ' => Ok(HangulJamo::HangulJongseongHieuhDashRieul), 'แ‡ท' => Ok(HangulJamo::HangulJongseongHieuhDashMieum), 'แ‡ธ' => Ok(HangulJamo::HangulJongseongHieuhDashPieup), 'แ‡น' => Ok(HangulJamo::HangulJongseongYeorinhieuh), 'แ‡บ' => Ok(HangulJamo::HangulJongseongKiyeokDashNieun), 'แ‡ป' => Ok(HangulJamo::HangulJongseongKiyeokDashPieup), 'แ‡ผ' => Ok(HangulJamo::HangulJongseongKiyeokDashChieuch), 'แ‡ฝ' => Ok(HangulJamo::HangulJongseongKiyeokDashKhieukh), 'แ‡พ' => Ok(HangulJamo::HangulJongseongKiyeokDashHieuh), _ => Err(()), } } } impl Into<u32> for HangulJamo { fn into(self) -> u32 { let c: char = self.into(); let hex = c .escape_unicode() .to_string() .replace("\\u{", "") .replace("}", ""); u32::from_str_radix(&hex, 16).unwrap() } } impl std::convert::TryFrom<u32> for HangulJamo { type Error = (); fn try_from(u: u32) -> Result<Self, Self::Error> { if let Ok(c) = char::try_from(u) { Self::try_from(c) } else { Err(()) } } } impl Iterator for HangulJamo { type Item = Self; fn next(&mut self) -> Option<Self> { let index: u32 = (*self).into(); use std::convert::TryFrom; Self::try_from(index + 1).ok() } } impl HangulJamo { /// The character with the lowest index in this unicode block pub fn new() -> Self { HangulJamo::HangulChoseongKiyeok } /// The character's name, in sentence case pub fn name(&self) -> String { let s = std::format!("HangulJamo{:#?}", self); string_morph::to_sentence_case(&s) } }
use std::io; fn main() { // ํŒจํ„ด ๋งค์นญ์„ ใ…… ใ…์šฉํ•˜๊ธฐ let mut buffer = String::new(); match io::stdin().read_line(& mut buffer) { Ok(count) => { println!("#################"); println!("{}", buffer); println!(" {} bytes read using pattern maching", count); println!("#################"); }, Err(error) => println!("error: {}", error), } // unwrap ์‚ฌ์šฉ let mut buffer = String::new(); let count: usize = io::stdin().read_line(& mut buffer).unwrap(); println!("#################"); println!("{}", buffer); println!(" {} bytes read using unwrap", count); println!("#################"); }
#[doc = "Register `PWR_WKUPCR` reader"] pub type R = crate::R<PWR_WKUPCR_SPEC>; #[doc = "Register `PWR_WKUPCR` writer"] pub type W = crate::W<PWR_WKUPCR_SPEC>; #[doc = "Field `WKUPC1` reader - WKUPC1"] pub type WKUPC1_R = crate::BitReader; #[doc = "Field `WKUPC1` writer - WKUPC1"] pub type WKUPC1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `WKUPC2` reader - WKUPC2"] pub type WKUPC2_R = crate::BitReader; #[doc = "Field `WKUPC2` writer - WKUPC2"] pub type WKUPC2_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `WKUPC3` reader - WKUPC3"] pub type WKUPC3_R = crate::BitReader; #[doc = "Field `WKUPC3` writer - WKUPC3"] pub type WKUPC3_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `WKUPC4` reader - WKUPC4"] pub type WKUPC4_R = crate::BitReader; #[doc = "Field `WKUPC4` writer - WKUPC4"] pub type WKUPC4_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `WKUPC5` reader - WKUPC5"] pub type WKUPC5_R = crate::BitReader; #[doc = "Field `WKUPC5` writer - WKUPC5"] pub type WKUPC5_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `WKUPC6` reader - WKUPC6"] pub type WKUPC6_R = crate::BitReader; #[doc = "Field `WKUPC6` writer - WKUPC6"] pub type WKUPC6_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `WKUPP1` reader - WKUPP1"] pub type WKUPP1_R = crate::BitReader; #[doc = "Field `WKUPP1` writer - WKUPP1"] pub type WKUPP1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `WKUPP2` reader - WKUPP2"] pub type WKUPP2_R = crate::BitReader; #[doc = "Field `WKUPP2` writer - WKUPP2"] pub type WKUPP2_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `WKUPP3` reader - WKUPP3"] pub type WKUPP3_R = crate::BitReader; #[doc = "Field `WKUPP3` writer - WKUPP3"] pub type WKUPP3_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `WKUPP4` reader - WKUPP4"] pub type WKUPP4_R = crate::BitReader; #[doc = "Field `WKUPP4` writer - WKUPP4"] pub type WKUPP4_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `WKUPP5` reader - WKUPP5"] pub type WKUPP5_R = crate::BitReader; #[doc = "Field `WKUPP5` writer - WKUPP5"] pub type WKUPP5_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `WKUPP6` reader - WKUPP6"] pub type WKUPP6_R = crate::BitReader; #[doc = "Field `WKUPP6` writer - WKUPP6"] pub type WKUPP6_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `WKUPPUPD1` reader - WKUPPUPD1"] pub type WKUPPUPD1_R = crate::FieldReader; #[doc = "Field `WKUPPUPD1` writer - WKUPPUPD1"] pub type WKUPPUPD1_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `WKUPPUPD2` reader - WKUPPUPD2"] pub type WKUPPUPD2_R = crate::FieldReader; #[doc = "Field `WKUPPUPD2` writer - WKUPPUPD2"] pub type WKUPPUPD2_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `WKUPPUPD3` reader - WKUPPUPD3"] pub type WKUPPUPD3_R = crate::FieldReader; #[doc = "Field `WKUPPUPD3` writer - WKUPPUPD3"] pub type WKUPPUPD3_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `WKUPPUPD4` reader - WKUPPUPD4"] pub type WKUPPUPD4_R = crate::FieldReader; #[doc = "Field `WKUPPUPD4` writer - WKUPPUPD4"] pub type WKUPPUPD4_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `WKUPPUPD5` reader - WKUPPUPD5"] pub type WKUPPUPD5_R = crate::FieldReader; #[doc = "Field `WKUPPUPD5` writer - WKUPPUPD5"] pub type WKUPPUPD5_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `WKUPPUPD6` reader - WKUPPUPD6"] pub type WKUPPUPD6_R = crate::FieldReader; #[doc = "Field `WKUPPUPD6` writer - WKUPPUPD6"] pub type WKUPPUPD6_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; impl R { #[doc = "Bit 0 - WKUPC1"] #[inline(always)] pub fn wkupc1(&self) -> WKUPC1_R { WKUPC1_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - WKUPC2"] #[inline(always)] pub fn wkupc2(&self) -> WKUPC2_R { WKUPC2_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - WKUPC3"] #[inline(always)] pub fn wkupc3(&self) -> WKUPC3_R { WKUPC3_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - WKUPC4"] #[inline(always)] pub fn wkupc4(&self) -> WKUPC4_R { WKUPC4_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - WKUPC5"] #[inline(always)] pub fn wkupc5(&self) -> WKUPC5_R { WKUPC5_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - WKUPC6"] #[inline(always)] pub fn wkupc6(&self) -> WKUPC6_R { WKUPC6_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 8 - WKUPP1"] #[inline(always)] pub fn wkupp1(&self) -> WKUPP1_R { WKUPP1_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - WKUPP2"] #[inline(always)] pub fn wkupp2(&self) -> WKUPP2_R { WKUPP2_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 10 - WKUPP3"] #[inline(always)] pub fn wkupp3(&self) -> WKUPP3_R { WKUPP3_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bit 11 - WKUPP4"] #[inline(always)] pub fn wkupp4(&self) -> WKUPP4_R { WKUPP4_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 12 - WKUPP5"] #[inline(always)] pub fn wkupp5(&self) -> WKUPP5_R { WKUPP5_R::new(((self.bits >> 12) & 1) != 0) } #[doc = "Bit 13 - WKUPP6"] #[inline(always)] pub fn wkupp6(&self) -> WKUPP6_R { WKUPP6_R::new(((self.bits >> 13) & 1) != 0) } #[doc = "Bits 16:17 - WKUPPUPD1"] #[inline(always)] pub fn wkuppupd1(&self) -> WKUPPUPD1_R { WKUPPUPD1_R::new(((self.bits >> 16) & 3) as u8) } #[doc = "Bits 18:19 - WKUPPUPD2"] #[inline(always)] pub fn wkuppupd2(&self) -> WKUPPUPD2_R { WKUPPUPD2_R::new(((self.bits >> 18) & 3) as u8) } #[doc = "Bits 20:21 - WKUPPUPD3"] #[inline(always)] pub fn wkuppupd3(&self) -> WKUPPUPD3_R { WKUPPUPD3_R::new(((self.bits >> 20) & 3) as u8) } #[doc = "Bits 22:23 - WKUPPUPD4"] #[inline(always)] pub fn wkuppupd4(&self) -> WKUPPUPD4_R { WKUPPUPD4_R::new(((self.bits >> 22) & 3) as u8) } #[doc = "Bits 24:25 - WKUPPUPD5"] #[inline(always)] pub fn wkuppupd5(&self) -> WKUPPUPD5_R { WKUPPUPD5_R::new(((self.bits >> 24) & 3) as u8) } #[doc = "Bits 26:27 - WKUPPUPD6"] #[inline(always)] pub fn wkuppupd6(&self) -> WKUPPUPD6_R { WKUPPUPD6_R::new(((self.bits >> 26) & 3) as u8) } } impl W { #[doc = "Bit 0 - WKUPC1"] #[inline(always)] #[must_use] pub fn wkupc1(&mut self) -> WKUPC1_W<PWR_WKUPCR_SPEC, 0> { WKUPC1_W::new(self) } #[doc = "Bit 1 - WKUPC2"] #[inline(always)] #[must_use] pub fn wkupc2(&mut self) -> WKUPC2_W<PWR_WKUPCR_SPEC, 1> { WKUPC2_W::new(self) } #[doc = "Bit 2 - WKUPC3"] #[inline(always)] #[must_use] pub fn wkupc3(&mut self) -> WKUPC3_W<PWR_WKUPCR_SPEC, 2> { WKUPC3_W::new(self) } #[doc = "Bit 3 - WKUPC4"] #[inline(always)] #[must_use] pub fn wkupc4(&mut self) -> WKUPC4_W<PWR_WKUPCR_SPEC, 3> { WKUPC4_W::new(self) } #[doc = "Bit 4 - WKUPC5"] #[inline(always)] #[must_use] pub fn wkupc5(&mut self) -> WKUPC5_W<PWR_WKUPCR_SPEC, 4> { WKUPC5_W::new(self) } #[doc = "Bit 5 - WKUPC6"] #[inline(always)] #[must_use] pub fn wkupc6(&mut self) -> WKUPC6_W<PWR_WKUPCR_SPEC, 5> { WKUPC6_W::new(self) } #[doc = "Bit 8 - WKUPP1"] #[inline(always)] #[must_use] pub fn wkupp1(&mut self) -> WKUPP1_W<PWR_WKUPCR_SPEC, 8> { WKUPP1_W::new(self) } #[doc = "Bit 9 - WKUPP2"] #[inline(always)] #[must_use] pub fn wkupp2(&mut self) -> WKUPP2_W<PWR_WKUPCR_SPEC, 9> { WKUPP2_W::new(self) } #[doc = "Bit 10 - WKUPP3"] #[inline(always)] #[must_use] pub fn wkupp3(&mut self) -> WKUPP3_W<PWR_WKUPCR_SPEC, 10> { WKUPP3_W::new(self) } #[doc = "Bit 11 - WKUPP4"] #[inline(always)] #[must_use] pub fn wkupp4(&mut self) -> WKUPP4_W<PWR_WKUPCR_SPEC, 11> { WKUPP4_W::new(self) } #[doc = "Bit 12 - WKUPP5"] #[inline(always)] #[must_use] pub fn wkupp5(&mut self) -> WKUPP5_W<PWR_WKUPCR_SPEC, 12> { WKUPP5_W::new(self) } #[doc = "Bit 13 - WKUPP6"] #[inline(always)] #[must_use] pub fn wkupp6(&mut self) -> WKUPP6_W<PWR_WKUPCR_SPEC, 13> { WKUPP6_W::new(self) } #[doc = "Bits 16:17 - WKUPPUPD1"] #[inline(always)] #[must_use] pub fn wkuppupd1(&mut self) -> WKUPPUPD1_W<PWR_WKUPCR_SPEC, 16> { WKUPPUPD1_W::new(self) } #[doc = "Bits 18:19 - WKUPPUPD2"] #[inline(always)] #[must_use] pub fn wkuppupd2(&mut self) -> WKUPPUPD2_W<PWR_WKUPCR_SPEC, 18> { WKUPPUPD2_W::new(self) } #[doc = "Bits 20:21 - WKUPPUPD3"] #[inline(always)] #[must_use] pub fn wkuppupd3(&mut self) -> WKUPPUPD3_W<PWR_WKUPCR_SPEC, 20> { WKUPPUPD3_W::new(self) } #[doc = "Bits 22:23 - WKUPPUPD4"] #[inline(always)] #[must_use] pub fn wkuppupd4(&mut self) -> WKUPPUPD4_W<PWR_WKUPCR_SPEC, 22> { WKUPPUPD4_W::new(self) } #[doc = "Bits 24:25 - WKUPPUPD5"] #[inline(always)] #[must_use] pub fn wkuppupd5(&mut self) -> WKUPPUPD5_W<PWR_WKUPCR_SPEC, 24> { WKUPPUPD5_W::new(self) } #[doc = "Bits 26:27 - WKUPPUPD6"] #[inline(always)] #[must_use] pub fn wkuppupd6(&mut self) -> WKUPPUPD6_W<PWR_WKUPCR_SPEC, 26> { WKUPPUPD6_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "Not reset by wakeup from Standby mode, but by any application reset (such as NRST, IWDG). Access 6 wait states when writing this register (when clearing a WKUPF, the AHB write access completes after the WKUPF has cleared). This register provides Write access security when enabled by TZEN register bit in Section10: Reset and clock control (RCC). When security is enabled a non-secure write access on individual WKUPC\\[6:1\\], WKUPP\\[6:1\\] bits and WKUPPUPD\\[6:1\\] bit pairs are discarded when the corresponding WKUPEN\\[6:1\\] bit in PWR MPU wakeup enable register (PWR_MPUWKUPENR) is set. No bus error is generated. Secure and non-secure read accesses are granted and return the register value. When a system reset occurs during the register write cycle the written data is not guaranteed.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`pwr_wkupcr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`pwr_wkupcr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct PWR_WKUPCR_SPEC; impl crate::RegisterSpec for PWR_WKUPCR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`pwr_wkupcr::R`](R) reader structure"] impl crate::Readable for PWR_WKUPCR_SPEC {} #[doc = "`write(|w| ..)` method takes [`pwr_wkupcr::W`](W) writer structure"] impl crate::Writable for PWR_WKUPCR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets PWR_WKUPCR to value 0"] impl crate::Resettable for PWR_WKUPCR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use crate::RrtRay::Ray; use crate::RrtVec3; use crate::RrtVec3::Vec3; #[derive(Copy, Clone)] pub struct hit_record { pub p : Vec3, pub normal : Vec3, pub t : f64, pub front_face : bool, } impl hit_record { pub fn new() -> hit_record { hit_record{ p : Vec3::new([0.0, 0.0, 0.0]), normal : Vec3::new([0.0, 0.0, 0.0]), t : 0.0, front_face : false } } pub fn set_face_normal(mut self, ray : Ray, outward_normal : Vec3) { self.front_face = RrtVec3::dot(ray.direction(), outward_normal) < 0.0; self.normal = if self.front_face { outward_normal } else { -outward_normal }; } } pub trait Hittable { fn hit(&self, ray : Ray, t_min : f64, t_max : f64, rec : hit_record) -> bool; }
mod benmark; extern crate chashmap; extern crate itertools; extern crate rayon; extern crate reqwest; use std::io::Read; use std::path::PathBuf; use error_chain::error_chain; use itertools::Itertools; use rayon::iter::*; use std::fs::File; use std::io::copy; error_chain! { foreign_links { Io(std::io::Error); HttpRequest(reqwest::Error); } } pub fn ontime_rank(filename: &str) -> Vec<(String, f64)> { let mut fi = File::open(filename).unwrap(); let mut infor = String::new(); fi.read_to_string(&mut infor).ok(); let ttt: Vec<&str> = infor.lines().skip(1).collect(); let perform: Vec<(String, i64)> = ttt.par_iter().map(|line| helper(line.to_string())).collect(); let information = perform.into_iter().into_group_map(); let numValue: Vec<(&str, f64)> = information.par_iter().map(|airline| checkTime(airline.0, airline.1)).collect(); return sorted(numValue).par_iter().map(|airline| (airline.0.to_string(), airline.1)).collect(); } fn mix<'a>(x: Vec<(&'a str, f64)>, y: Vec<(&'a str, f64)>) -> Vec<(&'a str, f64)> { let mut vec = Vec::new(); let (mut ttt, mut rrr) = (x.as_slice(), y.as_slice()); while !(ttt.is_empty() || rrr.is_empty()) { if ttt[0].1 > rrr[0].1 { vec.push(rrr[0].clone()); rrr = &rrr[1..]; } else { vec.push(ttt[0].clone()); ttt = &ttt[1..]; } } if !ttt.is_empty() { vec.extend(ttt); } else { vec.extend(rrr); } return vec; } fn helper(input: String) -> (String, i64) { let value: Vec<&str> = input[..75].split(',').take(15).collect(); let duration = match value[14].trim().parse::<i64>() { Ok(val) => val, Err(_err) => 0i64, }; return (String::from(value[8].trim()), duration); } fn sorted(xs: Vec<(&str, f64)>) -> Vec<(&str, f64)> { return xs.par_iter().cloned().map(|val| vec![val]) .reduce(|| vec![], |ttt, rrr| mix(ttt, rrr)); } fn checkTime<'a>(airline: &'a str, xs: &'a Vec<i64>) -> (&'a str, f64) { let length = xs.len() as i64; let ttt: i64 = xs.to_vec().par_iter().map(|state| if state.clone() > 0 { 0 } else { 1 }).reduce(|| 0, |a, b| a + b); return (airline.clone(), (ttt as f64 / length as f64) * 100f64); } async fn download(path: PathBuf) -> Result<()> { let destination = "https://cs.muic.mahidol.ac.th/~ktangwon/2008.csv.zip"; let result = reqwest::get(destination).await?; let mut place = { let filename = result.url().path_segments().and_then(|segments| segments.last()).and_then(|name| if name.is_empty() { None } else { Some(name) }).unwrap_or("tmp.bin"); println!("Can't download file: '{}'", filename); let name = path.join(filename); println!("File is at: {:?}", name); File::create(name)? }; let bab = result.bytes().await?; copy(&mut bab.as_ref(), &mut place)?; Ok(()) } fn unzip(path: &mut PathBuf) -> zip::result::ZipResult<()> { let mut location = File::open(path.join("2008.csv.zip"))?; let mut buff = Vec::new(); location.read_to_end(&mut buff)?; let mut zipped = zip::ZipArchive::new(location)?; let mut filecsv = zipped.by_index(0)?; println!("Unzipping: {:?}", filecsv.name()); let mut csv_place = File::create(path.join("2008.csv"))?; copy(&mut filecsv, &mut csv_place)?; Ok(()) } #[tokio::main] async fn main() -> Result<()> { let mut buff = PathBuf::from(env!("CARGO_MANIFEST_DIR")); buff.push("resources/data/"); let path = buff.clone(); match download(path.clone()).await { Ok(_) => println!("Download Success"), Err(err) => println!("Download failed: {:?}", err), }; match unzip(&mut path.clone()) { Ok(_) => println!("Unzipped Successfully"), Err(err) => println!("Error unzipping file: {:?}", err), }; buff.push("2008.csv"); let file_csv = buff.clone().into_os_string().into_string().ok(); let csv_string = file_csv.as_deref().unwrap_or(""); let last = ontime_rank(&csv_string); for airline in last { println!("Airline: {:?}, Percentage: {:?} %", airline.0, airline.1); } Ok(()) }
use crate::model::{company::CompanyResponse, intraday_prices::PricesResponse}; use anyhow::Result; use log::debug; use reqwest::{header::HeaderMap, Client, Method}; use serde::{de::DeserializeOwned, Serialize}; const BASE_URL: &'static str = "https://cloud.iexapis.com/stable"; pub struct ApiClient { base_url: String, api_token: String, http_client: Client, } #[derive(Debug, Serialize)] struct IexCloudResponseHeaders { iexcloud_messages_used: usize, iexcloud_credits_used: usize, iexcloud_premium_message_used: usize, iexcloud_premium_credits_used: usize, } impl From<HeaderMap> for IexCloudResponseHeaders { fn from(header: HeaderMap) -> Self { Self { iexcloud_messages_used: header.get("iexcloud-messages-used").map_or(0, |value| { value .to_str() .map_or(0, |data| data.to_string().parse().unwrap_or(0)) }), iexcloud_credits_used: header.get("iexcloud-credits-used").map_or(0, |value| { value .to_str() .map_or(0, |data| data.to_string().parse().unwrap_or(0)) }), iexcloud_premium_message_used: header.get("iexcloud-premium-messages-used").map_or( 0, |value| { value .to_str() .map_or(0, |data| data.to_string().parse().unwrap_or(0)) }, ), iexcloud_premium_credits_used: header.get("iexcloud-premium-credits-used").map_or( 0, |value| { value .to_str() .map_or(0, |data| data.to_string().parse().unwrap_or(0)) }, ), } } } impl ApiClient { /// Creates a new API client. pub fn new(api_token: String) -> Self { Self { base_url: BASE_URL.to_string(), api_token, http_client: Client::new(), } } /// Executes the actual HTTP request. async fn execute_request<T>(&self, method: reqwest::Method, url: String) -> Result<T> where T: DeserializeOwned, { let response = self .http_client .request(method.clone(), &url) .query(&[("token", &self.api_token)]) .send() .await?; let iex_headers = IexCloudResponseHeaders::from(response.headers().clone()); let json_body: serde_json::Value = response.json().await?; debug!( "Response data for request {} {} are: IEX Headers: {}; JSON Body: {}", method.as_str(), &url, &serde_json::to_string(&iex_headers)?, &serde_json::to_string(&json_body)? ); Ok(serde_json::from_value(json_body)?) } /// Fetches Company information for the specified symbol. /// Docs are here: https://iexcloud.io/docs/api/#company. pub async fn get_company(&self, symbol: &String) -> Result<CompanyResponse> { let url = format!("{}/stock/{}/company", self.base_url, symbol); Ok(self.execute_request(Method::GET, url).await?) } /// Fetches current intraday prices. /// Docs are here: https://iexcloud.io/docs/api/#intraday-prices. pub async fn get_intraday_prices(&self, symbol: &String) -> Result<PricesResponse> { let url = format!("{}/stock/{}/intraday-prices", self.base_url, symbol); Ok(self.execute_request(Method::GET, url).await?) } /// Fetches historical intraday prices for the specified date. /// Docs are here: https://iexcloud.io/docs/api/#historical-prices. pub async fn get_historical_prices( &self, symbol: &String, date: String, ) -> Result<PricesResponse> { let url = format!("{}/stock/{}/chart/date/{}", self.base_url, symbol, date); Ok(self.execute_request(Method::GET, url).await?) } }
/* * Datadog API V1 Collection * * Collection of all Datadog Public endpoints. * * The version of the OpenAPI document: 1.0 * Contact: support@datadoghq.com * Generated by: https://openapi-generator.tech */ /// TagToHosts : In this object, the key is the tag, the value is a list of host names that are reporting that tag. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TagToHosts { /// A list of tags to apply to the host. #[serde(rename = "tags", skip_serializing_if = "Option::is_none")] pub tags: Option<::std::collections::HashMap<String, Vec<String>>>, } impl TagToHosts { /// In this object, the key is the tag, the value is a list of host names that are reporting that tag. pub fn new() -> TagToHosts { TagToHosts { tags: None, } } }
const INPUT: usize = 990941; const INPUT_SLICED: [u8; 6] = [9, 9, 0, 9, 4, 1]; pub fn solve() { let mut recipes = Vec::with_capacity(INPUT + 12); recipes.extend_from_slice(&[3_u8, 7]); let mut elves = (0, 1); loop { let score = recipes[elves.0] + recipes[elves.1]; if score >= 10 { recipes.push(1); } recipes.push(score % 10); elves.0 = (elves.0 + recipes[elves.0] as usize + 1) % recipes.len(); elves.1 = (elves.1 + recipes[elves.1] as usize + 1) % recipes.len(); if recipes.len() >= INPUT + 10 { break; } } println!("{:?}", &recipes[INPUT..(INPUT + 10)]); } pub fn solve_extra() { let mut recipes = Vec::with_capacity(INPUT + 12); recipes.extend_from_slice(&[3_u8, 7]); let mut elves = (0, 1); let off_by_one = loop { let score = recipes[elves.0] + recipes[elves.1]; if score >= 10 { recipes.push(1); } recipes.push(score % 10); elves.0 = (elves.0 + recipes[elves.0] as usize + 1) % recipes.len(); elves.1 = (elves.1 + recipes[elves.1] as usize + 1) % recipes.len(); if score >= 10 { let start = if (recipes.len() - 1) < INPUT_SLICED.len() { 0 } else { recipes.len() - INPUT_SLICED.len() - 1 }; let end = if start + INPUT_SLICED.len() >= recipes.len() { recipes.len() } else { start + INPUT_SLICED.len() }; if recipes[start..end] == INPUT_SLICED { break true; } } else { let start = if recipes.len() < INPUT_SLICED.len() { 0 } else { recipes.len() - INPUT_SLICED.len() }; if recipes[start..] == INPUT_SLICED { break false; } } }; if off_by_one { println!("{:?}", recipes.len() - INPUT_SLICED.len() - 1); } else { println!("{:?}", recipes.len() - INPUT_SLICED.len()); } }
use std::str; use header::{RequestHeader, ResponseHeader, parse_value, serialize_value, parse_list0, serialize_list}; use header::item::Url; use Method; header!{ /// `From` header, [RFC7231 Section 5.5.1] pub struct From(String); (RequestHeader); NAME = "From"; SENSITIVE = false; parse(s, _base) { parse_value::<String>(s).map(Into::into) } serialize(self, iter) { serialize_value(iter, &self.0) } } header!{ /// `Referer` header, [RFC7231 Section 5.5.2] pub struct Referer(Url); (RequestHeader); NAME = "Referer"; SENSITIVE = false; parse(s, _base) { parse_value::<Url>(s).map(Into::into) } serialize(self, iter) { serialize_value(iter, &self.0) } } header!{ /// `User-Agent` header, [RFC7231 Section 5.5.3] /// /// The value is decoded as UTF-8. Invalid bytes are replaced /// with U+FFFD REPLACEMENT CHARACTER. pub struct UserAgent(String); (RequestHeader); NAME = "User-Agent"; SENSITIVE = false; parse(s, _base) { parse_value::<String>(s).map(Into::into) } serialize(self, iter) { serialize_value(iter, &self.0) } } header!{ /// `Allow` header, [RFC7231 Section 7.4.1] pub struct Allow(Vec<Method>); (ResponseHeader); NAME = "Allow"; SENSITIVE = false; parse(s, _base) { parse_list0::<Method>(s).map(Into::into) } serialize(self, iter) { serialize_list(iter, &self.0) } } header!{ /// `Server` header, [RFC7231 Section 7.4.2] /// /// The value is decoded as UTF-8. Invalid bytes are replaced /// with U+FFFD REPLACEMENT CHARACTER. pub struct Server(String); (ResponseHeader); NAME = "SERVER"; SENSITIVE = false; parse(s, _base) { parse_value::<String>(s).map(Into::into) } serialize(self, iter) { serialize_value(iter, &self.0) } }
use pretty_assertions::assert_eq; use sudo_test::{Command, Env, TextFile}; use crate::{Result, SUDOERS_USER_ALL_NOPASSWD, USERNAME}; #[test] fn user_can_read_file_owned_by_root() -> Result<()> { let expected = "hello"; let path = "/root/file"; let env = Env(SUDOERS_USER_ALL_NOPASSWD) .user(USERNAME) .file(path, expected) .build()?; let actual = Command::new("sudo") .args(["cat", path]) .as_user(USERNAME) .output(&env)? .stdout()?; assert_eq!(expected, actual); Ok(()) } #[test] fn user_can_write_file_owned_by_root() -> Result<()> { let path = "/root/file"; let env = Env(SUDOERS_USER_ALL_NOPASSWD) .user(USERNAME) .file(path, "") .build()?; Command::new("sudo") .args(["rm", path]) .as_user(USERNAME) .output(&env)? .assert_success() } #[test] fn user_can_execute_file_owned_by_root() -> Result<()> { let path = "/root/file"; let env = Env(SUDOERS_USER_ALL_NOPASSWD) .user(USERNAME) .file( path, TextFile( r#"#!/bin/sh exit 0"#, ) .chmod("100"), ) .build()?; Command::new("sudo") .arg(path) .as_user(USERNAME) .output(&env)? .assert_success() }
extern crate nell; use nell::ffi::route::rtmsg; use nell::sys::{Message, Cursor}; use std::net::{IpAddr, Ipv4Addr}; pub struct Route { pub sock_fd: i32, pub msg_cur: Cursor, pub bytes: Vec<u8>, } impl Route { pub fn new() -> Route { let sock_fd = unsafe { libc::socket(libc::AF_NETLINK, libc::SOCK_DGRAM, nell::sys::Family::Route as libc::c_int) }; Route { sock_fd: sock_fd, msg_cur: Cursor::default(), bytes: vec![0x24, 0x00, 0x00, 0x00, 0x1a, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x08, 0x00, 0x01, 0x00, 0x08, 0x08, 0x08, 0x08], } } pub fn lookup(&mut self, dst: &Ipv4Addr) -> Option<IpAddr> { let mut buf = [0u8; 1024]; self.bytes[32..].copy_from_slice(&dst.octets()); let rtmsg = unsafe { libc::write(self.sock_fd, self.bytes.as_ptr() as *const _, self.bytes.len()); let len = libc::read(self.sock_fd, buf.as_mut_ptr() as *mut _, buf.len()); self.msg_cur.reset(buf.as_mut_ptr(), len as usize); match self.msg_cur.next::<Message<rtmsg>>() { Some(msg) => msg.get(), None => Ok(nell::Netlink::None), } }; if let Ok(nell::sys::Netlink::Msg(msg)) = rtmsg { if let Ok(msg) = nell::api::route(msg) { return msg.gateway } }; None } }
use rendy::{ factory::{Config, Factory}, }; use winit::{ EventsLoop, WindowBuilder, }; #[cfg(feature = "dx12")] type Backend = rendy::dx12::Backend; #[cfg(feature = "metal")] type Backend = rendy::metal::Backend; #[cfg(feature = "vulkan")] type Backend = rendy::vulkan::Backend; #[cfg(any(feature = "dx12", feature = "metal", feature = "vulkan"))] fn main() { env_logger::Builder::from_default_env() .filter_level(log::LevelFilter::Info) .filter_module("init", log::LevelFilter::Trace) .init(); let config: Config = Default::default(); let mut factory: Factory<Backend> = Factory::new(config).unwrap(); factory.dispose(); } #[cfg(not(any(feature = "dx12", feature = "metal", feature = "vulkan")))] fn main() { panic!("Specify feature: { dx12, metal, vulkan }"); }
use std::ops; use crate::{Outcome, Player}; #[derive(PartialEq, Clone, Copy, Debug)] pub struct Direction(i8, i8); const HORIZONTAL: Direction = Direction(1, 0); const VERTICAL: Direction = Direction(0, 1); const FORWARD_DIAGONAL: Direction = Direction(1, 1); const BACKWARD_DIAGONAL: Direction = Direction(-1, 1); pub const ALL_DIRECTIONS: [Direction; 4] = [HORIZONTAL, VERTICAL, FORWARD_DIAGONAL, BACKWARD_DIAGONAL]; #[derive(PartialEq, Clone, Copy, Debug)] pub struct Location(u32, u32); impl ops::Add<Direction> for Location { type Output = Result<Location, &'static str>; fn add(self, rhs: Direction) -> Self::Output { if self.0 == 0 && rhs.0 < 0 { return Err("already at first column"); } else if self.1 == 0 && rhs.1 < 0 { return Err("already at first row"); } else { Ok(Location( (self.0 as i64 + rhs.0 as i64) as u32, (self.1 as i64 + rhs.1 as i64) as u32, )) } } } impl ops::Sub<Direction> for Location { type Output = Result<Location, &'static str>; fn sub(self, rhs: Direction) -> Self::Output { if self.0 == 0 && rhs.0 > 0 { return Err("already at first column"); } else if self.1 == 0 && rhs.1 > 0 { return Err("already at first row"); } else { Ok(Location( (self.0 as i64 - rhs.0 as i64) as u32, (self.1 as i64 - rhs.1 as i64) as u32, )) } } } pub struct Grid { values: Vec<Vec<Player>>, max_height: usize, } impl Grid { pub fn with_dimensions(width: usize, height: usize) -> Grid { Grid { values: vec![Vec::with_capacity(height); width], max_height: height, } } pub fn at(&self, loc: Location) -> Option<&Player> { if let Some(col) = self.values.get(loc.0 as usize) { col.get(loc.1 as usize) } else { None } } pub fn is_full(&self) -> bool { self.values.iter().all(|col| col.len() == self.max_height) } pub fn insert_piece(&mut self, player: Player, column: u32) -> Result<Location, Outcome> { let col = match self.values.get_mut(column as usize) { Some(col) => col, None => return Err(Outcome::IllegalColumn), }; let length = col.len(); if length >= self.max_height { return Err(Outcome::IllegalRow); } col.push(player); Ok(Location(column, length as u32)) } pub fn get_streak(&self, start: Location, direction: Direction) -> u32 { let player = match self.at(start) { Some(player) => player, None => return 0, }; let mut streak: u32 = 1; let mut position = start; while let Ok(pos) = position + direction { position = pos; if let Some(new_player) = self.at(pos) { if new_player == player { streak += 1 } else { break; } } else { break; } } position = start; while let Ok(pos) = position - direction { position = pos; if let Some(new_player) = self.at(pos) { if new_player == player { streak += 1; } else { break; } } else { break; } } streak } } #[cfg(test)] mod tests { use super::*; #[test] fn add_direction() { let location = Location(1, 2); let direction = Direction(1, -1); assert_eq!(location + direction, Ok(Location(2, 1))); } #[test] fn add_direction_column_error() { let location = Location(0, 0); let direction = Direction(-1, 0); assert_eq!(location + direction, Err("already at first column")); } #[test] fn add_direction_row_error() { let location = Location(0, 0); let direction = Direction(0, -1); assert_eq!(location + direction, Err("already at first row")); } #[test] fn sub_direction() { let location = Location(1, 2); let direction = Direction(1, -1); assert_eq!(location - direction, Ok(Location(0, 3))); } #[test] fn sub_direction_column_error() { let location = Location(0, 0); let direction = Direction(1, 0); assert_eq!(location - direction, Err("already at first column")); } #[test] fn sub_direction_row_error() { let location = Location(0, 0); let direction = Direction(0, 1); assert_eq!(location - direction, Err("already at first row")); } #[test] fn grid_full() { let mut grid = Grid::with_dimensions(2, 2); assert!(grid.insert_piece(1, 0).is_ok()); assert!(grid.insert_piece(1, 0).is_ok()); assert!(grid.insert_piece(1, 1).is_ok()); assert!(grid.insert_piece(1, 1).is_ok()); assert!(grid.is_full()); } #[test] fn inserting_bad_column() { let mut grid = Grid::with_dimensions(2, 2); let result = grid.insert_piece(1, 23).err(); assert_eq!(result, Some(Outcome::IllegalColumn)); } #[test] fn inserting_bad_row() { let mut grid = Grid::with_dimensions(2, 2); assert!(grid.insert_piece(1, 0).is_ok()); assert!(grid.insert_piece(1, 0).is_ok()); let result = grid.insert_piece(1, 0).err(); assert_eq!(result, Some(Outcome::IllegalRow)); } }
use super::*; #[derive(Clone, Debug, Default, PartialEq)] /// Container for [`Peptide`] sequences and their quantified ratios /// /// Allows constant-time lookup by amino-acid sequence pub struct Protein { pub accession: String, pub description: String, pub peptides: Vec<Peptide>, /// Constant-time indexing into peptides array - do we even need the Vec? /// /// Should look into average length of peptide Vec to determine /// if the extra memory usage here is worth the speedup. pub map: HashMap<Residue, usize>, } impl Protein { pub fn new(accession: String, description: String) -> Protein { Protein { accession, description, peptides: Vec::new(), map: HashMap::new(), } } /// Return a [`HashMap`] mapping peptide sequences to a [`Peptide`] struct pub fn as_map(&self) -> HashMap<&str, &Peptide> { self.peptides .iter() .map(|pep| (pep.sequence.as_ref(), pep)) .collect() } /// Add a ratio for a given peptide sequence to the [`Protein`] /// /// If the protein already contains a peptide with the same sequence as /// the peptide being added, the new ratio will be appended to /// the existing peptide match's ratios. pub fn add_ratio(&mut self, residue: Residue, seq: &str, ratio: Option<f32>, ms2: usize) { match self.map.get(&residue) { Some(idx) => { self.peptides[*idx].ratios.push(ratio); self.peptides[*idx].ms2 += ms2; // if self.peptides[*idx].ms2 == 0 { // dbg!(&self.peptides[*idx]); // } } None => { let idx = self.peptides.len(); self.peptides.push(Peptide { sequence: seq.into(), residue: residue, ms2, ratios: vec![ratio], }); self.map.insert(residue, idx); } } } pub fn collapse_redundant_sites(&mut self) { let mut count: HashMap<String, Vec<_>> = HashMap::new(); for (idx, p) in self.peptides.iter().enumerate() { count .entry(p.sequence.replace('*', "")) .or_insert_with(Vec::new) .push((idx, p.residue)); } for (_, mut indices) in count { indices.sort_by(|a, b| a.1.cmp(&b.1)); if indices.len() > 1 { let (keep, resi) = indices.pop().unwrap(); // let resi = self.peptides[keep].residue; for (remove_idx, _) in indices { let mut removed: Peptide = std::mem::replace(&mut self.peptides[remove_idx], Peptide::default()); removed.residue = resi; self.add_peptide(removed); } } } // Final step, remove the default peptide that we inserted to keep // indices in place, and then remake our hashmap let def = Peptide::default(); self.peptides = self.peptides.drain(..).filter(|p| *p != def).collect(); self.map = self .peptides .iter() .enumerate() .map(|(idx, pep)| (pep.residue, idx)) .collect(); } /// Add a new [`Peptide`] struct to the [`Protein`] /// /// If the protein already contains a peptide with the same sequence as /// the peptide being added, the new peptide's ratios will be appended to /// the existing peptide match's ratios. pub fn add_peptide(&mut self, peptide: Peptide) { match self.map.get(&peptide.residue) { Some(idx) => { self.peptides[*idx].ratios.extend(peptide.ratios); self.peptides[*idx].ms2 += peptide.ms2; } None => { let idx = self.peptides.len(); self.map.insert(peptide.residue, idx); self.peptides.push(peptide); } } } pub fn get(&self, residue: Residue) -> Option<&Peptide> { self.peptides.get(*self.map.get(&residue)?) } pub fn get_mut(&mut self, residue: Residue) -> Option<&mut Peptide> { self.peptides.get_mut(*self.map.get(&residue)?) } /// Similar to a [`HashMap`]'s `Entry`, return mutable reference to /// existing peptide, or create a new peptide entry for the sequence and /// return a mutable reference to it // pub fn get_or_insert(&mut self, residue: Residue) -> &mut Peptide { // match self.map.get(&residue) { // Some(idx) => &mut self.peptides[*idx], // None => { // let idx = self.peptides.len(); // self.peptides.push(Peptide { // sequence: seq.into(), // residue: None, // ms2: 1, // ratios: Vec::new(), // }); // self.map.insert(seq.into(), idx); // &mut self.peptides[idx] // } // } // } pub fn median_ratio(&self) -> Option<f32> { let medians = self .peptides .iter() .map(Peptide::median_ratio) .collect::<Vec<Option<f32>>>(); let mock = Peptide { sequence: String::default(), residue: 0, ms2: 0, ratios: medians, }; mock.median_ratio() } pub fn spectral_counts(&self) -> usize { self.peptides.iter().fold(0, |acc, x| { acc + x.ratios.iter().filter(|r| r.is_some()).count() }) } } impl FromIterator<Peptide> for Protein { fn from_iter<I: IntoIterator<Item = Peptide>>(iter: I) -> Self { let mut protein = Protein::default(); for peptide in iter { protein.add_peptide(peptide); } protein } } #[cfg(test)] mod test { use super::*; #[test] fn add_ratios() { let mut prot = Protein::default(); macro_rules! add { ($s:expr, $site:expr, $f:expr) => { prot.add_ratio($site, $s.into(), Some($f), 0) }; } add!("MRL", 0, 1.); add!("MRL", 0, 2.); add!("MRL", 0, 3.); add!("MEHQLL", 1, 20.0); assert_eq!(prot.peptides.len(), 2); assert_eq!( prot.get(0).unwrap().ratios, vec![Some(1.), Some(2.), Some(3.)] ); assert_eq!(prot.get(1).unwrap().ratios, vec![Some(20.0)]); assert_eq!(prot.spectral_counts(), 4); } #[test] fn removed_redundant_sites() { let mut prot = Protein::default(); macro_rules! add { ($s:expr, $site:expr, $f:expr) => { prot.add_ratio($site, $s.into(), Some($f), 0) }; } add!("K.LQFGSQPQVYNDFLDIMKEFK*SQSIDTPGVISR.V", 155, 1.); add!("K.LQFGSQPQVYNDFLDIMKEFK*SQSIDTPGVISR.V", 155, 5.); add!("K.LQFGSQPQVYNDFLDIMKEFK*SQSIDTPGVISR.V", 152, 2.); add!("K.LQFGSQPQVYNDFLDIMKEFK*SQSIDTPGVISR.V", 152, 3.5); add!("R.LK*VEDALSYLDQVK.L", 122, 20.0); assert_eq!(prot.peptides.len(), 3); assert_eq!(prot.get(152).unwrap().ratios, vec![Some(2.), Some(3.5)]); prot.collapse_redundant_sites(); assert_eq!(prot.peptides.len(), 2); assert_eq!( prot.get(152).unwrap().ratios, vec![Some(2.), Some(3.5), Some(1.), Some(5.)] ); assert_eq!(prot.get(155), None); } }
use gtk::prelude::*; use gio::prelude::*; use gtk::{ ScrolledWindow, TextView, Adjustment, MenuItem, MenuBar, Menu }; use std::env; fn main() { if gtk::init().is_err() { println!("Failed to initialize GTK"); return; } let uiapp = gtk::Application::new(Some("org.gtkrsnotes.demo"), gio::ApplicationFlags::FLAGS_NONE) .expect("Application::new failed"); uiapp.connect_activate(|app| { new_window(app).show_all(); }); uiapp.run(&env::args().collect::<Vec<_>>()); } fn editor_new() -> ScrolledWindow { let scr_win = ScrolledWindow::new::<Adjustment, Adjustment>(gtk::NONE_ADJUSTMENT, gtk::NONE_ADJUSTMENT); let txt_view = TextView::new(); scr_win.add(&txt_view); scr_win } fn new_window<T: IsA<gtk::Application>>(app: &T) -> gtk::ApplicationWindow { let win = gtk::ApplicationWindow::new(app); win.set_default_size(320, 320); win.set_title("Basic example"); win.add(&new_vbox()); win } fn new_menubar() -> MenuBar { let menu = MenuBar::new(); menu.append(&new_file_menu()); menu } fn new_vbox() -> gtk::Box { let ret = gtk::Box::new(gtk::Orientation::Vertical, 10); ret.pack_start(&new_menubar(), false, false, 0); ret.pack_start(&editor_new(), false, true, 0); ret } fn new_file_menu() -> MenuItem { let menu_item = MenuItem::new_with_label("File"); menu_item }
use crate::CXFederatedPlan; use connectorx::fed_rewriter::Plan; use libc::c_char; use std::convert::Into; use std::ffi::CString; impl Into<CXFederatedPlan> for Plan { fn into(self) -> CXFederatedPlan { CXFederatedPlan { db_name: CString::new(self.db_name.as_str()) .expect("new CString error") .into_raw() as *const c_char, db_alias: CString::new(self.db_alias.as_str()) .expect("new CString error") .into_raw() as *const c_char, sql: CString::new(self.sql.as_str()) .expect("new CString error") .into_raw() as *const c_char, cardinality: self.cardinality, } } }
pub mod forest; pub mod handle;
//! Low-level reading of the Header foudn in PAC files. use crate::error::PacError; use crate::Result; use ez_io::{ReadE, WriteE}; use std::io::{Read, Write}; /// Direct representation of the data found in the header #[derive(Clone)] pub struct PacHeader { pub magic_number: [u8; 8], // 'DW_PACK\0' pub file_pos: u32, // Always 0 pub file_cnt: u32, pub status: u32, // Always 0 } impl PacHeader { /// Reads the data from a Read object pub fn import<R: Read>(reader: &mut R) -> Result<PacHeader> { Ok(PacHeader { magic_number: { let mut magic_number = [0u8; 8]; reader.read_exact(&mut magic_number)?; if magic_number != [b'D', b'W', b'_', b'P', b'A', b'C', b'K', 0] { return Err(PacError::MagicNumber); } magic_number }, file_pos: reader.read_le_to_u32()?, file_cnt: reader.read_le_to_u32()?, status: reader.read_le_to_u32()?, }) } /// Writes the data to a Write object pub fn export<W: Write>(&self, writer: &mut W) -> Result<()> { writer.write_all(&self.magic_number)?; writer.write_le_to_u32(self.file_pos)?; writer.write_le_to_u32(self.file_cnt)?; writer.write_le_to_u32(self.status)?; Ok(()) } }
pub fn run(){ greeting("Hello", "Ali Hamza"); // In Rust we can bind the funtion value to variable let add_number = add(12, 12); println!("The sum is {}", add_number); // Closure let get_nums = |n1: i32, n2: i32| n1 + n2; println!("Get sum {}", get_nums(5, 5)); } fn greeting(greet: &str, name: &str){ println!("{} {}, Nie to meet you ", greet, name); } fn add(n1 : i32, n2: i32) -> i32 { n1 + n2 }
use crate::{ codegen::{ builder::{branch, core}, AatbeModule, CompileError, ValueTypePair, }, fmt::AatbeFmt, ty::LLVMTyInCtx, }; use parser::ast::{Expression, LoopType, PrimitiveType}; use llvm_sys_wrapper::Phi; impl AatbeModule { pub fn codegen_if(&mut self, if_expr: &Expression) -> Option<ValueTypePair> { match if_expr { Expression::If { cond_expr, then_expr, else_expr, is_expr, } => { let then_bb = self.basic_block("then".to_string()); let else_bb = if let Some(_) = else_expr { Some(self.basic_block("else".to_string())) } else { None }; let end_bb = self.basic_block("end".to_string()); self.start_scope(); let cond = self.codegen_expr(cond_expr)?; if *cond.prim().inner() != PrimitiveType::Bool { self.add_error(CompileError::ExpectedType { expected_ty: PrimitiveType::Bool.fmt(), found_ty: cond.prim().fmt(), value: cond_expr.fmt(), }); } branch::cond_branch(self, *cond, then_bb, else_bb.unwrap_or(end_bb)); core::pos_at_end(self, then_bb); let then_val = self.codegen_expr(then_expr); self.exit_scope(); let else_val = if let Some(bb) = else_bb { branch::branch(self, end_bb); core::pos_at_end(self, bb); if let Some(else_expr) = else_expr { self.codegen_expr(&*else_expr) } else { unreachable!() } } else { None }; if !self.has_ret(then_expr) { branch::branch(self, end_bb); } core::pos_at_end(self, end_bb); if !is_expr { return None; } if let Some(then_val) = then_val { let ty = then_val.prim().clone(); if ty != PrimitiveType::Unit { if else_val.is_some() { let phi = Phi::new( self.llvm_builder_ref().as_ref(), ty.llvm_ty_in_ctx(self), "", ); phi.add_incoming(*then_val, then_bb); if let Some(else_val) = else_val { if &ty != else_val.prim() { self.add_error(CompileError::ExpectedType { expected_ty: ty.clone().fmt(), found_ty: else_val.prim().fmt(), value: else_expr.as_ref().unwrap().fmt(), }); } phi.add_incoming(*else_val, else_bb.unwrap()); } Some((phi.as_ref(), ty).into()) } else { Some((*then_val, ty).into()) } } else { None } } else { None } } _ => unreachable!(), } } pub fn codegen_basic_loop(&mut self, basic_loop: &Expression) -> Option<ValueTypePair> { match basic_loop { Expression::Loop { loop_type, cond_expr, body, } => { let cond_bb = self.basic_block(String::default()); let body_bb = self.basic_block(String::default()); let end_bb = self.basic_block(String::default()); branch::branch(self, cond_bb); core::pos_at_end(self, cond_bb); let cond = self.codegen_expr(cond_expr)?; if *cond.prim().inner() != PrimitiveType::Bool { self.add_error(CompileError::ExpectedType { expected_ty: PrimitiveType::Bool.fmt(), found_ty: cond.prim().fmt(), value: cond_expr.fmt(), }); }; match loop_type { LoopType::While => branch::cond_branch(self, *cond, body_bb, end_bb), LoopType::Until => branch::cond_branch(self, *cond, end_bb, body_bb), }; core::pos_at_end(self, body_bb); self.codegen_expr(body); branch::branch(self, cond_bb); core::pos_at_end(self, end_bb); None } _ => unreachable!(), } } }
/* * Datadog API V1 Collection * * Collection of all Datadog Public endpoints. * * The version of the OpenAPI document: 1.0 * Contact: support@datadoghq.com * Generated by: https://openapi-generator.tech */ /// LogsListRequest : Object to send with the request to retrieve a list of logs from your Organization. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct LogsListRequest { /// The log index on which the request is performed. For multi-index organizations, the default is all live indexes. Historical indexes of rehydrated logs must be specified. #[serde(rename = "index", skip_serializing_if = "Option::is_none")] pub index: Option<String>, /// Number of logs return in the response. #[serde(rename = "limit", skip_serializing_if = "Option::is_none")] pub limit: Option<i32>, /// The search query - following the log search syntax. #[serde(rename = "query", skip_serializing_if = "Option::is_none")] pub query: Option<String>, #[serde(rename = "sort", skip_serializing_if = "Option::is_none")] pub sort: Option<crate::models::LogsSort>, /// Hash identifier of the first log to return in the list, available in a log `id` attribute. This parameter is used for the pagination feature. **Note**: This parameter is ignored if the corresponding log is out of the scope of the specified time window. #[serde(rename = "startAt", skip_serializing_if = "Option::is_none")] pub start_at: Option<String>, #[serde(rename = "time")] pub time: Box<crate::models::LogsListRequestTime>, } impl LogsListRequest { /// Object to send with the request to retrieve a list of logs from your Organization. pub fn new(time: crate::models::LogsListRequestTime) -> LogsListRequest { LogsListRequest { index: None, limit: None, query: None, sort: None, start_at: None, time: Box::new(time), } } }
//! # Gps distance //! Calculate the distance between two points given the longitude, latitude and altitude. //! //! ## Vincenty formula //! This implimentation of this problem will use Vincenty's formula. While more complex and slower //! than other methods, it is more accurate. For details see //! //! Work out the distance between two points on the sphere. Then, with pythagoras, work out the //! absolute distance. use super::Coordinate; /// # Inverse vincenty /// Breaks down for antipodal points. /// /// (Vincenty wiki)[https://en.wikipedia.org/wiki/Vincenty%27s_formulae] pub fn inverse_vincenty(start: &Coordinate, end: &Coordinate) -> f64 { #![allow(non_snake_case, non_upper_case_globals)] let max_iter = 200; const a: f64 = 6378137_f64; // length radius at equator const f: f64 = 1_f64 / 298.257223563; // flattening of the ellipsoid const b: f64 = (1_f64 - f) * a; // radius at the poles - 6356752.314245 meters in WGS-84 let U1: f64 = ((1_f64 - f) * start.latitude.unwrap().to_radians().tan() as f64).atan(); // Reduced latitude (latitude on the auxiliary sphere) let U2: f64 = ((1_f64 - f) * end.latitude.unwrap().to_radians().tan() as f64).atan(); let L: f64 = (end.longitude.unwrap().to_radians() - start.longitude.unwrap().to_radians()) as f64; let sinU1 = U1.sin(); let cosU1 = U1.cos(); let sinU2 = U2.sin(); let cosU2 = U2.cos(); let mut Y: f64 = L; // Should be ฮป, let mut counter = 0; let (cos_sq_alpha, sin_sigma, cos_2_sigma_m, cos_sigma, sigma) = loop { let sinY = Y.sin(); let cosY = Y.cos(); let sin_sigma = ((cosU2 * sinY).powi(2) + ((cosU1 * sinU2) - (sinU1 * cosU2 * cosY)).powi(2) ).sqrt(); if sin_sigma == 0_f64 { // The points are the same so 0 distance. return 0_f64; } let cos_sigma = sinU1 * sinU2 + cosU1 * cosU2 * cosY; let sigma = sin_sigma.atan2(cos_sigma); let sin_alpha = (cosU1 * cosU2 * sinY) / (sin_sigma); let cos_sq_alpha = 1_f64 - sin_alpha.powi(2); let cos_2_sigma_m = cos_sigma - ((2_f64 * sinU1 * sinU2) / cos_sq_alpha); let C = f / 16_f64 * cos_sq_alpha * (4_f64 + f * (4_f64 - 3.0 * cos_sq_alpha)); let prev_Y = Y; Y = &L + (1_f64 - C) * f * sin_alpha * (sigma + C * sin_sigma * (cos_2_sigma_m + C * cos_sigma * (-1_f64 + 2_f64 * cos_2_sigma_m.powi(2)))); if Y - prev_Y < 1e-12 { break (cos_sq_alpha, sin_sigma, cos_2_sigma_m, cos_sigma, sigma); } else if counter > max_iter { break (cos_sq_alpha, sin_sigma, cos_2_sigma_m, cos_sigma, sigma); } else { counter += 1; } }; let uSq = cos_sq_alpha * ((a.powi(2) - b.powi(2)) / b.powi(2)); let A = 1_f64 + uSq / 16382_f64 * (4096_f64 + uSq * (-768_f64 + uSq * (320_f64 - 175_f64 * uSq))); let B = uSq / 1024_f64 * (256_f64 + uSq * (-128_f64 + uSq * (74_f64 - 47_f64 * uSq))); let delta_sigma = B * sin_sigma * (cos_2_sigma_m + B / 4_f64 * (cos_sigma * (-1_f64 + 2_f64 * cos_2_sigma_m.powi(2)) - B / 6_f64 * cos_2_sigma_m * (-3_f64 + 4_f64 * sin_sigma.powi(2)) * (-3_f64 + 4_f64 * cos_2_sigma_m.powi(2)))); let s = b * A * (sigma - delta_sigma); return s; } /// # Haversine /// Less accurate than vincenty as it assumes that the earth is a perfect sphere, /// but less computationally expensive. /// /// (Haversine wiki) [https://en.wikipedia.org/wiki/Haversine_formula] pub fn haversine(start: &Coordinate, end: &Coordinate) -> f64 { let lat1 = start.latitude.unwrap().to_radians() as f64; let lat2 = end.latitude.unwrap().to_radians() as f64; let long1 = start.longitude.unwrap().to_radians() as f64; let long2 = end.longitude.unwrap().to_radians() as f64; let mean_earth_radius = 6371008.8; // https://en.wikipedia.org/wiki/Earth_radius#Global_average_radii let havlat = ((lat2 - lat1) / 2_f64).sin().powi(2); let havlong = ((long2 - long1) / 2_f64).sin().powi(2); let distance = ((havlat + lat1.cos() * lat2.cos() * havlong).sqrt()).asin() * 2_f64 * mean_earth_radius; return distance; } pub trait DeltaCoordinates { fn vincenty(&self) -> Vec<(f64, f64)>; fn haversine(&self) -> Vec<(f64, f64)>; } impl DeltaCoordinates for Vec<Coordinate> { fn vincenty(&self) -> Vec<(f64, f64)> { let mut return_vec: Vec<(f64, f64)> = Vec::new(); for t in 0..self.len() - 1 { let time_diff = self.get(t+1).unwrap().utc - self.get(t).unwrap().utc; let mut d = inverse_vincenty(self.get(t).unwrap(), self.get(t + 1).unwrap()); d = (d.powi(2) + (self.get(t).unwrap().altitude.unwrap() - self.get(t + 1).unwrap().altitude.unwrap()).powi(2) as f64).sqrt(); return_vec.push((time_diff, d)) } return return_vec; } fn haversine(&self) -> Vec<(f64, f64)> { let mut return_vec: Vec<(f64, f64)> = Vec::new(); for t in 0..self.len() - 1 { let time_diff = self.get(t+1).unwrap().utc - self.get(t).unwrap().utc; let mut d = haversine(self.get(t).unwrap(), self.get(t + 1).unwrap()); d = (d.powi(2) + (self.get(t).unwrap().altitude.unwrap() - self.get(t + 1).unwrap().altitude.unwrap()).powi(2) as f64).sqrt(); return_vec.push((time_diff, d)) } return return_vec; } } pub trait Kinematics{ fn distance(&self) -> Vec<f64>; fn speed(&self) -> Vec<f64>; } impl Kinematics for Vec<(f64, f64)> { fn distance(&self) -> Vec<f64>{ let mut return_vec: Vec<f64> = Vec::new(); for (_time_diff, distance) in self.iter() { return_vec.push(*distance) } return return_vec; } fn speed(&self) -> Vec<f64> { let mut return_vec: Vec<f64> = Vec::new(); for (time_diff, distance) in self.iter() { return_vec.push(distance/time_diff) } return return_vec; } } #[cfg(test)] mod test_distances { use super::{haversine, inverse_vincenty, Coordinate, DeltaCoordinates, Kinematics}; const SMALL1: Coordinate = Coordinate { utc: (0.0), latitude: Some(51.55814), longitude: Some(0.02955), altitude: Some(0.0) }; const SMALL2: Coordinate = Coordinate { utc: (0.0), latitude: Some(51.55795), longitude: Some(0.03014), altitude: Some(100.0) }; const SMALL3: Coordinate = Coordinate { utc: (0.0), latitude: Some(51.55795), longitude: Some(0.03014), altitude: Some(0.0) }; const LONDON: Coordinate = Coordinate { utc: (0.0), latitude: Some(51.500821), longitude: Some(-0.126670), altitude: Some(0.0) }; const PARIS: Coordinate = Coordinate { utc: (0.0), latitude: Some(48.858788), longitude: Some(2.293746), altitude: Some(0.0) }; const SYDNEY: Coordinate = Coordinate { utc: (0.0), latitude: Some(-33.852239), longitude: Some(151.210675), altitude: Some(0.0) }; #[test] fn vincenty_same_point() { let cal = inverse_vincenty(&LONDON, &LONDON).round(); assert_eq!(cal, 0.0) } #[test] fn vincenty_small_no_alt() { let locations: Vec<Coordinate> = vec![SMALL1, SMALL3]; let cal = locations.vincenty().distance().get(0).unwrap().round(); assert_eq!(cal, 46.0) } #[test] fn vincenty_small() { let locations: Vec<Coordinate> = vec![SMALL1, SMALL2]; let cal = locations.vincenty().distance().get(0).unwrap().round(); assert_eq!(cal, 110.0) } #[test] fn vincenty_lon_paris() { let cal = inverse_vincenty(&LONDON, &PARIS).round(); assert_eq!(cal, 340916.0) } #[test] fn vincenty_lon_syd() { let cal = inverse_vincenty(&LONDON, &SYDNEY).round(); assert_eq!(cal, 16988330.0) } #[test] fn haversine_same_point() { let cal = haversine(&LONDON, &LONDON).round(); assert_eq!(cal, 0.0) } #[test] fn haversine_small() { let locations: Vec<Coordinate> = vec![SMALL1, SMALL2]; let cal = locations.haversine().distance().get(0).unwrap().round(); assert_eq!(cal, 110.0) } #[test] fn haversine_small_no_alt() { let locations: Vec<Coordinate> = vec![SMALL1, SMALL3]; let cal = locations.haversine().distance().get(0).unwrap().round(); assert_eq!(cal, 46.0) } #[test] fn haversine_lon_paris() { let cal = haversine(&LONDON, &PARIS).round(); assert_eq!(cal, 340561.0) } #[test] fn haversine_lon_syd() { let cal = haversine(&LONDON, &SYDNEY).round(); assert_eq!(cal, 16992936.0) } }
use js_ffi::*; pub const KEYDOWN: JSValue = 1.0; pub const KEYUP: JSValue = 2.0;
#[macro_use] extern crate lazy_static; extern crate encoding; mod html_heuristics; mod dynamic_string; mod html_chunk; mod tag_parser; mod html_entities; pub mod html_parser;
// Copyright 2015 The Gfx-rs Developers. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #[macro_use] extern crate gfx; extern crate gfx_app; gfx_vertex_struct!( Vertex { pos: [f32; 2] = "a_Pos", color: [f32; 3] = "a_Color", }); gfx_pipeline!(pipe { vbuf: gfx::VertexBuffer<Vertex> = (), out: gfx::RenderTarget<gfx::format::Srgba8> = "Target0", }); struct App<R: gfx::Resources> { pso: gfx::PipelineState<R, pipe::Meta>, data: pipe::Data<R>, slice: gfx::Slice<R>, } impl<R: gfx::Resources> gfx_app::Application<R> for App<R> { fn new<F: gfx::Factory<R>>(mut factory: F, init: gfx_app::Init<R>) -> Self { use gfx::traits::FactoryExt; let vs = gfx_app::shade::Source { glsl_120: include_bytes!("shader/triangle_120.glslv"), glsl_150: include_bytes!("shader/triangle_150.glslv"), hlsl_40: include_bytes!("data/vertex.fx"), .. gfx_app::shade::Source::empty() }; let fs = gfx_app::shade::Source { glsl_120: include_bytes!("shader/triangle_120.glslf"), glsl_150: include_bytes!("shader/triangle_150.glslf"), hlsl_40: include_bytes!("data/pixel.fx"), .. gfx_app::shade::Source::empty() }; let vertex_data = [ Vertex { pos: [ -0.5, -0.5 ], color: [1.0, 0.0, 0.0] }, Vertex { pos: [ 0.5, -0.5 ], color: [0.0, 1.0, 0.0] }, Vertex { pos: [ 0.0, 0.5 ], color: [0.0, 0.0, 1.0] }, ]; let (vbuf, slice) = factory.create_vertex_buffer(&vertex_data); App { pso: factory.create_pipeline_simple( vs.select(init.backend).unwrap(), fs.select(init.backend).unwrap(), gfx::state::CullFace::Nothing, pipe::new() ).unwrap(), data: pipe::Data { vbuf: vbuf, out: init.color, }, slice: slice, } } fn render<C: gfx::CommandBuffer<R>>(&mut self, encoder: &mut gfx::Encoder<R, C>) { encoder.clear(&self.data.out, [0.1, 0.2, 0.3, 1.0]); encoder.draw(&self.slice, &self.pso, &self.data); } } pub fn main() { use gfx_app::Application; App::launch_default("Triangle example"); }
use sp_ipld::Ipld; use std::num::TryFromIntError; #[derive(PartialEq, Debug, Clone)] pub enum IpldError { Utf8(Vec<u8>, std::string::FromUtf8Error), ByteCount(Vec<u8>, u64), UnicodeChar(u32), U64(TryFromIntError), Uses(Ipld), Bool(Ipld), Position(Ipld), Literal(Ipld), LitType(Ipld), PrimOp(Ipld), NatOp(Ipld), IntOp(Ipld), BytesOp(Ipld), BitsOp(Ipld), TextOp(Ipld), CharOp(Ipld), BoolOp(Ipld), U8Op(Ipld), U16Op(Ipld), U32Op(Ipld), U64Op(Ipld), U128Op(Ipld), I8Op(Ipld), I16Op(Ipld), I32Op(Ipld), I64Op(Ipld), I128Op(Ipld), Anon(Ipld), Meta(Ipld), Entry(Ipld), Index(Ipld), IndexEntry(Ipld), Import(Ipld), ImportEntry(Ipld), Package(Ipld), }
//! GoodReads interaction record schemas and processing. use hashbrown::HashSet; use serde::Deserialize; use crate::arrow::*; use crate::ids::index::IdIndex; use crate::parsing::dates::*; use crate::parsing::*; use crate::prelude::*; pub const OUT_FILE: &'static str = "gr-interactions.parquet"; pub const USER_FILE: &'static str = "gr-users.parquet"; pub const UID_COL: &'static str = "user"; pub const UHASH_COL: &'static str = "user_hash"; /// Interaction records we read from JSON. #[derive(Deserialize)] pub struct RawInteraction { pub user_id: String, pub book_id: String, pub review_id: String, #[serde(alias = "isRead")] pub is_read: bool, pub rating: f32, pub date_added: String, pub date_updated: String, pub read_at: String, pub started_at: String, } /// GoodReads interaction records as actually written to the table. /// /// This struct is written to `gr-interactions.parquet` and records actual interaction data. /// Timestamps are UNIX timestamps recorded as 64-bit integers; they do not use a Parquet /// timestamp time, due to out-of-range values causing problems when loaded into Python. #[derive(ArrowField, ArrowSerialize, ArrowDeserialize)] pub struct IntRecord { pub rec_id: u32, /// The review ID. /// /// This is derived from the hexadecimal review ID by interpreting the hexadecimal-encoded /// review ID from the source data as two big-endian i64s and XORing them. The import /// process checks that this does not result in duplicate review IDs, and emits warnings /// if any are encountered. pub review_id: i64, pub user_id: i32, pub book_id: i32, pub is_read: u8, pub rating: Option<f32>, pub added: f32, pub updated: f32, pub read_started: Option<f32>, pub read_finished: Option<f32>, } /// Object writer to transform and write GoodReads interactions pub struct IntWriter { writer: TableWriter<IntRecord>, users: IdIndex<String>, review_ids: HashSet<i64>, n_recs: u32, } impl IntWriter { /// Open a new output pub fn open() -> Result<IntWriter> { let writer = TableWriter::open(OUT_FILE)?; Ok(IntWriter { writer, users: IdIndex::new(), review_ids: HashSet::new(), n_recs: 0, }) } } impl DataSink for IntWriter { fn output_files(&self) -> Vec<PathBuf> { path_list(&[OUT_FILE]) } } impl ObjectWriter<RawInteraction> for IntWriter { /// Write a single interaction to the output fn write_object(&mut self, row: RawInteraction) -> Result<()> { self.n_recs += 1; let rec_id = self.n_recs; let user_id = self.users.intern_owned(row.user_id)?; let book_id: i32 = row.book_id.parse()?; let (rev_hi, rev_lo) = decode_hex_i64_pair(&row.review_id)?; let review_id = rev_hi ^ rev_lo; if !self.review_ids.insert(review_id) { warn!("review id {} duplicated ({})", review_id, row.review_id); } self.writer.write_object(IntRecord { rec_id, review_id, user_id, book_id, is_read: row.is_read as u8, rating: if row.rating > 0.0 { Some(row.rating) } else { None }, added: parse_gr_date(&row.date_added).map(check_ts("added", 2005))?, updated: parse_gr_date(&row.date_updated).map(check_ts("updated", 2005))?, read_started: trim_opt(&row.started_at) .map(parse_gr_date) .transpose()? .map(check_ts("started", 1900)), read_finished: trim_opt(&row.read_at) .map(parse_gr_date) .transpose()? .map(check_ts("finished", 1900)), })?; Ok(()) } // Clean up and finalize output fn finish(self) -> Result<usize> { info!( "wrote {} records for {} users, closing output", self.n_recs, self.users.len() ); let res = self.writer.finish()?; info!("saving {} users", self.users.len()); self.users.save(USER_FILE, UID_COL, UHASH_COL)?; Ok(res) } }
#[doc = "Reader of register FDCAN_RXF0S"] pub type R = crate::R<u32, super::FDCAN_RXF0S>; #[doc = "Writer for register FDCAN_RXF0S"] pub type W = crate::W<u32, super::FDCAN_RXF0S>; #[doc = "Register FDCAN_RXF0S `reset()`'s with value 0"] impl crate::ResetValue for super::FDCAN_RXF0S { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `F0FL`"] pub type F0FL_R = crate::R<u8, u8>; #[doc = "Write proxy for field `F0FL`"] pub struct F0FL_W<'a> { w: &'a mut W, } impl<'a> F0FL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x7f) | ((value as u32) & 0x7f); self.w } } #[doc = "Reader of field `F0GI`"] pub type F0GI_R = crate::R<u8, u8>; #[doc = "Write proxy for field `F0GI`"] pub struct F0GI_W<'a> { w: &'a mut W, } impl<'a> F0GI_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x3f << 8)) | (((value as u32) & 0x3f) << 8); self.w } } #[doc = "Reader of field `F0PI`"] pub type F0PI_R = crate::R<u8, u8>; #[doc = "Write proxy for field `F0PI`"] pub struct F0PI_W<'a> { w: &'a mut W, } impl<'a> F0PI_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x3f << 16)) | (((value as u32) & 0x3f) << 16); self.w } } #[doc = "F0F\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum F0F_A { #[doc = "0: Rx FIFO 0 not full"] B_0X0 = 0, #[doc = "1: Rx FIFO 0 full"] B_0X1 = 1, } impl From<F0F_A> for bool { #[inline(always)] fn from(variant: F0F_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `F0F`"] pub type F0F_R = crate::R<bool, F0F_A>; impl F0F_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> F0F_A { match self.bits { false => F0F_A::B_0X0, true => F0F_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == F0F_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == F0F_A::B_0X1 } } #[doc = "Write proxy for field `F0F`"] pub struct F0F_W<'a> { w: &'a mut W, } impl<'a> F0F_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: F0F_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Rx FIFO 0 not full"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(F0F_A::B_0X0) } #[doc = "Rx FIFO 0 full"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(F0F_A::B_0X1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24); self.w } } #[doc = "RF0L\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum RF0L_A { #[doc = "0: No Rx FIFO 0 message\r\n lost"] B_0X0 = 0, #[doc = "1: Rx FIFO 0 message lost, also set\r\n after write attempt to Rx FIFO 0 of size\r\n zero"] B_0X1 = 1, } impl From<RF0L_A> for bool { #[inline(always)] fn from(variant: RF0L_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `RF0L`"] pub type RF0L_R = crate::R<bool, RF0L_A>; impl RF0L_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> RF0L_A { match self.bits { false => RF0L_A::B_0X0, true => RF0L_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == RF0L_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == RF0L_A::B_0X1 } } #[doc = "Write proxy for field `RF0L`"] pub struct RF0L_W<'a> { w: &'a mut W, } impl<'a> RF0L_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: RF0L_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "No Rx FIFO 0 message lost"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(RF0L_A::B_0X0) } #[doc = "Rx FIFO 0 message lost, also set after write attempt to Rx FIFO 0 of size zero"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(RF0L_A::B_0X1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 25)) | (((value as u32) & 0x01) << 25); self.w } } impl R { #[doc = "Bits 0:6 - F0FL"] #[inline(always)] pub fn f0fl(&self) -> F0FL_R { F0FL_R::new((self.bits & 0x7f) as u8) } #[doc = "Bits 8:13 - F0GI"] #[inline(always)] pub fn f0gi(&self) -> F0GI_R { F0GI_R::new(((self.bits >> 8) & 0x3f) as u8) } #[doc = "Bits 16:21 - F0PI"] #[inline(always)] pub fn f0pi(&self) -> F0PI_R { F0PI_R::new(((self.bits >> 16) & 0x3f) as u8) } #[doc = "Bit 24 - F0F"] #[inline(always)] pub fn f0f(&self) -> F0F_R { F0F_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bit 25 - RF0L"] #[inline(always)] pub fn rf0l(&self) -> RF0L_R { RF0L_R::new(((self.bits >> 25) & 0x01) != 0) } } impl W { #[doc = "Bits 0:6 - F0FL"] #[inline(always)] pub fn f0fl(&mut self) -> F0FL_W { F0FL_W { w: self } } #[doc = "Bits 8:13 - F0GI"] #[inline(always)] pub fn f0gi(&mut self) -> F0GI_W { F0GI_W { w: self } } #[doc = "Bits 16:21 - F0PI"] #[inline(always)] pub fn f0pi(&mut self) -> F0PI_W { F0PI_W { w: self } } #[doc = "Bit 24 - F0F"] #[inline(always)] pub fn f0f(&mut self) -> F0F_W { F0F_W { w: self } } #[doc = "Bit 25 - RF0L"] #[inline(always)] pub fn rf0l(&mut self) -> RF0L_W { RF0L_W { w: self } } }
use super::*; use rtp::packetizer::Marshaller; use bytes::Bytes; impl Context { pub fn decrypt_rtp_with_header( &mut self, encrypted: &Bytes, header: &rtp::header::Header, ) -> Result<Bytes, Error> { let roc; { if let Some(state) = self.get_srtp_ssrc_state(header.ssrc) { if let Some(replay_detector) = &mut state.replay_detector { if !replay_detector.check(header.sequence_number as u64) { return Err(Error::SrtpSsrcDuplicated( header.ssrc, header.sequence_number, )); } } roc = state.next_rollover_count(header.sequence_number); } else { return Err(Error::SsrcMissingFromSrtp(header.ssrc)); } } let dst = self.cipher.decrypt_rtp(encrypted, header, roc)?; { if let Some(state) = self.get_srtp_ssrc_state(header.ssrc) { if let Some(replay_detector) = &mut state.replay_detector { replay_detector.accept(); } state.update_rollover_count(header.sequence_number); } } Ok(dst) } /// DecryptRTP decrypts a RTP packet with an encrypted payload pub fn decrypt_rtp(&mut self, encrypted: &Bytes) -> Result<Bytes, Error> { let header = rtp::header::Header::unmarshal(encrypted)?; self.decrypt_rtp_with_header(encrypted, &header) } pub fn encrypt_rtp_with_header( &mut self, plaintext: &Bytes, header: &rtp::header::Header, ) -> Result<Bytes, Error> { let roc; { if let Some(state) = self.get_srtp_ssrc_state(header.ssrc) { roc = state.next_rollover_count(header.sequence_number); } else { return Err(Error::SsrcMissingFromSrtp(header.ssrc)); } } let dst = self.cipher .encrypt_rtp(&plaintext.slice(header.marshal_size()..), header, roc)?; { if let Some(state) = self.get_srtp_ssrc_state(header.ssrc) { state.update_rollover_count(header.sequence_number); } } Ok(dst) } /// EncryptRTP marshals and encrypts an RTP packet, writing to the dst buffer provided. /// If the dst buffer does not have the capacity to hold `len(plaintext) + 10` bytes, a new one will be allocated and returned. pub fn encrypt_rtp(&mut self, plaintext: &Bytes) -> Result<Bytes, Error> { let header = rtp::header::Header::unmarshal(plaintext)?; self.encrypt_rtp_with_header(plaintext, &header) } }
use std::convert::From; #[derive(Debug, Serialize, Deserialize)] pub struct Author { pub id: i32, pub name: String, pub country: String, } impl From<postgres::Row> for Author { fn from(row: postgres::Row) -> Self { Author { id: row.get(0), name: row.get(1), country: row.get(2), } } } #[derive(Debug, Deserialize)] pub struct NewAuthor { pub name: String, pub country: String, }
use super::state::State; use super::databus::Databus; pub type AddressingModeFn = fn(state: &State, bus: &dyn Databus, operand: u16) -> u16; pub const DO_NOTHING: AddressingModeFn = |_state: &State, _bus: &dyn Databus, _operand: u16| -> u16 { 0 }; pub const IMMEDIATE: AddressingModeFn = |_state: &State, _bus: &dyn Databus, operand: u16| -> u16 { operand }; pub const RELATIVE: AddressingModeFn = |state: &State, _bus: &dyn Databus, operand: u16| -> u16 { state.calculate_relative_pc(operand as i8) }; pub const ABSOLUTE: AddressingModeFn = |_state: &State, _bus: &dyn Databus, operand: u16| -> u16 { operand }; pub const ABSOLUTE_INDEXED_X: AddressingModeFn = |state: &State, _bus: &dyn Databus, operand: u16| -> u16 { operand.wrapping_add(state.x as u16) }; pub const ABSOLUTE_INDEXED_Y: AddressingModeFn = |state: &State, _bus: &dyn Databus, operand: u16| -> u16 { operand.wrapping_add(state.y as u16) }; pub const ZEROPAGE: AddressingModeFn = |_state: &State, _bus: &dyn Databus, operand: u16| -> u16 { operand }; pub const ZEROPAGE_INDEXED_X: AddressingModeFn = |state: &State, _bus: &dyn Databus, operand: u16| -> u16 { ((operand as u8).wrapping_add(state.x)) as u16 }; pub const ZEROPAGE_INDEXED_Y: AddressingModeFn = |state: &State, _bus: &dyn Databus, operand: u16| -> u16 { ((operand as u8).wrapping_add(state.y)) as u16 }; pub const INDIRECT: AddressingModeFn = |_state: &State, bus: &dyn Databus, operand: u16| -> u16 { let addr = operand as u16; let lo = bus.read(addr); let hi = if (addr & 0xff) == 0xff { bus.read(addr & 0xff00) } else { bus.read(addr + 1) }; ((hi as u16) << 8) + lo as u16 }; pub const INDEXED_INDIRECT_X: AddressingModeFn = |state: &State, bus: &dyn Databus, operand: u16| -> u16 { let addr = ((operand as u8).wrapping_add(state.x)); let lo = bus.read(addr as u16); let hi = bus.read(addr.wrapping_add(1) as u16); ((hi as u16) << 8) + lo as u16 }; pub const INDIRECT_INDEXED_Y: AddressingModeFn = |state: &State, bus: &dyn Databus, operand: u16| -> u16 { let addr = operand as u8; let lo = bus.read(addr as u16); let hi = bus.read(addr.wrapping_add(1) as u16); ((hi as u16) << 8) + lo as u16 + state.y as u16 }; #[derive(Clone, Copy, PartialEq)] pub enum AddressingMode { Unknown, Implied, Immediate, Absolute, AbsoluteIndexedX, AbsoluteIndexedY, Zeropage, ZeropageIndexedX, ZeropageIndexedY, Relative, Accumulator, Indirect, IndexedIndirectX, IndirectIndexedY, } impl AddressingMode { pub fn eval(&self, state: &State, bus: &dyn Databus, operand: u16) -> u16 { self.get_fn()(state, bus, operand) } pub fn crossing_page_boundry(&self, state: &State, bus: &dyn Databus, operand: u16) -> bool { match *self { // TODO This is probably incorrect! See implementations of the addressing modes AddressingMode::AbsoluteIndexedX => _crossing_page(operand, state.x), AddressingMode::AbsoluteIndexedY => _crossing_page(operand, state.y), AddressingMode::IndirectIndexedY => _crossing_page(bus.read_u16(operand), state.y), _ => false } } fn get_fn(&self) -> AddressingModeFn { match *self { AddressingMode::Implied => DO_NOTHING, AddressingMode::Immediate => IMMEDIATE, AddressingMode::Absolute => ABSOLUTE, AddressingMode::AbsoluteIndexedX => ABSOLUTE_INDEXED_X, AddressingMode::AbsoluteIndexedY => ABSOLUTE_INDEXED_Y, AddressingMode::Zeropage => ZEROPAGE, AddressingMode::ZeropageIndexedX => ZEROPAGE_INDEXED_X, AddressingMode::ZeropageIndexedY => ZEROPAGE_INDEXED_Y, AddressingMode::Relative => RELATIVE, AddressingMode::Accumulator => DO_NOTHING, AddressingMode::Indirect => INDIRECT, AddressingMode::IndexedIndirectX => INDEXED_INDIRECT_X, AddressingMode::IndirectIndexedY => INDIRECT_INDEXED_Y, AddressingMode::Unknown => DO_NOTHING } } pub fn format(&self, operand: u16) -> String { match *self { AddressingMode::Implied => format!(""), AddressingMode::Immediate => format!("#${:02X}", operand), AddressingMode::Absolute => format!("${:04X}", operand), AddressingMode::AbsoluteIndexedX => format!("${:04X},X", operand), AddressingMode::AbsoluteIndexedY => format!("${:04X},Y", operand), AddressingMode::Zeropage => format!("${:02X}", operand), AddressingMode::ZeropageIndexedX => format!("${:02X},X", operand), AddressingMode::ZeropageIndexedY => format!("${:02X},Y", operand), AddressingMode::Relative => format!("${:02X}", operand as i8), AddressingMode::Accumulator => format! {"A"}, AddressingMode::Indirect => format! {"(${:04X})", operand}, AddressingMode::IndexedIndirectX => format! {"(${:02X},X)", operand}, AddressingMode::IndirectIndexedY => format! {"(${:02X}),Y", operand}, _ => format!("##") } } } fn _crossing_page(operand: u16, offset: u8) -> bool { (operand & 0xff00) != ((operand.wrapping_add(offset as u16)) & 0xff00) }
use connectorx::{ prelude::*, sources::{ mysql::BinaryProtocol as MYSQLBinaryProtocol, postgres::{rewrite_tls_args, BinaryProtocol, PostgresSource}, }, sql::CXQuery, transports::PostgresArrowTransport, }; use datafusion::datasource::MemTable; use datafusion::prelude::*; use j4rs::{ClasspathEntry, InvocationArg, Jvm, JvmBuilder}; use postgres::NoTls; use std::collections::HashMap; use std::convert::TryFrom; use std::env; use std::fs; use std::iter::Iterator; use std::sync::Arc; use url::Url; fn main() { let db_map = HashMap::from([("db1", "POSTGRES"), ("db2", "POSTGRES"), ("LOCAL", "LOCAL")]); let path = fs::canonicalize("../federated-rewriter.jar").unwrap(); let entry = ClasspathEntry::new(path.to_str().unwrap()); let jvm: Jvm = JvmBuilder::new().classpath_entry(entry).build().unwrap(); let args: Vec<String> = env::args().collect(); let file = &args[1]; let sql = fs::read_to_string(file).unwrap(); println!("input sql: {}", sql); let sql = InvocationArg::try_from(sql).unwrap(); let ds1 = jvm .invoke_static( "org.apache.calcite.adapter.jdbc.JdbcSchema", "dataSource", &[ InvocationArg::try_from(env::var("DB1_JDBC_URL").unwrap()).unwrap(), InvocationArg::try_from(env::var("DB1_JDBC_DRIVER").unwrap()).unwrap(), InvocationArg::try_from(env::var("DB1_USER").unwrap()).unwrap(), InvocationArg::try_from(env::var("DB1_PASSWORD").unwrap()).unwrap(), ], ) .unwrap(); let ds2 = jvm .invoke_static( "org.apache.calcite.adapter.jdbc.JdbcSchema", "dataSource", &[ InvocationArg::try_from(env::var("DB2_JDBC_URL").unwrap()).unwrap(), InvocationArg::try_from(env::var("DB2_JDBC_DRIVER").unwrap()).unwrap(), InvocationArg::try_from(env::var("DB2_USER").unwrap()).unwrap(), InvocationArg::try_from(env::var("DB2_PASSWORD").unwrap()).unwrap(), ], ) .unwrap(); let db_conns = jvm.create_instance("java.util.HashMap", &[]).unwrap(); jvm.invoke( &db_conns, "put", &[ InvocationArg::try_from("db1").unwrap(), InvocationArg::try_from(ds1).unwrap(), ], ) .unwrap(); jvm.invoke( &db_conns, "put", &[ InvocationArg::try_from("db2").unwrap(), InvocationArg::try_from(ds2).unwrap(), ], ) .unwrap(); let db_conns = InvocationArg::try_from(db_conns).unwrap(); let rewriter = jvm .create_instance("ai.dataprep.federated.FederatedQueryRewriter", &[]) .unwrap(); let plan = jvm.invoke(&rewriter, "rewrite", &[db_conns, sql]).unwrap(); let count = jvm.invoke(&plan, "getCount", &[]).unwrap(); let count: i32 = jvm.to_rust(count).unwrap(); let ctx = SessionContext::new(); let mut local_sql = String::new(); let mut alias_names = vec![]; for i in 0..count { println!("\nquery {i}:"); let db = jvm .invoke( &plan, "getDBName", &[InvocationArg::try_from(i) .unwrap() .into_primitive() .unwrap()], ) .unwrap(); let db: String = jvm.to_rust(db).unwrap(); let alias_db = jvm .invoke( &plan, "getAliasDBName", &[InvocationArg::try_from(i) .unwrap() .into_primitive() .unwrap()], ) .unwrap(); let alias_db: String = jvm.to_rust(alias_db).unwrap(); let rewrite_sql = jvm .invoke( &plan, "getSql", &[InvocationArg::try_from(i) .unwrap() .into_primitive() .unwrap()], ) .unwrap(); let rewrite_sql: String = jvm.to_rust(rewrite_sql).unwrap(); println!("db: {}, rewrite sql: {}", db, rewrite_sql); if db == "LOCAL" { local_sql = rewrite_sql; } else { let mut destination = ArrowDestination::new(); let queries = [CXQuery::naked(rewrite_sql)]; let conn = match db.as_str() { "db1" => env::var("DB1").unwrap(), "db2" => env::var("DB2").unwrap(), _ => unimplemented!(), }; match db_map[db.as_str()] { "POSTGRES" => { let url = Url::parse(&conn).unwrap(); let (config, _) = rewrite_tls_args(&url).unwrap(); let sb = PostgresSource::<BinaryProtocol, NoTls>::new(config, NoTls, 1).unwrap(); let dispatcher = Dispatcher::< _, _, PostgresArrowTransport<BinaryProtocol, NoTls>, >::new( sb, &mut destination, &queries, None ); // println!("run dispatcher"); dispatcher.run().unwrap(); } "MYSQL" => { let source = MySQLSource::<MYSQLBinaryProtocol>::new(conn.as_str(), 1).unwrap(); let dispatcher = Dispatcher::<_, _, MySQLArrowTransport<MYSQLBinaryProtocol>>::new( source, &mut destination, &queries, None, ); dispatcher.run().unwrap(); } _ => {} }; let rbs = destination.arrow().unwrap(); // println!("schema: {}", rbs[0].schema()); // arrow::util::pretty::print_batches(&rbs).unwrap(); let provider = MemTable::try_new(rbs[0].schema(), vec![rbs]).unwrap(); ctx.register_table(alias_db.as_str(), Arc::new(provider)) .unwrap(); alias_names.push(alias_db); } } println!("\nquery final:"); let rt = Arc::new(tokio::runtime::Runtime::new().expect("Failed to create runtime")); // until datafusion fix the bug for alias in alias_names { local_sql = local_sql.replace(format!("\"{}\"", alias).as_str(), alias.as_str()); } println!("{}", local_sql); // let sql1 = "SELECT * FROM db2 INNER JOIN db1 ON db2.\"p_partkey\" = db1.\"l_partkey\" AND db2.\"EXPR$0\" AND (db2.\"EXPR$1\" AND db1.\"EXPR$1\") AND (db1.\"EXPR$2\" AND db2.\"EXPR$2\" AND (db1.\"EXPR$3\" AND db1.\"EXPR$4\"))"; // println!("==== run sql 1 ===="); // let t = rt.block_on(ctx.sql(sql1)).unwrap(); // // rt.block_on(t.limit(5).unwrap().show()).unwrap(); // let rbs1 = rt.block_on(t.collect()).unwrap(); // arrow::util::pretty::print_batches(&rbs1).unwrap(); // println!("==== run sql 2 ===="); let df = rt.block_on(ctx.sql(local_sql.as_str())).unwrap(); rt.block_on(df.explain(false, false).unwrap().show()) .unwrap(); rt.block_on(df.limit(5, None).unwrap().show()).unwrap(); let num_rows = rt .block_on(df.collect()) .unwrap() .into_iter() .map(|rb| rb.num_rows()) .sum::<usize>(); println!("Final # rows: {}", num_rows); }
mod common; #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_ldr_preinc_imm() { let (cpu, _mem) = common::execute_arm( "ldr-preinc-imm", " ldr r0, =var sub r2, r0, #3 mov r3, r2 ldr r0, [r0, #0] ldr r1, [r2, #3] var: .word 0x00000080 ", ); assert_eq!(cpu.registers.read(0), 0x80); assert_eq!(cpu.registers.read(1), 0x80); assert_eq!(cpu.registers.read(2), cpu.registers.read(3)); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_ldr_preinc_imm_unaligned() { let (cpu, _mem) = common::execute_arm( "ldr-preinc-imm-unaligned", " ldr r0, =var ldr r1, [r0, #1] ldr r2, [r0, #2] ldr r3, [r0, #3] var: .word 0xff008f00 ", ); assert_eq!(cpu.registers.read(1), 0x00ff008f); assert_eq!(cpu.registers.read(2), 0x8f00ff00); assert_eq!(cpu.registers.read(3), 0x008f00ff); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_ldr_predec_imm() { let (cpu, _mem) = common::execute_arm( "ldr-predec-imm", " ldr r0, =var mov r2, r0 mov r3, r2 add r0, r0, #206 ldr r1, [r0, #-206] ldr r2, [r2, #-0] var: .word 0x00000080 ", ); assert_eq!(cpu.registers.read(1), 0x80); assert_eq!(cpu.registers.read(2), 0x80); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_ldr_predec_imm_unaligned() { let (cpu, _mem) = common::execute_arm( "ldr-predec-imm-unaligned", " ldr r0, =var+4 ldr r0, [r0, #-2] var: .word 0xff008f00 ", ); assert_eq!(cpu.registers.read(0), 0x8f00ff00); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_ldr_preinc_imm_writeback() { let (cpu, _mem) = common::execute_arm( "ldr-preinc-imm-writeback", " ldr r0, =var sub r2, r0, #3 mov r3, r0 ldr r0, [r0, #0]! ldr r1, [r2, #3]! var: .word 0x00000080 ", ); assert_eq!(cpu.registers.read(0), 0x80); assert_eq!(cpu.registers.read(1), 0x80); assert_eq!(cpu.registers.read(2), cpu.registers.read(3)); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_ldr_preinc_imm_unaligned_writeback() { let (cpu, _mem) = common::execute_arm( "ldr-preinc-imm-unaligned-writeback", " ldr r0, =var ldr r0, [r0, #2]! var: .word 0xff008f00 ", ); assert_eq!(cpu.registers.read(0), 0x8f00ff00); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_ldr_predec_imm_writeback() { let (cpu, _mem) = common::execute_arm( "ldr-predec-imm-writeback", " ldr r0, =var add r2, r0, #1 mov r3, r0 add r0, r0, #206 ldr r0, [r0, #-206]! ldr r1, [r2, #-1]! var: .word 0x00000080 ", ); assert_eq!(cpu.registers.read(0), 0x80); assert_eq!(cpu.registers.read(1), 0x80); assert_eq!(cpu.registers.read(2), cpu.registers.read(3)); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_ldr_predec_imm_unaligned_writeback() { let (cpu, _mem) = common::execute_arm( "ldr-predec-imm-unaligned-writeback", " ldr r0, =var+4 ldr r0, [r0, #-2]! var: .word 0xff008f00 ", ); assert_eq!(cpu.registers.read(0), 0x8f00ff00); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_ldr_preinc_reg() { let mut exec = common::Executor::new("ldr-preinc-reg", arm::Isa::Arm); exec.data( " var: .word 0x00000080 ", ); exec.push( " ldr r0, =var sub r2, r0, #8 sub r0, r0, #1 mov r3, r2 mov r4, #2 ldr r0, [r0, r4, lsr #1] ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); exec.push( " ldr r0, [r2, r4, lsl #2] ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); assert_eq!(exec.cpu.registers.read(2), exec.cpu.registers.read(3)); exec.clear_source(); exec.push( " ldr r2, =var mov r2, r2, lsr #1 mov r3, #0xC0000000 @ this is in arm wrestler but it doesn't do anything??? ldr r0, [r2, r2] ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); exec.clear_source(); exec.push( " ldr r2, =var mov r3, #0x8 ldr r0, [r2, r3, lsr #32] ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); exec.clear_source(); exec.push( " ldr r2, =var add r2, r2, #1 mov r3, #0xC0000000 ldr r0, [r2, r3, asr #32] ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); exec.clear_source(); exec.push( " ldr r2, =var add r2, r2, #2 ldr r3, =0xFFFFFFFC adds r4, r3, r3 @ set carry ldr r0, [r2, r3, rrx] ", ); assert!(exec.cpu.registers.getf_c()); assert_eq!(exec.cpu.registers.read(0), 0x80); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_ldr_preinc_reg_unaligned() { let (cpu, _mem) = common::execute_arm( "ldr-preinc-reg-unaligned", " ldr r0, =var mov r2, #2 ldr r0, [r0, r2] var: .word 0xff008f00 ", ); assert_eq!(cpu.registers.read(0), 0x8f00ff00); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_ldr_predec_reg() { let mut exec = common::Executor::new("ldr-predec-reg", arm::Isa::Arm); exec.data( " var: .word 0x00000080 ", ); exec.push( " ldr r0, =var add r2, r0, #8 add r0, r0, #1 mov r3, r2 mov r4, #2 ldr r0, [r0, -r4, lsr #1] ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); exec.push( " ldr r0, [r2, -r4, lsl #2] ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); assert_eq!(exec.cpu.registers.read(2), exec.cpu.registers.read(3)); exec.clear_source(); exec.push( " ldr r2, =var mov r3, #0x8 ldr r0, [r2, -r3, lsr #32] ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); exec.clear_source(); exec.push( " ldr r2, =var sub r2, r2, #1 mov r3, #0x80000000 ldr r0, [r2, -r3, asr #32] ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); exec.clear_source(); exec.push( " ldr r2, =var sub r2, r2, #4 ldr r3, =0xFFFFFFF8 adds r4, r3, r3 @ set carry ldr r0, [r2, -r3, rrx] ", ); assert!(exec.cpu.registers.getf_c()); assert_eq!(exec.cpu.registers.read(0), 0x80); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_ldr_predec_reg_unaligned() { let mut exec = common::Executor::new("ldr-predec-reg-unaligned", arm::Isa::Arm); exec.data( " var: .word 0xff008f00 ", ); exec.push( " ldr r0, =var+4 mov r2, #1 ldr r0, [r0, -r2, lsl #1] ", ); assert_eq!(exec.cpu.registers.read(0), 0x8f00ff00); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_ldr_preinc_reg_writeback() { let mut exec = common::Executor::new("ldr-preinc-reg-writeback", arm::Isa::Arm); exec.data( " var: .word 0x00000080 ", ); exec.push( " ldr r0, =var mov r3, r0 sub r2, r0, #8 sub r0, r0, #1 mov r4, #2 ldr r0, [r0, r4, lsr #1]! ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); exec.push( " ldr r0, [r2, r4, lsl #2]! ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); assert_eq!(exec.cpu.registers.read(2), exec.cpu.registers.read(3)); exec.clear_source(); exec.push( " ldr r2, =var mov r4, r2 mov r2, r2, lsr#1 mov r3, #0xC0000000 ldr r0, [r2, r2]! ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); assert_eq!(exec.cpu.registers.read(2), exec.cpu.registers.read(4)); exec.clear_source(); exec.push( " ldr r2, =var mov r4, r2 add r2, r2, #1 mov r3, #0xC0000000 ldr r0, [r2, r3, asr #32]! ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); assert_eq!(exec.cpu.registers.read(2), exec.cpu.registers.read(4)); exec.clear_source(); exec.push( " ldr r2, =var mov r5, r2 add r2, r2, #2 ldr r3, =0xfffffffc adds r4, r3, r3 @ set carry ldr r0, [r2, r3, rrx]! ", ); assert!(exec.cpu.registers.getf_c()); assert_eq!(exec.cpu.registers.read(0), 0x80); assert_eq!(exec.cpu.registers.read(2), exec.cpu.registers.read(5)); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_ldr_preinc_reg_unaligned_writeback() { let mut exec = common::Executor::new("ldr-preinc-reg-unaligned-writeback", arm::Isa::Arm); exec.data( " var: .word 0xff008f00 ", ); exec.push( " ldr r0, =var mov r2, #2 ldr r0, [r0, r2]! ", ); assert_eq!(exec.cpu.registers.read(0), 0x8f00ff00); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_ldr_predec_reg_writeback() { let mut exec = common::Executor::new("ldr-predec-reg-writeback", arm::Isa::Arm); exec.data( " var: .word 0x00000080 ", ); exec.push( " ldr r0, =var mov r3, r0 add r2, r0, #8 add r0, r0, #1 mov r4, #2 ldr r0, [r0, -r4, lsr #1]! ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); exec.push( " ldr r0, [r2, -r4, lsl #2]! ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); assert_eq!(exec.cpu.registers.read(2), exec.cpu.registers.read(3)); exec.clear_source(); exec.push( " ldr r2, =var mov r4, r2 sub r2, r2, #1 mov r3, #0x80000000 ldr r0, [r2, -r3, asr #32]! ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); assert_eq!(exec.cpu.registers.read(2), exec.cpu.registers.read(4)); exec.clear_source(); exec.push( " ldr r2, =var mov r5, r2 sub r2, r2, #4 ldr r3, =0xfffffff8 adds r4, r3, r3 @ set carry ldr r0, [r2, -r3, rrx]! ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); assert_eq!(exec.cpu.registers.read(2), exec.cpu.registers.read(5)); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_ldr_predec_reg_unaligned_writeback() { let mut exec = common::Executor::new("ldr-predec-reg-unaligned-writeback", arm::Isa::Arm); exec.data( " var: .word 0xff008f00 ", ); exec.push( " ldr r0, =var+4 mov r2, #2 ldr r0, [r0, -r2]! ", ); assert_eq!(exec.cpu.registers.read(0), 0x8f00ff00); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_ldr_postinc_imm() { let mut exec = common::Executor::new("ldr-postinc-imm", arm::Isa::Arm); exec.data( " var: .word 0x00000080 ", ); exec.push( " ldr r0, =var add r3, r0, #3 mov r2, r0 ldr r0, [r0], #3 ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); exec.push( " ldr r0, [r2], #3 ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); assert_eq!(exec.cpu.registers.read(2), exec.cpu.registers.read(3)); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_ldr_postinc_imm_unaligned() { let mut exec = common::Executor::new("ldr-postinc-imm-unaligned", arm::Isa::Arm); exec.data( " var: .word 0xff008f00 ", ); exec.push( " ldr r0, =var+2 ldr r0, [r0], #5 ", ); assert_eq!(exec.cpu.registers.read(0), 0x8f00ff00); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_ldr_postdec_imm() { let mut exec = common::Executor::new("ldr-postdec-imm", arm::Isa::Arm); exec.data( " var: .word 0x00000080 ", ); exec.push( " ldr r0, =var mov r2, r0 sub r3, r0, #0xff ldr r0, [r0], #-0xff ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); exec.push( " ldr r0, [r2], #-0xff ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); assert_eq!(exec.cpu.registers.read(2), exec.cpu.registers.read(3)); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_ldr_postdec_imm_unaligned() { let mut exec = common::Executor::new("ldr-postdec-imm-unaligned", arm::Isa::Arm); exec.data( " var: .word 0xff008f00 ", ); exec.push( " ldr r0, =var+2 ldr r0, [r0], #-5 ", ); assert_eq!(exec.cpu.registers.read(0), 0x8f00ff00); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_ldr_postinc_reg() { let mut exec = common::Executor::new("ldr-postinc-reg", arm::Isa::Arm); exec.data( " var: .word 0x00000080 ", ); exec.push( " ldr r0, =var mov r2, r0 add r5, r0, #8 mov r3, r0 mov r4, #2 ldr r0, [r0], r4, lsr #1 ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); exec.push( " ldr r0, [r2], r4, lsl #2 ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); assert_eq!(exec.cpu.registers.read(2), exec.cpu.registers.read(5)); exec.clear_source(); exec.push( " ldr r2, =var mov r0, #123 add r3, r2, r0 ldr r0, [r2], r0 ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); assert_eq!(exec.cpu.registers.read(2), exec.cpu.registers.read(3)); exec.clear_source(); exec.push( " ldr r2, =var sub r4, r2, #1 mov r3, #0xC0000000 ldr r0, [r2], r3, asr #32 ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); assert_eq!(exec.cpu.registers.read(2), exec.cpu.registers.read(4)); exec.clear_source(); exec.push( " ldr r2, =var sub r4, r2, #2 ldr r3, =0xFFFFFFFC adds r5, r3, r3 @ set carry ldr r0, [r2], r3, rrx ", ); assert!(exec.cpu.registers.getf_c()); assert_eq!(exec.cpu.registers.read(0), 0x80); assert_eq!(exec.cpu.registers.read(2), exec.cpu.registers.read(4)); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_ldr_postinc_reg_unaligned() { let mut exec = common::Executor::new("ldr-postinc-reg-unaligned", arm::Isa::Arm); exec.data( " var: .word 0xff008f00 ", ); exec.push( " ldr r0, =var+2 mov r2, #1 ldr r0, [r0], r2 ", ); assert_eq!(exec.cpu.registers.read(0), 0x8f00ff00); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_ldr_postdec_reg() { let mut exec = common::Executor::new("ldr-postdec-reg", arm::Isa::Arm); exec.data( " var: .word 0x00000080 ", ); exec.push( " ldr r0, =var mov r2, r0 sub r5, r0, #16 mov r3, r0 mov r4, #2 ldr r0, [r0], -r4, lsr #1 ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); exec.push( " ldr r0, [r2], -r4, lsl #3 ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); assert_eq!(exec.cpu.registers.read(2), exec.cpu.registers.read(5)); exec.clear_source(); exec.push( " ldr r2, =var mov r0, #123 sub r3, r2, r0 ldr r0, [r2], -r0 ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); assert_eq!(exec.cpu.registers.read(2), exec.cpu.registers.read(3)); exec.clear_source(); exec.push( " ldr r2, =var add r4, r2, #1 mov r3, #0xC0000000 ldr r0, [r2], -r3, asr #32 ", ); assert_eq!(exec.cpu.registers.read(0), 0x80); assert_eq!(exec.cpu.registers.read(2), exec.cpu.registers.read(4)); exec.clear_source(); exec.push( " ldr r2, =var add r4, r2, #2 ldr r3, =0xfffffffc adds r5, r3, r3 @ set carry ldr r0, [r2], -r3, rrx ", ); assert!(exec.cpu.registers.getf_c()); assert_eq!(exec.cpu.registers.read(0), 0x80); assert_eq!(exec.cpu.registers.read(2), exec.cpu.registers.read(4)); } #[test] #[cfg(feature = "devkit-arm-tests")] pub fn test_ldr_postdec_reg_unaligned() { let mut exec = common::Executor::new("ldr-postdec-reg-unaligned", arm::Isa::Arm); exec.data( " var: .word 0xff008f00 ", ); exec.push( " ldr r0, =var+2 mov r2, #5 ldr r0, [r0], -r2 ", ); assert_eq!(exec.cpu.registers.read(0), 0x8f00ff00); }
/// A static slice of characters. pub type StaticCharVec = &'static [char]; pub static HTML_SPACE_CHARACTERS: StaticCharVec = &['\u{0020}', '\u{0009}', '\u{000a}', '\u{000c}', '\u{000d}']; pub fn char_is_whitespace(c: char) -> bool { HTML_SPACE_CHARACTERS.contains(&c) }
use proc_macro2::TokenStream; use quote::{format_ident, quote}; mod field_copy; mod field_ty; mod r#impl; use super::generics; use field_ty::CudaReprFieldTy; fn get_cuda_repr_ident(rust_repr_ident: &proc_macro2::Ident) -> proc_macro2::Ident { format_ident!("{}CudaRepresentation", rust_repr_ident) } #[allow(clippy::module_name_repetitions)] pub fn impl_rust_to_cuda(ast: &syn::DeriveInput) -> proc_macro::TokenStream { let (mut struct_fields_cuda, struct_semi_cuda) = if let syn::Data::Struct(s) = &ast.data { (s.fields.clone(), s.semi_token) } else { abort_call_site!("You can only derive the `RustToCuda` trait on structs for now."); }; let struct_name = &ast.ident; let struct_name_cuda = get_cuda_repr_ident(struct_name); let mut combined_cuda_alloc_type: TokenStream = quote! { rust_cuda::host::NullCudaAlloc }; let mut r2c_field_declarations: Vec<TokenStream> = Vec::new(); let mut r2c_field_initialisations: Vec<TokenStream> = Vec::new(); let mut r2c_field_destructors: Vec<TokenStream> = Vec::new(); let mut c2r_field_initialisations: Vec<TokenStream> = Vec::new(); match struct_fields_cuda { syn::Fields::Named(syn::FieldsNamed { named: ref mut fields, .. }) | syn::Fields::Unnamed(syn::FieldsUnnamed { unnamed: ref mut fields, .. }) => { let mut r2c_field_destructors_reverse: Vec<TokenStream> = Vec::new(); for (field_index, field) in fields.iter_mut().enumerate() { let cuda_repr_field_ty = field_ty::swap_field_type_and_get_cuda_repr_ty(field); combined_cuda_alloc_type = field_copy::impl_field_copy_init_and_expand_alloc_type( field, field_index, cuda_repr_field_ty, combined_cuda_alloc_type, &mut r2c_field_declarations, &mut r2c_field_initialisations, &mut r2c_field_destructors_reverse, &mut c2r_field_initialisations, ); } // The fields must be deallocated in the reverse order of their allocation r2c_field_destructors.extend(r2c_field_destructors_reverse.into_iter().rev()); }, syn::Fields::Unit => (), } let (struct_attrs_cuda, struct_generics_cuda) = generics::expand_cuda_struct_generics_where_requested_in_attrs(ast); let cuda_struct_declaration = r#impl::cuda_struct_declaration( &struct_attrs_cuda, &ast.vis, &struct_name_cuda, &struct_generics_cuda, &struct_fields_cuda, struct_semi_cuda, ); let rust_to_cuda_trait_impl = r#impl::rust_to_cuda_trait( struct_name, &struct_name_cuda, &struct_generics_cuda, &struct_fields_cuda, &combined_cuda_alloc_type, &r2c_field_declarations, &r2c_field_initialisations, &r2c_field_destructors, ); let cuda_as_rust_trait_impl = r#impl::cuda_as_rust_trait( struct_name, &struct_name_cuda, &struct_generics_cuda, &struct_fields_cuda, &c2r_field_initialisations, ); (quote! { #cuda_struct_declaration #rust_to_cuda_trait_impl #cuda_as_rust_trait_impl }) .into() }
use rand::{thread_rng, Rng}; pub fn random_bytes(length: usize) -> Vec<u8> { (0..length).map(|_| thread_rng().gen::<u8>()).collect() } pub fn random_in_range(lower: usize, upper: usize) -> usize { thread_rng().gen_range(lower..upper) } pub fn coin_flip() -> bool { thread_rng().gen() }
use crate::images; use rider_config::directories::*; use std::fs; use std::path::PathBuf; pub fn create(directories: &Directories) -> std::io::Result<()> { if !directories.themes_dir.exists() { fs::create_dir_all(&directories.themes_dir)?; images::create(directories)?; } if !directories.fonts_dir.exists() { fs::create_dir_all(&directories.fonts_dir)?; } write_default_fonts(directories)?; if !directories.log_dir.exists() { fs::create_dir_all(&directories.log_dir)?; } if !directories.project_dir.exists() { fs::create_dir_all(&directories.project_dir)?; } Ok(()) } fn write_default_fonts(directories: &Directories) -> std::io::Result<()> { let path = directories.fonts_dir.clone().to_str().unwrap().to_owned(); let mut buf = PathBuf::new(); buf.push(path); buf.push("DejaVuSansMono.ttf"); if !buf.exists() { let contents = include_bytes!("../assets/fonts/DejaVuSansMono.ttf"); fs::write(buf, contents.to_vec())?; } let path = directories.fonts_dir.clone().to_str().unwrap().to_owned(); let mut buf = PathBuf::new(); buf.push(path); buf.push("ElaineSans-Medium.ttf"); if !buf.exists() { let contents = include_bytes!("../assets/fonts/ElaineSans-Medium.ttf"); fs::write(buf, contents.to_vec())?; } Ok(()) } #[cfg(test)] mod tests { use super::*; use std::fs::create_dir_all; use std::path::Path; use uuid::Uuid; #[cfg(test)] fn join(a: String, b: String) -> String { vec![a, b].join("/") } #[test] fn assert_create_fonts() { let unique = Uuid::new_v4(); let test_path = join("/tmp/rider-tests".to_owned(), unique.to_string()); create_dir_all(test_path.clone()).unwrap(); let directories = Directories::new(Some(test_path.clone()), None); assert_eq!(create(&directories).is_ok(), true); assert_eq!( Path::new(join(test_path.clone(), "rider/fonts".to_owned()).as_str()).exists(), true ); } #[test] fn assert_create_log() { let unique = Uuid::new_v4(); let test_path = join("/tmp/rider-tests".to_owned(), unique.to_string()); create_dir_all(test_path.clone()).unwrap(); let directories = Directories::new(Some(test_path.clone()), None); assert_eq!(create(&directories).is_ok(), true); assert_eq!( Path::new(join(test_path.clone(), "rider/log".to_owned()).as_str()).exists(), true ); } #[test] fn assert_create_themes() { let unique = Uuid::new_v4(); let test_path = join("/tmp/rider-tests".to_owned(), unique.to_string()); create_dir_all(test_path.clone()).unwrap(); let directories = Directories::new(Some(test_path.clone()), None); assert_eq!( Path::new(join(test_path.clone(), "rider/themes".to_owned()).as_str()).exists(), false ); assert_eq!(create(&directories).is_ok(), true); assert_eq!( Path::new(join(test_path.clone(), "rider/themes".to_owned()).as_str()).exists(), true ); } }
pub mod tap;
pub fn sort<T: PartialOrd> (array: &mut Vec<T>, comparator: fn(&T,&T) -> bool) { loop{ let mut swap = false; for i in 1..array.len() { if comparator(&array[i], &array[i - 1]) { array.swap(i - 1, i); swap = true; } } if !swap { break; } } } #[cfg(test)] mod tests { #[test] fn already_sorted(){ let mut v = vec![1, 2, 3, 4, 5]; super::sort(&mut v, |x,y| x < y); assert_eq!(v, [1, 2, 3, 4, 5]); } #[test] fn one_element(){ let mut v = vec![1]; super::sort(&mut v, |x,y| x < y); assert_eq!(v, [1]); } #[test] fn two_elements(){ let mut v = vec![2, 1]; super::sort(&mut v, |x,y| x < y); assert_eq!(v, [1, 2]); } #[test] fn unsorted(){ let mut v = vec![3, 5, 1, 2, 4]; super::sort(&mut v, |x,y| x < y); assert_eq!(v, [1, 2, 3, 4, 5]); } #[test] fn last_should_be_first(){ let mut v = vec![2, 3, 4, 5, 1]; super::sort(&mut v, |x,y| x < y); assert_eq!(v, [1, 2, 3, 4, 5]); } #[test] fn first_should_be_last(){ let mut v = vec![5, 1, 2, 3, 4]; super::sort(&mut v, |x,y| x < y); assert_eq!(v, [1, 2, 3, 4, 5]); } }
#[doc = "Reader of register TEST_CTL"] pub type R = crate::R<u32, super::TEST_CTL>; #[doc = "Writer for register TEST_CTL"] pub type W = crate::W<u32, super::TEST_CTL>; #[doc = "Register TEST_CTL `reset()`'s with value 0"] impl crate::ResetValue for super::TEST_CTL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `TEST_MODE`"] pub type TEST_MODE_R = crate::R<u8, u8>; #[doc = "Write proxy for field `TEST_MODE`"] pub struct TEST_MODE_W<'a> { w: &'a mut W, } impl<'a> TEST_MODE_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x1f) | ((value as u32) & 0x1f); self.w } } #[doc = "Reader of field `PN_CTL`"] pub type PN_CTL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PN_CTL`"] pub struct PN_CTL_W<'a> { w: &'a mut W, } impl<'a> PN_CTL_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Reader of field `TM_PE`"] pub type TM_PE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TM_PE`"] pub struct TM_PE_W<'a> { w: &'a mut W, } impl<'a> TM_PE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Reader of field `TM_DISPOS`"] pub type TM_DISPOS_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TM_DISPOS`"] pub struct TM_DISPOS_W<'a> { w: &'a mut W, } impl<'a> TM_DISPOS_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Reader of field `TM_DISNEG`"] pub type TM_DISNEG_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TM_DISNEG`"] pub struct TM_DISNEG_W<'a> { w: &'a mut W, } impl<'a> TM_DISNEG_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "Reader of field `EN_CLK_MON`"] pub type EN_CLK_MON_R = crate::R<bool, bool>; #[doc = "Write proxy for field `EN_CLK_MON`"] pub struct EN_CLK_MON_W<'a> { w: &'a mut W, } impl<'a> EN_CLK_MON_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Reader of field `CSL_DEBUG`"] pub type CSL_DEBUG_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CSL_DEBUG`"] pub struct CSL_DEBUG_W<'a> { w: &'a mut W, } impl<'a> CSL_DEBUG_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "Reader of field `ENABLE_OSC`"] pub type ENABLE_OSC_R = crate::R<bool, bool>; #[doc = "Write proxy for field `ENABLE_OSC`"] pub struct ENABLE_OSC_W<'a> { w: &'a mut W, } impl<'a> ENABLE_OSC_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Reader of field `UNSCRAMBLE_WA`"] pub type UNSCRAMBLE_WA_R = crate::R<bool, bool>; #[doc = "Write proxy for field `UNSCRAMBLE_WA`"] pub struct UNSCRAMBLE_WA_W<'a> { w: &'a mut W, } impl<'a> UNSCRAMBLE_WA_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31); self.w } } impl R { #[doc = "Bits 0:4 - Test mode control: '0'-'31': TBD"] #[inline(always)] pub fn test_mode(&self) -> TEST_MODE_R { TEST_MODE_R::new((self.bits & 0x1f) as u8) } #[doc = "Bit 8 - Postive/negative margin mode control: '0': negative margin control '1': positive margin control"] #[inline(always)] pub fn pn_ctl(&self) -> PN_CTL_R { PN_CTL_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - PUMP_EN override: Pump Enable =PUMP_EN | PE_TM"] #[inline(always)] pub fn tm_pe(&self) -> TM_PE_R { TM_PE_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 10 - Test mode positive pump disable"] #[inline(always)] pub fn tm_dispos(&self) -> TM_DISPOS_R { TM_DISPOS_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 11 - Test mode negative pump disable"] #[inline(always)] pub fn tm_disneg(&self) -> TM_DISNEG_R { TM_DISNEG_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 16 - 1: enables the oscillator output monitor"] #[inline(always)] pub fn en_clk_mon(&self) -> EN_CLK_MON_R { EN_CLK_MON_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 17 - Engineering Debug Register"] #[inline(always)] pub fn csl_debug(&self) -> CSL_DEBUG_R { CSL_DEBUG_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 18 - 0': the oscillator enable logic has control over the internal oscillator '1': forces oscillator enable HI"] #[inline(always)] pub fn enable_osc(&self) -> ENABLE_OSC_R { ENABLE_OSC_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 31 - See BSN-242 memo '0': normal '1': disables the Word Address scrambling"] #[inline(always)] pub fn unscramble_wa(&self) -> UNSCRAMBLE_WA_R { UNSCRAMBLE_WA_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bits 0:4 - Test mode control: '0'-'31': TBD"] #[inline(always)] pub fn test_mode(&mut self) -> TEST_MODE_W { TEST_MODE_W { w: self } } #[doc = "Bit 8 - Postive/negative margin mode control: '0': negative margin control '1': positive margin control"] #[inline(always)] pub fn pn_ctl(&mut self) -> PN_CTL_W { PN_CTL_W { w: self } } #[doc = "Bit 9 - PUMP_EN override: Pump Enable =PUMP_EN | PE_TM"] #[inline(always)] pub fn tm_pe(&mut self) -> TM_PE_W { TM_PE_W { w: self } } #[doc = "Bit 10 - Test mode positive pump disable"] #[inline(always)] pub fn tm_dispos(&mut self) -> TM_DISPOS_W { TM_DISPOS_W { w: self } } #[doc = "Bit 11 - Test mode negative pump disable"] #[inline(always)] pub fn tm_disneg(&mut self) -> TM_DISNEG_W { TM_DISNEG_W { w: self } } #[doc = "Bit 16 - 1: enables the oscillator output monitor"] #[inline(always)] pub fn en_clk_mon(&mut self) -> EN_CLK_MON_W { EN_CLK_MON_W { w: self } } #[doc = "Bit 17 - Engineering Debug Register"] #[inline(always)] pub fn csl_debug(&mut self) -> CSL_DEBUG_W { CSL_DEBUG_W { w: self } } #[doc = "Bit 18 - 0': the oscillator enable logic has control over the internal oscillator '1': forces oscillator enable HI"] #[inline(always)] pub fn enable_osc(&mut self) -> ENABLE_OSC_W { ENABLE_OSC_W { w: self } } #[doc = "Bit 31 - See BSN-242 memo '0': normal '1': disables the Word Address scrambling"] #[inline(always)] pub fn unscramble_wa(&mut self) -> UNSCRAMBLE_WA_W { UNSCRAMBLE_WA_W { w: self } } }
// Problem 25 - 1000-digit Fibonacci number // // The Fibonacci sequence is defined by the recurrence relation: // // F(n) = F(nโˆ’1) + F(nโˆ’2), where F(1) = 1 and F(2) = 1. // // Hence the first 12 terms will be: // // F(1) = 1 // F(2) = 1 // F(3) = 2 // F(4) = 3 // F(5) = 5 // F(6) = 8 // F(7) = 13 // F(8) = 21 // F(9) = 34 // F(10) = 55 // F(11) = 89 // F(12) = 144 // // The 12th term, F(12), is the first term to contain three digits. // // What is the first term in the Fibonacci sequence to contain 1000 digits? fn main() { println!("{}", solution()); } fn solution() -> u32 { let threshold = 1000; let mut a = "1".to_string(); let mut b = "1".to_string(); let mut first = 0; for term in 3.. { let sum = add(&a, &b); if sum.len() >= threshold { first = term; break; } a = b; b = sum; } first } fn add(a: &String, b: &String) -> String { let digits_a = digits(a); let digits_b = digits(b); let mut sum = Vec::new(); let mut carry = 0; // `b` is assumed to be "longer"/"greater" than `a` for (ix, da) in digits_a.iter().enumerate() { let dsum = carry + da + digits_b[ix]; sum.push(dsum % 10); carry = dsum/10; } for db in digits_b.iter().skip(digits_a.len()) { let dsum = carry + db; sum.push(dsum % 10); carry = dsum/10; } if carry != 0 { sum.push(carry); } sum.iter() .rev() .fold(String::new(), |mut acc, d| { acc.push_str(&*d.to_string()); acc }) } fn digits(nstr: &String) -> Vec<u32> { nstr.chars().rev().map(|c| c.to_digit(10).unwrap() as u32).collect() }
/// Used to express the search filters applied to GUI inspect page #[derive(Clone, Debug, Default, Hash)] pub struct SearchParameters { /// Application protocol pub app: String, /// Domain pub domain: String, /// Country pub country: String, /// Autonomous System name pub as_name: String, /// Whether to display only favorites pub only_favorites: bool, } impl SearchParameters { pub fn is_some_filter_active(&self) -> bool { self.only_favorites || !self.app.is_empty() || !self.domain.is_empty() || !self.country.is_empty() || !self.as_name.is_empty() } } pub enum FilterInputType { App, Domain, Country, AS, }
//! Engine function alias. use crate::{Input, Output, Tracer}; use rand::rngs::ThreadRng; /// Rendering sampling engine function type. pub type Engine = fn(input: &Input, &mut ThreadRng, trace: Tracer, data: &mut Output, pixel: [usize; 2]);
use std::collections::HashMap; pub fn all_permutations(n: i32, k: i32) { let mut current_sequence: Vec<i32> = Vec::new(); let mut map: HashMap<i32, bool> = HashMap::new(); for i in 1..n + 1 { map.insert(i, false); } all_permutations_help(&mut current_sequence, n, k, &mut map); } fn all_permutations_help(tmp: &mut Vec<i32>, n: i32, k: i32, used: &mut HashMap<i32, bool>) { if tmp.len() as i32 == k { println!("{:?}", tmp); } for i in 1..n + 1 { let v = used.get(&i); match v { None => panic!("system failed"), Some(x) => { if *x { continue; } else { used.insert(i, true); tmp.push(i); all_permutations_help(tmp, n, k, used); tmp.pop(); used.insert(i, false); } } } } }
use string_repr::StringRepr; use wdg_uri::path::Path; #[cfg(test)] mod path { use super::{Path, StringRepr}; mod string_repr { use super::{Path, StringRepr}; #[test] fn fc0f0dd2_530d_4e38_8d33_f9985ee0f848() { assert_eq!( Path::new("/path/to/something").string_repr(), "/path/to/something" ) } } }
#![allow(dead_code)] #[macro_use] extern crate helloworld_derive; trait HelloWorld { fn hello_world(); } #[derive(HelloWorld)] struct FrenchToast; #[derive(HelloWorld)] struct Waffles; fn main() { println!("Hello"); }
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Operation>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Operation { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub display: Option<operation::Display>, #[serde(default, skip_serializing_if = "Option::is_none")] pub origin: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<OperationProperties>, } pub mod operation { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Display { #[serde(default, skip_serializing_if = "Option::is_none")] pub provider: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub resource: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub operation: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationProperties { #[serde(rename = "serviceSpecification", default, skip_serializing_if = "Option::is_none")] pub service_specification: Option<ServiceSpecification>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ServiceSpecification { #[serde(rename = "metricSpecifications", default, skip_serializing_if = "Vec::is_empty")] pub metric_specifications: Vec<MetricSpecification>, #[serde(rename = "logSpecifications", default, skip_serializing_if = "Vec::is_empty")] pub log_specifications: Vec<LogSpecification>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MetricSpecification { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(rename = "displayDescription", default, skip_serializing_if = "Option::is_none")] pub display_description: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub unit: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub dimensions: Vec<Dimension>, #[serde(rename = "aggregationType", default, skip_serializing_if = "Option::is_none")] pub aggregation_type: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub availabilities: Vec<MetricAvailability>, #[serde(default, skip_serializing_if = "Option::is_none")] pub category: Option<String>, #[serde(rename = "resourceIdDimensionNameOverride", default, skip_serializing_if = "Option::is_none")] pub resource_id_dimension_name_override: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct LogSpecification { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Dimension { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MetricAvailability { #[serde(rename = "timeGrain", default, skip_serializing_if = "Option::is_none")] pub time_grain: Option<String>, #[serde(rename = "blobDuration", default, skip_serializing_if = "Option::is_none")] pub blob_duration: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TrackedResource { #[serde(flatten)] pub resource: Resource, pub location: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ResourceProperties { #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<ProvisioningState>, #[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")] pub creation_time: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Accepted, Creating, Updating, Succeeded, Failed, Deleting, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Sku { pub name: sku::Name, pub capacity: i32, } pub mod sku { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Name { S1, S2, P1, L1, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WarmStoreConfigurationProperties { #[serde(rename = "dataRetention")] pub data_retention: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Gen2StorageConfigurationInput { #[serde(rename = "accountName")] pub account_name: String, #[serde(rename = "managementKey")] pub management_key: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Gen2StorageConfigurationOutput { #[serde(rename = "accountName")] pub account_name: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Gen2StorageConfigurationMutableProperties { #[serde(rename = "managementKey")] pub management_key: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CreateOrUpdateTrackedResourceProperties { pub location: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EnvironmentCreateOrUpdateParameters { #[serde(flatten)] pub create_or_update_tracked_resource_properties: CreateOrUpdateTrackedResourceProperties, pub kind: environment_create_or_update_parameters::Kind, pub sku: Sku, } pub mod environment_create_or_update_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Kind { Gen1, Gen2, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Gen1EnvironmentCreateOrUpdateParameters { #[serde(flatten)] pub environment_create_or_update_parameters: EnvironmentCreateOrUpdateParameters, pub properties: Gen1EnvironmentCreationProperties, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Gen2EnvironmentCreateOrUpdateParameters { #[serde(flatten)] pub environment_create_or_update_parameters: EnvironmentCreateOrUpdateParameters, pub properties: Gen2EnvironmentCreationProperties, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EnvironmentUpdateParameters { pub kind: environment_update_parameters::Kind, #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, } pub mod environment_update_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Kind { Gen1, Gen2, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Gen1EnvironmentUpdateParameters { #[serde(flatten)] pub environment_update_parameters: EnvironmentUpdateParameters, #[serde(default, skip_serializing_if = "Option::is_none")] pub sku: Option<Sku>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<Gen1EnvironmentMutableProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Gen2EnvironmentUpdateParameters { #[serde(flatten)] pub environment_update_parameters: EnvironmentUpdateParameters, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<Gen2EnvironmentMutableProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EnvironmentListResponse { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<EnvironmentResource>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EnvironmentResource { #[serde(flatten)] pub tracked_resource: TrackedResource, pub sku: Sku, pub kind: environment_resource::Kind, } pub mod environment_resource { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Kind { Gen1, Gen2, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Gen1EnvironmentResource { #[serde(flatten)] pub environment_resource: EnvironmentResource, pub properties: Gen1EnvironmentResourceProperties, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Gen2EnvironmentResource { #[serde(flatten)] pub environment_resource: EnvironmentResource, pub properties: Gen2EnvironmentResourceProperties, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Gen1EnvironmentCreationProperties { #[serde(rename = "dataRetentionTime")] pub data_retention_time: String, #[serde(rename = "storageLimitExceededBehavior", default, skip_serializing_if = "Option::is_none")] pub storage_limit_exceeded_behavior: Option<gen1_environment_creation_properties::StorageLimitExceededBehavior>, #[serde(rename = "partitionKeyProperties", default, skip_serializing_if = "Vec::is_empty")] pub partition_key_properties: Vec<TimeSeriesIdProperty>, } pub mod gen1_environment_creation_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum StorageLimitExceededBehavior { PurgeOldData, PauseIngress, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Gen2EnvironmentCreationProperties { #[serde(rename = "timeSeriesIdProperties")] pub time_series_id_properties: Vec<TimeSeriesIdProperty>, #[serde(rename = "storageConfiguration")] pub storage_configuration: Gen2StorageConfigurationInput, #[serde(rename = "warmStoreConfiguration", default, skip_serializing_if = "Option::is_none")] pub warm_store_configuration: Option<WarmStoreConfigurationProperties>, #[serde(rename = "publicNetworkAccess", default, skip_serializing_if = "Option::is_none")] pub public_network_access: Option<gen2_environment_creation_properties::PublicNetworkAccess>, #[serde(rename = "privateEndpointConnections", default, skip_serializing_if = "Vec::is_empty")] pub private_endpoint_connections: Vec<PrivateEndpointConnection>, } pub mod gen2_environment_creation_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum PublicNetworkAccess { #[serde(rename = "enabled")] Enabled, #[serde(rename = "disabled")] Disabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EnvironmentResourceProperties { #[serde(flatten)] pub resource_properties: ResourceProperties, #[serde(rename = "dataAccessId", default, skip_serializing_if = "Option::is_none")] pub data_access_id: Option<String>, #[serde(rename = "dataAccessFqdn", default, skip_serializing_if = "Option::is_none")] pub data_access_fqdn: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<EnvironmentStatus>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Gen1EnvironmentResourceProperties { #[serde(flatten)] pub gen1_environment_creation_properties: Gen1EnvironmentCreationProperties, #[serde(flatten)] pub environment_resource_properties: EnvironmentResourceProperties, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Gen2EnvironmentResourceProperties { #[serde(flatten)] pub environment_resource_properties: EnvironmentResourceProperties, #[serde(rename = "timeSeriesIdProperties")] pub time_series_id_properties: Vec<TimeSeriesIdProperty>, #[serde(rename = "storageConfiguration")] pub storage_configuration: Gen2StorageConfigurationOutput, #[serde(rename = "warmStoreConfiguration", default, skip_serializing_if = "Option::is_none")] pub warm_store_configuration: Option<WarmStoreConfigurationProperties>, #[serde(rename = "publicNetworkAccess", default, skip_serializing_if = "Option::is_none")] pub public_network_access: Option<gen2_environment_resource_properties::PublicNetworkAccess>, #[serde(rename = "privateEndpointConnections", default, skip_serializing_if = "Vec::is_empty")] pub private_endpoint_connections: Vec<PrivateEndpointConnection>, } pub mod gen2_environment_resource_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum PublicNetworkAccess { #[serde(rename = "enabled")] Enabled, #[serde(rename = "disabled")] Disabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Gen1EnvironmentMutableProperties { #[serde(rename = "dataRetentionTime", default, skip_serializing_if = "Option::is_none")] pub data_retention_time: Option<String>, #[serde(rename = "storageLimitExceededBehavior", default, skip_serializing_if = "Option::is_none")] pub storage_limit_exceeded_behavior: Option<gen1_environment_mutable_properties::StorageLimitExceededBehavior>, } pub mod gen1_environment_mutable_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum StorageLimitExceededBehavior { PurgeOldData, PauseIngress, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Gen2EnvironmentMutableProperties { #[serde(rename = "storageConfiguration", default, skip_serializing_if = "Option::is_none")] pub storage_configuration: Option<Gen2StorageConfigurationMutableProperties>, #[serde(rename = "warmStoreConfiguration", default, skip_serializing_if = "Option::is_none")] pub warm_store_configuration: Option<WarmStoreConfigurationProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TimeSeriesIdProperty { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<time_series_id_property::Type>, } pub mod time_series_id_property { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { String, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EnvironmentStatus { #[serde(default, skip_serializing_if = "Option::is_none")] pub ingress: Option<IngressEnvironmentStatus>, #[serde(rename = "warmStorage", default, skip_serializing_if = "Option::is_none")] pub warm_storage: Option<WarmStorageEnvironmentStatus>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IngressEnvironmentStatus { #[serde(default, skip_serializing_if = "Option::is_none")] pub state: Option<ingress_environment_status::State>, #[serde(rename = "stateDetails", default, skip_serializing_if = "Option::is_none")] pub state_details: Option<EnvironmentStateDetails>, } pub mod ingress_environment_status { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum State { Disabled, Ready, Running, Paused, Unknown, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EnvironmentStateDetails { #[serde(default, skip_serializing_if = "Option::is_none")] pub code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WarmStorageEnvironmentStatus { #[serde(rename = "propertiesUsage", default, skip_serializing_if = "Option::is_none")] pub properties_usage: Option<WarmStoragePropertiesUsage>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WarmStoragePropertiesUsage { #[serde(default, skip_serializing_if = "Option::is_none")] pub state: Option<warm_storage_properties_usage::State>, #[serde(rename = "stateDetails", default, skip_serializing_if = "Option::is_none")] pub state_details: Option<WarmStoragePropertiesUsageStateDetails>, } pub mod warm_storage_properties_usage { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum State { Ok, Error, Unknown, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WarmStoragePropertiesUsageStateDetails { #[serde(rename = "currentCount", default, skip_serializing_if = "Option::is_none")] pub current_count: Option<i32>, #[serde(rename = "maxCount", default, skip_serializing_if = "Option::is_none")] pub max_count: Option<i32>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IngressStartAtProperties { #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<ingress_start_at_properties::Type>, #[serde(default, skip_serializing_if = "Option::is_none")] pub time: Option<String>, } pub mod ingress_start_at_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { EarliestAvailable, EventSourceCreationTime, CustomEnqueuedTime, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventSourceCreateOrUpdateParameters { #[serde(flatten)] pub create_or_update_tracked_resource_properties: CreateOrUpdateTrackedResourceProperties, pub kind: event_source_create_or_update_parameters::Kind, #[serde(rename = "localTimestamp", default, skip_serializing_if = "Option::is_none")] pub local_timestamp: Option<LocalTimestamp>, } pub mod event_source_create_or_update_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Kind { #[serde(rename = "Microsoft.EventHub")] MicrosoftEventHub, #[serde(rename = "Microsoft.IoTHub")] MicrosoftIoTHub, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventHubEventSourceCreateOrUpdateParameters { #[serde(flatten)] pub event_source_create_or_update_parameters: EventSourceCreateOrUpdateParameters, pub properties: EventHubEventSourceCreationProperties, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IoTHubEventSourceCreateOrUpdateParameters { #[serde(flatten)] pub event_source_create_or_update_parameters: EventSourceCreateOrUpdateParameters, pub properties: IoTHubEventSourceCreationProperties, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventSourceUpdateParameters { pub kind: event_source_update_parameters::Kind, #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, } pub mod event_source_update_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Kind { #[serde(rename = "Microsoft.EventHub")] MicrosoftEventHub, #[serde(rename = "Microsoft.IoTHub")] MicrosoftIoTHub, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventHubEventSourceUpdateParameters { #[serde(flatten)] pub event_source_update_parameters: EventSourceUpdateParameters, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<EventHubEventSourceMutableProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IoTHubEventSourceUpdateParameters { #[serde(flatten)] pub event_source_update_parameters: EventSourceUpdateParameters, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<IoTHubEventSourceMutableProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventSourceListResponse { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<EventSourceResource>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventSourceResource { #[serde(flatten)] pub tracked_resource: TrackedResource, pub kind: event_source_resource::Kind, } pub mod event_source_resource { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Kind { #[serde(rename = "Microsoft.EventHub")] MicrosoftEventHub, #[serde(rename = "Microsoft.IoTHub")] MicrosoftIoTHub, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventHubEventSourceResource { #[serde(flatten)] pub event_source_resource: EventSourceResource, pub properties: EventHubEventSourceResourceProperties, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IoTHubEventSourceResource { #[serde(flatten)] pub event_source_resource: EventSourceResource, pub properties: IoTHubEventSourceResourceProperties, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventSourceCommonProperties { #[serde(flatten)] pub resource_properties: ResourceProperties, #[serde(rename = "timestampPropertyName", default, skip_serializing_if = "Option::is_none")] pub timestamp_property_name: Option<String>, #[serde(rename = "localTimestamp", default, skip_serializing_if = "Option::is_none")] pub local_timestamp: Option<LocalTimestamp>, #[serde(rename = "ingressStartAt", default, skip_serializing_if = "Option::is_none")] pub ingress_start_at: Option<IngressStartAtProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AzureEventSourceProperties { #[serde(flatten)] pub event_source_common_properties: EventSourceCommonProperties, #[serde(rename = "eventSourceResourceId")] pub event_source_resource_id: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventHubEventSourceCommonProperties { #[serde(flatten)] pub azure_event_source_properties: AzureEventSourceProperties, #[serde(rename = "serviceBusNamespace")] pub service_bus_namespace: String, #[serde(rename = "eventHubName")] pub event_hub_name: String, #[serde(rename = "consumerGroupName")] pub consumer_group_name: String, #[serde(rename = "keyName")] pub key_name: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventHubEventSourceCreationProperties { #[serde(flatten)] pub event_hub_event_source_common_properties: EventHubEventSourceCommonProperties, #[serde(rename = "sharedAccessKey")] pub shared_access_key: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventHubEventSourceResourceProperties { #[serde(flatten)] pub event_hub_event_source_common_properties: EventHubEventSourceCommonProperties, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IoTHubEventSourceCommonProperties { #[serde(flatten)] pub azure_event_source_properties: AzureEventSourceProperties, #[serde(rename = "iotHubName")] pub iot_hub_name: String, #[serde(rename = "consumerGroupName")] pub consumer_group_name: String, #[serde(rename = "keyName")] pub key_name: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IoTHubEventSourceCreationProperties { #[serde(flatten)] pub io_t_hub_event_source_common_properties: IoTHubEventSourceCommonProperties, #[serde(rename = "sharedAccessKey")] pub shared_access_key: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IoTHubEventSourceResourceProperties { #[serde(flatten)] pub io_t_hub_event_source_common_properties: IoTHubEventSourceCommonProperties, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct LocalTimestamp { #[serde(default, skip_serializing_if = "Option::is_none")] pub format: Option<local_timestamp::Format>, #[serde(rename = "timeZoneOffset", default, skip_serializing_if = "Option::is_none")] pub time_zone_offset: Option<local_timestamp::TimeZoneOffset>, } pub mod local_timestamp { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Format { Embedded, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TimeZoneOffset { #[serde(rename = "propertyName", default, skip_serializing_if = "Option::is_none")] pub property_name: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventSourceMutableProperties { #[serde(rename = "timestampPropertyName", default, skip_serializing_if = "Option::is_none")] pub timestamp_property_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventHubEventSourceMutableProperties { #[serde(flatten)] pub event_source_mutable_properties: EventSourceMutableProperties, #[serde(rename = "sharedAccessKey", default, skip_serializing_if = "Option::is_none")] pub shared_access_key: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IoTHubEventSourceMutableProperties { #[serde(flatten)] pub event_source_mutable_properties: EventSourceMutableProperties, #[serde(rename = "sharedAccessKey", default, skip_serializing_if = "Option::is_none")] pub shared_access_key: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReferenceDataSetCreateOrUpdateParameters { #[serde(flatten)] pub create_or_update_tracked_resource_properties: CreateOrUpdateTrackedResourceProperties, pub properties: ReferenceDataSetCreationProperties, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReferenceDataSetUpdateParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReferenceDataSetListResponse { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<ReferenceDataSetResource>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReferenceDataSetResource { #[serde(flatten)] pub tracked_resource: TrackedResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ReferenceDataSetResourceProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReferenceDataSetCreationProperties { #[serde(rename = "keyProperties")] pub key_properties: Vec<ReferenceDataSetKeyProperty>, #[serde(rename = "dataStringComparisonBehavior", default, skip_serializing_if = "Option::is_none")] pub data_string_comparison_behavior: Option<reference_data_set_creation_properties::DataStringComparisonBehavior>, } pub mod reference_data_set_creation_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum DataStringComparisonBehavior { Ordinal, OrdinalIgnoreCase, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReferenceDataSetResourceProperties { #[serde(flatten)] pub reference_data_set_creation_properties: ReferenceDataSetCreationProperties, #[serde(flatten)] pub resource_properties: ResourceProperties, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReferenceDataSetKeyProperty { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<reference_data_set_key_property::Type>, } pub mod reference_data_set_key_property { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { String, Double, Bool, DateTime, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AccessPolicyCreateOrUpdateParameters { pub properties: AccessPolicyResourceProperties, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AccessPolicyUpdateParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<AccessPolicyMutableProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AccessPolicyListResponse { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<AccessPolicyResource>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AccessPolicyResource { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<AccessPolicyResourceProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AccessPolicyResourceProperties { #[serde(rename = "principalObjectId", default, skip_serializing_if = "Option::is_none")] pub principal_object_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub roles: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AccessPolicyMutableProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub roles: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateEndpoint { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateEndpointConnection { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<PrivateEndpointConnectionProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateEndpointConnectionProperties { #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<PrivateEndpointConnectionProvisioningState>, #[serde(rename = "privateEndpoint", default, skip_serializing_if = "Option::is_none")] pub private_endpoint: Option<PrivateEndpoint>, #[serde(rename = "groupIds", default, skip_serializing_if = "Option::is_none")] pub group_ids: Option<PrivateEndpointGroupIds>, #[serde(rename = "privateLinkServiceConnectionState")] pub private_link_service_connection_state: PrivateLinkServiceConnectionState, } pub type PrivateEndpointGroupIds = Vec<String>; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateLinkServiceConnectionState { #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<PrivateEndpointServiceConnectionStatus>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "actionsRequired", default, skip_serializing_if = "Option::is_none")] pub actions_required: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum PrivateEndpointServiceConnectionStatus { Pending, Approved, Rejected, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum PrivateEndpointConnectionProvisioningState { Succeeded, Creating, Deleting, Failed, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateLinkResource { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<PrivateLinkResourceProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateLinkResourceProperties { #[serde(rename = "groupId", default, skip_serializing_if = "Option::is_none")] pub group_id: Option<String>, #[serde(rename = "requiredMembers", default, skip_serializing_if = "Vec::is_empty")] pub required_members: Vec<String>, #[serde(rename = "requiredZoneNames", default, skip_serializing_if = "Vec::is_empty")] pub required_zone_names: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateEndpointConnectionListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<PrivateEndpointConnection>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateLinkResourceListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<PrivateLinkResource>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CloudError { #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<CloudErrorBody>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CloudErrorBody { #[serde(default, skip_serializing_if = "Option::is_none")] pub code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub target: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub details: Vec<CloudErrorBody>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Resource { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, }
pub mod scene; pub mod geometry; pub mod sprite; pub mod input; pub mod tiles; pub mod ui; pub mod text; pub mod physics; pub mod rendering; pub mod game_context;
use packed_secret_sharing::packed::*; use packed_secret_sharing::*; use packed_secret_sharing::ntt; /* use this prime : 4610415792919412737 512th root ot unity: 1266473570726112470 729th root of unity: 2230453091198852918 3073700804129980417, 414345200490731620, 1697820560572790570, 8, 27, 2, 10 from [5, 5] [5, 1411300642881442990, 755230403484066526, 1873193081170044888, 2073840665913069205, 1167364399051202624, 816231852543661536, 1062052081340565995, 296681500362385504, 7730202141009458] [5, 98563416899351090, 702991160794567105, 29933450899899199, 2176346442046929493, 1596775264978130561, 260292684598891845, 1251985437174463998, 3059651942944547382, 1182115622347807999] [1937113453806524834, 1081261608772129829, 50, 1685750291142969254, 2941097270934669262, 1135448392566993238, 2330023659693944815, 104085561992962891, 524567367177051120, 2467612606526845848] */ fn main() { println!("Hello, world!"); let p = 3073700804129980417u128; let r2 = 414345200490731620u128; let r3 = 1697820560572790570u128; let mut pss = PackedSecretSharing::new(p, r2, r3, 8, 27, 2, 10); //prime: u128, root2: u128, root3:u128, degree: usize, num_secrets: usize, num_shares: usize let secrets: Vec<u64> = vec![5u64, 5u64]; let shares: Vec<u64> = vec![5, 1411300642881442990, 755230403484066526, 1873193081170044888, 2073840665913069205, 1167364399051202624, 816231852543661536, 1062052081340565995, 296681500362385504, 7730202141009458]; //pss.share_u64(&secrets); println!("{:?}", shares); let secrets2: Vec<u64> = vec![5u64, 5u64]; let shares2: Vec<u64> = vec![5, 98563416899351090, 702991160794567105, 29933450899899199, 2176346442046929493, 1596775264978130561, 260292684598891845, 1251985437174463998, 3059651942944547382, 1182115622347807999];//pss.share_u64(&secrets2); println!("{:?}", shares2); let mut rawSumm = Vec::new(); for i in 0..secrets2.len() { rawSumm.push(secrets[i] + secrets2[i]); } let mut sum = vec![0u128; 10]; for i in 0..10 { sum[i] = (shares[i] + shares2[i]) as u128; } // ====================================================== // let mut secrets_point = vec![0u128; 4]; // for i in 0..4 { // secrets_point[i] = r2.modpow(&(i as u128), &p); // } // let mut shares_point = vec![0u128; 512]; // for i in 0..512 { // shares_point[i] = r3.modpow(&(i as u128), &p); // } // let mut shares_val = sum.clone(); // shares_val.split_off(512); // let secrets = pss.reconstruct_with_points(&shares_point, &shares_val); let test: Vec<u128> = vec![1937113453806524834, 1081261608772129829, 50, 1685750291142969254, 2941097270934669262, 1135448392566993238, 2330023659693944815, 104085561992962891, 524567367177051120, 2467612606526845848]; let secrets = pss.reconstruct(&test); println!("{:?}", secrets); println!("{:?}", rawSumm); } use std::convert::TryInto; fn read_be_u64(input: Vec<u8>) -> Vec<u64> { let mut res = Vec::<u64>::new(); let mut ptr = &mut input.as_slice(); loop { let (int_bytes, rest) = ptr.split_at(std::mem::size_of::<u64>()); *ptr = rest; res.push(u64::from_be_bytes(int_bytes.try_into().unwrap())); if (rest.len() < 8) { break; } } res }
extern crate alga; extern crate fps_counter; extern crate generic_array; #[macro_use] extern crate imgui; #[macro_use] extern crate lazy_static; extern crate nalgebra as na; extern crate ncollide; extern crate nphysics3d as nphysics; extern crate pathfinding; extern crate png; extern crate rand; extern crate ron; #[macro_use] extern crate serde_derive; extern crate specs; extern crate typenum; #[macro_use] extern crate vulkano; #[macro_use] extern crate vulkano_shader_derive; extern crate vulkano_win; extern crate wavefront_obj; extern crate winit; extern crate app_dirs2; extern crate rodio; extern crate show_message; extern crate palette; extern crate locale_config; extern crate fluent_locale; #[macro_use] mod util; mod graphics; mod audio; mod entity; mod component; mod system; mod resource; pub mod maze; mod config; mod level; pub use config::CONFIG; use vulkano_win::VkSurfaceBuild; use show_message::UnwrapOrShow; use vulkano::swapchain; use vulkano::sync::now; use vulkano::sync::FenceSignalFuture; use vulkano::sync::GpuFuture; use vulkano::instance::Instance; use winit::{DeviceEvent, Event, WindowEvent, Icon}; use std::sync::Arc; use std::time::Duration; use std::time::Instant; use std::thread; use std::fs::File; use std::io::Read; fn init_imgui() -> ::imgui::ImGui { let mut imgui = ::imgui::ImGui::init(); imgui.set_ini_filename(None); imgui.set_log_filename(None); imgui.set_font_global_scale(::CONFIG.font_global_scale); imgui.set_mouse_draw_cursor(false); imgui.set_imgui_key(::imgui::ImGuiKey::Tab, 0); imgui.set_imgui_key(::imgui::ImGuiKey::LeftArrow, 1); imgui.set_imgui_key(::imgui::ImGuiKey::RightArrow, 2); imgui.set_imgui_key(::imgui::ImGuiKey::UpArrow, 3); imgui.set_imgui_key(::imgui::ImGuiKey::DownArrow, 4); imgui.set_imgui_key(::imgui::ImGuiKey::PageUp, 5); imgui.set_imgui_key(::imgui::ImGuiKey::PageDown, 6); imgui.set_imgui_key(::imgui::ImGuiKey::Home, 7); imgui.set_imgui_key(::imgui::ImGuiKey::End, 8); imgui.set_imgui_key(::imgui::ImGuiKey::Delete, 9); imgui.set_imgui_key(::imgui::ImGuiKey::Backspace, 10); imgui.set_imgui_key(::imgui::ImGuiKey::Enter, 11); imgui.set_imgui_key(::imgui::ImGuiKey::Escape, 12); imgui.set_imgui_key(::imgui::ImGuiKey::A, 13); imgui.set_imgui_key(::imgui::ImGuiKey::C, 14); imgui.set_imgui_key(::imgui::ImGuiKey::V, 15); imgui.set_imgui_key(::imgui::ImGuiKey::X, 16); imgui.set_imgui_key(::imgui::ImGuiKey::Y, 17); imgui.set_imgui_key(::imgui::ImGuiKey::Z, 18); CONFIG.style.set_style(imgui.style_mut()); imgui } fn main() { // On windows stack is overflowed otherwise ::std::thread::Builder::new().stack_size(32 * 1024 * 1024).spawn(|| { while let ControlFlow::Restart = new_game() {} }).unwrap().join().unwrap(); } enum ControlFlow { Restart, Quit, } fn new_game() -> ControlFlow { ::std::env::set_var("WINIT_UNIX_BACKEND", "x11"); let mut save = ::resource::Save::new(); let text = ::resource::Text::load(); let instance = { let extensions = vulkano_win::required_extensions(); let info = app_info_from_cargo_toml!(); Instance::new(Some(&info), &extensions, None) .unwrap_or_else_show(|e| format!("{}\n\n{}", text.vulkan_error, e)) }; let mut events_loop = winit::EventsLoop::new(); let mut window_builder = winit::WindowBuilder::new(); if save.fullscreen() { window_builder = window_builder.with_fullscreen(Some(events_loop.get_primary_monitor())); } let icon = { let icon_data = if cfg!(feature = "packed") { include_bytes!("../assets/icon.png").iter().cloned().collect::<Vec<_>>() } else { let mut data = vec![]; let mut file = File::open("assets/icon.png") .unwrap_or_else_show(|e| format!("Failed to open \"assets/icon.png\": {}", e)); file.read_to_end(&mut data) .unwrap_or_else_show(|e| format!("Failed to read \"assets/icon.png\": {}", e)); data }; Icon::from_bytes(&icon_data) .unwrap_or_else_show(|e| format!("Failed to load icon: {}", e)) }; let window = window_builder .with_window_icon(Some(icon)) .with_title("HyperZen Training") .build_vk_surface(&events_loop, instance.clone()) .unwrap_or_else_show(|e| format!("Failed to build vulkan window: {}\n\n{:#?}", e, e)); window.window().set_cursor(winit::MouseCursor::NoneCursor); let current_window_id = window.window().id(); let mut imgui = init_imgui(); let mut graphics = graphics::Graphics::new(&window, &mut imgui, &mut save); let mut previous_frame_end: Option<FenceSignalFuture<Box<GpuFuture>>> = None; let debug = ::std::env::var("HYPERZEN_TRAINING_DEBUG").map(|v| v == "1").unwrap_or(false); let mut world = specs::World::new(); world.register::<::component::Player>(); world.register::<::component::Teleport>(); world.register::<::component::Generator>(); world.register::<::component::Shooter>(); world.register::<::component::Hook>(); world.register::<::component::WeaponAnimation>(); world.register::<::component::Aim>(); world.register::<::component::StaticDraw>(); world.register::<::component::DynamicDraw>(); world.register::<::component::DynamicEraser>(); world.register::<::component::DynamicHud>(); world.register::<::component::DynamicGraphicsAssets>(); world.register::<::component::DeletBool>(); world.register::<::component::DeletTimer>(); world.register::<::component::Reducer>(); world.register::<::component::PhysicBody>(); world.register::<::component::Activated>(); world.register::<::component::Momentum>(); world.register::<::component::Avoider>(); world.register::<::component::Bouncer>(); world.register::<::component::Turret>(); world.register::<::component::DepthBall>(); world.register::<::component::Attracted>(); world.register::<::component::Motionless>(); world.register::<::component::Life>(); world.register::<::component::Contactor>(); world.register::<::component::Proximitor>(); world.register::<::component::FollowPlayer>(); world.register::<::component::PhysicSensor>(); world.add_resource(::resource::Help(String::new())); world.add_resource(text); world.add_resource(graphics.clone()); world.add_resource(Some(imgui)); world.add_resource(::resource::Events(vec![])); world.add_resource(instance.clone()); world.add_resource(::resource::Rendering::new()); world.add_resource(::resource::DebugMode(debug)); world.add_resource(::resource::FpsCounter(0)); world.add_resource(::resource::PlayerControl::new()); world.add_resource(::resource::Benchmarks::new()); world.add_resource(::resource::UpdateTime(0.0)); world.add_resource(::resource::GameDuration(Duration::new(0, 0))); world.add_resource(::resource::Activated(false)); world.add_resource(::resource::Audio::init(&save)); world.add_resource(::resource::LevelActions(vec![])); world.add_resource(::resource::ErasedStatus::new()); let menu_state = ::resource::MenuState::new(&save); world.add_resource(save); world.add_resource(menu_state); world.maintain(); let mut game_system = ::system::GameSystem::new(); game_system.run(&mut world); let mut pause_update_dispatcher = ::specs::DispatcherBuilder::new() .add(::system::MenuPauseControlSystem::new(), "menu_pause", &[]) .add(::system::HelpSystem, "help", &[]) .add(::system::AudioSystem, "audio", &[]) .build(); let mut game_update_dispatcher = ::specs::DispatcherBuilder::new() .add(::system::AudioSystem, "audio", &[]) .add(::system::MenuGameControlSystem, "menu_game", &[]) .add(::system::PlayerControlSystem, "player_control", &[]) .add(::system::AvoiderControlSystem, "avoider_control", &[]) .add(::system::BouncerControlSystem, "bouncer_control", &[]) .add(::system::TeleportSystem, "teleport", &[]) .add(::system::FollowPlayerSystem, "follower_control", &[]) .add(::system::TurretControlSystem::new(), "turret_control", &[]) .add(::system::GeneratorSystem, "generator", &[]) .add(::system::ShootSystem::new(), "shoot", &[]) .add(::system::HookSystem::new(), "hook", &[]) .add(::system::PhysicSystem, "physic", &[]) .add(::system::DeleterSystem, "deleter", &[]) .add(::system::PlayerDeathSystem, "death", &[]) .add(::system::ActivateSystem, "activate", &[]) .add(::system::ReducerSystem, "reducer", &[]) .add(::system::DepthCoefSystem, "depth_coef", &[]) .add(::system::DepthBallSystem, "depth_ball", &[]) .add(::system::AttractedSystem::new(), "attracted", &[]) .add_barrier() // following systems will delete physic bodies .add(::system::LifeSystem, "life", &[]) .build(); let mut prepare_game_draw_dispatcher = ::specs::DispatcherBuilder::new() .add( ::system::UpdateDynamicDrawEraserSystem, "update_dynamic_draw", &[], ) .build(); let mut draw_dispatcher = ::specs::DispatcherBuilder::new() .add(::system::DrawSystem, "draw_system", &[]) .build(); { assert!(world.read_resource::<::resource::UpdateTime>().0 == 0.0); game_update_dispatcher.dispatch(&mut world.res); world.maintain(); prepare_game_draw_dispatcher.dispatch(&mut world.res); world.maintain(); } let frame_duration = Duration::new( 0, (1_000_000_000.0 / ::CONFIG.fps as f32) as u32, ); let mut last_frame_instant = Instant::now(); let mut fps_counter = fps_counter::FPSCounter::new(); let mut benchmarker = util::Benchmarker::new(); let mut last_update_instant = Instant::now(); loop { benchmarker.start("pre_update"); if let Some(ref mut previous_frame_end) = previous_frame_end { previous_frame_end.cleanup_finished(); } // Poll events { let mut events = world.write_resource::<::resource::Events>(); events.0.clear(); let mut done = false; events_loop.poll_events(|ev| { // Filter out old window event match ev { Event::WindowEvent { window_id, .. } => if window_id != current_window_id { return } _ => (), } let retain = match ev { Event::WindowEvent { event: WindowEvent::Focused(true), .. } => { try_multiple_time!(window.window().set_cursor_state(winit::CursorState::Normal), 100, 10) .unwrap_or_else_show(|e| format!("Failed to reset cursor: {}", e)); try_multiple_time!(window.window().set_cursor_state(winit::CursorState::Grab), 100, 10) .unwrap_or_else_show(|e| format!("Failed to grab cursor: {}", e)); false } Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => { done = true; false } Event::WindowEvent { event: WindowEvent::MouseInput { .. }, .. } | Event::WindowEvent { event: WindowEvent::ReceivedCharacter(..), .. } | Event::WindowEvent { event: WindowEvent::MouseWheel { .. }, .. } | Event::WindowEvent { event: WindowEvent::KeyboardInput { .. }, .. } | Event::DeviceEvent { event: DeviceEvent::MouseMotion { .. }, .. } | Event::WindowEvent { event: WindowEvent::CursorMoved { .. }, .. } => true, _ => false, }; if retain { events.0.push(ev); } }); if done { break ControlFlow::Quit; } } if world.write_resource::<::resource::MenuState>().quit_button { break ControlFlow::Quit; } if world.write_resource::<::resource::MenuState>().restart_now_button { break ControlFlow::Restart; } benchmarker.end("pre_update"); // Update world benchmarker.start("update"); let delta_time = last_update_instant.elapsed(); last_update_instant = Instant::now(); if world.read_resource::<::resource::MenuState>().paused() { world.write_resource::<::resource::UpdateTime>().0 = 0.0; pause_update_dispatcher.dispatch(&mut world.res); } else { world.write_resource::<::resource::GameDuration>().0 += delta_time; world.write_resource::<::resource::UpdateTime>().0 = delta_time .as_secs() .saturating_mul(1_000_000_000) .saturating_add(delta_time.subsec_nanos() as u64) as f32 / 1_000_000_000.0; game_update_dispatcher.dispatch(&mut world.res); world.maintain(); game_system.run(&mut world); prepare_game_draw_dispatcher.dispatch(&mut world.res); world.maintain(); } benchmarker.end("update"); // Render world benchmarker.start("draw"); // On X with Xmonad and intel HD graphics the acquire stay sometimes forever let timeout = Duration::from_secs(2); let mut next_image = swapchain::acquire_next_image(graphics.swapchain.clone(), Some(timeout)); loop { match next_image { Err(vulkano::swapchain::AcquireError::OutOfDate) | Err(vulkano::swapchain::AcquireError::Timeout) => { // Drop ImGui *world.write_resource::<::resource::ImGuiOption>() = None; let mut imgui = init_imgui(); graphics.recreate(&window, &mut imgui); *world.write_resource::<::resource::ImGuiOption>() = Some(imgui); *world.write_resource() = graphics.clone(); next_image = swapchain::acquire_next_image(graphics.swapchain.clone(), Some(timeout)); } _ => break } } let (image_num, acquire_future) = next_image .unwrap_or_else_show(|e| format!("Failed to acquire next image: {}", e)); world.write_resource::<::resource::Rendering>().image_num = Some(image_num); world.write_resource::<::resource::Rendering>().size = window.window().get_inner_size(); draw_dispatcher.dispatch(&mut world.res); let (command_buffer, second_command_buffer) = { let mut rendering = world.write_resource::<::resource::Rendering>(); ( rendering.command_buffer.take().unwrap(), rendering.second_command_buffer.take().unwrap(), ) }; if let Some(previous_frame_end) = previous_frame_end { if let Ok(()) = previous_frame_end.wait(None) { let amount = graphics.erased_amount_buffer.read().unwrap()[0]; let total = graphics.dim[0] as f32 * graphics.dim[1] as f32; world.write_resource::<::resource::ErasedStatus>().amount = amount as f32 / total; } } let future = now(graphics.device.clone()) .then_execute(graphics.queue.clone(), command_buffer) .unwrap() .join(acquire_future) .then_execute(graphics.queue.clone(), second_command_buffer) .unwrap() .then_swapchain_present( graphics.queue.clone(), graphics.swapchain.clone(), image_num, ); let future = Box::new(future) as Box<GpuFuture>; let future = future.then_signal_fence_and_flush(); match future { Ok(future) => { previous_frame_end = Some(future); } Err(vulkano::sync::FlushError::OutOfDate) => { previous_frame_end = None; } Err(e) => { println!("ERROR: {:?}", e); previous_frame_end = None; } } benchmarker.end("draw"); // Sleep benchmarker.start("sleep"); let elapsed = last_frame_instant.elapsed(); if let Some(to_sleep) = frame_duration.checked_sub(elapsed) { thread::sleep(to_sleep); } last_frame_instant = Instant::now(); world .write_resource::<::resource::FpsCounter>() .0 = fps_counter.tick(); benchmarker.end("sleep"); *world.write_resource::<::resource::Benchmarks>() = benchmarker.get_all(); } }
use clang::*; use std::io::Write; #[macro_use] use super::gen_context::*; use super::symbol_status::SymbolStatus; use super::compile_entity_children; pub fn gen(gen_context: &mut GenContext, entity: Entity) { if let Some(entity_name) = entity.get_name() { // Write a Obj-C Interface binding gen_fmt!(gen_context, get_itf, "@interface {} : {} {{\n", GenContext::get_class_name(&entity_name), entity_name); gen_fmt!(gen_context, get_itf, " {}* vtable;\n}}\n\n", GenContext::get_vtable_name(&entity_name)); // Write a Obj-C Interface binding gen_all!(gen_context, get_vtable, b"typedef struct {\n"); // Write the implementation binding gen_fmt!(gen_context, get_impl, "@implementation {}\n\n", GenContext::get_class_name(&entity_name)); // Write the VSL binding gen_fmt!(gen_context, get_vsl, "public class {} {{\n", entity_name); let main_entity = match entity.get_kind() { EntityKind::ObjCProtocolDecl => entity, _ => unwrap_or_exit!( entity.get_type().and_then(|entity_type| entity_type.get_declaration()), "Failed to find decl for interface {}", entity_name ) }; compile_entity_children(gen_context, main_entity, true); // Close Obj-C interface gen_all!(gen_context, get_itf, b"@end\n\n"); // Close Obj-C implementation gen_fmt!(gen_context, get_impl, "@end\n\n"); // Close Obj-C vtable gen_fmt!(gen_context, get_vtable, "}} {};\n\n", GenContext::get_vtable_name(&entity_name)); // Close VSL binding gen_all!(gen_context, get_vsl, b"}\n\n"); } else { warn!("Could not get name for target resolution entity."); } }
#[allow(unused_imports)] use super::util::prelude::*; use super::util::{Pack, PackDepth}; use super::BlockMut; pub type NumberValue = f64; pub type NumberMin = NumberValue; pub type NumberMid = NumberValue; pub type NumberMax = NumberValue; #[derive(Clone)] pub enum Value { Number(NumberValue), NumberMinMax(NumberValue, NumberMin, NumberMax), NumberMid(NumberValue, NumberMid), Normal(String), Note(String), Check(bool), Select(usize, Vec<String>), } impl Value { pub fn to_string_with_option(&self, option: Option<&String>) -> String { let option = option.map(|option| option.as_str()); match (self, option) { (Self::Number(val), None) => val.to_string(), (Self::Number(val), Some("val")) => val.to_string(), (Self::NumberMinMax(val, ..), None) => val.to_string(), (Self::NumberMinMax(val, ..), Some("val")) => val.to_string(), (Self::NumberMinMax(_, min, ..), Some("min")) => min.to_string(), (Self::NumberMinMax(_, _, max), Some("max")) => max.to_string(), (Self::NumberMid(val, ..), None) => val.to_string(), (Self::NumberMid(val, ..), Some("val")) => val.to_string(), (Self::NumberMid(_, mid), Some("mid")) => mid.to_string(), (Self::Normal(text), None) => text.clone(), (Self::Normal(text), Some("val")) => text.clone(), (Self::Note(text), None) => text.clone(), (Self::Note(text), Some("val")) => text.clone(), (Self::Check(val), None) => val.to_string(), (Self::Check(val), Some("val")) => val.to_string(), (Self::Select(idx, vals), None) => vals .get(*idx) .map(|val| val.clone()) .unwrap_or_else(|| String::new()), (Self::Select(idx, vals), Some("val")) => vals .get(*idx) .map(|val| val.clone()) .unwrap_or_else(|| String::new()), (Self::Select(idx, ..), Some("idx")) => idx.to_string(), (Self::Select(_, vals), Some(idx)) if idx.parse::<usize>().is_ok() => vals .get(idx.parse::<usize>().unwrap()) .map(|val| val.clone()) .unwrap_or_else(|| String::new()), _ => String::new(), } } pub fn to_number(&self) -> Self { match self { Self::Number(val) => Self::Number(*val), Self::NumberMinMax(val, ..) => Self::Number(*val), Self::NumberMid(val, ..) => Self::Number(*val), Self::Normal(val) => val .parse::<NumberValue>() .map(|val| Self::Number(val)) .unwrap_or_else(|_| Self::Number(0.0)), Self::Note(val) => val .parse::<NumberValue>() .map(|val| Self::Number(val)) .unwrap_or_else(|_| Self::Number(0.0)), Self::Check(val) => Self::Number(if *val { 1.0 } else { 0.0 }), Self::Select(idx, ..) => Self::Number(*idx as NumberValue), } } pub fn to_number_min_max(&self) -> Self { match self { Self::Number(val) => Self::NumberMinMax(*val, 0.0, 100.0), Self::NumberMinMax(val, min, max) => Self::NumberMinMax(*val, *min, *max), Self::NumberMid(val, mid) => Self::NumberMinMax(*val, *mid / 2.0, *mid * 2.0), Self::Normal(val) => val .parse::<NumberValue>() .map(|val| Self::NumberMinMax(val, 0.0, 100.0)) .unwrap_or_else(|_| Self::NumberMinMax(0.0, 0.0, 100.0)), Self::Note(val) => val .parse::<NumberValue>() .map(|val| Self::NumberMinMax(val, 0.0, 100.0)) .unwrap_or_else(|_| Self::NumberMinMax(0.0, 0.0, 100.0)), Self::Check(val) => Self::NumberMinMax(if *val { 1.0 } else { 0.0 }, 0.0, 1.0), Self::Select(idx, list) => { Self::NumberMinMax(*idx as NumberValue, 0.0, (list.len() - 1) as NumberMax) } } } pub fn to_number_mid(&self) -> Self { match self { Self::Number(val) => Self::NumberMid(*val, 10.0), Self::NumberMinMax(val, min, max) => Self::NumberMid(*val, (*min + *max) / 2.0), Self::NumberMid(val, mid) => Self::NumberMid(*val, *mid), Self::Normal(val) => val .parse::<NumberValue>() .map(|val| Self::NumberMid(val, 10.0)) .unwrap_or_else(|_| Self::NumberMid(0.0, 10.0)), Self::Note(val) => val .parse::<NumberValue>() .map(|val| Self::NumberMid(val, 10.0)) .unwrap_or_else(|_| Self::NumberMid(0.0, 10.0)), Self::Check(val) => Self::NumberMid(if *val { 1.0 } else { 0.0 }, 0.5), Self::Select(idx, list) => { Self::NumberMid(*idx as NumberValue, (list.len() - 1) as NumberMax / 2.0) } } } pub fn to_normal(&self) -> Self { match self { Self::Number(val) => Self::Normal(format!("{}", *val)), Self::NumberMinMax(val, ..) => Self::Normal(format!("{}", *val)), Self::NumberMid(val, ..) => Self::Normal(format!("{}", *val)), Self::Normal(val) => Self::Normal(val.clone()), Self::Note(val) => Self::Normal(val.clone()), Self::Check(val) => Self::Normal(format!("{}", *val)), Self::Select(idx, ..) => Self::Normal(format!("{}", *idx)), } } pub fn to_note(&self) -> Self { match self { Self::Number(val) => Self::Note(format!("{}", *val)), Self::NumberMinMax(val, ..) => Self::Note(format!("{}", *val)), Self::NumberMid(val, ..) => Self::Note(format!("{}", *val)), Self::Normal(val) => Self::Note(val.clone()), Self::Note(val) => Self::Note(val.clone()), Self::Check(val) => Self::Note(format!("{}", *val)), Self::Select(idx, ..) => Self::Note(format!("{}", *idx)), } } pub fn to_check(&self) -> Self { match self { Self::Number(val) => Self::Check(*val != 0.0), Self::NumberMinMax(val, ..) => Self::Check(*val != 0.0), Self::NumberMid(val, ..) => Self::Check(*val != 0.0), Self::Normal(val) => Self::Check(*val == "true"), Self::Note(val) => Self::Check(*val == "true"), Self::Check(val) => Self::Check(*val), Self::Select(idx, ..) => Self::Check(*idx != 0), } } pub fn to_select(&self) -> Self { match self { Self::Number(val) => Self::Select(0, vec![format!("{}", *val)]), Self::NumberMinMax(val, ..) => Self::Select(0, vec![format!("{}", *val)]), Self::NumberMid(val, ..) => Self::Select(0, vec![format!("{}", *val)]), Self::Normal(val) => Self::Select(0, vec![val.clone()]), Self::Note(val) => Self::Select(0, vec![val.clone()]), Self::Check(val) => Self::Select( if *val { 1 } else { 0 }, vec![String::from("false"), String::from("true")], ), Self::Select(idx, list) => Self::Select(*idx, list.clone()), } } } impl std::fmt::Display for Value { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Check(val) => write!(f, "{}", val), Self::Normal(val) => write!(f, "{}", val), Self::Note(val) => write!(f, "{}", val), Self::Number(val) => write!(f, "{}", val), Self::NumberMid(val, ..) => write!(f, "{}", val), Self::NumberMinMax(val, ..) => write!(f, "{}", val), Self::Select(idx, list) => list .get(*idx) .map(|val| write!(f, "{}", val)) .unwrap_or_else(|| write!(f, "")), } } } #[async_trait(?Send)] impl Pack for Value { async fn pack(&self, pack_depth: PackDepth) -> JsValue { crate::debug::log_1("Value::pack"); match self { Self::Number(v) => (object! { "_tag": "Number", "_val": JsValue::from(*v) }) .into(), Self::NumberMinMax(v, i, a) => (object! { "_tag": "NumberMinMax", "_val": array![*v, *i, *a] }) .into(), Self::NumberMid(v, m) => (object! { "_tag": "NumberMid", "_val": array![*v, *m] }) .into(), Self::Normal(v) => (object! { "_tag": "Normal", "_val": v }) .into(), Self::Note(v) => (object! { "_tag": "Note", "_val": v }) .into(), Self::Check(v) => (object! { "_tag": "Check", "_val": *v }) .into(), Self::Select(v, s) => (object! { "_tag": "Select", "_val": array![*v, s.pack(pack_depth).await] }) .into(), } } async fn unpack(data: &JsValue, arena: ArenaMut) -> Option<Box<Self>> { let data = data.dyn_ref::<crate::libs::js_object::Object>()?; let tag = data.get("_tag")?.as_string()?; let val = data.get("_val")?; match tag.as_str() { "Number" => val .as_f64() .map(|v| Box::new(Self::Number(v as NumberValue))), "NumberMinMax" => { let val = js_sys::Array::from(&val).to_vec(); let val_0 = val.get(0)?.as_f64()?; let val_1 = val.get(0)?.as_f64()?; let val_2 = val.get(0)?.as_f64()?; Some(Box::new(Self::NumberMinMax( val_0 as NumberValue, val_1 as NumberValue, val_2 as NumberValue, ))) } "NumberMid" => { let val = js_sys::Array::from(&val).to_vec(); let val_0 = val.get(0)?.as_f64()?; let val_1 = val.get(0)?.as_f64()?; Some(Box::new(Self::NumberMid( val_0 as NumberValue, val_1 as NumberValue, ))) } "Normal" => val.as_string().map(|v| Box::new(Self::Normal(v))), "Note" => val.as_string().map(|v| Box::new(Self::Note(v))), "Check" => val.as_bool().map(|v| Box::new(Self::Check(v))), "Select" => { let val = js_sys::Array::from(&val).to_vec(); let val_0 = val.get(0)?.as_f64()? as usize; let val_1 = js_sys::Array::from(unwrap!(val.get(1); None).as_ref()).to_vec(); let mut list = vec![]; for item in val_1 { if let Some(item) = item.as_string() { list.push(item); } } Some(Box::new(Self::Select(val_0, list))) } _ => None, } } } pub enum DataView { Tabular, List, } #[async_trait(?Send)] impl Pack for DataView { async fn pack(&self, _: PackDepth) -> JsValue { crate::debug::log_1("DataView::pack"); match self { Self::Tabular => JsValue::from("Tabular"), Self::List => JsValue::from("List"), } } async fn unpack(data: &JsValue, arena: ArenaMut) -> Option<Box<Self>> { match data.as_string()?.as_str() { "Tabular" => Some(Box::new(Self::Tabular)), "List" => Some(Box::new(Self::List)), _ => None, } } } pub struct Data { view: DataView, values: Vec<Vec<Value>>, } #[async_trait(?Send)] impl Pack for Data { async fn pack(&self, pack_depth: PackDepth) -> JsValue { crate::debug::log_1("Data::pack"); (object! { "view": self.view.pack(pack_depth).await, "values": self.values.pack(pack_depth).await }) .into() } async fn unpack(data: &JsValue, arena: ArenaMut) -> Option<Box<Self>> { let data = data.dyn_ref::<crate::libs::js_object::Object>()?; let view = DataView::unpack( unwrap!(data.get("view"); None).as_ref(), ArenaMut::clone(&arena), ) .await?; let view = *view; let items = js_sys::Array::from(unwrap!(data.get("values"); None).as_ref()).to_vec(); let mut values = vec![]; for col_items in items { let col_items = js_sys::Array::from(&col_items).to_vec(); let mut col_values = vec![]; for item in col_items { if let Some(item) = Value::unpack(&item, ArenaMut::clone(&arena)).await { col_values.push(*item); } } values.push(col_values); } Some(Box::new(Self { view, values })) } } impl Data { pub fn new() -> Self { Self { view: DataView::List, values: vec![vec![]], } } pub fn view(&self) -> &DataView { &self.view } pub fn set_view(&mut self, view: DataView) { self.view = view; } pub fn values(&self) -> &Vec<Vec<Value>> { &self.values } pub fn push_value(&mut self, row_idx: usize, value: Value) { if let Some(row) = self.values.get_mut(row_idx) { row.push(value); } } pub fn push_row(&mut self) { self.values.push(vec![]); } pub fn set_value(&mut self, row: usize, col: usize, value: Value) { if let Some(cols) = self.values.get_mut(row) { if let Some(val) = cols.get_mut(col) { *val = value; } } } pub fn is_empty(&self) -> bool { self.values.is_empty() || self.values.iter().all(Vec::is_empty) } pub fn get_value0(&self) -> Option<&Value> { self.get_value1(0) } pub fn get_value1(&self, mut idx: usize) -> Option<&Value> { for row_offset in 0..self.values.len() { if let Some(value) = self.get_value2(row_offset, idx) { return Some(value); } idx -= self.values[row_offset].len(); } None } pub fn get_value2(&self, r: usize, c: usize) -> Option<&Value> { self.values.get(r).and_then(|cols| cols.get(c)) } fn remove_empty_row(&mut self) { let mut row_idx = 1; while row_idx < self.values.len() { if self.values[row_idx].len() == 0 { self.values.remove(row_idx); } else { row_idx += 1; } } } pub fn remove_value1(&mut self, mut idx: usize) -> bool { for row_offset in 0..self.values.len() { if self.remove_value2(row_offset, idx) { return true; } if let Some(cols) = self.values.get(row_offset) { idx -= cols.len(); } } false } pub fn remove_value2(&mut self, r: usize, c: usize) -> bool { if let Some(cols) = self.values.get_mut(r) { if c < cols.len() { cols.remove(c); self.remove_empty_row(); return true; } } false } pub fn ref_value(&self, args: Vec<&(String, Option<String>)>) -> Option<Value> { if args.len() == 0 { return self.get_value0().map(|val| val.clone()); } else if args.len() == 1 { if args[0].1.is_none() { if let Ok(idx) = args[0].0.parse::<usize>() { return self.get_value1(idx).map(|val| val.clone()); } } } else { if args[0].1.is_none() && args[1].1.is_none() { if let (Ok(r), Ok(c)) = (args[0].0.parse::<usize>(), args[1].0.parse::<usize>()) { return self.get_value2(r, c).map(|val| val.clone()); } } } None } } pub enum PropertyView { Board, List, } #[async_trait(?Send)] impl Pack for PropertyView { async fn pack(&self, _: PackDepth) -> JsValue { crate::debug::log_1("PropertyView::pack"); match self { Self::Board => JsValue::from("Board"), Self::List => JsValue::from("List"), } } async fn unpack(data: &JsValue, _arena: ArenaMut) -> Option<Box<Self>> { let data = data.as_string()?; match data.as_str() { "Board" => Some(Box::new(Self::Board)), "List" => Some(Box::new(Self::List)), _ => None, } } } block! { [pub Property(constructor, pack)] name: String = String::from(""); data: Data = Data::new(); view: PropertyView = PropertyView::List; children: Vec<BlockMut<Self>> = vec![]; } impl Property { pub fn name(&self) -> &String { &self.name } pub fn set_name(&mut self, name: String) { self.name = name; } pub fn data(&self) -> &Data { &self.data } pub fn data_mut(&mut self) -> &mut Data { &mut self.data } pub fn view(&self) -> &PropertyView { &self.view } pub fn set_view(&mut self, view: PropertyView) { self.view = view; } pub fn children(&self) -> &Vec<BlockMut<Self>> { &self.children } pub fn push_child(&mut self, child: BlockMut<Self>) { self.children.push(child); } pub fn remove_child(&mut self, block_id: &U128Id) { if let Some(child_idx) = self .children .iter() .position(|child| child.id() == *block_id) { self.children.remove(child_idx); } } pub fn ref_value( &self, mut name: Vec<&String>, args: Vec<&(String, Option<String>)>, ) -> Option<Value> { if name.len() > 1 { let name = if self.name == *name[0] { name.drain(1..).collect() } else { name }; self.ref_children_value(name, args) } else if name.len() == 1 { if self.name == *name[0] { self.data.ref_value(args) } else { self.ref_children_value(name, args) } } else { None } } fn ref_children_value( &self, name: Vec<&String>, args: Vec<&(String, Option<String>)>, ) -> Option<Value> { for child in &self.children { if let Some(value) = child .map(|child| child.ref_value(name.clone(), args.clone())) .unwrap_or_default() { return Some(value); } } None } }
/// An enum to represent all characters in the ArabicExtendedA block. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum ArabicExtendedA { /// \u{8a0}: 'เข ' ArabicLetterBehWithSmallVBelow, /// \u{8a1}: 'เขก' ArabicLetterBehWithHamzaAbove, /// \u{8a2}: 'เขข' ArabicLetterJeemWithTwoDotsAbove, /// \u{8a3}: 'เขฃ' ArabicLetterTahWithTwoDotsAbove, /// \u{8a4}: 'เขค' ArabicLetterFehWithDotBelowAndThreeDotsAbove, /// \u{8a5}: 'เขฅ' ArabicLetterQafWithDotBelow, /// \u{8a6}: 'เขฆ' ArabicLetterLamWithDoubleBar, /// \u{8a7}: 'เขง' ArabicLetterMeemWithThreeDotsAbove, /// \u{8a8}: 'เขจ' ArabicLetterYehWithTwoDotsBelowAndHamzaAbove, /// \u{8a9}: 'เขฉ' ArabicLetterYehWithTwoDotsBelowAndDotAbove, /// \u{8aa}: 'เขช' ArabicLetterRehWithLoop, /// \u{8ab}: 'เขซ' ArabicLetterWawWithDotWithin, /// \u{8ac}: 'เขฌ' ArabicLetterRohingyaYeh, /// \u{8ad}: 'เขญ' ArabicLetterLowAlef, /// \u{8ae}: 'เขฎ' ArabicLetterDalWithThreeDotsBelow, /// \u{8af}: 'เขฏ' ArabicLetterSadWithThreeDotsBelow, /// \u{8b0}: 'เขฐ' ArabicLetterGafWithInvertedStroke, /// \u{8b1}: 'เขฑ' ArabicLetterStraightWaw, /// \u{8b2}: 'เขฒ' ArabicLetterZainWithInvertedVAbove, /// \u{8b3}: 'เขณ' ArabicLetterAinWithThreeDotsBelow, /// \u{8b4}: 'เขด' ArabicLetterKafWithDotBelow, /// \u{8b6}: 'เขถ' ArabicLetterBehWithSmallMeemAbove, /// \u{8b7}: 'เขท' ArabicLetterPehWithSmallMeemAbove, /// \u{8b8}: 'เขธ' ArabicLetterTehWithSmallTehAbove, /// \u{8b9}: 'เขน' ArabicLetterRehWithSmallNoonAbove, /// \u{8ba}: 'เขบ' ArabicLetterYehWithTwoDotsBelowAndSmallNoonAbove, /// \u{8bb}: 'เขป' ArabicLetterAfricanFeh, /// \u{8bc}: 'เขผ' ArabicLetterAfricanQaf, /// \u{8bd}: 'เขฝ' ArabicLetterAfricanNoon, /// \u{8d3}: 'เฃ“' ArabicSmallLowWaw, /// \u{8d4}: 'เฃ”' ArabicSmallHighWordArDashRub, /// \u{8d5}: 'เฃ•' ArabicSmallHighSad, /// \u{8d6}: 'เฃ–' ArabicSmallHighAin, /// \u{8d7}: 'เฃ—' ArabicSmallHighQaf, /// \u{8d8}: 'เฃ˜' ArabicSmallHighNoonWithKasra, /// \u{8d9}: 'เฃ™' ArabicSmallLowNoonWithKasra, /// \u{8da}: 'เฃš' ArabicSmallHighWordAthDashThalatha, /// \u{8db}: 'เฃ›' ArabicSmallHighWordAsDashSajda, /// \u{8dc}: 'เฃœ' ArabicSmallHighWordAnDashNisf, /// \u{8dd}: 'เฃ' ArabicSmallHighWordSakta, /// \u{8de}: 'เฃž' ArabicSmallHighWordQif, /// \u{8df}: 'เฃŸ' ArabicSmallHighWordWaqfa, /// \u{8e0}: 'เฃ ' ArabicSmallHighFootnoteMarker, /// \u{8e1}: 'เฃก' ArabicSmallHighSignSafha, /// \u{8e2}: 'เฃข' ArabicDisputedEndOfAyah, /// \u{8e3}: 'เฃฃ' ArabicTurnedDammaBelow, /// \u{8e4}: 'เฃค' ArabicCurlyFatha, /// \u{8e5}: 'เฃฅ' ArabicCurlyDamma, /// \u{8e6}: 'เฃฆ' ArabicCurlyKasra, /// \u{8e7}: 'เฃง' ArabicCurlyFathatan, /// \u{8e8}: 'เฃจ' ArabicCurlyDammatan, /// \u{8e9}: 'เฃฉ' ArabicCurlyKasratan, /// \u{8ea}: 'เฃช' ArabicToneOneDotAbove, /// \u{8eb}: 'เฃซ' ArabicToneTwoDotsAbove, /// \u{8ec}: 'เฃฌ' ArabicToneLoopAbove, /// \u{8ed}: 'เฃญ' ArabicToneOneDotBelow, /// \u{8ee}: 'เฃฎ' ArabicToneTwoDotsBelow, /// \u{8ef}: 'เฃฏ' ArabicToneLoopBelow, /// \u{8f0}: 'เฃฐ' ArabicOpenFathatan, /// \u{8f1}: 'เฃฑ' ArabicOpenDammatan, /// \u{8f2}: 'เฃฒ' ArabicOpenKasratan, /// \u{8f3}: 'เฃณ' ArabicSmallHighWaw, /// \u{8f4}: 'เฃด' ArabicFathaWithRing, /// \u{8f5}: 'เฃต' ArabicFathaWithDotAbove, /// \u{8f6}: 'เฃถ' ArabicKasraWithDotBelow, /// \u{8f7}: 'เฃท' ArabicLeftArrowheadAbove, /// \u{8f8}: 'เฃธ' ArabicRightArrowheadAbove, /// \u{8f9}: 'เฃน' ArabicLeftArrowheadBelow, /// \u{8fa}: 'เฃบ' ArabicRightArrowheadBelow, /// \u{8fb}: 'เฃป' ArabicDoubleRightArrowheadAbove, /// \u{8fc}: 'เฃผ' ArabicDoubleRightArrowheadAboveWithDot, /// \u{8fd}: 'เฃฝ' ArabicRightArrowheadAboveWithDot, /// \u{8fe}: 'เฃพ' ArabicDammaWithDot, } impl Into<char> for ArabicExtendedA { fn into(self) -> char { match self { ArabicExtendedA::ArabicLetterBehWithSmallVBelow => 'เข ', ArabicExtendedA::ArabicLetterBehWithHamzaAbove => 'เขก', ArabicExtendedA::ArabicLetterJeemWithTwoDotsAbove => 'เขข', ArabicExtendedA::ArabicLetterTahWithTwoDotsAbove => 'เขฃ', ArabicExtendedA::ArabicLetterFehWithDotBelowAndThreeDotsAbove => 'เขค', ArabicExtendedA::ArabicLetterQafWithDotBelow => 'เขฅ', ArabicExtendedA::ArabicLetterLamWithDoubleBar => 'เขฆ', ArabicExtendedA::ArabicLetterMeemWithThreeDotsAbove => 'เขง', ArabicExtendedA::ArabicLetterYehWithTwoDotsBelowAndHamzaAbove => 'เขจ', ArabicExtendedA::ArabicLetterYehWithTwoDotsBelowAndDotAbove => 'เขฉ', ArabicExtendedA::ArabicLetterRehWithLoop => 'เขช', ArabicExtendedA::ArabicLetterWawWithDotWithin => 'เขซ', ArabicExtendedA::ArabicLetterRohingyaYeh => 'เขฌ', ArabicExtendedA::ArabicLetterLowAlef => 'เขญ', ArabicExtendedA::ArabicLetterDalWithThreeDotsBelow => 'เขฎ', ArabicExtendedA::ArabicLetterSadWithThreeDotsBelow => 'เขฏ', ArabicExtendedA::ArabicLetterGafWithInvertedStroke => 'เขฐ', ArabicExtendedA::ArabicLetterStraightWaw => 'เขฑ', ArabicExtendedA::ArabicLetterZainWithInvertedVAbove => 'เขฒ', ArabicExtendedA::ArabicLetterAinWithThreeDotsBelow => 'เขณ', ArabicExtendedA::ArabicLetterKafWithDotBelow => 'เขด', ArabicExtendedA::ArabicLetterBehWithSmallMeemAbove => 'เขถ', ArabicExtendedA::ArabicLetterPehWithSmallMeemAbove => 'เขท', ArabicExtendedA::ArabicLetterTehWithSmallTehAbove => 'เขธ', ArabicExtendedA::ArabicLetterRehWithSmallNoonAbove => 'เขน', ArabicExtendedA::ArabicLetterYehWithTwoDotsBelowAndSmallNoonAbove => 'เขบ', ArabicExtendedA::ArabicLetterAfricanFeh => 'เขป', ArabicExtendedA::ArabicLetterAfricanQaf => 'เขผ', ArabicExtendedA::ArabicLetterAfricanNoon => 'เขฝ', ArabicExtendedA::ArabicSmallLowWaw => 'เฃ“', ArabicExtendedA::ArabicSmallHighWordArDashRub => 'เฃ”', ArabicExtendedA::ArabicSmallHighSad => 'เฃ•', ArabicExtendedA::ArabicSmallHighAin => 'เฃ–', ArabicExtendedA::ArabicSmallHighQaf => 'เฃ—', ArabicExtendedA::ArabicSmallHighNoonWithKasra => 'เฃ˜', ArabicExtendedA::ArabicSmallLowNoonWithKasra => 'เฃ™', ArabicExtendedA::ArabicSmallHighWordAthDashThalatha => 'เฃš', ArabicExtendedA::ArabicSmallHighWordAsDashSajda => 'เฃ›', ArabicExtendedA::ArabicSmallHighWordAnDashNisf => 'เฃœ', ArabicExtendedA::ArabicSmallHighWordSakta => 'เฃ', ArabicExtendedA::ArabicSmallHighWordQif => 'เฃž', ArabicExtendedA::ArabicSmallHighWordWaqfa => 'เฃŸ', ArabicExtendedA::ArabicSmallHighFootnoteMarker => 'เฃ ', ArabicExtendedA::ArabicSmallHighSignSafha => 'เฃก', ArabicExtendedA::ArabicDisputedEndOfAyah => 'เฃข', ArabicExtendedA::ArabicTurnedDammaBelow => 'เฃฃ', ArabicExtendedA::ArabicCurlyFatha => 'เฃค', ArabicExtendedA::ArabicCurlyDamma => 'เฃฅ', ArabicExtendedA::ArabicCurlyKasra => 'เฃฆ', ArabicExtendedA::ArabicCurlyFathatan => 'เฃง', ArabicExtendedA::ArabicCurlyDammatan => 'เฃจ', ArabicExtendedA::ArabicCurlyKasratan => 'เฃฉ', ArabicExtendedA::ArabicToneOneDotAbove => 'เฃช', ArabicExtendedA::ArabicToneTwoDotsAbove => 'เฃซ', ArabicExtendedA::ArabicToneLoopAbove => 'เฃฌ', ArabicExtendedA::ArabicToneOneDotBelow => 'เฃญ', ArabicExtendedA::ArabicToneTwoDotsBelow => 'เฃฎ', ArabicExtendedA::ArabicToneLoopBelow => 'เฃฏ', ArabicExtendedA::ArabicOpenFathatan => 'เฃฐ', ArabicExtendedA::ArabicOpenDammatan => 'เฃฑ', ArabicExtendedA::ArabicOpenKasratan => 'เฃฒ', ArabicExtendedA::ArabicSmallHighWaw => 'เฃณ', ArabicExtendedA::ArabicFathaWithRing => 'เฃด', ArabicExtendedA::ArabicFathaWithDotAbove => 'เฃต', ArabicExtendedA::ArabicKasraWithDotBelow => 'เฃถ', ArabicExtendedA::ArabicLeftArrowheadAbove => 'เฃท', ArabicExtendedA::ArabicRightArrowheadAbove => 'เฃธ', ArabicExtendedA::ArabicLeftArrowheadBelow => 'เฃน', ArabicExtendedA::ArabicRightArrowheadBelow => 'เฃบ', ArabicExtendedA::ArabicDoubleRightArrowheadAbove => 'เฃป', ArabicExtendedA::ArabicDoubleRightArrowheadAboveWithDot => 'เฃผ', ArabicExtendedA::ArabicRightArrowheadAboveWithDot => 'เฃฝ', ArabicExtendedA::ArabicDammaWithDot => 'เฃพ', } } } impl std::convert::TryFrom<char> for ArabicExtendedA { type Error = (); fn try_from(c: char) -> Result<Self, Self::Error> { match c { 'เข ' => Ok(ArabicExtendedA::ArabicLetterBehWithSmallVBelow), 'เขก' => Ok(ArabicExtendedA::ArabicLetterBehWithHamzaAbove), 'เขข' => Ok(ArabicExtendedA::ArabicLetterJeemWithTwoDotsAbove), 'เขฃ' => Ok(ArabicExtendedA::ArabicLetterTahWithTwoDotsAbove), 'เขค' => Ok(ArabicExtendedA::ArabicLetterFehWithDotBelowAndThreeDotsAbove), 'เขฅ' => Ok(ArabicExtendedA::ArabicLetterQafWithDotBelow), 'เขฆ' => Ok(ArabicExtendedA::ArabicLetterLamWithDoubleBar), 'เขง' => Ok(ArabicExtendedA::ArabicLetterMeemWithThreeDotsAbove), 'เขจ' => Ok(ArabicExtendedA::ArabicLetterYehWithTwoDotsBelowAndHamzaAbove), 'เขฉ' => Ok(ArabicExtendedA::ArabicLetterYehWithTwoDotsBelowAndDotAbove), 'เขช' => Ok(ArabicExtendedA::ArabicLetterRehWithLoop), 'เขซ' => Ok(ArabicExtendedA::ArabicLetterWawWithDotWithin), 'เขฌ' => Ok(ArabicExtendedA::ArabicLetterRohingyaYeh), 'เขญ' => Ok(ArabicExtendedA::ArabicLetterLowAlef), 'เขฎ' => Ok(ArabicExtendedA::ArabicLetterDalWithThreeDotsBelow), 'เขฏ' => Ok(ArabicExtendedA::ArabicLetterSadWithThreeDotsBelow), 'เขฐ' => Ok(ArabicExtendedA::ArabicLetterGafWithInvertedStroke), 'เขฑ' => Ok(ArabicExtendedA::ArabicLetterStraightWaw), 'เขฒ' => Ok(ArabicExtendedA::ArabicLetterZainWithInvertedVAbove), 'เขณ' => Ok(ArabicExtendedA::ArabicLetterAinWithThreeDotsBelow), 'เขด' => Ok(ArabicExtendedA::ArabicLetterKafWithDotBelow), 'เขถ' => Ok(ArabicExtendedA::ArabicLetterBehWithSmallMeemAbove), 'เขท' => Ok(ArabicExtendedA::ArabicLetterPehWithSmallMeemAbove), 'เขธ' => Ok(ArabicExtendedA::ArabicLetterTehWithSmallTehAbove), 'เขน' => Ok(ArabicExtendedA::ArabicLetterRehWithSmallNoonAbove), 'เขบ' => Ok(ArabicExtendedA::ArabicLetterYehWithTwoDotsBelowAndSmallNoonAbove), 'เขป' => Ok(ArabicExtendedA::ArabicLetterAfricanFeh), 'เขผ' => Ok(ArabicExtendedA::ArabicLetterAfricanQaf), 'เขฝ' => Ok(ArabicExtendedA::ArabicLetterAfricanNoon), 'เฃ“' => Ok(ArabicExtendedA::ArabicSmallLowWaw), 'เฃ”' => Ok(ArabicExtendedA::ArabicSmallHighWordArDashRub), 'เฃ•' => Ok(ArabicExtendedA::ArabicSmallHighSad), 'เฃ–' => Ok(ArabicExtendedA::ArabicSmallHighAin), 'เฃ—' => Ok(ArabicExtendedA::ArabicSmallHighQaf), 'เฃ˜' => Ok(ArabicExtendedA::ArabicSmallHighNoonWithKasra), 'เฃ™' => Ok(ArabicExtendedA::ArabicSmallLowNoonWithKasra), 'เฃš' => Ok(ArabicExtendedA::ArabicSmallHighWordAthDashThalatha), 'เฃ›' => Ok(ArabicExtendedA::ArabicSmallHighWordAsDashSajda), 'เฃœ' => Ok(ArabicExtendedA::ArabicSmallHighWordAnDashNisf), 'เฃ' => Ok(ArabicExtendedA::ArabicSmallHighWordSakta), 'เฃž' => Ok(ArabicExtendedA::ArabicSmallHighWordQif), 'เฃŸ' => Ok(ArabicExtendedA::ArabicSmallHighWordWaqfa), 'เฃ ' => Ok(ArabicExtendedA::ArabicSmallHighFootnoteMarker), 'เฃก' => Ok(ArabicExtendedA::ArabicSmallHighSignSafha), 'เฃข' => Ok(ArabicExtendedA::ArabicDisputedEndOfAyah), 'เฃฃ' => Ok(ArabicExtendedA::ArabicTurnedDammaBelow), 'เฃค' => Ok(ArabicExtendedA::ArabicCurlyFatha), 'เฃฅ' => Ok(ArabicExtendedA::ArabicCurlyDamma), 'เฃฆ' => Ok(ArabicExtendedA::ArabicCurlyKasra), 'เฃง' => Ok(ArabicExtendedA::ArabicCurlyFathatan), 'เฃจ' => Ok(ArabicExtendedA::ArabicCurlyDammatan), 'เฃฉ' => Ok(ArabicExtendedA::ArabicCurlyKasratan), 'เฃช' => Ok(ArabicExtendedA::ArabicToneOneDotAbove), 'เฃซ' => Ok(ArabicExtendedA::ArabicToneTwoDotsAbove), 'เฃฌ' => Ok(ArabicExtendedA::ArabicToneLoopAbove), 'เฃญ' => Ok(ArabicExtendedA::ArabicToneOneDotBelow), 'เฃฎ' => Ok(ArabicExtendedA::ArabicToneTwoDotsBelow), 'เฃฏ' => Ok(ArabicExtendedA::ArabicToneLoopBelow), 'เฃฐ' => Ok(ArabicExtendedA::ArabicOpenFathatan), 'เฃฑ' => Ok(ArabicExtendedA::ArabicOpenDammatan), 'เฃฒ' => Ok(ArabicExtendedA::ArabicOpenKasratan), 'เฃณ' => Ok(ArabicExtendedA::ArabicSmallHighWaw), 'เฃด' => Ok(ArabicExtendedA::ArabicFathaWithRing), 'เฃต' => Ok(ArabicExtendedA::ArabicFathaWithDotAbove), 'เฃถ' => Ok(ArabicExtendedA::ArabicKasraWithDotBelow), 'เฃท' => Ok(ArabicExtendedA::ArabicLeftArrowheadAbove), 'เฃธ' => Ok(ArabicExtendedA::ArabicRightArrowheadAbove), 'เฃน' => Ok(ArabicExtendedA::ArabicLeftArrowheadBelow), 'เฃบ' => Ok(ArabicExtendedA::ArabicRightArrowheadBelow), 'เฃป' => Ok(ArabicExtendedA::ArabicDoubleRightArrowheadAbove), 'เฃผ' => Ok(ArabicExtendedA::ArabicDoubleRightArrowheadAboveWithDot), 'เฃฝ' => Ok(ArabicExtendedA::ArabicRightArrowheadAboveWithDot), 'เฃพ' => Ok(ArabicExtendedA::ArabicDammaWithDot), _ => Err(()), } } } impl Into<u32> for ArabicExtendedA { fn into(self) -> u32 { let c: char = self.into(); let hex = c .escape_unicode() .to_string() .replace("\\u{", "") .replace("}", ""); u32::from_str_radix(&hex, 16).unwrap() } } impl std::convert::TryFrom<u32> for ArabicExtendedA { type Error = (); fn try_from(u: u32) -> Result<Self, Self::Error> { if let Ok(c) = char::try_from(u) { Self::try_from(c) } else { Err(()) } } } impl Iterator for ArabicExtendedA { type Item = Self; fn next(&mut self) -> Option<Self> { let index: u32 = (*self).into(); use std::convert::TryFrom; Self::try_from(index + 1).ok() } } impl ArabicExtendedA { /// The character with the lowest index in this unicode block pub fn new() -> Self { ArabicExtendedA::ArabicLetterBehWithSmallVBelow } /// The character's name, in sentence case pub fn name(&self) -> String { let s = std::format!("ArabicExtendedA{:#?}", self); string_morph::to_sentence_case(&s) } }
extern crate docopt; extern crate pbr; extern crate rustc_serialize; use std::cmp; use std::fs::File; use std::io::{BufWriter, Write}; use std::iter; use docopt::Docopt; use pbr::ProgressBar; const USAGE: &'static str = " Lines Generate many many lines of \"hi\" Usage: lines <count> <file> lines (-h | --help) Options: -h --help Show this screen. "; #[derive(Debug, RustcDecodable)] struct Args { arg_count: usize, arg_file: String, } const ITERATION_SIZE: usize = 65535; // TODO: Configure string, configure buffer size fn main() { let args: Args = Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); println!("{} lines to {}", args.arg_count, args.arg_file); let payload = b"hi\n"; let buffer: Vec<u8> = iter::repeat(payload) .take(ITERATION_SIZE) .cloned() .flat_map(|s| s.to_vec()) .collect(); let iterations = args.arg_count / ITERATION_SIZE; let iterations = if args.arg_count % ITERATION_SIZE > 0 { iterations + 1 } else { iterations }; let file = File::create(&args.arg_file).expect("Cannot create file"); let mut writer = BufWriter::with_capacity(buffer.len(), file); let mut pb = ProgressBar::new(args.arg_count as u64); pb.format("โ•ขโ–Œโ–Œโ–‘โ•Ÿ"); for iteration in 0..iterations { let start_count = iteration * ITERATION_SIZE; let end_count = cmp::min(start_count + ITERATION_SIZE, args.arg_count); let iteration_count = end_count - start_count; let bytes_count = iteration_count * payload.len(); writer .write_all(&buffer[0..bytes_count]) .expect("Cannot write buffer to file"); pb.add(iteration_count as u64); } pb.finish_print("Done"); } // TODO: Add test
use amethyst::{ SimpleState, StateData, GameData, StateEvent, Trans, SimpleTrans, input::{is_mouse_button_down}, ui::{Anchor, UiLabelBuilder, UiEvent, UiCreator}, prelude::* }; use crate::components::*; use amethyst::renderer::rendy::wsi::winit::MouseButton; use amethyst::core::ecs::shred::ResourceId; use amethyst::core::ecs::Entity; use crate::state::game::Game; use crate::components::score::Score; #[derive(Default)] pub struct Title { title_label : Option<Entity> } impl SimpleState for Title { fn on_start(&mut self, data: StateData<'_, GameData<'_, '_>>) { let StateData { mut world, .. } = data; stage::initialize(world); player::initialize(world); block::initialize(world); score::initialize(world); world.exec(|mut creator: UiCreator<'_>| { self.title_label = Some(creator.create("ui/title/screen.ron", ())); }); } fn handle_event(&mut self, data: StateData<'_, GameData<'_, '_>>, event: StateEvent) -> SimpleTrans { let StateData { mut world, .. } = data; if let StateEvent::Window(event) = &event { if is_mouse_button_down(&event, MouseButton::Left) { let mut entity = self.title_label.unwrap(); world.delete_entity(entity); return Trans::Switch(Box::new(Game::default())) } } Trans::None } }
use alga::general::AbstractMonoid; use alga::general::AbstractMagma; use alga::general::Operator; use alga::general::Identity; use crate::TimeWindow; use crate::flat_fat::fat::FAT; use crate::flat_fat::flat_fat::FlatFAT; use crate::flat_fat::item::{Item,Combine}; pub struct TimeRA<Value, BinOp> where Value: AbstractMonoid<BinOp> + Clone+std::fmt::Debug, BinOp: Operator + std::fmt::Debug, { fat: FlatFAT<Item<Value, BinOp>, Combine>, size: usize, front: usize, back: usize, } impl<Value, BinOp> TimeRA<Value, BinOp> where Value: AbstractMonoid<BinOp> + Clone+std::fmt::Debug, BinOp: Operator + std::fmt::Debug, { fn with_capacity(capacity: usize) -> Self { TimeRA { fat: FlatFAT::with_capacity(capacity), size: 0, front: 0, back: 0, } } fn resize(&mut self) { } } impl<Value, BinOp> TimeWindow<usize, Value, BinOp> for TimeRA<Value, BinOp> where Value: AbstractMonoid<BinOp> + Clone+std::fmt::Debug, BinOp: Operator + std::fmt::Debug, { fn new() -> Self { TimeRA { fat: FlatFAT::with_capacity(0), size: 0, front: 0, back: 0, } } fn insert(&mut self, t: usize, v: Value) { self.size += 1; if self.size <= (3 * self.fat.capacity) / 4 { } } fn evict(&mut self, t: usize) { self.fat.update(&[(t, Item::identity())]); self.size -= 1; if self.size <= self.fat.capacity / 4 { } } fn query(&self) -> Value { if self.front < self.back { self.fat.suffix(self.front).operate(&self.fat.prefix(self.back)) } else { self.fat.aggregate() }.get_value() } }
use chrono::prelude::*; use std::fmt; use std::time::{Duration, UNIX_EPOCH}; use tonic::Code; mod discount_types; pub struct ServerError { pub code: Code, pub message: String, } // Implement std::fmt::Debug for ServerError impl fmt::Display for ServerError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "An Error Occurred, {}", self.message) // user-facing output } } // Implement std::fmt::Debug for ServerError impl fmt::Debug for ServerError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{{ file: {}, line: {}, message: {} }}", file!(), line!(), self.message ) } } pub struct UserDiscount { pub user_id: String, pub date_of_birth: u64, pub price: i32, } pub struct DiscountProduct { pub value: i32, pub discount_rate: i32, pub new_price: i32, } pub fn calculate_discount(user_discount: UserDiscount) -> Result<DiscountProduct, ServerError> { println!("Calculating discounts for user: {}", user_discount.user_id); let price = price_to_float(user_discount.price); let rate = get_user_discount(user_discount.date_of_birth)?; let discount_product = DiscountProduct { value: user_discount.price, discount_rate: float_to_price(rate), new_price: float_to_price(price * (1.0 - rate)), }; Ok(discount_product) } fn price_to_float(value: i32) -> f32 { let float_value = value as f32; float_value / 100.0 } fn float_to_price(value: f32) -> i32 { (value * 100.0) as i32 } fn get_user_discount(birthday: u64) -> Result<f32, ServerError> { let unix_date = UNIX_EPOCH + Duration::from_secs(birthday); let birthday = DateTime::<Utc>::from(unix_date); let now = Local::today(); let rate = if now.day() == 25 && now.month() == 11 { discount_types::Types::BlackFriday } else if now.day() == birthday.day() && now.month() == birthday.month() { discount_types::Types::Birthday } else { return Err(ServerError { message: "Not elegible for discount".to_string(), code: Code::NotFound, }); }; Ok(discount_types::discount_rates(rate)) } #[cfg(test)] mod tests { // Note this useful idiom: importing names from outer (for mod tests) scope. use super::*; #[test] fn test_birthday_discount() { let today = Local::now(); let resp = get_user_discount(today.timestamp() as u64).unwrap(); assert_eq!(resp, 0.05); } #[test] fn test_discount_error() { let date = Local.ymd(2014, 7, 8).and_hms(9, 10, 11); match get_user_discount(date.timestamp() as u64) { Ok(_) => assert!(false, "Should return error"), Err(_) => assert!(true), } } }
use actix_web::{HttpRequest, Responder}; pub fn index(_req: &HttpRequest) -> impl Responder { "version: 1.0" }
use std::collections::HashMap; use std::ops::Deref; pub struct KvStore { data: HashMap<String, String>, } impl KvStore { pub fn new() -> KvStore { KvStore { data: HashMap::new(), } } pub fn get(&mut self, key: String) -> Option<String> { match self.data.get(&key) { Some(val) => Some(val.parse::<String>().unwrap()), _ => None, } } pub fn set(&mut self, key: String, value: String) { self.data.insert(key, value); } pub fn remove(&mut self, key: String) { match self.data.get(&key) { Some(val) => { self.data.remove(&key); } _ => {} } } }
///How to write a Virtual Dom in Rust ///inspired from https://medium.com/@deathmood/how-to-write-your-own-virtual-dom-ee74acc13060 /// use html_parser::{ Dom, Node }; use html_parser::Element; use wasm_bindgen::prelude::*; use std::panic; use web_sys::console; macro_rules! log { ( $( $t:tt )* ) => { web_sys::console::log_1(&format!( $( $t )* ).into()); } } static html:&str = "<ul class='list'> <p> <li>item1</li> <li>item2</li> </p> </ul>"; /// /// Sample DOM elements like /// { tag:'..', props: '..' ,childern: [..] } /// /// DOM text nodes would be plain Strings /// /// //type NodeResult = Result<Node1,MyError>; ///Virtual DOM pub struct VirtualDom{ parent:Node1, // nodes:Vec<Box<Node>>, } impl VirtualDom{ fn new(root:Node1) ->Self{ VirtualDom{ parent:root, } } } #[derive(Debug)] pub struct Node1{ tag:String, props:Vec<String>, children:Vec<Node>, } pub fn parseNode(htl:&str) { let dm = Dom::parse(&htl).unwrap(); println!("{:?}",dm); let mut i = 0; let mut parentchild = dm.children.clone(); PrintElement(parentchild); } fn PrintElement(vecnode: Vec<Node>){ for child in vecnode{ match child { Node::Element(x) => { println!("{}",x.name); PrintElement(x.children); createElement(x.name.as_str()); } Node::Text(x) => { println!("{}",x); createText(x.as_str()); } _ => { println!("end of element");} } } // println!("{:?}",child); /* while let Node::Element(ref p) = parentchild{ let MychildNodeIter = p.children.clone(); let mut i =0; for child in MychildNodeIter{ if let Node::Element(x) = &child{ let nod = Node1{ tag:x.name.clone(), props:x.classes.clone(), children: x.children.clone(), }; println!("{}",nod.tag); // createElement(&nod); parentchild = nod.children[i].clone(); i += 1; } } } */ #[cfg(feature = "debug")] panic::set_hook(Box::new(console_error_panic_hook::hook)); // Node::Text(t) => {println!("{}",t);}, // Node::Comment(s) => { println!( "comment");}, // _ => { println!("unreachable")}, } #[wasm_bindgen(start)] pub fn run() -> Result<(),JsValue>{ parseNode(html); // let current = &node.children; // let mut i =0; // while !current.is_empty() { // createElement(&node)?; // current = &node.children[i]; // i=i+1; // } Ok(()) } pub fn createElement(tag:&str) -> Result<(),JsValue> { let window = web_sys::window().expect("no global window exists"); let document = window.document().expect("should have a document window"); let body = document.body().expect("document should have a body"); let val = document.create_element(tag)?; val.set_inner_html("hello rust"); body.append_child(&val)?; Ok(()) } pub fn createText(text:&str) -> Result<(),JsValue> { let window = web_sys::window().expect("no global window exists"); let document = window.document().expect("should have a document window"); let body = document.body().expect("document should have a body"); console::log_1(&text.into()); let val = document.create_comment(text); // val.set_inner_html("hello rust"); body.append_child(&val)?; Ok(()) } #[cfg(test)] mod tests{ use super::*; #[test] fn it_works(){ parseNode(html); } }
use crate::{entry_functions, expressions, types}; use std::collections::HashMap; pub fn compile_definition( module_builder: &fmm::build::ModuleBuilder, definition: &pir::ir::Definition, global_variables: &HashMap<String, fmm::build::TypedExpression>, types: &HashMap<String, pir::types::RecordBody>, ) -> Result<(), fmm::build::BuildError> { module_builder.define_variable( definition.name(), fmm::build::record(vec![ entry_functions::compile(module_builder, definition, global_variables, types)?, expressions::compile_arity(definition.arguments().iter().count()).into(), fmm::ir::Undefined::new(types::compile_closure_payload(definition, types)).into(), ]), definition.is_thunk(), fmm::ir::Linkage::External, ); Ok(()) }
use crate::prelude::*; use bitvec::prelude::*; fn solve(disc_size: usize, seed: BitVec) -> Result<String> { if disc_size % 2 != 0 { return Err(anyhow!("disc size must be even")); } let mut buf: BitVec = seed; let mut double_buf: BitVec = BitVec::with_capacity(disc_size * 2); buf.reserve(disc_size * 2); // Dragon curve-like expansion of data while buf.len() < disc_size { let len = buf.len(); double_buf.extend(buf.iter()); double_buf.push(false); double_buf.append(&mut buf); (!&mut double_buf[len + 1..]).reverse(); buf.clear(); std::mem::swap(&mut buf, &mut double_buf); } buf.truncate(disc_size); std::mem::drop(double_buf); // Checksum loop { for i in 0..buf.len() / 2 { let checksum_digit = buf[i * 2 + 0] == buf[i * 2 + 1]; buf.as_mut_bitslice().set(i, checksum_digit); } buf.truncate(buf.len() / 2); if buf.len() % 2 == 1 { break; } } Ok(buf.into_iter().map(|b| if b { '1' } else { '0' }).collect()) } pub fn pt1(input: BitVec) -> Result<String> { solve(272, input) } pub fn pt2(input: BitVec) -> Result<String> { solve(35651584, input) } pub fn parse(s: &str) -> IResult<&str, BitVec> { use parsers::*; fold_many1(one_of("01"), || BitVec::with_capacity(s.len()), |mut v, c| { v.push(c == '1'); v })(s) } #[test] fn day16() -> Result<()> { test_part!(parse, |input| solve(20, input), "10000" => "01100"); Ok(()) }
//! Implementation of the simulation's calculations and logic. use super::io::{Score, IO}; /// Lander simulation /// /// The terse member names come from the names of global variables in the /// original FOCAL code. #[derive(Copy, Clone, Default)] pub struct Lander { /// Altitude (miles) pub a: f64, /// Gravity pub g: f64, /// Intermediate altitude (miles) i: f64, /// Intermediate velocity (miles/sec) j: f64, /// Fuel rate (lbs/sec) pub k: f64, /// Elapsed time (sec) pub l: f64, /// Total weight (lbs) pub m: f64, /// Empty weight (lbs) pub n: f64, /// Time elapsed in current 10-second turn (sec) s: f64, /// Time remaining in current 10-second turn (sec) t: f64, /// Downward speed (miles/sec) pub v: f64, /// Thrust per pound of fuel burned pub z: f64, } impl Lander { /// Run the simulation until the lander is on the moon. /// /// Methods of the `IO` object will be called to get input and report /// results. pub fn play_game(&mut self, io: &mut dyn IO) { self.a = 120.0; self.v = 1.0; self.m = 32500.0; self.n = 16500.0; self.g = 0.001; self.z = 1.8; self.l = 0.0; io.start_game(self); self.start_turn(io); } /// Returns elapsed time in seconds pub fn elapsed_secs(&self) -> f64 { return self.l; } /// Returns altitude in miles pub fn altitude(&self) -> f64 { return self.a; } /// Returns downward speed as miles/hour pub fn v_mph(&self) -> f64 { 3600.0 * self.v } /// Returns pounds of fuel remaining pub fn fuel_remaining(&self) -> f64 { self.m - self.n } fn start_turn(&mut self, io: &mut dyn IO) { // 02.10 in original FOCAL code self.k = io.get_fuel_rate(self); self.t = 10.0; self.turn_loop(io); } fn turn_loop(&mut self, io: &mut dyn IO) { // 03.10 in original FOCAL code loop { if self.fuel_remaining() < 0.001 { self.fuel_out(io); return; } if self.t < 0.001 { self.start_turn(io); return; } self.s = self.t; if self.n + self.s * self.k - self.m > 0.0 { self.s = (self.m - self.n) / self.k; } self.apply_thrust(); if self.i <= 0.0 { self.loop_until_on_the_moon(io); return; } if (self.v > 0.0) && (self.j < 0.0) { // 08.10 in original FOCAL code loop { // FOCAL-to-Rust gotcha: In FOCAL, multiplication has a // higher precedence than division. In Rust, they have the // same precedence and are evaluated left-to-right. So the // original FOCAL subexpression `M * G / Z * K` can't be // copied as-is into Rust: `Z * K` has to be parenthesized // to get the same result. let w = (1.0 - self.m * self.g / (self.z * self.k)) / 2.0; self.s = self.m * self.v / (self.z * self.k * (w + (w * w + self.v / self.z).sqrt())) + 0.5; self.apply_thrust(); if self.i <= 0.0 { self.loop_until_on_the_moon(io); return; } self.update_state(); if self.j >= 0.0 || self.v <= 0.0 { self.turn_loop(io); return; } } } self.update_state(); } } fn loop_until_on_the_moon(&mut self, io: &mut dyn IO) { // 07.10 in original FOCAL code while self.s >= 0.005 { let d = self.v + (self.v * self.v + 2.0 * self.a * (self.g - self.z * self.k / self.m)).sqrt(); self.s = 2.0 * self.a / d; self.apply_thrust(); self.update_state(); } self.on_the_moon(io); } fn fuel_out(&mut self, io: &mut dyn IO) { // 04.10 in original FOCAL code io.fuel_out(self.l); self.s = ((self.v * self.v + 2.0 * self.a * self.g).sqrt() - self.v) / self.g; self.v += self.g * self.s; self.l += self.s; self.on_the_moon(io); return; } fn on_the_moon(&mut self, io: &mut dyn IO) { // 05.10 in original FOCAL code let w = self.v_mph(); let score = if w <= 1.0 { Score::Perfect } else if w <= 10.0 { Score::Good } else if w <= 22.0 { Score::Poor } else if w <= 40.0 { Score::CraftDamage } else if w <= 60.0 { Score::CrashLanding } else { Score::NoSurvivors(w * 0.277_277) }; io.on_the_moon(self, score) // fall out to unwind and exit play_game() } fn update_state(&mut self) { // Subroutine at line 06.10 in original FOCAL code self.l += self.s; self.t -= self.s; self.m -= self.s * self.k; self.a = self.i; self.v = self.j; } fn apply_thrust(&mut self) { // Subroutine at line 09.10 in original FOCAL code let q = self.s * self.k / self.m; let q_2 = q.powi(2); let q_3 = q.powi(3); let q_4 = q.powi(4); let q_5 = q.powi(5); self.j = self.v + self.g * self.s + self.z * (-q - q * q / 2.0 - q_3 / 3.0 - q_4 / 4.0 - q_5 / 5.0); self.i = self.a - self.g * self.s * self.s / 2.0 - self.v * self.s + self.z * self.s * (q / 2.0 + q_2 / 6.0 + q_3 / 12.0 + q_4 / 20.0 + q_5 / 30.0); } }
use std::io::prelude::*; use std::io::SeekFrom; use std::os::unix::io::{AsRawFd, RawFd}; use mio::{EventLoop, Handler, Token, EventSet, PollOpt}; use sys::{Edge, Selector, GPIOSelector, GPIOPinSelector}; use {Result, Error, Logic, DigitalLogic, DigitalWrite, DigitalRead, is_root}; #[derive(Debug)] pub struct Pin { pin: usize, exported: bool } impl Pin { pub unsafe fn new(pin: usize) -> Pin { Pin { pin: pin, exported: false } } pub fn export(&mut self) -> Result<()> { if !is_root() { return Err(Error::RootRequired) } // re-export let _ = GPIOSelector::write("unexport", self.pin); try!(GPIOSelector::write("export", self.pin)); self.exported = true; Ok(()) } pub fn input(&self) -> Result<PinInput> { // Set direction to in try!(GPIOPinSelector::write(self.pin, "direction", "in")); // Open value file let sel = try!(GPIOPinSelector::open_rd(self.pin, "value")); Ok(PinInput { sel: sel, pin: self.pin }) } pub fn output(&self) -> Result<PinOutput> { // Set direction to out try!(GPIOPinSelector::write(self.pin, "direction", "out")); // Open value file let sel = try!(GPIOPinSelector::open(self.pin, "value")); Ok(PinOutput { sel: sel, pin: self.pin }) } } impl Drop for Pin { fn drop(&mut self) { if self.exported { let _ = GPIOSelector::write("unexport", self.pin); } } } #[derive(Debug)] pub struct PinInput { sel: Selector, pin: usize } impl DigitalRead for PinInput { fn digital_read(&mut self) -> Result<Logic> { try!(self.sel.seek(SeekFrom::Start(0))); let mut buf = [0u8]; let len = try!(self.sel.read(&mut buf)); if len == 0 { return Err(Error::UnexpectedError); } match buf[0] { b'1' => Ok(Logic::High), b'0' => Ok(Logic::Low), _ => Err(Error::UnexpectedError), } } } impl PinInput { pub fn trigger<H: Handler>(&mut self, event_loop: &mut EventLoop<H>, token: Token, edge: Edge) -> Result<()> { // Set edge for trigger try!(self.set_edge(edge)); // Clear io buffer let mut s = String::with_capacity(255); try!(self.sel.read_to_string(&mut s)); // Register sel try!(event_loop.register(&self.sel, token, EventSet::readable(), PollOpt::edge() | PollOpt::urgent() )); Ok(()) } pub fn stop_trigger<H: Handler>(&mut self, event_loop: &mut EventLoop<H>) -> Result<()> { try!(event_loop.deregister(&self.sel)); Ok(()) } fn set_edge(&mut self, edge: Edge) -> Result<()> { try!(GPIOPinSelector::write(self.pin, "edge", match edge { Edge::NoInterrupt => "none", Edge::RisingEdge => "rising", Edge::FallingEdge => "falling", Edge::BothEdges => "both", })); Ok(()) } } impl AsRawFd for PinInput { fn as_raw_fd(&self) -> RawFd { self.sel.as_raw_fd() } } #[derive(Debug)] pub struct PinOutput { sel: Selector, pin: usize } impl DigitalWrite for PinOutput { fn digital_write<L: DigitalLogic>(&mut self, level: L) -> Result<()> { let buf: [u8;1] = match level.logic_level() { Logic::High => [b'1'], Logic::Low => [b'0'], }; let _ = try!(self.sel.write(&buf)); Ok(()) } } impl AsRawFd for PinOutput { fn as_raw_fd(&self) -> RawFd { self.sel.as_raw_fd() } }
use std::sync::Arc; use super::{MongoProductDao, MongoSourceDao, MongoWishlistDao}; use crate::persistence::{ProductDao, SourceDao, WishlistDao}; lazy_static! { static ref PRODUCT_DAO: Option<Arc<MongoProductDao>> = MongoProductDao::new().map(Arc::new).ok(); static ref WISHLIST_DAO: Option<Arc<MongoWishlistDao>> = MongoWishlistDao::new().map(Arc::new).ok(); static ref SOURCE_DAO: Option<Arc<MongoSourceDao>> = MongoSourceDao::new().map(Arc::new).ok(); } pub fn get_product_dao() -> Option<Arc<MongoProductDao>> { (*PRODUCT_DAO).clone() } pub fn get_wishlist_dao() -> Option<Arc<MongoWishlistDao>> { (*WISHLIST_DAO).clone() } pub fn get_source_dao() -> Option<Arc<MongoSourceDao>> { (*SOURCE_DAO).clone() }
use super::alias_from_arg_or_channel_name; use serenity::framework::standard::{Args, CommandError}; use serenity::model::channel::Message; use serenity::prelude::Context; use crate::db::DbConnectionKey; pub fn describe( context: &mut Context, message: &Message, mut args: Args, ) -> Result<(), CommandError> { let data = context.data.lock(); let db_conn = data .get::<DbConnectionKey>() .ok_or("No DbConnection was created on startup. This is a bug.")?; let description = args.single_quoted::<String>()?; let alias = alias_from_arg_or_channel_name(&mut args, &message)?; if !args.is_empty() { return Err(CommandError::from( "Too many arguments. TIP: the description needs to be in quotes", )); } db_conn.update_lobby_with_description(&alias, &description)?; message.reply(&format!("added description to {}", alias))?; Ok(()) }
fn main() { let name = String::from("Umair"); let name_length = name.len(); println!("{}",name_length); let age = [20,22,24,26]; //element 0 1 2 3 4 5 6 7 8 9 let temp = 9; println!("Age is : {}",age[temp]); //age.9 //tuple calling //age[3] //array calling // age[9] //println!("Age is : {:#?}",age.get(2)); }
// Generated from vec.rs.tera template. Edit the template, not the generated file. use crate::{BVec2, I64Vec2, IVec2, U64Vec2, UVec3}; #[cfg(not(target_arch = "spirv"))] use core::fmt; use core::iter::{Product, Sum}; use core::{f32, ops::*}; /// Creates a 2-dimensional vector. #[inline(always)] pub const fn uvec2(x: u32, y: u32) -> UVec2 { UVec2::new(x, y) } /// A 2-dimensional vector. #[cfg_attr(not(target_arch = "spirv"), derive(Hash))] #[derive(Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "cuda", repr(align(8)))] #[cfg_attr(not(target_arch = "spirv"), repr(C))] #[cfg_attr(target_arch = "spirv", repr(simd))] pub struct UVec2 { pub x: u32, pub y: u32, } impl UVec2 { /// All zeroes. pub const ZERO: Self = Self::splat(0); /// All ones. pub const ONE: Self = Self::splat(1); /// All `u32::MIN`. pub const MIN: Self = Self::splat(u32::MIN); /// All `u32::MAX`. pub const MAX: Self = Self::splat(u32::MAX); /// A unit vector pointing along the positive X axis. pub const X: Self = Self::new(1, 0); /// A unit vector pointing along the positive Y axis. pub const Y: Self = Self::new(0, 1); /// The unit axes. pub const AXES: [Self; 2] = [Self::X, Self::Y]; /// Creates a new vector. #[inline(always)] pub const fn new(x: u32, y: u32) -> Self { Self { x, y } } /// Creates a vector with all elements set to `v`. #[inline] pub const fn splat(v: u32) -> Self { Self { x: v, y: v } } /// Creates a vector from the elements in `if_true` and `if_false`, selecting which to use /// for each element of `self`. /// /// A true element in the mask uses the corresponding element from `if_true`, and false /// uses the element from `if_false`. #[inline] pub fn select(mask: BVec2, if_true: Self, if_false: Self) -> Self { Self { x: if mask.x { if_true.x } else { if_false.x }, y: if mask.y { if_true.y } else { if_false.y }, } } /// Creates a new vector from an array. #[inline] pub const fn from_array(a: [u32; 2]) -> Self { Self::new(a[0], a[1]) } /// `[x, y]` #[inline] pub const fn to_array(&self) -> [u32; 2] { [self.x, self.y] } /// Creates a vector from the first 2 values in `slice`. /// /// # Panics /// /// Panics if `slice` is less than 2 elements long. #[inline] pub const fn from_slice(slice: &[u32]) -> Self { Self::new(slice[0], slice[1]) } /// Writes the elements of `self` to the first 2 elements in `slice`. /// /// # Panics /// /// Panics if `slice` is less than 2 elements long. #[inline] pub fn write_to_slice(self, slice: &mut [u32]) { slice[0] = self.x; slice[1] = self.y; } /// Creates a 3D vector from `self` and the given `z` value. #[inline] pub const fn extend(self, z: u32) -> UVec3 { UVec3::new(self.x, self.y, z) } /// Computes the dot product of `self` and `rhs`. #[inline] pub fn dot(self, rhs: Self) -> u32 { (self.x * rhs.x) + (self.y * rhs.y) } /// Returns a vector where every component is the dot product of `self` and `rhs`. #[inline] pub fn dot_into_vec(self, rhs: Self) -> Self { Self::splat(self.dot(rhs)) } /// Returns a vector containing the minimum values for each element of `self` and `rhs`. /// /// In other words this computes `[self.x.min(rhs.x), self.y.min(rhs.y), ..]`. #[inline] pub fn min(self, rhs: Self) -> Self { Self { x: self.x.min(rhs.x), y: self.y.min(rhs.y), } } /// Returns a vector containing the maximum values for each element of `self` and `rhs`. /// /// In other words this computes `[self.x.max(rhs.x), self.y.max(rhs.y), ..]`. #[inline] pub fn max(self, rhs: Self) -> Self { Self { x: self.x.max(rhs.x), y: self.y.max(rhs.y), } } /// Component-wise clamping of values, similar to [`u32::clamp`]. /// /// Each element in `min` must be less-or-equal to the corresponding element in `max`. /// /// # Panics /// /// Will panic if `min` is greater than `max` when `glam_assert` is enabled. #[inline] pub fn clamp(self, min: Self, max: Self) -> Self { glam_assert!(min.cmple(max).all(), "clamp: expected min <= max"); self.max(min).min(max) } /// Returns the horizontal minimum of `self`. /// /// In other words this computes `min(x, y, ..)`. #[inline] pub fn min_element(self) -> u32 { self.x.min(self.y) } /// Returns the horizontal maximum of `self`. /// /// In other words this computes `max(x, y, ..)`. #[inline] pub fn max_element(self) -> u32 { self.x.max(self.y) } /// Returns a vector mask containing the result of a `==` comparison for each element of /// `self` and `rhs`. /// /// In other words, this computes `[self.x == rhs.x, self.y == rhs.y, ..]` for all /// elements. #[inline] pub fn cmpeq(self, rhs: Self) -> BVec2 { BVec2::new(self.x.eq(&rhs.x), self.y.eq(&rhs.y)) } /// Returns a vector mask containing the result of a `!=` comparison for each element of /// `self` and `rhs`. /// /// In other words this computes `[self.x != rhs.x, self.y != rhs.y, ..]` for all /// elements. #[inline] pub fn cmpne(self, rhs: Self) -> BVec2 { BVec2::new(self.x.ne(&rhs.x), self.y.ne(&rhs.y)) } /// Returns a vector mask containing the result of a `>=` comparison for each element of /// `self` and `rhs`. /// /// In other words this computes `[self.x >= rhs.x, self.y >= rhs.y, ..]` for all /// elements. #[inline] pub fn cmpge(self, rhs: Self) -> BVec2 { BVec2::new(self.x.ge(&rhs.x), self.y.ge(&rhs.y)) } /// Returns a vector mask containing the result of a `>` comparison for each element of /// `self` and `rhs`. /// /// In other words this computes `[self.x > rhs.x, self.y > rhs.y, ..]` for all /// elements. #[inline] pub fn cmpgt(self, rhs: Self) -> BVec2 { BVec2::new(self.x.gt(&rhs.x), self.y.gt(&rhs.y)) } /// Returns a vector mask containing the result of a `<=` comparison for each element of /// `self` and `rhs`. /// /// In other words this computes `[self.x <= rhs.x, self.y <= rhs.y, ..]` for all /// elements. #[inline] pub fn cmple(self, rhs: Self) -> BVec2 { BVec2::new(self.x.le(&rhs.x), self.y.le(&rhs.y)) } /// Returns a vector mask containing the result of a `<` comparison for each element of /// `self` and `rhs`. /// /// In other words this computes `[self.x < rhs.x, self.y < rhs.y, ..]` for all /// elements. #[inline] pub fn cmplt(self, rhs: Self) -> BVec2 { BVec2::new(self.x.lt(&rhs.x), self.y.lt(&rhs.y)) } /// Computes the squared length of `self`. #[doc(alias = "magnitude2")] #[inline] pub fn length_squared(self) -> u32 { self.dot(self) } /// Casts all elements of `self` to `f32`. #[inline] pub fn as_vec2(&self) -> crate::Vec2 { crate::Vec2::new(self.x as f32, self.y as f32) } /// Casts all elements of `self` to `f64`. #[inline] pub fn as_dvec2(&self) -> crate::DVec2 { crate::DVec2::new(self.x as f64, self.y as f64) } /// Casts all elements of `self` to `i32`. #[inline] pub fn as_ivec2(&self) -> crate::IVec2 { crate::IVec2::new(self.x as i32, self.y as i32) } /// Casts all elements of `self` to `i64`. #[inline] pub fn as_i64vec2(&self) -> crate::I64Vec2 { crate::I64Vec2::new(self.x as i64, self.y as i64) } /// Casts all elements of `self` to `u64`. #[inline] pub fn as_u64vec2(&self) -> crate::U64Vec2 { crate::U64Vec2::new(self.x as u64, self.y as u64) } } impl Default for UVec2 { #[inline(always)] fn default() -> Self { Self::ZERO } } impl Div<UVec2> for UVec2 { type Output = Self; #[inline] fn div(self, rhs: Self) -> Self { Self { x: self.x.div(rhs.x), y: self.y.div(rhs.y), } } } impl DivAssign<UVec2> for UVec2 { #[inline] fn div_assign(&mut self, rhs: Self) { self.x.div_assign(rhs.x); self.y.div_assign(rhs.y); } } impl Div<u32> for UVec2 { type Output = Self; #[inline] fn div(self, rhs: u32) -> Self { Self { x: self.x.div(rhs), y: self.y.div(rhs), } } } impl DivAssign<u32> for UVec2 { #[inline] fn div_assign(&mut self, rhs: u32) { self.x.div_assign(rhs); self.y.div_assign(rhs); } } impl Div<UVec2> for u32 { type Output = UVec2; #[inline] fn div(self, rhs: UVec2) -> UVec2 { UVec2 { x: self.div(rhs.x), y: self.div(rhs.y), } } } impl Mul<UVec2> for UVec2 { type Output = Self; #[inline] fn mul(self, rhs: Self) -> Self { Self { x: self.x.mul(rhs.x), y: self.y.mul(rhs.y), } } } impl MulAssign<UVec2> for UVec2 { #[inline] fn mul_assign(&mut self, rhs: Self) { self.x.mul_assign(rhs.x); self.y.mul_assign(rhs.y); } } impl Mul<u32> for UVec2 { type Output = Self; #[inline] fn mul(self, rhs: u32) -> Self { Self { x: self.x.mul(rhs), y: self.y.mul(rhs), } } } impl MulAssign<u32> for UVec2 { #[inline] fn mul_assign(&mut self, rhs: u32) { self.x.mul_assign(rhs); self.y.mul_assign(rhs); } } impl Mul<UVec2> for u32 { type Output = UVec2; #[inline] fn mul(self, rhs: UVec2) -> UVec2 { UVec2 { x: self.mul(rhs.x), y: self.mul(rhs.y), } } } impl Add<UVec2> for UVec2 { type Output = Self; #[inline] fn add(self, rhs: Self) -> Self { Self { x: self.x.add(rhs.x), y: self.y.add(rhs.y), } } } impl AddAssign<UVec2> for UVec2 { #[inline] fn add_assign(&mut self, rhs: Self) { self.x.add_assign(rhs.x); self.y.add_assign(rhs.y); } } impl Add<u32> for UVec2 { type Output = Self; #[inline] fn add(self, rhs: u32) -> Self { Self { x: self.x.add(rhs), y: self.y.add(rhs), } } } impl AddAssign<u32> for UVec2 { #[inline] fn add_assign(&mut self, rhs: u32) { self.x.add_assign(rhs); self.y.add_assign(rhs); } } impl Add<UVec2> for u32 { type Output = UVec2; #[inline] fn add(self, rhs: UVec2) -> UVec2 { UVec2 { x: self.add(rhs.x), y: self.add(rhs.y), } } } impl Sub<UVec2> for UVec2 { type Output = Self; #[inline] fn sub(self, rhs: Self) -> Self { Self { x: self.x.sub(rhs.x), y: self.y.sub(rhs.y), } } } impl SubAssign<UVec2> for UVec2 { #[inline] fn sub_assign(&mut self, rhs: UVec2) { self.x.sub_assign(rhs.x); self.y.sub_assign(rhs.y); } } impl Sub<u32> for UVec2 { type Output = Self; #[inline] fn sub(self, rhs: u32) -> Self { Self { x: self.x.sub(rhs), y: self.y.sub(rhs), } } } impl SubAssign<u32> for UVec2 { #[inline] fn sub_assign(&mut self, rhs: u32) { self.x.sub_assign(rhs); self.y.sub_assign(rhs); } } impl Sub<UVec2> for u32 { type Output = UVec2; #[inline] fn sub(self, rhs: UVec2) -> UVec2 { UVec2 { x: self.sub(rhs.x), y: self.sub(rhs.y), } } } impl Rem<UVec2> for UVec2 { type Output = Self; #[inline] fn rem(self, rhs: Self) -> Self { Self { x: self.x.rem(rhs.x), y: self.y.rem(rhs.y), } } } impl RemAssign<UVec2> for UVec2 { #[inline] fn rem_assign(&mut self, rhs: Self) { self.x.rem_assign(rhs.x); self.y.rem_assign(rhs.y); } } impl Rem<u32> for UVec2 { type Output = Self; #[inline] fn rem(self, rhs: u32) -> Self { Self { x: self.x.rem(rhs), y: self.y.rem(rhs), } } } impl RemAssign<u32> for UVec2 { #[inline] fn rem_assign(&mut self, rhs: u32) { self.x.rem_assign(rhs); self.y.rem_assign(rhs); } } impl Rem<UVec2> for u32 { type Output = UVec2; #[inline] fn rem(self, rhs: UVec2) -> UVec2 { UVec2 { x: self.rem(rhs.x), y: self.rem(rhs.y), } } } #[cfg(not(target_arch = "spirv"))] impl AsRef<[u32; 2]> for UVec2 { #[inline] fn as_ref(&self) -> &[u32; 2] { unsafe { &*(self as *const UVec2 as *const [u32; 2]) } } } #[cfg(not(target_arch = "spirv"))] impl AsMut<[u32; 2]> for UVec2 { #[inline] fn as_mut(&mut self) -> &mut [u32; 2] { unsafe { &mut *(self as *mut UVec2 as *mut [u32; 2]) } } } impl Sum for UVec2 { #[inline] fn sum<I>(iter: I) -> Self where I: Iterator<Item = Self>, { iter.fold(Self::ZERO, Self::add) } } impl<'a> Sum<&'a Self> for UVec2 { #[inline] fn sum<I>(iter: I) -> Self where I: Iterator<Item = &'a Self>, { iter.fold(Self::ZERO, |a, &b| Self::add(a, b)) } } impl Product for UVec2 { #[inline] fn product<I>(iter: I) -> Self where I: Iterator<Item = Self>, { iter.fold(Self::ONE, Self::mul) } } impl<'a> Product<&'a Self> for UVec2 { #[inline] fn product<I>(iter: I) -> Self where I: Iterator<Item = &'a Self>, { iter.fold(Self::ONE, |a, &b| Self::mul(a, b)) } } impl Not for UVec2 { type Output = Self; #[inline] fn not(self) -> Self::Output { Self { x: self.x.not(), y: self.y.not(), } } } impl BitAnd for UVec2 { type Output = Self; #[inline] fn bitand(self, rhs: Self) -> Self::Output { Self { x: self.x.bitand(rhs.x), y: self.y.bitand(rhs.y), } } } impl BitOr for UVec2 { type Output = Self; #[inline] fn bitor(self, rhs: Self) -> Self::Output { Self { x: self.x.bitor(rhs.x), y: self.y.bitor(rhs.y), } } } impl BitXor for UVec2 { type Output = Self; #[inline] fn bitxor(self, rhs: Self) -> Self::Output { Self { x: self.x.bitxor(rhs.x), y: self.y.bitxor(rhs.y), } } } impl BitAnd<u32> for UVec2 { type Output = Self; #[inline] fn bitand(self, rhs: u32) -> Self::Output { Self { x: self.x.bitand(rhs), y: self.y.bitand(rhs), } } } impl BitOr<u32> for UVec2 { type Output = Self; #[inline] fn bitor(self, rhs: u32) -> Self::Output { Self { x: self.x.bitor(rhs), y: self.y.bitor(rhs), } } } impl BitXor<u32> for UVec2 { type Output = Self; #[inline] fn bitxor(self, rhs: u32) -> Self::Output { Self { x: self.x.bitxor(rhs), y: self.y.bitxor(rhs), } } } impl Shl<i8> for UVec2 { type Output = Self; #[inline] fn shl(self, rhs: i8) -> Self::Output { Self { x: self.x.shl(rhs), y: self.y.shl(rhs), } } } impl Shr<i8> for UVec2 { type Output = Self; #[inline] fn shr(self, rhs: i8) -> Self::Output { Self { x: self.x.shr(rhs), y: self.y.shr(rhs), } } } impl Shl<i16> for UVec2 { type Output = Self; #[inline] fn shl(self, rhs: i16) -> Self::Output { Self { x: self.x.shl(rhs), y: self.y.shl(rhs), } } } impl Shr<i16> for UVec2 { type Output = Self; #[inline] fn shr(self, rhs: i16) -> Self::Output { Self { x: self.x.shr(rhs), y: self.y.shr(rhs), } } } impl Shl<i32> for UVec2 { type Output = Self; #[inline] fn shl(self, rhs: i32) -> Self::Output { Self { x: self.x.shl(rhs), y: self.y.shl(rhs), } } } impl Shr<i32> for UVec2 { type Output = Self; #[inline] fn shr(self, rhs: i32) -> Self::Output { Self { x: self.x.shr(rhs), y: self.y.shr(rhs), } } } impl Shl<i64> for UVec2 { type Output = Self; #[inline] fn shl(self, rhs: i64) -> Self::Output { Self { x: self.x.shl(rhs), y: self.y.shl(rhs), } } } impl Shr<i64> for UVec2 { type Output = Self; #[inline] fn shr(self, rhs: i64) -> Self::Output { Self { x: self.x.shr(rhs), y: self.y.shr(rhs), } } } impl Shl<u8> for UVec2 { type Output = Self; #[inline] fn shl(self, rhs: u8) -> Self::Output { Self { x: self.x.shl(rhs), y: self.y.shl(rhs), } } } impl Shr<u8> for UVec2 { type Output = Self; #[inline] fn shr(self, rhs: u8) -> Self::Output { Self { x: self.x.shr(rhs), y: self.y.shr(rhs), } } } impl Shl<u16> for UVec2 { type Output = Self; #[inline] fn shl(self, rhs: u16) -> Self::Output { Self { x: self.x.shl(rhs), y: self.y.shl(rhs), } } } impl Shr<u16> for UVec2 { type Output = Self; #[inline] fn shr(self, rhs: u16) -> Self::Output { Self { x: self.x.shr(rhs), y: self.y.shr(rhs), } } } impl Shl<u32> for UVec2 { type Output = Self; #[inline] fn shl(self, rhs: u32) -> Self::Output { Self { x: self.x.shl(rhs), y: self.y.shl(rhs), } } } impl Shr<u32> for UVec2 { type Output = Self; #[inline] fn shr(self, rhs: u32) -> Self::Output { Self { x: self.x.shr(rhs), y: self.y.shr(rhs), } } } impl Shl<u64> for UVec2 { type Output = Self; #[inline] fn shl(self, rhs: u64) -> Self::Output { Self { x: self.x.shl(rhs), y: self.y.shl(rhs), } } } impl Shr<u64> for UVec2 { type Output = Self; #[inline] fn shr(self, rhs: u64) -> Self::Output { Self { x: self.x.shr(rhs), y: self.y.shr(rhs), } } } impl Shl<crate::IVec2> for UVec2 { type Output = Self; #[inline] fn shl(self, rhs: crate::IVec2) -> Self::Output { Self { x: self.x.shl(rhs.x), y: self.y.shl(rhs.y), } } } impl Shr<crate::IVec2> for UVec2 { type Output = Self; #[inline] fn shr(self, rhs: crate::IVec2) -> Self::Output { Self { x: self.x.shr(rhs.x), y: self.y.shr(rhs.y), } } } impl Shl<crate::UVec2> for UVec2 { type Output = Self; #[inline] fn shl(self, rhs: crate::UVec2) -> Self::Output { Self { x: self.x.shl(rhs.x), y: self.y.shl(rhs.y), } } } impl Shr<crate::UVec2> for UVec2 { type Output = Self; #[inline] fn shr(self, rhs: crate::UVec2) -> Self::Output { Self { x: self.x.shr(rhs.x), y: self.y.shr(rhs.y), } } } impl Index<usize> for UVec2 { type Output = u32; #[inline] fn index(&self, index: usize) -> &Self::Output { match index { 0 => &self.x, 1 => &self.y, _ => panic!("index out of bounds"), } } } impl IndexMut<usize> for UVec2 { #[inline] fn index_mut(&mut self, index: usize) -> &mut Self::Output { match index { 0 => &mut self.x, 1 => &mut self.y, _ => panic!("index out of bounds"), } } } #[cfg(not(target_arch = "spirv"))] impl fmt::Display for UVec2 { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "[{}, {}]", self.x, self.y) } } #[cfg(not(target_arch = "spirv"))] impl fmt::Debug for UVec2 { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_tuple(stringify!(UVec2)) .field(&self.x) .field(&self.y) .finish() } } impl From<[u32; 2]> for UVec2 { #[inline] fn from(a: [u32; 2]) -> Self { Self::new(a[0], a[1]) } } impl From<UVec2> for [u32; 2] { #[inline] fn from(v: UVec2) -> Self { [v.x, v.y] } } impl From<(u32, u32)> for UVec2 { #[inline] fn from(t: (u32, u32)) -> Self { Self::new(t.0, t.1) } } impl From<UVec2> for (u32, u32) { #[inline] fn from(v: UVec2) -> Self { (v.x, v.y) } } impl TryFrom<IVec2> for UVec2 { type Error = core::num::TryFromIntError; #[inline] fn try_from(v: IVec2) -> Result<Self, Self::Error> { Ok(Self::new(u32::try_from(v.x)?, u32::try_from(v.y)?)) } } impl TryFrom<I64Vec2> for UVec2 { type Error = core::num::TryFromIntError; #[inline] fn try_from(v: I64Vec2) -> Result<Self, Self::Error> { Ok(Self::new(u32::try_from(v.x)?, u32::try_from(v.y)?)) } } impl TryFrom<U64Vec2> for UVec2 { type Error = core::num::TryFromIntError; #[inline] fn try_from(v: U64Vec2) -> Result<Self, Self::Error> { Ok(Self::new(u32::try_from(v.x)?, u32::try_from(v.y)?)) } }
use std::path::Path; use ggez::error::GameError::FontError; use ggez::graphics::{self, DrawParam, Image, Rect}; use ggez::mint; use ggez::{Context, GameResult}; #[derive(Debug)] pub struct Font { img: Image, } impl Font { const NCOL: usize = 16; const NROW: usize = 6; pub fn new<P: AsRef<Path>>(ctx: &mut Context, path: P) -> GameResult<Self> { let img = Image::new(ctx, path)?; if img.width() as usize % Self::NCOL != 0 { return Err(FontError("width is not divisible".to_owned())); } if img.height() as usize % Self::NROW != 0 { return Err(FontError("height is not divisible".to_owned())); } Ok(Self { img }) } pub fn glyph_width(&self) -> usize { self.img.width() as usize / Self::NCOL } pub fn glyph_height(&self) -> usize { self.img.height() as usize / Self::NROW } pub fn draw_char(&self, ctx: &mut Context, x: f32, y: f32, ch: char) -> GameResult { assert!(('\x20'..='\x7E').contains(&ch)); let (ch_c, ch_r) = { let idx = ch as usize - 0x20; (idx % Self::NCOL, idx / Self::NCOL) }; let src_coord = |x: usize, y: usize| -> (f32, f32) { ( x as f32 / self.img.width() as f32, y as f32 / self.img.height() as f32, ) }; let (sx, sy) = src_coord(ch_c * self.glyph_width(), ch_r * self.glyph_height()); let (sw, sh) = src_coord(self.glyph_width(), self.glyph_height()); graphics::draw( ctx, &self.img, DrawParam::default() .src(Rect { x: sx, y: sy, w: sw, h: sh, }) .dest(mint::Point2 { x, y }), ) } pub fn draw_str<S: AsRef<str>>(&self, ctx: &mut Context, x: f32, y: f32, s: S) -> GameResult { let s = s.as_ref(); for (i, ch) in s.chars().enumerate() { let dx = (i * self.glyph_width()) as f32; self.draw_char(ctx, x + dx, y, ch)?; } Ok(()) } }
use crate::{ gc::Gc, primitives::ListOperations, rerrs::ErrorKind, rvals::{FromSteelVal, IntoSteelVal, Result}, SteelErr, SteelVal, }; use std::collections::{HashMap, HashSet}; // Vectors impl<T: IntoSteelVal> IntoSteelVal for Vec<T> { fn into_steelval(self) -> Result<SteelVal> { let vec_vals: Result<Vec<SteelVal>> = self.into_iter().map(|x| x.into_steelval()).collect(); match vec_vals { Ok(l) => ListOperations::built_in_list_func_flat(&l), _ => Err(SteelErr::new( ErrorKind::ConversionError, "Could not convert vector of values to SteelVal list".to_string(), )), } } } impl<T: FromSteelVal> FromSteelVal for Vec<T> { fn from_steelval(val: SteelVal) -> Result<Self> { match val { SteelVal::Pair(_) => { let result_vec_vals: Result<Self> = SteelVal::iter(val.clone()) .into_iter() .map(FromSteelVal::from_steelval) .collect(); match result_vec_vals { Ok(x) => Ok(x), _ => Err(SteelErr::new( ErrorKind::ConversionError, "Could not convert SteelVal list to Vector of values".to_string(), )), } } SteelVal::VectorV(v) => { let result_vec_vals: Result<Self> = v .iter() .map(|x| FromSteelVal::from_steelval(x.clone())) .collect(); match result_vec_vals { Ok(x) => Ok(x), _ => Err(SteelErr::new( ErrorKind::ConversionError, "Could not convert SteelVal list to Vector of values".to_string(), )), } } // TODO _ => Err(SteelErr::new( ErrorKind::ConversionError, "Could not convert SteelVal list to Vector of values".to_string(), )), } } } // HashMap impl<K: IntoSteelVal, V: IntoSteelVal> IntoSteelVal for HashMap<K, V> { fn into_steelval(mut self) -> Result<SteelVal> { let mut hm = im_rc::HashMap::new(); for (key, val) in self.drain() { hm.insert(key.into_steelval()?, val.into_steelval()?); } Ok(SteelVal::HashMapV(Gc::new(hm))) } } impl<K: FromSteelVal + Eq + std::hash::Hash, V: FromSteelVal> FromSteelVal for HashMap<K, V> { fn from_steelval(val: SteelVal) -> Result<Self> { // todo!() if let SteelVal::HashMapV(hm) = val { let mut h = HashMap::new(); for (key, value) in hm.unwrap().into_iter() { h.insert(K::from_steelval(key)?, V::from_steelval(value)?); } Ok(h) } else { Err(SteelErr::new( ErrorKind::ConversionError, "Could not convert SteelVal to HashMap".to_string(), )) } } } // BTreeMap // impl<K: IntoSteelVal, V: IntoSteelVal> IntoSteelVal for BTreeMap<K, V> { // fn into_steelval(self) -> Result<SteelVal> { // let mut hm = im_rc::HashMap::new(); // for (key, val) in self.drain() { // hm.insert(key.into_steelval()?, val.into_steelval()?); // } // Ok(SteelVal::HashMapV(Gc::new(hm))) // } // } // impl<K: FromSteelVal, V: FromSteelVal> FromSteelVal for BTreeMap<K, V> { // fn from_steelval(val: SteelVal) -> Result<Self> { // todo!() // } // } // HashSet impl<K: IntoSteelVal> IntoSteelVal for HashSet<K> { fn into_steelval(mut self) -> Result<SteelVal> { let mut hs = im_rc::HashSet::new(); for value in self.drain() { hs.insert(value.into_steelval()?); } Ok(SteelVal::HashSetV(Gc::new(hs))) } } impl<K: FromSteelVal + Eq + std::hash::Hash> FromSteelVal for HashSet<K> { fn from_steelval(val: SteelVal) -> Result<Self> { if let SteelVal::HashSetV(hs) = val { let mut h = HashSet::new(); for k in hs.unwrap().into_iter() { h.insert(K::from_steelval(k)?); } Ok(h) } else { Err(SteelErr::new( ErrorKind::ConversionError, "Could not convert SteelVal to HashSet".to_string(), )) } } } // BTreeSet // impl<K: IntoSteelVal> IntoSteelVal for BTreeSet<K> { // fn into_steelval(self) -> Result<SteelVal> { // todo!() // } // } // impl<K: FromSteelVal> FromSteelVal for BTreeSet<K> { // fn from_steelval(val: SteelVal) -> Result<Self> { // todo!() // } // } #[cfg(test)] mod conversion_tests { use super::*; use crate::rvals::ConsCell; use im_rc::vector; #[test] fn vec_into_list() { let input_vec = vec![1, 2]; let expected = SteelVal::Pair(Gc::new(ConsCell::new( SteelVal::IntV(1), Some(Gc::new(ConsCell::new(SteelVal::IntV(2), None))), ))); assert_eq!(input_vec.into_steelval().unwrap(), expected) } #[test] fn vec_from_list() { let input_list = SteelVal::Pair(Gc::new(ConsCell::new( SteelVal::IntV(1), Some(Gc::new(ConsCell::new(SteelVal::IntV(2), None))), ))); let expected = vec![1, 2]; let result = <Vec<i32>>::from_steelval(input_list).unwrap(); assert_eq!(result, expected) } #[test] fn vec_from_vector() { let input_vector = SteelVal::VectorV(Gc::new(vector![SteelVal::IntV(1), SteelVal::IntV(2)])); let expected = vec![1, 2]; let result = <Vec<i32>>::from_steelval(input_vector).unwrap(); assert_eq!(result, expected); } #[test] fn vec_from_steelval_error() { let input = SteelVal::IntV(2); assert!(<Vec<i32>>::from_steelval(input).is_err()); } #[test] fn hashmap_into_steelval() { let mut input = HashMap::new(); input.insert("foo".to_string(), "bar".to_string()); input.insert("foo2".to_string(), "bar2".to_string()); let expected = SteelVal::HashMapV(Gc::new(im_rc::hashmap! { SteelVal::StringV("foo".into()) => SteelVal::StringV("bar".into()), SteelVal::StringV("foo2".into()) => SteelVal::StringV("bar2".into()) })); assert_eq!(input.into_steelval().unwrap(), expected); } #[test] fn hashmap_from_steelval_hashmap() { let input = SteelVal::HashMapV(Gc::new(im_rc::hashmap! { SteelVal::StringV("foo".into()) => SteelVal::StringV("bar".into()), SteelVal::StringV("foo2".into()) => SteelVal::StringV("bar2".into()) })); let mut expected = HashMap::new(); expected.insert("foo".to_string(), "bar".to_string()); expected.insert("foo2".to_string(), "bar2".to_string()); assert_eq!( <HashMap<String, String>>::from_steelval(input).unwrap(), expected ); } #[test] fn hashset_into_steelval() { let mut input = HashSet::new(); input.insert("foo".to_string()); input.insert("bar".to_string()); let expected = SteelVal::HashSetV(Gc::new(im_rc::hashset! { SteelVal::StringV("foo".into()), SteelVal::StringV("bar".into()) })); assert_eq!(input.into_steelval().unwrap(), expected); } #[test] fn hashset_from_steelval_hashset() { let input = SteelVal::HashSetV(Gc::new(im_rc::hashset! { SteelVal::StringV("foo".into()), SteelVal::StringV("bar".into()) })); let mut expected = HashSet::new(); expected.insert("foo".to_string()); expected.insert("bar".to_string()); assert_eq!(<HashSet<String>>::from_steelval(input).unwrap(), expected); } }
use crate::{BotResult, Database}; use dashmap::DashMap; use futures::stream::StreamExt; impl Database { pub async fn add_stream_track(&self, channel: u64, user: u64) -> BotResult<bool> { let done = sqlx::query!( "INSERT INTO stream_tracks VALUES ($1,$2) ON CONFLICT DO NOTHING", channel as i64, user as i64 ) .execute(&self.pool) .await?; Ok(done.rows_affected() > 0) } #[cold] pub async fn get_stream_tracks(&self) -> BotResult<DashMap<u64, Vec<u64>>> { let mut stream = sqlx::query!("SELECT * FROM stream_tracks").fetch(&self.pool); let tracks: DashMap<_, Vec<_>> = DashMap::with_capacity(1000); while let Some(entry) = stream.next().await.transpose()? { let channel_id: i64 = entry.channel_id; let user_id: i64 = entry.user_id; tracks .entry(user_id as u64) .or_default() .push(channel_id as u64); } Ok(tracks) } pub async fn remove_channel_tracks(&self, channel: u64) -> BotResult<()> { sqlx::query!( "DELETE FROM stream_tracks WHERE channel_id=$1", channel as i64, ) .execute(&self.pool) .await?; Ok(()) } pub async fn remove_stream_track(&self, channel: u64, user: u64) -> BotResult<bool> { let done = sqlx::query!( "DELETE FROM stream_tracks WHERE channel_id=$1 AND user_id=$2", channel as i64, user as i64, ) .execute(&self.pool) .await?; Ok(done.rows_affected() > 0) } }
type DataType = std::collections::HashMap<u32, u32>; fn knapsack( data: &[u32], limit: u32, current_weight: u32, count: &mut DataType, containers_used: u32, ) { for (idx, _) in data.iter().enumerate() { let new_weight = current_weight + data[idx]; if new_weight == limit { let combination = count.entry(containers_used).or_insert(0); *combination += 1; continue; } else if new_weight < limit { knapsack( &data[idx + 1..], limit, new_weight, count, containers_used + 1, ); } } } fn part_1(input: &[u32], capacity: u32) -> u32 { let mut combinations = DataType::new(); knapsack(input, capacity, 0, &mut combinations, 0); combinations.iter().fold(0, |acc, p| acc + p.1) } fn part_2(input: &[u32], capacity: u32) -> u32 { let mut combinations = DataType::new(); knapsack(input, capacity, 0, &mut combinations, 0); *combinations.iter().min().unwrap().1 } fn main() { let input = [ 33, 14, 18, 20, 45, 35, 16, 35, 1, 13, 18, 13, 50, 44, 48, 6, 24, 41, 30, 42, ]; println!("part_1: {}", part_1(&input, 150)); println!("part_2: {}", part_2(&input, 150)); } #[cfg(test)] mod day17 { use super::*; #[test] fn test_part_1() { assert_eq!(4, part_1(&[5, 5, 10, 15, 20], 25)); } #[test] fn test_part_2() { assert_eq!(3, part_2(&[5, 5, 10, 15, 20], 25)); } }
use std::collections::HashSet; use std::env; use std::fs; #[derive(Debug)] enum Instruction { Acc(i32), Jmp(i32), Nop, } fn to_instruction(line: &str) -> Instruction { let mut split = line.split_ascii_whitespace(); match split.next().unwrap() { "acc" => Instruction::Acc(split.next().unwrap().parse::<i32>().unwrap()), "jmp" => Instruction::Jmp(split.next().unwrap().parse::<i32>().unwrap()), "nop" => Instruction::Nop, _ => unreachable!(), } } type Program = Vec<Instruction>; fn to_program(text: &str) -> Program { text.lines().map(to_instruction).collect() } fn find_loop(program: Program) -> i32 { let mut cur: i32 = 0; let mut acc = 0; let mut seen = HashSet::new(); loop { if seen.contains(&cur) { return acc; } seen.insert(cur); println!("{:?}", program[cur as usize]); match program[cur as usize] { Instruction::Acc(x) => { acc += x; cur += 1; } Instruction::Jmp(x) => cur += x, Instruction::Nop => cur += 1, } } } fn main() { let args: Vec<String> = env::args().collect(); let program_text = fs::read_to_string(&args[1]).unwrap(); println!("{:?}", find_loop(to_program(&program_text))); }
//!Acid testing program #![feature(array_chunks, core_intrinsics, thread_local)] const PAGE_SIZE: usize = 4096; mod cross_scheme_link; mod daemon; mod scheme_data_leak; fn e<T, E: ToString>(error: Result<T, E>) -> Result<T, String> { error.map_err(|e| e.to_string()) } fn create_test() -> Result<(), String> { use std::fs; use std::io::{self, Read, Write}; use std::path::PathBuf; let mut test_dir = PathBuf::new(); test_dir.push("test_dir"); let mut test_file = test_dir.clone(); test_file.push("test_file"); let test_file_err = fs::File::create(&test_file).err().map(|err| err.kind()); if test_file_err != Some(io::ErrorKind::NotFound) { return Err(format!("Incorrect open error: {:?}, should be NotFound", test_file_err)); } fs::create_dir(&test_dir).map_err(|err| format!("{}", err))?; let test_data = "Test data"; { let mut file = fs::File::create(&test_file).map_err(|err| format!("{}", err))?; file.write(test_data.as_bytes()).map_err(|err| format!("{}", err))?; } { let mut file = fs::File::open(&test_file).map_err(|err| format!("{}", err))?; let mut buffer: Vec<u8> = Vec::new(); file.read_to_end(&mut buffer).map_err(|err| format!("{}", err))?; assert_eq!(buffer.len(), test_data.len()); for (&a, b) in buffer.iter().zip(test_data.bytes()) { if a != b { return Err(format!("{} did not contain the correct data", test_file.display())); } } } Ok(()) } fn page_fault_test() -> Result<(), String> { use std::sync::atomic::{AtomicUsize, compiler_fence, Ordering}; use syscall::flag::{MapFlags, SigActionFlags, SIGSEGV}; use syscall::data::{Map, SigAction}; const ADDR: usize = 0xDEADC0DE; const ALIGNED_ADDR: usize = ADDR / PAGE_SIZE * PAGE_SIZE; static STATE: AtomicUsize = AtomicUsize::new(0); fn map(value: u8) { unsafe { let _ = syscall::fmap(!0, &Map { offset: 0, address: ALIGNED_ADDR, size: PAGE_SIZE, flags: MapFlags::MAP_FIXED_NOREPLACE | MapFlags::MAP_PRIVATE | MapFlags::PROT_READ | MapFlags::PROT_WRITE }).expect("[signal handler]: failed to re-map address"); (ADDR as *mut u8).write_volatile(value); } } extern "C" fn page_fault_handler(_signo: usize) { std::panic::catch_unwind(|| { let prev_state = STATE.fetch_add(1, Ordering::Relaxed); compiler_fence(Ordering::SeqCst); match prev_state { 0 => { println!("[signal handler]: Mapping to fix page fault..."); map(42); } 1 => { println!("[signal handler]: Remapping to finish main process..."); map(43); } _ => unreachable!("[signal handler]: Page fault should NOT occur more than twice! What went wrong?"), } syscall::sigreturn().expect("[signal handler]: expected sigreturn to work") }).unwrap_or_else(|_| std::intrinsics::abort()); } let new_sigaction = SigAction { sa_handler: Some(page_fault_handler), // I think this is currently ignored by the kernel. TODO sa_mask: [0; 2], sa_flags: SigActionFlags::empty(), }; syscall::sigaction(SIGSEGV, Some(&new_sigaction), None).map_err(|err| format!("{}", err))?; for i in 0..2 { println!("Reading {} time:", if i == 0 { "first" } else if i == 1 { "second" } else { unreachable!() }); println!("value {}", unsafe { (ADDR as *const u8).read_volatile() }); if i == 0 { println!("Unmapping to test TLB flush..."); } let _ = unsafe { syscall::funmap(ALIGNED_ADDR, PAGE_SIZE).expect("failed to unmap") }; } compiler_fence(Ordering::SeqCst); match STATE.load(Ordering::Relaxed) { 0 => panic!("failed: no page fault was caught, maybe 0xDEADC0DE was already mapped?"), 1 => panic!("failed: unmap was unsuccessful"), 2 => (), _ => unreachable!(), } Ok(()) } #[cfg(target_arch = "x86_64")] fn switch_test() -> Result<(), String> { use std::thread; use x86::time::rdtscp; let tsc = unsafe { rdtscp() }; let switch_thread = thread::spawn(|| -> usize { let mut j = 0; while j < 500 { thread::yield_now(); j += 1; } j }); let mut i = 0; while i < 500 { thread::yield_now(); i += 1; } let j = switch_thread.join().unwrap(); let dtsc = unsafe { rdtscp() } - tsc; println!("P {} C {} T {}", i, j, dtsc); Ok(()) } fn tcp_fin_test() -> Result<(), String> { use std::io::Write; use std::net::TcpStream; let mut conn = TcpStream::connect("static.redox-os.org:80").map_err(|err| format!("{}", err))?; conn.write(b"TEST").map_err(|err| format!("{}", err))?; drop(conn); Ok(()) } fn thread_test() -> Result<(), String> { use std::process::Command; use std::thread; use std::time::Instant; println!("Trying to stop kernel..."); let start = Instant::now(); while start.elapsed().as_secs() == 0 {} println!("Kernel preempted!"); println!("Trying to kill kernel..."); let mut threads = Vec::new(); for i in 0..10 { threads.push(thread::spawn(move || { let mut sub_threads = Vec::new(); for j in 0..10 { sub_threads.push(thread::spawn(move || { Command::new("ion") .arg("-c") .arg(&format!("echo {}:{}", i, j)) .spawn().unwrap() .wait().unwrap(); })); } Command::new("ion") .arg("-c") .arg(&format!("echo {}", i)) .spawn().unwrap() .wait().unwrap(); for sub_thread in sub_threads { let _ = sub_thread.join(); } })); } for thread in threads { let _ = thread.join(); } println!("Kernel survived thread test!"); Ok(()) } /// Test of zero values in thread BSS #[thread_local] static mut TBSS_TEST_ZERO: usize = 0; /// Test of non-zero values in thread data. #[thread_local] static mut TDATA_TEST_NONZERO: usize = usize::max_value(); fn tls_test() -> Result<(), String> { use std::thread; thread::spawn(|| { unsafe { assert_eq!(TBSS_TEST_ZERO, 0); TBSS_TEST_ZERO += 1; assert_eq!(TBSS_TEST_ZERO, 1); assert_eq!(TDATA_TEST_NONZERO, usize::max_value()); TDATA_TEST_NONZERO -= 1; assert_eq!(TDATA_TEST_NONZERO, usize::max_value() - 1); } }).join().unwrap(); unsafe { assert_eq!(TBSS_TEST_ZERO, 0); TBSS_TEST_ZERO += 1; assert_eq!(TBSS_TEST_ZERO, 1); assert_eq!(TDATA_TEST_NONZERO, usize::max_value()); TDATA_TEST_NONZERO -= 1; assert_eq!(TDATA_TEST_NONZERO, usize::max_value() - 1); } Ok(()) } fn efault_test() -> Result<(), String> { use syscall::*; let ret = unsafe { syscall3(SYS_WRITE, 1, 0xdeadbeef, 0xfeedface) }; assert_eq!(ret, Err(Error::new(EFAULT))); Ok(()) } fn main() { use std::collections::BTreeMap; use std::{env, process}; use std::time::Instant; let mut tests: BTreeMap<&'static str, fn() -> Result<(), String>> = BTreeMap::new(); tests.insert("create_test", create_test); tests.insert("page_fault", page_fault_test); #[cfg(target_arch = "x86_64")] tests.insert("switch", switch_test); tests.insert("tcp_fin", tcp_fin_test); tests.insert("thread", thread_test); tests.insert("tls", tls_test); tests.insert("cross_scheme_link", cross_scheme_link::cross_scheme_link); tests.insert("efault", efault_test); tests.insert("scheme_data_leak", scheme_data_leak::scheme_data_leak_test); let mut ran_test = false; for arg in env::args().skip(1) { if let Some(test) = tests.get(&arg.as_str()) { ran_test = true; let time = Instant::now(); let res = test(); let elapsed = time.elapsed(); match res { Ok(_) => { println!("acid: {}: passed: {} ns", arg, elapsed.as_secs() * 1000000000 + elapsed.subsec_nanos() as u64); }, Err(err) => { println!("acid: {}: failed: {}", arg, err); } } } else { println!("acid: {}: not found", arg); process::exit(1); } } if ! ran_test { for test in tests { println!("{}", test.0); } } }
use std::env; use std::ffi::OsString; use std::io::ErrorKind; use std::process; use std::process::Command; use starship::config::StarshipConfig; use std::fs::File; use std::io::Write; use toml::map::Map; use toml::Value; #[cfg(not(windows))] const STD_EDITOR: &str = "vi"; #[cfg(windows)] const STD_EDITOR: &str = "notepad.exe"; pub fn update_configuration(name: &str, value: &str) { let config_path = get_config_path(); let keys: Vec<&str> = name.split('.').collect(); if keys.len() != 2 { log::error!("Please pass in a config key with a '.'"); process::exit(1); } let starship_config = StarshipConfig::initialize(); let mut config = starship_config .config .expect("Failed to load starship config"); if let Some(table) = config.as_table_mut() { if !table.contains_key(keys[0]) { table.insert(keys[0].to_string(), Value::Table(Map::new())); } if let Some(values) = table.get(keys[0]).unwrap().as_table() { let mut updated_values = values.clone(); if value.parse::<bool>().is_ok() { updated_values.insert( keys[1].to_string(), Value::Boolean(value.parse::<bool>().unwrap()), ); } else if value.parse::<i64>().is_ok() { updated_values.insert( keys[1].to_string(), Value::Integer(value.parse::<i64>().unwrap()), ); } else { updated_values.insert(keys[1].to_string(), Value::String(value.to_string())); } table.insert(keys[0].to_string(), Value::Table(updated_values)); } let config_str = toml::to_string_pretty(&table).expect("Failed to serialize the config to string"); File::create(&config_path) .and_then(|mut file| file.write_all(config_str.as_ref())) .expect("Error writing starship config"); } } pub fn edit_configuration() { let config_path = get_config_path(); let editor_cmd = shell_words::split(&get_editor()).expect("Unmatched quotes found in $EDITOR."); let command = Command::new(&editor_cmd[0]) .args(&editor_cmd[1..]) .arg(config_path) .status(); match command { Ok(_) => (), Err(error) => match error.kind() { ErrorKind::NotFound => { eprintln!( "Error: editor {:?} was not found. Did you set your $EDITOR or $VISUAL \ environment variables correctly?", editor_cmd ); std::process::exit(1) } other_error => panic!("failed to open file: {:?}", other_error), }, }; } fn get_editor() -> String { get_editor_internal(env::var("VISUAL").ok(), env::var("EDITOR").ok()) } fn get_editor_internal(visual: Option<String>, editor: Option<String>) -> String { let editor_name = visual.unwrap_or_else(|| "".into()); if !editor_name.is_empty() { return editor_name; } let editor_name = editor.unwrap_or_else(|| "".into()); if !editor_name.is_empty() { return editor_name; } STD_EDITOR.into() } fn get_config_path() -> OsString { if let Some(config_path) = env::var_os("STARSHIP_CONFIG") { return config_path; } dirs_next::home_dir() .expect("couldn't find home directory") .join(".config") .join("starship.toml") .into() } #[cfg(test)] mod tests { use super::*; // This is every possible permutation, 3ยฒ = 9. #[test] fn visual_set_editor_set() { let actual = get_editor_internal(Some("foo".into()), Some("bar".into())); assert_eq!("foo", actual); } #[test] fn visual_set_editor_empty() { let actual = get_editor_internal(Some("foo".into()), None); assert_eq!("foo", actual); } #[test] fn visual_set_editor_not_set() { let actual = get_editor_internal(Some("foo".into()), None); assert_eq!("foo", actual); } #[test] fn visual_empty_editor_set() { let actual = get_editor_internal(Some("".into()), Some("bar".into())); assert_eq!("bar", actual); } #[test] fn visual_empty_editor_empty() { let actual = get_editor_internal(Some("".into()), Some("".into())); assert_eq!(STD_EDITOR, actual); } #[test] fn visual_empty_editor_not_set() { let actual = get_editor_internal(Some("".into()), None); assert_eq!(STD_EDITOR, actual); } #[test] fn visual_not_set_editor_set() { let actual = get_editor_internal(None, Some("bar".into())); assert_eq!("bar", actual); } #[test] fn visual_not_set_editor_empty() { let actual = get_editor_internal(None, Some("".into())); assert_eq!(STD_EDITOR, actual); } #[test] fn visual_not_set_editor_not_set() { let actual = get_editor_internal(None, None); assert_eq!(STD_EDITOR, actual); } }
pub fn dfs<F, GT: ::graph::GraphTraversal>(g: &GT, s: usize, mapped_function: &mut Box<F>, marker: &mut ::mark::Marker) where F: FnMut(usize) { mapped_function(s); marker.mark(s); for &v in g.fwd_edges(s) { if !marker.is_marked(v) { dfs(g, v, mapped_function, marker); } } } pub fn full_dfs<F, GT: ::graph::GraphTraversal>(g: &GT, mapped_function: &mut Box<F>, marker: &mut ::mark::Marker) where F: FnMut(usize) { for v in g.sources() { dfs(g, v, mapped_function, marker); } } #[test] fn simple_dws() { let mut g = ::graph::Graph::new(); g.push_edgelist_fwd(vec![1,2]); g.push_edgelist_fwd(vec![3,4]); g.push_edgelist_fwd(vec![]); g.push_edgelist_fwd(vec![]); g.push_edgelist_fwd(vec![]); g.push_edgelist_fwd(vec![]); g.push_edgelist_bwd(vec![]); g.push_edgelist_bwd(vec![0]); g.push_edgelist_bwd(vec![0]); g.push_edgelist_bwd(vec![1]); g.push_edgelist_bwd(vec![1]); g.push_edgelist_bwd(vec![]); let mut dfs_out: Vec<usize> = vec![]; { let mut p = Box::new(|x: usize| { dfs_out.push(x); }); let mut marker = ::mark::TMarker::new(g.len()); full_dfs(&g, &mut p, &mut marker); } assert_eq!(dfs_out, [0,1,3,4,2,5]); }
use std::net::SocketAddr; use rsocket_rust::{async_trait, error::RSocketError, transport::ServerTransport, Result}; use tokio::net::TcpListener; use super::client::WebsocketClientTransport; const WS_PROTO: &str = "ws://"; #[derive(Debug)] pub struct WebsocketServerTransport { addr: SocketAddr, listener: Option<TcpListener>, } #[async_trait] impl ServerTransport for WebsocketServerTransport { type Item = WebsocketClientTransport; async fn start(&mut self) -> Result<()> { if self.listener.is_some() { warn!("websocket server transport started already!"); return Ok(()); } match TcpListener::bind(self.addr).await { Ok(listener) => { self.listener = Some(listener); Ok(()) } Err(e) => Err(RSocketError::IO(e).into()), } } async fn next(&mut self) -> Option<Result<WebsocketClientTransport>> { match self.listener.as_mut() { Some(listener) => match listener.accept().await { Ok((socket, _)) => Some(Ok(WebsocketClientTransport::from(socket))), Err(e) => Some(Err(RSocketError::Other(e.into()).into())), }, None => None, } } } #[inline] fn parse_socket_addr(addr: impl AsRef<str>) -> SocketAddr { let addr = addr.as_ref(); if addr.starts_with(WS_PROTO) { addr.chars() .skip(WS_PROTO.len()) .collect::<String>() .parse() } else { addr.parse() } .expect("Invalid transport string!") } impl From<SocketAddr> for WebsocketServerTransport { fn from(addr: SocketAddr) -> WebsocketServerTransport { WebsocketServerTransport { addr, listener: None, } } } impl From<String> for WebsocketServerTransport { fn from(addr: String) -> WebsocketServerTransport { WebsocketServerTransport { addr: parse_socket_addr(addr), listener: None, } } } impl From<&str> for WebsocketServerTransport { fn from(addr: &str) -> WebsocketServerTransport { WebsocketServerTransport { addr: parse_socket_addr(addr), listener: None, } } }
use num::Num; use rand::distributions::Distribution; use rand::distributions::Standard; use rand::random; use std::convert::Into; use std::fmt::Debug; use std::ops::Add; use std::ops::AddAssign; use std::ops::Div; use std::ops::DivAssign; use std::ops::Index; use std::ops::Mul; use std::ops::MulAssign; use std::ops::Neg; use std::ops::Sub; #[derive(Clone, Copy, PartialEq)] pub struct Vec3<T> where T: Num + Copy + Into<f64> + Debug, { e: [T; 3], } impl<T: Num + Copy + Into<f64> + Debug> Debug for Vec3<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> { write!(f, "({:?},{:?},{:?})", self.e[0], self.e[1], self.e[2]) } } impl<T: Add<Output = T> + Num + Copy + Into<f64> + Debug + Default> Add for Vec3<T> { type Output = Self; #[inline] fn add(self, rhs: Self) -> Self { Vec3::with_values( self.e[0] + rhs.e[0], self.e[1] + rhs.e[1], self.e[2] + rhs.e[2], ) } } impl<T: Sub<Output = T> + Num + Copy + Into<f64> + Debug + Default> Sub for Vec3<T> { type Output = Self; #[inline] fn sub(self, rhs: Self) -> Self { Vec3::with_values( self.e[0] - rhs.e[0], self.e[1] - rhs.e[1], self.e[2] - rhs.e[2], ) } } impl<T: Mul<Output = T> + Num + Copy + Into<f64> + Debug + Default> Mul for Vec3<T> { type Output = Self; #[inline] fn mul(self, rhs: Self) -> Self { Vec3::with_values( self.e[0] * rhs.e[0], self.e[1] * rhs.e[1], self.e[2] * rhs.e[2], ) } } impl<T: Mul<Output = T> + Num + Copy + Into<f64> + Debug + Default> Mul<T> for Vec3<T> { type Output = Self; #[inline] fn mul(self, t: T) -> Self { Vec3::with_values(self.e[0] * t, self.e[1] * t, self.e[2] * t) } } impl<T: Neg<Output = T> + Num + Copy + Into<f64> + Debug + Default> Neg for Vec3<T> { type Output = Self; #[inline] fn neg(self) -> <Self as std::ops::Neg>::Output { Vec3::with_values(-self.e[0], -self.e[1], -self.e[2]) } } impl<T: Neg<Output = T> + Num + Copy + Into<f64> + Debug + Default> Neg for &Vec3<T> { type Output = Vec3<T>; #[inline] fn neg(self) -> Self::Output { Vec3::with_values(-self.e[0], -self.e[1], -self.e[2]) } } impl<T: Num + Copy + Into<f64> + Debug> AddAssign<T> for Vec3<T> { #[inline] fn add_assign(&mut self, rhs: T) { self.e[0] = self.e[0] + rhs; self.e[1] = self.e[1] + rhs; self.e[2] = self.e[2] + rhs; } } impl<T: Num + Copy + Into<f64> + Debug> AddAssign<&Vec3<T>> for Vec3<T> { #[inline] fn add_assign(&mut self, rhs: &Vec3<T>) { self.e[0] = self.e[0] + rhs.e[0]; self.e[1] = self.e[1] + rhs.e[1]; self.e[2] = self.e[2] + rhs.e[2]; } } impl<T: Num + Copy + Into<f64> + Debug> MulAssign<T> for Vec3<T> { #[inline] fn mul_assign(&mut self, rhs: T) { self.e[0] = self.e[0] * rhs; self.e[1] = self.e[1] * rhs; self.e[2] = self.e[2] * rhs; } } impl Div<f64> for Vec3<f64> { type Output = Self; #[inline] fn div(self, t: f64) -> Self { Vec3::with_values(self.e[0] / t, self.e[1] / t, self.e[2] / t) } } impl Div<f64> for Vec3<f32> { type Output = Self; #[inline] fn div(self, t: f64) -> Self { let t = t as f32; Vec3::with_values(self.e[0] / t, self.e[1] / t, self.e[2] / t) } } impl<T: Num + Copy + Into<f64> + Debug> DivAssign<T> for Vec3<T> { #[inline] fn div_assign(&mut self, rhs: T) { self.e[0] = self.e[0] / rhs; self.e[1] = self.e[1] / rhs; self.e[2] = self.e[2] / rhs; } } impl<T: Num + Copy + Into<f64> + Debug> Index<usize> for Vec3<T> { type Output = T; fn index(&self, index: usize) -> &<Self as std::ops::Index<usize>>::Output { &self.e[index] } } impl<T: Num + Copy + Debug + Into<f64>> AsRef<Vec3<T>> for Vec3<T> { fn as_ref(&self) -> &Vec3<T> { self } } impl<T: Num + Copy + Into<f64> + Debug + Default + Sized> Vec3<T> { #[inline] pub fn length(&self) -> f64 { self.length_squared().into().sqrt() } #[inline] pub fn length_squared(&self) -> T { self.e[0] * self.e[0] + self.e[1] * self.e[1] + self.e[2] * self.e[2] } #[inline] pub fn x(&self) -> T { self.e[0] } #[inline] pub fn y(&self) -> T { self.e[1] } #[inline] pub fn z(&self) -> T { self.e[2] } #[inline] pub fn with_values(x: T, y: T, z: T) -> Vec3<T> { Vec3 { e: [x, y, z] } } #[inline] pub fn new() -> Vec3<T> { Vec3 { e: [T::default(), T::default(), T::default()], } } #[inline] pub fn as_std_vec(&self) -> Vec<T> { vec![self.x(), self.y(), self.z()] } #[inline] pub fn dot<A: AsRef<Vec3<T>>>(&self, v: A) -> f64 { let m = v.as_ref(); (self.e[0] * m.e[0] + self.e[1] * m.e[1] + self.e[2] * m.e[2]).into() } #[inline] pub fn cross(&self, v: &Self) -> Self { Vec3::with_values( self.e[1] * v.e[2] - self.e[2] * v.e[1], self.e[2] * v.e[0] - self.e[0] * v.e[2], self.e[0] * v.e[1] - self.e[1] * v.e[0], ) } } impl Vec3<f64> { pub fn unit_vec(&self) -> Self { *self / self.length() } } impl Vec3<f32> { pub fn unit_vec(&self) -> Self { *self / self.length() } } /// Generic implementation to generate /// random vectors3 from T default generators impl<T> Distribution<Vec3<T>> for Standard where T: Num + Copy + Into<f64> + Debug + Default, Standard: Distribution<T>, { fn sample<R: rand::Rng + ?Sized>(&self, _: &mut R) -> Vec3<T> where R: rand::Rng, { Vec3::with_values(random::<T>(), random::<T>(), random::<T>()) } } #[cfg(test)] mod tests { use crate::math::vec3::Vec3; #[test] fn with_values() { let e = [1.0, 4.0, 99.5]; assert_eq!(Vec3 { e }, Vec3::with_values(1.0, 4.0, 99.5)); } #[test] fn break_equality() { assert_ne!( Vec3::with_values(5.0, 9., 33.7), Vec3::with_values(1.0, 4.0, 99.5) ); } #[test] fn xyz() { let v = Vec3::with_values(5.0, 9., 33.7); assert_eq!(v.x(), 5.0); assert_eq!(v.y(), 9.0); assert_eq!(v.z(), 33.7); } #[test] fn length() { let v = Vec3::with_values(2.0, 4.0, 4.0); assert_eq!(v.length_squared(), 36.); assert_eq!(v.length(), 6.); } #[test] fn add() { let v = Vec3::with_values(2.0, 4.0, 4.0); let w = Vec3::with_values(1.0, 3.0, 7.0); assert_eq!(v + w, Vec3::with_values(3.0, 7.0, 11.0)); } #[test] fn neg() { let v = Vec3::with_values(2.0, 4.0, 4.0); assert_eq!(-v, Vec3::with_values(-2.0, -4.0, -4.0)); } #[test] fn add_assign() { let mut v = Vec3::with_values(2.0, 4.0, 3.0); v += 5.; assert_eq!(v, Vec3::with_values(7.0, 9.0, 8.0)); } #[test] fn mul_assign() { let mut v = Vec3::with_values(2.0, 4.0, 5.0); v *= 2.; assert_eq!(v, Vec3::with_values(4.0, 8.0, 10.0)); } #[test] fn new() { let v = Vec3::new(); let w = Vec3::new(); assert_eq!(v, Vec3::with_values(0, 0, 0)); assert_eq!(w, Vec3::with_values(0., 0., 0.)); } #[test] fn index() { let v = Vec3::with_values(2.0, 4.0, 5.0); assert_eq!(v[0], 2.0); assert_eq!(v[1], 4.0); assert_eq!(v[2], 5.0); } #[test] #[should_panic] fn index_out_of_bounds() { let v = Vec3::with_values(2.0, 4.0, 5.0); let x = v[5]; } #[test] fn dot() { let u = Vec3::with_values(2.0, 4.0, 5.0); let v = Vec3::with_values(1.0, 5.0, 2.0); assert_eq!(u.dot(v), 32.); } #[test] fn cross() { let u = Vec3::with_values(2.0, 4.0, 5.0); let v = Vec3::with_values(1.0, 5.0, 2.0); assert_eq!(u.cross(&v), Vec3::with_values(-17., 1., 6.)); } #[test] fn unit() { let u: Vec3<f64> = Vec3::with_values(6.0, 4.0, 5.0); let a = u.unit_vec(); let n = (77f64).sqrt(); assert_eq!(a, Vec3::with_values(6.0 / n, 4.0 / n, 5.0 / n)); } #[test] fn self_dot_equals_length_squared() { let u: Vec3<f64> = Vec3::with_values(6.0, 4.0, 5.0); assert_eq!(u.dot(u), u.length_squared()); } }
//! Utilities for creating optimal work schedules. //! //! # Weeks //! //! This library relies heavily on the concept of a _week_ as a unit of time. A _week_ is defined //! as a series of 7 _weekdays_ beginning with Monday and ending with Sunday. Weekdays are //! represented by variants of the [`chrono::Weekday`] enum. pub mod agenda; pub mod timetable; pub mod worker; pub use chrono::Weekday; pub use time::Duration; pub use crate::agenda::Agenda; pub use crate::timetable::{TimeRange, Timetable, WeekTime}; pub use crate::worker::Roster; /// Manages an Agenda and a Roster of Workers that can fulfill it. pub struct Project { agenda: Agenda, roster: Roster, } impl Project { pub fn new(agenda: Agenda, roster: Roster) -> Self { Project { agenda, roster } } }
use crate::Event; use libc::{c_int, ioctl, sighandler_t, signal, winsize, SIGWINCH, STDIN_FILENO, TIOCGWINSZ}; use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::{mpsc, Mutex}; use std::thread; use super::Terminal; static TERM_WIDTH: AtomicU32 = AtomicU32::new(0); static TERM_HEIGHT: AtomicU32 = AtomicU32::new(0); static mut RESIZE_CHANNEL: Option<Mutex<mpsc::Sender<Event>>> = None; extern "C" fn handle_resize(_sig: c_int) { let mut size = winsize { ws_row: 0, ws_col: 0, ws_xpixel: 0, ws_ypixel: 0, }; unsafe { ioctl(STDIN_FILENO, TIOCGWINSZ, &mut size); } let width = size.ws_col as u32; let height = size.ws_row as u32; TERM_WIDTH.store(width, Ordering::SeqCst); TERM_HEIGHT.store(height, Ordering::SeqCst); unsafe { if let Some(chan) = RESIZE_CHANNEL.as_ref() { chan.lock() .unwrap() .send(Event::Resize(width, height)) .expect("Failed to send resize event"); } } } impl Terminal { pub fn listen_for_resize(&mut self) { unsafe { if RESIZE_CHANNEL.is_none() { let (resize_tx, resize_rx) = mpsc::channel(); RESIZE_CHANNEL = Some(Mutex::new(resize_tx)); let senders_arc = self.event_channels.clone(); // FIXME store thread handle somewhere thread::spawn(move || { while let Ok(event) = resize_rx.recv() { // Forward event to all listeners let senders = senders_arc.lock().unwrap(); for tx in &*senders { tx.send(event.clone()).expect("Failed to send event"); } } }); } signal(SIGWINCH, handle_resize as sighandler_t); } self.refresh_size(); } pub fn refresh_size(&self) { handle_resize(SIGWINCH); } pub fn width(&self) -> u32 { TERM_WIDTH.load(Ordering::SeqCst) } pub fn height(&self) -> u32 { TERM_HEIGHT.load(Ordering::SeqCst) } }
use petgraph::graphmap::UnGraphMap; use petgraph::algo::astar; use arrayvec::ArrayString; use std::fs::File; use std::io::{BufReader, BufRead}; use std::io; fn populate_graph(g: &mut UnGraphMap::<ArrayString::<[u8; 3]>, i32>) -> Result<(), io::Error> { let f = File::open("input")?; let br = BufReader::new(f); for line in br.lines() { let input = line?; g.add_edge( ArrayString::from(&input[4..7]).expect(""), ArrayString::from(&input[0..3]).expect(""), 1 ); } Ok(()) } fn main() { let mut g = UnGraphMap::new(); populate_graph(&mut g).expect(""); let directs = g.node_count() - 1; println!("{} direct orbits", directs); let mut indirects = 0; for n in g.nodes() { // Searching undirected increases time by order of magnitude (a few // seconds) vs directed but only have to run once and saves dev time // for next part if let Some((d, _)) = astar(&g, n, |s| {s.as_str() == "COM"}, |_| {1}, |_| {1}) { indirects += std::cmp::max(d, 1) - 1; } } println!("{} indirect orbits", indirects); println!("{} total orbits", directs + indirects); if let Some((d, _)) = astar( &g, ArrayString::from("YOU").expect(""), |s| {s.as_str() == "SAN"}, |_| {1}, |_| {1} ) { println!("YOU are {} bodies away from SAN", d - 2); } else { println!("Couldn't find SAN โ€พ\\_(ใƒ„)_/โ€พ"); } }
extern crate wasmer_runtime; use std::sync::{Arc, Mutex}; use wasmer_runtime::{error, func, imports, instantiate, Array, Ctx, WasmPtr}; // Make sure that the compiled wasm-sample-app is accessible at this path. static WASM: &'static [u8] = include_bytes!("../wasm-sample-app/target/wasm32-unknown-unknown/release/wasm_sample_app.wasm"); fn main() -> error::Result<()> { // create shared data that we'll use in 2 host functions let shared_data = Arc::new(Mutex::new(0usize)); // copy the [`Arc`] and move it into the closure let data = Arc::clone(&shared_data); let print_str2 = move |ctx: &mut Ctx, ptr: WasmPtr<u8, Array>, len: u32| { let memory = ctx.memory(0); // Use helper method on `WasmPtr` to read a utf8 string let string = ptr.get_utf8_string(memory, len).unwrap(); // Get the value from the shared data let guard = data.lock().unwrap(); // Print it! println!("{}: {}", guard, string); }; // Copy the [`Arc`] and move it into the closure let data = Arc::clone(&shared_data); let increment_shared = move || { // get the shared data and increment it let mut guard = data.lock().unwrap(); *guard += 1; }; // Let's define the import object used to import our function // into our webassembly sample application. // // We've defined a macro that makes it super easy. // // The signature tells the runtime what the signature (the parameter // and return types) of the function we're defining here is. // The allowed types are `i32`, `u32`, `i64`, `u64`, // `f32`, and `f64`. // // Make sure to check this carefully! let import_object = imports! { // Define the "env" namespace that was implicitly used // by our sample application. "env" => { // name // the func! macro autodetects the signature "print_str" => func!(print_str), // we can use closures here too "print_str2" => func!(print_str2), "increment_shared" => func!(increment_shared), }, }; // Compile our webassembly into an `Instance`. let instance = instantiate(WASM, &import_object)?; // Call our exported function! instance.call("hello_wasm", &[])?; Ok(()) } // Let's define our "print_str" function. // // The declaration must start with "extern" or "extern "C"". fn print_str(ctx: &mut Ctx, ptr: WasmPtr<u8, Array>, len: u32) { // Get a slice that maps to the memory currently used by the webassembly // instance. // // Webassembly only supports a single memory for now, // but in the near future, it'll support multiple. // // Therefore, we don't assume you always just want to access first // memory and force you to specify the first memory. let memory = ctx.memory(0); // Use helper method on `WasmPtr` to read a utf8 string let string = ptr.get_utf8_string(memory, len).unwrap(); // Print it! println!("{}", string); }
use std::{collections::HashSet, str::FromStr, usize}; use lazy_static::lazy_static; use regex::{Regex}; // compile regex statically so it does not have to be recompiled in loop iterations lazy_static! { static ref re_statement: Regex = Regex::new(r"(\w{3})\s+([+-])(\d+)").unwrap(); } pub fn day8 () { let example_input = std::fs::read_to_string("inputs/d8.example").unwrap(); let input = std::fs::read_to_string("inputs/d8").unwrap(); let mut example_vm = Vm::from_script(&example_input); for statement in &example_vm.script { println!("{:?}", statement); } println!("Example final acc value: {}", example_vm.run_all()) // let vm = Vm::from_script(&input); } // Let's implement this week's task in a more OO-like fashion instead of the rather functional approach of the last weeks #[derive(Clone, Debug, Default)] struct Vm { ip_pos: usize, previously_executed: HashSet<usize>, acc: i64, pub script: Vec<Statement>, loop_found: bool, // when an endless loop is entered or the end of the script is reached } // Missing information in the instructions: What happens when 'jmp' ing outside of the scripts bounds? impl Vm { pub fn from_script(script: &str) -> Self { let statements = script .lines() .map(|line| line.parse::<Statement>().unwrap()); Self { script: statements.collect(), ..Default::default() } } // Returns state changes instead of applying them directly to be easily testable // returns if a loop was found, the new ip_pos, the new acc value fn step(&self) -> (bool, usize, i64) { // false if already contained, so negate the value let loop_found = !self.previously_executed.insert(self.ip_pos); let mut jumped = false; let mut new_ip_pos = self.ip_pos; let mut new_acc = self.acc; let statement = self.script[self.ip_pos]; match statement.instruction { Instruction::Nop => (), Instruction::Acc => new_acc += statement.value, // instruction pointer is a usize, we have to perform a conversion Instruction::Jmp => { // if statement.value >= 0 { // self.ip_pos + statement.value // } else { // self.ip_pos -= usize::try_from(statement.value.abs()) // } jumped = true; new_ip_pos = self.ip_pos.wrapping_add(statement.value as usize); }, } if !jumped { new_ip_pos += 1; } println!("{:?}", (loop_found, new_ip_pos, new_acc)); (loop_found, new_ip_pos, new_acc) } /// runs the entire script and returns the final acc value /// termination happens /// a) at the end of the script /// b) when an inifinite loop is entered (a previously visited ip position is visited again) pub fn run_all(&mut self) -> i64 { let mut loop_found = false; while !loop_found && self.ip_pos < self.script.len() { let (l, ip_pos, acc) = self.step(); loop_found = l; self.ip_pos = ip_pos; self.acc = acc; } self.acc } } #[derive(Clone, Copy, Debug)] enum Instruction { Nop, Acc, Jmp, } impl FromStr for Instruction { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "nop" => Ok(Self::Nop), "acc" => Ok(Self::Acc), "jmp" => Ok(Self::Jmp), _ => Err("Failed to parse instruction") } } } #[derive(Clone, Copy, Debug)] struct Statement { instruction: Instruction, value: i64, } impl FromStr for Statement { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { let captures = re_statement.captures(s); if let Some(captures) = captures { let instruction = captures[1].parse::<Instruction>()?; let sign = &captures[2]; let digit = match captures[3].parse::<u32>() { Ok(u32) => u32, Err(_) => return Err("Failed to parse integer digit."), }; let value = match sign { "+" => i64::from(digit), "-" => -1_i64 * i64::from(digit), _ => panic!(), // this case is impossible to reach. The other cases are guaranteed to be true based on the regular expression }; Ok( Self { instruction, value}) } else { Err("No match found.") } } }
use clearTimeout; use setTimeout; use MessageEvent; use WebSocket; use carrier_core::dns::DnsRecord; use carrier_core::identity::{Address, Identity, Secret, SignedAddress}; use carrier_core::noise; use carrier_core::packet::{EncryptedPacket, RoutingKey}; use carrier_core::rpc::{self, CallHandler}; use carrier_core::transport::{self, ChannelProgress}; use failure::Error; use js_sys; use std::collections::HashMap; use std::mem; use std::sync::{Arc, Mutex}; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; pub enum State { Invalid, XInit, Hs { noise: noise::HandshakeRequester }, Transport, } pub struct Endpoint { pub ws: Arc<WebSocket>, pub state: State, pub secret: Secret, pub on_connect: Box<FnMut(Arc<Mutex<Channel>>)>, pub recv_closure: Option<Closure<FnMut(MessageEvent)>>, pub close_closure: Option<Closure<FnMut()>>, pub channels: HashMap<RoutingKey, Arc<Mutex<Channel>>>, } pub struct Channel { pub ep: Arc<Mutex<Endpoint>>, pub transport: transport::Channel, pub streams: HashMap<u32, Box<CallHandler<Channel>>>, pub activate_closure: Option<Closure<FnMut()>>, pub timer_id: u32, } impl Channel { pub fn new(ep: Arc<Mutex<Endpoint>>, transport: transport::Channel) -> Arc<Mutex<Self>> { let s = Arc::new(Mutex::new(Self { activate_closure: None, timer_id: 0, streams: HashMap::new(), transport, ep, })); let s_ = s.clone(); s.lock().unwrap().activate_closure = Some(Closure::new(move || { s_.lock().unwrap().activate(); })); s.lock().unwrap().wakeup(); s } pub fn get_free_stream_id(&self) -> u32 { for i in 1..<u32>::max_value() { if i % 2 == 0 { continue; } if !self.streams.contains_key(&i) { return i; } } panic!("out of streams"); } pub fn wakeup(&mut self) { clearTimeout(self.timer_id); self.timer_id = setTimeout(&self.activate_closure.as_ref().unwrap(), 10); } pub fn activate(&mut self) -> Result<(), Error> { clearTimeout(self.timer_id); let mut cont = true; while cont { let progress = self.transport.progress()?; match progress { ChannelProgress::Later(d) => { let d = d.as_secs() as u32 * 1000 + d.subsec_millis(); self.timer_id = setTimeout(&self.activate_closure.as_ref().unwrap(), d); trace!("ChannelProgress::Later {:?}", d); cont = false; } ChannelProgress::SendPacket(b) => { self.ep.lock().unwrap().ws.send(b); } ChannelProgress::ReceiveHeader(stream, b) => { warn!("received header, but we dont expect any"); } ChannelProgress::ReceiveStream(stream, b) => { let streams = &mut self.streams as *mut HashMap<u32, Box<CallHandler<Channel>>>; if let Some(mut h) = unsafe { &mut *streams }.get_mut(&stream) { h.recv(self, b); } } ChannelProgress::Close(stream) => { let streams = &mut self.streams as *mut HashMap<u32, Box<CallHandler<Channel>>>; if let Some(mut h) = unsafe { &mut *streams }.get_mut(&stream) { h.close(self); } } ChannelProgress::Disconnect => { panic!("disconnect!"); break; } } let mut removeme = Vec::new(); let streams = &mut self.streams as *mut HashMap<u32, Box<CallHandler<Channel>>>; for (stream, h) in unsafe { &mut *streams } { trace!("poll stream {}", stream); loop { match h.progress(self).unwrap() { rpc::Progress::Wait => { break; } rpc::Progress::Close => { self.transport.close(*stream); cont = true; } rpc::Progress::Header(b) => { self.transport.header(*stream, b); cont = true; } rpc::Progress::Stream(b) => { self.transport.stream(*stream, b); cont = true; } rpc::Progress::Done => { removeme.push(*stream); break; } } } } for remove in removeme { self.streams.remove(&remove); } } Ok(()) } } impl Drop for Channel { fn drop(&mut self) { debug!("endpoint dropped"); clearTimeout(self.timer_id); } } impl Endpoint { pub fn new<F>(ws: &str, secret: Secret, onconnect: F) where F: 'static + FnMut(Arc<Mutex<Channel>>), { let ws = Arc::new(WebSocket::new(ws)); ws.set_binaryType("arraybuffer"); let s = Arc::new(Mutex::new(Self { ws: ws.clone(), state: State::XInit, secret, recv_closure: None, close_closure: None, channels: HashMap::new(), on_connect: Box::new(onconnect), })); let s_ = s.clone(); s.lock().unwrap().recv_closure = Some(Closure::new(move |ev: MessageEvent| { let s = s_.clone(); s_.lock().unwrap().onmessage(s, ev); })); ws.set_onmessage(&s.lock().unwrap().recv_closure.as_ref().unwrap()); let s_ = s.clone(); s.lock().unwrap().close_closure = Some(Closure::new(move || { debug!("websocket disconnect"); let mut s = s_.lock().unwrap(); s.recv_closure = None; s.close_closure = None; for (_, ch) in s.channels.drain() {} })); ws.set_onclose(&s.lock().unwrap().close_closure.as_ref().unwrap()); } pub fn onmessage(&mut self, s: Arc<Mutex<Endpoint>>, ev: MessageEvent) { trace!("onmsg"); let data = ev.data(); if data.is_string() { let record = DnsRecord::from_signed_txt(&ev.data().as_string().unwrap()).unwrap(); match mem::replace(&mut self.state, State::Invalid) { State::XInit => { let timestamp = js_sys::Date::now() as u64; let (noise, pkt) = noise::initiate(&record.x, &self.secret, timestamp).unwrap(); self.ws.send(pkt.encode()); self.state = State::Hs { noise } } any => self.state = any, } } else { let bin: js_sys::ArrayBuffer = data.dyn_into().unwrap(); let mut b = vec![0; bin.byte_length() as usize]; let view = js_sys::DataView::new(&bin, 0, bin.byte_length() as usize); for i in 0..bin.byte_length() as usize { b[i] = view.get_uint8(i); } let pkt = EncryptedPacket::decode(&b).unwrap(); match mem::replace(&mut self.state, State::Invalid) { State::Hs { mut noise } => { let route = pkt.route; let identity = noise.recv_response(pkt).unwrap(); let noise = noise.into_transport().unwrap(); info!("connection established with {}", identity); let transport = transport::Channel::new(noise, format!("ws2p:{}", identity)); self.state = State::Transport {}; let mut channel = Channel::new(s, transport); (self.on_connect)(channel.clone()); self.channels.insert(route, channel); } State::Transport => { let mut wakeup = false; if let Some(channel) = self.channels.get_mut(&pkt.route) { if let Err(e) = channel.lock().unwrap().transport.recv(pkt) { error!("{}", e); } channel.lock().unwrap().wakeup(); } else { warn!("received pkt for unknown route {}", pkt.route); } self.state = State::Transport; } any => self.state = any, } } } }
#![feature(start)] extern crate GolfManiaLib as glib; mod view; mod login_logic; use glib::model::{score_card}; use glib::model::map::*; use view::console; #[start] fn main( argc : isize, argv: *const *const u8 ) -> isize { let test : Map = MapBuilder::from_named(None).unwrap(); for thing in test.into_iter() { //println!("{:?}", thing); } 1337 }
mod query_subcommand { use std::process::Command; use assert_cmd::prelude::*; fn build_cmd() -> Command { let mut cmd = Command::cargo_bin("qsv").unwrap(); cmd.arg("query"); cmd } #[test] fn it_can_run_the_commandline_for_a_simple_query() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = build_cmd(); cmd.arg("SELECT 1 = 1"); cmd.assert().success(); Ok(()) } #[test] fn it_errors_if_no_query_is_passed() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = build_cmd(); cmd.assert() .failure() .stderr(predicates::str::contains( "The following required arguments were not provided", )) .stderr(predicates::str::contains("<query>")); Ok(()) } #[test] fn it_will_run_a_simple_query_with_subqueries() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = build_cmd(); cmd.arg("select * from (select * from (select*from ./testdata/occupations.csv))"); cmd.assert().success(); Ok(()) } #[test] fn it_will_run_a_simple_query_with_spaces_in_filename() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = build_cmd(); cmd.arg( "select * from (select * from (select*from `./testdata/occupations with spaces.csv`))", ); cmd.assert().success(); Ok(()) } #[test] fn it_will_run_a_simple_query_with_ctes() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = build_cmd(); cmd.arg("with some_cte (age) as (select distinct(age) from testdata/people.csv where age <> 13) select * from testdata/occupations.csv occupation INNER JOIN some_cte on (occupation.minimum_age = some_cte.age)"); cmd.assert().success(); Ok(()) } #[test] fn it_will_run_a_simple_query_with_unions() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = build_cmd(); cmd.arg("select age from ./testdata/people.csv union select minimum_age as age from ./testdata/occupations.csv"); cmd.assert().success(); Ok(()) } #[test] fn it_will_run_a_simple_query_with_sqrt_on_float() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = build_cmd(); cmd.arg("select sqrt(12374)"); cmd.assert() .success() .stdout(predicates::str::contains("111.23848254988019")); Ok(()) } #[test] fn it_will_run_a_simple_query_with_sqrt_on_integer() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = build_cmd(); cmd.arg("select sqrt(4)"); cmd.assert() .success() .stdout(predicates::str::contains("2")); Ok(()) } #[test] fn it_will_run_a_simple_query_with_md5() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = build_cmd(); cmd.arg("select md5('foobar')"); cmd.assert().success().stdout(predicates::str::contains( "3858f62230ac3c915f300c664312c63f", )); Ok(()) } #[test] fn it_will_run_a_simple_query_with_stddev() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = build_cmd(); cmd.arg("select stddev(number) from testdata/statistical.csv"); cmd.assert() .success() .stdout(predicates::str::contains("1.7078251276599")); Ok(()) } #[test] fn it_will_run_with_an_alternate_delimiter() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = build_cmd(); cmd.arg("select min(minimum_age) from testdata/slash_as_separator.csv"); cmd.arg("--delimiter=/"); cmd.assert() .success() .stdout(predicates::str::contains("25")); Ok(()) } #[test] fn it_will_run_with_trim() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = build_cmd(); cmd.arg("select min(minimum_age) from testdata/occupations_with_extraneous_spaces.csv"); cmd.arg("--trim"); cmd.assert().success(); Ok(()) } #[test] fn it_will_run_with_textonly() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = build_cmd(); cmd.arg("select md5(column) from testdata/sortable_columns.csv"); cmd.arg("--textonly"); cmd.assert().success(); Ok(()) } #[test] fn it_will_run_a_query_from_a_gz_file() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = build_cmd(); cmd.arg("select * from testdata/people.csv.gz"); cmd.assert().success(); Ok(()) } #[test] fn it_will_run_a_query_and_output_header() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = build_cmd(); cmd.arg("select * from testdata/people.csv"); cmd.arg("--output-header"); cmd.assert() .success() .stdout(predicates::str::contains("name,age")); Ok(()) } #[test] fn it_will_handle_a_column_of_floats() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = build_cmd(); cmd.arg("select avg(number) from testdata/all_floats.csv"); cmd.arg("--textonly"); cmd.assert() .success() .stdout(predicates::str::contains("2.5100000000000002")); Ok(()) } #[test] fn it_will_handle_a_column_of_mixed_floats() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = build_cmd(); cmd.arg("select avg(number) from testdata/mixed_floats.csv"); cmd.arg("--textonly"); cmd.assert() .success() .stdout(predicates::str::contains("2.14")); Ok(()) } #[test] fn it_rejects_multiple_sql_statements_in_query() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = build_cmd(); cmd.arg("select 1 = 1;select 1 = 1;"); cmd.arg("--textonly"); cmd.assert().failure().stderr(predicates::str::contains( "Expected exactly one SQL statement in query input", )); Ok(()) } #[test] fn it_succeeds_with_a_single_statement_ended_with_semicolon( ) -> Result<(), Box<dyn std::error::Error>> { let mut cmd = build_cmd(); cmd.arg("select 1 = 1;"); cmd.arg("--textonly"); cmd.assert().success(); Ok(()) } #[test] fn it_succeeds_with_a_csv_with_spaces_in_headers() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = build_cmd(); cmd.arg("select \"minimum age\" from testdata/occupations_with_spaces_in_headers.csv"); cmd.assert().success(); Ok(()) } #[test] fn it_succeeds_without_running_sql_in_file_headers() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = build_cmd(); cmd.arg("select \"minimum age\" from testdata/sql_injection.csv"); cmd.assert().success(); Ok(()) } } mod analyze_subcommand { use std::process::Command; use assert_cmd::prelude::*; use predicates::str::contains; fn build_cmd() -> Command { let mut cmd = Command::cargo_bin("qsv").unwrap(); cmd.arg("analyze"); cmd } #[test] fn it_can_run_the_commandline_for_a_simple_query() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = build_cmd(); cmd.arg("SELECT 1 = 1"); cmd.assert().success(); Ok(()) } #[test] fn it_errors_if_no_query_is_passed() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = build_cmd(); cmd.assert() .failure() .stderr(contains( "The following required arguments were not provided", )) .stderr(contains("<query>")); Ok(()) } #[test] fn it_will_run_a_simple_query_with_subqueries() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = build_cmd(); cmd.arg("select * from (select * from (select*from ./testdata/occupations.csv))"); cmd.assert() .success() .stdout(contains("./testdata/occupations.csv:")) .stdout(contains("minimum_age -> integer")) .stdout(contains("occupation -> text")); Ok(()) } #[test] fn it_will_run_a_simple_query_with_spaces_in_filename() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = build_cmd(); cmd.arg( "select * from (select * from (select*from `./testdata/occupations with spaces.csv`))", ); cmd.assert().success(); Ok(()) } #[test] fn it_will_run_a_simple_query_with_unions() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = build_cmd(); cmd.arg("select age from ./testdata/people.csv union select minimum_age as age from ./testdata/occupations.csv"); cmd.assert() .success() .stdout(contains("./testdata/occupations.csv:")) .stdout(contains("minimum_age -> integer")) .stdout(contains("occupation -> text")) .stdout(contains("./testdata/people.csv:")) .stdout(contains("name -> text")) .stdout(contains("age -> integer")); Ok(()) } } mod stats_subcommand { use std::process::Command; use assert_cmd::prelude::*; use predicates::str::contains; fn build_cmd() -> Command { let mut cmd = Command::cargo_bin("qsv").unwrap(); cmd.arg("stats"); cmd } #[test] fn it_can_run_the_commandline_for_a_simple_query() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = build_cmd(); cmd.arg("testdata/statistical.csv"); cmd.assert() .success() .stdout(contains("Mean: 3.50000")) .stdout(contains("Stddev: 1.707")) .stdout(contains("Min: 1")) .stdout(contains("Max: 6")) .stdout(contains("Unique: 6")); Ok(()) } #[test] fn it_errors_if_no_query_is_passed() -> Result<(), Box<dyn std::error::Error>> { let mut cmd = build_cmd(); cmd.assert() .failure() .stderr(contains( "The following required arguments were not provided", )) .stderr(contains("<filename>")); Ok(()) } }
/// Position is a (row, col) position on a Grid. /// /// For example such table has 4 cells. /// Which indexes are (0, 0), (0, 1), (1, 0), (1, 1). /// /// ```text /// โ”Œโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ” /// โ”‚ 0 โ”‚ 1 โ”‚ /// โ”œโ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”ค /// โ”‚ 1 โ”‚ 2 โ”‚ /// โ””โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”˜ /// ``` pub type Position = (usize, usize);
use super::Value; use crate::value::Quotes; use std::default::Default; use std::fmt; /// the actual arguments of a function or mixin call. /// /// Each argument has a Value. Arguments may be named. /// If the optional name is None, the argument is positional. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd)] pub struct CallArgs(pub Vec<(Option<String>, Value)>); impl CallArgs { pub fn new(v: Vec<(Option<String>, Value)>) -> Self { CallArgs(v) } pub fn from_value(v: Value) -> Self { match v { Value::List(v, _, false) => { if let [Value::Map(map), Value::Literal(mark, Quotes::None)] = &v[..] { if mark == "..." { return CallArgs( map.iter() .map(|(k, v)| { ( match k { Value::Null => None, Value::Literal(s, _) => { Some(s.clone()) } _x => None, // TODO return Err(Error::bad_value("string", &x)), }, v.clone(), ) }) .collect(), ); } } CallArgs(v.into_iter().map(|v| (None, v)).collect()) } v => CallArgs(vec![(None, v)]), } } pub fn iter(&self) -> ::std::slice::Iter<(Option<String>, Value)> { self.0.iter() } pub fn len(&self) -> usize { self.0.len() } pub fn is_empty(&self) -> bool { self.0.is_empty() } pub fn get(&self, index: usize) -> Option<&(Option<String>, Value)> { self.0.get(index) } } impl Default for CallArgs { fn default() -> Self { CallArgs(vec![]) } } impl fmt::Display for CallArgs { fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result { let t = self .0 .iter() .map(|kv| match *kv { (Some(ref k), ref v) => { format!("${}: {}", k, v.format(Default::default())) } (None, ref v) => format!("{}", v.format(Default::default())), }) .collect::<Vec<_>>() .join(", "); write!(out, "{}", t) } }
// // Copyright ยฉ 2017, ACM@UIUC // // This file is part of the Groot Project. // // The Groot Project is open source software, released under the // University of Illinois/NCSA Open Source License. You should have // received a copy of this license in a file with the distribution. mod server; fn main() { server::canopy::canopy_server(); }
//! # Message Broker //! //! This module contains the message broker client interface through which actor modules access //! a bound `wascc:messaging` capability provider use wapc_guest::host_call; const CAPID_MESSAGING: &str = "wascc:messaging"; use crate::HandlerResult; use codec::messaging::{BrokerMessage, RequestMessage, OP_PERFORM_REQUEST, OP_PUBLISH_MESSAGE}; use codec::serialize; use wascc_codec as codec; /// Create a new named message broker host binding pub fn host(binding: &str) -> MessageBrokerHostBinding { MessageBrokerHostBinding { binding: binding.to_string(), } } /// Create a default message broker host binding pub fn default() -> MessageBrokerHostBinding { MessageBrokerHostBinding { binding: "default".to_string(), } } /// Exposes message broker functionality to actor modules pub struct MessageBrokerHostBinding { binding: String, } impl MessageBrokerHostBinding { /// Publishes a message on a given subject with an optional reply subject pub fn publish( &self, subject: &str, reply_to: Option<&str>, payload: &[u8], ) -> HandlerResult<()> { let cmd = BrokerMessage { subject: subject.to_string(), reply_to: reply_to.map_or("".to_string(), |r| r.to_string()), body: payload.to_vec(), }; host_call( &self.binding, CAPID_MESSAGING, OP_PUBLISH_MESSAGE, &serialize(cmd)?, ) .map_err(|e| e.into()) .map(|_vec| ()) } /// Publishes a message and expects a reply to come back within a given timeout (in milliseconds) pub fn request( &self, subject: &str, payload: &[u8], timeout_ms: u64, ) -> HandlerResult<Vec<u8>> { let cmd = RequestMessage { subject: subject.to_string(), timeout_ms: timeout_ms as _, body: payload.to_vec(), }; // The broker plugin applies no wrapper around the response from the broker, the // raw payload is delivered. host_call( &self.binding, CAPID_MESSAGING, OP_PERFORM_REQUEST, &serialize(cmd)?, ) .map_err(|e| e.into()) } }
// MIT License // // Copyright (c) 2021 Ferhat GeรงdoฤŸan All Rights Reserved. // Distributed under the terms of the MIT License. // // use { crate::{ ast::{ ast_helpers::{ to, from_module }, GreteaKeywords }, parser::{GreteaParser}, tokenizer::gretea_tokenizer::{TOKEN_LIST}, optimize::{ OptimizeBlocks, optimizer } }, std::collections::{BTreeMap} }; use crate::ast::GreteaFunctionData; pub struct GreteaCodegen { pub generated: String, pub sources : BTreeMap<String, bool>, pub optimize : bool } pub struct CodegenData { pub return_type: String, pub arguments : Vec<String> } impl GreteaCodegen { pub fn import(&mut self, subdirectory: String) { let subdirectories: Vec<String> = subdirectory.split('.') .map(|data| data.to_string()).collect(); let mut dir = String::new(); let mut is_stl = false; for lol in subdirectories { if lol == "tea" { is_stl = true; } dir.push_str(format!("{}/", lol).as_str()); } dir.pop(); dir = to(dir.trim()); self.sources .insert(dir.clone(), is_stl); self.generated.push_str( &*format!("#{}{}{}.hpp{}\n", "include", if is_stl { '"' } else { '"' }, dir.replace('\n', "").split('/').last().unwrap(), if is_stl { '"' } else { '"' })); } pub fn function(&mut self, parser : &mut GreteaParser, args : &BTreeMap<String, String>, name : &String, return_val: &String, generic : &String, is_expand : bool, is_void : bool) { if !generic.is_empty() { self.generated.push_str(format!("template<typename{} {}>\n", if is_expand { "..." } else { "" }, generic).as_str()) } parser.func_data.push(GreteaFunctionData { __function_name : name.clone(), __function_return_type: return_val.clone(), __function_arguments : args.clone() }); let mut arguments = String::new(); for map in args.iter() { // ^^^ (name, type) -> (type, name) arguments.push_str(&*format!("{} {},", map.1.clone(), map.0.clone())); } arguments.pop(); self.generated.push_str(&*format!("{} {}({}) {}\n", return_val, name, arguments, if is_void { "{" } else { "" })); } pub fn function_call(&mut self, args: &Vec<String>, name: &String, is_unpack: bool) { let mut arguments = String::new(); if name != &"main" { for arg in args.iter() { arguments.push_str(&*format!("{},", arg)); } arguments.pop(); } self.generated.push_str(&*format!("{}{}({}){};\n", if is_unpack { "(" } else { "" }, name, arguments, if is_unpack { ", ...)" } else { "" })); } pub fn variable_definition(&mut self, data: &String, var_type: &String, name: &String, is_mut: bool) { let __data = format!("= {};", data).clone(); self.generated.push_str(&*format!("{} {} {} {}\n", if !is_mut { "const" } else { "" }, if var_type.is_empty() { "auto" } else { var_type }, name, if data.is_empty() { ";" } else { __data.as_str() })); } pub fn preprocess_set(&mut self, data: &String, name: &String) { self.generated.push_str(&*format!("#define {} {}\n", name, if !data.is_empty() { data } else { "0" })); } pub fn statement(&mut self, tokens: &Vec<String>, is_while: bool) { if !is_while && tokens.last().unwrap() == "else" { self.generated.push_str(format!("{} {{\n", "else").as_str()); } else { let mut is_else_if = false; let mut statement = String::from( format!("{} {}", tokens.get(0).unwrap(), if !is_while && tokens.get(1).unwrap() == "if" { is_else_if = true; "if(" } else { "(" })); for token in if self.optimize { optimizer::optimize(tokens, OptimizeBlocks::StatementBool) } else { tokens.clone() }.iter().skip( if is_else_if { 2 } else { 1 }) { statement.push_str(format!("{}", from_module(token)).as_str()); } self.generated.push_str(format!("{}) {{\n", statement).as_str()); } } pub fn statement_directive(&mut self, tokens: &Vec<String>) { if tokens.last().unwrap() == "else" { self.generated.push_str(format!("#{}\n", "else").as_str()); } else { let mut is_else_if = false; let mut statement = String::from( format!("#{} ", if tokens.get(1).unwrap() == "if" { is_else_if = true; "elif" } else { "if" })); for token in tokens.iter().skip( if is_else_if { 2 } else { 1 }) { statement.push_str(format!("{}", token).as_str()); } self.generated.push_str(format!("{}\n", statement).as_str()); } } pub fn directive_end(&mut self) { self.generated.push_str(format!("#{}\n", "endif").as_str()); } pub fn module(&mut self, module_name: &String) { self.generated.push_str(format!("namespace {}", module_name).as_str()); } pub fn structure(&mut self, struct_name: &String, struct_generic: &String) { self.generated.push_str(format!("{}class {}\n", if !struct_generic.is_empty() { format!("template<typename {}>\n", struct_generic) } else { to("") }, struct_name).as_str()); } pub fn structure_var(&mut self, name: &String, data: &String) { self.generated.push_str(format!(".{} = {}", name, data).as_str()); } pub fn enumeration(&mut self, name: &String, _type: &String, data: &String) { self.generated.push_str(format!("enum {} {} {{\n{}\n}};", name, if !_type.is_empty() { format!(": {}", _type.clone()) } else { to("") }, data).as_str()); } pub fn for_loop(&mut self) { self.generated.push_str("while(1)"); } pub fn for_iter(&mut self, var_name: &String, var_iter: &String) { self.generated.push_str(format!("for(auto {} : {})", var_name, var_iter).as_str()); } pub fn for_continue(&mut self) { self.generated.push_str("continue;\n"); } pub fn for_break(&mut self) { self.generated.push_str("break;\n"); } pub fn return_variable(&mut self, return_variable: &String) { self.generated.push_str(format!("return {};", if return_variable.is_empty() { "" } else { return_variable.as_str() }).as_str()) } pub fn header_guards(&mut self) { self.generated.push_str(format!("#{} {}\n", "pragma", "once").as_str()); } pub fn assembly(&mut self, data: &String) { let mut is_direct = false; // No compiler-specific. self.generated.push_str("asm(\n"); for line in data.split('\n') { if is_direct { if line.trim() == "_?" { is_direct = false; continue; } self.generated.push_str(format!("{}\n", line).as_str()); continue; } if line.trim() == "?_" { is_direct = true; continue; } if line.len() >= 2 { self.generated.push_str(format!("\"{}\"\n", line).as_str()); } } self.generated.push_str(");\n"); } pub fn cpp_vector(&mut self, __type: &String) { self.generated.push_str(&*format!("std::vector<{}>", __type)); } pub fn character(&mut self, character: &String) { self.generated.push_str(&*format!("{}\n", character)); } }
use crate::AsTable; use clap::{crate_authors, crate_version, App, AppSettings, Arg, ArgMatches}; use digitalocean::prelude::*; use failure::Error; use serde; use serde_json; use serde_yaml; use toml; mod account; pub use self::account::Root as Account; mod certificate; pub use self::certificate::Root as Certificate; mod droplet; pub use self::droplet::Root as Droplet; mod domain; pub use self::domain::Root as Domain; mod ssh_key; pub use self::ssh_key::Root as SshKey; mod region; pub use self::region::Root as Region; mod infrastructure; pub use self::infrastructure::Root as Infrastructure; /// `Component`s are `clap::App`s. Just call them with `app` to get the Clap `App`/`Subcommand` /// object. (Yes you can just use an `App`, cool huh?) then later use `handle()` to chain the args /// in. /// /// `Component`s are deliberately simple: They just take a `digitalocean::DigitalOcean` client and /// the `clap::ArgMatches` when they handle the request. This means splitting one into its own app, /// or integrating it with another `clap::App` is ridiculously simple. If you want tighter /// integration please check out the `DigitalOcean` crate. pub trait Component { /// The default output style of the `Component`. For non-outputting parts of the component /// chain this is `None`. const DEFAULT_OUTPUT: Option<&'static str> = None; /// Builds the `clap::App` that corresponds to this `Component`. fn app() -> App<'static, 'static>; /// Handle the request with some `ArgMatches`. This does one of two things: /// 1. It finalizes and terminates a request. /// 2. Invoke another `Component`. Eg. With `ocean droplet create` the /// `component::droplet::Root` compnent which would call the `component::droplet::Create` /// component. fn handle(client: DigitalOcean, arg_matches: &ArgMatches) -> Result<(), Error>; /// Handles outputting the values appropriately. fn output<T>(values: T, format: Option<&str>) -> Result<(), Error> where T: serde::ser::Serialize + ::std::fmt::Debug + AsTable, { match format.or(Self::DEFAULT_OUTPUT) { Some("debug") => println!("{:#?}", values), Some("json") => println!("{}", serde_json::to_string_pretty(&values)?), Some("toml") => { // This is a slightly nasty workaround for // https://github.com/alexcrichton/toml-rs/issues/142 let workaround = toml::value::Value::try_from(&values)?; println!("{}", toml::to_string_pretty(&workaround)?) } Some("yaml") => println!("{}", serde_yaml::to_string(&values)?), Some("table") => values.as_table(), _ => unreachable!(), }; Ok(()) } } /// The root of the application. pub struct Root; impl Component for Root { fn app() -> App<'static, 'static> { App::new(env!("CARGO_PKG_NAME")) .version(crate_version!()) .author(crate_authors!()) .about(env!("CARGO_PKG_DESCRIPTION")) .global_settings(&[ AppSettings::ColoredHelp, AppSettings::GlobalVersion, AppSettings::InferSubcommands, ]) .setting(AppSettings::SubcommandRequired) .arg( Arg::with_name("token") .long("token") .short("t") .value_name("TOKEN") .help("The DigitalOcean API key to use") .required(false) .takes_value(true), ) .arg( Arg::with_name("output") .long("output") .short("o") .help("Output in a given format") .takes_value(true) .possible_values(&["json", "yaml", "toml", "table", "debug"]) .required(false) .global(true), ) .subcommand(Account::app()) .subcommand(Certificate::app()) .subcommand(Droplet::app()) .subcommand(Domain::app()) .subcommand(Infrastructure::app()) .subcommand(SshKey::app()) .subcommand(Region::app()) } fn handle(client: DigitalOcean, arg_matches: &ArgMatches) -> Result<(), Error> { match arg_matches.subcommand() { ("account", Some(arg_matches)) => Account::handle(client, arg_matches), ("certificate", Some(arg_matches)) => Certificate::handle(client, arg_matches), ("droplet", Some(arg_matches)) => Droplet::handle(client, arg_matches), ("domain", Some(arg_matches)) => Domain::handle(client, arg_matches), ("key", Some(arg_matches)) => SshKey::handle(client, arg_matches), ("infrastructure", Some(arg_matches)) => Infrastructure::handle(client, arg_matches), ("region", Some(arg_matches)) => Region::handle(client, arg_matches), _ => panic!("Unknown subcommand provided"), } } }
//! Sx127x LoRa mode definitions //! //! Copyright 2019 Ryan Kurte pub use super::common::*; /// LoRa Radio Configuration Object #[derive(Copy, Clone, PartialEq, Debug)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct LoRaConfig { /// LoRa Frequency hopping configuration (defaults to disabled) pub frequency_hop: FrequencyHopping, /// Preamble length in symbols (defaults to 0x8) /// (note that hardware adds four additional symbols in LoRa mode) pub preamble_len: u16, /// Payload length configuration (defaults to Variable / Explicit header mode) pub payload_len: PayloadLength, /// Payload RX CRC configuration (defaults to enabled) pub payload_crc: PayloadCrc, /// IQ inversion configuration (defaults to disabled) pub invert_iq: bool, /// TxSingle timeout value (defaults to 0x64) pub symbol_timeout: u16, } impl Default for LoRaConfig { fn default() -> Self { LoRaConfig { preamble_len: 0x8, symbol_timeout: 0x64, payload_len: PayloadLength::Variable, payload_crc: PayloadCrc::Enabled, frequency_hop: FrequencyHopping::Disabled, invert_iq: false, } } } /// LoRa radio channel configuration #[derive(Copy, Clone, PartialEq, Debug)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr(feature = "serde", serde(default))] pub struct LoRaChannel { /// LoRa frequency in Hz (defaults to 434 MHz) pub freq: u32, /// LoRa channel bandwidth (defaults to 125kHz) pub bw: Bandwidth, /// LoRa spreading factor (defaults to SF7) pub sf: SpreadingFactor, /// LoRa coding rate (defaults to 4/5) pub cr: CodingRate, } impl Default for LoRaChannel { fn default() -> Self { Self { freq: 434e6 as u32, bw: Bandwidth::Bw125kHz, sf: SpreadingFactor::Sf7, cr: CodingRate::Cr4_5, } } } pub const BANDWIDTH_MASK: u8 = 0b1111_0000; /// LoRa channel bandwidth in kHz #[allow(non_snake_case)] #[derive(Copy, Clone, PartialEq, Debug)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum Bandwidth { /// 62.5kHz bandwidth //Bandwidth62_5kHz = 0b0110_0000, /// 125kHz bandwidth Bw125kHz = 0b0111_0000, /// 250kHz bandwidth Bw250kHz = 0b1000_0000, /// 500kHz bandwidth Bw500kHz = 0b1001_0000, } pub const SPREADING_FACTOR_MASK: u8 = 0b1111_0000; /// LoRa spreading factor in chips / symbol #[derive(Copy, Clone, PartialEq, Debug)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum SpreadingFactor { /// Sf6: 64 chips / symbol Sf6 = 0b0110_0000, /// Sf7: 128 chips / symbol Sf7 = 0b0111_0000, /// Sf8: 256 chips / symbol Sf8 = 0b1000_0000, /// Sf9: 512 chips / symbol Sf9 = 0b1001_0000, /// Sf10: 1024 chips / symbol Sf10 = 0b1010_0000, /// Sf11: 2048 chips / symbol Sf11 = 0b1011_0000, /// Sf12: 4096 chips / symbol Sf12 = 0b1100_0000, } pub const CODERATE_MASK: u8 = 0b0000_1110; #[derive(Copy, Clone, PartialEq, Debug)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum CodingRate { /// LoRa Coding rate 4/5 Cr4_5 = 0b0000_0010, /// LoRa Coding rate 4/6 Cr4_6 = 0b0000_0100, /// LoRa Coding rate 4/7 Cr4_7 = 0b0000_0110, /// LoRa Coding rate 4/8 Cr4_8 = 0b0000_1000, } pub const IMPLICITHEADER_MASK: u8 = 0b0000_0001; pub const IMPLICITHEADER_ENABLE: u8 = 0b0000_0001; pub const IMPLICITHEADER_DISABLE: u8 = 0b0000_0000; pub const RXPAYLOADCRC_MASK: u8 = 0b0000_0100; /// Payload RX CRC configuration #[derive(Copy, Clone, PartialEq, Debug)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum PayloadCrc { Disabled = 0x00, Enabled = 0x04, } pub const SYMBTIMEOUTMSB_MASK: u8 = 0b0000_0011; pub const ACG_AUTO_ON_MASK: u8 = 0b0000_0100; pub const ACG_AUTO_ON_ENABLED: u8 = 0b0000_0100; pub const ACG_AUTO_ON_DISABLED: u8 = 0b0000_0000; pub const LOWDATARATEOPTIMIZE_MASK: u8 = 0b0000_1000; /// Low datarate optimization state #[derive(Copy, Clone, PartialEq, Debug)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum LowDatarateOptimise { /// Low datarate optimizations disabled Disabled = 0x00, /// Low datarate optimizations enabled, this is required when symbol length > 16ms Enabled = 0x08, } pub const PLLHOP_FASTHOP_MASK: u8 = 0b1000_0000; pub const PLLHOP_FASTHOP_ON: u8 = 0b1000_0000; pub const PLLHOP_FASTHOP_OFF: u8 = 0b0000_0000; /// Frequency hopping configuration #[derive(Copy, Clone, PartialEq, Debug)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum FrequencyHopping { Disabled, /// Enabled specifies the number of symbol periods between frequency hops Enabled(u16), } pub const RF_MID_BAND_THRESH: u32 = 525000000; pub const DETECTIONOPTIMIZE_MASK: u8 = 0b0000_0011; pub const AUTOMATICIF_MASK: u8 = 0b1000_0000; pub const AUTOMATICIF_ON: u8 = 0b1000_0000; pub const AUTOMATICIF_OFF: u8 = 0b0000_0000; /// LoRa detection optimization mode #[derive(Copy, Clone, PartialEq, Debug)] #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum DetectionOptimize { /// Optimised for Sf7 to Sf12 Sf7To12 = 0x03, /// Optimised for Sf6 Sf6 = 0x05, } pub const INVERTIQ_RX_MASK: u8 = 0xBF; pub const INVERTIQ_RX_OFF: u8 = 0x00; pub const INVERTIQ_RX_ON: u8 = 0x40; pub const INVERTIQ_TX_MASK: u8 = 0xFE; pub const INVERTIQ_TX_OFF: u8 = 0x01; pub const INVERTIQ_TX_ON: u8 = 0x00; pub const INVERTIQ2_ON: u8 = 0x19; pub const INVERTIQ2_OFF: u8 = 0x1D; bitflags! { /// Interrupt flags register 1 pub struct Irq: u8 { /// Timeout interrupt, manually cleared const RX_TIMEOUT = 0b1000_0000; /// Packet receipt complete const RX_DONE = 0b0100_0000; /// Indicates an invalid CRC was received const CRC_ERROR = 0b0010_0000; /// Indicates a valid header has been received const VALID_HEADER = 0b0001_0000; /// Packet sending complete const TX_DONE = 0b0000_1000; /// Set when a timeout occurs const CAD_DONE = 0b0000_0100; /// Set when a preamble is detected (must be manually cleared) const PREAMBLED_DETECT = 0b0000_0010; /// Set when Sync and Address (if enabled) are detected const SYNC_ADDR_MATCH = 0b0000_0001; } } bitflags! { ///Modem Status flags pub struct ModemStatus: u8 { const MODEM_CLEAR = 0b0001_0000; const HEADER_VALID = 0b0000_1000; const RX_ONGOING = 0b0000_0100; const SIGNAL_SYNCHRONIZED = 0b0000_0010; const SIGNAL_DETECTED = 0b0000_0001; } }
mod info_routes; pub use info_routes::*;
use std::time::Instant; const INPUT: &str = include_str!("../input.txt"); const OFFSETS: [(isize, isize); 8] = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ]; type GridRow = Vec<char>; type Grid = Vec<GridRow>; fn read_grid() -> Grid { INPUT.lines().map(|line| line.chars().collect()).collect() } fn step(grid: Grid, extended: bool) -> (Grid, bool) { let mut new_grid = grid.clone(); let mut changed = false; let neighbor_limit = if extended { 5 } else { 4 }; for (r, row) in grid.iter().enumerate() { for (c, item) in row.iter().enumerate() { if matches!(item, 'L' | '#') { let neighbors = count_neighbors(&grid, r, c, extended); if *item == 'L' { if neighbors == 0 { new_grid[r][c] = '#'; changed = true; } } else if neighbors >= neighbor_limit { new_grid[r][c] = 'L'; changed = true; } } } } (new_grid, changed) } fn count_neighbors(grid: &[GridRow], r: usize, c: usize, extended: bool) -> u64 { let mut total = 0; for (row_off, col_off) in &OFFSETS { let mut dr = *row_off; let mut dc = *col_off; loop { let new_r = ((r as isize) + dr) as usize; let new_c = ((c as isize) + dc) as usize; match grid.get(new_r).and_then(|row| row.get(new_c)) { Some('#') => { total += 1; break; } Some('L') | None => { break; } Some('.') => (), _ => unreachable!(), } if extended { dr += row_off; dc += col_off; } else { break; } } } total } fn get_neighbors_at_steady_state(extended: bool) -> usize { let mut grid = read_grid(); loop { let (new, changed) = step(grid, extended); if !changed { return new .iter() .map(|row| row.iter().filter(|c| **c == '#').count()) .sum(); } grid = new; } } fn part1() -> usize { get_neighbors_at_steady_state(false) } fn part2() -> usize { get_neighbors_at_steady_state(true) } fn main() { let start = Instant::now(); println!("part 1: {}", part1()); println!("part 1 took {}ms", (Instant::now() - start).as_millis()); let start = Instant::now(); println!("part 2: {}", part2()); println!("part 2 took {}ms", (Instant::now() - start).as_millis()); } #[cfg(test)] mod tests { use super::{part1, part2}; #[test] fn test_part1() { assert_eq!(part1(), 2113); } #[test] fn test_part2() { assert_eq!(part2(), 1865); } }
use iron::prelude::*; use common::http::*; use common::utils::*; use services::message::*; use services::user::get_user_id; pub fn render_unread_message(req: &mut Request) -> IronResult<Response> { let session = get_session_obj(req); let username = session["username"].as_str().unwrap(); let user_id = get_user_id(username); let page: u32 = get_query_page(req); let base_url = "/".to_string() + username + "/message/unread?page="; let list = get_user_message_list(user_id, page); let list_count = get_user_message_list_count(user_id); let pagination = build_pagination(page, list_count, &*base_url); let mut data = ViewData::new(req); data.insert("has_message_list", json!(list.len())); data.insert("message_list", json!(list)); data.insert("pagination", json!(pagination)); respond_view("message", &data) } pub fn read_message(req: &mut Request) -> IronResult<Response> { let params = get_router_params(req); let message_id = params.find("message_id").unwrap(); let query = get_request_query(req); let topic_id = &*query.get("topic-id").unwrap()[0]; let comment_id = &*query.get("comment-id").unwrap()[0]; delete_message(message_id); let url = "/topic/".to_string() + topic_id + "#" + comment_id; redirect_to(&*url) } pub fn read_all_message(req: &mut Request) -> IronResult<Response> { let session = get_session_obj(req); let username = session["username"].as_str().unwrap(); let user_id = get_user_id(username); delete_all_message_by_user_id(user_id); redirect_to(&*format!("/{}/message/unread", username)) }
use bayard_client::client::client::{create_client, Clerk}; use clap::ArgMatches; use crate::util::log::set_logger; pub fn run_search_cli(matches: &ArgMatches) -> Result<(), String> { set_logger(); let servers: Vec<_> = matches .values_of("SERVERS") .unwrap() .map(|addr| create_client(addr)) .collect(); let from = matches.value_of("FROM").unwrap().parse::<u64>().unwrap(); let limit = matches.value_of("LIMIT").unwrap().parse::<u64>().unwrap(); let exclude_count = matches.is_present("EXCLUDE_COUNT"); let exclude_docs = matches.is_present("EXCLUDE_DOCS"); let facet_field = matches.value_of("FACET_FIELD").unwrap(); let mut facet_prefixes: Vec<String> = Vec::new(); if let Some(_facet_prefixes) = matches.values_of("FACET_PREFIX") { _facet_prefixes .map(|s| facet_prefixes.push(s.to_string())) .count(); } // let mut facets: Vec<String> = Vec::new(); // if let Some(_facets) = matches.values_of("FACET") { // _facets.map(|s| { // facets.push(s.to_string()) // } // ).count(); // } let query = matches.value_of("QUERY").unwrap(); let client_id = rand::random(); let mut client = Clerk::new(&servers, client_id); let value = client.search( query, from, limit, exclude_count, exclude_docs, facet_field, facet_prefixes, ); // let value = client.search(query, from, limit, exclude_count, exclude_docs, facets); print!("{}", value); Ok(()) }
extern crate oxygengine_core as core; extern crate oxygengine_input as input; pub mod component; pub mod resource; pub mod system; pub mod ui_theme_asset_protocol; // reexport macros. pub use raui_core::{ post_hooks, pre_hooks, prelude::{MessageData, Prefab, PropsData}, unpack_named_slots, widget, }; pub mod prelude { pub use crate::{ component::*, resource::*, system::*, ui_theme_asset_protocol::*, UserInterfaceBundleSetup, }; } pub mod raui { pub mod core { pub use raui_core::*; } pub mod material { pub use raui_material::*; } } use crate::{ component::UserInterfaceView, resource::UserInterface, system::{user_interface_system, UserInterfaceSystemCache, UserInterfaceSystemResources}, }; use core::{ app::AppBuilder, assets::database::AssetsDatabase, ecs::{ pipeline::{PipelineBuilder, PipelineBuilderError}, Universe, }, prefab::PrefabManager, }; use raui_core::application::ProcessContext; #[derive(Default)] pub struct UserInterfaceBundleSetup { user_interface: UserInterface, process_context_setup: Option<Box<dyn Fn(&Universe, &mut ProcessContext) + Send + Sync + 'static>>, } impl UserInterfaceBundleSetup { pub fn user_interface(mut self, v: UserInterface) -> Self { self.user_interface = v; self } pub fn process_context_setup<F>(mut self, f: F) -> Self where F: Fn(&Universe, &mut ProcessContext) + Send + Sync + 'static, { self.process_context_setup = Some(Box::new(f)); self } } pub fn bundle_installer<PB>( builder: &mut AppBuilder<PB>, setup: UserInterfaceBundleSetup, ) -> Result<(), PipelineBuilderError> where PB: PipelineBuilder, { let UserInterfaceBundleSetup { user_interface, process_context_setup, } = setup; let mut cache = UserInterfaceSystemCache::default(); cache.process_context_setup = process_context_setup; builder.install_resource(user_interface); builder.install_resource(cache); builder.install_system::<UserInterfaceSystemResources>( "user-interface", user_interface_system, &[], )?; Ok(()) } pub fn prefabs_installer(prefabs: &mut PrefabManager) { prefabs.register_component_factory::<UserInterfaceView>("UserInterfaceView"); } pub fn protocols_installer(database: &mut AssetsDatabase) { database.register(ui_theme_asset_protocol::UiThemeAssetProtocol); }
fn is_prime(n: u32) -> bool { for i in (2..n) { if n % i == 0 { return false; } } true }
use std::collections::HashMap; #[derive(Debug)] #[derive(PartialEq)] enum Token { OpenBracket, CloseBracket, Atom(String), } fn to_tokens(text: &str) -> Vec<Token> { let mut tokens = Vec::<Token>::new(); let mut atom = String::new(); for c in text.chars() { if !atom.is_empty() && ( c == '(' || c == ')' || !c.is_ascii_graphic()) { tokens.push(Token::Atom(atom.clone())); atom.clear(); } if c == '(' { tokens.push(Token::OpenBracket); } else if c == ')' { tokens.push(Token::CloseBracket); } else if c.is_ascii_graphic() { atom.push(c); } } if !atom.is_empty() { tokens.push(Token::Atom(atom.clone())); } tokens } #[test] fn test_to_tokens() { { let tokens = to_tokens(""); assert_eq!(tokens.len(), 0); } { let tokens = to_tokens("a"); assert_eq!(tokens.len(), 1); assert!(match &tokens[0] { Token::Atom(text) => text == "a", _ => false }); assert_eq!(tokens, vec!(Token::Atom("a".to_string()))); } } #[derive(Clone)] enum SExpression { Atom(String), List(Vec<SExpression>) } fn to_sexpression(tokens: &[Token]) -> Option<SExpression> { fn to_list(begin: std::slice::Iter<Token>) -> Option<(SExpression, std::slice::Iter<Token>)> { let mut list: Vec<SExpression> = Vec::new(); let mut current = begin; loop { let (sexp, next) = match current.next() { Some(Token::Atom(s)) => (SExpression::Atom(s.to_string()), current), Some(Token::OpenBracket) => match to_list(current) { Some(list) => list, _ => break, //Bad inner list }, Some(Token::CloseBracket) => return Some((SExpression::List(list), current)), None => break, //Ran out of tokens before finding matching CloseBracket }; list.push(sexp); current = next; } return None; } if tokens.is_empty() { return None } let mut current = tokens.iter(); let (sexp, mut next) = match current.next() { Some(Token::OpenBracket) => match to_list(current) { Some(sexp_next) => sexp_next, _ => return None, }, Some(Token::CloseBracket) => return None, Some(Token::Atom(s)) => (SExpression::Atom(s.to_string()), current), None => return None, }; match next.next() { Some(_) => return None, //More than one sexpression when either list or atom expected _ => Some(sexp), } } #[test] fn test_to_sexpression() { { let tokens = to_tokens(""); let sexp = to_sexpression(&tokens); assert!(match sexp { None => true, _ => false }); } { let tokens = to_tokens("()"); let sexp = to_sexpression(&tokens); assert!(match sexp { Some(SExpression::List(list)) => (list.len() == 0), _ => false }); } { let tokens = to_tokens("a"); let sexp = to_sexpression(&tokens); assert!(match sexp { Some(SExpression::Atom(s)) => s == "a", _ => false }); } { let tokens = to_tokens("(atom turkey) or"); let sexp = to_sexpression(&tokens); assert!(match sexp { None => true, _ => false }); } { let tokens = to_tokens("((atom turkey third) or)"); let sexp = to_sexpression(&tokens); match sexp { Some(SExpression::List(list)) => { assert_eq!(list.len(), 2); match &list[0] { SExpression::List(list2) => { assert_eq!(list2.len(), 3); assert!(match &list2[0] { SExpression::Atom(s) => (s == "atom"), _ => false, }); assert!(match &list2[1] { SExpression::Atom(s) => (s == "turkey"), _ => false, }); assert!(match &list2[2] { SExpression::Atom(s) => (s == "third"), _ => false, }); }, _ => assert!(false), } assert!(match &list[1] { SExpression::Atom(s) => (s == "or"), _ => false, }); }, _ => assert!(false), } } { let tokens = to_tokens("(how are you doing so far)"); let sexp = to_sexpression(&tokens); assert!(match sexp { Some(SExpression::List(list)) => (list.len() == 6), _ => false, }); } { let tokens = to_tokens("(((how) are)((you)(doing so))far)"); let sexp = to_sexpression(&tokens); assert!(match sexp { Some(SExpression::List(_)) => true, _ => false, }); assert!(if let Some(SExpression::List(_)) = sexp { true } else { false }); assert!(match sexp { Some(SExpression::List(list)) => (list.len() == 3), _ => false, }); } } fn is_atom(tokens: &Vec<Token>) -> bool { tokens.len() == 1 && match &tokens[0] { Token::Atom(_) => true, _ => false } } use test_case::test_case; #[test_case("atom", true; "is_atom: simple word")] #[test_case("turkey", true; "is_atom: simple word 2")] #[test_case("1492", true; "is_atom: number")] #[test_case("u", true; "is_atom: single letter")] #[test_case("*abc$", true; "is_atom: include $")] #[test_case("", false; "is_atom: empty string")] #[test_case(" ", false; "is_atom: whitespace")] #[test_case(" a", true; "is_atom: whitespace before")] #[test_case("a ", true; "is_atom: whitespace after")] #[test_case(" a ", true; "is_atom: whitespace before and after")] #[test_case("(", false; "is_atom: left bracket")] #[test_case("(abc$", false; "is_atom: left bracket and atom")] #[test_case("(abc$)", false; "is_atom: bracketed atom")] fn test_is_atom(s: &str, expected: bool) { let tokens = to_tokens(s); assert_eq!(is_atom(&tokens), expected); } fn is_list(tokens: &Vec<Token>) -> bool { let mut depth = 0; let mut max_depth = 0; for token in tokens { match token { Token::OpenBracket => { depth += 1; if depth > max_depth { max_depth = depth; } }, Token::CloseBracket => { depth -= 1; if depth < 0 { return false; } }, Token::Atom(_) => { //Check that atom isn't found outside outermost list if depth <= 0 { return false; } } } } depth == 0 && max_depth > 0 } #[test_case("atom", false; "is_list: atom")] #[test_case("(atom)", true; "is_list: one atom list")] #[test_case("()", true; "is_list: empty list")] #[test_case("(atom", false; "is_list: unclosed list")] #[test_case("(atom turkey or)", true; "is_list: list of 3 atoms")] #[test_case("(atom (turkey (pitch black))or ())", true; "is_list: nested list")] #[test_case(" ( atom turkey or ) ", true; "is_list: spaced out list")] #[test_case("(atom turkey) or", false; "is_list: list and atom")] #[test_case("((atom turkey) or)", true; "is_list: list of list and atom")] fn test_is_list(s: &str, expected: bool) { assert_eq!(is_list(&to_tokens(s)), expected); } /// s_expression fn is_s_exp(tokens: &Vec<Token>) -> bool { is_atom(tokens) || is_list(tokens) } #[test] fn test_is_s_exp() { assert_eq!(is_s_exp(&to_tokens("")), false); assert_eq!(is_s_exp(&to_tokens(" ")), false); assert_eq!(is_s_exp(&to_tokens("xyz")), true); assert_eq!(is_s_exp(&to_tokens("(x y z)")), true); assert_eq!(is_s_exp(&to_tokens("(x y) z")), false); assert_eq!(is_s_exp(&to_tokens("atom atom")), false); } type Environment = HashMap<String, SExpression>; impl SExpression { fn car(&self) -> Option<SExpression> { match &*self { SExpression::List(list) if !list.is_empty() => Some(list[0].clone()), _ => None, } } fn cdr(&self) -> Option<SExpression> { match &*self { SExpression::List(list) if !list.is_empty() => Some(SExpression::List(list[1..].to_vec())), _ => None, } } fn cons(&self, list: &SExpression) -> Option<SExpression> { match list { SExpression::List(list) => { let mut list = list.clone(); list.insert(0, self.clone()); Some(SExpression::List(list)) }, _ => None, } } fn is_null(&self) -> SExpression { SExpression::Atom(match &*self { SExpression::List(list) => list.is_empty().to_string(), _ => String::from("false"), }) } //`quote` returns the following parameter without evaluation fn quote(&self) -> Option<SExpression> { Some(self.clone()) } fn is_atom_(&self) -> bool { match &*self { SExpression::Atom(_) => true, _ => false, } } fn is_atom(&self) -> SExpression { SExpression::Atom(self.is_atom_().to_string()) } fn is_eq(&self, other: &SExpression) -> SExpression { fn is_eq_(lhs: &SExpression, rhs: &SExpression) -> bool { match lhs { SExpression::Atom(lhs) => match rhs { SExpression::Atom(rhs) => (lhs == rhs), _ => false, }, SExpression::List(lhs) => match rhs { SExpression::List(rhs) => (lhs.len() == rhs.len()) && lhs.iter().zip(rhs).any(|(lhs,rhs)|is_eq_(&lhs,&rhs)), _ => false, }, } } SExpression::Atom(is_eq_(self, other).to_string()) } fn is_lat(&self) -> SExpression { SExpression::Atom((match &*self { SExpression::Atom(_) => false, SExpression::List(list) => list.iter().all(|s|s.is_atom_()), }).to_string()) } fn is_true(&self) -> bool { match &*self { SExpression::Atom(s) => (s == "true"), _ => false, } } fn cond(&self, conditions: &mut std::slice::Iter<SExpression>, env: &mut Environment) -> Option<SExpression> { let applicable_condition = conditions.find(|&condition| { match condition { SExpression::List(condition) if condition.len() > 1 => match condition[0].eval(env) { Some(condition) => condition.is_true(), _ => false, }, _ => false, } }); match applicable_condition { Some(SExpression::List(condition)) => condition[1].eval(env), _ => None, } } fn define(&self, other: &SExpression, env: &mut Environment) { match *&self { SExpression::Atom(s) => {env.insert(s.to_string(), other.clone()); ()}, _ => (), } } fn eval(&self, env: &mut Environment) -> Option<SExpression> { fn eval_list(list: &Vec<SExpression>, env: &mut Environment) -> Option<SExpression> { let mut new_list : Vec<SExpression> = Vec::new(); let mut current = list.iter(); while let Some(sexp) = current.next() { match sexp { SExpression::Atom(a) if a == "car" => return current.next()?.eval(env)?.car(), SExpression::Atom(a) if a == "cdr" => return current.next()?.eval(env)?.cdr(), SExpression::Atom(a) if a == "cons" => return current.next()?.eval(env)?.cons(&current.next()?.eval(env)?), SExpression::Atom(a) if a == "null?" => return Some(current.next()?.eval(env)?.is_null()), SExpression::Atom(a) if a == "quote" || a == "'" => return current.next()?.quote(), SExpression::Atom(a) if a == "atom?" => return Some(current.next()?.eval(env)?.is_atom()), SExpression::Atom(a) if a == "eq?" => return Some(current.next()?.eval(env)?.is_eq(&current.next()?.eval(env)?)), SExpression::Atom(a) if a == "lat?" => return Some(current.next()?.eval(env)?.is_lat()), SExpression::Atom(a) if a == "cond" => return sexp.cond(&mut current, env), SExpression::Atom(a) if a == "define" => current.next()?.eval(env)?.define(&current.next()?.eval(env)?, env), _ => match sexp.eval(env) { Some(sexp) => new_list.push(sexp), _ => (), }, } } Some(SExpression::List(new_list)) } match &*self { SExpression::List(list) => eval_list(&list, env), SExpression::Atom(s) => match env.get(s) { Some(sexp) => sexp.clone().eval(env), _ => Some(self.clone()), }, } } } #[test] fn test_car() { { let tokens = to_tokens("hotdog"); let sexp = to_sexpression(&tokens); match sexp { Some(sexp) => assert!(match sexp.car() { None => true, _ => false, }), _ => assert!(false), } } { let tokens = to_tokens("()"); let sexp = to_sexpression(&tokens); match sexp { Some(sexp) => assert!(match sexp.car() { None => true, _ => false, }), _ => assert!(false), } } { let tokens = to_tokens("(a b c)"); let sexp = to_sexpression(&tokens); match sexp { Some(sexp) => match sexp.car() { Some(SExpression::Atom(s)) => assert_eq!(s,"a"), _ => assert!(false), }, _ => assert!(false), } } { let tokens = to_tokens("((a b c) x y z)"); let sexp = to_sexpression(&tokens); match sexp { Some(sexp) => match sexp.car() { Some(SExpression::List(list)) => { assert_eq!(list.len(), 3); match &list[2] { SExpression::Atom(s) => assert_eq!(s, "c"), _ => assert!(false), } }, _ => assert!(false), }, _ => assert!(false), } } } #[test] fn test_eval_car() { let mut env = Environment::new(); { let tokens = to_tokens("(car (a b c))"); let sexp = to_sexpression(&tokens); match sexp { Some(sexp) => match sexp.eval(&mut env) { Some(SExpression::Atom(s)) => assert_eq!(s, "a"), _ => assert!(false), }, _ => assert!(false), } } { let tokens = to_tokens("(car a)"); let sexp = to_sexpression(&tokens); match sexp { Some(sexp) => assert!(match sexp.eval(&mut env) { None => true, _ => false, }), _ => assert!(false), } } } fn sexpression_to_string(sexp: &SExpression, env: &mut Environment) -> String { let mut s = String::new(); match sexp { SExpression::Atom(_) => match sexp.eval(env) { Some(SExpression::Atom(s_)) => s += &s_, Some(sexp) => s += &sexpression_to_string(&sexp, env), _ => (), }, SExpression::List(list) => { s += "("; let mut current = list.iter(); if let Some(sexp) = current.next() { if let Some(sexp) = sexp.eval(env) { s += &sexpression_to_string(&sexp, env); while let Some(sexp) = current.next() { if let Some(sexp) = sexp.eval(env) { s += " "; s += &sexpression_to_string(&sexp, env); } } } } s += ")"; } } s } fn eval_scheme_to_string(s: &str) -> String { let tokens = to_tokens(s); let mut env = Environment::new(); match to_sexpression(&tokens) { Some(sexp) => match sexp.eval(&mut env) { Some(sexp) => sexpression_to_string(&sexp, &mut env), _ => String::from("Bad eval!"), }, _ if s == "" => String::new(), _ => String::from("Bad scheme!"), } } #[test_case("", ""; "eval: empty")] #[test_case("a", "a"; "eval: atom")] #[test_case("(", "Bad scheme!"; "eval: bad input")] #[test_case("()", "()"; "eval: empty list")] #[test_case(" ( ( a b ) c ) ", "((a b) c)"; "eval: list with whitespace")] #[test_case("(car (hotdogs))", "hotdogs"; "eval: car")] #[test_case("(car ((hotdogs)))", "(hotdogs)"; "eval: car hotdogs nested")] #[test_case("(car (((hotdogs))))", "((hotdogs))"; "eval: car hotdogs more nested")] #[test_case("(car ( ((hotdogs)) (and) (pickle) relish ) )", "((hotdogs))"; "eval: car nested list")] #[test_case("(car (car ( ((hotdogs)) (and) (pickle) relish ) ) )", "(hotdogs)"; "eval: nested car")] #[test_case("(car a)", "Bad eval!"; "eval: car of atom")] #[test_case("(cdr (a b c) )", "(b c)"; "eval: cdr")] #[test_case("(cdr ((a b c) x y z) )", "(x y z)"; "eval: cdr nested list")] #[test_case("(cdr (hamburger) )", "()"; "eval: cdr 1-list")] #[test_case("(cdr a)", "Bad eval!"; "eval: cdr of atom")] #[test_case("(cdr ())", "Bad eval!"; "eval: cdr of empty list")] #[test_case("(car (cdr ((b) (x y) ((c))) ))", "(x y)"; "eval: car cdr")] #[test_case("(cdr (cdr ((b) (x y) ((c))) ))", "(((c)))"; "eval: cdr cdr")] #[test_case("(cdr (car ((b) (x y) ((c))) ))", "()"; "eval: cdr car")] #[test_case("(cons peanut ())", "(peanut)"; "eval: cons into empty list")] #[test_case("(cons () ())", "(())"; "eval: cons empty list into empty list")] #[test_case("(cons peanut (butter and jelly))", "(peanut butter and jelly)"; "eval: cons")] #[test_case("(null? spaghetti)", "false"; "eval: null? atom")] #[test_case("(null? ())", "true"; "eval: null? empty list")] #[test_case("(null? (()))", "false"; "eval: null? non-empty list")] #[test_case("(null? (car (())))", "true"; "eval: null? car non-empty list")] #[test_case("(quote ())", "()"; "eval: quote")] #[test_case("('())", "()"; "eval: quote apostrophe")] #[test_case("(null? (a b c))", "false"; "eval: null? list")] #[test_case("(atom? Harry)", "true"; "eval: atom? atom")] #[test_case("(atom? (Harry had a heap of apples))", "false"; "eval: atom? list")] #[test_case("(atom? ())", "false"; "eval: atom? empty list")] #[test_case("(atom? (car (Harry had a heap of apples)))", "true"; "eval: atom? car list")] #[test_case("(atom? (cdr (Harry had a heap of apples)))", "false"; "eval: atom? cdr list")] #[test_case("(atom? (cdr (Harry)))", "false"; "eval: atom? cdr 1-list")] #[test_case("(atom? (car (cdr (swing low sweet cherry oat))))", "true"; "eval: atom? car cdr list")] #[test_case("(atom? (car (cdr (swing (low sweet) cherry oat))))", "false"; "eval: atom? car cdr list of list")] #[test_case("(eq? Harry Harry)", "true"; "eval: eq? same atoms")] #[test_case("(eq? margarine butter)", "false"; "eval: eq? different atoms")] #[test_case("(eq? () (strawberry))", "false"; "eval: eq? different lists")] #[test_case("(eq? (strawberry tea) (strawberry tea))", "true"; "eval: eq? same lists")] #[test_case("(eq? 6 7)", "false"; "eval: eq? different numbers")] #[test_case("(eq? 7 7)", "true"; "eval: eq? same numbers")] #[test_case("(eq? (car (Mary had a little lamb)) Mary)", "true"; "eval: eq? car")] #[test_case("(eq? (cdr (soured milk)) milk)", "false"; "eval: eq? cdr list and atom")] #[test_case("(eq? (cdr (soured milk)) (milk))", "true"; "eval: eq? cdr list and list")] #[test_case("(eq? (car (beans beans we need jelly beans)) (car (cdr (beans beans we need jelly beans))) )", "true"; "eval: eq? 1st 2nd")] #[test_case("(lat? (Jack Sprat could eat no chicken fat) )", "true"; "eval: lat? list of atoms")] #[test_case("(lat? ((Jack) Sprat could eat no chicken fat) )", "false"; "eval: lat? list including list")] #[test_case("(lat? (Jack (Sprat could) eat no chicken fat) )", "false"; "eval: lat? another list including list")] #[test_case("(lat? () )", "true"; "eval: lat? empty list")] #[test_case("(cond (true a) )", "a"; "eval: cond true")] #[test_case("(cond (false a) (true b) )", "b"; "eval: cond false true")] #[test_case("(cond (true a) (true b) )", "a"; "eval: cond first result")] #[test_case("(cond (false a) )", "Bad eval!"; "eval: cond no result")] #[test_case("(cond ((eq? a a) equal) (true not-equal) )", "equal"; "eval: cond apply eq? to same")] #[test_case("(cond ((eq? a b) equal) (true not-equal) )", "not-equal"; "eval: cond apply eq? to different")] #[test_case("((define else true) (cond ((eq? a b) equal) (else not-equal)) )", "(() not-equal)"; "eval: cond use else")] #[test_case("(define a b)", "()"; "eval: define isolated")] #[test_case("( (eq? a b) (eq? c c))", "(false true)"; "eval: multiple expressions")] #[test_case("( (define a b) a)", "(() b)"; "eval: define substitute definition")] fn test_eval_scheme_to_string(s: &str, expected: &str) { assert_eq!(eval_scheme_to_string(&s), expected); } fn main() { println!("little_schemer"); }