diff --git a/.all-contributorsrc b/.all-contributorsrc deleted file mode 100644 index f2033dcde9..0000000000 --- a/.all-contributorsrc +++ /dev/null @@ -1,1553 +0,0 @@ -{ - "files": [ - "AUTHORS.md" - ], - "imageSize": 100, - "commit": false, - "contributors": [ - { - "login": "carols10cents", - "name": "Carol (Nichols || Goulding)", - "avatar_url": "https://avatars2.githubusercontent.com/u/193874?v=4", - "profile": "http://carol-nichols.com", - "contributions": [ - "code", - "content" - ] - }, - { - "login": "QuietMisdreavus", - "name": "QuietMisdreavus", - "avatar_url": "https://avatars2.githubusercontent.com/u/5217170?v=4", - "profile": "https://twitter.com/QuietMisdreavus", - "contributions": [ - "code", - "content" - ] - }, - { - "login": "robertlugg", - "name": "Robert M Lugg", - "avatar_url": "https://avatars0.githubusercontent.com/u/6054540?v=4", - "profile": "https://github.com/robertlugg", - "contributions": [ - "content" - ] - }, - { - "login": "hynek", - "name": "Hynek Schlawack", - "avatar_url": "https://avatars3.githubusercontent.com/u/41240?v=4", - "profile": "https://hynek.me/about/", - "contributions": [ - "code" - ] - }, - { - "login": "spacekookie", - "name": "Katharina Fey", - "avatar_url": "https://avatars0.githubusercontent.com/u/7669898?v=4", - "profile": "https://spacekookie.de", - "contributions": [ - "code" - ] - }, - { - "login": "lukabavdaz", - "name": "lukabavdaz", - "avatar_url": "https://avatars0.githubusercontent.com/u/9624558?v=4", - "profile": "https://github.com/lukabavdaz", - "contributions": [ - "code", - "content" - ] - }, - { - "login": "evestera", - "name": "Erik Vesteraas", - "avatar_url": "https://avatars2.githubusercontent.com/u/4187449?v=4", - "profile": "http://vestera.as", - "contributions": [ - "code" - ] - }, - { - "login": "Delet0r", - "name": "delet0r", - "avatar_url": "https://avatars1.githubusercontent.com/u/23195618?v=4", - "profile": "https://github.com/Delet0r", - "contributions": [ - "code" - ] - }, - { - "login": "shaunbennett", - "name": "Shaun Bennett", - "avatar_url": "https://avatars1.githubusercontent.com/u/10522375?v=4", - "profile": "http://phinary.ca", - "contributions": [ - "code" - ] - }, - { - "login": "abagshaw", - "name": "Andrew Bagshaw", - "avatar_url": "https://avatars2.githubusercontent.com/u/8594541?v=4", - "profile": "https://github.com/abagshaw", - "contributions": [ - "code" - ] - }, - { - "login": "kisom", - "name": "Kyle Isom", - "avatar_url": "https://avatars2.githubusercontent.com/u/175578?v=4", - "profile": "https://ai6ua.net/", - "contributions": [ - "code" - ] - }, - { - "login": "ColinPitrat", - "name": "Colin Pitrat", - "avatar_url": "https://avatars3.githubusercontent.com/u/1541863?v=4", - "profile": "https://github.com/ColinPitrat", - "contributions": [ - "code" - ] - }, - { - "login": "zacanger", - "name": "Zac Anger", - "avatar_url": "https://avatars3.githubusercontent.com/u/12520493?v=4", - "profile": "https://zacanger.com", - "contributions": [ - "code" - ] - }, - { - "login": "mgeier", - "name": "Matthias Geier", - "avatar_url": "https://avatars1.githubusercontent.com/u/705404?v=4", - "profile": "https://github.com/mgeier", - "contributions": [ - "code" - ] - }, - { - "login": "cjpearce", - "name": "Chris Pearce", - "avatar_url": "https://avatars1.githubusercontent.com/u/3453268?v=4", - "profile": "https://github.com/cjpearce", - "contributions": [ - "code" - ] - }, - { - "login": "yvan-sraka", - "name": "Yvan Sraka", - "avatar_url": "https://avatars2.githubusercontent.com/u/705213?v=4", - "profile": "https://yvan-sraka.github.io", - "contributions": [ - "code" - ] - }, - { - "login": "dendi239", - "name": "Denys Smirnov", - "avatar_url": "https://avatars3.githubusercontent.com/u/16478650?v=4", - "profile": "https://github.com/dendi239", - "contributions": [ - "code" - ] - }, - { - "login": "eddyp", - "name": "eddyp", - "avatar_url": "https://avatars2.githubusercontent.com/u/123772?v=4", - "profile": "https://github.com/eddyp", - "contributions": [ - "code" - ] - }, - { - "login": "briankung", - "name": "Brian Kung", - "avatar_url": "https://avatars1.githubusercontent.com/u/2836167?v=4", - "profile": "http://about.me/BrianKung", - "contributions": [ - "code", - "content" - ] - }, - { - "login": "miller-time", - "name": "Russell", - "avatar_url": "https://avatars3.githubusercontent.com/u/281039?v=4", - "profile": "https://rcousineau.gitlab.io", - "contributions": [ - "code" - ] - }, - { - "login": "danwilhelm", - "name": "Dan Wilhelm", - "avatar_url": "https://avatars3.githubusercontent.com/u/6137185?v=4", - "profile": "http://danwilhelm.com", - "contributions": [ - "doc" - ] - }, - { - "login": "Jesse-Cameron", - "name": "Jesse", - "avatar_url": "https://avatars3.githubusercontent.com/u/3723654?v=4", - "profile": "https://github.com/Jesse-Cameron", - "contributions": [ - "code", - "content" - ] - }, - { - "login": "MrFroop", - "name": "Fredrik Jambrén", - "avatar_url": "https://avatars3.githubusercontent.com/u/196700?v=4", - "profile": "https://github.com/MrFroop", - "contributions": [ - "code" - ] - }, - { - "login": "petemcfarlane", - "name": "Pete McFarlane", - "avatar_url": "https://avatars3.githubusercontent.com/u/3472717?v=4", - "profile": "https://github.com/petemcfarlane", - "contributions": [ - "content" - ] - }, - { - "login": "nkanderson", - "name": "nkanderson", - "avatar_url": "https://avatars0.githubusercontent.com/u/4128825?v=4", - "profile": "https://github.com/nkanderson", - "contributions": [ - "code", - "content" - ] - }, - { - "login": "ajaxm", - "name": "Ajax M", - "avatar_url": "https://avatars0.githubusercontent.com/u/13360138?v=4", - "profile": "https://github.com/ajaxm", - "contributions": [ - "doc" - ] - }, - { - "login": "Dylnuge", - "name": "Dylan Nugent", - "avatar_url": "https://avatars2.githubusercontent.com/u/118624?v=4", - "profile": "https://dylnuge.com", - "contributions": [ - "content" - ] - }, - { - "login": "vyaslav", - "name": "vyaslav", - "avatar_url": "https://avatars0.githubusercontent.com/u/1385427?v=4", - "profile": "https://github.com/vyaslav", - "contributions": [ - "code", - "content" - ] - }, - { - "login": "gdoenlen", - "name": "George", - "avatar_url": "https://avatars1.githubusercontent.com/u/17297466?v=4", - "profile": "https://join.sfxd.org", - "contributions": [ - "code" - ] - }, - { - "login": "nyxtom", - "name": "Thomas Holloway", - "avatar_url": "https://avatars2.githubusercontent.com/u/222763?v=4", - "profile": "https://github.com/nyxtom", - "contributions": [ - "code", - "content" - ] - }, - { - "login": "workingjubilee", - "name": "Jubilee", - "avatar_url": "https://avatars1.githubusercontent.com/u/46493976?v=4", - "profile": "https://github.com/workingjubilee", - "contributions": [ - "code" - ] - }, - { - "login": "WofWca", - "name": "WofWca", - "avatar_url": "https://avatars1.githubusercontent.com/u/39462442?v=4", - "profile": "https://github.com/WofWca", - "contributions": [ - "code" - ] - }, - { - "login": "jrvidal", - "name": "Roberto Vidal", - "avatar_url": "https://avatars0.githubusercontent.com/u/1636604?v=4", - "profile": "https://github.com/jrvidal", - "contributions": [ - "code", - "doc", - "ideas", - "maintenance" - ] - }, - { - "login": "jensim", - "name": "Jens", - "avatar_url": "https://avatars0.githubusercontent.com/u/3663856?v=4", - "profile": "https://github.com/jensim", - "contributions": [ - "doc" - ] - }, - { - "login": "rahatarmanahmed", - "name": "Rahat Ahmed", - "avatar_url": "https://avatars3.githubusercontent.com/u/3174006?v=4", - "profile": "http://rahatah.me/d", - "contributions": [ - "doc" - ] - }, - { - "login": "AbdouSeck", - "name": "Abdou Seck", - "avatar_url": "https://avatars2.githubusercontent.com/u/6490055?v=4", - "profile": "https://github.com/AbdouSeck", - "contributions": [ - "code", - "content", - "review" - ] - }, - { - "login": "codehearts", - "name": "Katie", - "avatar_url": "https://avatars0.githubusercontent.com/u/2885412?v=4", - "profile": "https://codehearts.com", - "contributions": [ - "code" - ] - }, - { - "login": "Socratides", - "name": "Socrates", - "avatar_url": "https://avatars3.githubusercontent.com/u/27732983?v=4", - "profile": "https://github.com/Socratides", - "contributions": [ - "doc" - ] - }, - { - "login": "gnodarse", - "name": "gnodarse", - "avatar_url": "https://avatars3.githubusercontent.com/u/46761795?v=4", - "profile": "https://github.com/gnodarse", - "contributions": [ - "content" - ] - }, - { - "login": "harrisonmetz", - "name": "Harrison Metzger", - "avatar_url": "https://avatars1.githubusercontent.com/u/7883408?v=4", - "profile": "https://github.com/harrisonmetz", - "contributions": [ - "code" - ] - }, - { - "login": "TorbenJ", - "name": "Torben Jonas", - "avatar_url": "https://avatars2.githubusercontent.com/u/9077102?v=4", - "profile": "https://github.com/TorbenJ", - "contributions": [ - "code", - "content" - ] - }, - { - "login": "pbx", - "name": "Paul Bissex", - "avatar_url": "https://avatars0.githubusercontent.com/u/641?v=4", - "profile": "http://paulbissex.com/", - "contributions": [ - "doc" - ] - }, - { - "login": "sjmann", - "name": "Steven Mann", - "avatar_url": "https://avatars0.githubusercontent.com/u/6589896?v=4", - "profile": "https://github.com/sjmann", - "contributions": [ - "code", - "content" - ] - }, - { - "login": "Tarnadas", - "name": "Mario Reder", - "avatar_url": "https://avatars2.githubusercontent.com/u/5855071?v=4", - "profile": "https://smmdb.net/", - "contributions": [ - "code", - "content" - ] - }, - { - "login": "sl4m", - "name": "skim", - "avatar_url": "https://avatars0.githubusercontent.com/u/47347?v=4", - "profile": "https://keybase.io/skim", - "contributions": [ - "code" - ] - }, - { - "login": "sanjaykdragon", - "name": "Sanjay K", - "avatar_url": "https://avatars1.githubusercontent.com/u/10261698?v=4", - "profile": "https://github.com/sanjaykdragon", - "contributions": [ - "code", - "content" - ] - }, - { - "login": "crodjer", - "name": "Rohan Jain", - "avatar_url": "https://avatars1.githubusercontent.com/u/343499?v=4", - "profile": "http://www.rohanjain.in", - "contributions": [ - "code" - ] - }, - { - "login": "saidaspen", - "name": "Said Aspen", - "avatar_url": "https://avatars1.githubusercontent.com/u/7727687?v=4", - "profile": "https://www.saidaspen.se", - "contributions": [ - "code", - "content" - ] - }, - { - "login": "uce", - "name": "Ufuk Celebi", - "avatar_url": "https://avatars3.githubusercontent.com/u/1756620?v=4", - "profile": "https://github.com/uce", - "contributions": [ - "code" - ] - }, - { - "login": "lebedevsergey", - "name": "lebedevsergey", - "avatar_url": "https://avatars2.githubusercontent.com/u/7325764?v=4", - "profile": "https://github.com/lebedevsergey", - "contributions": [ - "doc" - ] - }, - { - "login": "avrong", - "name": "Aleksei Trifonov", - "avatar_url": "https://avatars2.githubusercontent.com/u/6342851?v=4", - "profile": "https://github.com/avrong", - "contributions": [ - "content" - ] - }, - { - "login": "Darrenmeehan", - "name": "Darren Meehan", - "avatar_url": "https://avatars2.githubusercontent.com/u/411136?v=4", - "profile": "https://drn.ie", - "contributions": [ - "content" - ] - }, - { - "login": "jihchi", - "name": "Jihchi Lee", - "avatar_url": "https://avatars1.githubusercontent.com/u/87983?v=4", - "profile": "https://github.com/jihchi", - "contributions": [ - "content" - ] - }, - { - "login": "bertonha", - "name": "Christofer Bertonha", - "avatar_url": "https://avatars3.githubusercontent.com/u/1225902?v=4", - "profile": "https://github.com/bertonha", - "contributions": [ - "content" - ] - }, - { - "login": "apatniv", - "name": "Vivek Bharath Akupatni", - "avatar_url": "https://avatars2.githubusercontent.com/u/22565917?v=4", - "profile": "https://github.com/apatniv", - "contributions": [ - "code", - "test" - ] - }, - { - "login": "DiD92", - "name": "Dídac Sementé Fernández", - "avatar_url": "https://avatars3.githubusercontent.com/u/6002416?v=4", - "profile": "https://github.com/DiD92", - "contributions": [ - "code", - "content" - ] - }, - { - "login": "wrobstory", - "name": "Rob Story", - "avatar_url": "https://avatars3.githubusercontent.com/u/2601457?v=4", - "profile": "https://github.com/wrobstory", - "contributions": [ - "code" - ] - }, - { - "login": "siobhanjacobson", - "name": "Siobhan Jacobson", - "avatar_url": "https://avatars2.githubusercontent.com/u/28983835?v=4", - "profile": "https://github.com/siobhanjacobson", - "contributions": [ - "code" - ] - }, - { - "login": "EvanCarroll", - "name": "Evan Carroll", - "avatar_url": "https://avatars2.githubusercontent.com/u/19922?v=4", - "profile": "https://www.linkedin.com/in/evancarroll/", - "contributions": [ - "content" - ] - }, - { - "login": "jmahmood", - "name": "Jawaad Mahmood", - "avatar_url": "https://avatars3.githubusercontent.com/u/95606?v=4", - "profile": "http://www.jawaadmahmood.com", - "contributions": [ - "content" - ] - }, - { - "login": "GaurangTandon", - "name": "Gaurang Tandon", - "avatar_url": "https://avatars1.githubusercontent.com/u/6308683?v=4", - "profile": "https://github.com/GaurangTandon", - "contributions": [ - "content" - ] - }, - { - "login": "dev-cyprium", - "name": "Stefan Kupresak", - "avatar_url": "https://avatars1.githubusercontent.com/u/6002628?v=4", - "profile": "https://github.com/dev-cyprium", - "contributions": [ - "content" - ] - }, - { - "login": "greg-el", - "name": "Greg Leonard", - "avatar_url": "https://avatars3.githubusercontent.com/u/45019882?v=4", - "profile": "https://github.com/greg-el", - "contributions": [ - "content" - ] - }, - { - "login": "ryanpcmcquen", - "name": "Ryan McQuen", - "avatar_url": "https://avatars3.githubusercontent.com/u/772937?v=4", - "profile": "https://ryanpcmcquen.org", - "contributions": [ - "code" - ] - }, - { - "login": "AnnikaCodes", - "name": "Annika", - "avatar_url": "https://avatars3.githubusercontent.com/u/56906084?v=4", - "profile": "https://github.com/AnnikaCodes", - "contributions": [ - "review" - ] - }, - { - "login": "darnuria", - "name": "Axel Viala", - "avatar_url": "https://avatars1.githubusercontent.com/u/2827553?v=4", - "profile": "https://darnuria.eu", - "contributions": [ - "code" - ] - }, - { - "login": "sazid", - "name": "Mohammed Sazid Al Rashid", - "avatar_url": "https://avatars1.githubusercontent.com/u/2370167?v=4", - "profile": "https://sazid.github.io", - "contributions": [ - "content", - "code" - ] - }, - { - "login": "seeplusplus", - "name": "Caleb Webber", - "avatar_url": "https://avatars1.githubusercontent.com/u/17479099?v=4", - "profile": "https://codingthemsoftly.com", - "contributions": [ - "maintenance" - ] - }, - { - "login": "pcn", - "name": "Peter N", - "avatar_url": "https://avatars2.githubusercontent.com/u/1056756?v=4", - "profile": "https://github.com/pcn", - "contributions": [ - "maintenance" - ] - }, - { - "login": "seancad", - "name": "seancad", - "avatar_url": "https://avatars1.githubusercontent.com/u/47405611?v=4", - "profile": "https://github.com/seancad", - "contributions": [ - "maintenance" - ] - }, - { - "login": "wsh", - "name": "Will Hayworth", - "avatar_url": "https://avatars3.githubusercontent.com/u/181174?v=4", - "profile": "http://willhayworth.com", - "contributions": [ - "content" - ] - }, - { - "login": "chrizel", - "name": "Christian Zeller", - "avatar_url": "https://avatars3.githubusercontent.com/u/20802?v=4", - "profile": "https://github.com/chrizel", - "contributions": [ - "content" - ] - }, - { - "login": "jfchevrette", - "name": "Jean-Francois Chevrette", - "avatar_url": "https://avatars.githubusercontent.com/u/3001?v=4", - "profile": "https://github.com/jfchevrette", - "contributions": [ - "content", - "code" - ] - }, - { - "login": "jbaber", - "name": "John Baber-Lucero", - "avatar_url": "https://avatars.githubusercontent.com/u/1908117?v=4", - "profile": "https://github.com/jbaber", - "contributions": [ - "content" - ] - }, - { - "login": "tal-zvon", - "name": "Tal", - "avatar_url": "https://avatars.githubusercontent.com/u/3195851?v=4", - "profile": "https://github.com/tal-zvon", - "contributions": [ - "content" - ] - }, - { - "login": "apogeeoak", - "name": "apogeeoak", - "avatar_url": "https://avatars.githubusercontent.com/u/59737221?v=4", - "profile": "https://github.com/apogeeoak", - "contributions": [ - "content", - "code" - ] - }, - { - "login": "Crell", - "name": "Larry Garfield", - "avatar_url": "https://avatars.githubusercontent.com/u/254863?v=4", - "profile": "http://www.garfieldtech.com/", - "contributions": [ - "content" - ] - }, - { - "login": "circumspect", - "name": "circumspect", - "avatar_url": "https://avatars.githubusercontent.com/u/40770208?v=4", - "profile": "https://github.com/circumspect", - "contributions": [ - "content" - ] - }, - { - "login": "cjwyett", - "name": "Cyrus Wyett", - "avatar_url": "https://avatars.githubusercontent.com/u/34195737?v=4", - "profile": "https://github.com/cjwyett", - "contributions": [ - "content" - ] - }, - { - "login": "cadolphs", - "name": "cadolphs", - "avatar_url": "https://avatars.githubusercontent.com/u/13894820?v=4", - "profile": "https://github.com/cadolphs", - "contributions": [ - "code" - ] - }, - { - "login": "hpwxf", - "name": "Pascal H.", - "avatar_url": "https://avatars.githubusercontent.com/u/26146722?v=4", - "profile": "https://www.haveneer.com", - "contributions": [ - "content" - ] - }, - { - "login": "chapeupreto", - "name": "Rod Elias", - "avatar_url": "https://avatars.githubusercontent.com/u/834048?v=4", - "profile": "https://twitter.com/chapeupreto", - "contributions": [ - "content" - ] - }, - { - "login": "blerchy", - "name": "Matt Lebl", - "avatar_url": "https://avatars.githubusercontent.com/u/2555355?v=4", - "profile": "https://github.com/blerchy", - "contributions": [ - "code" - ] - }, - { - "login": "flakolefluk", - "name": "Ignacio Le Fluk", - "avatar_url": "https://avatars.githubusercontent.com/u/11986564?v=4", - "profile": "http://flakolefluk.dev", - "contributions": [ - "content" - ] - }, - { - "login": "tlyu", - "name": "Taylor Yu", - "avatar_url": "https://avatars.githubusercontent.com/u/431873?v=4", - "profile": "https://github.com/tlyu", - "contributions": [ - "code", - "content" - ] - }, - { - "login": "Zerotask", - "name": "Patrick Hintermayer", - "avatar_url": "https://avatars.githubusercontent.com/u/20150243?v=4", - "profile": "https://zerotask.github.io", - "contributions": [ - "code" - ] - }, - { - "login": "arthas168", - "name": "Pete Pavlovski", - "avatar_url": "https://avatars.githubusercontent.com/u/32264020?v=4", - "profile": "https://petkopavlovski.com/", - "contributions": [ - "content" - ] - }, - { - "login": "k12ish", - "name": "k12ish", - "avatar_url": "https://avatars.githubusercontent.com/u/45272873?v=4", - "profile": "https://github.com/k12ish", - "contributions": [ - "content" - ] - }, - { - "login": "hongshaoyang", - "name": "Shao Yang Hong", - "avatar_url": "https://avatars.githubusercontent.com/u/19281800?v=4", - "profile": "https://github.com/hongshaoyang", - "contributions": [ - "content" - ] - }, - { - "login": "bmacer", - "name": "Brandon Macer", - "avatar_url": "https://avatars.githubusercontent.com/u/13931806?v=4", - "profile": "https://github.com/bmacer", - "contributions": [ - "content" - ] - }, - { - "login": "stoiandan", - "name": "Stoian Dan", - "avatar_url": "https://avatars.githubusercontent.com/u/10388612?v=4", - "profile": "https://github.com/stoiandan", - "contributions": [ - "content" - ] - }, - { - "login": "PiDelport", - "name": "Pi Delport", - "avatar_url": "https://avatars.githubusercontent.com/u/630271?v=4", - "profile": "https://about.me/pjdelport", - "contributions": [ - "content" - ] - }, - { - "login": "sateeshkumarb", - "name": "Sateesh ", - "avatar_url": "https://avatars.githubusercontent.com/u/429263?v=4", - "profile": "https://github.com/sateeshkumarb", - "contributions": [ - "code", - "content" - ] - }, - { - "login": "kayuapi", - "name": "ZC", - "avatar_url": "https://avatars.githubusercontent.com/u/10304328?v=4", - "profile": "https://github.com/kayuapi", - "contributions": [ - "content" - ] - }, - { - "login": "hyperparabolic", - "name": "hyperparabolic", - "avatar_url": "https://avatars.githubusercontent.com/u/12348474?v=4", - "profile": "https://github.com/hyperparabolic", - "contributions": [ - "code" - ] - }, - { - "login": "kolbma", - "name": "arlecchino", - "avatar_url": "https://avatars.githubusercontent.com/u/5228369?v=4", - "profile": "https://www.net4visions.at", - "contributions": [ - "doc" - ] - }, - { - "login": "jazzplato", - "name": "Richthofen", - "avatar_url": "https://avatars.githubusercontent.com/u/7576730?v=4", - "profile": "https://richthofen.io/", - "contributions": [ - "code" - ] - }, - { - "login": "cseltol", - "name": "Ivan Nerazumov", - "avatar_url": "https://avatars.githubusercontent.com/u/64264529?v=4", - "profile": "https://github.com/cseltol", - "contributions": [ - "doc" - ] - }, - { - "login": "lauralindzey", - "name": "lauralindzey", - "avatar_url": "https://avatars.githubusercontent.com/u/65185744?v=4", - "profile": "https://github.com/lauralindzey", - "contributions": [ - "doc" - ] - }, - { - "login": "sinharaksh1t", - "name": "Rakshit Sinha", - "avatar_url": "https://avatars.githubusercontent.com/u/28585848?v=4", - "profile": "https://github.com/sinharaksh1t", - "contributions": [ - "content" - ] - }, - { - "login": "dbednar230", - "name": "Damian", - "avatar_url": "https://avatars.githubusercontent.com/u/54457902?v=4", - "profile": "https://github.com/dbednar230", - "contributions": [ - "content" - ] - }, - { - "login": "benarmstead", - "name": "Ben Armstead", - "avatar_url": "https://avatars.githubusercontent.com/u/70973680?v=4", - "profile": "https://benarmstead.co.uk", - "contributions": [ - "code" - ] - }, - { - "login": "anuk909", - "name": "anuk909", - "avatar_url": "https://avatars.githubusercontent.com/u/34924662?v=4", - "profile": "https://github.com/anuk909", - "contributions": [ - "content", - "code" - ] - }, - { - "login": "granddaifuku", - "name": "granddaifuku", - "avatar_url": "https://avatars.githubusercontent.com/u/49578068?v=4", - "profile": "https://granddaifuku.com/", - "contributions": [ - "content" - ] - }, - { - "login": "Weilet", - "name": "Weilet", - "avatar_url": "https://avatars.githubusercontent.com/u/32561597?v=4", - "profile": "https://weilet.me", - "contributions": [ - "content" - ] - }, - { - "login": "Millione", - "name": "LIU JIE", - "avatar_url": "https://avatars.githubusercontent.com/u/38575932?v=4", - "profile": "https://github.com/Millione", - "contributions": [ - "content" - ] - }, - { - "login": "abusch", - "name": "Antoine Büsch", - "avatar_url": "https://avatars.githubusercontent.com/u/506344?v=4", - "profile": "https://github.com/abusch", - "contributions": [ - "code" - ] - }, - { - "login": "frogtd", - "name": "frogtd", - "avatar_url": "https://avatars.githubusercontent.com/u/31412003?v=4", - "profile": "https://frogtd.com/", - "contributions": [ - "content" - ] - }, - { - "login": "EmisonLu", - "name": "Zhenghao Lu", - "avatar_url": "https://avatars.githubusercontent.com/u/54395432?v=4", - "profile": "https://github.com/EmisonLu", - "contributions": [ - "content" - ] - }, - { - "login": "fredr", - "name": "Fredrik Enestad", - "avatar_url": "https://avatars.githubusercontent.com/u/762956?v=4", - "profile": "https://soundtrackyourbrand.com", - "contributions": [ - "content" - ] - }, - { - "login": "xuesongbj", - "name": "xuesong", - "avatar_url": "https://avatars.githubusercontent.com/u/18476085?v=4", - "profile": "http://xuesong.pydevops.com", - "contributions": [ - "content" - ] - }, - { - "login": "MpdWalsh", - "name": "Michael Walsh", - "avatar_url": "https://avatars.githubusercontent.com/u/48160144?v=4", - "profile": "https://github.com/MpdWalsh", - "contributions": [ - "code" - ] - }, - { - "login": "alirezaghey", - "name": "alirezaghey", - "avatar_url": "https://avatars.githubusercontent.com/u/26653424?v=4", - "profile": "https://github.com/alirezaghey", - "contributions": [ - "content" - ] - }, - { - "login": "frvannes16", - "name": "Franklin van Nes", - "avatar_url": "https://avatars.githubusercontent.com/u/3188475?v=4", - "profile": "https://github.com/frvannes16", - "contributions": [ - "code" - ] - }, - { - "login": "nekonako", - "name": "nekonako", - "avatar_url": "https://avatars.githubusercontent.com/u/46141275?v=4", - "profile": "https://nekonako.github.io", - "contributions": [ - "code" - ] - }, - { - "login": "tan-zx", - "name": "ZX", - "avatar_url": "https://avatars.githubusercontent.com/u/67887489?v=4", - "profile": "https://github.com/tan-zx", - "contributions": [ - "content" - ] - }, - { - "login": "sundevilyang", - "name": "Yang Wen", - "avatar_url": "https://avatars.githubusercontent.com/u/1499214?v=4", - "profile": "https://github.com/sundevilyang", - "contributions": [ - "content" - ] - }, - { - "login": "highb", - "name": "Brandon High", - "avatar_url": "https://avatars.githubusercontent.com/u/759848?v=4", - "profile": "https://brandon-high.com", - "contributions": [ - "doc" - ] - }, - { - "login": "x-hgg-x", - "name": "x-hgg-x", - "avatar_url": "https://avatars.githubusercontent.com/u/39058530?v=4", - "profile": "https://github.com/x-hgg-x", - "contributions": [ - "code" - ] - }, - { - "login": "KisaragiEffective", - "name": "Kisaragi", - "avatar_url": "https://avatars.githubusercontent.com/u/48310258?v=4", - "profile": "http://kisaragieffective.github.io", - "contributions": [ - "doc" - ] - }, - { - "login": "Kallu-A", - "name": "Lucas Aries", - "avatar_url": "https://avatars.githubusercontent.com/u/73198738?v=4", - "profile": "https://github.com/Kallu-A", - "contributions": [ - "content" - ] - }, - { - "login": "ragreenburg", - "name": "ragreenburg", - "avatar_url": "https://avatars.githubusercontent.com/u/24358100?v=4", - "profile": "https://github.com/ragreenburg", - "contributions": [ - "content" - ] - }, - { - "login": "stevenfukase", - "name": "stevenfukase", - "avatar_url": "https://avatars.githubusercontent.com/u/66785624?v=4", - "profile": "https://github.com/stevenfukase", - "contributions": [ - "content" - ] - }, - { - "login": "J-S-Kim", - "name": "J-S-Kim", - "avatar_url": "https://avatars.githubusercontent.com/u/17569303?v=4", - "profile": "https://github.com/J-S-Kim", - "contributions": [ - "content" - ] - }, - { - "login": "Fointard", - "name": "Fointard", - "avatar_url": "https://avatars.githubusercontent.com/u/9333398?v=4", - "profile": "https://github.com/Fointard", - "contributions": [ - "content" - ] - }, - { - "login": "rytheo", - "name": "Ryan Lowe", - "avatar_url": "https://avatars.githubusercontent.com/u/22184325?v=4", - "profile": "https://github.com/rytheo", - "contributions": [ - "code" - ] - }, - { - "login": "cuishuang", - "name": "cui fliter", - "avatar_url": "https://avatars.githubusercontent.com/u/15921519?v=4", - "profile": "http://www.dashen.tech", - "contributions": [ - "content" - ] - }, - { - "login": "luskwater", - "name": "Ron Lusk", - "avatar_url": "https://avatars.githubusercontent.com/u/42529?v=4", - "profile": "https://github.com/luskwater", - "contributions": [ - "content" - ] - }, - { - "login": "liby", - "name": "Bryan Lee", - "avatar_url": "https://avatars.githubusercontent.com/u/38807139?v=4", - "profile": "http://liby.github.io/liby/", - "contributions": [ - "content" - ] - }, - { - "login": "nandajavarma", - "name": "Nandaja Varma", - "avatar_url": "https://avatars.githubusercontent.com/u/2624550?v=4", - "profile": "http://nandaja.space", - "contributions": [ - "doc" - ] - }, - { - "login": "merelymyself", - "name": "pwygab", - "avatar_url": "https://avatars.githubusercontent.com/u/88221256?v=4", - "profile": "https://github.com/merelymyself", - "contributions": [ - "code" - ] - }, - { - "login": "lucasgrvarela", - "name": "Lucas Grigolon Varela", - "avatar_url": "https://avatars.githubusercontent.com/u/37870368?v=4", - "profile": "http://linkedin.com/in/lucasgrvarela", - "contributions": [ - "content" - ] - }, - { - "login": "bufo24", - "name": "Bufo", - "avatar_url": "https://avatars.githubusercontent.com/u/32884105?v=4", - "profile": "https://github.com/bufo24", - "contributions": [ - "content" - ] - }, - { - "login": "jackos", - "name": "Jack Clayton", - "avatar_url": "https://avatars.githubusercontent.com/u/77730378?v=4", - "profile": "http://rustnote.com", - "contributions": [ - "code" - ] - }, - { - "login": "klkl0808", - "name": "Konstantin", - "avatar_url": "https://avatars.githubusercontent.com/u/24694249?v=4", - "profile": "https://github.com/klkl0808", - "contributions": [ - "content" - ] - }, - { - "login": "0pling", - "name": "0pling", - "avatar_url": "https://avatars.githubusercontent.com/u/104090344?v=4", - "profile": "https://github.com/0pling", - "contributions": [ - "content" - ] - }, - { - "login": "KatanaFluorescent", - "name": "KatanaFluorescent", - "avatar_url": "https://avatars.githubusercontent.com/u/60199077?v=4", - "profile": "https://github.com/KatanaFluorescent", - "contributions": [ - "code" - ] - }, - { - "login": "Drew-Morris", - "name": "Drew Morris", - "avatar_url": "https://avatars.githubusercontent.com/u/95818166?v=4", - "profile": "https://github.com/Drew-Morris", - "contributions": [ - "code" - ] - }, - { - "login": "camperdue42", - "name": "camperdue42", - "avatar_url": "https://avatars.githubusercontent.com/u/43047763?v=4", - "profile": "https://github.com/camperdue42", - "contributions": [ - "content" - ] - }, - { - "login": "YsuOS", - "name": "YsuOS", - "avatar_url": "https://avatars.githubusercontent.com/u/30138661?v=4", - "profile": "https://github.com/YsuOS", - "contributions": [ - "content" - ] - }, - { - "login": "icecream17", - "name": "Steven Nguyen", - "avatar_url": "https://avatars.githubusercontent.com/u/58114641?v=4", - "profile": "https://lichess.org/@/StevenEmily", - "contributions": [ - "content" - ] - }, - { - "login": "nacairns1", - "name": "nacairns1", - "avatar_url": "https://avatars.githubusercontent.com/u/94420090?v=4", - "profile": "https://noahcairns.dev", - "contributions": [ - "content" - ] - }, - { - "login": "pgjbz", - "name": "Paulo Gabriel Justino Bezerra", - "avatar_url": "https://avatars.githubusercontent.com/u/22059237?v=4", - "profile": "https://github.com/pgjbz", - "contributions": [ - "content" - ] - }, - { - "login": "jaystile", - "name": "Jason", - "avatar_url": "https://avatars.githubusercontent.com/u/46078028?v=4", - "profile": "https://github.com/jaystile", - "contributions": [ - "content" - ] - }, - { - "login": "exdx", - "name": "exdx", - "avatar_url": "https://avatars.githubusercontent.com/u/31546601?v=4", - "profile": "https://exdx.github.io", - "contributions": [ - "content" - ] - }, - { - "login": "Jzow", - "name": "James Zow", - "avatar_url": "https://avatars.githubusercontent.com/u/68860495?v=4", - "profile": "https://github.com/Jzow", - "contributions": [ - "content" - ] - }, - { - "login": "jayber", - "name": "James Bromley", - "avatar_url": "https://avatars.githubusercontent.com/u/2474334?v=4", - "profile": "https://jamesabromley.wordpress.com/", - "contributions": [ - "content" - ] - }, - { - "login": "swhiteCQC", - "name": "swhiteCQC", - "avatar_url": "https://avatars.githubusercontent.com/u/77438466?v=4", - "profile": "https://github.com/swhiteCQC", - "contributions": [ - "content" - ] - }, - { - "login": "neilpate", - "name": "Neil Pate", - "avatar_url": "https://avatars.githubusercontent.com/u/7802334?v=4", - "profile": "https://github.com/neilpate", - "contributions": [ - "content" - ] - }, - { - "login": "wojexe", - "name": "wojexe", - "avatar_url": "https://avatars.githubusercontent.com/u/21208490?v=4", - "profile": "https://wojexe.com", - "contributions": [ - "content" - ] - }, - { - "login": "Tostapunk", - "name": "Mattia Schiavon", - "avatar_url": "https://avatars.githubusercontent.com/u/25140297?v=4", - "profile": "https://github.com/Tostapunk", - "contributions": [ - "content" - ] - }, - { - "login": "PrettyWood", - "name": "Eric Jolibois", - "avatar_url": "https://avatars.githubusercontent.com/u/18406791?v=4", - "profile": "http://toucantoco.com", - "contributions": [ - "content" - ] - }, - { - "login": "EdwinChang24", - "name": "Edwin Chang", - "avatar_url": "https://avatars.githubusercontent.com/u/88263098?v=4", - "profile": "http://edwinchang.vercel.app", - "contributions": [ - "content" - ] - }, - { - "login": "saikatdas0790", - "name": "Saikat Das", - "avatar_url": "https://avatars.githubusercontent.com/u/7412443?v=4", - "profile": "https://saikat.dev/", - "contributions": [ - "content" - ] - }, - { - "login": "thatlittleboy", - "name": "Jeremy Goh", - "avatar_url": "https://avatars.githubusercontent.com/u/30731072?v=4", - "profile": "https://github.com/thatlittleboy", - "contributions": [ - "content" - ] - }, - { - "login": "Lioness100", - "name": "Lioness100", - "avatar_url": "https://avatars.githubusercontent.com/u/65814829?v=4", - "profile": "https://github.com/Lioness100", - "contributions": [ - "content" - ] - }, - { - "login": "tvkn", - "name": "Tristan Nicholls", - "avatar_url": "https://avatars.githubusercontent.com/u/79277926?v=4", - "profile": "https://github.com/tvkn", - "contributions": [ - "content" - ] - }, - { - "login": "clairew", - "name": "Claire", - "avatar_url": "https://avatars.githubusercontent.com/u/9344258?v=4", - "profile": "http://clairewang.net", - "contributions": [ - "content" - ] - }, - { - "login": "Mouwrice", - "name": "Maurice Van Wassenhove", - "avatar_url": "https://avatars.githubusercontent.com/u/56763273?v=4", - "profile": "https://github.com/Mouwrice", - "contributions": [ - "content" - ] - }, - { - "login": "johnmendel", - "name": "John Mendelewski", - "avatar_url": "https://avatars.githubusercontent.com/u/77524?v=4", - "profile": "http://jmthree.com", - "contributions": [ - "code" - ] - }, - { - "login": "brianfakhoury", - "name": "Brian Fakhoury", - "avatar_url": "https://avatars.githubusercontent.com/u/20828724?v=4", - "profile": "http://fakhoury.xyz", - "contributions": [ - "content" - ] - }, - { - "login": "markusboehme", - "name": "Markus Boehme", - "avatar_url": "https://avatars.githubusercontent.com/u/5074759?v=4", - "profile": "https://github.com/markusboehme", - "contributions": [ - "code" - ] - }, - { - "login": "nico-vromans", - "name": "Nico Vromans", - "avatar_url": "https://avatars.githubusercontent.com/u/48183857?v=4", - "profile": "https://github.com/nico-vromans", - "contributions": [ - "content" - ] - }, - { - "login": "vostok92", - "name": "vostok92", - "avatar_url": "https://avatars.githubusercontent.com/u/540339?v=4", - "profile": "https://github.com/vostok92", - "contributions": [ - "content" - ] - }, - { - "login": "magnusrodseth", - "name": "Magnus Rødseth", - "avatar_url": "https://avatars.githubusercontent.com/u/59113973?v=4", - "profile": "http://magnusrodseth.vercel.app", - "contributions": [ - "content" - ] - }, - { - "login": "rubiesonthesky", - "name": "rubiesonthesky", - "avatar_url": "https://avatars.githubusercontent.com/u/2591240?v=4", - "profile": "https://github.com/rubiesonthesky", - "contributions": [ - "content" - ] - }, - { - "login": "GabrielBianconi", - "name": "Gabriel Bianconi", - "avatar_url": "https://avatars.githubusercontent.com/u/1275491?v=4", - "profile": "http://www.gabrielbianconi.com/", - "contributions": [ - "content" - ] - }, - { - "login": "Kodylow", - "name": "Kody Low", - "avatar_url": "https://avatars.githubusercontent.com/u/74332828?v=4", - "profile": "https://github.com/Kodylow", - "contributions": [ - "content" - ] - } - ], - "contributorsPerLine": 8, - "projectName": "rustlings", - "projectOwner": "rust-lang", - "repoType": "github", - "repoHost": "https://github.com", - "skipCi": true -} diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000000..b8fa3f7745 --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,2 @@ +[alias] +dev = ["run", "--", "dev"] diff --git a/.editorconfig b/.editorconfig deleted file mode 100644 index aab09aa35d..0000000000 --- a/.editorconfig +++ /dev/null @@ -1,7 +0,0 @@ -root = true - -[*.rs] -end_of_line = lf -insert_final_newline = true -indent_style = space -indent_size = 4 diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index bf2a041a4b..0d130904dc 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -1,20 +1,47 @@ -name: Rustlings Tests +name: Check on: push: - branches: [ main ] + branches: [main] + paths-ignore: + - website + - '*.md' pull_request: - branches: [ main ] + branches: [main] + paths-ignore: + - website + - '*.md' env: CARGO_TERM_COLOR: always jobs: - build: + clippy: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 - - name: Build - run: cargo build --verbose - - name: Run tests - run: cargo test --verbose + - uses: actions/checkout@v6 + - name: Clippy + run: cargo clippy -- --deny warnings + fmt: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - name: rustfmt + run: cargo fmt --all --check + test: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + steps: + - uses: actions/checkout@v6 + - uses: swatinem/rust-cache@v2 + - name: cargo test + run: cargo test --workspace + dev-check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: swatinem/rust-cache@v2 + - name: rustlings dev check + run: cargo dev check --require-solutions diff --git a/.github/workflows/website.yml b/.github/workflows/website.yml new file mode 100644 index 0000000000..d751358143 --- /dev/null +++ b/.github/workflows/website.yml @@ -0,0 +1,43 @@ +name: Website + +on: + workflow_dispatch: + push: + branches: [main] + paths: [website] + +jobs: + build: + defaults: + run: + working-directory: website + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - name: Install TailwindCSS + run: npm install + - name: Build CSS + run: npx @tailwindcss/cli -m -i input.css -o static/main.css + - name: Download Zola + run: curl -fsSL https://github.com/getzola/zola/releases/download/v0.20.0/zola-v0.20.0-x86_64-unknown-linux-gnu.tar.gz | tar xz + - name: Build site + run: ./zola build + - name: Upload static files as artifact + uses: actions/upload-pages-artifact@v3 + with: + path: website/public/ + + deploy: + needs: build + # Grant GITHUB_TOKEN the permissions required to make a Pages deployment + permissions: + pages: write # to deploy to Pages + id-token: write # to verify the deployment originates from an appropriate source + # Deploy to the github-pages environment + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + runs-on: ubuntu-latest + steps: + - name: Deploy to GitHub Pages + uses: actions/deploy-pages@v4 diff --git a/.gitignore b/.gitignore index 534453bca1..ea65eb1ed8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,12 +1,19 @@ -*.swp +# Cargo target/ -**/*.rs.bk +Cargo.lock +!/Cargo.lock + +# State file +.rustlings-state.txt + +# OS .DS_Store -*.pdb -exercises/clippy/Cargo.toml -exercises/clippy/Cargo.lock -rust-project.json +.direnv/ + +# Editor +*.swp .idea -.vscode *.iml -*.o + +# Ignore file for editors like Helix +.ignore diff --git a/.gitpod.yml b/.gitpod.yml deleted file mode 100644 index 73cb802da9..0000000000 --- a/.gitpod.yml +++ /dev/null @@ -1,7 +0,0 @@ -tasks: - - init: /workspace/rustlings/install.sh - command: /workspace/.cargo/bin/rustlings watch - -vscode: - extensions: - - rust-lang.rust@0.7.8 diff --git a/.replit b/.replit deleted file mode 100644 index 8462a6fca8..0000000000 --- a/.replit +++ /dev/null @@ -1,2 +0,0 @@ -language = "rust" -run = "[ -x ~/.cargo/bin/rustlings ] && ~/.cargo/bin/rustlings watch || ./install.sh" diff --git a/.typos.toml b/.typos.toml new file mode 100644 index 0000000000..743c87416f --- /dev/null +++ b/.typos.toml @@ -0,0 +1,7 @@ +[default.extend-words] +"earch" = "earch" # Because of earch in the list footer + +[files] +extend-exclude = [ + "CHANGELOG.md", +] diff --git a/AUTHORS.md b/AUTHORS.md deleted file mode 100644 index 8edf09bfb2..0000000000 --- a/AUTHORS.md +++ /dev/null @@ -1,229 +0,0 @@ -## Authors - -This file lists the people that have contributed to this project. - -Excluded from this list are @carols10cents and @diannasoreil, the principal -authors. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Carol (Nichols || Goulding)

💻 🖋

QuietMisdreavus

💻 🖋

Robert M Lugg

🖋

Hynek Schlawack

💻

Katharina Fey

💻

lukabavdaz

💻 🖋

Erik Vesteraas

💻

delet0r

💻

Shaun Bennett

💻

Andrew Bagshaw

💻

Kyle Isom

💻

Colin Pitrat

💻

Zac Anger

💻

Matthias Geier

💻

Chris Pearce

💻

Yvan Sraka

💻

Denys Smirnov

💻

eddyp

💻

Brian Kung

💻 🖋

Russell

💻

Dan Wilhelm

📖

Jesse

💻 🖋

Fredrik Jambrén

💻

Pete McFarlane

🖋

nkanderson

💻 🖋

Ajax M

📖

Dylan Nugent

🖋

vyaslav

💻 🖋

George

💻

Thomas Holloway

💻 🖋

Jubilee

💻

WofWca

💻

Roberto Vidal

💻 📖 🤔 🚧

Jens

📖

Rahat Ahmed

📖

Abdou Seck

💻 🖋 👀

Katie

💻

Socrates

📖

gnodarse

🖋

Harrison Metzger

💻

Torben Jonas

💻 🖋

Paul Bissex

📖

Steven Mann

💻 🖋

Mario Reder

💻 🖋

skim

💻

Sanjay K

💻 🖋

Rohan Jain

💻

Said Aspen

💻 🖋

Ufuk Celebi

💻

lebedevsergey

📖

Aleksei Trifonov

🖋

Darren Meehan

🖋

Jihchi Lee

🖋

Christofer Bertonha

🖋

Vivek Bharath Akupatni

💻 ⚠️

Dídac Sementé Fernández

💻 🖋

Rob Story

💻

Siobhan Jacobson

💻

Evan Carroll

🖋

Jawaad Mahmood

🖋

Gaurang Tandon

🖋

Stefan Kupresak

🖋

Greg Leonard

🖋

Ryan McQuen

💻

Annika

👀

Axel Viala

💻

Mohammed Sazid Al Rashid

🖋 💻

Caleb Webber

🚧

Peter N

🚧

seancad

🚧

Will Hayworth

🖋

Christian Zeller

🖋

Jean-Francois Chevrette

🖋 💻

John Baber-Lucero

🖋

Tal

🖋

apogeeoak

🖋 💻

Larry Garfield

🖋

circumspect

🖋

Cyrus Wyett

🖋

cadolphs

💻

Pascal H.

🖋

Rod Elias

🖋

Matt Lebl

💻

Ignacio Le Fluk

🖋

Taylor Yu

💻 🖋

Patrick Hintermayer

💻

Pete Pavlovski

🖋

k12ish

🖋

Shao Yang Hong

🖋

Brandon Macer

🖋

Stoian Dan

🖋

Pi Delport

🖋

Sateesh

💻 🖋

ZC

🖋

hyperparabolic

💻

arlecchino

📖

Richthofen

💻

Ivan Nerazumov

📖

lauralindzey

📖

Rakshit Sinha

🖋

Damian

🖋

Ben Armstead

💻

anuk909

🖋 💻

granddaifuku

🖋

Weilet

🖋

LIU JIE

🖋

Antoine Büsch

💻

frogtd

🖋

Zhenghao Lu

🖋

Fredrik Enestad

🖋

xuesong

🖋

Michael Walsh

💻

alirezaghey

🖋

Franklin van Nes

💻

nekonako

💻

ZX

🖋

Yang Wen

🖋

Brandon High

📖

x-hgg-x

💻

Kisaragi

📖

Lucas Aries

🖋

ragreenburg

🖋

stevenfukase

🖋

J-S-Kim

🖋

Fointard

🖋

Ryan Lowe

💻

cui fliter

🖋

Ron Lusk

🖋

Bryan Lee

🖋

Nandaja Varma

📖

pwygab

💻

Lucas Grigolon Varela

🖋

Bufo

🖋

Jack Clayton

💻

Konstantin

🖋

0pling

🖋

KatanaFluorescent

💻

Drew Morris

💻

camperdue42

🖋

YsuOS

🖋

Steven Nguyen

🖋

nacairns1

🖋

Paulo Gabriel Justino Bezerra

🖋

Jason

🖋

exdx

🖋

James Zow

🖋

James Bromley

🖋

swhiteCQC

🖋

Neil Pate

🖋

wojexe

🖋

Mattia Schiavon

🖋

Eric Jolibois

🖋

Edwin Chang

🖋

Saikat Das

🖋

Jeremy Goh

🖋

Lioness100

🖋

Tristan Nicholls

🖋

Claire

🖋

Maurice Van Wassenhove

🖋

John Mendelewski

💻

Brian Fakhoury

🖋

Markus Boehme

💻

Nico Vromans

🖋

vostok92

🖋

Magnus Rødseth

🖋

rubiesonthesky

🖋

Gabriel Bianconi

🖋

Kody Low

🖋
- - - - - - -This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b15cf996a..2d2b4153d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,381 @@ - +## Unreleased + +### Changed + +- `vecs2`: Removed the use of `map` and `collect`, which are only taught later. + +## 6.5.0 (2025-08-21) + +### Added + +- Check that Clippy is installed before initialization + +### Changed + +- Upgrade to Rust edition 2024 +- Raise the minimum supported Rust version to `1.88` +- Don't follow symlinks in the file watcher +- `dev new`: Don't add `.rustlings-state.txt` to `.gitignore` + +### Fixed + +- Fix file links in VS Code +- Fix error printing when the progress bar is shown +- `dev check`: Don't check formatting if there are no solution files + +## 6.4.0 (2024-11-11) + +### Added + +- The list of exercises is now searchable by pressing `s` or `/` 🔍️ (thanks to [@frroossst](https://github.com/frroossst)) +- New option `c` in the prompt to manually check all exercises ✅ (thanks to [@Nahor](https://github.com/Nahor)) +- New command `check-all` to manually check all exercises ✅ (thanks to [@Nahor](https://github.com/Nahor)) +- Addictive animation for showing the progress of checking all exercises. A nice showcase of parallelism in Rust ✨ +- New option `x` in the prompt to reset the file of the current exercise 🔄 +- Allow `dead_code` for all exercises and solutions ⚰️ (thanks to [@huss4in](https://github.com/huss4in)) +- Pause input while running an exercise to avoid unexpected prompt interactions ⏸️ +- Limit the maximum number of exercises to 999. Any community exercises willing to reach that limit? 🔝 + +### Changed + +- `enums3`: Remove redundant enum definition task (thanks to [@senekor](https://github.com/senekor)) +- `if2`: Make the exercise less confusing by avoiding "fizz", "fuzz", "foo", "bar" and "baz" (thanks to [@senekor](https://github.com/senekor)) +- `hashmap3`: Use the method `Entry::or_default`. +- Update the state of all exercises when checking all of them (thanks to [@Nahor](https://github.com/Nahor)) +- The main prompt doesn't need a confirmation with ENTER on Unix-like systems anymore. +- No more jumping back to a previous exercise when its file is changed. Use the list to jump between exercises. +- Dump the solution file after an exercise is done even if the solution's directory doesn't exist. +- Rework the footer in the list. +- Optimize the file watcher. + +### Fixed + +- Fix bad contrast in the list on terminals with a light theme. + +## 6.3.0 (2024-08-29) + +### Added + +- Add the following exercise lints: + - `forbid(unsafe_code)`: You shouldn't write unsafe code in Rustlings. + - `forbid(unstable_features)`: You don't need unstable features in Rustlings and shouldn't rely on them while learning Rust. + - `forbid(todo)`: You forgot a `todo!()`. + - `forbid(empty_loop)`: This can only happen by mistake in Rustlings. + - `deny(infinite_loop)`: No infinite loops are needed in Rustlings. + - `deny(mem_forget)`: You shouldn't leak memory while still learning Rust. +- Show a link to every exercise file in the list. +- Add scroll padding in the list. +- Break the help footer of the list into two lines when the terminal width isn't big enough. +- Enable scrolling with the mouse in the list. +- `dev check`: Show the progress of checks. +- `dev check`: Check that the length of all exercise names is lower than 32. +- `dev check`: Check if exercise contains no tests and isn't marked with `test = false`. + +### Changed + +- The compilation time when installing Rustlings is reduced. +- Pressing `c` in the list for "continue on" now quits the list after setting the selected exercise as the current one. +- Better highlighting of the solution file after an exercise is done. +- Don't show the output of successful tests anymore. Instead, show the pretty output for tests. +- Be explicit about `q` only quitting the list and not the whole program in the list. +- Be explicit about `r` only resetting one exercise (the selected one) in the list. +- Ignore the standard output of `git init`. +- `threads3`: Remove the queue length and improve tests. +- `errors4`: Use match instead of a comparison chain in the solution. +- `functions3`: Only take `u8` to avoid using a too high number of iterations by mistake. +- `dev check`: Always check with strict Clippy (warnings to errors) when checking the solutions. + +### Fixed + +- Fix the error on some systems about too many open files during the final check of all exercises. +- Fix the list when the terminal height is too low. +- Restore the terminal after an error in the list. + +## 6.2.0 (2024-08-09) + +### Added + +- Show a message before checking and running an exercise. This gives the user instant feedback and avoids confusion if the checks take too long. +- Show a helpful error message when trying to install Rustlings with a Rust version lower than the minimum one that Rustlings supports. +- Add a `README.md` file to the `solutions/` directory. +- Allow initializing Rustlings in a Cargo workspace. +- `dev check`: Check that all solutions are formatted with `rustfmt`. + +### Changed + +- Remove the state file and the solutions directory from the generated `.gitignore` file. +- Run the final check of all exercises in parallel. +- Small exercise improvements. + +## 6.1.0 (2024-07-10) + +#### Added + +- `dev check`: Check that all exercises (including community ones) include at least one `TODO` comment. +- `dev check`: Check that all exercises actually fail to run (not already solved). + +#### Changed + +- Make enum variants more consistent between enum exercises. +- `iterators3`: Teach about the possible case of integer overflow during division. + +#### Fixed + +- Exit with a helpful error message on missing/unsupported terminal/TTY. +- Mark the last exercise as done. + +## 6.0.1 (2024-07-04) + +Small exercise improvements and fixes. +Most importantly, fixed that the exercise `clippy1` was already solved 😅 + +## 6.0.0 (2024-07-03) + +This release is the result of a complete rewrite to deliver a ton of new features and improvements ✨ +The most important changes are highlighted below. + +### Installation + +The installation has been simplified a lot! +To install Rustlings after installing Rust, all what you need to do now is running the following command: + +```bash +cargo install rustlings +``` + +Yes, this means that Rustlings is now on [crates.io](https://crates.io/crates/rustlings) 🎉 + +You can read about the motivations of this change in [this issue](https://github.com/rust-lang/rustlings/issues/1919). + +### UI/UX + +- The UI is now responsive when the terminal is resized. +- The progress bar was moved to the bottom so that you can always see your progress and the current exercise to work on. +- The current exercise path is now a terminal link. It will open the exercise file in your default editor when you click on it. +- A small prompt is now always shown at the bottom. It allows you to choose an action by entering a character. For example, entering `h` will show you the hint of the current exercise. +- The comment "I AM NOT DONE!" doesn't exist anymore. Instead of needing to remove it to go to the next exercise, you need to enter `n` in the terminal. + +### List mode + +A new list mode was added! +You can enter it by entering `l` in the watch mode. +It offers the following features: + +- Browse all exercises and see their state (pending/done). +- Filter exercises based on their state (pending/done). +- Continue at another exercise. This allows you to skip some exercises or go back to previous ones. +- Reset an exercise so you can start over and revert your changes. + +### Solutions + +After finishing an exercise, a solution file will be available and Rustlings will show you its path in green. +This allows you to compare your solution with an idiomatic solution and maybe learn about other ways to solve a problem. + +While writing the solutions, all exercises have been polished 🌟 +For example, every exercise now contains `TODO` comments to highlight what the user needs to change and where. + +### LSP support out of the box + +Instead of creating a `project.json` file using `rustlings lsp`, Rustlings now works with a `Cargo.toml` file out of the box. +No actions are needed to activate the language server `rust-analyzer`. + +This should avoid issues related to the language server or to running exercises, especially the ones with Clippy. + +### Clippy + +Clippy lints are now shown on all exercises, not only the Clippy exercises 📎 +Make Clippy your friend from early on 🥰 + +### Community Exercises + +Rustlings now supports community exercises! + +Do you want to create your own set of Rustlings exercises to focus on some specific topic? +Or do you want to translate the original Rustlings exercises? +Then follow the link to the guide about [community exercises](https://rustlings.rust-lang.org/community-exercises)! + +## 5.6.1 (2023-09-18) + +#### Changed + +- Converted all exercises with assertions to test mode. + +#### Fixed + +- `cow1`: Reverted regression introduced by calling `to_mut` where it + shouldn't have been called, and clarified comment. +- `primitive_types3`: Require at least an array of 100 elements. +- Removed hint comments when no hint exists for the exercise. +- `as_ref_mut`: Fixed a typo in a test function name. +- `enums3`: Fixed formatting with `rustfmt`. + +## 5.6.0 (2023-09-04) + +#### Added + +- New exercise: `if3`, teaching the user about `if let` statements. +- `hashmaps2`: Added an extra test function to check if the amount of fruits is higher than zero. +- `enums3`: Added a test for `Message`. +- `if1`: Added a test case to check equal values. +- `if3`: Added a note specifying that there are no test changes needed. + +#### Changed + +- Swapped the order of threads and smart pointer exercises. +- Rewrote the CLI to use `clap` - it's matured much since we switched to `argh` :) +- `structs3`: Switched from i32 to u32. +- `move_semantics`: Switched 1-4 to tests, and rewrote them to be way simpler, while still teaching about the same + concepts. + +#### Fixed + +- `iterators5`: + - Removed an outdated part of the hint. + - Renamed variables to use snake_case. +- `vecs2`: Updated the hint to reference the renamed loop variable. +- `enums3`: Changed message string in test so that it gets properly tested. +- `strings2`: Corrected line number in hint, then removed it (this both happened as part of this release cycle). +- `primitive_types4`: Updated hint to the correct ending index. +- `quiz1`: Removed duplicated sentence from exercise comments. +- `errors4`: Improved comment. +- `from_into`: Fixed test values. +- `cow1`: Added `.to_mut()` to distinguish from the previous test case. +- `threads2`: Updated hint text to reference the correct book heading. + +#### Housekeeping + +- Cleaned up the explanation paragraphs at the start of each exercise. +- Lots of Nix housekeeping that I don't feel qualified to write about! +- Improved CI workflows, we're now testing on multiple platforms at once. + +## 5.5.1 (2023-05-17) + +#### Fixed + +- Reverted `rust-project.json` path generation due to an upstream `rust-analyzer` fix. + +## 5.5.0 (2023-05-17) + +#### Added + +- `strings2`: Added a reference to the book chapter for reference conversion +- `lifetimes`: Added a link to the lifetimekata project +- Added a new `tests4` exercises, which teaches about testing for panics +- Added a `!` prefix command to watch mode that runs an external command +- Added a `--success-hints` option to watch mode that shows hints on exercise success + +#### Changed + +- `vecs2`: Renamed iterator variable bindings for clarify +- `lifetimes`: Changed order of book references +- `hashmaps2`: Clarified instructions in the todo block +- Moved lifetime exercises before test exercises (via the recommended book ordering) +- `options2`: Improved tests for layering options +- `modules2`: Added more information to the hint + +#### Fixed + +- `errors2`: Corrected a comment wording +- `iterators2`: Fixed a spelling mistake in the hint text +- `variables`: Wrapped the mut keyword with backticks for readability +- `move_semantics2`: Removed references to line numbers +- `cow1`: Clarified the `owned_no_mutation` comments +- `options3`: Changed exercise to panic when no match is found +- `rustlings lsp` now generates absolute paths, which should fix VSCode `rust-analyzer` usage on Windows + +#### Housekeeping + +- Added a markdown linter to run on GitHub actions +- Split quick installation section into two code blocks + +## 5.4.1 (2023-03-10) + +#### Changed + +- `vecs`: Added links to `iter_mut` and `map` to README.md +- `cow1`: Changed main to tests +- `iterators1`: Formatted according to rustfmt + +#### Fixed + +- `errors5`: Unified undisclosed type notation +- `arc1`: Improved readability by avoiding implicit dereference +- `macros4`: Prevented auto-fix by adding `#[rustfmt::skip]` +- `cli`: Actually show correct progress percentages + +## 5.4.0 (2023-02-12) + +#### Changed + +- Reordered exercises + - Unwrapped `standard_library_types` into `iterators` and `smart_pointers` + - Moved smart pointer exercises behind threads + - Ordered `rc1` before `arc1` +- **intro1**: Added a note on `rustlings lsp` +- **threads1**: Panic if threads are not joined +- **cli**: + - Made progress bar update proportional to amount of files verified + - Decreased `watch` delay from 2 to 1 second + +#### Fixed + +- Capitalized "Rust" in exercise hints +- **enums3**: Removed superfluous tuple brackets +- **quiz2, clippy1, iterators1**: Fixed a typo +- **rc1**: Fixed a prompt error +- **cli**: + - Fixed a typo in a method name + - Specified the edition in `rustc` commands + +#### Housekeeping + +- Bumped min Rust version to 1.58 in installation script + +## 5.3.0 (2022-12-23) + +#### Added + +- **cli**: Added a percentage display in watch mode +- Added a `flake.nix` for Nix users + +#### Changed + +- **structs3**: Added an additional test +- **macros**: Added a link to MacroKata in the README + +#### Fixed + +- **strings3**: Added a link to `std` in the hint +- **threads1**: Corrected a hint link +- **iterators1**: Clarified hint steps +- **errors5**: Fix a typo in the hint +- **options1**: Clarified on the usage of the 24-hour system +- **threads2, threads3**: Explicitly use `Arc::clone` +- **structs3**: Clarifed the hint +- **quiz2, as_ref_mut, options1, traits1, traits2**: Clarified hints +- **traits1, traits2, cli**: Tidied up unmatching backticks +- **enums2**: Removed unnecessary indirection of self +- **enums3**: Added an extra tuple comment + +#### Housekeeping + +- Added a VSCode extension recommendation +- Applied some Clippy and rustfmt formatting +- Added a note on Windows PowerShell and other shell compatibility + +## 5.2.1 (2022-09-06) + +#### Fixed + +- **quiz1**: Reworded the comment to actually reflect what's going on in the tests. + Also added another assert just to make sure. +- **rc1**: Fixed a typo in the hint. +- **lifetimes**: Add quotes to the `println!` output, for readability. + +#### Housekeeping + +- Fixed a typo in README.md + ## 5.2.0 (2022-08-27) #### Added @@ -15,14 +392,12 @@ - **quiz1**: Adjusted the explanations to be consistent with the tests - ## 5.1.1 (2022-08-17) #### Bug Fixes - Fixed an incorrect assertion in options1 - ## 5.1.0 (2022-08-16) #### Features @@ -57,7 +432,6 @@ - Clarified manual installation instructions using `cargo install --path .` - Added a link to our Zulip in the readme file - ## 5.0.0 (2022-07-16) #### Features @@ -115,7 +489,7 @@ - **from_str**: Added a hint comment about string error message conversion with `Box`. - **try_from_into**: Fixed the function name in comment. - + #### Removed - Removed the legacy LSP feature that was using `mod.rs` files. @@ -130,7 +504,6 @@ - Updated spacing in Cargo.toml. - Added a GitHub actions config so that tests run on every PR/commit. - ## 4.8.0 (2022-07-01) #### Features @@ -151,7 +524,6 @@ - Replaced the git.io URL with the fully qualified URL because of git.io's sunsetting. - Removed the deprecated Rust GitPod extension. - ## 4.7.1 (2022-04-20) #### Features @@ -172,423 +544,389 @@ - The changelog will now be manually written instead of being automatically generated by the Git log. - ## 4.7.0 (2022-04-14) - #### Features -* Add move_semantics6.rs exercise (#908) ([3f0e1303](https://github.com/rust-lang/rustlings/commit/3f0e1303e0b3bf3fecc0baced3c8b8a37f83c184)) -* **intro:** Add intro section. ([21c9f441](https://github.com/rust-lang/rustlings/commit/21c9f44168394e08338fd470b5f49b1fd235986f)) -* Include exercises folder in the project structure behind a feature, enabling rust-analyzer to work (#917) ([179a75a6](https://github.com/rust-lang/rustlings/commit/179a75a68d03ac9518dec2297fb17f91a4fc506b)) +- Add move_semantics6.rs exercise (#908) ([3f0e1303](https://github.com/rust-lang/rustlings/commit/3f0e1303e0b3bf3fecc0baced3c8b8a37f83c184)) +- **intro:** Add intro section. ([21c9f441](https://github.com/rust-lang/rustlings/commit/21c9f44168394e08338fd470b5f49b1fd235986f)) +- Include exercises folder in the project structure behind a feature, enabling rust-analyzer to work (#917) ([179a75a6](https://github.com/rust-lang/rustlings/commit/179a75a68d03ac9518dec2297fb17f91a4fc506b)) #### Bug Fixes -* Fix a few spelling mistakes ([1c0fe3cb](https://github.com/rust-lang/rustlings/commit/1c0fe3cbcca85f90b3985985b8e265ee872a2ab2)) -* **cli:** - * Move long text strings into constants. ([f78c4802](https://github.com/rust-lang/rustlings/commit/f78c48020830d7900dd8d81f355606581670446d)) - * Replace `filter_map()` with `find_map()` ([9b27e8d](https://github.com/rust-lang/rustlings/commit/9b27e8d993ca20232fe38a412750c3f845a83b65)) -* **clippy1:** - * Set clippy::float_cmp lint to deny (#907) ([71a06044](https://github.com/rust-lang/rustlings/commit/71a06044e6a96ff756dc31d7b0ed665ae4badb57)) - * Updated code to test correctness clippy lint with approx_constant lint rule ([f2650de3](https://github.com/rust-lang/rustlings/commit/f2650de369810867d2763e935ac0963c32ec420e)) -* **errors1:** - * Add a comment to make the purpose more clear (#486) ([cbcde345](https://github.com/rust-lang/rustlings/commit/cbcde345409c3e550112e449242848eaa3391bb6)) - * Don't modify tests (#958) ([60bb7cc](https://github.com/rust-lang/rustlings/commit/60bb7cc3931d21d3986ad52b2b302e632a93831c)) -* **errors6:** Remove existing answer code ([43d0623](https://github.com/rust-lang/rustlings/commit/43d0623086edbc46fe896ba59c7afa22c3da9f7a)) -* **functions5:** Remove wrong new line and small English improvements (#885) ([8ef4869b](https://github.com/rust-lang/rustlings/commit/8ef4869b264094e5a9b50452b4534823a9df19c3)) -* **install:** protect path with whitespaces using quotes and stop at the first error ([d114847f](https://github.com/rust-lang/rustlings/commit/d114847f256c5f571c0b4c87e04b04bce3435509)) -* **intro1:** Add compiler error explanation. ([9b8de655](https://github.com/rust-lang/rustlings/commit/9b8de65525a5576b78cf0c8e4098cdd34296338f)) -* **iterators1:** reorder TODO steps ([0bd7a063](https://github.com/rust-lang/rustlings/commit/0bd7a0631a17a9d69af5746795a30efc9cf64e6e)) -* **move_semantics2:** Add comment ([89650f80](https://github.com/rust-lang/rustlings/commit/89650f808af23a32c9a2c6d46592b77547a6a464)) -* **move_semantics5:** correct typo (#857) ([46c28d5c](https://github.com/rust-lang/rustlings/commit/46c28d5cef3d8446b5a356b19d8dbc725f91a3a0)) -* **quiz1:** update to say quiz covers "If" ([1622e8c1](https://github.com/rust-lang/rustlings/commit/1622e8c198d89739765c915203efff0091bdeb78)) -* **structs3:** - * Add a hint for panic (#608) ([4f7ff5d9](https://github.com/rust-lang/rustlings/commit/4f7ff5d9c7b2d8b045194c1a9469d37e30257c4a)) - * remove redundant 'return' (#852) ([bf33829d](https://github.com/rust-lang/rustlings/commit/bf33829da240375d086f96267fc2e02fa6b07001)) - * Assigned value to `cents_per_gram` in test ([d1ee2da](https://github.com/rust-lang/rustlings/commit/d1ee2daf14f19105e6db3f9c610f44293d688532)) -* **structs3.rs:** assigned value to cents_per_gram in test ([d1ee2daf](https://github.com/rust-lang/rustlings/commit/d1ee2daf14f19105e6db3f9c610f44293d688532)) -* **traits1:** rename test functions to snake case (#854) ([1663a16e](https://github.com/rust-lang/rustlings/commit/1663a16eade6ca646b6ed061735f7982434d530d)) +- Fix a few spelling mistakes ([1c0fe3cb](https://github.com/rust-lang/rustlings/commit/1c0fe3cbcca85f90b3985985b8e265ee872a2ab2)) +- **cli:** + - Move long text strings into constants. ([f78c4802](https://github.com/rust-lang/rustlings/commit/f78c48020830d7900dd8d81f355606581670446d)) + - Replace `filter_map()` with `find_map()` ([9b27e8d](https://github.com/rust-lang/rustlings/commit/9b27e8d993ca20232fe38a412750c3f845a83b65)) +- **clippy1:** + - Set clippy::float_cmp lint to deny (#907) ([71a06044](https://github.com/rust-lang/rustlings/commit/71a06044e6a96ff756dc31d7b0ed665ae4badb57)) + - Updated code to test correctness clippy lint with approx_constant lint rule ([f2650de3](https://github.com/rust-lang/rustlings/commit/f2650de369810867d2763e935ac0963c32ec420e)) +- **errors1:** + - Add a comment to make the purpose more clear (#486) ([cbcde345](https://github.com/rust-lang/rustlings/commit/cbcde345409c3e550112e449242848eaa3391bb6)) + - Don't modify tests (#958) ([60bb7cc](https://github.com/rust-lang/rustlings/commit/60bb7cc3931d21d3986ad52b2b302e632a93831c)) +- **errors6:** Remove existing answer code ([43d0623](https://github.com/rust-lang/rustlings/commit/43d0623086edbc46fe896ba59c7afa22c3da9f7a)) +- **functions5:** Remove wrong new line and small English improvements (#885) ([8ef4869b](https://github.com/rust-lang/rustlings/commit/8ef4869b264094e5a9b50452b4534823a9df19c3)) +- **install:** protect path with whitespaces using quotes and stop at the first error ([d114847f](https://github.com/rust-lang/rustlings/commit/d114847f256c5f571c0b4c87e04b04bce3435509)) +- **intro1:** Add compiler error explanation. ([9b8de655](https://github.com/rust-lang/rustlings/commit/9b8de65525a5576b78cf0c8e4098cdd34296338f)) +- **iterators1:** reorder TODO steps ([0bd7a063](https://github.com/rust-lang/rustlings/commit/0bd7a0631a17a9d69af5746795a30efc9cf64e6e)) +- **move_semantics2:** Add comment ([89650f80](https://github.com/rust-lang/rustlings/commit/89650f808af23a32c9a2c6d46592b77547a6a464)) +- **move_semantics5:** correct typo (#857) ([46c28d5c](https://github.com/rust-lang/rustlings/commit/46c28d5cef3d8446b5a356b19d8dbc725f91a3a0)) +- **quiz1:** update to say quiz covers "If" ([1622e8c1](https://github.com/rust-lang/rustlings/commit/1622e8c198d89739765c915203efff0091bdeb78)) +- **structs3:** + - Add a hint for panic (#608) ([4f7ff5d9](https://github.com/rust-lang/rustlings/commit/4f7ff5d9c7b2d8b045194c1a9469d37e30257c4a)) + - remove redundant 'return' (#852) ([bf33829d](https://github.com/rust-lang/rustlings/commit/bf33829da240375d086f96267fc2e02fa6b07001)) + - Assigned value to `cents_per_gram` in test ([d1ee2da](https://github.com/rust-lang/rustlings/commit/d1ee2daf14f19105e6db3f9c610f44293d688532)) +- **structs3.rs:** assigned value to cents_per_gram in test ([d1ee2daf](https://github.com/rust-lang/rustlings/commit/d1ee2daf14f19105e6db3f9c610f44293d688532)) +- **traits1:** rename test functions to snake case (#854) ([1663a16e](https://github.com/rust-lang/rustlings/commit/1663a16eade6ca646b6ed061735f7982434d530d)) #### Documentation improvements -* Add hints on how to get GCC installed (#741) ([bc56861](https://github.com/rust-lang/rustlings/commit/bc5686174463ad6f4f6b824b0e9b97c3039d4886)) -* Fix some code blocks that were not highlighted ([17f9d74](https://github.com/rust-lang/rustlings/commit/17f9d7429ccd133a72e815fb5618e0ce79560929)) - +- Add hints on how to get GCC installed (#741) ([bc56861](https://github.com/rust-lang/rustlings/commit/bc5686174463ad6f4f6b824b0e9b97c3039d4886)) +- Fix some code blocks that were not highlighted ([17f9d74](https://github.com/rust-lang/rustlings/commit/17f9d7429ccd133a72e815fb5618e0ce79560929)) - ## 4.6.0 (2021-09-25) - #### Features -* add advanced_errs2 ([abd6b70c](https://github.com/rust-lang/rustlings/commit/abd6b70c72dc6426752ff41f09160b839e5c449e)) -* add advanced_errs1 ([882d535b](https://github.com/rust-lang/rustlings/commit/882d535ba8628d5e0b37e8664b3e2f26260b2671)) -* Add a farewell message when quitting `watch` ([1caef0b4](https://github.com/rust-lang/rustlings/commit/1caef0b43494c8b8cdd6c9260147e70d510f1aca)) -* add more watch commands ([a7dc080b](https://github.com/rust-lang/rustlings/commit/a7dc080b95e49146fbaafe6922a6de2f8cb1582a), closes [#842](https://github.com/rust-lang/rustlings/issues/842)) -* **modules:** update exercises, add modules3 (#822) ([dfd2fab4](https://github.com/rust-lang/rustlings/commit/dfd2fab4f33d1bf59e2e5ee03123c0c9a67a9481)) -* **quiz1:** add default function name in comment (#838) ([0a11bad7](https://github.com/rust-lang/rustlings/commit/0a11bad71402b5403143d642f439f57931278c07)) +- add advanced_errs2 ([abd6b70c](https://github.com/rust-lang/rustlings/commit/abd6b70c72dc6426752ff41f09160b839e5c449e)) +- add advanced_errs1 ([882d535b](https://github.com/rust-lang/rustlings/commit/882d535ba8628d5e0b37e8664b3e2f26260b2671)) +- Add a farewell message when quitting `watch` ([1caef0b4](https://github.com/rust-lang/rustlings/commit/1caef0b43494c8b8cdd6c9260147e70d510f1aca)) +- add more watch commands ([a7dc080b](https://github.com/rust-lang/rustlings/commit/a7dc080b95e49146fbaafe6922a6de2f8cb1582a), closes [#842](https://github.com/rust-lang/rustlings/issues/842)) +- **modules:** update exercises, add modules3 (#822) ([dfd2fab4](https://github.com/rust-lang/rustlings/commit/dfd2fab4f33d1bf59e2e5ee03123c0c9a67a9481)) +- **quiz1:** add default function name in comment (#838) ([0a11bad7](https://github.com/rust-lang/rustlings/commit/0a11bad71402b5403143d642f439f57931278c07)) #### Bug Fixes -* Correct small typo in exercises/conversions/from_str.rs ([86cc8529](https://github.com/rust-lang/rustlings/commit/86cc85295ae36948963ae52882e285d7e3e29323)) -* **cli:** typo in exercise.rs (#848) ([06d5c097](https://github.com/rust-lang/rustlings/commit/06d5c0973a3dffa3c6c6f70acb775d4c6630323c)) -* **from_str, try_from_into:** custom error types ([2dc93cad](https://github.com/rust-lang/rustlings/commit/2dc93caddad43821743e4903d89b355df58d7a49)) -* **modules2:** fix typo (#835) ([1c3beb0a](https://github.com/rust-lang/rustlings/commit/1c3beb0a59178c950dc05fe8ee2346b017429ae0)) -* **move_semantics5:** - * change &mut *y to &mut x (#814) ([d75759e8](https://github.com/rust-lang/rustlings/commit/d75759e829fdcd64ef071cf4b6eae2a011a7718b)) - * Clarify instructions ([df25684c](https://github.com/rust-lang/rustlings/commit/df25684cb79f8413915e00b5efef29369849cef1)) -* **quiz1:** Fix inconsistent wording (#826) ([03131a3d](https://github.com/rust-lang/rustlings/commit/03131a3d35d9842598150f9da817f7cc26e2669a)) - +- Correct small typo in exercises/conversions/from_str.rs ([86cc8529](https://github.com/rust-lang/rustlings/commit/86cc85295ae36948963ae52882e285d7e3e29323)) +- **cli:** typo in exercise.rs (#848) ([06d5c097](https://github.com/rust-lang/rustlings/commit/06d5c0973a3dffa3c6c6f70acb775d4c6630323c)) +- **from_str, try_from_into:** custom error types ([2dc93cad](https://github.com/rust-lang/rustlings/commit/2dc93caddad43821743e4903d89b355df58d7a49)) +- **modules2:** fix typo (#835) ([1c3beb0a](https://github.com/rust-lang/rustlings/commit/1c3beb0a59178c950dc05fe8ee2346b017429ae0)) +- **move_semantics5:** + - change &mut \*y to &mut x (#814) ([d75759e8](https://github.com/rust-lang/rustlings/commit/d75759e829fdcd64ef071cf4b6eae2a011a7718b)) + - Clarify instructions ([df25684c](https://github.com/rust-lang/rustlings/commit/df25684cb79f8413915e00b5efef29369849cef1)) +- **quiz1:** Fix inconsistent wording (#826) ([03131a3d](https://github.com/rust-lang/rustlings/commit/03131a3d35d9842598150f9da817f7cc26e2669a)) - - ## 4.5.0 (2021-07-07) - #### Features -* Add move_semantics5 exercise. (#746) ([399ab328](https://github.com/rust-lang/rustlings/commit/399ab328d8d407265c09563aa4ef4534b2503ff2)) -* **cli:** Add "next" to run the next unsolved exercise. (#785) ([d20e413a](https://github.com/rust-lang/rustlings/commit/d20e413a68772cd493561f2651cf244e822b7ca5)) +- Add move_semantics5 exercise. (#746) ([399ab328](https://github.com/rust-lang/rustlings/commit/399ab328d8d407265c09563aa4ef4534b2503ff2)) +- **cli:** Add "next" to run the next unsolved exercise. (#785) ([d20e413a](https://github.com/rust-lang/rustlings/commit/d20e413a68772cd493561f2651cf244e822b7ca5)) #### Bug Fixes -* rename result1 to errors4 ([50ab289d](https://github.com/rust-lang/rustlings/commit/50ab289da6b9eb19a7486c341b00048c516b88c0)) -* move_semantics5 hints ([1b858285](https://github.com/rust-lang/rustlings/commit/1b85828548f46f58b622b5e0c00f8c989f928807)) -* remove trailing whitespaces from iterators1 ([4d4fa774](https://github.com/rust-lang/rustlings/commit/4d4fa77459392acd3581c6068aa8be9a02de12fc)) -* add hints to generics1 and generics2 exercises ([31457940](https://github.com/rust-lang/rustlings/commit/31457940846b3844d78d4a4d2b074bc8d6aaf1eb)) -* remove trailing whitespace ([d9b69bd1](https://github.com/rust-lang/rustlings/commit/d9b69bd1a0a7a99f2c0d80933ad2eea44c8c71b2)) -* **installation:** first PowerShell command ([aa9a943d](https://github.com/rust-lang/rustlings/commit/aa9a943ddf3ae260782e73c26bcc9db60e5894b6)) -* **iterators5:** derive Clone, Copy ([91fc9e31](https://github.com/rust-lang/rustlings/commit/91fc9e3118f4af603c9911698cc2a234725cb032)) -* **quiz1:** Updated question description (#794) ([d8766496](https://github.com/rust-lang/rustlings/commit/d876649616cc8a8dd5f539f8bc1a5434b960b1e9)) -* **try_from_into, from_str:** hints for dyn Error ([11d2cf0d](https://github.com/rust-lang/rustlings/commit/11d2cf0d604dee3f5023c17802d69438e69fa50e)) -* **variables5:** confine the answer further ([48ffcbd2](https://github.com/rust-lang/rustlings/commit/48ffcbd2c4cc4d936c2c7480019190f179813cc5)) - +- rename result1 to errors4 ([50ab289d](https://github.com/rust-lang/rustlings/commit/50ab289da6b9eb19a7486c341b00048c516b88c0)) +- move_semantics5 hints ([1b858285](https://github.com/rust-lang/rustlings/commit/1b85828548f46f58b622b5e0c00f8c989f928807)) +- remove trailing whitespaces from iterators1 ([4d4fa774](https://github.com/rust-lang/rustlings/commit/4d4fa77459392acd3581c6068aa8be9a02de12fc)) +- add hints to generics1 and generics2 exercises ([31457940](https://github.com/rust-lang/rustlings/commit/31457940846b3844d78d4a4d2b074bc8d6aaf1eb)) +- remove trailing whitespace ([d9b69bd1](https://github.com/rust-lang/rustlings/commit/d9b69bd1a0a7a99f2c0d80933ad2eea44c8c71b2)) +- **installation:** first PowerShell command ([aa9a943d](https://github.com/rust-lang/rustlings/commit/aa9a943ddf3ae260782e73c26bcc9db60e5894b6)) +- **iterators5:** derive Clone, Copy ([91fc9e31](https://github.com/rust-lang/rustlings/commit/91fc9e3118f4af603c9911698cc2a234725cb032)) +- **quiz1:** Updated question description (#794) ([d8766496](https://github.com/rust-lang/rustlings/commit/d876649616cc8a8dd5f539f8bc1a5434b960b1e9)) +- **try_from_into, from_str:** hints for dyn Error ([11d2cf0d](https://github.com/rust-lang/rustlings/commit/11d2cf0d604dee3f5023c17802d69438e69fa50e)) +- **variables5:** confine the answer further ([48ffcbd2](https://github.com/rust-lang/rustlings/commit/48ffcbd2c4cc4d936c2c7480019190f179813cc5)) - - ## 4.4.0 (2021-04-24) - #### Bug Fixes -* Fix spelling error in main.rs ([91ee27f2](https://github.com/rust-lang/rustlings/commit/91ee27f22bd3797a9db57e5fd430801c170c5db8)) -* typo in default out text ([644c49f1](https://github.com/rust-lang/rustlings/commit/644c49f1e04cbb24e95872b3a52b07d692ae3bc8)) -* **collections:** Naming exercises for vectors and hashmap ([bef39b12](https://github.com/rust-lang/rustlings/commit/bef39b125961310b34b34871e480a82e82af4678)) -* **from_str:** - * Correct typos ([5f7c89f8](https://github.com/rust-lang/rustlings/commit/5f7c89f85db1f33da01911eaa479c3a2d4721678)) - * test for error instead of unwrap/should_panic ([15e71535](https://github.com/rust-lang/rustlings/commit/15e71535f37cfaed36e22eb778728d186e2104ab)) - * use trait objects for from_str ([c3e7b831](https://github.com/rust-lang/rustlings/commit/c3e7b831786c9172ed8bd5d150f3c432f242fba9)) -* **functions3:** improve function argument type (#687) ([a6509cc4](https://github.com/rust-lang/rustlings/commit/a6509cc4d545d8825f01ddf7ee37823b372154dd)) -* **hashmap2:** Update incorrect assertion (#660) ([72aaa15e](https://github.com/rust-lang/rustlings/commit/72aaa15e6ab4b72b3422f1c6356396e20a2a2bb8)) -* **info:** Fix typo (#635) ([cddc1e86](https://github.com/rust-lang/rustlings/commit/cddc1e86e7ec744ee644cc774a4887b1a0ded3e8)) -* **iterators2:** Moved errors out of tests. ([baf4ba17](https://github.com/rust-lang/rustlings/commit/baf4ba175ba6eb92989e3dd54ecbec4bedc9a863), closes [#359](https://github.com/rust-lang/rustlings/issues/359)) -* **iterators3:** Enabled iterators3.rs to run without commented out tests. ([c6712dfc](https://github.com/rust-lang/rustlings/commit/c6712dfccd1a093e590ad22bbc4f49edc417dac0)) -* **main:** Let find_exercise work with borrows ([347f30bd](https://github.com/rust-lang/rustlings/commit/347f30bd867343c5ace1097e085a1f7e356553f7)) -* **move_semantics4:** - * Remove redundant "instead" (#640) ([cc266d7d](https://github.com/rust-lang/rustlings/commit/cc266d7d80b91e79df3f61984f231b7f1587218e)) - * Small readbility improvement (#617) ([10965920](https://github.com/rust-lang/rustlings/commit/10965920fbdf8a1efc85bed869e55a1787006404)) -* **option2:** Rename uninformative variables (#675) ([b4de6594](https://github.com/rust-lang/rustlings/commit/b4de6594380636817d13c2677ec6f472a964cf43)) -* **quiz3:** Force an answer to Q2 (#672) ([0d894e6f](https://github.com/rust-lang/rustlings/commit/0d894e6ff739943901e1ae8c904582e5c2f843bd)) -* **structs:** Add 5.3 to structs/README (#652) ([6bd791f2](https://github.com/rust-lang/rustlings/commit/6bd791f2f44aa7f0ad926df767f6b1fa8f12a9a9)) -* **structs2:** correct grammar in hint (#663) ([ebdb66c7](https://github.com/rust-lang/rustlings/commit/ebdb66c7bfb6d687a14cc511a559a222e6fc5de4)) -* **structs3:** - * reword heading comment (#664) ([9f3e8c2d](https://github.com/rust-lang/rustlings/commit/9f3e8c2dde645e5264c2d2200e68842b5f47bfa3)) - * add check to prevent naive implementation of is_international ([05a753fe](https://github.com/rust-lang/rustlings/commit/05a753fe6333d36dbee5f68c21dec04eacdc75df)) -* **threads1:** line number correction ([7857b0a6](https://github.com/rust-lang/rustlings/commit/7857b0a689b0847f48d8c14cbd1865e3b812d5ca)) -* **try_from_into:** use trait objects ([2e93a588](https://github.com/rust-lang/rustlings/commit/2e93a588e0abe8badb7eafafb9e7d073c2be5df8)) +- Fix spelling error in main.rs ([91ee27f2](https://github.com/rust-lang/rustlings/commit/91ee27f22bd3797a9db57e5fd430801c170c5db8)) +- typo in default out text ([644c49f1](https://github.com/rust-lang/rustlings/commit/644c49f1e04cbb24e95872b3a52b07d692ae3bc8)) +- **collections:** Naming exercises for vectors and hashmap ([bef39b12](https://github.com/rust-lang/rustlings/commit/bef39b125961310b34b34871e480a82e82af4678)) +- **from_str:** + - Correct typos ([5f7c89f8](https://github.com/rust-lang/rustlings/commit/5f7c89f85db1f33da01911eaa479c3a2d4721678)) + - test for error instead of unwrap/should_panic ([15e71535](https://github.com/rust-lang/rustlings/commit/15e71535f37cfaed36e22eb778728d186e2104ab)) + - use trait objects for from_str ([c3e7b831](https://github.com/rust-lang/rustlings/commit/c3e7b831786c9172ed8bd5d150f3c432f242fba9)) +- **functions3:** improve function argument type (#687) ([a6509cc4](https://github.com/rust-lang/rustlings/commit/a6509cc4d545d8825f01ddf7ee37823b372154dd)) +- **hashmap2:** Update incorrect assertion (#660) ([72aaa15e](https://github.com/rust-lang/rustlings/commit/72aaa15e6ab4b72b3422f1c6356396e20a2a2bb8)) +- **info:** Fix typo (#635) ([cddc1e86](https://github.com/rust-lang/rustlings/commit/cddc1e86e7ec744ee644cc774a4887b1a0ded3e8)) +- **iterators2:** Moved errors out of tests. ([baf4ba17](https://github.com/rust-lang/rustlings/commit/baf4ba175ba6eb92989e3dd54ecbec4bedc9a863), closes [#359](https://github.com/rust-lang/rustlings/issues/359)) +- **iterators3:** Enabled iterators3.rs to run without commented out tests. ([c6712dfc](https://github.com/rust-lang/rustlings/commit/c6712dfccd1a093e590ad22bbc4f49edc417dac0)) +- **main:** Let find_exercise work with borrows ([347f30bd](https://github.com/rust-lang/rustlings/commit/347f30bd867343c5ace1097e085a1f7e356553f7)) +- **move_semantics4:** + - Remove redundant "instead" (#640) ([cc266d7d](https://github.com/rust-lang/rustlings/commit/cc266d7d80b91e79df3f61984f231b7f1587218e)) + - Small readbility improvement (#617) ([10965920](https://github.com/rust-lang/rustlings/commit/10965920fbdf8a1efc85bed869e55a1787006404)) +- **option2:** Rename uninformative variables (#675) ([b4de6594](https://github.com/rust-lang/rustlings/commit/b4de6594380636817d13c2677ec6f472a964cf43)) +- **quiz3:** Force an answer to Q2 (#672) ([0d894e6f](https://github.com/rust-lang/rustlings/commit/0d894e6ff739943901e1ae8c904582e5c2f843bd)) +- **structs:** Add 5.3 to structs/README (#652) ([6bd791f2](https://github.com/rust-lang/rustlings/commit/6bd791f2f44aa7f0ad926df767f6b1fa8f12a9a9)) +- **structs2:** correct grammar in hint (#663) ([ebdb66c7](https://github.com/rust-lang/rustlings/commit/ebdb66c7bfb6d687a14cc511a559a222e6fc5de4)) +- **structs3:** + - reword heading comment (#664) ([9f3e8c2d](https://github.com/rust-lang/rustlings/commit/9f3e8c2dde645e5264c2d2200e68842b5f47bfa3)) + - add check to prevent naive implementation of is_international ([05a753fe](https://github.com/rust-lang/rustlings/commit/05a753fe6333d36dbee5f68c21dec04eacdc75df)) +- **threads1:** line number correction ([7857b0a6](https://github.com/rust-lang/rustlings/commit/7857b0a689b0847f48d8c14cbd1865e3b812d5ca)) +- **try_from_into:** use trait objects ([2e93a588](https://github.com/rust-lang/rustlings/commit/2e93a588e0abe8badb7eafafb9e7d073c2be5df8)) #### Features -* Replace clap with argh ([7928122f](https://github.com/rust-lang/rustlings/commit/7928122fcef9ca7834d988b1ec8ca0687478beeb)) -* Replace emojis when NO_EMOJI env variable present ([8d62a996](https://github.com/rust-lang/rustlings/commit/8d62a9963708dbecd9312e8bcc4b47049c72d155)) -* Added iterators5.rs exercise. ([b29ea17e](https://github.com/rust-lang/rustlings/commit/b29ea17ea94d1862114af2cf5ced0e09c197dc35)) -* **arc1:** Add more details to description and hint (#710) ([81be4044](https://github.com/rust-lang/rustlings/commit/81be40448777fa338ebced3b0bfc1b32d6370313)) -* **cli:** Improve the list command with options, and then some ([8bbe4ff1](https://github.com/rust-lang/rustlings/commit/8bbe4ff1385c5c169c90cd3ff9253f9a91daaf8e)) -* **list:** - * updated progress percentage ([1c6f7e4b](https://github.com/rust-lang/rustlings/commit/1c6f7e4b7b9b3bd36f4da2bb2b69c549cc8bd913)) - * added progress info ([c0e3daac](https://github.com/rust-lang/rustlings/commit/c0e3daacaf6850811df5bc57fa43e0f249d5cfa4)) +- Replace clap with argh ([7928122f](https://github.com/rust-lang/rustlings/commit/7928122fcef9ca7834d988b1ec8ca0687478beeb)) +- Replace emojis when NO_EMOJI env variable present ([8d62a996](https://github.com/rust-lang/rustlings/commit/8d62a9963708dbecd9312e8bcc4b47049c72d155)) +- Added iterators5.rs exercise. ([b29ea17e](https://github.com/rust-lang/rustlings/commit/b29ea17ea94d1862114af2cf5ced0e09c197dc35)) +- **arc1:** Add more details to description and hint (#710) ([81be4044](https://github.com/rust-lang/rustlings/commit/81be40448777fa338ebced3b0bfc1b32d6370313)) +- **cli:** Improve the list command with options, and then some ([8bbe4ff1](https://github.com/rust-lang/rustlings/commit/8bbe4ff1385c5c169c90cd3ff9253f9a91daaf8e)) +- **list:** + - updated progress percentage ([1c6f7e4b](https://github.com/rust-lang/rustlings/commit/1c6f7e4b7b9b3bd36f4da2bb2b69c549cc8bd913)) + - added progress info ([c0e3daac](https://github.com/rust-lang/rustlings/commit/c0e3daacaf6850811df5bc57fa43e0f249d5cfa4)) - - - ## 4.3.0 (2020-12-29) #### Features -* Rewrite default out text ([44d39112](https://github.com/rust-lang/rustlings/commit/44d39112ff122b29c9793fe52e605df1612c6490)) -* match exercise order to book chapters (#541) ([033bf119](https://github.com/rust-lang/rustlings/commit/033bf1198fc8bfce1b570e49da7cde010aa552e3)) -* Crab? (#586) ([fa9f522b](https://github.com/rust-lang/rustlings/commit/fa9f522b7f043d7ef73a39f003a9272dfe72c4f4)) -* add "rustlings list" command ([838f9f30](https://github.com/rust-lang/rustlings/commit/838f9f30083d0b23fd67503dcf0fbeca498e6647)) -* **try_from_into:** remove duplicate annotation ([04f1d079](https://github.com/rust-lang/rustlings/commit/04f1d079aa42a2f49af694bc92c67d731d31a53f)) +- Rewrite default out text ([44d39112](https://github.com/rust-lang/rustlings/commit/44d39112ff122b29c9793fe52e605df1612c6490)) +- match exercise order to book chapters (#541) ([033bf119](https://github.com/rust-lang/rustlings/commit/033bf1198fc8bfce1b570e49da7cde010aa552e3)) +- Crab? (#586) ([fa9f522b](https://github.com/rust-lang/rustlings/commit/fa9f522b7f043d7ef73a39f003a9272dfe72c4f4)) +- add "rustlings list" command ([838f9f30](https://github.com/rust-lang/rustlings/commit/838f9f30083d0b23fd67503dcf0fbeca498e6647)) +- **try_from_into:** remove duplicate annotation ([04f1d079](https://github.com/rust-lang/rustlings/commit/04f1d079aa42a2f49af694bc92c67d731d31a53f)) #### Bug Fixes -* update structs README ([bcf14cf6](https://github.com/rust-lang/rustlings/commit/bcf14cf677adb3a38a3ac3ca53f3c69f61153025)) -* added missing exercises to info.toml ([90cfb6ff](https://github.com/rust-lang/rustlings/commit/90cfb6ff28377531bfc34acb70547bdb13374f6b)) -* gives a bit more context to magic number ([30644c9a](https://github.com/rust-lang/rustlings/commit/30644c9a062b825c0ea89435dc59f0cad86b110e)) -* **functions2:** Change signature to trigger precise error message: (#605) ([0ef95947](https://github.com/rust-lang/rustlings/commit/0ef95947cc30482e63a7045be6cc2fb6f6dcb4cc)) -* **structs1:** Adjust wording (#573) ([9334783d](https://github.com/rust-lang/rustlings/commit/9334783da31d821cc59174fbe8320df95828926c)) -* **try_from_into:** - * type error ([4f4cfcf3](https://github.com/rust-lang/rustlings/commit/4f4cfcf3c36c8718c7c170c9c3a6935e6ef0618c)) - * Update description (#584) ([96347df9](https://github.com/rust-lang/rustlings/commit/96347df9df294f01153b29d9ad4ba361f665c755)) -* **vec1:** Have test compare every element in a and v ([9b6c6293](https://github.com/rust-lang/rustlings/commit/9b6c629397b24b944f484f5b2bbd8144266b5695)) - - +- update structs README ([bcf14cf6](https://github.com/rust-lang/rustlings/commit/bcf14cf677adb3a38a3ac3ca53f3c69f61153025)) +- added missing exercises to info.toml ([90cfb6ff](https://github.com/rust-lang/rustlings/commit/90cfb6ff28377531bfc34acb70547bdb13374f6b)) +- gives a bit more context to magic number ([30644c9a](https://github.com/rust-lang/rustlings/commit/30644c9a062b825c0ea89435dc59f0cad86b110e)) +- **functions2:** Change signature to trigger precise error message: (#605) ([0ef95947](https://github.com/rust-lang/rustlings/commit/0ef95947cc30482e63a7045be6cc2fb6f6dcb4cc)) +- **structs1:** Adjust wording (#573) ([9334783d](https://github.com/rust-lang/rustlings/commit/9334783da31d821cc59174fbe8320df95828926c)) +- **try_from_into:** + - type error ([4f4cfcf3](https://github.com/rust-lang/rustlings/commit/4f4cfcf3c36c8718c7c170c9c3a6935e6ef0618c)) + - Update description (#584) ([96347df9](https://github.com/rust-lang/rustlings/commit/96347df9df294f01153b29d9ad4ba361f665c755)) +- **vec1:** Have test compare every element in a and v ([9b6c6293](https://github.com/rust-lang/rustlings/commit/9b6c629397b24b944f484f5b2bbd8144266b5695)) + ## 4.2.0 (2020-11-07) #### Features -* Add HashMap exercises ([633c00cf](https://github.com/rust-lang/rustlings/commit/633c00cf8071e1e82959a3010452a32f34f29fc9)) -* Add Vec exercises ([0c12fa31](https://github.com/rust-lang/rustlings/commit/0c12fa31c57c03c6287458a0a8aca7afd057baf6)) -* **primitive_types6:** Add a test (#548) ([2b1fb2b7](https://github.com/rust-lang/rustlings/commit/2b1fb2b739bf9ad8d6b7b12af25fee173011bfc4)) -* **try_from_into:** Add tests (#571) ([95ccd926](https://github.com/rust-lang/rustlings/commit/95ccd92616ae79ba287cce221101e0bbe4f68cdc)) +- Add HashMap exercises ([633c00cf](https://github.com/rust-lang/rustlings/commit/633c00cf8071e1e82959a3010452a32f34f29fc9)) +- Add Vec exercises ([0c12fa31](https://github.com/rust-lang/rustlings/commit/0c12fa31c57c03c6287458a0a8aca7afd057baf6)) +- **primitive_types6:** Add a test (#548) ([2b1fb2b7](https://github.com/rust-lang/rustlings/commit/2b1fb2b739bf9ad8d6b7b12af25fee173011bfc4)) +- **try_from_into:** Add tests (#571) ([95ccd926](https://github.com/rust-lang/rustlings/commit/95ccd92616ae79ba287cce221101e0bbe4f68cdc)) #### Bug Fixes -* log error output when inotify limit is exceeded ([d61b4e5a](https://github.com/rust-lang/rustlings/commit/d61b4e5a13b44d72d004082f523fa1b6b24c1aca)) -* more unique temp_file ([5643ef05](https://github.com/rust-lang/rustlings/commit/5643ef05bc81e4a840e9456f4406a769abbe1392)) -* **installation:** Update the MinRustVersion ([21bfb2d4](https://github.com/rust-lang/rustlings/commit/21bfb2d4777429c87d8d3b5fbf0ce66006dcd034)) -* **iterators2:** Update description (#578) ([197d3a3d](https://github.com/rust-lang/rustlings/commit/197d3a3d8961b2465579218a6749b2b2cefa8ddd)) -* **primitive_types6:** - * remove 'unused doc comment' warning ([472d8592](https://github.com/rust-lang/rustlings/commit/472d8592d65c8275332a20dfc269e7ac0d41bc88)) - * missing comma in test ([4fb230da](https://github.com/rust-lang/rustlings/commit/4fb230daf1251444fcf29e085cee222a91f8a37e)) -* **quiz3:** Second test is for odd numbers, not even. (#553) ([18e0bfef](https://github.com/rust-lang/rustlings/commit/18e0bfef1de53071e353ba1ec5837002ff7290e6)) +- log error output when inotify limit is exceeded ([d61b4e5a](https://github.com/rust-lang/rustlings/commit/d61b4e5a13b44d72d004082f523fa1b6b24c1aca)) +- more unique temp_file ([5643ef05](https://github.com/rust-lang/rustlings/commit/5643ef05bc81e4a840e9456f4406a769abbe1392)) +- **installation:** Update the MinRustVersion ([21bfb2d4](https://github.com/rust-lang/rustlings/commit/21bfb2d4777429c87d8d3b5fbf0ce66006dcd034)) +- **iterators2:** Update description (#578) ([197d3a3d](https://github.com/rust-lang/rustlings/commit/197d3a3d8961b2465579218a6749b2b2cefa8ddd)) +- **primitive_types6:** + - remove 'unused doc comment' warning ([472d8592](https://github.com/rust-lang/rustlings/commit/472d8592d65c8275332a20dfc269e7ac0d41bc88)) + - missing comma in test ([4fb230da](https://github.com/rust-lang/rustlings/commit/4fb230daf1251444fcf29e085cee222a91f8a37e)) +- **quiz3:** Second test is for odd numbers, not even. (#553) ([18e0bfef](https://github.com/rust-lang/rustlings/commit/18e0bfef1de53071e353ba1ec5837002ff7290e6)) - ## 4.1.0 (2020-10-05) #### Bug Fixes -* Update rustlings version in Cargo.lock ([1cc40bc9](https://github.com/rust-lang/rustlings/commit/1cc40bc9ce95c23d56f6d91fa1c4deb646231fef)) -* **arc1:** index mod should equal thread count ([b4062ef6](https://github.com/rust-lang/rustlings/commit/b4062ef6993e80dac107c4093ea85166ad3ee0fa)) -* **enums3:** Update Message::ChangeColor to take a tuple. (#457) ([4b6540c7](https://github.com/rust-lang/rustlings/commit/4b6540c71adabad647de8a09e57295e7c7c7d794)) -* **exercises:** adding question mark to quiz2 ([101072ab](https://github.com/rust-lang/rustlings/commit/101072ab9f8c80b40b8b88cb06cbe38aca2481c5)) -* **generics3:** clarify grade change ([47f7672c](https://github.com/rust-lang/rustlings/commit/47f7672c0307732056e7426e81d351f0dd7e22e5)) -* **structs3:** Small adjustment of variable name ([114b54cb](https://github.com/rust-lang/rustlings/commit/114b54cbdb977234b39e5f180d937c14c78bb8b2)) -* **using_as:** Add test so that proper type is returned. (#512) ([3286c5ec](https://github.com/rust-lang/rustlings/commit/3286c5ec19ea5fb7ded81d047da5f8594108a490)) +- Update rustlings version in Cargo.lock ([1cc40bc9](https://github.com/rust-lang/rustlings/commit/1cc40bc9ce95c23d56f6d91fa1c4deb646231fef)) +- **arc1:** index mod should equal thread count ([b4062ef6](https://github.com/rust-lang/rustlings/commit/b4062ef6993e80dac107c4093ea85166ad3ee0fa)) +- **enums3:** Update Message::ChangeColor to take a tuple. (#457) ([4b6540c7](https://github.com/rust-lang/rustlings/commit/4b6540c71adabad647de8a09e57295e7c7c7d794)) +- **exercises:** adding question mark to quiz2 ([101072ab](https://github.com/rust-lang/rustlings/commit/101072ab9f8c80b40b8b88cb06cbe38aca2481c5)) +- **generics3:** clarify grade change ([47f7672c](https://github.com/rust-lang/rustlings/commit/47f7672c0307732056e7426e81d351f0dd7e22e5)) +- **structs3:** Small adjustment of variable name ([114b54cb](https://github.com/rust-lang/rustlings/commit/114b54cbdb977234b39e5f180d937c14c78bb8b2)) +- **using_as:** Add test so that proper type is returned. (#512) ([3286c5ec](https://github.com/rust-lang/rustlings/commit/3286c5ec19ea5fb7ded81d047da5f8594108a490)) #### Features -* Added iterators1.rs exercise ([9642f5a3](https://github.com/rust-lang/rustlings/commit/9642f5a3f686270a4f8f6ba969919ddbbc4f7fdd)) -* Add ability to run rustlings on repl.it (#471) ([8f7b5bd0](https://github.com/rust-lang/rustlings/commit/8f7b5bd00eb83542b959830ef55192d2d76db90a)) -* Add gitpod support (#473) ([4821a8be](https://github.com/rust-lang/rustlings/commit/4821a8be94af4f669042a06ab917934cfacd032f)) -* Remind the user of the hint option (#425) ([816b1f5e](https://github.com/rust-lang/rustlings/commit/816b1f5e85d6cc6e72673813a85d0ada2a8f84af)) -* Remind the user of the hint option (#425) ([9f61db5d](https://github.com/rust-lang/rustlings/commit/9f61db5dbe38538cf06571fcdd5f806e7901e83a)) -* **cli:** Added 'cls' command to 'watch' mode (#474) ([4f2468e1](https://github.com/rust-lang/rustlings/commit/4f2468e14f574a93a2e9b688367b5752ed96ae7b)) -* **try_from_into:** Add insufficient length test (#469) ([523d18b8](https://github.com/rust-lang/rustlings/commit/523d18b873a319f7c09262f44bd40e2fab1830e5)) +- Added iterators1.rs exercise ([9642f5a3](https://github.com/rust-lang/rustlings/commit/9642f5a3f686270a4f8f6ba969919ddbbc4f7fdd)) +- Add ability to run rustlings on repl.it (#471) ([8f7b5bd0](https://github.com/rust-lang/rustlings/commit/8f7b5bd00eb83542b959830ef55192d2d76db90a)) +- Add gitpod support (#473) ([4821a8be](https://github.com/rust-lang/rustlings/commit/4821a8be94af4f669042a06ab917934cfacd032f)) +- Remind the user of the hint option (#425) ([816b1f5e](https://github.com/rust-lang/rustlings/commit/816b1f5e85d6cc6e72673813a85d0ada2a8f84af)) +- Remind the user of the hint option (#425) ([9f61db5d](https://github.com/rust-lang/rustlings/commit/9f61db5dbe38538cf06571fcdd5f806e7901e83a)) +- **cli:** Added 'cls' command to 'watch' mode (#474) ([4f2468e1](https://github.com/rust-lang/rustlings/commit/4f2468e14f574a93a2e9b688367b5752ed96ae7b)) +- **try_from_into:** Add insufficient length test (#469) ([523d18b8](https://github.com/rust-lang/rustlings/commit/523d18b873a319f7c09262f44bd40e2fab1830e5)) - ## 4.0.0 (2020-07-08) #### Breaking Changes -* Add a --nocapture option to display test harnesses' outputs ([8ad5f9bf](https://github.com/rust-lang/rustlings/commit/8ad5f9bf531a4848b1104b7b389a20171624c82f)) -* Rename test to quiz, fixes #244 ([010a0456](https://github.com/rust-lang/rustlings/commit/010a04569282149cea7f7a76fc4d7f4c9f0f08dd)) +- Add a --nocapture option to display test harnesses' outputs ([8ad5f9bf](https://github.com/rust-lang/rustlings/commit/8ad5f9bf531a4848b1104b7b389a20171624c82f)) +- Rename test to quiz, fixes #244 ([010a0456](https://github.com/rust-lang/rustlings/commit/010a04569282149cea7f7a76fc4d7f4c9f0f08dd)) #### Features -* Add traits README ([173bb141](https://github.com/rust-lang/rustlings/commit/173bb14140c5530cbdb59e53ace3991a99d804af)) -* Add box1.rs exercise ([7479a473](https://github.com/rust-lang/rustlings/commit/7479a4737bdcac347322ad0883ca528c8675e720)) -* Rewrite try_from_into (#393) ([763aa6e3](https://github.com/rust-lang/rustlings/commit/763aa6e378a586caae2d8d63755a85eeba227933)) -* Add if2 exercise ([1da84b5f](https://github.com/rust-lang/rustlings/commit/1da84b5f7c489f65bd683c244f13c7d1ee812df0)) -* Added exercise structs3.rs ([b66e2e09](https://github.com/rust-lang/rustlings/commit/b66e2e09622243e086a0f1258dd27e1a2d61c891)) -* Add exercise variables6 covering const (#352) ([5999acd2](https://github.com/rust-lang/rustlings/commit/5999acd24a4f203292be36e0fd18d385887ec481)) +- Add traits README ([173bb141](https://github.com/rust-lang/rustlings/commit/173bb14140c5530cbdb59e53ace3991a99d804af)) +- Add box1.rs exercise ([7479a473](https://github.com/rust-lang/rustlings/commit/7479a4737bdcac347322ad0883ca528c8675e720)) +- Rewrite try_from_into (#393) ([763aa6e3](https://github.com/rust-lang/rustlings/commit/763aa6e378a586caae2d8d63755a85eeba227933)) +- Add if2 exercise ([1da84b5f](https://github.com/rust-lang/rustlings/commit/1da84b5f7c489f65bd683c244f13c7d1ee812df0)) +- Added exercise structs3.rs ([b66e2e09](https://github.com/rust-lang/rustlings/commit/b66e2e09622243e086a0f1258dd27e1a2d61c891)) +- Add exercise variables6 covering const (#352) ([5999acd2](https://github.com/rust-lang/rustlings/commit/5999acd24a4f203292be36e0fd18d385887ec481)) #### Bug Fixes -* Change then to than ([ddd98ad7](https://github.com/rust-lang/rustlings/commit/ddd98ad75d3668fbb10eff74374148aa5ed2344d)) -* rename quiz1 to tests1 in info (#420) ([0dd1c6ca](https://github.com/rust-lang/rustlings/commit/0dd1c6ca6b389789e0972aa955fe17aa15c95f29)) -* fix quiz naming inconsistency (#421) ([5563adbb](https://github.com/rust-lang/rustlings/commit/5563adbb890587fc48fbbc9c4028642687f1e85b)) -* confine the user further in variable exercises ([06ef4cc6](https://github.com/rust-lang/rustlings/commit/06ef4cc654e75d22a526812919ee49b8956280bf)) -* update iterator and macro text for typos and clarity ([95900828](https://github.com/rust-lang/rustlings/commit/959008284834bece0196a01e17ac69a7e3590116)) -* update generics2 closes #362 ([964c974a](https://github.com/rust-lang/rustlings/commit/964c974a0274199d755073b917c2bc5da0c9b4f1)) -* confusing comment in conversions/try_from_into.rs ([c9e4f2cf](https://github.com/rust-lang/rustlings/commit/c9e4f2cfb4c48d0b7451263cfb43b9426438122d)) -* **arc1:** Passively introduce attributes (#429) ([113cdae2](https://github.com/rust-lang/rustlings/commit/113cdae2d4e4c55905e8056ad326ede7fd7de356)) -* **box1:** fix comment typo (#426) ([bb2ca251](https://github.com/rust-lang/rustlings/commit/bb2ca251106b27a7272d9a30872904dd1376654c)) -* **errorsn:** Try harder to confine the user. (#388) ([2b20c8a0](https://github.com/rust-lang/rustlings/commit/2b20c8a0f5774d07c58d110d75879f33fc6273b5)) -* **from_into.rs:** typo ([a901499e](https://github.com/rust-lang/rustlings/commit/a901499ededd3ce1995164700514fe4e9a0373ea)) -* **generics2:** Guide students to the answer (#430) ([e6bd8021](https://github.com/rust-lang/rustlings/commit/e6bd8021d9a7dd06feebc30c9d5f953901d7b419)) -* **installation:** - * Provide a backup git reference when tag can't be curl ([9e4fb100](https://github.com/rust-lang/rustlings/commit/9e4fb1009f1c9e3433915c03e22c2af422e5c5fe)) - * Check if python is available while checking for git,rustc and cargo ([9cfb617d](https://github.com/rust-lang/rustlings/commit/9cfb617d5b0451b4b51644a1298965390cda9884)) -* **option1:** - * Don't add only zeros to the numbers array ([cce6a442](https://github.com/rust-lang/rustlings/commit/cce6a4427718724a9096800754cd3abeca6a1580)) - * Add cast to usize, as it is confusing in the context of an exercise about Option ([f6cffc7e](https://github.com/rust-lang/rustlings/commit/f6cffc7e487b42f15a6f958e49704c93a8d4465b)) -* **option2:** Add TODO to comments (#400) ([10967bce](https://github.com/rust-lang/rustlings/commit/10967bce57682812dc0891a9f9757da1a9d87404)) -* **options1:** Add hint about Array Initialization (#389) ([9f75554f](https://github.com/rust-lang/rustlings/commit/9f75554f2a30295996f03f0160b98c0458305502)) -* **test2:** name of type String and &str (#394) ([d6c0a688](https://github.com/rust-lang/rustlings/commit/d6c0a688e6a96f93ad60d540d4b326f342fc0d45)) -* **variables6:** minor typo (#419) ([524e17df](https://github.com/rust-lang/rustlings/commit/524e17df10db95f7b90a0f75cc8997182a8a4094)) - - +- Change then to than ([ddd98ad7](https://github.com/rust-lang/rustlings/commit/ddd98ad75d3668fbb10eff74374148aa5ed2344d)) +- rename quiz1 to tests1 in info (#420) ([0dd1c6ca](https://github.com/rust-lang/rustlings/commit/0dd1c6ca6b389789e0972aa955fe17aa15c95f29)) +- fix quiz naming inconsistency (#421) ([5563adbb](https://github.com/rust-lang/rustlings/commit/5563adbb890587fc48fbbc9c4028642687f1e85b)) +- confine the user further in variable exercises ([06ef4cc6](https://github.com/rust-lang/rustlings/commit/06ef4cc654e75d22a526812919ee49b8956280bf)) +- update iterator and macro text for typos and clarity ([95900828](https://github.com/rust-lang/rustlings/commit/959008284834bece0196a01e17ac69a7e3590116)) +- update generics2 closes #362 ([964c974a](https://github.com/rust-lang/rustlings/commit/964c974a0274199d755073b917c2bc5da0c9b4f1)) +- confusing comment in conversions/try_from_into.rs ([c9e4f2cf](https://github.com/rust-lang/rustlings/commit/c9e4f2cfb4c48d0b7451263cfb43b9426438122d)) +- **arc1:** Passively introduce attributes (#429) ([113cdae2](https://github.com/rust-lang/rustlings/commit/113cdae2d4e4c55905e8056ad326ede7fd7de356)) +- **box1:** fix comment typo (#426) ([bb2ca251](https://github.com/rust-lang/rustlings/commit/bb2ca251106b27a7272d9a30872904dd1376654c)) +- **errorsn:** Try harder to confine the user. (#388) ([2b20c8a0](https://github.com/rust-lang/rustlings/commit/2b20c8a0f5774d07c58d110d75879f33fc6273b5)) +- **from_into.rs:** typo ([a901499e](https://github.com/rust-lang/rustlings/commit/a901499ededd3ce1995164700514fe4e9a0373ea)) +- **generics2:** Guide students to the answer (#430) ([e6bd8021](https://github.com/rust-lang/rustlings/commit/e6bd8021d9a7dd06feebc30c9d5f953901d7b419)) +- **installation:** + - Provide a backup git reference when tag can't be curl ([9e4fb100](https://github.com/rust-lang/rustlings/commit/9e4fb1009f1c9e3433915c03e22c2af422e5c5fe)) + - Check if python is available while checking for git,rustc and cargo ([9cfb617d](https://github.com/rust-lang/rustlings/commit/9cfb617d5b0451b4b51644a1298965390cda9884)) +- **option1:** + - Don't add only zeros to the numbers array ([cce6a442](https://github.com/rust-lang/rustlings/commit/cce6a4427718724a9096800754cd3abeca6a1580)) + - Add cast to usize, as it is confusing in the context of an exercise about Option ([f6cffc7e](https://github.com/rust-lang/rustlings/commit/f6cffc7e487b42f15a6f958e49704c93a8d4465b)) +- **option2:** Add TODO to comments (#400) ([10967bce](https://github.com/rust-lang/rustlings/commit/10967bce57682812dc0891a9f9757da1a9d87404)) +- **options1:** Add hint about Array Initialization (#389) ([9f75554f](https://github.com/rust-lang/rustlings/commit/9f75554f2a30295996f03f0160b98c0458305502)) +- **test2:** name of type String and &str (#394) ([d6c0a688](https://github.com/rust-lang/rustlings/commit/d6c0a688e6a96f93ad60d540d4b326f342fc0d45)) +- **variables6:** minor typo (#419) ([524e17df](https://github.com/rust-lang/rustlings/commit/524e17df10db95f7b90a0f75cc8997182a8a4094)) + ## 3.0.0 (2020-04-11) #### Breaking Changes -* make "compile" exercises print output (#278) ([3b6d5c](https://github.com/fmoko/rustlings/commit/3b6d5c3aaa27a242a832799eb66e96897d26fde3)) +- make "compile" exercises print output (#278) ([3b6d5c](https://github.com/fmoko/rustlings/commit/3b6d5c3aaa27a242a832799eb66e96897d26fde3)) #### Bug Fixes -* **primitive_types:** revert primitive_types4 (#296) ([b3a3351e](https://github.com/rust-lang/rustlings/commit/b3a3351e8e6a0bdee07077d7b0382953821649ae)) -* **run:** compile clippy exercise files (#295) ([3ab084a4](https://github.com/rust-lang/rustlings/commit/3ab084a421c0f140ae83bf1fc3f47b39342e7373)) -* **conversions:** - * add additional test to meet exercise rules (#284) ([bc22ec3](https://github.com/fmoko/rustlings/commit/bc22ec382f843347333ef1301fc1bad773657f38)) - * remove duplicate not done comment (#292) ([dab90f](https://github.com/fmoko/rustlings/commit/dab90f7b91a6000fe874e3d664f244048e5fa342)) -* don't hardcode documentation version for traits (#288) ([30e6af](https://github.com/fmoko/rustlings/commit/30e6af60690c326fb5d3a9b7335f35c69c09137d)) +- **primitive_types:** revert primitive_types4 (#296) ([b3a3351e](https://github.com/rust-lang/rustlings/commit/b3a3351e8e6a0bdee07077d7b0382953821649ae)) +- **run:** compile clippy exercise files (#295) ([3ab084a4](https://github.com/rust-lang/rustlings/commit/3ab084a421c0f140ae83bf1fc3f47b39342e7373)) +- **conversions:** + - add additional test to meet exercise rules (#284) ([bc22ec3](https://github.com/fmoko/rustlings/commit/bc22ec382f843347333ef1301fc1bad773657f38)) + - remove duplicate not done comment (#292) ([dab90f](https://github.com/fmoko/rustlings/commit/dab90f7b91a6000fe874e3d664f244048e5fa342)) +- don't hardcode documentation version for traits (#288) ([30e6af](https://github.com/fmoko/rustlings/commit/30e6af60690c326fb5d3a9b7335f35c69c09137d)) #### Features -* add Option2 exercise (#290) ([86b5c08b](https://github.com/rust-lang/rustlings/commit/86b5c08b9bea1576127a7c5f599f5752072c087d)) -* add exercise for option (#282) ([135e5d47](https://github.com/rust-lang/rustlings/commit/135e5d47a7c395aece6f6022117fb20c82f2d3d4)) -* add new exercises for generics (#280) ([76be5e4e](https://github.com/rust-lang/rustlings/commit/76be5e4e991160f5fd9093f03ee2ba260e8f7229)) -* **ci:** add buildkite config ([b049fa2c](https://github.com/rust-lang/rustlings/commit/b049fa2c84dba0f0c8906ac44e28fd45fba51a71)) +- add Option2 exercise (#290) ([86b5c08b](https://github.com/rust-lang/rustlings/commit/86b5c08b9bea1576127a7c5f599f5752072c087d)) +- add exercise for option (#282) ([135e5d47](https://github.com/rust-lang/rustlings/commit/135e5d47a7c395aece6f6022117fb20c82f2d3d4)) +- add new exercises for generics (#280) ([76be5e4e](https://github.com/rust-lang/rustlings/commit/76be5e4e991160f5fd9093f03ee2ba260e8f7229)) +- **ci:** add buildkite config ([b049fa2c](https://github.com/rust-lang/rustlings/commit/b049fa2c84dba0f0c8906ac44e28fd45fba51a71)) - ### 2.2.1 (2020-02-27) #### Bug Fixes -* Re-add cloning the repo to install scripts ([3d9b03c5](https://github.com/rust-lang/rustlings/commit/3d9b03c52b8dc51b140757f6fd25ad87b5782ef5)) +- Re-add cloning the repo to install scripts ([3d9b03c5](https://github.com/rust-lang/rustlings/commit/3d9b03c52b8dc51b140757f6fd25ad87b5782ef5)) #### Features -* Add clippy lints (#269) ([1e2fd9c9](https://github.com/rust-lang/rustlings/commit/1e2fd9c92f8cd6e389525ca1a999fca4c90b5921)) +- Add clippy lints (#269) ([1e2fd9c9](https://github.com/rust-lang/rustlings/commit/1e2fd9c92f8cd6e389525ca1a999fca4c90b5921)) - ## 2.2.0 (2020-02-25) - #### Bug Fixes -* Update deps to version compatable with aarch64-pc-windows (#263) ([19a93428](https://github.com/rust-lang/rustlings/commit/19a93428b3c73d994292671f829bdc8e5b7b3401)) -* **docs:** - * Added a necessary step to Windows installation process (#242) ([3906efcd](https://github.com/rust-lang/rustlings/commit/3906efcd52a004047b460ed548037093de3f523f)) - * Fixed mangled sentence from book; edited for clarity (#266) ([ade52ff](https://github.com/rust-lang/rustlings/commit/ade52ffb739987287ddd5705944c8777705faed9)) - * Updated iterators readme to account for iterators4 exercise (#273) ([bec8e3a](https://github.com/rust-lang/rustlings/commit/bec8e3a644cbd88db1c73ea5f1d8a364f4a34016)) -* **installation:** make fatal errors more obvious (#272) ([17d0951e](https://github.com/rust-lang/rustlings/commit/17d0951e66fda8e11b204d5c4c41a0d5e22e78f7)) -* **iterators2:** - * Remove reference to missing iterators2.rs (#245) ([419f7797](https://github.com/rust-lang/rustlings/commit/419f7797f294e4ce6a2b883199731b5bde77d262)) -* **as_ref_mut:** Enable a test and improve per clippy's suggestion (#256) ([dfdf809](https://github.com/rust-lang/rustlings/commit/dfdf8093ebbd4145864995627b812780de52f902)) -* **tests1:** - * Change test command ([fe10e06c](https://github.com/rust-lang/rustlings/commit/fe10e06c3733ddb4a21e90d09bf79bfe618e97ce) - * Correct test command in tests1.rs comment (#263) ([39fa7ae](https://github.com/rust-lang/rustlings/commit/39fa7ae8b70ad468da49b06f11b2383135a63bcf)) +- Update deps to version compatible with aarch64-pc-windows (#263) ([19a93428](https://github.com/rust-lang/rustlings/commit/19a93428b3c73d994292671f829bdc8e5b7b3401)) +- **docs:** + - Added a necessary step to Windows installation process (#242) ([3906efcd](https://github.com/rust-lang/rustlings/commit/3906efcd52a004047b460ed548037093de3f523f)) + - Fixed mangled sentence from book; edited for clarity (#266) ([ade52ff](https://github.com/rust-lang/rustlings/commit/ade52ffb739987287ddd5705944c8777705faed9)) + - Updated iterators readme to account for iterators4 exercise (#273) ([bec8e3a](https://github.com/rust-lang/rustlings/commit/bec8e3a644cbd88db1c73ea5f1d8a364f4a34016)) +- **installation:** make fatal errors more obvious (#272) ([17d0951e](https://github.com/rust-lang/rustlings/commit/17d0951e66fda8e11b204d5c4c41a0d5e22e78f7)) +- **iterators2:** + - Remove reference to missing iterators2.rs (#245) ([419f7797](https://github.com/rust-lang/rustlings/commit/419f7797f294e4ce6a2b883199731b5bde77d262)) +- **as_ref_mut:** Enable a test and improve per clippy's suggestion (#256) ([dfdf809](https://github.com/rust-lang/rustlings/commit/dfdf8093ebbd4145864995627b812780de52f902)) +- **tests1:** + - Change test command ([fe10e06c](https://github.com/rust-lang/rustlings/commit/fe10e06c3733ddb4a21e90d09bf79bfe618e97ce) + - Correct test command in tests1.rs comment (#263) ([39fa7ae](https://github.com/rust-lang/rustlings/commit/39fa7ae8b70ad468da49b06f11b2383135a63bcf)) #### Features -* Add variables5.rs exercise (#264) ([0c73609e](https://github.com/rust-lang/rustlings/commit/0c73609e6f2311295e95d6f96f8c747cfc4cba03)) -* Show a completion message when watching (#253) ([d25ee55a](https://github.com/rust-lang/rustlings/commit/d25ee55a3205882d35782e370af855051b39c58c)) -* Add type conversion and parsing exercises (#249) ([0c85dc11](https://github.com/rust-lang/rustlings/commit/0c85dc1193978b5165491b99cc4922caf8d14a65)) -* Created consistent money unit (#258) ([fd57f8f](https://github.com/rust-lang/rustlings/commit/fd57f8f2c1da2af8ddbebbccec214e6f40f4dbab)) -* Enable test for exercise test4 (#276) ([8b971ff](https://github.com/rust-lang/rustlings/commit/8b971ffab6079a706ac925f5917f987932b55c07)) -* Added traits exercises (#274 but specifically #216, which originally added - this :heart:) ([b559cdd](https://github.com/rust-lang/rustlings/commit/b559cdd73f32c0d0cfc1feda39f82b3e3583df17)) +- Add variables5.rs exercise (#264) ([0c73609e](https://github.com/rust-lang/rustlings/commit/0c73609e6f2311295e95d6f96f8c747cfc4cba03)) +- Show a completion message when watching (#253) ([d25ee55a](https://github.com/rust-lang/rustlings/commit/d25ee55a3205882d35782e370af855051b39c58c)) +- Add type conversion and parsing exercises (#249) ([0c85dc11](https://github.com/rust-lang/rustlings/commit/0c85dc1193978b5165491b99cc4922caf8d14a65)) +- Created consistent money unit (#258) ([fd57f8f](https://github.com/rust-lang/rustlings/commit/fd57f8f2c1da2af8ddbebbccec214e6f40f4dbab)) +- Enable test for exercise test4 (#276) ([8b971ff](https://github.com/rust-lang/rustlings/commit/8b971ffab6079a706ac925f5917f987932b55c07)) +- Added traits exercises (#274 but specifically #216, which originally added + this :heart:) ([b559cdd](https://github.com/rust-lang/rustlings/commit/b559cdd73f32c0d0cfc1feda39f82b3e3583df17)) - - ## 2.1.0 (2019-11-27) #### Bug Fixes -* add line numbers in several exercises and hints ([b565c4d3](https://github.com/rust-lang/rustlings/commit/b565c4d3e74e8e110bef201a082fa1302722a7c3)) -* **arc1:** Fix some words in the comment ([c42c3b21](https://github.com/rust-lang/rustlings/commit/c42c3b2101df9164c8cd7bb344def921e5ba3e61)) -* **enums:** Add link to chapter on pattern syntax (#242) ([615ce327](https://github.com/rust-lang/rustlings/commit/615ce3279800c56d89f19d218ccb7ef576624feb)) -* **primitive_types4:** - * update outdated hint ([4c5189df](https://github.com/rust-lang/rustlings/commit/4c5189df2bdd9a231f6b2611919ba5aa14da0d3f)) - * update outdated comment ([ded2c034](https://github.com/rust-lang/rustlings/commit/ded2c034ba93fa1e3c2c2ea16b83abc1a57265e8)) -* **strings2:** update line number in hint ([a09f684f](https://github.com/rust-lang/rustlings/commit/a09f684f05c58d239a6fc59ec5f81c2533e8b820)) -* **variables1:** Correct wrong word in comment ([fda5a470](https://github.com/rust-lang/rustlings/commit/fda5a47069e0954f16a04e8e50945e03becb71a5)) +- add line numbers in several exercises and hints ([b565c4d3](https://github.com/rust-lang/rustlings/commit/b565c4d3e74e8e110bef201a082fa1302722a7c3)) +- **arc1:** Fix some words in the comment ([c42c3b21](https://github.com/rust-lang/rustlings/commit/c42c3b2101df9164c8cd7bb344def921e5ba3e61)) +- **enums:** Add link to chapter on pattern syntax (#242) ([615ce327](https://github.com/rust-lang/rustlings/commit/615ce3279800c56d89f19d218ccb7ef576624feb)) +- **primitive_types4:** + - update outdated hint ([4c5189df](https://github.com/rust-lang/rustlings/commit/4c5189df2bdd9a231f6b2611919ba5aa14da0d3f)) + - update outdated comment ([ded2c034](https://github.com/rust-lang/rustlings/commit/ded2c034ba93fa1e3c2c2ea16b83abc1a57265e8)) +- **strings2:** update line number in hint ([a09f684f](https://github.com/rust-lang/rustlings/commit/a09f684f05c58d239a6fc59ec5f81c2533e8b820)) +- **variables1:** Correct wrong word in comment ([fda5a470](https://github.com/rust-lang/rustlings/commit/fda5a47069e0954f16a04e8e50945e03becb71a5)) #### Features -* **watch:** show hint while watching ([8143d57b](https://github.com/rust-lang/rustlings/commit/8143d57b4e88c51341dd4a18a14c536042cc009c)) +- **watch:** show hint while watching ([8143d57b](https://github.com/rust-lang/rustlings/commit/8143d57b4e88c51341dd4a18a14c536042cc009c)) - ## 2.0.0 (2019-11-12) #### Bug Fixes -* **default:** Clarify the installation procedure ([c371b853](https://github.com/rust-lang/rustlings/commit/c371b853afa08947ddeebec0edd074b171eeaae0)) -* **info:** Fix trailing newlines for hints ([795b6e34](https://github.com/rust-lang/rustlings/commit/795b6e348094a898e9227a14f6232f7bb94c8d31)) -* **run:** make `run` never prompt ([4b265465](https://github.com/rust-lang/rustlings/commit/4b26546589f7d2b50455429482cf1f386ceae8b3)) +- **default:** Clarify the installation procedure ([c371b853](https://github.com/rust-lang/rustlings/commit/c371b853afa08947ddeebec0edd074b171eeaae0)) +- **info:** Fix trailing newlines for hints ([795b6e34](https://github.com/rust-lang/rustlings/commit/795b6e348094a898e9227a14f6232f7bb94c8d31)) +- **run:** make `run` never prompt ([4b265465](https://github.com/rust-lang/rustlings/commit/4b26546589f7d2b50455429482cf1f386ceae8b3)) #### Breaking Changes -* Refactor hint system ([9bdb0a12](https://github.com/rust-lang/rustlings/commit/9bdb0a12e45a8e9f9f6a4bd4a9c172c5376c7f60)) -* improve `watch` execution mode ([2cdd6129](https://github.com/rust-lang/rustlings/commit/2cdd61294f0d9a53775ee24ad76435bec8a21e60)) -* Index exercises by name ([627cdc07](https://github.com/rust-lang/rustlings/commit/627cdc07d07dfe6a740e885e0ddf6900e7ec336b)) -* **run:** makes `run` never prompt ([4b265465](https://github.com/rust-lang/rustlings/commit/4b26546589f7d2b50455429482cf1f386ceae8b3)) +- Refactor hint system ([9bdb0a12](https://github.com/rust-lang/rustlings/commit/9bdb0a12e45a8e9f9f6a4bd4a9c172c5376c7f60)) +- improve `watch` execution mode ([2cdd6129](https://github.com/rust-lang/rustlings/commit/2cdd61294f0d9a53775ee24ad76435bec8a21e60)) +- Index exercises by name ([627cdc07](https://github.com/rust-lang/rustlings/commit/627cdc07d07dfe6a740e885e0ddf6900e7ec336b)) +- **run:** makes `run` never prompt ([4b265465](https://github.com/rust-lang/rustlings/commit/4b26546589f7d2b50455429482cf1f386ceae8b3)) #### Features -* **cli:** check for rustc before doing anything ([36a033b8](https://github.com/rust-lang/rustlings/commit/36a033b87a6549c1e5639c908bf7381c84f4f425)) -* **hint:** Add test for hint ([ce9fa6eb](https://github.com/rust-lang/rustlings/commit/ce9fa6ebbfdc3e7585d488d9409797285708316f)) +- **cli:** check for rustc before doing anything ([36a033b8](https://github.com/rust-lang/rustlings/commit/36a033b87a6549c1e5639c908bf7381c84f4f425)) +- **hint:** Add test for hint ([ce9fa6eb](https://github.com/rust-lang/rustlings/commit/ce9fa6ebbfdc3e7585d488d9409797285708316f)) - ### 1.5.1 (2019-11-11) #### Bug Fixes -* **errors3:** Update hint ([dcfb427b](https://github.com/rust-lang/rustlings/commit/dcfb427b09585f0193f0a294443fdf99f11c64cb), closes [#185](https://github.com/rust-lang/rustlings/issues/185)) -* **if1:** Remove `return` reference ([ad03d180](https://github.com/rust-lang/rustlings/commit/ad03d180c9311c0093e56a3531eec1a9a70cdb45)) -* **strings:** Move Strings before Structs ([6dcecb38](https://github.com/rust-lang/rustlings/commit/6dcecb38a4435593beb87c8e12d6314143631482), closes [#204](https://github.com/rust-lang/rustlings/issues/204)) -* **structs1:** Remove misleading comment ([f72e5a8f](https://github.com/rust-lang/rustlings/commit/f72e5a8f05568dde04eaeac10b9a69872f21cb37)) -* **threads:** Move Threads behind SLT ([fbe91a67](https://github.com/rust-lang/rustlings/commit/fbe91a67a482bfe64cbcdd58d06ba830a0f39da3), closes [#205](https://github.com/rust-lang/rustlings/issues/205)) -* **watch:** clear screen before each `verify()` ([3aff590](https://github.com/rust-lang/rustlings/commit/3aff59085586c24196a547c2693adbdcf4432648)) +- **errors3:** Update hint ([dcfb427b](https://github.com/rust-lang/rustlings/commit/dcfb427b09585f0193f0a294443fdf99f11c64cb), closes [#185](https://github.com/rust-lang/rustlings/issues/185)) +- **if1:** Remove `return` reference ([ad03d180](https://github.com/rust-lang/rustlings/commit/ad03d180c9311c0093e56a3531eec1a9a70cdb45)) +- **strings:** Move Strings before Structs ([6dcecb38](https://github.com/rust-lang/rustlings/commit/6dcecb38a4435593beb87c8e12d6314143631482), closes [#204](https://github.com/rust-lang/rustlings/issues/204)) +- **structs1:** Remove misleading comment ([f72e5a8f](https://github.com/rust-lang/rustlings/commit/f72e5a8f05568dde04eaeac10b9a69872f21cb37)) +- **threads:** Move Threads behind SLT ([fbe91a67](https://github.com/rust-lang/rustlings/commit/fbe91a67a482bfe64cbcdd58d06ba830a0f39da3), closes [#205](https://github.com/rust-lang/rustlings/issues/205)) +- **watch:** clear screen before each `verify()` ([3aff590](https://github.com/rust-lang/rustlings/commit/3aff59085586c24196a547c2693adbdcf4432648)) - ## 1.5.0 (2019-11-09) #### Bug Fixes -* **test1:** Rewrite logic ([79a56942](https://github.com/rust-lang/rustlings/commit/79a569422c8309cfc9e4aed25bf4ab3b3859996b)) -* **installation:** Fix rustlings installation check ([7a252c47](https://github.com/rust-lang/rustlings/commit/7a252c475551486efb52f949b8af55803b700bc6)) -* **iterators:** Rename iterator3.rs ([433d2115](https://github.com/rust-lang/rustlings/commit/433d2115bc1c04b6d34a335a18c9a8f3e2672bc6)) -* **iterators2:** Remove syntax resulting in misleading error message ([4cde8664](https://github.com/rust-lang/rustlings/commit/4cde86643e12db162a66e62f23b78962986046ac)) -* **option1:** - * Fix arguments passed to assert! macro (#222) ([4c2cf6da](https://github.com/rust-lang/rustlings/commit/4c2cf6da755efe02725e05ecc3a303304c10a6da)) - * Fix arguments passed to assert! macro ([ead4f7af](https://github.com/rust-lang/rustlings/commit/ead4f7af9e10e53418efdde5c359159347282afd)) - * Add test for prematurely passing exercise ([a750e4a1](https://github.com/rust-lang/rustlings/commit/a750e4a1a3006227292bb17d57d78ce84da6bfc6)) -* **primitive_types4:** Fail on a slice covering the wrong area ([5b1e673c](https://github.com/rust-lang/rustlings/commit/5b1e673cec1658afc4ebbbc800213847804facf5)) -* **readme:** http to https ([70946b85](https://github.com/rust-lang/rustlings/commit/70946b85e536e80e70ed9505cb650ca0a3a1fbb5)) -* **test1:** - * Swap assertion parameter order ([4086d463](https://github.com/rust-lang/rustlings/commit/4086d463a981e81d97781851d17db2ced290f446)) - * renamed function name to snake case closes #180 ([89d5186c](https://github.com/rust-lang/rustlings/commit/89d5186c0dae8135ecabf90ee8bb35949bc2d29b)) +- **test1:** Rewrite logic ([79a56942](https://github.com/rust-lang/rustlings/commit/79a569422c8309cfc9e4aed25bf4ab3b3859996b)) +- **installation:** Fix rustlings installation check ([7a252c47](https://github.com/rust-lang/rustlings/commit/7a252c475551486efb52f949b8af55803b700bc6)) +- **iterators:** Rename iterator3.rs ([433d2115](https://github.com/rust-lang/rustlings/commit/433d2115bc1c04b6d34a335a18c9a8f3e2672bc6)) +- **iterators2:** Remove syntax resulting in misleading error message ([4cde8664](https://github.com/rust-lang/rustlings/commit/4cde86643e12db162a66e62f23b78962986046ac)) +- **option1:** + - Fix arguments passed to assert! macro (#222) ([4c2cf6da](https://github.com/rust-lang/rustlings/commit/4c2cf6da755efe02725e05ecc3a303304c10a6da)) + - Fix arguments passed to assert! macro ([ead4f7af](https://github.com/rust-lang/rustlings/commit/ead4f7af9e10e53418efdde5c359159347282afd)) + - Add test for prematurely passing exercise ([a750e4a1](https://github.com/rust-lang/rustlings/commit/a750e4a1a3006227292bb17d57d78ce84da6bfc6)) +- **primitive_types4:** Fail on a slice covering the wrong area ([5b1e673c](https://github.com/rust-lang/rustlings/commit/5b1e673cec1658afc4ebbbc800213847804facf5)) +- **readme:** http to https ([70946b85](https://github.com/rust-lang/rustlings/commit/70946b85e536e80e70ed9505cb650ca0a3a1fbb5)) +- **test1:** + - Swap assertion parameter order ([4086d463](https://github.com/rust-lang/rustlings/commit/4086d463a981e81d97781851d17db2ced290f446)) + - renamed function name to snake case closes #180 ([89d5186c](https://github.com/rust-lang/rustlings/commit/89d5186c0dae8135ecabf90ee8bb35949bc2d29b)) #### Features -* Add enums exercises ([dc150321](https://github.com/rust-lang/rustlings/commit/dc15032112fc485226a573a18139e5ce928b1755)) -* Added exercise for struct update syntax ([1c4c8764](https://github.com/rust-lang/rustlings/commit/1c4c8764ed118740cd4cee73272ddc6cceb9d959)) -* **iterators2:** adds iterators2 exercise including config ([9288fccf](https://github.com/rust-lang/rustlings/commit/9288fccf07a2c5043b76d0fd6491e4cf72d76031)) +- Add enums exercises ([dc150321](https://github.com/rust-lang/rustlings/commit/dc15032112fc485226a573a18139e5ce928b1755)) +- Added exercise for struct update syntax ([1c4c8764](https://github.com/rust-lang/rustlings/commit/1c4c8764ed118740cd4cee73272ddc6cceb9d959)) +- **iterators2:** adds iterators2 exercise including config ([9288fccf](https://github.com/rust-lang/rustlings/commit/9288fccf07a2c5043b76d0fd6491e4cf72d76031)) - ### 1.4.1 (2019-08-13) - #### Bug Fixes -* **iterators2:** Remove syntax resulting in misleading error message ([4cde8664](https://github.com/rust-lang/rustlings/commit/4cde86643e12db162a66e62f23b78962986046ac)) -* **option1:** Add test for prematurely passing exercise ([a750e4a1](https://github.com/rust-lang/rustlings/commit/a750e4a1a3006227292bb17d57d78ce84da6bfc6)) -* **test1:** Swap assertion parameter order ([4086d463](https://github.com/rust-lang/rustlings/commit/4086d463a981e81d97781851d17db2ced290f446)) - - +- **iterators2:** Remove syntax resulting in misleading error message ([4cde8664](https://github.com/rust-lang/rustlings/commit/4cde86643e12db162a66e62f23b78962986046ac)) +- **option1:** Add test for prematurely passing exercise ([a750e4a1](https://github.com/rust-lang/rustlings/commit/a750e4a1a3006227292bb17d57d78ce84da6bfc6)) +- **test1:** Swap assertion parameter order ([4086d463](https://github.com/rust-lang/rustlings/commit/4086d463a981e81d97781851d17db2ced290f446)) - ## 1.4.0 (2019-07-13) #### Bug Fixes -* **installation:** Fix rustlings installation check ([7a252c47](https://github.com/rust-lang/rustlings/commit/7a252c475551486efb52f949b8af55803b700bc6)) -* **iterators:** Rename iterator3.rs ([433d2115](https://github.com/rust-lang/rustlings/commit/433d2115bc1c04b6d34a335a18c9a8f3e2672bc6)) -* **readme:** http to https ([70946b85](https://github.com/rust-lang/rustlings/commit/70946b85e536e80e70ed9505cb650ca0a3a1fbb5)) -* **test1:** renamed function name to snake case ([89d5186c](https://github.com/rust-lang/rustlings/commit/89d5186c0dae8135ecabf90ee8bb35949bc2d29b)) -* **cli:** Check if changed exercise file exists before calling verify ([ba85ca3](https://github.com/rust-lang/rustlings/commit/ba85ca32c4cfc61de46851ab89f9c58a28f33c88)) -* **structs1:** Fix the irrefutable let pattern warning ([cc6a141](https://github.com/rust-lang/rustlings/commit/cc6a14104d7c034eadc98297eaaa972d09c50b1f)) +- **installation:** Fix rustlings installation check ([7a252c47](https://github.com/rust-lang/rustlings/commit/7a252c475551486efb52f949b8af55803b700bc6)) +- **iterators:** Rename iterator3.rs ([433d2115](https://github.com/rust-lang/rustlings/commit/433d2115bc1c04b6d34a335a18c9a8f3e2672bc6)) +- **readme:** http to https ([70946b85](https://github.com/rust-lang/rustlings/commit/70946b85e536e80e70ed9505cb650ca0a3a1fbb5)) +- **test1:** renamed function name to snake case ([89d5186c](https://github.com/rust-lang/rustlings/commit/89d5186c0dae8135ecabf90ee8bb35949bc2d29b)) +- **cli:** Check if changed exercise file exists before calling verify ([ba85ca3](https://github.com/rust-lang/rustlings/commit/ba85ca32c4cfc61de46851ab89f9c58a28f33c88)) +- **structs1:** Fix the irrefutable let pattern warning ([cc6a141](https://github.com/rust-lang/rustlings/commit/cc6a14104d7c034eadc98297eaaa972d09c50b1f)) #### Features -* **changelog:** Use clog for changelogs ([34e31232](https://github.com/rust-lang/rustlings/commit/34e31232dfddde284a341c9609b33cd27d9d5724)) -* **iterators2:** adds iterators2 exercise including config ([9288fccf](https://github.com/rust-lang/rustlings/commit/9288fccf07a2c5043b76d0fd6491e4cf72d76031)) +- **changelog:** Use clog for changelogs ([34e31232](https://github.com/rust-lang/rustlings/commit/34e31232dfddde284a341c9609b33cd27d9d5724)) +- **iterators2:** adds iterators2 exercise including config ([9288fccf](https://github.com/rust-lang/rustlings/commit/9288fccf07a2c5043b76d0fd6491e4cf72d76031)) - ### 1.3.0 (2019-06-05) #### Features @@ -604,14 +942,12 @@ - Fix broken link (#164, @HanKruiger) - Remove highlighting and syntect (#167, @komaeda) - ### 1.2.2 (2019-05-07) #### Bug Fixes - Reverted `--nocapture` flag since it was causing tests to pass unconditionally - ### 1.2.1 (2019-04-22) #### Bug Fixes @@ -619,7 +955,6 @@ - Fix the `--nocapture` feature (@komaeda) - Provide a nicer error message for when you're in the wrong directory - ### 1.2.0 (2019-04-22) #### Features @@ -627,7 +962,6 @@ - Add errors to exercises that compile without user changes (@yvan-sraka) - Use --nocapture when testing, enabling `println!` when running (@komaeda) - ### 1.1.1 (2019-04-14) #### Bug fixes @@ -640,7 +974,6 @@ - Fix links by deleting book version (@diodfr, #142) - Canonicalize paths to fix path matching (@cjpearce, #143) - ### 1.1.0 (2019-03-20) - errors2.rs: update link to Rust book (#124) @@ -650,14 +983,12 @@ - Give a warning when Rustlings isn't run from the right directory (#123) - Verify that rust version is recent enough to install Rustlings (#131) - ### 1.0.1 (2019-03-06) - Adds a way to install Rustlings in one command (`curl -L https://git.io/rustlings | bash`) - Makes `rustlings watch` react to create file events (@shaunbennett, #117) - Reworks the exercise management to use an external TOML file instead of just listing them in the code - ### 1.0.0 (2019-03-06) Initial release. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index cc8ac92358..95605f70a7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,130 +1,61 @@ -## Contributing to Rustlings +# Contributing to Rustlings -First off, thanks for taking the time to contribute!! ❤️ +First off, thanks for taking the time to contribute! ❤️ -### Quick Reference +## Quick Reference -I want to... +I want to … -_add an exercise! ➡️ [read this](#addex) and then [open a Pull Request](#prs)_ +- _report a bug!_ ➡️ [open an issue](#issues) +- _fix a bug!_ ➡️ [open a pull request](#pull-requests) +- _implement a new feature!_ ➡️ [open an issue to discuss it first, then a pull request](#issues) +- _add an exercise!_ ➡️ [read this](#adding-an-exercise) +- _update an outdated exercise!_ ➡️ [open a pull request](#pull-requests) -_update an outdated exercise! ➡️ [open a Pull Request](#prs)_ - -_report a bug! ➡️ [open an Issue](#issues)_ - -_fix a bug! ➡️ [open a Pull Request](#prs)_ - -_implement a new feature! ➡️ [open an Issue to discuss it first, then a Pull Request](#issues)_ - - -### Working on the source code - -`rustlings` is basically a glorified `rustc` wrapper. Therefore the source code -isn't really that complicated since the bulk of the work is done by `rustc`. -`src/main.rs` contains a simple `argh` CLI that connects to most of the other source files. - - -### Adding an exercise - -The first step is to add the exercise! Name the file `exercises/yourTopic/yourTopicN.rs`, make sure to -put in some helpful links, and link to sections of the book in `exercises/yourTopic/README.md`. - -Next make sure it runs with `rustlings`. The exercise metadata is stored in `info.toml`, under the `exercises` array. The order of the `exercises` array determines the order the exercises are run by `rustlings verify` and `rustlings watch`. - -Add the metadata for your exercise in the correct order in the `exercises` array. If you are unsure of the correct ordering, add it at the bottom and ask in your pull request. The exercise metadata should contain the following: -```diff - ... -+ [[exercises]] -+ name = "yourTopicN" -+ path = "exercises/yourTopic/yourTopicN.rs" -+ mode = "compile" -+ hint = """ -+ Some kind of useful hint for your exercise.""" - ... -``` - -The `mode` attribute decides whether Rustlings will only compile your exercise, or compile and test it. If you have tests to verify in your exercise, choose `test`, otherwise `compile`. If you're working on a Clippy exercise, use `mode = "clippy"`. - -That's all! Feel free to put up a pull request. - - -### Issues +## Issues You can open an issue [here](https://github.com/rust-lang/rustlings/issues/new). If you're reporting a bug, please include the output of the following commands: -- `rustc --version` +- `cargo --version` - `rustlings --version` - `ls -la` - Your OS name and version - -### Pull Requests - -Opening a pull request is as easy as forking the repository and committing your -changes. There's a couple of things to watch out for: - -#### Write correct commit messages - -We follow the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0-beta.4/) -specification. -This means that you have to format your commit messages in a specific way. Say -you're working on adding a new exercise called `foobar1.rs`. You could write -the following commit message: - -``` -feat: add foobar1.rs exercise -``` +## Pull Requests -If you're just fixing a bug, please use the `fix` type: +You are welcome to open a pull request, but unless it is small and trivial, **please open an issue to discuss your idea first** 🙏🏼 -``` -fix(verify): make sure verify doesn't self-destruct -``` +Opening a pull request is as easy as forking the repository and committing your changes. +If you need any help with it or face any Git related problems, don't hesitate to ask for help 🤗 -The scope within the brackets is optional, but should be any of these: +It may take time to review your pull request. +Please be patient 😇 -- `installation` (for the installation script) -- `cli` (for general CLI changes) -- `verify` (for the verification source file) -- `watch` (for the watch functionality source) -- `run` (for the run functionality source) -- `EXERCISENAME` (if you're changing a specific exercise, or set of exercises, - substitute them here) +When updating an exercise, check if its solution needs to be updated. -When the commit also happens to close an existing issue, link it in the message -body: +## Adding An Exercise -``` -fix: update foobar +- Name the file `exercises/yourTopic/yourTopicN.rs`. +- Make sure to put in some helpful links, and link to sections of The Book in `exercises/yourTopic/README.md`. +- In the exercise, add a `// TODO: …` comment where user changes are required. +- Add a solution at `solutions/yourTopic/yourTopicN.rs` with comments explaining it. +- Add the [metadata for your exercise](#exercise-metadata) in the `rustlings-macros/info.toml` file. +- Make sure your exercise runs with `rustlings run yourTopicN`. +- [Open a pull request](#pull-requests). -closes #101029908 -``` +### Exercise Metadata -If you're doing simple changes, like updating a book link, use `chore`: +The exercise metadata should contain the following: +```toml +[[exercises]] +name = "yourTopicN" +dir = "yourTopic" +hint = """ +A useful (multi-line) hint for your exercise. +Include links to a section in The Book or a documentation page.""" ``` -chore: update exercise1.rs book link -``` - -If you're updating documentation, use `docs`: - -``` -docs: add more information to Readme -``` - -If, and only if, you're absolutely sure you want to make a breaking change -(please discuss this beforehand!), add an exclamation mark to the type and -explain the breaking change in the message body: - -``` -fix!: completely change verification - -BREAKING CHANGE: This has to be done because lorem ipsum dolor -``` - -#### Pull Request Workflow -Once you open a Pull Request, it may be reviewed or labeled (or both) until -the maintainers accept your change. Please be patient, it may take some time -for this to happen! +If your exercise doesn't contain any test, add `test = false` to the exercise metadata. +But adding tests is recommended. diff --git a/Cargo.lock b/Cargo.lock index 2370e8dcda..f883653fd3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,62 +1,68 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] -name = "aho-corasick" -version = "0.7.18" +name = "anstream" +version = "0.6.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f" +checksum = "3ae563653d1938f79b1ab1b5e668c87c76a9930414574a6583a7b7e11a8e6192" dependencies = [ - "memchr", + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", ] [[package]] -name = "argh" -version = "0.1.5" +name = "anstyle" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e7317a549bc17c5278d9e72bb6e62c6aa801ac2567048e39ebc1c194249323e" -dependencies = [ - "argh_derive", - "argh_shared", -] +checksum = "862ed96ca487e809f1c8e5a8447f6ee2cf102f846893800b20cebdf541fc6bbd" [[package]] -name = "argh_derive" -version = "0.1.5" +name = "anstyle-parse" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60949c42375351e9442e354434b0cba2ac402c1237edf673cac3a4bf983b8d3c" +checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2" dependencies = [ - "argh_shared", - "heck", - "proc-macro2", - "quote", - "syn", + "utf8parse", ] [[package]] -name = "argh_shared" -version = "0.1.5" +name = "anstyle-query" +version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a61eb019cb8f415d162cb9f12130ee6bbe9168b7d953c17f4ad049e4051ca00" +checksum = "9e231f6134f61b71076a3eab506c379d4f36122f2af15a9ff04415ea4c3339e2" +dependencies = [ + "windows-sys 0.60.2", +] [[package]] -name = "assert_cmd" -version = "0.11.1" +name = "anstyle-wincon" +version = "3.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dc477793bd82ec39799b6f6b3df64938532fdf2ab0d49ef817eac65856a5a1e" +checksum = "3e0633414522a32ffaac8ac6cc8f748e090c5717661fddeea04219e2344f5f2a" dependencies = [ - "escargot", - "predicates", - "predicates-core", - "predicates-tree", + "anstyle", + "once_cell_polyfill", + "windows-sys 0.60.2", ] +[[package]] +name = "anyhow" +version = "1.0.99" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0674a1ddeecb70197781e945de4b3b8ffb61fa939a5597bcf48503737663100" + [[package]] name = "autocfg" -version = "1.0.1" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" [[package]] name = "bitflags" @@ -65,155 +71,170 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] -name = "cfg-if" -version = "0.1.10" +name = "bitflags" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" +checksum = "6a65b545ab31d687cff52899d4890855fec459eb6afe0da6417b8a18da87aa29" [[package]] name = "cfg-if" -version = "1.0.0" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +checksum = "2fd1289c04a9ea8cb22300a459a72a385d7c73d3259e2ed7dcb2af674838cfa9" [[package]] -name = "console" -version = "0.15.0" +name = "clap" +version = "4.5.45" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a28b32d32ca44b70c3e4acd7db1babf555fa026e385fb95f18028f88848b3c31" +checksum = "1fc0e74a703892159f5ae7d3aac52c8e6c392f5ae5f359c70b5881d60aaac318" dependencies = [ - "encode_unicode", - "libc", - "once_cell", - "regex", - "terminal_size", - "unicode-width", - "winapi 0.3.9", + "clap_builder", + "clap_derive", ] [[package]] -name = "difference" -version = "2.0.0" +name = "clap_builder" +version = "4.5.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "524cbf6897b527295dff137cec09ecf3a05f4fddffd7dfcd1585403449e74198" +checksum = "b3e7f4214277f3c7aa526a59dd3fbe306a370daee1f8b7b8c987069cd8e888a8" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] [[package]] -name = "encode_unicode" -version = "0.3.6" +name = "clap_derive" +version = "4.5.45" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f" +checksum = "14cb31bb0a7d536caef2639baa7fad459e15c3144efefa6dbd1c84562c4739f6" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] [[package]] -name = "escargot" -version = "0.4.0" +name = "clap_lex" +version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ceb9adbf9874d5d028b5e4c5739d22b71988252b25c9c98fe7cf9738bee84597" -dependencies = [ - "lazy_static", - "log", - "serde", - "serde_json", -] +checksum = "b94f61472cee1439c0b966b47e3aca9ae07e45d070759512cd390ea2bebc6675" [[package]] -name = "filetime" -version = "0.2.15" +name = "colorchoice" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "975ccf83d8d9d0d84682850a38c8169027be83368805971cc4f238c2b245bc98" -dependencies = [ - "cfg-if 1.0.0", - "libc", - "redox_syscall", - "winapi 0.3.9", -] +checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" [[package]] -name = "float-cmp" -version = "0.8.0" +name = "crossterm" +version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1267f4ac4f343772758f7b1bdcbe767c218bbab93bb432acbf5162bbf85a6c4" +checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b" dependencies = [ - "num-traits", + "bitflags 2.9.2", + "crossterm_winapi", + "document-features", + "mio", + "parking_lot", + "rustix", + "signal-hook", + "signal-hook-mio", + "winapi", ] [[package]] -name = "fsevent" -version = "0.4.0" +name = "crossterm_winapi" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ab7d1bd1bd33cc98b0889831b72da23c0aa4df9cec7e0702f46ecea04b35db6" +checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" dependencies = [ - "bitflags", - "fsevent-sys", + "winapi", ] [[package]] -name = "fsevent-sys" -version = "2.0.1" +name = "document-features" +version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f41b048a94555da0f42f1d632e2e19510084fb8e303b0daa2816e733fb3644a0" +checksum = "95249b50c6c185bee49034bcb378a49dc2b5dff0be90ff6616d31d64febab05d" dependencies = [ - "libc", + "litrs", ] [[package]] -name = "fuchsia-zircon" -version = "0.3.3" +name = "equivalent" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e9763c69ebaae630ba35f74888db465e49e259ba1bc0eda7d06f4a067615d82" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "778e2ac28f6c47af28e4907f13ffd1e1ddbd400980a9abd7c8df189bf578a5ad" dependencies = [ - "bitflags", - "fuchsia-zircon-sys", + "libc", + "windows-sys 0.60.2", ] [[package]] -name = "fuchsia-zircon-sys" -version = "0.3.3" +name = "fastrand" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3dcaa9ae7725d12cdb85b3ad99a434db70b468c09ded17e012d86b5c1010f7a7" +checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" [[package]] -name = "glob" -version = "0.3.0" +name = "fsevent-sys" +version = "4.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574" +checksum = "76ee7a02da4d231650c7cea31349b889be2f45ddb3ef3032d2ec8185f6313fd2" +dependencies = [ + "libc", +] [[package]] -name = "heck" +name = "getrandom" version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c" +checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4" dependencies = [ - "unicode-segmentation", + "cfg-if", + "libc", + "r-efi", + "wasi 0.14.2+wasi-0.2.4", ] [[package]] -name = "home" -version = "0.5.3" +name = "hashbrown" +version = "0.15.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2456aef2e6b6a9784192ae780c0f15bc57df0e918585282325e8c8ac27737654" -dependencies = [ - "winapi 0.3.9", -] +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" [[package]] -name = "indicatif" -version = "0.16.2" +name = "indexmap" +version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d207dc617c7a380ab07ff572a6e52fa202a2a8f355860ac9c38e23f8196be1b" +checksum = "fe4cd85333e22411419a0bcae1297d25e58c9443848b11dc6a86fefe8c78a661" dependencies = [ - "console", - "lazy_static", - "number_prefix", - "regex", + "equivalent", + "hashbrown", ] [[package]] name = "inotify" -version = "0.7.1" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4816c66d2c8ae673df83366c18341538f234a26d65a9ecea5c348b453ac1d02f" +checksum = "f37dccff2791ab604f9babef0ba14fbe0be30bd368dc541e2b08d07c8aa908f3" dependencies = [ - "bitflags", + "bitflags 2.9.2", "inotify-sys", "libc", ] @@ -228,258 +249,224 @@ dependencies = [ ] [[package]] -name = "iovec" -version = "0.1.4" +name = "is_terminal_polyfill" +version = "1.70.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2b3ea6ff95e175473f8ffe6a7eb7c00d054240321b84c57051175fe3c1e075e" -dependencies = [ - "libc", -] +checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf" [[package]] name = "itoa" -version = "1.0.2" +version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "112c678d4050afce233f4f2852bb2eb519230b3cf12f33585275537d7e41578d" +checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" [[package]] -name = "kernel32-sys" -version = "0.2.2" +name = "kqueue" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d" +checksum = "eac30106d7dce88daf4a3fcb4879ea939476d5074a9b7ddd0fb97fa4bed5596a" dependencies = [ - "winapi 0.2.8", - "winapi-build", + "kqueue-sys", + "libc", ] [[package]] -name = "lazy_static" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" - -[[package]] -name = "lazycell" -version = "1.3.0" +name = "kqueue-sys" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" +checksum = "ed9625ffda8729b85e45cf04090035ac368927b8cebc34898e7c120f52e4838b" +dependencies = [ + "bitflags 1.3.2", + "libc", +] [[package]] name = "libc" -version = "0.2.100" +version = "0.2.175" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1fa8cddc8fbbee11227ef194b5317ed014b8acbf15139bd716a18ad3fe99ec5" +checksum = "6a82ae493e598baaea5209805c49bbf2ea7de956d50d7da0da1164f9c6d28543" [[package]] -name = "log" -version = "0.4.14" +name = "linux-raw-sys" +version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51b9bbe6c47d51fc3e1a9b945965946b4c44142ab8792c50835a980d362c2710" -dependencies = [ - "cfg-if 1.0.0", -] +checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" [[package]] -name = "memchr" -version = "2.4.1" +name = "litrs" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a" +checksum = "f5e54036fe321fd421e10d732f155734c4e4afd610dd556d9a82833ab3ee0bed" [[package]] -name = "mio" -version = "0.6.23" +name = "lock_api" +version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4afd66f5b91bf2a3bc13fad0e21caedac168ca4c707504e75585648ae80e4cc4" +checksum = "96936507f153605bddfcda068dd804796c84324ed2510809e5b2a624c81da765" dependencies = [ - "cfg-if 0.1.10", - "fuchsia-zircon", - "fuchsia-zircon-sys", - "iovec", - "kernel32-sys", - "libc", - "log", - "miow", - "net2", - "slab", - "winapi 0.2.8", + "autocfg", + "scopeguard", ] [[package]] -name = "mio-extras" -version = "2.0.6" +name = "log" +version = "0.4.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52403fe290012ce777c4626790c8951324a2b9e3316b3143779c72b029742f19" -dependencies = [ - "lazycell", - "log", - "mio", - "slab", -] +checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94" [[package]] -name = "miow" -version = "0.2.2" +name = "memchr" +version = "2.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebd808424166322d4a38da87083bfddd3ac4c131334ed55856112eb06d46944d" -dependencies = [ - "kernel32-sys", - "net2", - "winapi 0.2.8", - "ws2_32-sys", -] +checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0" [[package]] -name = "net2" -version = "0.2.37" +name = "mio" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "391630d12b68002ae1e25e8f974306474966550ad82dac6886fb8910c19568ae" +checksum = "78bed444cc8a2160f01cbcf811ef18cac863ad68ae8ca62092e8db51d51c761c" dependencies = [ - "cfg-if 0.1.10", "libc", - "winapi 0.3.9", + "log", + "wasi 0.11.1+wasi-snapshot-preview1", + "windows-sys 0.59.0", ] -[[package]] -name = "normalize-line-endings" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" - [[package]] name = "notify" -version = "4.0.17" +version = "8.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae03c8c853dba7bfd23e571ff0cff7bc9dceb40a4cd684cd1681824183f45257" +checksum = "4d3d07927151ff8575b7087f245456e549fea62edf0ec4e565a5ee50c8402bc3" dependencies = [ - "bitflags", - "filetime", - "fsevent", + "bitflags 2.9.2", "fsevent-sys", "inotify", + "kqueue", "libc", + "log", "mio", - "mio-extras", + "notify-types", "walkdir", - "winapi 0.3.9", + "windows-sys 0.60.2", ] [[package]] -name = "num-traits" -version = "0.2.14" +name = "notify-types" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290" -dependencies = [ - "autocfg", -] +checksum = "5e0826a989adedc2a244799e823aece04662b66609d96af8dff7ac6df9a8925d" [[package]] -name = "number_prefix" -version = "0.4.0" +name = "once_cell" +version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3" +checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" [[package]] -name = "once_cell" -version = "1.10.0" +name = "once_cell_polyfill" +version = "1.70.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87f3e037eac156d1775da914196f0f37741a274155e34a0b7e427c35d2a2ecb9" +checksum = "a4895175b425cb1f87721b59f0f286c2092bd4af812243672510e1ac53e2e0ad" [[package]] -name = "predicates" -version = "1.0.8" +name = "parking_lot" +version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f49cfaf7fdaa3bfacc6fa3e7054e65148878354a5cfddcf661df4c851f8021df" +checksum = "70d58bf43669b5795d1576d0641cfb6fbb2057bf629506267a92807158584a13" dependencies = [ - "difference", - "float-cmp", - "normalize-line-endings", - "predicates-core", - "regex", + "lock_api", + "parking_lot_core", ] [[package]] -name = "predicates-core" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57e35a3326b75e49aa85f5dc6ec15b41108cf5aee58eabb1f274dd18b73c2451" - -[[package]] -name = "predicates-tree" -version = "1.0.3" +name = "parking_lot_core" +version = "0.9.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7dd0fd014130206c9352efbdc92be592751b2b9274dff685348341082c6ea3d" +checksum = "bc838d2a56b5b1a6c25f55575dfc605fabb63bb2365f6c2353ef9159aa69e4a5" dependencies = [ - "predicates-core", - "treeline", + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-targets 0.52.6", ] [[package]] name = "proc-macro2" -version = "1.0.28" +version = "1.0.101" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c7ed8b8c7b886ea3ed7dde405212185f423ab44682667c8c6dd14aa1d9f6612" +checksum = "89ae43fd86e4158d6db51ad8e2b80f313af9cc74f5c0e03ccb87de09998732de" dependencies = [ - "unicode-xid", + "unicode-ident", ] [[package]] name = "quote" -version = "1.0.9" +version = "1.0.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d0b9745dc2debf507c8422de05d7226cc1f0644216dfdfead988f9b1ab32a7" +checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" dependencies = [ "proc-macro2", ] [[package]] -name = "redox_syscall" -version = "0.2.10" +name = "r-efi" +version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8383f39639269cde97d255a32bdb68c047337295414940c68bdd30c2e13203ff" -dependencies = [ - "bitflags", -] +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" [[package]] -name = "regex" -version = "1.5.5" +name = "redox_syscall" +version = "0.5.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a11647b6b25ff05a515cb92c365cec08801e83423a235b51e231e1808747286" +checksum = "5407465600fb0548f1442edf71dd20683c6ed326200ace4b1ef0763521bb3b77" dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", + "bitflags 2.9.2", ] [[package]] -name = "regex-syntax" -version = "0.6.25" +name = "rustix" +version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b" +checksum = "11181fbabf243db407ef8df94a6ce0b2f9a733bd8be4ad02b4eda9602296cac8" +dependencies = [ + "bitflags 2.9.2", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.60.2", +] [[package]] name = "rustlings" -version = "5.1.1" -dependencies = [ - "argh", - "assert_cmd", - "console", - "glob", - "home", - "indicatif", +version = "6.5.0" +dependencies = [ + "anyhow", + "clap", + "crossterm", "notify", - "predicates", - "regex", + "rustix", + "rustlings-macros", "serde", "serde_json", + "tempfile", + "toml", +] + +[[package]] +name = "rustlings-macros" +version = "6.5.0" +dependencies = [ + "quote", + "serde", "toml", ] [[package]] name = "ryu" -version = "1.0.5" +version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e" +checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" [[package]] name = "same-file" @@ -490,20 +477,26 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + [[package]] name = "serde" -version = "1.0.129" +version = "1.0.219" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1f72836d2aa753853178eda473a3b9d8e4eefdaf20523b919677e6de489f8f1" +checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.129" +version = "1.0.219" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e57ae87ad533d9a56427558b516d0adac283614e347abf85b0dc0cbbf0a249f3" +checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00" dependencies = [ "proc-macro2", "quote", @@ -512,91 +505,166 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.81" +version = "1.0.143" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b7ce2b32a1aed03c558dc61a5cd328f15aff2dbc17daad8fb8af04d2100e15c" +checksum = "d401abef1d108fbd9cbaebc3e46611f4b1021f714a0597a71f41ee463f5f4a5a" dependencies = [ "itoa", + "memchr", "ryu", "serde", ] [[package]] -name = "slab" -version = "0.4.4" +name = "serde_spanned" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40734c41988f7306bb04f0ecf60ec0f3f1caa34290e4e8ea471dcd3346483b83" +dependencies = [ + "serde", +] + +[[package]] +name = "signal-hook" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook-mio" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34db1a06d485c9142248b7a054f034b349b212551f3dfd19c94d45a754a217cd" +dependencies = [ + "libc", + "mio", + "signal-hook", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a4719bff48cee6b39d12c020eeb490953ad2443b7055bd0b21fca26bd8c28b" +dependencies = [ + "libc", +] + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + +[[package]] +name = "strsim" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c307a32c1c5c437f38c7fd45d753050587732ba8628319fbdf12a7e289ccc590" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" [[package]] name = "syn" -version = "1.0.75" +version = "2.0.106" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7f58f7e8eaa0009c5fec437aabf511bd9933e4b2d7407bd05273c01a8906ea7" +checksum = "ede7c438028d4436d71104916910f5bb611972c5cfd7f89b8300a8186e6fada6" dependencies = [ "proc-macro2", "quote", - "unicode-xid", + "unicode-ident", ] [[package]] -name = "terminal_size" -version = "0.1.17" +name = "tempfile" +version = "3.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "633c1a546cee861a1a6d0dc69ebeca693bf4296661ba7852b9d21d159e0506df" +checksum = "15b61f8f20e3a6f7e0649d825294eaf317edce30f82cf6026e7e4cb9222a7d1e" dependencies = [ - "libc", - "winapi 0.3.9", + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys 0.60.2", ] [[package]] name = "toml" -version = "0.5.9" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7" +checksum = "75129e1dc5000bfbaa9fee9d1b21f974f9fbad9daec557a521ee6e080825f6e8" dependencies = [ + "indexmap", "serde", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", ] [[package]] -name = "treeline" -version = "0.1.0" +name = "toml_datetime" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7f741b240f1a48843f9b8e0444fb55fb2a4ff67293b50a9179dfd5ea67f8d41" +checksum = "bade1c3e902f58d73d3f294cd7f20391c1cb2fbcb643b73566bc773971df91e3" +dependencies = [ + "serde", +] [[package]] -name = "unicode-segmentation" -version = "1.8.0" +name = "toml_parser" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8895849a949e7845e06bd6dc1aa51731a103c42707010a5b591c0038fb73385b" +checksum = "b551886f449aa90d4fe2bdaa9f4a2577ad2dde302c61ecf262d80b116db95c10" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcc842091f2def52017664b53082ecbbeb5c7731092bad69d2c63050401dfd64" [[package]] -name = "unicode-width" -version = "0.1.8" +name = "unicode-ident" +version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9337591893a19b88d8d87f2cec1e73fad5cdfd10e5a6f349f498ad6ea2ffb1e3" +checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" [[package]] -name = "unicode-xid" +name = "utf8parse" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "walkdir" -version = "2.3.2" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "808cf2735cd4b6866113f648b791c6adc5714537bc222d9347bb203386ffda56" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" dependencies = [ "same-file", - "winapi 0.3.9", "winapi-util", ] [[package]] -name = "winapi" -version = "0.2.8" +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasi" +version = "0.14.2+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9683f9a5a998d873c0d21fcbe3c083009670149a8fab228644b8bd36b2c48cb3" +dependencies = [ + "wit-bindgen-rt", +] [[package]] name = "winapi" @@ -608,12 +676,6 @@ dependencies = [ "winapi-x86_64-pc-windows-gnu", ] -[[package]] -name = "winapi-build" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc" - [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" @@ -622,11 +684,11 @@ checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-util" -version = "0.1.5" +version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" +checksum = "0978bf7171b3d90bac376700cb56d606feb40f251a475a5d6634613564460b22" dependencies = [ - "winapi 0.3.9", + "windows-sys 0.60.2", ] [[package]] @@ -636,11 +698,169 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] -name = "ws2_32-sys" -version = "0.2.1" +name = "windows-link" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a" + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.3", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5fe6031c4041849d7c496a8ded650796e7b6ecc19df1a431c1a363342e5dc91" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm 0.53.0", + "windows_aarch64_msvc 0.53.0", + "windows_i686_gnu 0.53.0", + "windows_i686_gnullvm 0.53.0", + "windows_i686_msvc 0.53.0", + "windows_x86_64_gnu 0.53.0", + "windows_x86_64_gnullvm 0.53.0", + "windows_x86_64_msvc 0.53.0", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86b8d5f90ddd19cb4a147a5fa63ca848db3df085e25fee3cc10b39b6eebae764" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1dc67659d35f387f5f6c479dc4e28f1d4bb90ddd1a5d3da2e5d97b42d6272c3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce6ccbdedbf6d6354471319e781c0dfef054c81fbc7cf83f338a4296c0cae11" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "581fee95406bb13382d2f65cd4a908ca7b1e4c2f1917f143ba16efe98a589b5d" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e55b5ac9ea33f2fc1716d1742db15574fd6fc8dadc51caab1c16a3d3b4190ba" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a6e035dd0599267ce1ee132e51c27dd29437f63325753051e71dd9e42406c57" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486" + +[[package]] +name = "winnow" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3edebf492c8125044983378ecb5766203ad3b4c2f7a922bd7dd207f6d443e95" + +[[package]] +name = "wit-bindgen-rt" +version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d59cefebd0c892fa2dd6de581e937301d8552cb44489cdff035c6187cb63fa5e" +checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1" dependencies = [ - "winapi 0.2.8", - "winapi-build", + "bitflags 2.9.2", ] diff --git a/Cargo.toml b/Cargo.toml index 25cd7bfefe..4469b28112 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,26 +1,87 @@ +[workspace] +exclude = [ + "tests/test_exercises", + "dev", +] + +[workspace.package] +version = "6.5.0" +authors = [ + "Mo Bitar ", # https://github.com/mo8it + "Liv ", # https://github.com/shadows-withal + # Alumni + "Carol (Nichols || Goulding) ", # https://github.com/carols10cents +] +repository = "https://github.com/rust-lang/rustlings" +license = "MIT" +edition = "2024" # On Update: Update the edition of `rustfmt` in `dev check` and `CARGO_TOML` in `dev new`. +rust-version = "1.88" + +[workspace.dependencies] +serde = { version = "1.0", features = ["derive"] } +toml = { version = "0.9", default-features = false, features = ["std", "parse", "serde"] } + [package] name = "rustlings" -version = "5.2.0" -authors = ["Liv ", "Carol (Nichols || Goulding) "] -edition = "2021" +description = "Small exercises to get you used to reading and writing Rust code!" +version.workspace = true +authors.workspace = true +repository.workspace = true +license.workspace = true +edition.workspace = true +rust-version.workspace = true +keywords = [ + "exercise", + "learning", +] +include = [ + "/src/", + "/exercises/", + "/solutions/", + # A symlink to be able to include `dev/Cargo.toml` although `dev` is excluded. + "/dev-Cargo.toml", + "/README.md", + "/LICENSE", +] [dependencies] -argh = "0.1" -indicatif = "0.16" -console = "0.15" -notify = "4.0" -toml = "0.5" -regex = "1.5" -serde = { version = "1.0", features = ["derive"] } -serde_json = "1.0.81" -home = "0.5.3" -glob = "0.3.0" +anyhow = "1.0" +clap = { version = "4.5", features = ["derive"] } +crossterm = { version = "0.29", default-features = false, features = ["windows", "events"] } +notify = "8.0" +rustlings-macros = { path = "rustlings-macros", version = "=6.5.0" } +serde_json = "1.0" +serde.workspace = true +toml.workspace = true -[[bin]] -name = "rustlings" -path = "src/main.rs" +[target.'cfg(not(windows))'.dependencies] +rustix = { version = "1.0", default-features = false, features = ["std", "stdio", "termios"] } [dev-dependencies] -assert_cmd = "0.11.0" -predicates = "1.0.1" -glob = "0.3.0" +tempfile = "3.21" + +[profile.release] +panic = "abort" + +[profile.dev] +panic = "abort" + +[package.metadata.release] +pre-release-hook = ["./release-hook.sh"] +pre-release-commit-message = "Release 🎉" + +[workspace.lints.rust] +unsafe_code = "forbid" +unstable_features = "forbid" + +[workspace.lints.clippy] +empty_loop = "forbid" +disallowed-types = "deny" +disallowed-methods = "deny" +infinite_loop = "deny" +mem_forget = "deny" +dbg_macro = "warn" +todo = "warn" + +[lints] +workspace = true diff --git a/README.md b/README.md index 2392ba9d93..0ae6265de9 100644 --- a/README.md +++ b/README.md @@ -1,163 +1,7 @@ -# rustlings 🦀❤️ +# [Rustlings](https://rustlings.rust-lang.org) 🦀 -Greetings and welcome to `rustlings`. This project contains small exercises to get you used to reading and writing Rust code. This includes reading and responding to compiler messages! +Small exercises to get you used to reading and writing [Rust](https://www.rust-lang.org) code - _Recommended in parallel to reading [the official Rust book](https://doc.rust-lang.org/book) 📚️_ -_...looking for the old, web-based version of Rustlings? Try [here](https://github.com/rust-lang/rustlings/tree/rustlings-1)_ +Visit the **website** for a demo, info about setup and more: -Alternatively, for a first-time Rust learner, there are several other resources: - -- [The Book](https://doc.rust-lang.org/book/index.html) - The most comprehensive resource for learning Rust, but a bit theoretical sometimes. You will be using this along with Rustlings! -- [Rust By Example](https://doc.rust-lang.org/rust-by-example/index.html) - Learn Rust by solving little exercises! It's almost like `rustlings`, but online - -## Getting Started - -_Note: If you're on MacOS, make sure you've installed Xcode and its developer tools by typing `xcode-select --install`._ -_Note: If you're on Linux, make sure you've installed gcc. Deb: `sudo apt install gcc`. Yum: `sudo yum -y install gcc`._ - -You will need to have Rust installed. You can get it by visiting https://rustup.rs. This'll also install Cargo, Rust's package/project manager. - -## MacOS/Linux - -Just run: - -```bash -curl -L https://raw.githubusercontent.com/rust-lang/rustlings/main/install.sh | bash -# Or if you want it to be installed to a different path: -curl -L https://raw.githubusercontent.com/rust-lang/rustlings/main/install.sh | bash -s mypath/ -``` - -This will install Rustlings and give you access to the `rustlings` command. Run it to get started! - -## Windows - -In PowerShell (Run as Administrator), set `ExecutionPolicy` to `RemoteSigned`: - -```ps1 -Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser -``` - -Then, you can run: - -```ps1 -Start-BitsTransfer -Source https://raw.githubusercontent.com/rust-lang/rustlings/main/install.ps1 -Destination $env:TMP/install_rustlings.ps1; Unblock-File $env:TMP/install_rustlings.ps1; Invoke-Expression $env:TMP/install_rustlings.ps1 -``` - -To install Rustlings. Same as on MacOS/Linux, you will have access to the `rustlings` command after it. - -If you get a permission denied message, you might have to exclude the directory where you cloned Rustlings in your antivirus. - -## Browser - -[Run on Repl.it](https://repl.it/github/rust-lang/rustlings) - -[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/rust-lang/rustlings) - -## Manually - -Basically: Clone the repository at the latest tag, run `cargo install --path .`. - -```bash -# find out the latest version at https://github.com/rust-lang/rustlings/releases/latest (on edit 5.1.1) -git clone -b 5.1.1 --depth 1 https://github.com/rust-lang/rustlings -cd rustlings -cargo install --force --path . -``` - -If there are installation errors, ensure that your toolchain is up to date. For the latest, run: - -```bash -rustup update -``` - -Then, same as above, run `rustlings` to get started. - -## Doing exercises - -The exercises are sorted by topic and can be found in the subdirectory `rustlings/exercises/`. For every topic there is an additional README file with some resources to get you started on the topic. We really recommend that you have a look at them before you start. - -The task is simple. Most exercises contain an error that keeps them from compiling, and it's up to you to fix it! Some exercises are also run as tests, but rustlings handles them all the same. To run the exercises in the recommended order, execute: - -```bash -rustlings watch -``` - -This will try to verify the completion of every exercise in a predetermined order (what we think is best for newcomers). It will also rerun automatically every time you change a file in the `exercises/` directory. If you want to only run it once, you can use: - -```bash -rustlings verify -``` - -This will do the same as watch, but it'll quit after running. - -In case you want to go by your own order, or want to only verify a single exercise, you can run: - -```bash -rustlings run myExercise1 -``` - -Or simply use the following command to run the next unsolved exercise in the course: - -```bash -rustlings run next -``` - -In case you get stuck, you can run the following command to get a hint for your -exercise: - -```bash -rustlings hint myExercise1 -``` - -You can also get the hint for the next unsolved exercise with the following command: - -```bash -rustlings hint next -``` - -To check your progress, you can run the following command: - -```bash -rustlings list -``` - -## Testing yourself - -After every couple of sections, there will be a quiz that'll test your knowledge on a bunch of sections at once. These quizzes are found in `exercises/quizN.rs`. - -## Enabling `rust-analyzer` - -Run the command `rustlings lsp` which will generate a `rust-project.json` at the root of the project, this allows [rust-analyzer](https://rust-analyzer.github.io/) to parse each exercise. - -## Continuing On - -Once you've completed Rustlings, put your new knowledge to good use! Continue practicing your Rust skills by building your own projects, contributing to Rustlings, or finding other open-source projects to contribute to. - -## Uninstalling Rustlings - -If you want to remove Rustlings from your system, there's two steps. First, you'll need to remove the exercises folder that the install script created -for you: - -```bash -rm -rf rustlings # or your custom folder name, if you chose and or renamed it -``` - -Second, since Rustlings got installed via `cargo install`, it's only reasonable to assume that you can also remove it using Cargo, and -exactly that is the case. Run `cargo uninstall` to remove the `rustlings` binary: - -```bash -cargo uninstall rustlings -``` - -Now you should be done! - -## Contributing - -See [CONTRIBUTING.md](./CONTRIBUTING.md). - -Development-focused discussion about Rustlings happens in the [**rustlings** stream](https://rust-lang.zulipchat.com/#narrow/stream/334454-rustlings) -on the [Rust Project Zulip](https://rust-lang.zulipchat.com). Feel free to start a new thread there -if you have ideas or suggestions! - -## Contributors ✨ - -Thanks goes to the wonderful people listed in [AUTHORS.md](./AUTHORS.md) 🎉 +## ➡️ [rustlings.rust-lang.org](https://rustlings.rust-lang.org) ⬅️ diff --git a/build.rs b/build.rs new file mode 100644 index 0000000000..5687864183 --- /dev/null +++ b/build.rs @@ -0,0 +1,5 @@ +fn main() { + // Fix building from source on Windows because it can't handle file links. + #[cfg(windows)] + let _ = std::fs::copy("dev/Cargo.toml", "dev-Cargo.toml"); +} diff --git a/clippy.toml b/clippy.toml new file mode 100644 index 0000000000..89b0a886f7 --- /dev/null +++ b/clippy.toml @@ -0,0 +1,11 @@ +disallowed-types = [ + { path = "crossterm::style::Stylize", reason = "inefficient, use `.queue(…)` instead" }, + { path = "crossterm::style::styled_content::StyledContent", reason = "inefficient, use `.queue(…)` instead" }, +] + +disallowed-methods = [ + { path = "crossterm::style::style", reason = "inefficient, use `.queue(…)` instead" }, + { path = "std::thread::spawn", replacement = "std::thread::Builder::spawn", reason = "handle the error" }, + { path = "std::thread::Scope::spawn", replacement = "std::thread::Builder::spawn", reason = "handle the error" }, + { path = "std::process::exit", replacement = "std::process::ExitCode" }, +] diff --git a/dev-Cargo.toml b/dev-Cargo.toml new file mode 120000 index 0000000000..9230c2e948 --- /dev/null +++ b/dev-Cargo.toml @@ -0,0 +1 @@ +dev/Cargo.toml \ No newline at end of file diff --git a/dev/Cargo.toml b/dev/Cargo.toml new file mode 100644 index 0000000000..4f725b704b --- /dev/null +++ b/dev/Cargo.toml @@ -0,0 +1,223 @@ +# Don't edit the `bin` list manually! It is updated by `cargo dev update`. This comment line will be stripped in `rustlings init`. +bin = [ + { name = "intro1", path = "../exercises/00_intro/intro1.rs" }, + { name = "intro1_sol", path = "../solutions/00_intro/intro1.rs" }, + { name = "intro2", path = "../exercises/00_intro/intro2.rs" }, + { name = "intro2_sol", path = "../solutions/00_intro/intro2.rs" }, + { name = "variables1", path = "../exercises/01_variables/variables1.rs" }, + { name = "variables1_sol", path = "../solutions/01_variables/variables1.rs" }, + { name = "variables2", path = "../exercises/01_variables/variables2.rs" }, + { name = "variables2_sol", path = "../solutions/01_variables/variables2.rs" }, + { name = "variables3", path = "../exercises/01_variables/variables3.rs" }, + { name = "variables3_sol", path = "../solutions/01_variables/variables3.rs" }, + { name = "variables4", path = "../exercises/01_variables/variables4.rs" }, + { name = "variables4_sol", path = "../solutions/01_variables/variables4.rs" }, + { name = "variables5", path = "../exercises/01_variables/variables5.rs" }, + { name = "variables5_sol", path = "../solutions/01_variables/variables5.rs" }, + { name = "variables6", path = "../exercises/01_variables/variables6.rs" }, + { name = "variables6_sol", path = "../solutions/01_variables/variables6.rs" }, + { name = "functions1", path = "../exercises/02_functions/functions1.rs" }, + { name = "functions1_sol", path = "../solutions/02_functions/functions1.rs" }, + { name = "functions2", path = "../exercises/02_functions/functions2.rs" }, + { name = "functions2_sol", path = "../solutions/02_functions/functions2.rs" }, + { name = "functions3", path = "../exercises/02_functions/functions3.rs" }, + { name = "functions3_sol", path = "../solutions/02_functions/functions3.rs" }, + { name = "functions4", path = "../exercises/02_functions/functions4.rs" }, + { name = "functions4_sol", path = "../solutions/02_functions/functions4.rs" }, + { name = "functions5", path = "../exercises/02_functions/functions5.rs" }, + { name = "functions5_sol", path = "../solutions/02_functions/functions5.rs" }, + { name = "if1", path = "../exercises/03_if/if1.rs" }, + { name = "if1_sol", path = "../solutions/03_if/if1.rs" }, + { name = "if2", path = "../exercises/03_if/if2.rs" }, + { name = "if2_sol", path = "../solutions/03_if/if2.rs" }, + { name = "if3", path = "../exercises/03_if/if3.rs" }, + { name = "if3_sol", path = "../solutions/03_if/if3.rs" }, + { name = "quiz1", path = "../exercises/quizzes/quiz1.rs" }, + { name = "quiz1_sol", path = "../solutions/quizzes/quiz1.rs" }, + { name = "primitive_types1", path = "../exercises/04_primitive_types/primitive_types1.rs" }, + { name = "primitive_types1_sol", path = "../solutions/04_primitive_types/primitive_types1.rs" }, + { name = "primitive_types2", path = "../exercises/04_primitive_types/primitive_types2.rs" }, + { name = "primitive_types2_sol", path = "../solutions/04_primitive_types/primitive_types2.rs" }, + { name = "primitive_types3", path = "../exercises/04_primitive_types/primitive_types3.rs" }, + { name = "primitive_types3_sol", path = "../solutions/04_primitive_types/primitive_types3.rs" }, + { name = "primitive_types4", path = "../exercises/04_primitive_types/primitive_types4.rs" }, + { name = "primitive_types4_sol", path = "../solutions/04_primitive_types/primitive_types4.rs" }, + { name = "primitive_types5", path = "../exercises/04_primitive_types/primitive_types5.rs" }, + { name = "primitive_types5_sol", path = "../solutions/04_primitive_types/primitive_types5.rs" }, + { name = "primitive_types6", path = "../exercises/04_primitive_types/primitive_types6.rs" }, + { name = "primitive_types6_sol", path = "../solutions/04_primitive_types/primitive_types6.rs" }, + { name = "vecs1", path = "../exercises/05_vecs/vecs1.rs" }, + { name = "vecs1_sol", path = "../solutions/05_vecs/vecs1.rs" }, + { name = "vecs2", path = "../exercises/05_vecs/vecs2.rs" }, + { name = "vecs2_sol", path = "../solutions/05_vecs/vecs2.rs" }, + { name = "move_semantics1", path = "../exercises/06_move_semantics/move_semantics1.rs" }, + { name = "move_semantics1_sol", path = "../solutions/06_move_semantics/move_semantics1.rs" }, + { name = "move_semantics2", path = "../exercises/06_move_semantics/move_semantics2.rs" }, + { name = "move_semantics2_sol", path = "../solutions/06_move_semantics/move_semantics2.rs" }, + { name = "move_semantics3", path = "../exercises/06_move_semantics/move_semantics3.rs" }, + { name = "move_semantics3_sol", path = "../solutions/06_move_semantics/move_semantics3.rs" }, + { name = "move_semantics4", path = "../exercises/06_move_semantics/move_semantics4.rs" }, + { name = "move_semantics4_sol", path = "../solutions/06_move_semantics/move_semantics4.rs" }, + { name = "move_semantics5", path = "../exercises/06_move_semantics/move_semantics5.rs" }, + { name = "move_semantics5_sol", path = "../solutions/06_move_semantics/move_semantics5.rs" }, + { name = "structs1", path = "../exercises/07_structs/structs1.rs" }, + { name = "structs1_sol", path = "../solutions/07_structs/structs1.rs" }, + { name = "structs2", path = "../exercises/07_structs/structs2.rs" }, + { name = "structs2_sol", path = "../solutions/07_structs/structs2.rs" }, + { name = "structs3", path = "../exercises/07_structs/structs3.rs" }, + { name = "structs3_sol", path = "../solutions/07_structs/structs3.rs" }, + { name = "enums1", path = "../exercises/08_enums/enums1.rs" }, + { name = "enums1_sol", path = "../solutions/08_enums/enums1.rs" }, + { name = "enums2", path = "../exercises/08_enums/enums2.rs" }, + { name = "enums2_sol", path = "../solutions/08_enums/enums2.rs" }, + { name = "enums3", path = "../exercises/08_enums/enums3.rs" }, + { name = "enums3_sol", path = "../solutions/08_enums/enums3.rs" }, + { name = "strings1", path = "../exercises/09_strings/strings1.rs" }, + { name = "strings1_sol", path = "../solutions/09_strings/strings1.rs" }, + { name = "strings2", path = "../exercises/09_strings/strings2.rs" }, + { name = "strings2_sol", path = "../solutions/09_strings/strings2.rs" }, + { name = "strings3", path = "../exercises/09_strings/strings3.rs" }, + { name = "strings3_sol", path = "../solutions/09_strings/strings3.rs" }, + { name = "strings4", path = "../exercises/09_strings/strings4.rs" }, + { name = "strings4_sol", path = "../solutions/09_strings/strings4.rs" }, + { name = "modules1", path = "../exercises/10_modules/modules1.rs" }, + { name = "modules1_sol", path = "../solutions/10_modules/modules1.rs" }, + { name = "modules2", path = "../exercises/10_modules/modules2.rs" }, + { name = "modules2_sol", path = "../solutions/10_modules/modules2.rs" }, + { name = "modules3", path = "../exercises/10_modules/modules3.rs" }, + { name = "modules3_sol", path = "../solutions/10_modules/modules3.rs" }, + { name = "hashmaps1", path = "../exercises/11_hashmaps/hashmaps1.rs" }, + { name = "hashmaps1_sol", path = "../solutions/11_hashmaps/hashmaps1.rs" }, + { name = "hashmaps2", path = "../exercises/11_hashmaps/hashmaps2.rs" }, + { name = "hashmaps2_sol", path = "../solutions/11_hashmaps/hashmaps2.rs" }, + { name = "hashmaps3", path = "../exercises/11_hashmaps/hashmaps3.rs" }, + { name = "hashmaps3_sol", path = "../solutions/11_hashmaps/hashmaps3.rs" }, + { name = "quiz2", path = "../exercises/quizzes/quiz2.rs" }, + { name = "quiz2_sol", path = "../solutions/quizzes/quiz2.rs" }, + { name = "options1", path = "../exercises/12_options/options1.rs" }, + { name = "options1_sol", path = "../solutions/12_options/options1.rs" }, + { name = "options2", path = "../exercises/12_options/options2.rs" }, + { name = "options2_sol", path = "../solutions/12_options/options2.rs" }, + { name = "options3", path = "../exercises/12_options/options3.rs" }, + { name = "options3_sol", path = "../solutions/12_options/options3.rs" }, + { name = "errors1", path = "../exercises/13_error_handling/errors1.rs" }, + { name = "errors1_sol", path = "../solutions/13_error_handling/errors1.rs" }, + { name = "errors2", path = "../exercises/13_error_handling/errors2.rs" }, + { name = "errors2_sol", path = "../solutions/13_error_handling/errors2.rs" }, + { name = "errors3", path = "../exercises/13_error_handling/errors3.rs" }, + { name = "errors3_sol", path = "../solutions/13_error_handling/errors3.rs" }, + { name = "errors4", path = "../exercises/13_error_handling/errors4.rs" }, + { name = "errors4_sol", path = "../solutions/13_error_handling/errors4.rs" }, + { name = "errors5", path = "../exercises/13_error_handling/errors5.rs" }, + { name = "errors5_sol", path = "../solutions/13_error_handling/errors5.rs" }, + { name = "errors6", path = "../exercises/13_error_handling/errors6.rs" }, + { name = "errors6_sol", path = "../solutions/13_error_handling/errors6.rs" }, + { name = "generics1", path = "../exercises/14_generics/generics1.rs" }, + { name = "generics1_sol", path = "../solutions/14_generics/generics1.rs" }, + { name = "generics2", path = "../exercises/14_generics/generics2.rs" }, + { name = "generics2_sol", path = "../solutions/14_generics/generics2.rs" }, + { name = "traits1", path = "../exercises/15_traits/traits1.rs" }, + { name = "traits1_sol", path = "../solutions/15_traits/traits1.rs" }, + { name = "traits2", path = "../exercises/15_traits/traits2.rs" }, + { name = "traits2_sol", path = "../solutions/15_traits/traits2.rs" }, + { name = "traits3", path = "../exercises/15_traits/traits3.rs" }, + { name = "traits3_sol", path = "../solutions/15_traits/traits3.rs" }, + { name = "traits4", path = "../exercises/15_traits/traits4.rs" }, + { name = "traits4_sol", path = "../solutions/15_traits/traits4.rs" }, + { name = "traits5", path = "../exercises/15_traits/traits5.rs" }, + { name = "traits5_sol", path = "../solutions/15_traits/traits5.rs" }, + { name = "quiz3", path = "../exercises/quizzes/quiz3.rs" }, + { name = "quiz3_sol", path = "../solutions/quizzes/quiz3.rs" }, + { name = "lifetimes1", path = "../exercises/16_lifetimes/lifetimes1.rs" }, + { name = "lifetimes1_sol", path = "../solutions/16_lifetimes/lifetimes1.rs" }, + { name = "lifetimes2", path = "../exercises/16_lifetimes/lifetimes2.rs" }, + { name = "lifetimes2_sol", path = "../solutions/16_lifetimes/lifetimes2.rs" }, + { name = "lifetimes3", path = "../exercises/16_lifetimes/lifetimes3.rs" }, + { name = "lifetimes3_sol", path = "../solutions/16_lifetimes/lifetimes3.rs" }, + { name = "tests1", path = "../exercises/17_tests/tests1.rs" }, + { name = "tests1_sol", path = "../solutions/17_tests/tests1.rs" }, + { name = "tests2", path = "../exercises/17_tests/tests2.rs" }, + { name = "tests2_sol", path = "../solutions/17_tests/tests2.rs" }, + { name = "tests3", path = "../exercises/17_tests/tests3.rs" }, + { name = "tests3_sol", path = "../solutions/17_tests/tests3.rs" }, + { name = "iterators1", path = "../exercises/18_iterators/iterators1.rs" }, + { name = "iterators1_sol", path = "../solutions/18_iterators/iterators1.rs" }, + { name = "iterators2", path = "../exercises/18_iterators/iterators2.rs" }, + { name = "iterators2_sol", path = "../solutions/18_iterators/iterators2.rs" }, + { name = "iterators3", path = "../exercises/18_iterators/iterators3.rs" }, + { name = "iterators3_sol", path = "../solutions/18_iterators/iterators3.rs" }, + { name = "iterators4", path = "../exercises/18_iterators/iterators4.rs" }, + { name = "iterators4_sol", path = "../solutions/18_iterators/iterators4.rs" }, + { name = "iterators5", path = "../exercises/18_iterators/iterators5.rs" }, + { name = "iterators5_sol", path = "../solutions/18_iterators/iterators5.rs" }, + { name = "box1", path = "../exercises/19_smart_pointers/box1.rs" }, + { name = "box1_sol", path = "../solutions/19_smart_pointers/box1.rs" }, + { name = "rc1", path = "../exercises/19_smart_pointers/rc1.rs" }, + { name = "rc1_sol", path = "../solutions/19_smart_pointers/rc1.rs" }, + { name = "arc1", path = "../exercises/19_smart_pointers/arc1.rs" }, + { name = "arc1_sol", path = "../solutions/19_smart_pointers/arc1.rs" }, + { name = "cow1", path = "../exercises/19_smart_pointers/cow1.rs" }, + { name = "cow1_sol", path = "../solutions/19_smart_pointers/cow1.rs" }, + { name = "threads1", path = "../exercises/20_threads/threads1.rs" }, + { name = "threads1_sol", path = "../solutions/20_threads/threads1.rs" }, + { name = "threads2", path = "../exercises/20_threads/threads2.rs" }, + { name = "threads2_sol", path = "../solutions/20_threads/threads2.rs" }, + { name = "threads3", path = "../exercises/20_threads/threads3.rs" }, + { name = "threads3_sol", path = "../solutions/20_threads/threads3.rs" }, + { name = "macros1", path = "../exercises/21_macros/macros1.rs" }, + { name = "macros1_sol", path = "../solutions/21_macros/macros1.rs" }, + { name = "macros2", path = "../exercises/21_macros/macros2.rs" }, + { name = "macros2_sol", path = "../solutions/21_macros/macros2.rs" }, + { name = "macros3", path = "../exercises/21_macros/macros3.rs" }, + { name = "macros3_sol", path = "../solutions/21_macros/macros3.rs" }, + { name = "macros4", path = "../exercises/21_macros/macros4.rs" }, + { name = "macros4_sol", path = "../solutions/21_macros/macros4.rs" }, + { name = "clippy1", path = "../exercises/22_clippy/clippy1.rs" }, + { name = "clippy1_sol", path = "../solutions/22_clippy/clippy1.rs" }, + { name = "clippy2", path = "../exercises/22_clippy/clippy2.rs" }, + { name = "clippy2_sol", path = "../solutions/22_clippy/clippy2.rs" }, + { name = "clippy3", path = "../exercises/22_clippy/clippy3.rs" }, + { name = "clippy3_sol", path = "../solutions/22_clippy/clippy3.rs" }, + { name = "using_as", path = "../exercises/23_conversions/using_as.rs" }, + { name = "using_as_sol", path = "../solutions/23_conversions/using_as.rs" }, + { name = "from_into", path = "../exercises/23_conversions/from_into.rs" }, + { name = "from_into_sol", path = "../solutions/23_conversions/from_into.rs" }, + { name = "from_str", path = "../exercises/23_conversions/from_str.rs" }, + { name = "from_str_sol", path = "../solutions/23_conversions/from_str.rs" }, + { name = "try_from_into", path = "../exercises/23_conversions/try_from_into.rs" }, + { name = "try_from_into_sol", path = "../solutions/23_conversions/try_from_into.rs" }, + { name = "as_ref_mut", path = "../exercises/23_conversions/as_ref_mut.rs" }, + { name = "as_ref_mut_sol", path = "../solutions/23_conversions/as_ref_mut.rs" }, +] + +[package] +name = "exercises" +edition = "2024" +# Don't publish the exercises on crates.io! +publish = false + +[profile.release] +panic = "abort" + +[profile.dev] +panic = "abort" + +[lints.rust] +# You shouldn't write unsafe code in Rustlings! +unsafe_code = "forbid" +# You don't need unstable features in Rustlings and shouldn't rely on them while learning Rust. +unstable_features = "forbid" +# Dead code warnings can't be avoided in some exercises and might distract while learning. +dead_code = "allow" + +[lints.clippy] +# You forgot a `todo!()`! +todo = "forbid" +# This can only happen by mistake in Rustlings. +empty_loop = "forbid" +# No infinite loops are needed in Rustlings. +infinite_loop = "deny" +# You shouldn't leak memory while still learning Rust! +mem_forget = "deny" +# Currently, there are no disallowed methods. This line avoids problems when developing Rustlings. +disallowed_methods = "allow" diff --git a/dev/rustlings-repo.txt b/dev/rustlings-repo.txt new file mode 100644 index 0000000000..5d456c8803 --- /dev/null +++ b/dev/rustlings-repo.txt @@ -0,0 +1 @@ +This file is used to check if the user tries to run Rustlings in the repository (the method before version 6) diff --git a/exercises/intro/README.md b/exercises/00_intro/README.md similarity index 100% rename from exercises/intro/README.md rename to exercises/00_intro/README.md diff --git a/exercises/00_intro/intro1.rs b/exercises/00_intro/intro1.rs new file mode 100644 index 0000000000..172a6ab1f2 --- /dev/null +++ b/exercises/00_intro/intro1.rs @@ -0,0 +1,24 @@ +// TODO: We sometimes encourage you to keep trying things on a given exercise +// even after you already figured it out. If you got everything working and feel +// ready for the next exercise, enter `n` in the terminal. +// +// The exercise file will be reloaded when you change one of the lines below! +// Try adding a new `println!` and check the updated output in the terminal. + +fn main() { + println!(r#" Welcome to... "#); + println!(r#" _ _ _ "#); + println!(r#" _ __ _ _ ___| |_| (_)_ __ __ _ ___ "#); + println!(r#" | '__| | | / __| __| | | '_ \ / _` / __| "#); + println!(r#" | | | |_| \__ \ |_| | | | | | (_| \__ \ "#); + println!(r#" |_| \__,_|___/\__|_|_|_| |_|\__, |___/ "#); + println!(r#" |___/ "#); + println!(); + println!("This exercise compiles successfully. The remaining exercises contain a compiler"); + println!("or logic error. The central concept behind Rustlings is to fix these errors and"); + println!("solve the exercises. Good luck!"); + println!(); + println!("The file of this exercise is `exercises/00_intro/intro1.rs`. Have a look!"); + println!("The current exercise path will be always shown under the progress bar."); + println!("You can click on the path to open the exercise file in your editor."); +} diff --git a/exercises/00_intro/intro2.rs b/exercises/00_intro/intro2.rs new file mode 100644 index 0000000000..c6cb6451ae --- /dev/null +++ b/exercises/00_intro/intro2.rs @@ -0,0 +1,4 @@ +fn main() { + // TODO: Fix the code to print "Hello world!". + printline!("Hello world!"); +} diff --git a/exercises/variables/README.md b/exercises/01_variables/README.md similarity index 70% rename from exercises/variables/README.md rename to exercises/01_variables/README.md index 11a7a78ab8..5ba2efcaa2 100644 --- a/exercises/variables/README.md +++ b/exercises/01_variables/README.md @@ -1,8 +1,8 @@ # Variables In Rust, variables are immutable by default. -When a variable is immutable, once a value is bound to a name, you can’t change that value. -You can make them mutable by adding mut in front of the variable name. +When a variable is immutable, once a value is bound to a name, you can't change that value. +You can make them mutable by adding `mut` in front of the variable name. ## Further information diff --git a/exercises/01_variables/variables1.rs b/exercises/01_variables/variables1.rs new file mode 100644 index 0000000000..f83b44d415 --- /dev/null +++ b/exercises/01_variables/variables1.rs @@ -0,0 +1,6 @@ +fn main() { + // TODO: Add the missing keyword. + x = 5; + + println!("x has the value {x}"); +} diff --git a/exercises/variables/variables2.rs b/exercises/01_variables/variables2.rs similarity index 51% rename from exercises/variables/variables2.rs rename to exercises/01_variables/variables2.rs index 641aeb8e09..e2a360351a 100644 --- a/exercises/variables/variables2.rs +++ b/exercises/01_variables/variables2.rs @@ -1,10 +1,7 @@ -// variables2.rs -// Execute `rustlings hint variables2` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - fn main() { + // TODO: Change the line below to fix the compiler error. let x; + if x == 10 { println!("x is ten!"); } else { diff --git a/exercises/01_variables/variables3.rs b/exercises/01_variables/variables3.rs new file mode 100644 index 0000000000..06f35bb1e2 --- /dev/null +++ b/exercises/01_variables/variables3.rs @@ -0,0 +1,6 @@ +fn main() { + // TODO: Change the line below to fix the compiler error. + let x: i32; + + println!("Number {x}"); +} diff --git a/exercises/01_variables/variables4.rs b/exercises/01_variables/variables4.rs new file mode 100644 index 0000000000..6c138b18b9 --- /dev/null +++ b/exercises/01_variables/variables4.rs @@ -0,0 +1,8 @@ +// TODO: Fix the compiler error. +fn main() { + let x = 3; + println!("Number {x}"); + + x = 5; // Don't change this line + println!("Number {x}"); +} diff --git a/exercises/01_variables/variables5.rs b/exercises/01_variables/variables5.rs new file mode 100644 index 0000000000..cf5620da5f --- /dev/null +++ b/exercises/01_variables/variables5.rs @@ -0,0 +1,8 @@ +fn main() { + let number = "T-H-R-E-E"; // Don't change this line + println!("Spell a number: {number}"); + + // TODO: Fix the compiler error by changing the line below without renaming the variable. + number = 3; + println!("Number plus two is: {}", number + 2); +} diff --git a/exercises/01_variables/variables6.rs b/exercises/01_variables/variables6.rs new file mode 100644 index 0000000000..4a040fddac --- /dev/null +++ b/exercises/01_variables/variables6.rs @@ -0,0 +1,6 @@ +// TODO: Change the line below to fix the compiler error. +const NUMBER = 3; + +fn main() { + println!("Number: {NUMBER}"); +} diff --git a/exercises/functions/README.md b/exercises/02_functions/README.md similarity index 100% rename from exercises/functions/README.md rename to exercises/02_functions/README.md diff --git a/exercises/02_functions/functions1.rs b/exercises/02_functions/functions1.rs new file mode 100644 index 0000000000..a812c21bf2 --- /dev/null +++ b/exercises/02_functions/functions1.rs @@ -0,0 +1,5 @@ +// TODO: Add some function with the name `call_me` without arguments or a return value. + +fn main() { + call_me(); // Don't change this line +} diff --git a/exercises/functions/functions2.rs b/exercises/02_functions/functions2.rs similarity index 51% rename from exercises/functions/functions2.rs rename to exercises/02_functions/functions2.rs index 7d40a578c7..2c773c6b7f 100644 --- a/exercises/functions/functions2.rs +++ b/exercises/02_functions/functions2.rs @@ -1,14 +1,10 @@ -// functions2.rs -// Execute `rustlings hint functions2` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -fn main() { - call_me(3); -} - +// TODO: Add the missing type of the argument `num` after the colon `:`. fn call_me(num:) { for i in 0..num { println!("Ring! Call number {}", i + 1); } } + +fn main() { + call_me(3); +} diff --git a/exercises/02_functions/functions3.rs b/exercises/02_functions/functions3.rs new file mode 100644 index 0000000000..8d65477219 --- /dev/null +++ b/exercises/02_functions/functions3.rs @@ -0,0 +1,10 @@ +fn call_me(num: u8) { + for i in 0..num { + println!("Ring! Call number {}", i + 1); + } +} + +fn main() { + // TODO: Fix the function call. + call_me(); +} diff --git a/exercises/02_functions/functions4.rs b/exercises/02_functions/functions4.rs new file mode 100644 index 0000000000..b22bffdaf2 --- /dev/null +++ b/exercises/02_functions/functions4.rs @@ -0,0 +1,22 @@ +// This store is having a sale where if the price is an even number, you get 10 +// Rustbucks off, but if it's an odd number, it's 3 Rustbucks off. +// Don't worry about the function bodies themselves, we are only interested in +// the signatures for now. + +fn is_even(num: i64) -> bool { + num % 2 == 0 +} + +// TODO: Fix the function signature. +fn sale_price(price: i64) -> { + if is_even(price) { + price - 10 + } else { + price - 3 + } +} + +fn main() { + let original_price = 51; + println!("Your sale price is {}", sale_price(original_price)); +} diff --git a/exercises/02_functions/functions5.rs b/exercises/02_functions/functions5.rs new file mode 100644 index 0000000000..34a2ac7dce --- /dev/null +++ b/exercises/02_functions/functions5.rs @@ -0,0 +1,9 @@ +// TODO: Fix the function body without changing the signature. +fn square(num: i32) -> i32 { + num * num; +} + +fn main() { + let answer = square(3); + println!("The square of 3 is {answer}"); +} diff --git a/exercises/if/README.md b/exercises/03_if/README.md similarity index 100% rename from exercises/if/README.md rename to exercises/03_if/README.md diff --git a/exercises/if/if1.rs b/exercises/03_if/if1.rs similarity index 54% rename from exercises/if/if1.rs rename to exercises/03_if/if1.rs index 587e03f88a..e5a3c5a5b2 100644 --- a/exercises/if/if1.rs +++ b/exercises/03_if/if1.rs @@ -1,15 +1,15 @@ -// if1.rs -// Execute `rustlings hint if1` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -pub fn bigger(a: i32, b: i32) -> i32 { - // Complete this function to return the bigger number! +fn bigger(a: i32, b: i32) -> i32 { + // TODO: Complete this function to return the bigger number! + // If both numbers are equal, any of them can be returned. // Do not use: // - another function call // - additional variables } +fn main() { + // You can optionally experiment here. +} + // Don't mind this for now :) #[cfg(test)] mod tests { @@ -24,4 +24,9 @@ mod tests { fn fortytwo_is_bigger_than_thirtytwo() { assert_eq!(42, bigger(32, 42)); } + + #[test] + fn equal_numbers() { + assert_eq!(42, bigger(42, 42)); + } } diff --git a/exercises/03_if/if2.rs b/exercises/03_if/if2.rs new file mode 100644 index 0000000000..ca8493cc81 --- /dev/null +++ b/exercises/03_if/if2.rs @@ -0,0 +1,37 @@ +// TODO: Fix the compiler error on this function. +fn picky_eater(food: &str) -> &str { + if food == "strawberry" { + "Yummy!" + } else { + 1 + } +} + +fn main() { + // You can optionally experiment here. +} + +// TODO: Read the tests to understand the desired behavior. +// Make all tests pass without changing them. +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn yummy_food() { + // This means that calling `picky_eater` with the argument "strawberry" should return "Yummy!". + assert_eq!(picky_eater("strawberry"), "Yummy!"); + } + + #[test] + fn neutral_food() { + assert_eq!(picky_eater("potato"), "I guess I can eat that."); + } + + #[test] + fn default_disliked_food() { + assert_eq!(picky_eater("broccoli"), "No thanks!"); + assert_eq!(picky_eater("gummy bears"), "No thanks!"); + assert_eq!(picky_eater("literally anything"), "No thanks!"); + } +} diff --git a/exercises/03_if/if3.rs b/exercises/03_if/if3.rs new file mode 100644 index 0000000000..89164eb218 --- /dev/null +++ b/exercises/03_if/if3.rs @@ -0,0 +1,53 @@ +fn animal_habitat(animal: &str) -> &str { + // TODO: Fix the compiler error in the statement below. + let identifier = if animal == "crab" { + 1 + } else if animal == "gopher" { + 2.0 + } else if animal == "snake" { + 3 + } else { + "Unknown" + }; + + // Don't change the expression below! + if identifier == 1 { + "Beach" + } else if identifier == 2 { + "Burrow" + } else if identifier == 3 { + "Desert" + } else { + "Unknown" + } +} + +fn main() { + // You can optionally experiment here. +} + +// Don't change the tests! +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn gopher_lives_in_burrow() { + assert_eq!(animal_habitat("gopher"), "Burrow") + } + + #[test] + fn snake_lives_in_desert() { + assert_eq!(animal_habitat("snake"), "Desert") + } + + #[test] + fn crab_lives_on_beach() { + assert_eq!(animal_habitat("crab"), "Beach") + } + + #[test] + fn unknown_animal() { + assert_eq!(animal_habitat("dinosaur"), "Unknown") + } +} diff --git a/exercises/primitive_types/README.md b/exercises/04_primitive_types/README.md similarity index 54% rename from exercises/primitive_types/README.md rename to exercises/04_primitive_types/README.md index cea69b02af..d67668a335 100644 --- a/exercises/primitive_types/README.md +++ b/exercises/04_primitive_types/README.md @@ -5,5 +5,5 @@ compiler. In this section, we'll go through the most important ones. ## Further information -- [Data Types](https://doc.rust-lang.org/stable/book/ch03-02-data-types.html) -- [The Slice Type](https://doc.rust-lang.org/stable/book/ch04-03-slices.html) +- [Data Types](https://doc.rust-lang.org/book/ch03-02-data-types.html) +- [The Slice Type](https://doc.rust-lang.org/book/ch04-03-slices.html) diff --git a/exercises/04_primitive_types/primitive_types1.rs b/exercises/04_primitive_types/primitive_types1.rs new file mode 100644 index 0000000000..84923c7500 --- /dev/null +++ b/exercises/04_primitive_types/primitive_types1.rs @@ -0,0 +1,15 @@ +// Booleans (`bool`) + +fn main() { + let is_morning = true; + if is_morning { + println!("Good morning!"); + } + + // TODO: Define a boolean variable with the name `is_evening` before the `if` statement below. + // The value of the variable should be the negation (opposite) of `is_morning`. + // let … + if is_evening { + println!("Good evening!"); + } +} diff --git a/exercises/primitive_types/primitive_types2.rs b/exercises/04_primitive_types/primitive_types2.rs similarity index 60% rename from exercises/primitive_types/primitive_types2.rs rename to exercises/04_primitive_types/primitive_types2.rs index 8730baab43..14018475dd 100644 --- a/exercises/primitive_types/primitive_types2.rs +++ b/exercises/04_primitive_types/primitive_types2.rs @@ -1,12 +1,6 @@ -// primitive_types2.rs -// Fill in the rest of the line that has code missing! -// No hints, there's no tricks, just get used to typing these :) - -// I AM NOT DONE +// Characters (`char`) fn main() { - // Characters (`char`) - // Note the _single_ quotes, these are different from the double quotes // you've been seeing around. let my_first_initial = 'C'; @@ -18,9 +12,12 @@ fn main() { println!("Neither alphabetic nor numeric!"); } - let // Finish this line like the example! What's your favorite character? - // Try a letter, try a number, try a special character, try a character - // from a different language than your own, try an emoji! + // TODO: Analogous to the example before, declare a variable called `your_character` + // below with your favorite character. + // Try a letter, try a digit (in single quotes), try a special character, try a character + // from a different language than your own, try an emoji 😉 + // let your_character = ''; + if your_character.is_alphabetic() { println!("Alphabetical!"); } else if your_character.is_numeric() { diff --git a/exercises/04_primitive_types/primitive_types3.rs b/exercises/04_primitive_types/primitive_types3.rs new file mode 100644 index 0000000000..9b79c0cf2a --- /dev/null +++ b/exercises/04_primitive_types/primitive_types3.rs @@ -0,0 +1,11 @@ +fn main() { + // TODO: Create an array called `a` with at least 100 elements in it. + // let a = ??? + + if a.len() >= 100 { + println!("Wow, that's a big array!"); + } else { + println!("Meh, I eat arrays like that for breakfast."); + panic!("Array not big enough, more elements needed"); + } +} diff --git a/exercises/04_primitive_types/primitive_types4.rs b/exercises/04_primitive_types/primitive_types4.rs new file mode 100644 index 0000000000..16e4fd9321 --- /dev/null +++ b/exercises/04_primitive_types/primitive_types4.rs @@ -0,0 +1,16 @@ +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + #[test] + fn slice_out_of_array() { + let a = [1, 2, 3, 4, 5]; + + // TODO: Get a slice called `nice_slice` out of the array `a` so that the test passes. + // let nice_slice = ??? + + assert_eq!([2, 3, 4], nice_slice); + } +} diff --git a/exercises/04_primitive_types/primitive_types5.rs b/exercises/04_primitive_types/primitive_types5.rs new file mode 100644 index 0000000000..6e00ef51f8 --- /dev/null +++ b/exercises/04_primitive_types/primitive_types5.rs @@ -0,0 +1,8 @@ +fn main() { + let cat = ("Furry McFurson", 3.5); + + // TODO: Destructure the `cat` tuple in one statement so that the println works. + // let /* your pattern here */ = cat; + + println!("{name} is {age} years old"); +} diff --git a/exercises/04_primitive_types/primitive_types6.rs b/exercises/04_primitive_types/primitive_types6.rs new file mode 100644 index 0000000000..a97e53110e --- /dev/null +++ b/exercises/04_primitive_types/primitive_types6.rs @@ -0,0 +1,17 @@ +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + #[test] + fn indexing_tuple() { + let numbers = (1, 2, 3); + + // TODO: Use a tuple index to access the second element of `numbers` + // and assign it to a variable called `second`. + // let second = ???; + + assert_eq!(second, 2, "This is not the 2nd number in the tuple!"); + } +} diff --git a/exercises/vecs/README.md b/exercises/05_vecs/README.md similarity index 77% rename from exercises/vecs/README.md rename to exercises/05_vecs/README.md index ebe90bf310..e1b6128523 100644 --- a/exercises/vecs/README.md +++ b/exercises/05_vecs/README.md @@ -12,4 +12,6 @@ the other useful data structure, hash maps, later. ## Further information -- [Storing Lists of Values with Vectors](https://doc.rust-lang.org/stable/book/ch08-01-vectors.html) +- [Storing Lists of Values with Vectors](https://doc.rust-lang.org/book/ch08-01-vectors.html) +- [`iter_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.iter_mut) +- [`map`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.map) diff --git a/exercises/05_vecs/vecs1.rs b/exercises/05_vecs/vecs1.rs new file mode 100644 index 0000000000..68e1affaa7 --- /dev/null +++ b/exercises/05_vecs/vecs1.rs @@ -0,0 +1,24 @@ +fn array_and_vec() -> ([i32; 4], Vec) { + let a = [10, 20, 30, 40]; // Array + + // TODO: Create a vector called `v` which contains the exact same elements as in the array `a`. + // Use the vector macro. + // let v = ???; + + (a, v) +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_array_and_vec_similarity() { + let (a, v) = array_and_vec(); + assert_eq!(a, *v); + } +} diff --git a/exercises/05_vecs/vecs2.rs b/exercises/05_vecs/vecs2.rs new file mode 100644 index 0000000000..0c996266d8 --- /dev/null +++ b/exercises/05_vecs/vecs2.rs @@ -0,0 +1,26 @@ +fn vec_loop(input: &[i32]) -> Vec { + let mut output = Vec::new(); + + for element in input { + // TODO: Multiply each element in the `input` slice by 2 and push it to + // the `output` vector. + } + + output +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_vec_loop() { + let input = [2, 4, 6, 8, 10]; + let ans = vec_loop(&input); + assert_eq!(ans, [4, 8, 12, 16, 20]); + } +} diff --git a/exercises/move_semantics/README.md b/exercises/06_move_semantics/README.md similarity index 100% rename from exercises/move_semantics/README.md rename to exercises/06_move_semantics/README.md diff --git a/exercises/06_move_semantics/move_semantics1.rs b/exercises/06_move_semantics/move_semantics1.rs new file mode 100644 index 0000000000..4eb3d618ef --- /dev/null +++ b/exercises/06_move_semantics/move_semantics1.rs @@ -0,0 +1,24 @@ +// TODO: Fix the compiler error in this function. +fn fill_vec(vec: Vec) -> Vec { + let vec = vec; + + vec.push(88); + + vec +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn move_semantics1() { + let vec0 = vec![22, 44, 66]; + let vec1 = fill_vec(vec0); + assert_eq!(vec1, vec![22, 44, 66, 88]); + } +} diff --git a/exercises/06_move_semantics/move_semantics2.rs b/exercises/06_move_semantics/move_semantics2.rs new file mode 100644 index 0000000000..a3ab7a0f18 --- /dev/null +++ b/exercises/06_move_semantics/move_semantics2.rs @@ -0,0 +1,28 @@ +fn fill_vec(vec: Vec) -> Vec { + let mut vec = vec; + + vec.push(88); + + vec +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + // TODO: Make both vectors `vec0` and `vec1` accessible at the same time to + // fix the compiler error in the test. + #[test] + fn move_semantics2() { + let vec0 = vec![22, 44, 66]; + + let vec1 = fill_vec(vec0); + + assert_eq!(vec0, [22, 44, 66]); + assert_eq!(vec1, [22, 44, 66, 88]); + } +} diff --git a/exercises/06_move_semantics/move_semantics3.rs b/exercises/06_move_semantics/move_semantics3.rs new file mode 100644 index 0000000000..11dbbbebff --- /dev/null +++ b/exercises/06_move_semantics/move_semantics3.rs @@ -0,0 +1,22 @@ +// TODO: Fix the compiler error in the function without adding any new line. +fn fill_vec(vec: Vec) -> Vec { + vec.push(88); + + vec +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn move_semantics3() { + let vec0 = vec![22, 44, 66]; + let vec1 = fill_vec(vec0); + assert_eq!(vec1, [22, 44, 66, 88]); + } +} diff --git a/exercises/06_move_semantics/move_semantics4.rs b/exercises/06_move_semantics/move_semantics4.rs new file mode 100644 index 0000000000..56da988cd4 --- /dev/null +++ b/exercises/06_move_semantics/move_semantics4.rs @@ -0,0 +1,18 @@ +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + // TODO: Fix the compiler errors only by reordering the lines in the test. + // Don't add, change or remove any line. + #[test] + fn move_semantics4() { + let mut x = Vec::new(); + let y = &mut x; + let z = &mut x; + y.push(42); + z.push(13); + assert_eq!(x, [42, 13]); + } +} diff --git a/exercises/06_move_semantics/move_semantics5.rs b/exercises/06_move_semantics/move_semantics5.rs new file mode 100644 index 0000000000..cd0dafd08d --- /dev/null +++ b/exercises/06_move_semantics/move_semantics5.rs @@ -0,0 +1,24 @@ +#![allow(clippy::ptr_arg)] + +// TODO: Fix the compiler errors without changing anything except adding or +// removing references (the character `&`). + +// Shouldn't take ownership +fn get_char(data: String) -> char { + data.chars().last().unwrap() +} + +// Should take ownership +fn string_uppercase(mut data: &String) { + data = data.to_uppercase(); + + println!("{data}"); +} + +fn main() { + let data = "Rust is great!".to_string(); + + get_char(data); + + string_uppercase(&data); +} diff --git a/exercises/structs/README.md b/exercises/07_structs/README.md similarity index 100% rename from exercises/structs/README.md rename to exercises/07_structs/README.md diff --git a/exercises/07_structs/structs1.rs b/exercises/07_structs/structs1.rs new file mode 100644 index 0000000000..959c4c6a68 --- /dev/null +++ b/exercises/07_structs/structs1.rs @@ -0,0 +1,47 @@ +struct ColorRegularStruct { + // TODO: Add the fields that the test `regular_structs` expects. + // What types should the fields have? What are the minimum and maximum values for RGB colors? +} + +struct ColorTupleStruct(/* TODO: Add the fields that the test `tuple_structs` expects */); + +#[derive(Debug)] +struct UnitStruct; + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn regular_structs() { + // TODO: Instantiate a regular struct. + // let green = + + assert_eq!(green.red, 0); + assert_eq!(green.green, 255); + assert_eq!(green.blue, 0); + } + + #[test] + fn tuple_structs() { + // TODO: Instantiate a tuple struct. + // let green = + + assert_eq!(green.0, 0); + assert_eq!(green.1, 255); + assert_eq!(green.2, 0); + } + + #[test] + fn unit_structs() { + // TODO: Instantiate a unit struct. + // let unit_struct = + let message = format!("{unit_struct:?}s are fun!"); + + assert_eq!(message, "UnitStructs are fun!"); + } +} diff --git a/exercises/structs/structs2.rs b/exercises/07_structs/structs2.rs similarity index 87% rename from exercises/structs/structs2.rs rename to exercises/07_structs/structs2.rs index 32e311fa9a..79141af95d 100644 --- a/exercises/structs/structs2.rs +++ b/exercises/07_structs/structs2.rs @@ -1,9 +1,3 @@ -// structs2.rs -// Address all the TODOs to make the tests pass! -// Execute `rustlings hint structs2` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - #[derive(Debug)] struct Order { name: String, @@ -27,6 +21,10 @@ fn create_order_template() -> Order { } } +fn main() { + // You can optionally experiment here. +} + #[cfg(test)] mod tests { use super::*; @@ -34,8 +32,10 @@ mod tests { #[test] fn your_order() { let order_template = create_order_template(); + // TODO: Create your own order using the update syntax and template above! // let your_order = + assert_eq!(your_order.name, "Hacker in Rust"); assert_eq!(your_order.year, order_template.year); assert_eq!(your_order.made_by_phone, order_template.made_by_phone); diff --git a/exercises/07_structs/structs3.rs b/exercises/07_structs/structs3.rs new file mode 100644 index 0000000000..69e5ced7f8 --- /dev/null +++ b/exercises/07_structs/structs3.rs @@ -0,0 +1,87 @@ +// Structs contain data, but can also have logic. In this exercise, we have +// defined the `Package` struct, and we want to test some logic attached to it. + +#[derive(Debug)] +struct Package { + sender_country: String, + recipient_country: String, + weight_in_grams: u32, +} + +impl Package { + fn new(sender_country: String, recipient_country: String, weight_in_grams: u32) -> Self { + if weight_in_grams < 10 { + // This isn't how you should handle errors in Rust, but we will + // learn about error handling later. + panic!("Can't ship a package with weight below 10 grams"); + } + + Self { + sender_country, + recipient_country, + weight_in_grams, + } + } + + // TODO: Add the correct return type to the function signature. + fn is_international(&self) { + // TODO: Read the tests that use this method to find out when a package + // is considered international. + } + + // TODO: Add the correct return type to the function signature. + fn get_fees(&self, cents_per_gram: u32) { + // TODO: Calculate the package's fees. + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[should_panic] + fn fail_creating_weightless_package() { + let sender_country = String::from("Spain"); + let recipient_country = String::from("Austria"); + + Package::new(sender_country, recipient_country, 5); + } + + #[test] + fn create_international_package() { + let sender_country = String::from("Spain"); + let recipient_country = String::from("Russia"); + + let package = Package::new(sender_country, recipient_country, 1200); + + assert!(package.is_international()); + } + + #[test] + fn create_local_package() { + let sender_country = String::from("Canada"); + let recipient_country = sender_country.clone(); + + let package = Package::new(sender_country, recipient_country, 1200); + + assert!(!package.is_international()); + } + + #[test] + fn calculate_transport_fees() { + let sender_country = String::from("Spain"); + let recipient_country = String::from("Spain"); + + let cents_per_gram = 3; + + let package = Package::new(sender_country, recipient_country, 1500); + + assert_eq!(package.get_fees(cents_per_gram), 4500); + assert_eq!(package.get_fees(cents_per_gram * 2), 9000); + } +} diff --git a/exercises/enums/README.md b/exercises/08_enums/README.md similarity index 67% rename from exercises/enums/README.md rename to exercises/08_enums/README.md index 30d4d91db2..b05cb42260 100644 --- a/exercises/enums/README.md +++ b/exercises/08_enums/README.md @@ -1,10 +1,10 @@ # Enums Rust allows you to define types called "enums" which enumerate possible values. -Enums are a feature in many languages, but their capabilities differ in each language. Rust’s enums are most similar to algebraic data types in functional languages, such as F#, OCaml, and Haskell. +Enums are a feature in many languages, but their capabilities differ in each language. Rust's enums are most similar to algebraic data types in functional languages, such as F#, OCaml, and Haskell. Useful in combination with enums is Rust's "pattern matching" facility, which makes it easy to run different code for different values of an enumeration. ## Further information - [Enums](https://doc.rust-lang.org/book/ch06-00-enums.html) -- [Pattern syntax](https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html) +- [Pattern syntax](https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html) diff --git a/exercises/enums/enums1.rs b/exercises/08_enums/enums1.rs similarity index 63% rename from exercises/enums/enums1.rs rename to exercises/08_enums/enums1.rs index 511ba740e2..c0d0c308d2 100644 --- a/exercises/enums/enums1.rs +++ b/exercises/08_enums/enums1.rs @@ -1,16 +1,12 @@ -// enums1.rs -// No hints this time! ;) - -// I AM NOT DONE - #[derive(Debug)] enum Message { - // TODO: define a few types of messages as used below + // TODO: Define a few types of messages as used below. } fn main() { - println!("{:?}", Message::Quit); - println!("{:?}", Message::Echo); + println!("{:?}", Message::Resize); println!("{:?}", Message::Move); + println!("{:?}", Message::Echo); println!("{:?}", Message::ChangeColor); + println!("{:?}", Message::Quit); } diff --git a/exercises/enums/enums2.rs b/exercises/08_enums/enums2.rs similarity index 52% rename from exercises/enums/enums2.rs rename to exercises/08_enums/enums2.rs index 18479f874d..d70f6398d1 100644 --- a/exercises/enums/enums2.rs +++ b/exercises/08_enums/enums2.rs @@ -1,22 +1,27 @@ -// enums2.rs -// Execute `rustlings hint enums2` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE +#[derive(Debug)] +struct Point { + x: u64, + y: u64, +} #[derive(Debug)] enum Message { - // TODO: define the different variants used below + // TODO: Define the different variants used below. } impl Message { fn call(&self) { - println!("{:?}", &self); + println!("{self:?}"); } } fn main() { let messages = [ - Message::Move { x: 10, y: 30 }, + Message::Resize { + width: 10, + height: 30, + }, + Message::Move(Point { x: 10, y: 15 }), Message::Echo(String::from("hello world")), Message::ChangeColor(200, 255, 255), Message::Quit, diff --git a/exercises/08_enums/enums3.rs b/exercises/08_enums/enums3.rs new file mode 100644 index 0000000000..cb05f657c2 --- /dev/null +++ b/exercises/08_enums/enums3.rs @@ -0,0 +1,88 @@ +struct Point { + x: u64, + y: u64, +} + +enum Message { + Resize { width: u64, height: u64 }, + Move(Point), + Echo(String), + ChangeColor(u8, u8, u8), + Quit, +} + +struct State { + width: u64, + height: u64, + position: Point, + message: String, + // RGB color composed of red, green and blue. + color: (u8, u8, u8), + quit: bool, +} + +impl State { + fn resize(&mut self, width: u64, height: u64) { + self.width = width; + self.height = height; + } + + fn move_position(&mut self, point: Point) { + self.position = point; + } + + fn echo(&mut self, s: String) { + self.message = s; + } + + fn change_color(&mut self, red: u8, green: u8, blue: u8) { + self.color = (red, green, blue); + } + + fn quit(&mut self) { + self.quit = true; + } + + fn process(&mut self, message: Message) { + // TODO: Create a match expression to process the different message + // variants using the methods defined above. + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_match_message_call() { + let mut state = State { + width: 0, + height: 0, + position: Point { x: 0, y: 0 }, + message: String::from("hello world"), + color: (0, 0, 0), + quit: false, + }; + + state.process(Message::Resize { + width: 10, + height: 30, + }); + state.process(Message::Move(Point { x: 10, y: 15 })); + state.process(Message::Echo(String::from("Hello world!"))); + state.process(Message::ChangeColor(255, 0, 255)); + state.process(Message::Quit); + + assert_eq!(state.width, 10); + assert_eq!(state.height, 30); + assert_eq!(state.position.x, 10); + assert_eq!(state.position.y, 15); + assert_eq!(state.message, "Hello world!"); + assert_eq!(state.color, (255, 0, 255)); + assert!(state.quit); + } +} diff --git a/exercises/strings/README.md b/exercises/09_strings/README.md similarity index 79% rename from exercises/strings/README.md rename to exercises/09_strings/README.md index fa2104cc37..a3d22f03d1 100644 --- a/exercises/strings/README.md +++ b/exercises/09_strings/README.md @@ -1,6 +1,6 @@ # Strings -Rust has two string types, a string slice (`&str`) and an owned string (`String`). +Rust has two string types: a string slice (`&str`) and an owned string (`String`). We're not going to dictate when you should use which one, but we'll show you how to identify and create them, as well as use them. diff --git a/exercises/09_strings/strings1.rs b/exercises/09_strings/strings1.rs new file mode 100644 index 0000000000..6abdbb48f0 --- /dev/null +++ b/exercises/09_strings/strings1.rs @@ -0,0 +1,9 @@ +// TODO: Fix the compiler error without changing the function signature. +fn current_favorite_color() -> String { + "blue" +} + +fn main() { + let answer = current_favorite_color(); + println!("My current favorite color is {answer}"); +} diff --git a/exercises/strings/strings2.rs b/exercises/09_strings/strings2.rs similarity index 53% rename from exercises/strings/strings2.rs rename to exercises/09_strings/strings2.rs index 0c48ec959d..93d9cb6b7f 100644 --- a/exercises/strings/strings2.rs +++ b/exercises/09_strings/strings2.rs @@ -1,18 +1,14 @@ -// strings2.rs -// Make me compile without changing the function signature! -// Execute `rustlings hint strings2` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE +// TODO: Fix the compiler error in the `main` function without changing this function. +fn is_a_color_word(attempt: &str) -> bool { + attempt == "green" || attempt == "blue" || attempt == "red" +} fn main() { - let word = String::from("green"); // Try not changing this line :) + let word = String::from("green"); // Don't change this line. + if is_a_color_word(word) { println!("That is a color word I know!"); } else { println!("That is not a color word I know."); } } - -fn is_a_color_word(attempt: &str) -> bool { - attempt == "green" || attempt == "blue" || attempt == "red" -} diff --git a/exercises/09_strings/strings3.rs b/exercises/09_strings/strings3.rs new file mode 100644 index 0000000000..f5e45b0ffc --- /dev/null +++ b/exercises/09_strings/strings3.rs @@ -0,0 +1,46 @@ +fn trim_me(input: &str) -> &str { + // TODO: Remove whitespace from both ends of a string. +} + +fn compose_me(input: &str) -> String { + // TODO: Add " world!" to the string! There are multiple ways to do this. +} + +fn replace_me(input: &str) -> String { + // TODO: Replace "cars" in the string with "balloons". +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn trim_a_string() { + assert_eq!(trim_me("Hello! "), "Hello!"); + assert_eq!(trim_me(" What's up!"), "What's up!"); + assert_eq!(trim_me(" Hola! "), "Hola!"); + assert_eq!(trim_me("Hi!"), "Hi!"); + } + + #[test] + fn compose_a_string() { + assert_eq!(compose_me("Hello"), "Hello world!"); + assert_eq!(compose_me("Goodbye"), "Goodbye world!"); + } + + #[test] + fn replace_a_string() { + assert_eq!( + replace_me("I think cars are cool"), + "I think balloons are cool", + ); + assert_eq!( + replace_me("I love to look at cars"), + "I love to look at balloons", + ); + } +} diff --git a/exercises/09_strings/strings4.rs b/exercises/09_strings/strings4.rs new file mode 100644 index 0000000000..473072636d --- /dev/null +++ b/exercises/09_strings/strings4.rs @@ -0,0 +1,37 @@ +// Calls of this function should be replaced with calls of `string_slice` or `string`. +fn placeholder() {} + +fn string_slice(arg: &str) { + println!("{arg}"); +} + +fn string(arg: String) { + println!("{arg}"); +} + +// TODO: Here are a bunch of values - some are `String`, some are `&str`. +// Your task is to replace `placeholder(…)` with either `string_slice(…)` +// or `string(…)` depending on what you think each value is. +fn main() { + placeholder("blue"); + + placeholder("red".to_string()); + + placeholder(String::from("hi")); + + placeholder("rust is fun!".to_owned()); + + placeholder("nice weather".into()); + + placeholder(format!("Interpolation {}", "Station")); + + // WARNING: This is byte indexing, not character indexing. + // Character indexing can be done using `s.chars().nth(INDEX)`. + placeholder(&String::from("abc")[0..1]); + + placeholder(" hello there ".trim()); + + placeholder("Happy Monday!".replace("Mon", "Tues")); + + placeholder("mY sHiFt KeY iS sTiCkY".to_lowercase()); +} diff --git a/exercises/modules/README.md b/exercises/10_modules/README.md similarity index 100% rename from exercises/modules/README.md rename to exercises/10_modules/README.md diff --git a/exercises/modules/modules1.rs b/exercises/10_modules/modules1.rs similarity index 71% rename from exercises/modules/modules1.rs rename to exercises/10_modules/modules1.rs index 8dd0e40229..d97ab23a53 100644 --- a/exercises/modules/modules1.rs +++ b/exercises/10_modules/modules1.rs @@ -1,8 +1,4 @@ -// modules1.rs -// Execute `rustlings hint modules1` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - +// TODO: Fix the compiler error about calling a private function. mod sausage_factory { // Don't let anybody outside of this module see this! fn get_secret_recipe() -> String { diff --git a/exercises/10_modules/modules2.rs b/exercises/10_modules/modules2.rs new file mode 100644 index 0000000000..782a70eace --- /dev/null +++ b/exercises/10_modules/modules2.rs @@ -0,0 +1,26 @@ +// You can bring module paths into scopes and provide new names for them with +// the `use` and `as` keywords. + +mod delicious_snacks { + // TODO: Add the following two `use` statements after fixing them. + // use self::fruits::PEAR as ???; + // use self::veggies::CUCUMBER as ???; + + mod fruits { + pub const PEAR: &str = "Pear"; + pub const APPLE: &str = "Apple"; + } + + mod veggies { + pub const CUCUMBER: &str = "Cucumber"; + pub const CARROT: &str = "Carrot"; + } +} + +fn main() { + println!( + "favorite snacks: {} and {}", + delicious_snacks::fruit, + delicious_snacks::veggie, + ); +} diff --git a/exercises/10_modules/modules3.rs b/exercises/10_modules/modules3.rs new file mode 100644 index 0000000000..691608d275 --- /dev/null +++ b/exercises/10_modules/modules3.rs @@ -0,0 +1,13 @@ +// You can use the `use` keyword to bring module paths from modules from +// anywhere and especially from the standard library into your scope. + +// TODO: Bring `SystemTime` and `UNIX_EPOCH` from the `std::time` module into +// your scope. Bonus style points if you can do it with one line! +// use ???; + +fn main() { + match SystemTime::now().duration_since(UNIX_EPOCH) { + Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()), + Err(_) => panic!("SystemTime before UNIX EPOCH!"), + } +} diff --git a/exercises/hashmaps/README.md b/exercises/11_hashmaps/README.md similarity index 89% rename from exercises/hashmaps/README.md rename to exercises/11_hashmaps/README.md index 30471cf967..80ec14416e 100644 --- a/exercises/hashmaps/README.md +++ b/exercises/11_hashmaps/README.md @@ -1,6 +1,7 @@ # Hashmaps + A *hash map* allows you to associate a value with a particular key. -You may also know this by the names [*unordered map* in C++](https://en.cppreference.com/w/cpp/container/unordered_map), +You may also know this by the names [*unordered map* in C++](https://en.cppreference.com/w/cpp/container/unordered_map), [*dictionary* in Python](https://docs.python.org/3/tutorial/datastructures.html#dictionaries) or an *associative array* in other languages. This is the other data structure that we've been talking about before, when diff --git a/exercises/hashmaps/hashmaps1.rs b/exercises/11_hashmaps/hashmaps1.rs similarity index 50% rename from exercises/hashmaps/hashmaps1.rs rename to exercises/11_hashmaps/hashmaps1.rs index fd8dd2f82c..74001d0432 100644 --- a/exercises/hashmaps/hashmaps1.rs +++ b/exercises/11_hashmaps/hashmaps1.rs @@ -1,30 +1,27 @@ -// hashmaps1.rs -// A basket of fruits in the form of a hash map needs to be defined. -// The key represents the name of the fruit and the value represents -// how many of that particular fruit is in the basket. You have to put -// at least three different types of fruits (e.g apple, banana, mango) -// in the basket and the total count of all the fruits should be at -// least five. -// -// Make me compile and pass the tests! -// -// Execute `rustlings hint hashmaps1` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE +// A basket of fruits in the form of a hash map needs to be defined. The key +// represents the name of the fruit and the value represents how many of that +// particular fruit is in the basket. You have to put at least 3 different +// types of fruits (e.g. apple, banana, mango) in the basket and the total count +// of all the fruits should be at least 5. use std::collections::HashMap; fn fruit_basket() -> HashMap { - let mut basket = // TODO: declare your hash map here. + // TODO: Declare the hash map. + // let mut basket = // Two bananas are already given for you :) basket.insert(String::from("banana"), 2); - // TODO: Put more fruits in your basket here. + // TODO: Put more fruits in your basket. basket } +fn main() { + // You can optionally experiment here. +} + #[cfg(test)] mod tests { use super::*; diff --git a/exercises/11_hashmaps/hashmaps2.rs b/exercises/11_hashmaps/hashmaps2.rs new file mode 100644 index 0000000000..e9f53fea3c --- /dev/null +++ b/exercises/11_hashmaps/hashmaps2.rs @@ -0,0 +1,97 @@ +// We're collecting different fruits to bake a delicious fruit cake. For this, +// we have a basket, which we'll represent in the form of a hash map. The key +// represents the name of each fruit we collect and the value represents how +// many of that particular fruit we have collected. Three types of fruits - +// Apple (4), Mango (2) and Lychee (5) are already in the basket hash map. You +// must add fruit to the basket so that there is at least one of each kind and +// more than 11 in total - we have a lot of mouths to feed. You are not allowed +// to insert any more of the fruits that are already in the basket (Apple, +// Mango, and Lychee). + +use std::collections::HashMap; + +#[derive(Hash, PartialEq, Eq, Debug)] +enum Fruit { + Apple, + Banana, + Mango, + Lychee, + Pineapple, +} + +fn fruit_basket(basket: &mut HashMap) { + let fruit_kinds = [ + Fruit::Apple, + Fruit::Banana, + Fruit::Mango, + Fruit::Lychee, + Fruit::Pineapple, + ]; + + for fruit in fruit_kinds { + // TODO: Insert new fruits if they are not already present in the + // basket. Note that you are not allowed to put any type of fruit that's + // already present! + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + // Don't modify this function! + fn get_fruit_basket() -> HashMap { + let content = [(Fruit::Apple, 4), (Fruit::Mango, 2), (Fruit::Lychee, 5)]; + HashMap::from_iter(content) + } + + #[test] + fn test_given_fruits_are_not_modified() { + let mut basket = get_fruit_basket(); + fruit_basket(&mut basket); + assert_eq!(*basket.get(&Fruit::Apple).unwrap(), 4); + assert_eq!(*basket.get(&Fruit::Mango).unwrap(), 2); + assert_eq!(*basket.get(&Fruit::Lychee).unwrap(), 5); + } + + #[test] + fn at_least_five_types_of_fruits() { + let mut basket = get_fruit_basket(); + fruit_basket(&mut basket); + let count_fruit_kinds = basket.len(); + assert!(count_fruit_kinds >= 5); + } + + #[test] + fn greater_than_eleven_fruits() { + let mut basket = get_fruit_basket(); + fruit_basket(&mut basket); + let count = basket.values().sum::(); + assert!(count > 11); + } + + #[test] + fn all_fruit_types_in_basket() { + let fruit_kinds = [ + Fruit::Apple, + Fruit::Banana, + Fruit::Mango, + Fruit::Lychee, + Fruit::Pineapple, + ]; + + let mut basket = get_fruit_basket(); + fruit_basket(&mut basket); + + for fruit_kind in fruit_kinds { + let Some(amount) = basket.get(&fruit_kind) else { + panic!("Fruit kind {fruit_kind:?} was not found in basket"); + }; + assert!(*amount > 0); + } + } +} diff --git a/exercises/11_hashmaps/hashmaps3.rs b/exercises/11_hashmaps/hashmaps3.rs new file mode 100644 index 0000000000..5b390ab9b8 --- /dev/null +++ b/exercises/11_hashmaps/hashmaps3.rs @@ -0,0 +1,77 @@ +// A list of scores (one per line) of a soccer match is given. Each line is of +// the form ",,," +// Example: "England,France,4,2" (England scored 4 goals, France 2). +// +// You have to build a scores table containing the name of the team, the total +// number of goals the team scored, and the total number of goals the team +// conceded. + +use std::collections::HashMap; + +// A structure to store the goal details of a team. +#[derive(Default)] +struct TeamScores { + goals_scored: u8, + goals_conceded: u8, +} + +fn build_scores_table(results: &str) -> HashMap<&str, TeamScores> { + // The name of the team is the key and its associated struct is the value. + let mut scores = HashMap::<&str, TeamScores>::new(); + + for line in results.lines() { + let mut split_iterator = line.split(','); + // NOTE: We use `unwrap` because we didn't deal with error handling yet. + let team_1_name = split_iterator.next().unwrap(); + let team_2_name = split_iterator.next().unwrap(); + let team_1_score: u8 = split_iterator.next().unwrap().parse().unwrap(); + let team_2_score: u8 = split_iterator.next().unwrap().parse().unwrap(); + + // TODO: Populate the scores table with the extracted details. + // Keep in mind that goals scored by team 1 will be the number of goals + // conceded by team 2. Similarly, goals scored by team 2 will be the + // number of goals conceded by team 1. + } + + scores +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + const RESULTS: &str = "England,France,4,2 +France,Italy,3,1 +Poland,Spain,2,0 +Germany,England,2,1 +England,Spain,1,0"; + + #[test] + fn build_scores() { + let scores = build_scores_table(RESULTS); + + assert!(["England", "France", "Germany", "Italy", "Poland", "Spain"] + .into_iter() + .all(|team_name| scores.contains_key(team_name))); + } + + #[test] + fn validate_team_score_1() { + let scores = build_scores_table(RESULTS); + let team = scores.get("England").unwrap(); + assert_eq!(team.goals_scored, 6); + assert_eq!(team.goals_conceded, 4); + } + + #[test] + fn validate_team_score_2() { + let scores = build_scores_table(RESULTS); + let team = scores.get("Spain").unwrap(); + assert_eq!(team.goals_scored, 0); + assert_eq!(team.goals_conceded, 3); + } +} diff --git a/exercises/options/README.md b/exercises/12_options/README.md similarity index 84% rename from exercises/options/README.md rename to exercises/12_options/README.md index 6140a16779..624572a3bc 100644 --- a/exercises/options/README.md +++ b/exercises/12_options/README.md @@ -1,7 +1,8 @@ # Options -Type Option represents an optional value: every Option is either Some and contains a value, or None, and does not. +Type Option represents an optional value: every Option is either Some and contains a value, or None, and does not. Option types are very common in Rust code, as they have a number of uses: + - Initial values - Return values for functions that are not defined over their entire input range (partial functions) - Return value for otherwise reporting simple errors, where None is returned on error @@ -13,7 +14,7 @@ Option types are very common in Rust code, as they have a number of uses: ## Further Information -- [Option Enum Format](https://doc.rust-lang.org/stable/book/ch10-01-syntax.html#in-enum-definitions) +- [Option Enum Format](https://doc.rust-lang.org/book/ch10-01-syntax.html#in-enum-definitions) - [Option Module Documentation](https://doc.rust-lang.org/std/option/) - [Option Enum Documentation](https://doc.rust-lang.org/std/option/enum.Option.html) - [if let](https://doc.rust-lang.org/rust-by-example/flow_control/if_let.html) diff --git a/exercises/12_options/options1.rs b/exercises/12_options/options1.rs new file mode 100644 index 0000000000..d0c412a8d4 --- /dev/null +++ b/exercises/12_options/options1.rs @@ -0,0 +1,36 @@ +// This function returns how much ice cream there is left in the fridge. +// If it's before 22:00 (24-hour system), then 5 scoops are left. At 22:00, +// someone eats it all, so no ice cream is left (value 0). Return `None` if +// `hour_of_day` is higher than 23. +fn maybe_ice_cream(hour_of_day: u16) -> Option { + // TODO: Complete the function body. +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn raw_value() { + // TODO: Fix this test. How do you get the value contained in the + // Option? + let ice_creams = maybe_ice_cream(12); + + assert_eq!(ice_creams, 5); // Don't change this line. + } + + #[test] + fn check_ice_cream() { + assert_eq!(maybe_ice_cream(0), Some(5)); + assert_eq!(maybe_ice_cream(9), Some(5)); + assert_eq!(maybe_ice_cream(18), Some(5)); + assert_eq!(maybe_ice_cream(22), Some(0)); + assert_eq!(maybe_ice_cream(23), Some(0)); + assert_eq!(maybe_ice_cream(24), None); + assert_eq!(maybe_ice_cream(25), None); + } +} diff --git a/exercises/12_options/options2.rs b/exercises/12_options/options2.rs new file mode 100644 index 0000000000..07c27c6ec2 --- /dev/null +++ b/exercises/12_options/options2.rs @@ -0,0 +1,39 @@ +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + #[test] + fn simple_option() { + let target = "rustlings"; + let optional_target = Some(target); + + // TODO: Make this an if-let statement whose value is `Some`. + word = optional_target { + assert_eq!(word, target); + } + } + + #[test] + fn layered_option() { + let range = 10; + let mut optional_integers: Vec> = vec![None]; + + for i in 1..=range { + optional_integers.push(Some(i)); + } + + let mut cursor = range; + + // TODO: Make this a while-let statement. Remember that `Vec::pop()` + // adds another layer of `Option`. You can do nested pattern matching + // in if-let and while-let statements. + integer = optional_integers.pop() { + assert_eq!(integer, cursor); + cursor -= 1; + } + + assert_eq!(cursor, 0); + } +} diff --git a/exercises/12_options/options3.rs b/exercises/12_options/options3.rs new file mode 100644 index 0000000000..c97b1d3cf4 --- /dev/null +++ b/exercises/12_options/options3.rs @@ -0,0 +1,17 @@ +#[derive(Debug)] +struct Point { + x: i32, + y: i32, +} + +fn main() { + let optional_point = Some(Point { x: 100, y: 200 }); + + // TODO: Fix the compiler error by adding something to this match statement. + match optional_point { + Some(p) => println!("Coordinates are {},{}", p.x, p.y), + _ => panic!("No match!"), + } + + println!("{optional_point:?}"); // Don't change this line. +} diff --git a/exercises/error_handling/README.md b/exercises/13_error_handling/README.md similarity index 61% rename from exercises/error_handling/README.md rename to exercises/13_error_handling/README.md index 5255ace99e..9b6674bc7a 100644 --- a/exercises/error_handling/README.md +++ b/exercises/13_error_handling/README.md @@ -1,7 +1,8 @@ # Error handling -Most errors aren’t serious enough to require the program to stop entirely. -Sometimes, when a function fails, it’s for a reason that you can easily interpret and respond to. -For example, if you try to open a file and that operation fails because the file doesn’t exist, you might want to create the file instead of terminating the process. + +Most errors aren't serious enough to require the program to stop entirely. +Sometimes, when a function fails, it's for a reason that you can easily interpret and respond to. +For example, if you try to open a file and that operation fails because the file doesn't exist, you might want to create the file instead of terminating the process. ## Further information diff --git a/exercises/13_error_handling/errors1.rs b/exercises/13_error_handling/errors1.rs new file mode 100644 index 0000000000..e07fddc3cd --- /dev/null +++ b/exercises/13_error_handling/errors1.rs @@ -0,0 +1,41 @@ +// TODO: This function refuses to generate text to be printed on a nametag if +// you pass it an empty string. It'd be nicer if it explained what the problem +// was instead of just returning `None`. Thankfully, Rust has a similar +// construct to `Option` that can be used to express error conditions. Change +// the function signature and body to return `Result` instead +// of `Option`. +fn generate_nametag_text(name: String) -> Option { + if name.is_empty() { + // Empty names aren't allowed + None + } else { + Some(format!("Hi! My name is {name}")) + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn generates_nametag_text_for_a_nonempty_name() { + assert_eq!( + generate_nametag_text("Beyoncé".to_string()).as_deref(), + Ok("Hi! My name is Beyoncé"), + ); + } + + #[test] + fn explains_why_generating_nametag_text_fails() { + assert_eq!( + generate_nametag_text(String::new()) + .as_ref() + .map_err(|e| e.as_str()), + Err("Empty names aren't allowed"), + ); + } +} diff --git a/exercises/error_handling/errors2.rs b/exercises/13_error_handling/errors2.rs similarity index 51% rename from exercises/error_handling/errors2.rs rename to exercises/13_error_handling/errors2.rs index 1cd8fc66b0..defe359b48 100644 --- a/exercises/error_handling/errors2.rs +++ b/exercises/13_error_handling/errors2.rs @@ -1,37 +1,39 @@ -// errors2.rs // Say we're writing a game where you can buy items with tokens. All items cost // 5 tokens, and whenever you purchase items there is a processing fee of 1 -// token. A player of the game will type in how many items they want to buy, -// and the `total_cost` function will calculate the total number of tokens. -// Since the player typed in the quantity, though, we get it as a string-- and -// they might have typed anything, not just numbers! - -// Right now, this function isn't handling the error case at all (and isn't -// handling the success case properly either). What we want to do is: -// if we call the `parse` function on a string that is not a number, that -// function will return a `ParseIntError`, and in that case, we want to -// immediately return that error from our function and not try to multiply -// and add. - -// There are at least two ways to implement this that are both correct-- but -// one is a lot shorter! -// Execute `rustlings hint errors2` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE +// token. A player of the game will type in how many items they want to buy, and +// the `total_cost` function will calculate the total cost of the items. Since +// the player typed in the quantity, we get it as a string. They might have +// typed anything, not just numbers! +// +// Right now, this function isn't handling the error case at all. What we want +// to do is: If we call the `total_cost` function on a string that is not a +// number, that function will return a `ParseIntError`. In that case, we want to +// immediately return that error from our function and not try to multiply and +// add. +// +// There are at least two ways to implement this that are both correct. But one +// is a lot shorter! use std::num::ParseIntError; -pub fn total_cost(item_quantity: &str) -> Result { +fn total_cost(item_quantity: &str) -> Result { let processing_fee = 1; let cost_per_item = 5; + + // TODO: Handle the error case as described above. let qty = item_quantity.parse::(); Ok(qty * cost_per_item + processing_fee) } +fn main() { + // You can optionally experiment here. +} + #[cfg(test)] mod tests { use super::*; + use std::num::IntErrorKind; #[test] fn item_quantity_is_a_valid_number() { @@ -41,8 +43,8 @@ mod tests { #[test] fn item_quantity_is_an_invalid_number() { assert_eq!( - total_cost("beep boop").unwrap_err().to_string(), - "invalid digit found in string" + total_cost("beep boop").unwrap_err().kind(), + &IntErrorKind::InvalidDigit, ); } } diff --git a/exercises/error_handling/errors3.rs b/exercises/13_error_handling/errors3.rs similarity index 68% rename from exercises/error_handling/errors3.rs rename to exercises/13_error_handling/errors3.rs index a2d2d1901d..8e8c38a2a1 100644 --- a/exercises/error_handling/errors3.rs +++ b/exercises/13_error_handling/errors3.rs @@ -1,31 +1,31 @@ -// errors3.rs // This is a program that is trying to use a completed version of the // `total_cost` function from the previous exercise. It's not working though! // Why not? What should we do to fix it? -// Execute `rustlings hint errors3` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE use std::num::ParseIntError; +// Don't change this function. +fn total_cost(item_quantity: &str) -> Result { + let processing_fee = 1; + let cost_per_item = 5; + let qty = item_quantity.parse::()?; + + Ok(qty * cost_per_item + processing_fee) +} + +// TODO: Fix the compiler error by changing the signature and body of the +// `main` function. fn main() { let mut tokens = 100; let pretend_user_input = "8"; + // Don't change this line. let cost = total_cost(pretend_user_input)?; if cost > tokens { println!("You can't afford that many!"); } else { tokens -= cost; - println!("You now have {} tokens.", tokens); + println!("You now have {tokens} tokens."); } } - -pub fn total_cost(item_quantity: &str) -> Result { - let processing_fee = 1; - let cost_per_item = 5; - let qty = item_quantity.parse::()?; - - Ok(qty * cost_per_item + processing_fee) -} diff --git a/exercises/13_error_handling/errors4.rs b/exercises/13_error_handling/errors4.rs new file mode 100644 index 0000000000..144fce7b22 --- /dev/null +++ b/exercises/13_error_handling/errors4.rs @@ -0,0 +1,38 @@ +#[derive(PartialEq, Debug)] +enum CreationError { + Negative, + Zero, +} + +#[derive(PartialEq, Debug)] +struct PositiveNonzeroInteger(u64); + +impl PositiveNonzeroInteger { + fn new(value: i64) -> Result { + // TODO: This function shouldn't always return an `Ok`. + // Read the tests below to clarify what should be returned. + Ok(Self(value as u64)) + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_creation() { + assert_eq!( + PositiveNonzeroInteger::new(10), + Ok(PositiveNonzeroInteger(10)), + ); + assert_eq!( + PositiveNonzeroInteger::new(-10), + Err(CreationError::Negative), + ); + assert_eq!(PositiveNonzeroInteger::new(0), Err(CreationError::Zero)); + } +} diff --git a/exercises/13_error_handling/errors5.rs b/exercises/13_error_handling/errors5.rs new file mode 100644 index 0000000000..125779b867 --- /dev/null +++ b/exercises/13_error_handling/errors5.rs @@ -0,0 +1,56 @@ +// This exercise is an altered version of the `errors4` exercise. It uses some +// concepts that we won't get to until later in the course, like `Box` and the +// `From` trait. It's not important to understand them in detail right now, but +// you can read ahead if you like. For now, think of the `Box` type as +// an "I want anything that does ???" type. +// +// In short, this particular use case for boxes is for when you want to own a +// value and you care only that it is a type which implements a particular +// trait. To do so, the `Box` is declared as of type `Box` where +// `Trait` is the trait the compiler looks for on any value used in that +// context. For this exercise, that context is the potential errors which +// can be returned in a `Result`. + +use std::error::Error; +use std::fmt; + +#[derive(PartialEq, Debug)] +enum CreationError { + Negative, + Zero, +} + +// This is required so that `CreationError` can implement `Error`. +impl fmt::Display for CreationError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let description = match *self { + CreationError::Negative => "number is negative", + CreationError::Zero => "number is zero", + }; + f.write_str(description) + } +} + +impl Error for CreationError {} + +#[derive(PartialEq, Debug)] +struct PositiveNonzeroInteger(u64); + +impl PositiveNonzeroInteger { + fn new(value: i64) -> Result { + match value { + x if x < 0 => Err(CreationError::Negative), + 0 => Err(CreationError::Zero), + x => Ok(PositiveNonzeroInteger(x as u64)), + } + } +} + +// TODO: Add the correct return type `Result<(), Box>`. What can we +// use to describe both errors? Is there a trait which both errors implement? +fn main() { + let pretend_user_input = "42"; + let x: i64 = pretend_user_input.parse()?; + println!("output={:?}", PositiveNonzeroInteger::new(x)?); + Ok(()) +} diff --git a/exercises/13_error_handling/errors6.rs b/exercises/13_error_handling/errors6.rs new file mode 100644 index 0000000000..b1995e036a --- /dev/null +++ b/exercises/13_error_handling/errors6.rs @@ -0,0 +1,89 @@ +// Using catch-all error types like `Box` isn't recommended for +// library code where callers might want to make decisions based on the error +// content instead of printing it out or propagating it further. Here, we define +// a custom error type to make it possible for callers to decide what to do next +// when our function returns an error. + +use std::num::ParseIntError; + +#[derive(PartialEq, Debug)] +enum CreationError { + Negative, + Zero, +} + +// A custom error type that we will be using in `PositiveNonzeroInteger::parse`. +#[derive(PartialEq, Debug)] +enum ParsePosNonzeroError { + Creation(CreationError), + ParseInt(ParseIntError), +} + +impl ParsePosNonzeroError { + fn from_creation(err: CreationError) -> Self { + Self::Creation(err) + } + + // TODO: Add another error conversion function here. + // fn from_parse_int(???) -> Self { ??? } +} + +#[derive(PartialEq, Debug)] +struct PositiveNonzeroInteger(u64); + +impl PositiveNonzeroInteger { + fn new(value: i64) -> Result { + match value { + x if x < 0 => Err(CreationError::Negative), + 0 => Err(CreationError::Zero), + x => Ok(Self(x as u64)), + } + } + + fn parse(s: &str) -> Result { + // TODO: change this to return an appropriate error instead of panicking + // when `parse()` returns an error. + let x: i64 = s.parse().unwrap(); + Self::new(x).map_err(ParsePosNonzeroError::from_creation) + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_parse_error() { + assert!(matches!( + PositiveNonzeroInteger::parse("not a number"), + Err(ParsePosNonzeroError::ParseInt(_)), + )); + } + + #[test] + fn test_negative() { + assert_eq!( + PositiveNonzeroInteger::parse("-555"), + Err(ParsePosNonzeroError::Creation(CreationError::Negative)), + ); + } + + #[test] + fn test_zero() { + assert_eq!( + PositiveNonzeroInteger::parse("0"), + Err(ParsePosNonzeroError::Creation(CreationError::Zero)), + ); + } + + #[test] + fn test_positive() { + let x = PositiveNonzeroInteger::new(42).unwrap(); + assert_eq!(x.0, 42); + assert_eq!(PositiveNonzeroInteger::parse("42"), Ok(x)); + } +} diff --git a/exercises/generics/README.md b/exercises/14_generics/README.md similarity index 77% rename from exercises/generics/README.md rename to exercises/14_generics/README.md index de46d5034a..0c8c8cb1aa 100644 --- a/exercises/generics/README.md +++ b/exercises/14_generics/README.md @@ -1,11 +1,11 @@ # Generics Generics is the topic of generalizing types and functionalities to broader cases. -This is extremely useful for reducing code duplication in many ways, but can call for rather involving syntax. +This is extremely useful for reducing code duplication in many ways, but can call for some rather involved syntax. Namely, being generic requires taking great care to specify over which types a generic type is actually considered valid. The simplest and most common use of generics is for type parameters. ## Further information -- [Generic Data Types](https://doc.rust-lang.org/stable/book/ch10-01-syntax.html) +- [Generic Data Types](https://doc.rust-lang.org/book/ch10-01-syntax.html) - [Bounds](https://doc.rust-lang.org/rust-by-example/generics/bounds.html) diff --git a/exercises/14_generics/generics1.rs b/exercises/14_generics/generics1.rs new file mode 100644 index 0000000000..87ed990b65 --- /dev/null +++ b/exercises/14_generics/generics1.rs @@ -0,0 +1,18 @@ +// `Vec` is generic over the type `T`. In most cases, the compiler is able to +// infer `T`, for example after pushing a value with a concrete type to the vector. +// But in this exercise, the compiler needs some help through a type annotation. + +fn main() { + // TODO: Fix the compiler error by annotating the type of the vector + // `Vec`. Choose `T` as some integer type that can be created from + // `u8` and `i8`. + let mut numbers = Vec::new(); + + // Don't change the lines below. + let n1: u8 = 42; + numbers.push(n1.into()); + let n2: i8 = -1; + numbers.push(n2.into()); + + println!("{numbers:?}"); +} diff --git a/exercises/generics/generics2.rs b/exercises/14_generics/generics2.rs similarity index 62% rename from exercises/generics/generics2.rs rename to exercises/14_generics/generics2.rs index aedbd55c94..8908725bf9 100644 --- a/exercises/generics/generics2.rs +++ b/exercises/14_generics/generics2.rs @@ -1,20 +1,20 @@ // This powerful wrapper provides the ability to store a positive integer value. -// Rewrite it using generics so that it supports wrapping ANY type. - -// Execute `rustlings hint generics2` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - +// TODO: Rewrite it using a generic so that it supports wrapping ANY type. struct Wrapper { value: u32, } +// TODO: Adapt the struct's implementation to be generic over the wrapped value. impl Wrapper { - pub fn new(value: u32) -> Self { + fn new(value: u32) -> Self { Wrapper { value } } } +fn main() { + // You can optionally experiment here. +} + #[cfg(test)] mod tests { use super::*; diff --git a/exercises/traits/README.md b/exercises/15_traits/README.md similarity index 100% rename from exercises/traits/README.md rename to exercises/15_traits/README.md index de67acd060..ac87c64ebc 100644 --- a/exercises/traits/README.md +++ b/exercises/15_traits/README.md @@ -7,13 +7,13 @@ Data types can implement traits. To do so, the methods making up the trait are d In this way, traits are somewhat similar to Java interfaces and C++ abstract classes. Some additional common Rust traits include: + - `Clone` (the `clone` method) - `Display` (which allows formatted display via `{}`) - `Debug` (which allows formatted display via `{:?}`) Because traits indicate shared behavior between data types, they are useful when writing generics. - ## Further information - [Traits](https://doc.rust-lang.org/book/ch10-02-traits.html) diff --git a/exercises/15_traits/traits1.rs b/exercises/15_traits/traits1.rs new file mode 100644 index 0000000000..85be17ea82 --- /dev/null +++ b/exercises/15_traits/traits1.rs @@ -0,0 +1,30 @@ +// The trait `AppendBar` has only one function which appends "Bar" to any object +// implementing this trait. +trait AppendBar { + fn append_bar(self) -> Self; +} + +impl AppendBar for String { + // TODO: Implement `AppendBar` for the type `String`. +} + +fn main() { + let s = String::from("Foo"); + let s = s.append_bar(); + println!("s: {s}"); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn is_foo_bar() { + assert_eq!(String::from("Foo").append_bar(), "FooBar"); + } + + #[test] + fn is_bar_bar() { + assert_eq!(String::from("").append_bar().append_bar(), "BarBar"); + } +} diff --git a/exercises/15_traits/traits2.rs b/exercises/15_traits/traits2.rs new file mode 100644 index 0000000000..d724dc288e --- /dev/null +++ b/exercises/15_traits/traits2.rs @@ -0,0 +1,22 @@ +trait AppendBar { + fn append_bar(self) -> Self; +} + +// TODO: Implement the trait `AppendBar` for a vector of strings. +// `append_bar` should push the string "Bar" into the vector. + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn is_vec_pop_eq_bar() { + let mut foo = vec![String::from("Foo")].append_bar(); + assert_eq!(foo.pop().unwrap(), "Bar"); + assert_eq!(foo.pop().unwrap(), "Foo"); + } +} diff --git a/exercises/traits/traits3.rs b/exercises/15_traits/traits3.rs similarity index 51% rename from exercises/traits/traits3.rs rename to exercises/15_traits/traits3.rs index 6d2fd6c379..c244650da6 100644 --- a/exercises/traits/traits3.rs +++ b/exercises/15_traits/traits3.rs @@ -1,15 +1,8 @@ -// traits3.rs -// -// Your task is to implement the Licensed trait for -// both structures and have them return the same -// information without writing the same function twice. -// -// Consider what you can add to the Licensed trait. -// Execute `rustlings hint traits3` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -pub trait Licensed { +trait Licensed { + // TODO: Add a default implementation for `licensing_info` so that + // implementors like the two structs below can share that default behavior + // without repeating the function. + // The default license information should be the string "Default license". fn licensing_info(&self) -> String; } @@ -21,8 +14,12 @@ struct OtherSoftware { version_number: String, } -impl Licensed for SomeSoftware {} // Don't edit this line -impl Licensed for OtherSoftware {} // Don't edit this line +impl Licensed for SomeSoftware {} // Don't edit this line. +impl Licensed for OtherSoftware {} // Don't edit this line. + +fn main() { + // You can optionally experiment here. +} #[cfg(test)] mod tests { @@ -30,7 +27,7 @@ mod tests { #[test] fn is_licensing_info_the_same() { - let licensing_info = String::from("Some information"); + let licensing_info = "Default license"; let some_software = SomeSoftware { version_number: 1 }; let other_software = OtherSoftware { version_number: "v2.0.0".to_string(), diff --git a/exercises/15_traits/traits4.rs b/exercises/15_traits/traits4.rs new file mode 100644 index 0000000000..80092a6466 --- /dev/null +++ b/exercises/15_traits/traits4.rs @@ -0,0 +1,35 @@ +trait Licensed { + fn licensing_info(&self) -> String { + "Default license".to_string() + } +} + +struct SomeSoftware; +struct OtherSoftware; + +impl Licensed for SomeSoftware {} +impl Licensed for OtherSoftware {} + +// TODO: Fix the compiler error by only changing the signature of this function. +fn compare_license_types(software1: ???, software2: ???) -> bool { + software1.licensing_info() == software2.licensing_info() +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn compare_license_information() { + assert!(compare_license_types(SomeSoftware, OtherSoftware)); + } + + #[test] + fn compare_license_information_backwards() { + assert!(compare_license_types(OtherSoftware, SomeSoftware)); + } +} diff --git a/exercises/15_traits/traits5.rs b/exercises/15_traits/traits5.rs new file mode 100644 index 0000000000..5b356ac738 --- /dev/null +++ b/exercises/15_traits/traits5.rs @@ -0,0 +1,39 @@ +trait SomeTrait { + fn some_function(&self) -> bool { + true + } +} + +trait OtherTrait { + fn other_function(&self) -> bool { + true + } +} + +struct SomeStruct; +impl SomeTrait for SomeStruct {} +impl OtherTrait for SomeStruct {} + +struct OtherStruct; +impl SomeTrait for OtherStruct {} +impl OtherTrait for OtherStruct {} + +// TODO: Fix the compiler error by only changing the signature of this function. +fn some_func(item: ???) -> bool { + item.some_function() && item.other_function() +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_some_func() { + assert!(some_func(SomeStruct)); + assert!(some_func(OtherStruct)); + } +} diff --git a/exercises/lifetimes/README.md b/exercises/16_lifetimes/README.md similarity index 69% rename from exercises/lifetimes/README.md rename to exercises/16_lifetimes/README.md index 72befb3eab..91373f733a 100644 --- a/exercises/lifetimes/README.md +++ b/exercises/16_lifetimes/README.md @@ -3,15 +3,20 @@ Lifetimes tell the compiler how to check whether references live long enough to be valid in any given situation. For example lifetimes say "make sure parameter 'a' lives as long as parameter 'b' so that the return -value is valid". +value is valid". -They are only necessary on borrows, i.e. references, +They are only necessary on borrows, i.e. references, since copied parameters or moves are owned in their scope and cannot be referenced outside. Lifetimes mean that calling code of e.g. functions -can be checked to make sure their arguments are valid. Lifetimes are +can be checked to make sure their arguments are valid. Lifetimes are restrictive of their callers. +If you'd like to learn more about lifetime annotations, the +[lifetimekata](https://tfpk.github.io/lifetimekata/) project +has a similar style of exercises to Rustlings, but is all about +learning to write lifetime annotations. + ## Further information -- [Validating References with Lifetimes](https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html) - [Lifetimes (in Rust By Example)](https://doc.rust-lang.org/stable/rust-by-example/scope/lifetime.html) +- [Validating References with Lifetimes](https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html) diff --git a/exercises/16_lifetimes/lifetimes1.rs b/exercises/16_lifetimes/lifetimes1.rs new file mode 100644 index 0000000000..19e2d398b5 --- /dev/null +++ b/exercises/16_lifetimes/lifetimes1.rs @@ -0,0 +1,28 @@ +// The Rust compiler needs to know how to check whether supplied references are +// valid, so that it can let the programmer know if a reference is at risk of +// going out of scope before it is used. Remember, references are borrows and do +// not own their own data. What if their owner goes out of scope? + +// TODO: Fix the compiler error by updating the function signature. +fn longest(x: &str, y: &str) -> &str { + if x.len() > y.len() { + x + } else { + y + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_longest() { + assert_eq!(longest("abcd", "123"), "abcd"); + assert_eq!(longest("abc", "1234"), "1234"); + } +} diff --git a/exercises/16_lifetimes/lifetimes2.rs b/exercises/16_lifetimes/lifetimes2.rs new file mode 100644 index 0000000000..de5a5dfc79 --- /dev/null +++ b/exercises/16_lifetimes/lifetimes2.rs @@ -0,0 +1,20 @@ +// Don't change this function. +fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { + if x.len() > y.len() { + x + } else { + y + } +} + +fn main() { + // TODO: Fix the compiler error by moving one line. + + let string1 = String::from("long string is long"); + let result; + { + let string2 = String::from("xyz"); + result = longest(&string1, &string2); + } + println!("The longest string is '{result}'"); +} diff --git a/exercises/16_lifetimes/lifetimes3.rs b/exercises/16_lifetimes/lifetimes3.rs new file mode 100644 index 0000000000..1cc27592c6 --- /dev/null +++ b/exercises/16_lifetimes/lifetimes3.rs @@ -0,0 +1,16 @@ +// Lifetimes are also needed when structs hold references. + +// TODO: Fix the compiler errors about the struct. +struct Book { + author: &str, + title: &str, +} + +fn main() { + let book = Book { + author: "George Orwell", + title: "1984", + }; + + println!("{} by {}", book.title, book.author); +} diff --git a/exercises/tests/README.md b/exercises/17_tests/README.md similarity index 100% rename from exercises/tests/README.md rename to exercises/17_tests/README.md diff --git a/exercises/17_tests/tests1.rs b/exercises/17_tests/tests1.rs new file mode 100644 index 0000000000..7529f9f049 --- /dev/null +++ b/exercises/17_tests/tests1.rs @@ -0,0 +1,23 @@ +// Tests are important to ensure that your code does what you think it should +// do. + +fn is_even(n: i64) -> bool { + n % 2 == 0 +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + // TODO: Import `is_even`. You can use a wildcard to import everything in + // the outer module. + + #[test] + fn you_can_assert() { + // TODO: Test the function `is_even` with some values. + assert!(); + assert!(); + } +} diff --git a/exercises/17_tests/tests2.rs b/exercises/17_tests/tests2.rs new file mode 100644 index 0000000000..0c6573e8f0 --- /dev/null +++ b/exercises/17_tests/tests2.rs @@ -0,0 +1,23 @@ +// Calculates the power of 2 using a bit shift. +// `1 << n` is equivalent to "2 to the power of n". +fn power_of_2(n: u8) -> u64 { + 1 << n +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn you_can_assert_eq() { + // TODO: Test the function `power_of_2` with some values. + assert_eq!(); + assert_eq!(); + assert_eq!(); + assert_eq!(); + } +} diff --git a/exercises/17_tests/tests3.rs b/exercises/17_tests/tests3.rs new file mode 100644 index 0000000000..822184ef75 --- /dev/null +++ b/exercises/17_tests/tests3.rs @@ -0,0 +1,49 @@ +struct Rectangle { + width: i32, + height: i32, +} + +impl Rectangle { + // Don't change this function. + fn new(width: i32, height: i32) -> Self { + if width <= 0 || height <= 0 { + // Returning a `Result` would be better here. But we want to learn + // how to test functions that can panic. + panic!("Rectangle width and height must be positive"); + } + + Rectangle { width, height } + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn correct_width_and_height() { + // TODO: This test should check if the rectangle has the size that we + // pass to its constructor. + let rect = Rectangle::new(10, 20); + assert_eq!(todo!(), 10); // Check width + assert_eq!(todo!(), 20); // Check height + } + + // TODO: This test should check if the program panics when we try to create + // a rectangle with negative width. + #[test] + fn negative_width() { + let _rect = Rectangle::new(-10, 10); + } + + // TODO: This test should check if the program panics when we try to create + // a rectangle with negative height. + #[test] + fn negative_height() { + let _rect = Rectangle::new(10, -10); + } +} diff --git a/exercises/18_iterators/README.md b/exercises/18_iterators/README.md new file mode 100644 index 0000000000..0e8b671e44 --- /dev/null +++ b/exercises/18_iterators/README.md @@ -0,0 +1,8 @@ +# Iterators + +This section will teach you about Iterators. + +## Further information + +- [Iterator](https://doc.rust-lang.org/book/ch13-02-iterators.html) +- [Iterator documentation](https://doc.rust-lang.org/stable/std/iter/) diff --git a/exercises/18_iterators/iterators1.rs b/exercises/18_iterators/iterators1.rs new file mode 100644 index 0000000000..ca937ed00e --- /dev/null +++ b/exercises/18_iterators/iterators1.rs @@ -0,0 +1,25 @@ +// When performing operations on elements within a collection, iterators are +// essential. This module helps you get familiar with the structure of using an +// iterator and how to go through elements within an iterable collection. + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + #[test] + fn iterators() { + let my_fav_fruits = ["banana", "custard apple", "avocado", "peach", "raspberry"]; + + // TODO: Create an iterator over the array. + let mut fav_fruits_iterator = todo!(); + + assert_eq!(fav_fruits_iterator.next(), Some(&"banana")); + assert_eq!(fav_fruits_iterator.next(), todo!()); // TODO: Replace `todo!()` + assert_eq!(fav_fruits_iterator.next(), Some(&"avocado")); + assert_eq!(fav_fruits_iterator.next(), todo!()); // TODO: Replace `todo!()` + assert_eq!(fav_fruits_iterator.next(), Some(&"raspberry")); + assert_eq!(fav_fruits_iterator.next(), todo!()); // TODO: Replace `todo!()` + } +} diff --git a/exercises/18_iterators/iterators2.rs b/exercises/18_iterators/iterators2.rs new file mode 100644 index 0000000000..5903e657e9 --- /dev/null +++ b/exercises/18_iterators/iterators2.rs @@ -0,0 +1,57 @@ +// In this exercise, you'll learn some of the unique advantages that iterators +// can offer. + +// TODO: Complete the `capitalize_first` function. +// "hello" -> "Hello" +fn capitalize_first(input: &str) -> String { + let mut chars = input.chars(); + match chars.next() { + None => String::new(), + Some(first) => todo!(), + } +} + +// TODO: Apply the `capitalize_first` function to a slice of string slices. +// Return a vector of strings. +// ["hello", "world"] -> ["Hello", "World"] +fn capitalize_words_vector(words: &[&str]) -> Vec { + // ??? +} + +// TODO: Apply the `capitalize_first` function again to a slice of string +// slices. Return a single string. +// ["hello", " ", "world"] -> "Hello World" +fn capitalize_words_string(words: &[&str]) -> String { + // ??? +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_success() { + assert_eq!(capitalize_first("hello"), "Hello"); + } + + #[test] + fn test_empty() { + assert_eq!(capitalize_first(""), ""); + } + + #[test] + fn test_iterate_string_vec() { + let words = vec!["hello", "world"]; + assert_eq!(capitalize_words_vector(&words), ["Hello", "World"]); + } + + #[test] + fn test_iterate_into_string() { + let words = vec!["hello", " ", "world"]; + assert_eq!(capitalize_words_string(&words), "Hello World"); + } +} diff --git a/exercises/18_iterators/iterators3.rs b/exercises/18_iterators/iterators3.rs new file mode 100644 index 0000000000..dce09055dd --- /dev/null +++ b/exercises/18_iterators/iterators3.rs @@ -0,0 +1,75 @@ +#[derive(Debug, PartialEq, Eq)] +enum DivisionError { + // Example: 42 / 0 + DivideByZero, + // Only case for `i64`: `i64::MIN / -1` because the result is `i64::MAX + 1` + IntegerOverflow, + // Example: 5 / 2 = 2.5 + NotDivisible, +} + +// TODO: Calculate `a` divided by `b` if `a` is evenly divisible by `b`. +// Otherwise, return a suitable error. +fn divide(a: i64, b: i64) -> Result { + todo!(); +} + +// TODO: Add the correct return type and complete the function body. +// Desired output: `Ok([1, 11, 1426, 3])` +fn result_with_list() { + let numbers = [27, 297, 38502, 81]; + let division_results = numbers.into_iter().map(|n| divide(n, 27)); +} + +// TODO: Add the correct return type and complete the function body. +// Desired output: `[Ok(1), Ok(11), Ok(1426), Ok(3)]` +fn list_of_results() { + let numbers = [27, 297, 38502, 81]; + let division_results = numbers.into_iter().map(|n| divide(n, 27)); +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_success() { + assert_eq!(divide(81, 9), Ok(9)); + assert_eq!(divide(81, -1), Ok(-81)); + assert_eq!(divide(i64::MIN, i64::MIN), Ok(1)); + } + + #[test] + fn test_divide_by_0() { + assert_eq!(divide(81, 0), Err(DivisionError::DivideByZero)); + } + + #[test] + fn test_integer_overflow() { + assert_eq!(divide(i64::MIN, -1), Err(DivisionError::IntegerOverflow)); + } + + #[test] + fn test_not_divisible() { + assert_eq!(divide(81, 6), Err(DivisionError::NotDivisible)); + } + + #[test] + fn test_divide_0_by_something() { + assert_eq!(divide(0, 81), Ok(0)); + } + + #[test] + fn test_result_with_list() { + assert_eq!(result_with_list().unwrap(), [1, 11, 1426, 3]); + } + + #[test] + fn test_list_of_results() { + assert_eq!(list_of_results(), [Ok(1), Ok(11), Ok(1426), Ok(3)]); + } +} diff --git a/exercises/18_iterators/iterators4.rs b/exercises/18_iterators/iterators4.rs new file mode 100644 index 0000000000..c296f0e426 --- /dev/null +++ b/exercises/18_iterators/iterators4.rs @@ -0,0 +1,41 @@ +fn factorial(num: u64) -> u64 { + // TODO: Complete this function to return the factorial of `num` which is + // defined as `1 * 2 * 3 * … * num`. + // https://en.wikipedia.org/wiki/Factorial + // + // Do not use: + // - early returns (using the `return` keyword explicitly) + // Try not to use: + // - imperative style loops (for/while) + // - additional variables + // For an extra challenge, don't use: + // - recursion +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn factorial_of_0() { + assert_eq!(factorial(0), 1); + } + + #[test] + fn factorial_of_1() { + assert_eq!(factorial(1), 1); + } + #[test] + fn factorial_of_2() { + assert_eq!(factorial(2), 2); + } + + #[test] + fn factorial_of_4() { + assert_eq!(factorial(4), 24); + } +} diff --git a/exercises/standard_library_types/iterators5.rs b/exercises/18_iterators/iterators5.rs similarity index 52% rename from exercises/standard_library_types/iterators5.rs rename to exercises/18_iterators/iterators5.rs index 0593d1231b..7e434cc5f9 100644 --- a/exercises/standard_library_types/iterators5.rs +++ b/exercises/18_iterators/iterators5.rs @@ -1,16 +1,8 @@ -// iterators5.rs -// Let's define a simple model to track Rustlings exercise progress. Progress +// Let's define a simple model to track Rustlings' exercise progress. Progress // will be modelled using a hash map. The name of the exercise is the key and // the progress is the value. Two counting functions were created to count the -// number of exercises with a given progress. These counting functions use -// imperative style for loops. Recreate this counting functionality using -// iterators. Only the two iterator methods (count_iterator and -// count_collection_iterator) need to be modified. -// Execute `rustlings hint iterators5` or use the `hint` watch subcommand for a hint. -// -// Make the code compile and the tests pass. - -// I AM NOT DONE +// number of exercises with a given progress. Recreate this counting +// functionality using iterators. Try to not use imperative loops (for/while). use std::collections::HashMap; @@ -24,24 +16,25 @@ enum Progress { fn count_for(map: &HashMap, value: Progress) -> usize { let mut count = 0; for val in map.values() { - if val == &value { + if *val == value { count += 1; } } count } +// TODO: Implement the functionality of `count_for` but with an iterator instead +// of a `for` loop. fn count_iterator(map: &HashMap, value: Progress) -> usize { - // map is a hashmap with String keys and Progress values. - // map = { "variables1": Complete, "from_str": None, ... } - todo!(); + // `map` is a hash map with `String` keys and `Progress` values. + // map = { "variables1": Complete, "from_str": None, … } } fn count_collection_for(collection: &[HashMap], value: Progress) -> usize { let mut count = 0; for map in collection { for val in map.values() { - if val == &value { + if *val == value { count += 1; } } @@ -49,50 +42,22 @@ fn count_collection_for(collection: &[HashMap], value: Progres count } +// TODO: Implement the functionality of `count_collection_for` but with an +// iterator instead of a `for` loop. fn count_collection_iterator(collection: &[HashMap], value: Progress) -> usize { - // collection is a slice of hashmaps. - // collection = [{ "variables1": Complete, "from_str": None, ... }, - // { "variables2": Complete, ... }, ... ] - todo!(); + // `collection` is a slice of hash maps. + // collection = [{ "variables1": Complete, "from_str": None, … }, + // { "variables2": Complete, … }, … ] +} + +fn main() { + // You can optionally experiment here. } #[cfg(test)] mod tests { use super::*; - #[test] - fn count_complete() { - let map = get_map(); - assert_eq!(3, count_iterator(&map, Progress::Complete)); - } - - #[test] - fn count_equals_for() { - let map = get_map(); - assert_eq!( - count_for(&map, Progress::Complete), - count_iterator(&map, Progress::Complete) - ); - } - - #[test] - fn count_collection_complete() { - let collection = get_vec_map(); - assert_eq!( - 6, - count_collection_iterator(&collection, Progress::Complete) - ); - } - - #[test] - fn count_collection_equals_for() { - let collection = get_vec_map(); - assert_eq!( - count_collection_for(&collection, Progress::Complete), - count_collection_iterator(&collection, Progress::Complete) - ); - } - fn get_map() -> HashMap { use Progress::*; @@ -121,4 +86,68 @@ mod tests { vec![map, other] } + + #[test] + fn count_complete() { + let map = get_map(); + assert_eq!(count_iterator(&map, Progress::Complete), 3); + } + + #[test] + fn count_some() { + let map = get_map(); + assert_eq!(count_iterator(&map, Progress::Some), 1); + } + + #[test] + fn count_none() { + let map = get_map(); + assert_eq!(count_iterator(&map, Progress::None), 2); + } + + #[test] + fn count_complete_equals_for() { + let map = get_map(); + let progress_states = [Progress::Complete, Progress::Some, Progress::None]; + for progress_state in progress_states { + assert_eq!( + count_for(&map, progress_state), + count_iterator(&map, progress_state), + ); + } + } + + #[test] + fn count_collection_complete() { + let collection = get_vec_map(); + assert_eq!( + count_collection_iterator(&collection, Progress::Complete), + 6, + ); + } + + #[test] + fn count_collection_some() { + let collection = get_vec_map(); + assert_eq!(count_collection_iterator(&collection, Progress::Some), 1); + } + + #[test] + fn count_collection_none() { + let collection = get_vec_map(); + assert_eq!(count_collection_iterator(&collection, Progress::None), 4); + } + + #[test] + fn count_collection_equals_for() { + let collection = get_vec_map(); + let progress_states = [Progress::Complete, Progress::Some, Progress::None]; + + for progress_state in progress_states { + assert_eq!( + count_collection_for(&collection, progress_state), + count_collection_iterator(&collection, progress_state), + ); + } + } } diff --git a/exercises/19_smart_pointers/README.md b/exercises/19_smart_pointers/README.md new file mode 100644 index 0000000000..d56d2b6281 --- /dev/null +++ b/exercises/19_smart_pointers/README.md @@ -0,0 +1,12 @@ +# Smart Pointers + +In Rust, smart pointers are variables that contain an address in memory and reference some other data, but they also have additional metadata and capabilities. +Smart pointers in Rust often own the data they point to, while references only borrow data. + +## Further Information + +- [Smart Pointers](https://doc.rust-lang.org/book/ch15-00-smart-pointers.html) +- [Using Box to Point to Data on the Heap](https://doc.rust-lang.org/book/ch15-01-box.html) +- [Rc\, the Reference Counted Smart Pointer](https://doc.rust-lang.org/book/ch15-04-rc.html) +- [Shared-State Concurrency](https://doc.rust-lang.org/book/ch16-03-shared-state.html) +- [Cow Documentation](https://doc.rust-lang.org/std/borrow/enum.Cow.html) diff --git a/exercises/19_smart_pointers/arc1.rs b/exercises/19_smart_pointers/arc1.rs new file mode 100644 index 0000000000..6bb860f93f --- /dev/null +++ b/exercises/19_smart_pointers/arc1.rs @@ -0,0 +1,45 @@ +// In this exercise, we are given a `Vec` of `u32` called `numbers` with values +// ranging from 0 to 99. We would like to use this set of numbers within 8 +// different threads simultaneously. Each thread is going to get the sum of +// every eighth value with an offset. +// +// The first thread (offset 0), will sum 0, 8, 16, … +// The second thread (offset 1), will sum 1, 9, 17, … +// The third thread (offset 2), will sum 2, 10, 18, … +// … +// The eighth thread (offset 7), will sum 7, 15, 23, … +// +// Each thread should own a reference-counting pointer to the vector of +// numbers. But `Rc` isn't thread-safe. Therefore, we need to use `Arc`. +// +// Don't get distracted by how threads are spawned and joined. We will practice +// that later in the exercises about threads. + +// Don't change the lines below. +#![forbid(unused_imports)] +use std::{sync::Arc, thread}; + +fn main() { + let numbers: Vec<_> = (0..100u32).collect(); + + // TODO: Define `shared_numbers` by using `Arc`. + // let shared_numbers = ???; + + let mut join_handles = Vec::new(); + + for offset in 0..8 { + // TODO: Define `child_numbers` using `shared_numbers`. + // let child_numbers = ???; + + let handle = thread::spawn(move || { + let sum: u32 = child_numbers.iter().filter(|&&n| n % 8 == offset).sum(); + println!("Sum of offset {offset} is {sum}"); + }); + + join_handles.push(handle); + } + + for handle in join_handles.into_iter() { + handle.join().unwrap(); + } +} diff --git a/exercises/19_smart_pointers/box1.rs b/exercises/19_smart_pointers/box1.rs new file mode 100644 index 0000000000..d70e1c3d39 --- /dev/null +++ b/exercises/19_smart_pointers/box1.rs @@ -0,0 +1,50 @@ +// At compile time, Rust needs to know how much space a type takes up. This +// becomes problematic for recursive types, where a value can have as part of +// itself another value of the same type. To get around the issue, we can use a +// `Box` - a smart pointer used to store data on the heap, which also allows us +// to wrap a recursive type. +// +// The recursive type we're implementing in this exercise is the "cons list", a +// data structure frequently found in functional programming languages. Each +// item in a cons list contains two elements: The value of the current item and +// the next item. The last item is a value called `Nil`. + +// TODO: Use a `Box` in the enum definition to make the code compile. +#[derive(PartialEq, Debug)] +enum List { + Cons(i32, List), + Nil, +} + +// TODO: Create an empty cons list. +fn create_empty_list() -> List { + todo!() +} + +// TODO: Create a non-empty cons list. +fn create_non_empty_list() -> List { + todo!() +} + +fn main() { + println!("This is an empty cons list: {:?}", create_empty_list()); + println!( + "This is a non-empty cons list: {:?}", + create_non_empty_list(), + ); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_create_empty_list() { + assert_eq!(create_empty_list(), List::Nil); + } + + #[test] + fn test_create_non_empty_list() { + assert_ne!(create_empty_list(), create_non_empty_list()); + } +} diff --git a/exercises/19_smart_pointers/cow1.rs b/exercises/19_smart_pointers/cow1.rs new file mode 100644 index 0000000000..1566500716 --- /dev/null +++ b/exercises/19_smart_pointers/cow1.rs @@ -0,0 +1,69 @@ +// This exercise explores the `Cow` (Clone-On-Write) smart pointer. It can +// enclose and provide immutable access to borrowed data and clone the data +// lazily when mutation or ownership is required. The type is designed to work +// with general borrowed data via the `Borrow` trait. + +use std::borrow::Cow; + +fn abs_all(input: &mut Cow<[i32]>) { + for ind in 0..input.len() { + let value = input[ind]; + if value < 0 { + // Clones into a vector if not already owned. + input.to_mut()[ind] = -value; + } + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reference_mutation() { + // Clone occurs because `input` needs to be mutated. + let vec = vec![-1, 0, 1]; + let mut input = Cow::from(&vec); + abs_all(&mut input); + assert!(matches!(input, Cow::Owned(_))); + } + + #[test] + fn reference_no_mutation() { + // No clone occurs because `input` doesn't need to be mutated. + let vec = vec![0, 1, 2]; + let mut input = Cow::from(&vec); + abs_all(&mut input); + // TODO: Replace `todo!()` with `Cow::Owned(_)` or `Cow::Borrowed(_)`. + assert!(matches!(input, todo!())); + } + + #[test] + fn owned_no_mutation() { + // We can also pass `vec` without `&` so `Cow` owns it directly. In this + // case, no mutation occurs (all numbers are already absolute) and thus + // also no clone. But the result is still owned because it was never + // borrowed or mutated. + let vec = vec![0, 1, 2]; + let mut input = Cow::from(vec); + abs_all(&mut input); + // TODO: Replace `todo!()` with `Cow::Owned(_)` or `Cow::Borrowed(_)`. + assert!(matches!(input, todo!())); + } + + #[test] + fn owned_mutation() { + // Of course this is also the case if a mutation does occur (not all + // numbers are absolute). In this case, the call to `to_mut()` in the + // `abs_all` function returns a reference to the same data as before. + let vec = vec![-1, 0, 1]; + let mut input = Cow::from(vec); + abs_all(&mut input); + // TODO: Replace `todo!()` with `Cow::Owned(_)` or `Cow::Borrowed(_)`. + assert!(matches!(input, todo!())); + } +} diff --git a/exercises/19_smart_pointers/rc1.rs b/exercises/19_smart_pointers/rc1.rs new file mode 100644 index 0000000000..ecd3438701 --- /dev/null +++ b/exercises/19_smart_pointers/rc1.rs @@ -0,0 +1,105 @@ +// In this exercise, we want to express the concept of multiple owners via the +// `Rc` type. This is a model of our solar system - there is a `Sun` type and +// multiple `Planet`s. The planets take ownership of the sun, indicating that +// they revolve around the sun. + +use std::rc::Rc; + +#[derive(Debug)] +struct Sun; + +#[derive(Debug)] +enum Planet { + Mercury(Rc), + Venus(Rc), + Earth(Rc), + Mars(Rc), + Jupiter(Rc), + Saturn(Rc), + Uranus(Rc), + Neptune(Rc), +} + +impl Planet { + fn details(&self) { + println!("Hi from {self:?}!"); + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rc1() { + let sun = Rc::new(Sun); + println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference + + let mercury = Planet::Mercury(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 2 references + mercury.details(); + + let venus = Planet::Venus(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 3 references + venus.details(); + + let earth = Planet::Earth(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 4 references + earth.details(); + + let mars = Planet::Mars(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 5 references + mars.details(); + + let jupiter = Planet::Jupiter(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 6 references + jupiter.details(); + + // TODO + let saturn = Planet::Saturn(Rc::new(Sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 7 references + saturn.details(); + + // TODO + let uranus = Planet::Uranus(Rc::new(Sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 8 references + uranus.details(); + + // TODO + let neptune = Planet::Neptune(Rc::new(Sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 9 references + neptune.details(); + + assert_eq!(Rc::strong_count(&sun), 9); + + drop(neptune); + println!("reference count = {}", Rc::strong_count(&sun)); // 8 references + + drop(uranus); + println!("reference count = {}", Rc::strong_count(&sun)); // 7 references + + drop(saturn); + println!("reference count = {}", Rc::strong_count(&sun)); // 6 references + + drop(jupiter); + println!("reference count = {}", Rc::strong_count(&sun)); // 5 references + + drop(mars); + println!("reference count = {}", Rc::strong_count(&sun)); // 4 references + + // TODO + println!("reference count = {}", Rc::strong_count(&sun)); // 3 references + + // TODO + println!("reference count = {}", Rc::strong_count(&sun)); // 2 references + + // TODO + println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference + + assert_eq!(Rc::strong_count(&sun), 1); + } +} diff --git a/exercises/threads/README.md b/exercises/20_threads/README.md similarity index 58% rename from exercises/threads/README.md rename to exercises/20_threads/README.md index d086694761..0b32fb1def 100644 --- a/exercises/threads/README.md +++ b/exercises/20_threads/README.md @@ -1,9 +1,10 @@ # Threads -In most current operating systems, an executed program’s code is run in a process, and the operating system manages multiple processes at once. +In most current operating systems, an executed program's code is run in a process, and the operating system manages multiple processes at once. Within your program, you can also have independent parts that run simultaneously. The features that run these independent parts are called threads. ## Further information - [Dining Philosophers example](https://doc.rust-lang.org/1.4.0/book/dining-philosophers.html) - [Using Threads to Run Code Simultaneously](https://doc.rust-lang.org/book/ch16-01-threads.html) +- [Using Message Passing to Transfer Data Between Threads](https://doc.rust-lang.org/book/ch16-02-message-passing.html) diff --git a/exercises/20_threads/threads1.rs b/exercises/20_threads/threads1.rs new file mode 100644 index 0000000000..dbc64b1644 --- /dev/null +++ b/exercises/20_threads/threads1.rs @@ -0,0 +1,37 @@ +// This program spawns multiple threads that each runs for at least 250ms, and +// each thread returns how much time it took to complete. The program should +// wait until all the spawned threads have finished and should collect their +// return values into a vector. + +use std::{ + thread, + time::{Duration, Instant}, +}; + +fn main() { + let mut handles = Vec::new(); + for i in 0..10 { + let handle = thread::spawn(move || { + let start = Instant::now(); + thread::sleep(Duration::from_millis(250)); + println!("Thread {i} done"); + start.elapsed().as_millis() + }); + handles.push(handle); + } + + let mut results = Vec::new(); + for handle in handles { + // TODO: Collect the results of all threads into the `results` vector. + // Use the `JoinHandle` struct which is returned by `thread::spawn`. + } + + if results.len() != 10 { + panic!("Oh no! Some thread isn't done yet!"); + } + + println!(); + for (i, result) in results.into_iter().enumerate() { + println!("Thread {i} took {result}ms"); + } +} diff --git a/exercises/20_threads/threads2.rs b/exercises/20_threads/threads2.rs new file mode 100644 index 0000000000..7020cb9cea --- /dev/null +++ b/exercises/20_threads/threads2.rs @@ -0,0 +1,34 @@ +// Building on the last exercise, we want all of the threads to complete their +// work. But this time, the spawned threads need to be in charge of updating a +// shared value: `JobStatus.jobs_done` + +use std::{sync::Arc, thread, time::Duration}; + +struct JobStatus { + jobs_done: u32, +} + +fn main() { + // TODO: `Arc` isn't enough if you want a **mutable** shared state. + let status = Arc::new(JobStatus { jobs_done: 0 }); + + let mut handles = Vec::new(); + for _ in 0..10 { + let status_shared = Arc::clone(&status); + let handle = thread::spawn(move || { + thread::sleep(Duration::from_millis(250)); + + // TODO: You must take an action before you update a shared value. + status_shared.jobs_done += 1; + }); + handles.push(handle); + } + + // Waiting for all jobs to complete. + for handle in handles { + handle.join().unwrap(); + } + + // TODO: Print the value of `JobStatus.jobs_done`. + println!("Jobs done: {}", todo!()); +} diff --git a/exercises/20_threads/threads3.rs b/exercises/20_threads/threads3.rs new file mode 100644 index 0000000000..6d16bd9fec --- /dev/null +++ b/exercises/20_threads/threads3.rs @@ -0,0 +1,60 @@ +use std::{sync::mpsc, thread, time::Duration}; + +struct Queue { + first_half: Vec, + second_half: Vec, +} + +impl Queue { + fn new() -> Self { + Self { + first_half: vec![1, 2, 3, 4, 5], + second_half: vec![6, 7, 8, 9, 10], + } + } +} + +fn send_tx(q: Queue, tx: mpsc::Sender) { + // TODO: We want to send `tx` to both threads. But currently, it is moved + // into the first thread. How could you solve this problem? + thread::spawn(move || { + for val in q.first_half { + println!("Sending {val:?}"); + tx.send(val).unwrap(); + thread::sleep(Duration::from_millis(250)); + } + }); + + thread::spawn(move || { + for val in q.second_half { + println!("Sending {val:?}"); + tx.send(val).unwrap(); + thread::sleep(Duration::from_millis(250)); + } + }); +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn threads3() { + let (tx, rx) = mpsc::channel(); + let queue = Queue::new(); + + send_tx(queue, tx); + + let mut received = Vec::with_capacity(10); + for value in rx { + received.push(value); + } + + received.sort(); + assert_eq!(received, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); + } +} diff --git a/exercises/21_macros/README.md b/exercises/21_macros/README.md new file mode 100644 index 0000000000..de7fb7ba3b --- /dev/null +++ b/exercises/21_macros/README.md @@ -0,0 +1,15 @@ +# Macros + +Rust's macro system is very powerful, but also kind of difficult to wrap your +head around. We're not going to teach you how to write your own fully-featured +macros. Instead, we'll show you how to use and create them. + +If you'd like to learn more about writing your own macros, the +[macrokata](https://github.com/tfpk/macrokata) project has a similar style +of exercises to Rustlings, but is all about learning to write Macros. + +## Further information + +- [The Rust Book - Macros](https://doc.rust-lang.org/book/ch20-05-macros.html) +- [The Little Book of Rust Macros](https://veykril.github.io/tlborm/) +- [Rust by Example - macro_rules!](https://doc.rust-lang.org/rust-by-example/macros.html) diff --git a/exercises/macros/macros1.rs b/exercises/21_macros/macros1.rs similarity index 50% rename from exercises/macros/macros1.rs rename to exercises/21_macros/macros1.rs index 634d0a7011..fb3c3ff9b3 100644 --- a/exercises/macros/macros1.rs +++ b/exercises/21_macros/macros1.rs @@ -1,8 +1,3 @@ -// macros1.rs -// Execute `rustlings hint macros1` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - macro_rules! my_macro { () => { println!("Check out my macro!"); @@ -10,5 +5,6 @@ macro_rules! my_macro { } fn main() { + // TODO: Fix the macro call. my_macro(); } diff --git a/exercises/macros/macros2.rs b/exercises/21_macros/macros2.rs similarity index 50% rename from exercises/macros/macros2.rs rename to exercises/21_macros/macros2.rs index f6092cab44..2d9dec76ca 100644 --- a/exercises/macros/macros2.rs +++ b/exercises/21_macros/macros2.rs @@ -1,12 +1,8 @@ -// macros2.rs -// Execute `rustlings hint macros2` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - fn main() { my_macro!(); } +// TODO: Fix the compiler error by moving the whole definition of this macro. macro_rules! my_macro { () => { println!("Check out my macro!"); diff --git a/exercises/21_macros/macros3.rs b/exercises/21_macros/macros3.rs new file mode 100644 index 0000000000..95374948be --- /dev/null +++ b/exercises/21_macros/macros3.rs @@ -0,0 +1,13 @@ +// TODO: Fix the compiler error without taking the macro definition out of this +// module. +mod macros { + macro_rules! my_macro { + () => { + println!("Check out my macro!"); + }; + } +} + +fn main() { + my_macro!(); +} diff --git a/exercises/macros/macros4.rs b/exercises/21_macros/macros4.rs similarity index 65% rename from exercises/macros/macros4.rs rename to exercises/21_macros/macros4.rs index c1fc5e8b16..9d77f6a5c8 100644 --- a/exercises/macros/macros4.rs +++ b/exercises/21_macros/macros4.rs @@ -1,8 +1,5 @@ -// macros4.rs -// Execute `rustlings hint macros4` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - +// TODO: Fix the compiler error by adding one or two characters. +#[rustfmt::skip] macro_rules! my_macro { () => { println!("Check out my macro!"); diff --git a/exercises/clippy/README.md b/exercises/22_clippy/README.md similarity index 100% rename from exercises/clippy/README.md rename to exercises/22_clippy/README.md diff --git a/exercises/22_clippy/clippy1.rs b/exercises/22_clippy/clippy1.rs new file mode 100644 index 0000000000..7165da4559 --- /dev/null +++ b/exercises/22_clippy/clippy1.rs @@ -0,0 +1,15 @@ +// The Clippy tool is a collection of lints to analyze your code so you can +// catch common mistakes and improve your Rust code. +// +// For these exercises, the code will fail to compile when there are Clippy +// warnings. Check Clippy's suggestions from the output to solve the exercise. + +fn main() { + // TODO: Fix the Clippy lint in this line. + let pi = 3.14; + let radius: f32 = 5.0; + + let area = pi * radius.powi(2); + + println!("The area of a circle with radius {radius:.2} is {area:.5}"); +} diff --git a/exercises/22_clippy/clippy2.rs b/exercises/22_clippy/clippy2.rs new file mode 100644 index 0000000000..8cfe6f80a2 --- /dev/null +++ b/exercises/22_clippy/clippy2.rs @@ -0,0 +1,10 @@ +fn main() { + let mut res = 42; + let option = Some(12); + // TODO: Fix the Clippy lint. + for x in option { + res += x; + } + + println!("{res}"); +} diff --git a/exercises/22_clippy/clippy3.rs b/exercises/22_clippy/clippy3.rs new file mode 100644 index 0000000000..3f23aaeea9 --- /dev/null +++ b/exercises/22_clippy/clippy3.rs @@ -0,0 +1,30 @@ +// Here are some more easy Clippy fixes so you can see its utility. +// TODO: Fix all the Clippy lints. + +#[allow(unused_variables, unused_assignments)] +fn main() { + let my_option: Option<&str> = None; + // Assume that you don't know the value of `my_option`. + // In the case of `Some`, we want to print its value. + if my_option.is_none() { + println!("{}", my_option.unwrap()); + } + + #[rustfmt::skip] + let my_arr = &[ + -1, -2, -3 + -4, -5, -6 + ]; + println!("My array! Here it is: {my_arr:?}"); + + let mut my_vec = vec![1, 2, 3, 4, 5]; + my_vec.resize(0, 5); + println!("This Vec is empty, see? {my_vec:?}"); + + let mut value_a = 45; + let mut value_b = 66; + // Let's swap these two! + value_a = value_b; + value_b = value_a; + println!("value a: {value_a}; value b: {value_b}"); +} diff --git a/exercises/conversions/README.md b/exercises/23_conversions/README.md similarity index 99% rename from exercises/conversions/README.md rename to exercises/23_conversions/README.md index 8d7da93ecb..619a78c565 100644 --- a/exercises/conversions/README.md +++ b/exercises/23_conversions/README.md @@ -6,6 +6,7 @@ The simplest form of type conversion is a type cast expression. It is denoted wi Rust also offers traits that facilitate type conversions upon implementation. These traits can be found under the [`convert`](https://doc.rust-lang.org/std/convert/index.html) module. The traits are the following: + - `From` and `Into` covered in [`from_into`](from_into.rs) - `TryFrom` and `TryInto` covered in [`try_from_into`](try_from_into.rs) - `AsRef` and `AsMut` covered in [`as_ref_mut`](as_ref_mut.rs) @@ -17,5 +18,6 @@ These should be the main ways ***within the standard library*** to convert data ## Further information These are not directly covered in the book, but the standard library has a great documentation for it. + - [conversions](https://doc.rust-lang.org/std/convert/index.html) -- [`FromStr` trait](https://doc.rust-lang.org/std/str/trait.FromStr.html) \ No newline at end of file +- [`FromStr` trait](https://doc.rust-lang.org/std/str/trait.FromStr.html) diff --git a/exercises/conversions/as_ref_mut.rs b/exercises/23_conversions/as_ref_mut.rs similarity index 65% rename from exercises/conversions/as_ref_mut.rs rename to exercises/23_conversions/as_ref_mut.rs index 9f47973990..d7892dd490 100644 --- a/exercises/conversions/as_ref_mut.rs +++ b/exercises/23_conversions/as_ref_mut.rs @@ -1,26 +1,28 @@ -// AsRef and AsMut allow for cheap reference-to-reference conversions. -// Read more about them at https://doc.rust-lang.org/std/convert/trait.AsRef.html -// and https://doc.rust-lang.org/std/convert/trait.AsMut.html, respectively. -// Execute `rustlings hint as_ref_mut` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE +// AsRef and AsMut allow for cheap reference-to-reference conversions. Read more +// about them at https://doc.rust-lang.org/std/convert/trait.AsRef.html and +// https://doc.rust-lang.org/std/convert/trait.AsMut.html, respectively. // Obtain the number of bytes (not characters) in the given argument -// Add the AsRef trait appropriately as a trait bound +// (`.len()` returns the number of bytes in a string). +// TODO: Add the `AsRef` trait appropriately as a trait bound. fn byte_counter(arg: T) -> usize { - arg.as_ref().as_bytes().len() + arg.as_ref().len() } -// Obtain the number of characters (not bytes) in the given argument -// Add the AsRef trait appropriately as a trait bound +// Obtain the number of characters (not bytes) in the given argument. +// TODO: Add the `AsRef` trait appropriately as a trait bound. fn char_counter(arg: T) -> usize { arg.as_ref().chars().count() } -// Squares a number using AsMut. Add the trait bound as is appropriate and -// implement the function body. +// Squares a number using `as_mut()`. +// TODO: Add the appropriate trait bound. fn num_sq(arg: &mut T) { - ??? + // TODO: Implement the function body. +} + +fn main() { + // You can optionally experiment here. } #[cfg(test)] @@ -52,7 +54,7 @@ mod tests { } #[test] - fn mult_box() { + fn mut_box() { let mut num: Box = Box::new(3); num_sq(&mut num); assert_eq!(*num, 9); diff --git a/exercises/conversions/from_into.rs b/exercises/23_conversions/from_into.rs similarity index 52% rename from exercises/conversions/from_into.rs rename to exercises/23_conversions/from_into.rs index 6c272c3bcd..bc2783a30f 100644 --- a/exercises/conversions/from_into.rs +++ b/exercises/23_conversions/from_into.rs @@ -1,83 +1,79 @@ -// The From trait is used for value-to-value conversions. -// If From is implemented correctly for a type, the Into trait should work conversely. -// You can read more about it at https://doc.rust-lang.org/std/convert/trait.From.html -// Execute `rustlings hint from_into` or use the `hint` watch subcommand for a hint. +// The `From` trait is used for value-to-value conversions. If `From` is +// implemented, an implementation of `Into` is automatically provided. +// You can read more about it in the documentation: +// https://doc.rust-lang.org/std/convert/trait.From.html #[derive(Debug)] struct Person { name: String, - age: usize, + age: u8, } -// We implement the Default trait to use it as a fallback -// when the provided string is not convertible into a Person object +// We implement the Default trait to use it as a fallback when the provided +// string is not convertible into a `Person` object. impl Default for Person { - fn default() -> Person { - Person { + fn default() -> Self { + Self { name: String::from("John"), age: 30, } } } -// Your task is to complete this implementation -// in order for the line `let p = Person::from("Mark,20")` to compile -// Please note that you'll need to parse the age component into a `usize` -// with something like `"4".parse::()`. The outcome of this needs to -// be handled appropriately. +// TODO: Complete this `From` implementation to be able to parse a `Person` +// out of a string in the form of "Mark,20". +// Note that you'll need to parse the age component into a `u8` with something +// like `"4".parse::()`. // // Steps: -// 1. If the length of the provided string is 0, then return the default of Person -// 2. Split the given string on the commas present in it -// 3. Extract the first element from the split operation and use it as the name -// 4. If the name is empty, then return the default of Person -// 5. Extract the other element from the split operation and parse it into a `usize` as the age -// If while parsing the age, something goes wrong, then return the default of Person -// Otherwise, then return an instantiated Person object with the results - -// I AM NOT DONE - +// 1. Split the given string on the commas present in it. +// 2. If the split operation returns less or more than 2 elements, return the +// default of `Person`. +// 3. Use the first element from the split operation as the name. +// 4. If the name is empty, return the default of `Person`. +// 5. Parse the second element from the split operation into a `u8` as the age. +// 6. If parsing the age fails, return the default of `Person`. impl From<&str> for Person { - fn from(s: &str) -> Person { - } + fn from(s: &str) -> Self {} } fn main() { - // Use the `from` function + // Use the `from` function. let p1 = Person::from("Mark,20"); - // Since From is implemented for Person, we should be able to use Into + println!("{p1:?}"); + + // Since `From` is implemented for Person, we are able to use `Into`. let p2: Person = "Gerald,70".into(); - println!("{:?}", p1); - println!("{:?}", p2); + println!("{p2:?}"); } #[cfg(test)] mod tests { use super::*; + #[test] fn test_default() { - // Test that the default person is 30 year old John let dp = Person::default(); assert_eq!(dp.name, "John"); assert_eq!(dp.age, 30); } + #[test] fn test_bad_convert() { - // Test that John is returned when bad string is provided let p = Person::from(""); assert_eq!(p.name, "John"); assert_eq!(p.age, 30); } + #[test] fn test_good_convert() { - // Test that "Mark,20" works let p = Person::from("Mark,20"); assert_eq!(p.name, "Mark"); assert_eq!(p.age, 20); } + #[test] fn test_bad_age() { - // Test that "Mark,twenty" will return the default person due to an error in parsing age let p = Person::from("Mark,twenty"); assert_eq!(p.name, "John"); assert_eq!(p.age, 30); @@ -127,7 +123,7 @@ mod tests { #[test] fn test_trailing_comma_and_some_string() { - let p: Person = Person::from("Mike,32,man"); + let p: Person = Person::from("Mike,32,dog"); assert_eq!(p.name, "John"); assert_eq!(p.age, 30); } diff --git a/exercises/23_conversions/from_str.rs b/exercises/23_conversions/from_str.rs new file mode 100644 index 0000000000..ec6d3fd129 --- /dev/null +++ b/exercises/23_conversions/from_str.rs @@ -0,0 +1,113 @@ +// This is similar to the previous `from_into` exercise. But this time, we'll +// implement `FromStr` and return errors instead of falling back to a default +// value. Additionally, upon implementing `FromStr`, you can use the `parse` +// method on strings to generate an object of the implementor type. You can read +// more about it in the documentation: +// https://doc.rust-lang.org/std/str/trait.FromStr.html + +use std::num::ParseIntError; +use std::str::FromStr; + +#[derive(Debug, PartialEq)] +struct Person { + name: String, + age: u8, +} + +// We will use this error type for the `FromStr` implementation. +#[derive(Debug, PartialEq)] +enum ParsePersonError { + // Incorrect number of fields + BadLen, + // Empty name field + NoName, + // Wrapped error from parse::() + ParseInt(ParseIntError), +} + +// TODO: Complete this `FromStr` implementation to be able to parse a `Person` +// out of a string in the form of "Mark,20". +// Note that you'll need to parse the age component into a `u8` with something +// like `"4".parse::()`. +// +// Steps: +// 1. Split the given string on the commas present in it. +// 2. If the split operation returns less or more than 2 elements, return the +// error `ParsePersonError::BadLen`. +// 3. Use the first element from the split operation as the name. +// 4. If the name is empty, return the error `ParsePersonError::NoName`. +// 5. Parse the second element from the split operation into a `u8` as the age. +// 6. If parsing the age fails, return the error `ParsePersonError::ParseInt`. +impl FromStr for Person { + type Err = ParsePersonError; + + fn from_str(s: &str) -> Result {} +} + +fn main() { + let p = "Mark,20".parse::(); + println!("{p:?}"); +} + +#[cfg(test)] +mod tests { + use super::*; + use ParsePersonError::*; + + #[test] + fn empty_input() { + assert_eq!("".parse::(), Err(BadLen)); + } + + #[test] + fn good_input() { + let p = "John,32".parse::(); + assert!(p.is_ok()); + let p = p.unwrap(); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 32); + } + + #[test] + fn missing_age() { + assert!(matches!("John,".parse::(), Err(ParseInt(_)))); + } + + #[test] + fn invalid_age() { + assert!(matches!("John,twenty".parse::(), Err(ParseInt(_)))); + } + + #[test] + fn missing_comma_and_age() { + assert_eq!("John".parse::(), Err(BadLen)); + } + + #[test] + fn missing_name() { + assert_eq!(",1".parse::(), Err(NoName)); + } + + #[test] + fn missing_name_and_age() { + assert!(matches!(",".parse::(), Err(NoName | ParseInt(_)))); + } + + #[test] + fn missing_name_and_invalid_age() { + assert!(matches!( + ",one".parse::(), + Err(NoName | ParseInt(_)), + )); + } + + #[test] + fn trailing_comma() { + assert_eq!("John,32,".parse::(), Err(BadLen)); + } + + #[test] + fn trailing_comma_and_some_string() { + assert_eq!("John,32,man".parse::(), Err(BadLen)); + } +} diff --git a/exercises/23_conversions/try_from_into.rs b/exercises/23_conversions/try_from_into.rs new file mode 100644 index 0000000000..f3ae80a9e4 --- /dev/null +++ b/exercises/23_conversions/try_from_into.rs @@ -0,0 +1,177 @@ +// `TryFrom` is a simple and safe type conversion that may fail in a controlled +// way under some circumstances. Basically, this is the same as `From`. The main +// difference is that this should return a `Result` type instead of the target +// type itself. You can read more about it in the documentation: +// https://doc.rust-lang.org/std/convert/trait.TryFrom.html + +#![allow(clippy::useless_vec)] +use std::convert::{TryFrom, TryInto}; + +#[derive(Debug, PartialEq)] +struct Color { + red: u8, + green: u8, + blue: u8, +} + +// We will use this error type for the `TryFrom` conversions. +#[derive(Debug, PartialEq)] +enum IntoColorError { + // Incorrect length of slice + BadLen, + // Integer conversion error + IntConversion, +} + +// TODO: Tuple implementation. +// Correct RGB color values must be integers in the 0..=255 range. +impl TryFrom<(i16, i16, i16)> for Color { + type Error = IntoColorError; + + fn try_from(tuple: (i16, i16, i16)) -> Result {} +} + +// TODO: Array implementation. +impl TryFrom<[i16; 3]> for Color { + type Error = IntoColorError; + + fn try_from(arr: [i16; 3]) -> Result {} +} + +// TODO: Slice implementation. +// This implementation needs to check the slice length. +impl TryFrom<&[i16]> for Color { + type Error = IntoColorError; + + fn try_from(slice: &[i16]) -> Result {} +} + +fn main() { + // Using the `try_from` function. + let c1 = Color::try_from((183, 65, 14)); + println!("{c1:?}"); + + // Since `TryFrom` is implemented for `Color`, we can use `TryInto`. + let c2: Result = [183, 65, 14].try_into(); + println!("{c2:?}"); + + let v = vec![183, 65, 14]; + // With slice we should use the `try_from` function + let c3 = Color::try_from(&v[..]); + println!("{c3:?}"); + // or put the slice within round brackets and use `try_into`. + let c4: Result = (&v[..]).try_into(); + println!("{c4:?}"); +} + +#[cfg(test)] +mod tests { + use super::*; + use IntoColorError::*; + + #[test] + fn test_tuple_out_of_range_positive() { + assert_eq!(Color::try_from((256, 1000, 10000)), Err(IntConversion)); + } + + #[test] + fn test_tuple_out_of_range_negative() { + assert_eq!(Color::try_from((-1, -10, -256)), Err(IntConversion)); + } + + #[test] + fn test_tuple_sum() { + assert_eq!(Color::try_from((-1, 255, 255)), Err(IntConversion)); + } + + #[test] + fn test_tuple_correct() { + let c: Result = (183, 65, 14).try_into(); + assert!(c.is_ok()); + assert_eq!( + c.unwrap(), + Color { + red: 183, + green: 65, + blue: 14, + } + ); + } + + #[test] + fn test_array_out_of_range_positive() { + let c: Result = [1000, 10000, 256].try_into(); + assert_eq!(c, Err(IntConversion)); + } + + #[test] + fn test_array_out_of_range_negative() { + let c: Result = [-10, -256, -1].try_into(); + assert_eq!(c, Err(IntConversion)); + } + + #[test] + fn test_array_sum() { + let c: Result = [-1, 255, 255].try_into(); + assert_eq!(c, Err(IntConversion)); + } + + #[test] + fn test_array_correct() { + let c: Result = [183, 65, 14].try_into(); + assert!(c.is_ok()); + assert_eq!( + c.unwrap(), + Color { + red: 183, + green: 65, + blue: 14 + } + ); + } + + #[test] + fn test_slice_out_of_range_positive() { + let arr = [10000, 256, 1000]; + assert_eq!(Color::try_from(&arr[..]), Err(IntConversion)); + } + + #[test] + fn test_slice_out_of_range_negative() { + let arr = [-256, -1, -10]; + assert_eq!(Color::try_from(&arr[..]), Err(IntConversion)); + } + + #[test] + fn test_slice_sum() { + let arr = [-1, 255, 255]; + assert_eq!(Color::try_from(&arr[..]), Err(IntConversion)); + } + + #[test] + fn test_slice_correct() { + let v = vec![183, 65, 14]; + let c: Result = Color::try_from(&v[..]); + assert!(c.is_ok()); + assert_eq!( + c.unwrap(), + Color { + red: 183, + green: 65, + blue: 14, + } + ); + } + + #[test] + fn test_slice_excess_length() { + let v = vec![0, 0, 0, 0]; + assert_eq!(Color::try_from(&v[..]), Err(BadLen)); + } + + #[test] + fn test_slice_insufficient_length() { + let v = vec![0, 0]; + assert_eq!(Color::try_from(&v[..]), Err(BadLen)); + } +} diff --git a/exercises/conversions/using_as.rs b/exercises/23_conversions/using_as.rs similarity index 57% rename from exercises/conversions/using_as.rs rename to exercises/23_conversions/using_as.rs index 8c9b7113d8..c131d1f32f 100644 --- a/exercises/conversions/using_as.rs +++ b/exercises/23_conversions/using_as.rs @@ -1,15 +1,10 @@ // Type casting in Rust is done via the usage of the `as` operator. -// Please note that the `as` operator is not only used when type casting. -// It also helps with renaming imports. -// -// The goal is to make sure that the division does not fail to compile -// and returns the proper type. -// Execute `rustlings hint using_as` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE +// Note that the `as` operator is not only used when type casting. It also helps +// with renaming imports. fn average(values: &[f64]) -> f64 { let total = values.iter().sum::(); + // TODO: Make a conversion before dividing. total / values.len() } diff --git a/exercises/README.md b/exercises/README.md index e52137caaa..24ebd06965 100644 --- a/exercises/README.md +++ b/exercises/README.md @@ -7,9 +7,9 @@ | if | §3.5 | | primitive_types | §3.2, §4.3 | | vecs | §8.1 | -| move_semantics | §4.1, §4.2 | +| move_semantics | §4.1-2 | | structs | §5.1, §5.3 | -| enums | §6, §18.3 | +| enums | §6, §19.3 | | strings | §8.2 | | modules | §7 | | hashmaps | §8.3 | @@ -17,10 +17,11 @@ | error_handling | §9 | | generics | §10 | | traits | §10.2 | -| tests | §11.1 | | lifetimes | §10.3 | -| standard_library_types | §13.2, §15.1, §16.3 | -| threads | §16.1, §16.2, §16.3 | -| macros | §19.6 | -| clippy | n/a | +| tests | §11.1 | +| iterators | §13.2-4 | +| smart_pointers | §15, §16.3 | +| threads | §16.1-3 | +| macros | §20.5 | +| clippy | Appendix D | | conversions | n/a | diff --git a/exercises/clippy/clippy1.rs b/exercises/clippy/clippy1.rs deleted file mode 100644 index bad46891fe..0000000000 --- a/exercises/clippy/clippy1.rs +++ /dev/null @@ -1,23 +0,0 @@ -// clippy1.rs -// The Clippy tool is a collection of lints to analyze your code -// so you can catch common mistakes and improve your Rust code. -// -// For these exercises the code will fail to compile when there are clippy warnings -// check clippy's suggestions from the output to solve the exercise. -// Execute `rustlings hint clippy1` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -use std::f32; - -fn main() { - let pi = 3.14f32; - let radius = 5.00f32; - - let area = pi * f32::powi(radius, 2); - - println!( - "The area of a circle with radius {:.2} is {:.5}!", - radius, area - ) -} diff --git a/exercises/clippy/clippy2.rs b/exercises/clippy/clippy2.rs deleted file mode 100644 index dac40dbef6..0000000000 --- a/exercises/clippy/clippy2.rs +++ /dev/null @@ -1,13 +0,0 @@ -// clippy2.rs -// Execute `rustlings hint clippy2` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -fn main() { - let mut res = 42; - let option = Some(12); - for x in option { - res += x; - } - println!("{}", res); -} diff --git a/exercises/clippy/clippy3.rs b/exercises/clippy/clippy3.rs deleted file mode 100644 index b0159ebe66..0000000000 --- a/exercises/clippy/clippy3.rs +++ /dev/null @@ -1,28 +0,0 @@ -// clippy3.rs -// Here's a couple more easy Clippy fixes, so you can see its utility. - -// I AM NOT DONE - -#[allow(unused_variables, unused_assignments)] -fn main() { - let my_option: Option<()> = None; - if my_option.is_none() { - my_option.unwrap(); - } - - let my_arr = &[ - -1, -2, -3 - -4, -5, -6 - ]; - println!("My array! Here it is: {:?}", my_arr); - - let my_empty_vec = vec![1, 2, 3, 4, 5].resize(0, 5); - println!("This Vec is empty, see? {:?}", my_empty_vec); - - let mut value_a = 45; - let mut value_b = 66; - // Let's swap these two! - value_a = value_b; - value_b = value_a; - println!("value a: {}; value b: {}", value_a, value_b); -} diff --git a/exercises/conversions/from_str.rs b/exercises/conversions/from_str.rs deleted file mode 100644 index fe168159b4..0000000000 --- a/exercises/conversions/from_str.rs +++ /dev/null @@ -1,127 +0,0 @@ -// from_str.rs -// This is similar to from_into.rs, but this time we'll implement `FromStr` -// and return errors instead of falling back to a default value. -// Additionally, upon implementing FromStr, you can use the `parse` method -// on strings to generate an object of the implementor type. -// You can read more about it at https://doc.rust-lang.org/std/str/trait.FromStr.html -// Execute `rustlings hint from_str` or use the `hint` watch subcommand for a hint. - -use std::num::ParseIntError; -use std::str::FromStr; - -#[derive(Debug, PartialEq)] -struct Person { - name: String, - age: usize, -} - -// We will use this error type for the `FromStr` implementation. -#[derive(Debug, PartialEq)] -enum ParsePersonError { - // Empty input string - Empty, - // Incorrect number of fields - BadLen, - // Empty name field - NoName, - // Wrapped error from parse::() - ParseInt(ParseIntError), -} - -// I AM NOT DONE - -// Steps: -// 1. If the length of the provided string is 0, an error should be returned -// 2. Split the given string on the commas present in it -// 3. Only 2 elements should be returned from the split, otherwise return an error -// 4. Extract the first element from the split operation and use it as the name -// 5. Extract the other element from the split operation and parse it into a `usize` as the age -// with something like `"4".parse::()` -// 6. If while extracting the name and the age something goes wrong, an error should be returned -// If everything goes well, then return a Result of a Person object -// -// As an aside: `Box` implements `From<&'_ str>`. This means that if you want to return a -// string error message, you can do so via just using return `Err("my error message".into())`. - -impl FromStr for Person { - type Err = ParsePersonError; - fn from_str(s: &str) -> Result { - } -} - -fn main() { - let p = "Mark,20".parse::().unwrap(); - println!("{:?}", p); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn empty_input() { - assert_eq!("".parse::(), Err(ParsePersonError::Empty)); - } - #[test] - fn good_input() { - let p = "John,32".parse::(); - assert!(p.is_ok()); - let p = p.unwrap(); - assert_eq!(p.name, "John"); - assert_eq!(p.age, 32); - } - #[test] - fn missing_age() { - assert!(matches!( - "John,".parse::(), - Err(ParsePersonError::ParseInt(_)) - )); - } - - #[test] - fn invalid_age() { - assert!(matches!( - "John,twenty".parse::(), - Err(ParsePersonError::ParseInt(_)) - )); - } - - #[test] - fn missing_comma_and_age() { - assert_eq!("John".parse::(), Err(ParsePersonError::BadLen)); - } - - #[test] - fn missing_name() { - assert_eq!(",1".parse::(), Err(ParsePersonError::NoName)); - } - - #[test] - fn missing_name_and_age() { - assert!(matches!( - ",".parse::(), - Err(ParsePersonError::NoName | ParsePersonError::ParseInt(_)) - )); - } - - #[test] - fn missing_name_and_invalid_age() { - assert!(matches!( - ",one".parse::(), - Err(ParsePersonError::NoName | ParsePersonError::ParseInt(_)) - )); - } - - #[test] - fn trailing_comma() { - assert_eq!("John,32,".parse::(), Err(ParsePersonError::BadLen)); - } - - #[test] - fn trailing_comma_and_some_string() { - assert_eq!( - "John,32,man".parse::(), - Err(ParsePersonError::BadLen) - ); - } -} diff --git a/exercises/enums/enums3.rs b/exercises/enums/enums3.rs deleted file mode 100644 index 55acf6bc9d..0000000000 --- a/exercises/enums/enums3.rs +++ /dev/null @@ -1,65 +0,0 @@ -// enums3.rs -// Address all the TODOs to make the tests pass! -// Execute `rustlings hint enums3` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -enum Message { - // TODO: implement the message variant types based on their usage below -} - -struct Point { - x: u8, - y: u8, -} - -struct State { - color: (u8, u8, u8), - position: Point, - quit: bool, -} - -impl State { - fn change_color(&mut self, color: (u8, u8, u8)) { - self.color = color; - } - - fn quit(&mut self) { - self.quit = true; - } - - fn echo(&self, s: String) { - println!("{}", s); - } - - fn move_position(&mut self, p: Point) { - self.position = p; - } - - fn process(&mut self, message: Message) { - // TODO: create a match expression to process the different message variants - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_match_message_call() { - let mut state = State { - quit: false, - position: Point { x: 0, y: 0 }, - color: (0, 0, 0), - }; - state.process(Message::ChangeColor((255, 0, 255))); - state.process(Message::Echo(String::from("hello world"))); - state.process(Message::Move(Point { x: 10, y: 15 })); - state.process(Message::Quit); - - assert_eq!(state.color, (255, 0, 255)); - assert_eq!(state.position.x, 10); - assert_eq!(state.position.y, 15); - assert_eq!(state.quit, true); - } -} diff --git a/exercises/error_handling/errors1.rs b/exercises/error_handling/errors1.rs deleted file mode 100644 index bcee9723e9..0000000000 --- a/exercises/error_handling/errors1.rs +++ /dev/null @@ -1,39 +0,0 @@ -// errors1.rs -// This function refuses to generate text to be printed on a nametag if -// you pass it an empty string. It'd be nicer if it explained what the problem -// was, instead of just sometimes returning `None`. Thankfully, Rust has a similar -// construct to `Option` that can be used to express error conditions. Let's use it! -// Execute `rustlings hint errors1` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -pub fn generate_nametag_text(name: String) -> Option { - if name.is_empty() { - // Empty names aren't allowed. - None - } else { - Some(format!("Hi! My name is {}", name)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn generates_nametag_text_for_a_nonempty_name() { - assert_eq!( - generate_nametag_text("Beyoncé".into()), - Ok("Hi! My name is Beyoncé".into()) - ); - } - - #[test] - fn explains_why_generating_nametag_text_fails() { - assert_eq!( - generate_nametag_text("".into()), - // Don't change this line - Err("`name` was empty; it must be nonempty.".into()) - ); - } -} diff --git a/exercises/error_handling/errors4.rs b/exercises/error_handling/errors4.rs deleted file mode 100644 index 0efe8ccd5a..0000000000 --- a/exercises/error_handling/errors4.rs +++ /dev/null @@ -1,30 +0,0 @@ -// errors4.rs -// Execute `rustlings hint errors4` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -#[derive(PartialEq, Debug)] -struct PositiveNonzeroInteger(u64); - -#[derive(PartialEq, Debug)] -enum CreationError { - Negative, - Zero, -} - -impl PositiveNonzeroInteger { - fn new(value: i64) -> Result { - // Hmm...? Why is this only returning an Ok value? - Ok(PositiveNonzeroInteger(value as u64)) - } -} - -#[test] -fn test_creation() { - assert!(PositiveNonzeroInteger::new(10).is_ok()); - assert_eq!( - Err(CreationError::Negative), - PositiveNonzeroInteger::new(-10) - ); - assert_eq!(Err(CreationError::Zero), PositiveNonzeroInteger::new(0)); -} diff --git a/exercises/error_handling/errors5.rs b/exercises/error_handling/errors5.rs deleted file mode 100644 index 2ba8f9039d..0000000000 --- a/exercises/error_handling/errors5.rs +++ /dev/null @@ -1,65 +0,0 @@ -// errors5.rs - -// This program uses an altered version of the code from errors4. - -// This exercise uses some concepts that we won't get to until later in the course, like `Box` and the -// `From` trait. It's not important to understand them in detail right now, but you can read ahead if you like. -// For now, think of the `Box` type as an "I want anything that does ???" type, which, given -// Rust's usual standards for runtime safety, should strike you as somewhat lenient! - -// In short, this particular use case for boxes is for when you want to own a value and you care only that it is a -// type which implements a particular trait. To do so, The Box is declared as of type Box where Trait is the trait -// the compiler looks for on any value used in that context. For this exercise, that context is the potential errors -// which can be returned in a Result. - -// What can we use to describe both errors? In other words, is there a trait which both errors implement? - -// Execute `rustlings hint errors5` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -use std::error; -use std::fmt; -use std::num::ParseIntError; - -// TODO: update the return type of `main()` to make this compile. -fn main() -> Result<(), Box> { - let pretend_user_input = "42"; - let x: i64 = pretend_user_input.parse()?; - println!("output={:?}", PositiveNonzeroInteger::new(x)?); - Ok(()) -} - -// Don't change anything below this line. - -#[derive(PartialEq, Debug)] -struct PositiveNonzeroInteger(u64); - -#[derive(PartialEq, Debug)] -enum CreationError { - Negative, - Zero, -} - -impl PositiveNonzeroInteger { - fn new(value: i64) -> Result { - match value { - x if x < 0 => Err(CreationError::Negative), - x if x == 0 => Err(CreationError::Zero), - x => Ok(PositiveNonzeroInteger(x as u64)) - } - } -} - -// This is required so that `CreationError` can implement `error::Error`. -impl fmt::Display for CreationError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let description = match *self { - CreationError::Negative => "number is negative", - CreationError::Zero => "number is zero", - }; - f.write_str(description) - } -} - -impl error::Error for CreationError {} diff --git a/exercises/error_handling/errors6.rs b/exercises/error_handling/errors6.rs deleted file mode 100644 index 1306fb03e1..0000000000 --- a/exercises/error_handling/errors6.rs +++ /dev/null @@ -1,96 +0,0 @@ -// errors6.rs - -// Using catch-all error types like `Box` isn't recommended -// for library code, where callers might want to make decisions based on the -// error content, instead of printing it out or propagating it further. Here, -// we define a custom error type to make it possible for callers to decide -// what to do next when our function returns an error. - -// Execute `rustlings hint errors6` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -use std::num::ParseIntError; - -// This is a custom error type that we will be using in `parse_pos_nonzero()`. -#[derive(PartialEq, Debug)] -enum ParsePosNonzeroError { - Creation(CreationError), - ParseInt(ParseIntError) -} - -impl ParsePosNonzeroError { - fn from_creation(err: CreationError) -> ParsePosNonzeroError { - ParsePosNonzeroError::Creation(err) - } - // TODO: add another error conversion function here. - // fn from_parseint... -} - -fn parse_pos_nonzero(s: &str) - -> Result -{ - // TODO: change this to return an appropriate error instead of panicking - // when `parse()` returns an error. - let x: i64 = s.parse().unwrap(); - PositiveNonzeroInteger::new(x) - .map_err(ParsePosNonzeroError::from_creation) -} - -// Don't change anything below this line. - -#[derive(PartialEq, Debug)] -struct PositiveNonzeroInteger(u64); - -#[derive(PartialEq, Debug)] -enum CreationError { - Negative, - Zero, -} - -impl PositiveNonzeroInteger { - fn new(value: i64) -> Result { - match value { - x if x < 0 => Err(CreationError::Negative), - x if x == 0 => Err(CreationError::Zero), - x => Ok(PositiveNonzeroInteger(x as u64)) - } - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn test_parse_error() { - // We can't construct a ParseIntError, so we have to pattern match. - assert!(matches!( - parse_pos_nonzero("not a number"), - Err(ParsePosNonzeroError::ParseInt(_)) - )); - } - - #[test] - fn test_negative() { - assert_eq!( - parse_pos_nonzero("-555"), - Err(ParsePosNonzeroError::Creation(CreationError::Negative)) - ); - } - - #[test] - fn test_zero() { - assert_eq!( - parse_pos_nonzero("0"), - Err(ParsePosNonzeroError::Creation(CreationError::Zero)) - ); - } - - #[test] - fn test_positive() { - let x = PositiveNonzeroInteger::new(42); - assert!(x.is_ok()); - assert_eq!(parse_pos_nonzero("42"), Ok(x.unwrap())); - } -} diff --git a/exercises/functions/functions1.rs b/exercises/functions/functions1.rs deleted file mode 100644 index 03d8af7020..0000000000 --- a/exercises/functions/functions1.rs +++ /dev/null @@ -1,8 +0,0 @@ -// functions1.rs -// Execute `rustlings hint functions1` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -fn main() { - call_me(); -} diff --git a/exercises/functions/functions3.rs b/exercises/functions/functions3.rs deleted file mode 100644 index 3b9e585b6c..0000000000 --- a/exercises/functions/functions3.rs +++ /dev/null @@ -1,14 +0,0 @@ -// functions3.rs -// Execute `rustlings hint functions3` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -fn main() { - call_me(); -} - -fn call_me(num: u32) { - for i in 0..num { - println!("Ring! Call number {}", i + 1); - } -} diff --git a/exercises/functions/functions4.rs b/exercises/functions/functions4.rs deleted file mode 100644 index 65d5be4ff6..0000000000 --- a/exercises/functions/functions4.rs +++ /dev/null @@ -1,27 +0,0 @@ -// functions4.rs -// Execute `rustlings hint functions4` or use the `hint` watch subcommand for a hint. - -// This store is having a sale where if the price is an even number, you get -// 10 Rustbucks off, but if it's an odd number, it's 3 Rustbucks off. -// (Don't worry about the function bodies themselves, we're only interested -// in the signatures for now. If anything, this is a good way to peek ahead -// to future exercises!) - -// I AM NOT DONE - -fn main() { - let original_price = 51; - println!("Your sale price is {}", sale_price(original_price)); -} - -fn sale_price(price: i32) -> { - if is_even(price) { - price - 10 - } else { - price - 3 - } -} - -fn is_even(num: i32) -> bool { - num % 2 == 0 -} diff --git a/exercises/functions/functions5.rs b/exercises/functions/functions5.rs deleted file mode 100644 index 5d7629617f..0000000000 --- a/exercises/functions/functions5.rs +++ /dev/null @@ -1,13 +0,0 @@ -// functions5.rs -// Execute `rustlings hint functions5` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -fn main() { - let answer = square(3); - println!("The square of 3 is {}", answer); -} - -fn square(num: i32) -> i32 { - num * num; -} diff --git a/exercises/generics/generics1.rs b/exercises/generics/generics1.rs deleted file mode 100644 index 4c34ae47d6..0000000000 --- a/exercises/generics/generics1.rs +++ /dev/null @@ -1,11 +0,0 @@ -// This shopping list program isn't compiling! -// Use your knowledge of generics to fix it. - -// Execute `rustlings hint generics1` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -fn main() { - let mut shopping_list: Vec = Vec::new(); - shopping_list.push("milk"); -} diff --git a/exercises/hashmaps/hashmaps2.rs b/exercises/hashmaps/hashmaps2.rs deleted file mode 100644 index 454b3e1d7b..0000000000 --- a/exercises/hashmaps/hashmaps2.rs +++ /dev/null @@ -1,80 +0,0 @@ -// hashmaps2.rs - -// A basket of fruits in the form of a hash map is given. The key -// represents the name of the fruit and the value represents how many -// of that particular fruit is in the basket. You have to put *MORE -// THAN 11* fruits in the basket. Three types of fruits - Apple (4), -// Mango (2) and Lychee (5) are already given in the basket. You are -// not allowed to insert any more of these fruits! -// -// Make me pass the tests! -// -// Execute `rustlings hint hashmaps2` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -use std::collections::HashMap; - -#[derive(Hash, PartialEq, Eq)] -enum Fruit { - Apple, - Banana, - Mango, - Lychee, - Pineapple, -} - -fn fruit_basket(basket: &mut HashMap) { - let fruit_kinds = vec![ - Fruit::Apple, - Fruit::Banana, - Fruit::Mango, - Fruit::Lychee, - Fruit::Pineapple, - ]; - - for fruit in fruit_kinds { - // TODO: Put new fruits if not already present. Note that you - // are not allowed to put any type of fruit that's already - // present! - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn get_fruit_basket() -> HashMap { - let mut basket = HashMap::::new(); - basket.insert(Fruit::Apple, 4); - basket.insert(Fruit::Mango, 2); - basket.insert(Fruit::Lychee, 5); - - basket - } - - #[test] - fn test_given_fruits_are_not_modified() { - let mut basket = get_fruit_basket(); - fruit_basket(&mut basket); - assert_eq!(*basket.get(&Fruit::Apple).unwrap(), 4); - assert_eq!(*basket.get(&Fruit::Mango).unwrap(), 2); - assert_eq!(*basket.get(&Fruit::Lychee).unwrap(), 5); - } - - #[test] - fn at_least_five_types_of_fruits() { - let mut basket = get_fruit_basket(); - fruit_basket(&mut basket); - let count_fruit_kinds = basket.len(); - assert!(count_fruit_kinds >= 5); - } - - #[test] - fn greater_than_eleven_fruits() { - let mut basket = get_fruit_basket(); - fruit_basket(&mut basket); - let count = basket.values().sum::(); - assert!(count > 11); - } -} diff --git a/exercises/hashmaps/hashmaps3.rs b/exercises/hashmaps/hashmaps3.rs deleted file mode 100644 index 18dd44c914..0000000000 --- a/exercises/hashmaps/hashmaps3.rs +++ /dev/null @@ -1,87 +0,0 @@ -// hashmaps3.rs - -// A list of scores (one per line) of a soccer match is given. Each line -// is of the form : -// ,,, -// Example: England,France,4,2 (England scored 4 goals, France 2). - -// You have to build a scores table containing the name of the team, goals -// the team scored, and goals the team conceded. One approach to build -// the scores table is to use a Hashmap. The solution is partially -// written to use a Hashmap, complete it to pass the test. - -// Make me pass the tests! - -// Execute `rustlings hint hashmaps3` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -use std::collections::HashMap; - -// A structure to store team name and its goal details. -struct Team { - name: String, - goals_scored: u8, - goals_conceded: u8, -} - -fn build_scores_table(results: String) -> HashMap { - // The name of the team is the key and its associated struct is the value. - let mut scores: HashMap = HashMap::new(); - - for r in results.lines() { - let v: Vec<&str> = r.split(',').collect(); - let team_1_name = v[0].to_string(); - let team_1_score: u8 = v[2].parse().unwrap(); - let team_2_name = v[1].to_string(); - let team_2_score: u8 = v[3].parse().unwrap(); - // TODO: Populate the scores table with details extracted from the - // current line. Keep in mind that goals scored by team_1 - // will be number of goals conceded from team_2, and similarly - // goals scored by team_2 will be the number of goals conceded by - // team_1. - } - scores -} - -#[cfg(test)] -mod tests { - use super::*; - - fn get_results() -> String { - let results = "".to_string() - + "England,France,4,2\n" - + "France,Italy,3,1\n" - + "Poland,Spain,2,0\n" - + "Germany,England,2,1\n"; - results - } - - #[test] - fn build_scores() { - let scores = build_scores_table(get_results()); - - let mut keys: Vec<&String> = scores.keys().collect(); - keys.sort(); - assert_eq!( - keys, - vec!["England", "France", "Germany", "Italy", "Poland", "Spain"] - ); - } - - #[test] - fn validate_team_score_1() { - let scores = build_scores_table(get_results()); - let team = scores.get("England").unwrap(); - assert_eq!(team.goals_scored, 5); - assert_eq!(team.goals_conceded, 4); - } - - #[test] - fn validate_team_score_2() { - let scores = build_scores_table(get_results()); - let team = scores.get("Spain").unwrap(); - assert_eq!(team.goals_scored, 0); - assert_eq!(team.goals_conceded, 2); - } -} diff --git a/exercises/if/if2.rs b/exercises/if/if2.rs deleted file mode 100644 index effddbb6eb..0000000000 --- a/exercises/if/if2.rs +++ /dev/null @@ -1,36 +0,0 @@ -// if2.rs - -// Step 1: Make me compile! -// Step 2: Get the bar_for_fuzz and default_to_baz tests passing! -// Execute `rustlings hint if2` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -pub fn foo_if_fizz(fizzish: &str) -> &str { - if fizzish == "fizz" { - "foo" - } else { - 1 - } -} - -// No test changes needed! -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn foo_for_fizz() { - assert_eq!(foo_if_fizz("fizz"), "foo") - } - - #[test] - fn bar_for_fuzz() { - assert_eq!(foo_if_fizz("fuzz"), "bar") - } - - #[test] - fn default_to_baz() { - assert_eq!(foo_if_fizz("literally anything"), "baz") - } -} diff --git a/exercises/intro/intro1.rs b/exercises/intro/intro1.rs deleted file mode 100644 index 45c5acbaa6..0000000000 --- a/exercises/intro/intro1.rs +++ /dev/null @@ -1,30 +0,0 @@ -// intro1.rs -// About this `I AM NOT DONE` thing: -// We sometimes encourage you to keep trying things on a given exercise, even -// after you already figured it out. If you got everything working and feel -// ready for the next exercise, remove the `I AM NOT DONE` comment below. -// Execute `rustlings hint intro1` or use the `hint` watch subcommand for a hint. -// -// If you're running this using `rustlings watch`: The exercise file will be reloaded -// when you change one of the lines below! Try adding a `println!` line, or try changing -// what it outputs in your terminal. Try removing a semicolon and see what happens! - -// I AM NOT DONE - -fn main() { - println!("Hello and"); - println!(r#" welcome to... "#); - println!(r#" _ _ _ "#); - println!(r#" _ __ _ _ ___| |_| (_)_ __ __ _ ___ "#); - println!(r#" | '__| | | / __| __| | | '_ \ / _` / __| "#); - println!(r#" | | | |_| \__ \ |_| | | | | | (_| \__ \ "#); - println!(r#" |_| \__,_|___/\__|_|_|_| |_|\__, |___/ "#); - println!(r#" |___/ "#); - println!(); - println!("This exercise compiles successfully. The remaining exercises contain a compiler"); - println!("or logic error. The central concept behind Rustlings is to fix these errors and"); - println!("solve the exercises. Good luck!"); - println!(); - println!("The source for this exercise is in `exercises/intro/intro1.rs`. Have a look!"); - println!("Going forward, the source of the exercises will always be in the success/failure output."); -} diff --git a/exercises/intro/intro2.rs b/exercises/intro/intro2.rs deleted file mode 100644 index efc1af2059..0000000000 --- a/exercises/intro/intro2.rs +++ /dev/null @@ -1,9 +0,0 @@ -// intro2.rs -// Make the code print a greeting to the world. -// Execute `rustlings hint intro2` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -fn main() { - println!("Hello {}!"); -} diff --git a/exercises/lifetimes/lifetimes1.rs b/exercises/lifetimes/lifetimes1.rs deleted file mode 100644 index 58e995c65f..0000000000 --- a/exercises/lifetimes/lifetimes1.rs +++ /dev/null @@ -1,26 +0,0 @@ -// lifetimes1.rs -// -// The Rust compiler needs to know how to check whether supplied references are -// valid, so that it can let the programmer know if a reference is at risk -// of going out of scope before it is used. Remember, references are borrows -// and do not own their own data. What if their owner goes out of scope? -// -// Execute `rustlings hint lifetimes1` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -fn longest(x: &str, y: &str) -> &str { - if x.len() > y.len() { - x - } else { - y - } -} - -fn main() { - let string1 = String::from("abcd"); - let string2 = "xyz"; - - let result = longest(string1.as_str(), string2); - println!("The longest string is {}", result); -} diff --git a/exercises/lifetimes/lifetimes2.rs b/exercises/lifetimes/lifetimes2.rs deleted file mode 100644 index c73a28adde..0000000000 --- a/exercises/lifetimes/lifetimes2.rs +++ /dev/null @@ -1,27 +0,0 @@ -// lifetimes2.rs -// -// So if the compiler is just validating the references passed -// to the annotated parameters and the return type, what do -// we need to change? -// -// Execute `rustlings hint lifetimes2` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { - if x.len() > y.len() { - x - } else { - y - } -} - -fn main() { - let string1 = String::from("long string is long"); - let result; - { - let string2 = String::from("xyz"); - result = longest(string1.as_str(), string2.as_str()); - } - println!("The longest string is {}", result); -} diff --git a/exercises/lifetimes/lifetimes3.rs b/exercises/lifetimes/lifetimes3.rs deleted file mode 100644 index ea48370876..0000000000 --- a/exercises/lifetimes/lifetimes3.rs +++ /dev/null @@ -1,20 +0,0 @@ -// lifetimes3.rs -// -// Lifetimes are also needed when structs hold references. -// -// Execute `rustlings hint lifetimes3` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -struct Book { - author: &str, - title: &str, -} - -fn main() { - let name = String::from("Jill Smith"); - let title = String::from("Fish Flying"); - let book = Book { author: &name, title: &title }; - - println!("{} by {}", book.title, book.author); -} diff --git a/exercises/macros/README.md b/exercises/macros/README.md deleted file mode 100644 index 31a941b7c5..0000000000 --- a/exercises/macros/README.md +++ /dev/null @@ -1,10 +0,0 @@ -# Macros - -Rust's macro system is very powerful, but also kind of difficult to wrap your -head around. We're not going to teach you how to write your own fully-featured -macros. Instead, we'll show you how to use and create them. - -## Further information - -- [Macros](https://doc.rust-lang.org/book/ch19-06-macros.html) -- [The Little Book of Rust Macros](https://veykril.github.io/tlborm/) diff --git a/exercises/macros/macros3.rs b/exercises/macros/macros3.rs deleted file mode 100644 index 106f1c6dc8..0000000000 --- a/exercises/macros/macros3.rs +++ /dev/null @@ -1,17 +0,0 @@ -// macros3.rs -// Make me compile, without taking the macro out of the module! -// Execute `rustlings hint macros3` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -mod macros { - macro_rules! my_macro { - () => { - println!("Check out my macro!"); - }; - } -} - -fn main() { - my_macro!(); -} diff --git a/exercises/modules/modules2.rs b/exercises/modules/modules2.rs deleted file mode 100644 index c30a3897bb..0000000000 --- a/exercises/modules/modules2.rs +++ /dev/null @@ -1,30 +0,0 @@ -// modules2.rs -// You can bring module paths into scopes and provide new names for them with the -// 'use' and 'as' keywords. Fix these 'use' statements to make the code compile. -// Execute `rustlings hint modules2` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -mod delicious_snacks { - // TODO: Fix these use statements - use self::fruits::PEAR as ??? - use self::veggies::CUCUMBER as ??? - - mod fruits { - pub const PEAR: &'static str = "Pear"; - pub const APPLE: &'static str = "Apple"; - } - - mod veggies { - pub const CUCUMBER: &'static str = "Cucumber"; - pub const CARROT: &'static str = "Carrot"; - } -} - -fn main() { - println!( - "favorite snacks: {} and {}", - delicious_snacks::fruit, - delicious_snacks::veggie - ); -} diff --git a/exercises/modules/modules3.rs b/exercises/modules/modules3.rs deleted file mode 100644 index 35e07990ef..0000000000 --- a/exercises/modules/modules3.rs +++ /dev/null @@ -1,18 +0,0 @@ -// modules3.rs -// You can use the 'use' keyword to bring module paths from modules from anywhere -// and especially from the Rust standard library into your scope. -// Bring SystemTime and UNIX_EPOCH -// from the std::time module. Bonus style points if you can do it with one line! -// Execute `rustlings hint modules3` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -// TODO: Complete this use statement -use ??? - -fn main() { - match SystemTime::now().duration_since(UNIX_EPOCH) { - Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()), - Err(_) => panic!("SystemTime before UNIX EPOCH!"), - } -} diff --git a/exercises/move_semantics/move_semantics1.rs b/exercises/move_semantics/move_semantics1.rs deleted file mode 100644 index aac6dfc39c..0000000000 --- a/exercises/move_semantics/move_semantics1.rs +++ /dev/null @@ -1,26 +0,0 @@ -// move_semantics1.rs -// Execute `rustlings hint move_semantics1` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -fn main() { - let vec0 = Vec::new(); - - let vec1 = fill_vec(vec0); - - println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1); - - vec1.push(88); - - println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1); -} - -fn fill_vec(vec: Vec) -> Vec { - let mut vec = vec; - - vec.push(22); - vec.push(44); - vec.push(66); - - vec -} diff --git a/exercises/move_semantics/move_semantics2.rs b/exercises/move_semantics/move_semantics2.rs deleted file mode 100644 index 64870850ec..0000000000 --- a/exercises/move_semantics/move_semantics2.rs +++ /dev/null @@ -1,28 +0,0 @@ -// move_semantics2.rs -// Make me compile without changing line 13 or moving line 10! -// Execute `rustlings hint move_semantics2` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -fn main() { - let vec0 = Vec::new(); - - let mut vec1 = fill_vec(vec0); - - // Do not change the following line! - println!("{} has length {} content `{:?}`", "vec0", vec0.len(), vec0); - - vec1.push(88); - - println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1); -} - -fn fill_vec(vec: Vec) -> Vec { - let mut vec = vec; - - vec.push(22); - vec.push(44); - vec.push(66); - - vec -} diff --git a/exercises/move_semantics/move_semantics3.rs b/exercises/move_semantics/move_semantics3.rs deleted file mode 100644 index eaa30e3344..0000000000 --- a/exercises/move_semantics/move_semantics3.rs +++ /dev/null @@ -1,26 +0,0 @@ -// move_semantics3.rs -// Make me compile without adding new lines-- just changing existing lines! -// (no lines with multiple semicolons necessary!) -// Execute `rustlings hint move_semantics3` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -fn main() { - let vec0 = Vec::new(); - - let mut vec1 = fill_vec(vec0); - - println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1); - - vec1.push(88); - - println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1); -} - -fn fill_vec(vec: Vec) -> Vec { - vec.push(22); - vec.push(44); - vec.push(66); - - vec -} diff --git a/exercises/move_semantics/move_semantics4.rs b/exercises/move_semantics/move_semantics4.rs deleted file mode 100644 index 99834ec34e..0000000000 --- a/exercises/move_semantics/move_semantics4.rs +++ /dev/null @@ -1,30 +0,0 @@ -// move_semantics4.rs -// Refactor this code so that instead of passing `vec0` into the `fill_vec` function, -// the Vector gets created in the function itself and passed back to the main -// function. -// Execute `rustlings hint move_semantics4` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -fn main() { - let vec0 = Vec::new(); - - let mut vec1 = fill_vec(vec0); - - println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1); - - vec1.push(88); - - println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1); -} - -// `fill_vec()` no longer takes `vec: Vec` as argument -fn fill_vec() -> Vec { - let mut vec = vec; - - vec.push(22); - vec.push(44); - vec.push(66); - - vec -} diff --git a/exercises/move_semantics/move_semantics5.rs b/exercises/move_semantics/move_semantics5.rs deleted file mode 100644 index 36eae127ac..0000000000 --- a/exercises/move_semantics/move_semantics5.rs +++ /dev/null @@ -1,15 +0,0 @@ -// move_semantics5.rs -// Make me compile only by reordering the lines in `main()`, but without -// adding, changing or removing any of them. -// Execute `rustlings hint move_semantics5` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -fn main() { - let mut x = 100; - let y = &mut x; - let z = &mut x; - *y += 100; - *z += 1000; - assert_eq!(x, 1200); -} diff --git a/exercises/move_semantics/move_semantics6.rs b/exercises/move_semantics/move_semantics6.rs deleted file mode 100644 index eb52a848d3..0000000000 --- a/exercises/move_semantics/move_semantics6.rs +++ /dev/null @@ -1,25 +0,0 @@ -// move_semantics6.rs -// Execute `rustlings hint move_semantics6` or use the `hint` watch subcommand for a hint. -// You can't change anything except adding or removing references. - -// I AM NOT DONE - -fn main() { - let data = "Rust is great!".to_string(); - - get_char(data); - - string_uppercase(&data); -} - -// Should not take ownership -fn get_char(data: String) -> char { - data.chars().last().unwrap() -} - -// Should take ownership -fn string_uppercase(mut data: &String) { - data = &data.to_uppercase(); - - println!("{}", data); -} diff --git a/exercises/options/options1.rs b/exercises/options/options1.rs deleted file mode 100644 index d1735c2f76..0000000000 --- a/exercises/options/options1.rs +++ /dev/null @@ -1,35 +0,0 @@ -// options1.rs -// Execute `rustlings hint options1` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -// This function returns how much icecream there is left in the fridge. -// If it's before 10PM, there's 5 pieces left. At 10PM, someone eats them -// all, so there'll be no more left :( -// TODO: Return an Option! -fn maybe_icecream(time_of_day: u16) -> Option { - // We use the 24-hour system here, so 10PM is a value of 22 - // The Option output should gracefully handle cases where time_of_day > 24. - ??? -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn check_icecream() { - assert_eq!(maybe_icecream(9), Some(5)); - assert_eq!(maybe_icecream(10), Some(5)); - assert_eq!(maybe_icecream(23), Some(0)); - assert_eq!(maybe_icecream(22), Some(0)); - assert_eq!(maybe_icecream(25), None); - } - - #[test] - fn raw_value() { - // TODO: Fix this test. How do you get at the value contained in the Option? - let icecreams = maybe_icecream(12); - assert_eq!(icecreams, 5); - } -} diff --git a/exercises/options/options2.rs b/exercises/options/options2.rs deleted file mode 100644 index b112047181..0000000000 --- a/exercises/options/options2.rs +++ /dev/null @@ -1,36 +0,0 @@ -// options2.rs -// Execute `rustlings hint options2` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn simple_option() { - let target = "rustlings"; - let optional_target = Some(target); - - // TODO: Make this an if let statement whose value is "Some" type - word = optional_target { - assert_eq!(word, target); - } - } - - #[test] - fn layered_option() { - let mut range = 10; - let mut optional_integers: Vec> = Vec::new(); - for i in 0..(range + 1) { - optional_integers.push(Some(i)); - } - - // TODO: make this a while let statement - remember that vector.pop also adds another layer of Option - // You can stack `Option`'s into while let and if let - integer = optional_integers.pop() { - assert_eq!(integer, range); - range -= 1; - } - } -} diff --git a/exercises/options/options3.rs b/exercises/options/options3.rs deleted file mode 100644 index 3f995c520a..0000000000 --- a/exercises/options/options3.rs +++ /dev/null @@ -1,19 +0,0 @@ -// options3.rs -// Execute `rustlings hint options3` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -struct Point { - x: i32, - y: i32, -} - -fn main() { - let y: Option = Some(Point { x: 100, y: 200 }); - - match y { - Some(p) => println!("Co-ordinates are {},{} ", p.x, p.y), - _ => println!("no match"), - } - y; // Fix without deleting this line. -} diff --git a/exercises/primitive_types/primitive_types1.rs b/exercises/primitive_types/primitive_types1.rs deleted file mode 100644 index 091213925c..0000000000 --- a/exercises/primitive_types/primitive_types1.rs +++ /dev/null @@ -1,19 +0,0 @@ -// primitive_types1.rs -// Fill in the rest of the line that has code missing! -// No hints, there's no tricks, just get used to typing these :) - -// I AM NOT DONE - -fn main() { - // Booleans (`bool`) - - let is_morning = true; - if is_morning { - println!("Good morning!"); - } - - let // Finish the rest of this line like the example! Or make it be false! - if is_evening { - println!("Good evening!"); - } -} diff --git a/exercises/primitive_types/primitive_types3.rs b/exercises/primitive_types/primitive_types3.rs deleted file mode 100644 index fa7d019a44..0000000000 --- a/exercises/primitive_types/primitive_types3.rs +++ /dev/null @@ -1,15 +0,0 @@ -// primitive_types3.rs -// Create an array with at least 100 elements in it where the ??? is. -// Execute `rustlings hint primitive_types3` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -fn main() { - let a = ??? - - if a.len() >= 100 { - println!("Wow, that's a big array!"); - } else { - println!("Meh, I eat arrays like that for breakfast."); - } -} diff --git a/exercises/primitive_types/primitive_types4.rs b/exercises/primitive_types/primitive_types4.rs deleted file mode 100644 index 71fa243cfb..0000000000 --- a/exercises/primitive_types/primitive_types4.rs +++ /dev/null @@ -1,14 +0,0 @@ -// primitive_types4.rs -// Get a slice out of Array a where the ??? is so that the test passes. -// Execute `rustlings hint primitive_types4` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -#[test] -fn slice_out_of_array() { - let a = [1, 2, 3, 4, 5]; - - let nice_slice = ??? - - assert_eq!([2, 3, 4], nice_slice) -} diff --git a/exercises/primitive_types/primitive_types5.rs b/exercises/primitive_types/primitive_types5.rs deleted file mode 100644 index 4fd9141fe6..0000000000 --- a/exercises/primitive_types/primitive_types5.rs +++ /dev/null @@ -1,12 +0,0 @@ -// primitive_types5.rs -// Destructure the `cat` tuple so that the println will work. -// Execute `rustlings hint primitive_types5` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -fn main() { - let cat = ("Furry McFurson", 3.5); - let /* your pattern here */ = cat; - - println!("{} is {} years old.", name, age); -} diff --git a/exercises/primitive_types/primitive_types6.rs b/exercises/primitive_types/primitive_types6.rs deleted file mode 100644 index ddf8b42351..0000000000 --- a/exercises/primitive_types/primitive_types6.rs +++ /dev/null @@ -1,16 +0,0 @@ -// primitive_types6.rs -// Use a tuple index to access the second element of `numbers`. -// You can put the expression for the second element where ??? is so that the test passes. -// Execute `rustlings hint primitive_types6` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -#[test] -fn indexing_tuple() { - let numbers = (1, 2, 3); - // Replace below ??? with the tuple indexing syntax. - let second = ???; - - assert_eq!(2, second, - "This is not the 2nd number in the tuple!") -} diff --git a/exercises/quiz1.rs b/exercises/quiz1.rs deleted file mode 100644 index d1e76e598a..0000000000 --- a/exercises/quiz1.rs +++ /dev/null @@ -1,26 +0,0 @@ -// quiz1.rs -// This is a quiz for the following sections: -// - Variables -// - Functions -// - If - -// Mary is buying apples. One apple usually costs 2 Rustbucks, but if you buy -// 40 or more at once, each apple only costs 1! Write a function that calculates -// the price of an order of apples given the quantity bought. No hints this time! - -// I AM NOT DONE - -// Put your function here! -// fn calculate_price_of_apples { - -// Don't modify this function! -#[test] -fn verify_test() { - let price1 = calculate_price_of_apples(35); - let price2 = calculate_price_of_apples(40); - let price3 = calculate_price_of_apples(65); - - assert_eq!(70, price1); - assert_eq!(80, price2); - assert_eq!(65, price3); -} diff --git a/exercises/quiz2.rs b/exercises/quiz2.rs deleted file mode 100644 index d8fa954aa2..0000000000 --- a/exercises/quiz2.rs +++ /dev/null @@ -1,62 +0,0 @@ -// quiz2.rs -// This is a quiz for the following sections: -// - Strings -// - Vecs -// - Move semantics -// - Modules -// - Enums - -// Let's build a little machine in form of a function. -// As input, we're going to give a list of strings and commands. These commands -// determine what action is going to be applied to the string. It can either be: -// - Uppercase the string -// - Trim the string -// - Append "bar" to the string a specified amount of times -// The exact form of this will be: -// - The input is going to be a Vector of a 2-length tuple, -// the first element is the string, the second one is the command. -// - The output element is going to be a Vector of strings. -// Execute `rustlings hint quiz2` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -pub enum Command { - Uppercase, - Trim, - Append(usize), -} - -mod my_module { - use super::Command; - - // TODO: Complete the function signature! - pub fn transformer(input: ???) -> ??? { - // TODO: Complete the output declaration! - let mut output: ??? = vec![]; - for (string, command) in input.iter() { - // TODO: Complete the function body. You can do it! - } - output - } -} - -#[cfg(test)] -mod tests { - // TODO: What do we have to import to have `transformer` in scope? - use ???; - use super::Command; - - #[test] - fn it_works() { - let output = transformer(vec![ - ("hello".into(), Command::Uppercase), - (" all roads lead to rome! ".into(), Command::Trim), - ("foo".into(), Command::Append(1)), - ("bar".into(), Command::Append(5)), - ]); - assert_eq!(output[0], "HELLO"); - assert_eq!(output[1], "all roads lead to rome!"); - assert_eq!(output[2], "foobar"); - assert_eq!(output[3], "barbarbarbarbarbar"); - } -} diff --git a/exercises/quiz3.rs b/exercises/quiz3.rs deleted file mode 100644 index 15dc46990e..0000000000 --- a/exercises/quiz3.rs +++ /dev/null @@ -1,62 +0,0 @@ -// quiz3.rs -// This quiz tests: -// - Generics -// - Traits -// An imaginary magical school has a new report card generation system written in Rust! -// Currently the system only supports creating report cards where the student's grade -// is represented numerically (e.g. 1.0 -> 5.5). -// However, the school also issues alphabetical grades (A+ -> F-) and needs -// to be able to print both types of report card! - -// Make the necessary code changes in the struct ReportCard and the impl block -// to support alphabetical report cards. Change the Grade in the second test to "A+" -// to show that your changes allow alphabetical grades. - -// Execute `rustlings hint quiz3` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -pub struct ReportCard { - pub grade: f32, - pub student_name: String, - pub student_age: u8, -} - -impl ReportCard { - pub fn print(&self) -> String { - format!("{} ({}) - achieved a grade of {}", - &self.student_name, &self.student_age, &self.grade) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn generate_numeric_report_card() { - let report_card = ReportCard { - grade: 2.1, - student_name: "Tom Wriggle".to_string(), - student_age: 12, - }; - assert_eq!( - report_card.print(), - "Tom Wriggle (12) - achieved a grade of 2.1" - ); - } - - #[test] - fn generate_alphabetic_report_card() { - // TODO: Make sure to change the grade here after you finish the exercise. - let report_card = ReportCard { - grade: 2.1, - student_name: "Gary Plotter".to_string(), - student_age: 11, - }; - assert_eq!( - report_card.print(), - "Gary Plotter (11) - achieved a grade of A+" - ); - } -} diff --git a/exercises/quizzes/README.md b/exercises/quizzes/README.md new file mode 100644 index 0000000000..4d3bcd9450 --- /dev/null +++ b/exercises/quizzes/README.md @@ -0,0 +1,3 @@ +# Quizzes + +After every couple of sections, there will be a quiz in this directory that'll test your knowledge on a bunch of sections at once. diff --git a/exercises/quizzes/quiz1.rs b/exercises/quizzes/quiz1.rs new file mode 100644 index 0000000000..04fb2aaf8d --- /dev/null +++ b/exercises/quizzes/quiz1.rs @@ -0,0 +1,31 @@ +// This is a quiz for the following sections: +// - Variables +// - Functions +// - If +// +// Mary is buying apples. The price of an apple is calculated as follows: +// - An apple costs 2 rustbucks. +// - However, if Mary buys more than 40 apples, the price of each apple in the +// entire order is reduced to only 1 rustbuck! + +// TODO: Write a function that calculates the price of an order of apples given +// the quantity bought. +// fn calculate_price_of_apples(???) -> ??? { ??? } + +fn main() { + // You can optionally experiment here. +} + +// Don't change the tests! +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn verify_test() { + assert_eq!(calculate_price_of_apples(35), 70); + assert_eq!(calculate_price_of_apples(40), 80); + assert_eq!(calculate_price_of_apples(41), 41); + assert_eq!(calculate_price_of_apples(65), 65); + } +} diff --git a/exercises/quizzes/quiz2.rs b/exercises/quizzes/quiz2.rs new file mode 100644 index 0000000000..2cddba907e --- /dev/null +++ b/exercises/quizzes/quiz2.rs @@ -0,0 +1,63 @@ +// This is a quiz for the following sections: +// - Strings +// - Vecs +// - Move semantics +// - Modules +// - Enums +// +// Let's build a little machine in the form of a function. As input, we're going +// to give a list of strings and commands. These commands determine what action +// is going to be applied to the string. It can either be: +// - Uppercase the string +// - Trim the string +// - Append "bar" to the string a specified amount of times +// +// The exact form of this will be: +// - The input is going to be a Vector of 2-length tuples, +// the first element is the string, the second one is the command. +// - The output element is going to be a vector of strings. + +enum Command { + Uppercase, + Trim, + Append(usize), +} + +mod my_module { + use super::Command; + + // TODO: Complete the function as described above. + // pub fn transformer(input: ???) -> ??? { ??? } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + // TODO: What do we need to import to have `transformer` in scope? + // use ???; + use super::Command; + + #[test] + fn it_works() { + let input = vec![ + ("hello".to_string(), Command::Uppercase), + (" all roads lead to rome! ".to_string(), Command::Trim), + ("foo".to_string(), Command::Append(1)), + ("bar".to_string(), Command::Append(5)), + ]; + let output = transformer(input); + + assert_eq!( + output, + [ + "HELLO", + "all roads lead to rome!", + "foobar", + "barbarbarbarbarbar", + ] + ); + } +} diff --git a/exercises/quizzes/quiz3.rs b/exercises/quizzes/quiz3.rs new file mode 100644 index 0000000000..c877c5f8e6 --- /dev/null +++ b/exercises/quizzes/quiz3.rs @@ -0,0 +1,64 @@ +// This quiz tests: +// - Generics +// - Traits +// +// An imaginary magical school has a new report card generation system written +// in Rust! Currently, the system only supports creating report cards where the +// student's grade is represented numerically (e.g. 1.0 -> 5.5). However, the +// school also issues alphabetical grades (A+ -> F-) and needs to be able to +// print both types of report card! +// +// Make the necessary code changes in the struct `ReportCard` and the impl +// block to support alphabetical report cards in addition to numerical ones. + +// TODO: Adjust the struct as described above. +struct ReportCard { + grade: f32, + student_name: String, + student_age: u8, +} + +// TODO: Adjust the impl block as described above. +impl ReportCard { + fn print(&self) -> String { + format!( + "{} ({}) - achieved a grade of {}", + &self.student_name, &self.student_age, &self.grade, + ) + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn generate_numeric_report_card() { + let report_card = ReportCard { + grade: 2.1, + student_name: "Tom Wriggle".to_string(), + student_age: 12, + }; + assert_eq!( + report_card.print(), + "Tom Wriggle (12) - achieved a grade of 2.1", + ); + } + + #[test] + fn generate_alphabetic_report_card() { + let report_card = ReportCard { + grade: "A+", + student_name: "Gary Plotter".to_string(), + student_age: 11, + }; + assert_eq!( + report_card.print(), + "Gary Plotter (11) - achieved a grade of A+", + ); + } +} diff --git a/exercises/standard_library_types/README.md b/exercises/standard_library_types/README.md deleted file mode 100644 index 809d61feb6..0000000000 --- a/exercises/standard_library_types/README.md +++ /dev/null @@ -1,10 +0,0 @@ -# Standard library types - -This section will teach you about Box, Shared-State Concurrency and Iterators. - -## Further information - -- [Using Box to Point to Data on the Heap](https://doc.rust-lang.org/book/ch15-01-box.html) -- [Shared-State Concurrency](https://doc.rust-lang.org/book/ch16-03-shared-state.html) -- [Iterator](https://doc.rust-lang.org/book/ch13-02-iterators.html) -- [Iterator documentation](https://doc.rust-lang.org/stable/std/iter/) diff --git a/exercises/standard_library_types/arc1.rs b/exercises/standard_library_types/arc1.rs deleted file mode 100644 index 93a27036f2..0000000000 --- a/exercises/standard_library_types/arc1.rs +++ /dev/null @@ -1,42 +0,0 @@ -// arc1.rs -// In this exercise, we are given a Vec of u32 called "numbers" with values ranging -// from 0 to 99 -- [ 0, 1, 2, ..., 98, 99 ] -// We would like to use this set of numbers within 8 different threads simultaneously. -// Each thread is going to get the sum of every eighth value, with an offset. -// The first thread (offset 0), will sum 0, 8, 16, ... -// The second thread (offset 1), will sum 1, 9, 17, ... -// The third thread (offset 2), will sum 2, 10, 18, ... -// ... -// The eighth thread (offset 7), will sum 7, 15, 23, ... - -// Because we are using threads, our values need to be thread-safe. Therefore, -// we are using Arc. We need to make a change in each of the two TODOs. - - -// Make this code compile by filling in a value for `shared_numbers` where the -// first TODO comment is, and create an initial binding for `child_numbers` -// where the second TODO comment is. Try not to create any copies of the `numbers` Vec! -// Execute `rustlings hint arc1` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -#![forbid(unused_imports)] // Do not change this, (or the next) line. -use std::sync::Arc; -use std::thread; - -fn main() { - let numbers: Vec<_> = (0..100u32).collect(); - let shared_numbers = // TODO - let mut joinhandles = Vec::new(); - - for offset in 0..8 { - let child_numbers = // TODO - joinhandles.push(thread::spawn(move || { - let sum: u32 = child_numbers.iter().filter(|n| *n % 8 == offset).sum(); - println!("Sum of offset {} is {}", offset, sum); - })); - } - for handle in joinhandles.into_iter() { - handle.join().unwrap(); - } -} diff --git a/exercises/standard_library_types/box1.rs b/exercises/standard_library_types/box1.rs deleted file mode 100644 index 66cf00f329..0000000000 --- a/exercises/standard_library_types/box1.rs +++ /dev/null @@ -1,56 +0,0 @@ -// box1.rs -// -// At compile time, Rust needs to know how much space a type takes up. This becomes problematic -// for recursive types, where a value can have as part of itself another value of the same type. -// To get around the issue, we can use a `Box` - a smart pointer used to store data on the heap, -// which also allows us to wrap a recursive type. -// -// The recursive type we're implementing in this exercise is the `cons list` - a data structure -// frequently found in functional programming languages. Each item in a cons list contains two -// elements: the value of the current item and the next item. The last item is a value called `Nil`. -// -// Step 1: use a `Box` in the enum definition to make the code compile -// Step 2: create both empty and non-empty cons lists by replacing `todo!()` -// -// Note: the tests should not be changed -// -// Execute `rustlings hint box1` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -#[derive(PartialEq, Debug)] -pub enum List { - Cons(i32, List), - Nil, -} - -fn main() { - println!("This is an empty cons list: {:?}", create_empty_list()); - println!( - "This is a non-empty cons list: {:?}", - create_non_empty_list() - ); -} - -pub fn create_empty_list() -> List { - todo!() -} - -pub fn create_non_empty_list() -> List { - todo!() -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_create_empty_list() { - assert_eq!(List::Nil, create_empty_list()) - } - - #[test] - fn test_create_non_empty_list() { - assert_ne!(create_empty_list(), create_non_empty_list()) - } -} diff --git a/exercises/standard_library_types/cow1.rs b/exercises/standard_library_types/cow1.rs deleted file mode 100644 index 5fba2519d3..0000000000 --- a/exercises/standard_library_types/cow1.rs +++ /dev/null @@ -1,48 +0,0 @@ -// cow1.rs - -// This exercise explores the Cow, or Clone-On-Write type. -// Cow is a clone-on-write smart pointer. -// It can enclose and provide immutable access to borrowed data, and clone the data lazily when mutation or ownership is required. -// The type is designed to work with general borrowed data via the Borrow trait. - -// I AM NOT DONE - -use std::borrow::Cow; - -fn abs_all<'a, 'b>(input: &'a mut Cow<'b, [i32]>) -> &'a mut Cow<'b, [i32]> { - for i in 0..input.len() { - let v = input[i]; - if v < 0 { - // Clones into a vector if not already owned. - input.to_mut()[i] = -v; - } - } - input -} - -fn main() { - // No clone occurs because `input` doesn't need to be mutated. - let slice = [0, 1, 2]; - let mut input = Cow::from(&slice[..]); - match abs_all(&mut input) { - Cow::Borrowed(_) => println!("I borrowed the slice!"), - _ => panic!("expected borrowed value"), - } - - // Clone occurs because `input` needs to be mutated. - let slice = [-1, 0, 1]; - let mut input = Cow::from(&slice[..]); - match abs_all(&mut input) { - Cow::Owned(_) => println!("I modified the slice and now own it!"), - _ => panic!("expected owned value"), - } - - // No clone occurs because `input` is already owned. - let slice = vec![-1, 0, 1]; - let mut input = Cow::from(slice); - match abs_all(&mut input) { - // TODO - Cow::Borrowed(_) => println!("I own this slice!"), - _ => panic!("expected borrowed value"), - } -} diff --git a/exercises/standard_library_types/iterators1.rs b/exercises/standard_library_types/iterators1.rs deleted file mode 100644 index 0379c6bb41..0000000000 --- a/exercises/standard_library_types/iterators1.rs +++ /dev/null @@ -1,24 +0,0 @@ -// iterators1.rs -// -// Make me compile by filling in the `???`s -// -// When performing operations on elements within a collection, iterators are essential. -// This module helps you get familiar with the structure of using an iterator and -// how to go through elements within an iterable collection. -// -// Execute `rustlings hint iterators1` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -fn main () { - let my_fav_fruits = vec!["banana", "custard apple", "avocado", "peach", "raspberry"]; - - let mut my_iterable_fav_fruits = ???; // TODO: Step 1 - - assert_eq!(my_iterable_fav_fruits.next(), Some(&"banana")); - assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 2 - assert_eq!(my_iterable_fav_fruits.next(), Some(&"avocado")); - assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 3 - assert_eq!(my_iterable_fav_fruits.next(), Some(&"raspberry")); - assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 4 -} diff --git a/exercises/standard_library_types/iterators3.rs b/exercises/standard_library_types/iterators3.rs deleted file mode 100644 index c97a625877..0000000000 --- a/exercises/standard_library_types/iterators3.rs +++ /dev/null @@ -1,85 +0,0 @@ -// iterators3.rs -// This is a bigger exercise than most of the others! You can do it! -// Here is your mission, should you choose to accept it: -// 1. Complete the divide function to get the first four tests to pass. -// 2. Get the remaining tests to pass by completing the result_with_list and -// list_of_results functions. -// Execute `rustlings hint iterators3` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -#[derive(Debug, PartialEq, Eq)] -pub enum DivisionError { - NotDivisible(NotDivisibleError), - DivideByZero, -} - -#[derive(Debug, PartialEq, Eq)] -pub struct NotDivisibleError { - dividend: i32, - divisor: i32, -} - -// Calculate `a` divided by `b` if `a` is evenly divisible by `b`. -// Otherwise, return a suitable error. -pub fn divide(a: i32, b: i32) -> Result { - todo!(); -} - -// Complete the function and return a value of the correct type so the test passes. -// Desired output: Ok([1, 11, 1426, 3]) -fn result_with_list() -> () { - let numbers = vec![27, 297, 38502, 81]; - let division_results = numbers.into_iter().map(|n| divide(n, 27)); -} - -// Complete the function and return a value of the correct type so the test passes. -// Desired output: [Ok(1), Ok(11), Ok(1426), Ok(3)] -fn list_of_results() -> () { - let numbers = vec![27, 297, 38502, 81]; - let division_results = numbers.into_iter().map(|n| divide(n, 27)); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_success() { - assert_eq!(divide(81, 9), Ok(9)); - } - - #[test] - fn test_not_divisible() { - assert_eq!( - divide(81, 6), - Err(DivisionError::NotDivisible(NotDivisibleError { - dividend: 81, - divisor: 6 - })) - ); - } - - #[test] - fn test_divide_by_0() { - assert_eq!(divide(81, 0), Err(DivisionError::DivideByZero)); - } - - #[test] - fn test_divide_0_by_something() { - assert_eq!(divide(0, 81), Ok(0)); - } - - #[test] - fn test_result_with_list() { - assert_eq!(format!("{:?}", result_with_list()), "Ok([1, 11, 1426, 3])"); - } - - #[test] - fn test_list_of_results() { - assert_eq!( - format!("{:?}", list_of_results()), - "[Ok(1), Ok(11), Ok(1426), Ok(3)]" - ); - } -} diff --git a/exercises/standard_library_types/iterators4.rs b/exercises/standard_library_types/iterators4.rs deleted file mode 100644 index a02470ec14..0000000000 --- a/exercises/standard_library_types/iterators4.rs +++ /dev/null @@ -1,40 +0,0 @@ -// iterators4.rs -// Execute `rustlings hint iterators4` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -pub fn factorial(num: u64) -> u64 { - // Complete this function to return the factorial of num - // Do not use: - // - return - // Try not to use: - // - imperative style loops (for, while) - // - additional variables - // For an extra challenge, don't use: - // - recursion - // Execute `rustlings hint iterators4` for hints. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn factorial_of_0() { - assert_eq!(1, factorial(0)); - } - - #[test] - fn factorial_of_1() { - assert_eq!(1, factorial(1)); - } - #[test] - fn factorial_of_2() { - assert_eq!(2, factorial(2)); - } - - #[test] - fn factorial_of_4() { - assert_eq!(24, factorial(4)); - } -} diff --git a/exercises/standard_library_types/rc1.rs b/exercises/standard_library_types/rc1.rs deleted file mode 100644 index 9b907fde8c..0000000000 --- a/exercises/standard_library_types/rc1.rs +++ /dev/null @@ -1,98 +0,0 @@ -// rc1.rs -// In this exercise, we want to express the concept of multiple owners via the Rc type. -// This is a model of our solar system - there is a Sun type and multiple Planets. -// The Planets take ownership of the sun, indicating that they revolve around the sun. - -// Make this code compile by using the proper Rc primitives to express that the sun has multiple owners. - -// I AM NOT DONE -use std::rc::Rc; - -#[derive(Debug)] -struct Sun {} - -#[derive(Debug)] -enum Planet { - Mercury(Rc), - Venus(Rc), - Earth(Rc), - Mars(Rc), - Jupiter(Rc), - Saturn(Rc), - Uranus(Rc), - Neptune(Rc), -} - -impl Planet { - fn details(&self) { - println!("Hi from {:?}!", self) - } -} - -fn main() { - let sun = Rc::new(Sun {}); - println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference - - let mercury = Planet::Mercury(Rc::clone(&sun)); - println!("reference count = {}", Rc::strong_count(&sun)); // 2 references - mercury.details(); - - let venus = Planet::Venus(Rc::clone(&sun)); - println!("reference count = {}", Rc::strong_count(&sun)); // 3 references - venus.details(); - - let earth = Planet::Earth(Rc::clone(&sun)); - println!("reference count = {}", Rc::strong_count(&sun)); // 4 references - earth.details(); - - let mars = Planet::Mars(Rc::clone(&sun)); - println!("reference count = {}", Rc::strong_count(&sun)); // 5 references - mars.details(); - - let jupiter = Planet::Jupiter(Rc::clone(&sun)); - println!("reference count = {}", Rc::strong_count(&sun)); // 6 references - jupiter.details(); - - // TODO - let saturn = Planet::Saturn(Rc::new(Sun {})); - println!("reference count = {}", Rc::strong_count(&sun)); // 7 references - saturn.details(); - - // TODO - let uranus = Planet::Uranus(Rc::new(Sun {})); - println!("reference count = {}", Rc::strong_count(&sun)); // 8 references - uranus.details(); - - // TODO - let neptune = Planet::Neptune(Rc::new(Sun {})); - println!("reference count = {}", Rc::strong_count(&sun)); // 9 references - neptune.details(); - - assert_eq!(Rc::strong_count(&sun), 9); - - drop(neptune); - println!("reference count = {}", Rc::strong_count(&sun)); // 8 references - - drop(uranus); - println!("reference count = {}", Rc::strong_count(&sun)); // 7 references - - drop(saturn); - println!("reference count = {}", Rc::strong_count(&sun)); // 6 references - - drop(jupiter); - println!("reference count = {}", Rc::strong_count(&sun)); // 5 references - - drop(mars); - println!("reference count = {}", Rc::strong_count(&sun)); // 4 references - - // TODO - println!("reference count = {}", Rc::strong_count(&sun)); // 3 references - - // TODO - println!("reference count = {}", Rc::strong_count(&sun)); // 2 references - - // TODO - println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference - - assert_eq!(Rc::strong_count(&sun), 1); -} diff --git a/exercises/strings/strings1.rs b/exercises/strings/strings1.rs deleted file mode 100644 index 0de86a1dbf..0000000000 --- a/exercises/strings/strings1.rs +++ /dev/null @@ -1,14 +0,0 @@ -// strings1.rs -// Make me compile without changing the function signature! -// Execute `rustlings hint strings1` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -fn main() { - let answer = current_favorite_color(); - println!("My current favorite color is {}", answer); -} - -fn current_favorite_color() -> String { - "blue" -} diff --git a/exercises/strings/strings3.rs b/exercises/strings/strings3.rs deleted file mode 100644 index e2353aecc9..0000000000 --- a/exercises/strings/strings3.rs +++ /dev/null @@ -1,43 +0,0 @@ -// strings3.rs -// Execute `rustlings hint strings3` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -fn trim_me(input: &str) -> String { - // TODO: Remove whitespace from both ends of a string! - ??? -} - -fn compose_me(input: &str) -> String { - // TODO: Add " world!" to the string! There's multiple ways to do this! - ??? -} - -fn replace_me(input: &str) -> String { - // TODO: Replace "cars" in the string with "balloons"! - ??? -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn trim_a_string() { - assert_eq!(trim_me("Hello! "), "Hello!"); - assert_eq!(trim_me(" What's up!"), "What's up!"); - assert_eq!(trim_me(" Hola! "), "Hola!"); - } - - #[test] - fn compose_a_string() { - assert_eq!(compose_me("Hello"), "Hello world!"); - assert_eq!(compose_me("Goodbye"), "Goodbye world!"); - } - - #[test] - fn replace_a_string() { - assert_eq!(replace_me("I think cars are cool"), "I think balloons are cool"); - assert_eq!(replace_me("I love to look at cars"), "I love to look at balloons"); - } -} diff --git a/exercises/strings/strings4.rs b/exercises/strings/strings4.rs deleted file mode 100644 index c410b56252..0000000000 --- a/exercises/strings/strings4.rs +++ /dev/null @@ -1,29 +0,0 @@ -// strings4.rs - -// Ok, here are a bunch of values-- some are `String`s, some are `&str`s. Your -// task is to call one of these two functions on each value depending on what -// you think each value is. That is, add either `string_slice` or `string` -// before the parentheses on each line. If you're right, it will compile! -// No hints this time! - -// I AM NOT DONE - -fn string_slice(arg: &str) { - println!("{}", arg); -} -fn string(arg: String) { - println!("{}", arg); -} - -fn main() { - ???("blue"); - ???("red".to_string()); - ???(String::from("hi")); - ???("rust is fun!".to_owned()); - ???("nice weather".into()); - ???(format!("Interpolation {}", "Station")); - ???(&String::from("abc")[0..1]); - ???(" hello there ".trim()); - ???("Happy Monday!".to_string().replace("Mon", "Tues")); - ???("mY sHiFt KeY iS sTiCkY".to_lowercase()); -} diff --git a/exercises/structs/structs1.rs b/exercises/structs/structs1.rs deleted file mode 100644 index 0d91c469e5..0000000000 --- a/exercises/structs/structs1.rs +++ /dev/null @@ -1,48 +0,0 @@ -// structs1.rs -// Address all the TODOs to make the tests pass! -// Execute `rustlings hint structs1` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -struct ColorClassicStruct { - // TODO: Something goes here -} - -struct ColorTupleStruct(/* TODO: Something goes here */); - -#[derive(Debug)] -struct UnitLikeStruct; - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn classic_c_structs() { - // TODO: Instantiate a classic c struct! - // let green = - - assert_eq!(green.red, 0); - assert_eq!(green.green, 255); - assert_eq!(green.blue, 0); - } - - #[test] - fn tuple_structs() { - // TODO: Instantiate a tuple struct! - // let green = - - assert_eq!(green.0, 0); - assert_eq!(green.1, 255); - assert_eq!(green.2, 0); - } - - #[test] - fn unit_structs() { - // TODO: Instantiate a unit-like struct! - // let unit_like_struct = - let message = format!("{:?}s are fun!", unit_like_struct); - - assert_eq!(message, "UnitLikeStructs are fun!"); - } -} diff --git a/exercises/tests/tests1.rs b/exercises/tests/tests1.rs deleted file mode 100644 index 8b6ea37469..0000000000 --- a/exercises/tests/tests1.rs +++ /dev/null @@ -1,18 +0,0 @@ -// tests1.rs -// Tests are important to ensure that your code does what you think it should do. -// Tests can be run on this file with the following command: -// rustlings run tests1 - -// This test has a problem with it -- make the test compile! Make the test -// pass! Make the test fail! -// Execute `rustlings hint tests1` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -#[cfg(test)] -mod tests { - #[test] - fn you_can_assert() { - assert!(); - } -} diff --git a/exercises/tests/tests2.rs b/exercises/tests/tests2.rs deleted file mode 100644 index a5ac15b11f..0000000000 --- a/exercises/tests/tests2.rs +++ /dev/null @@ -1,14 +0,0 @@ -// tests2.rs -// This test has a problem with it -- make the test compile! Make the test -// pass! Make the test fail! -// Execute `rustlings hint tests2` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -#[cfg(test)] -mod tests { - #[test] - fn you_can_assert_eq() { - assert_eq!(); - } -} diff --git a/exercises/tests/tests3.rs b/exercises/tests/tests3.rs deleted file mode 100644 index 196a81a0e5..0000000000 --- a/exercises/tests/tests3.rs +++ /dev/null @@ -1,26 +0,0 @@ -// tests3.rs -// This test isn't testing our function -- make it do that in such a way that -// the test passes. Then write a second test that tests whether we get the result -// we expect to get when we call `is_even(5)`. -// Execute `rustlings hint tests3` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -pub fn is_even(num: i32) -> bool { - num % 2 == 0 -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn is_true_when_even() { - assert!(); - } - - #[test] - fn is_false_when_odd() { - assert!(); - } -} diff --git a/exercises/threads/threads1.rs b/exercises/threads/threads1.rs deleted file mode 100644 index e59f4ce490..0000000000 --- a/exercises/threads/threads1.rs +++ /dev/null @@ -1,31 +0,0 @@ -// threads1.rs -// Execute `rustlings hint threads1` or use the `hint` watch subcommand for a hint. -// This program should wait until all the spawned threads have finished before exiting. - -// I AM NOT DONE - -use std::thread; -use std::time::Duration; - - -fn main() { - - let mut handles = vec![]; - for i in 0..10 { - thread::spawn(move || { - thread::sleep(Duration::from_millis(250)); - println!("thread {} is complete", i); - }); - } - - let mut completed_threads = 0; - for handle in handles { - // TODO: a struct is returned from thread::spawn, can you use it? - completed_threads += 1; - } - - if completed_threads != 10 { - panic!("Oh no! All the spawned threads did not finish!"); - } - -} diff --git a/exercises/threads/threads2.rs b/exercises/threads/threads2.rs deleted file mode 100644 index d0f8578f02..0000000000 --- a/exercises/threads/threads2.rs +++ /dev/null @@ -1,34 +0,0 @@ -// threads2.rs -// Execute `rustlings hint threads2` or use the `hint` watch subcommand for a hint. -// Building on the last exercise, we want all of the threads to complete their work but this time -// the spawned threads need to be in charge of updating a shared value: JobStatus.jobs_completed - -// I AM NOT DONE - -use std::sync::Arc; -use std::thread; -use std::time::Duration; - -struct JobStatus { - jobs_completed: u32, -} - -fn main() { - let status = Arc::new(JobStatus { jobs_completed: 0 }); - let mut handles = vec![]; - for _ in 0..10 { - let status_shared = status.clone(); - let handle = thread::spawn(move || { - thread::sleep(Duration::from_millis(250)); - // TODO: You must take an action before you update a shared value - status_shared.jobs_completed += 1; - }); - handles.push(handle); - } - for handle in handles { - handle.join().unwrap(); - // TODO: Print the value of the JobStatus.jobs_completed. Did you notice anything - // interesting in the output? Do you have to 'join' on all the handles? - println!("jobs completed {}", ???); - } -} diff --git a/exercises/threads/threads3.rs b/exercises/threads/threads3.rs deleted file mode 100644 index 27e9908829..0000000000 --- a/exercises/threads/threads3.rs +++ /dev/null @@ -1,64 +0,0 @@ -// threads3.rs -// Execute `rustlings hint threads3` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -use std::sync::mpsc; -use std::sync::Arc; -use std::thread; -use std::time::Duration; - -struct Queue { - length: u32, - first_half: Vec, - second_half: Vec, -} - -impl Queue { - fn new() -> Self { - Queue { - length: 10, - first_half: vec![1, 2, 3, 4, 5], - second_half: vec![6, 7, 8, 9, 10], - } - } -} - -fn send_tx(q: Queue, tx: mpsc::Sender) -> () { - let qc = Arc::new(q); - let qc1 = qc.clone(); - let qc2 = qc.clone(); - - thread::spawn(move || { - for val in &qc1.first_half { - println!("sending {:?}", val); - tx.send(*val).unwrap(); - thread::sleep(Duration::from_secs(1)); - } - }); - - thread::spawn(move || { - for val in &qc2.second_half { - println!("sending {:?}", val); - tx.send(*val).unwrap(); - thread::sleep(Duration::from_secs(1)); - } - }); -} - -fn main() { - let (tx, rx) = mpsc::channel(); - let queue = Queue::new(); - let queue_length = queue.length; - - send_tx(queue, tx); - - let mut total_received: u32 = 0; - for received in rx { - println!("Got: {}", received); - total_received += 1; - } - - println!("total numbers received: {}", total_received); - assert_eq!(total_received, queue_length) -} diff --git a/exercises/traits/traits1.rs b/exercises/traits/traits1.rs deleted file mode 100644 index 5b9d8d5064..0000000000 --- a/exercises/traits/traits1.rs +++ /dev/null @@ -1,44 +0,0 @@ -// traits1.rs -// Time to implement some traits! -// -// Your task is to implement the trait -// `AppendBar' for the type `String'. -// -// The trait AppendBar has only one function, -// which appends "Bar" to any object -// implementing this trait. -// Execute `rustlings hint traits1` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -trait AppendBar { - fn append_bar(self) -> Self; -} - -impl AppendBar for String { - //Add your code here -} - -fn main() { - let s = String::from("Foo"); - let s = s.append_bar(); - println!("s: {}", s); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn is_foo_bar() { - assert_eq!(String::from("Foo").append_bar(), String::from("FooBar")); - } - - #[test] - fn is_bar_bar() { - assert_eq!( - String::from("").append_bar().append_bar(), - String::from("BarBar") - ); - } -} diff --git a/exercises/traits/traits2.rs b/exercises/traits/traits2.rs deleted file mode 100644 index 708bb19a00..0000000000 --- a/exercises/traits/traits2.rs +++ /dev/null @@ -1,32 +0,0 @@ -// traits2.rs -// -// Your task is to implement the trait -// `AppendBar' for a vector of strings. -// -// To implement this trait, consider for -// a moment what it means to 'append "Bar"' -// to a vector of strings. -// -// No boiler plate code this time, -// you can do this! -// Execute `rustlings hint traits2` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -trait AppendBar { - fn append_bar(self) -> Self; -} - -//TODO: Add your code here - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn is_vec_pop_eq_bar() { - let mut foo = vec![String::from("Foo")].append_bar(); - assert_eq!(foo.pop().unwrap(), String::from("Bar")); - assert_eq!(foo.pop().unwrap(), String::from("Foo")); - } -} diff --git a/exercises/traits/traits4.rs b/exercises/traits/traits4.rs deleted file mode 100644 index 6b541665ff..0000000000 --- a/exercises/traits/traits4.rs +++ /dev/null @@ -1,46 +0,0 @@ -// traits4.rs -// -// Your task is to replace the '??' sections so the code compiles. -// Don't change any line other than the marked one. -// Execute `rustlings hint traits4` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -pub trait Licensed { - fn licensing_info(&self) -> String { - "some information".to_string() - } -} - -struct SomeSoftware {} - -struct OtherSoftware {} - -impl Licensed for SomeSoftware {} -impl Licensed for OtherSoftware {} - -// YOU MAY ONLY CHANGE THE NEXT LINE -fn compare_license_types(software: ??, software_two: ??) -> bool { - software.licensing_info() == software_two.licensing_info() -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn compare_license_information() { - let some_software = SomeSoftware {}; - let other_software = OtherSoftware {}; - - assert!(compare_license_types(some_software, other_software)); - } - - #[test] - fn compare_license_information_backwards() { - let some_software = SomeSoftware {}; - let other_software = OtherSoftware {}; - - assert!(compare_license_types(other_software, some_software)); - } -} diff --git a/exercises/traits/traits5.rs b/exercises/traits/traits5.rs deleted file mode 100644 index 0fbca28aec..0000000000 --- a/exercises/traits/traits5.rs +++ /dev/null @@ -1,37 +0,0 @@ -// traits5.rs -// -// Your task is to replace the '??' sections so the code compiles. -// Don't change any line other than the marked one. -// Execute `rustlings hint traits5` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -pub trait SomeTrait { - fn some_function(&self) -> bool { - true - } -} - -pub trait OtherTrait { - fn other_function(&self) -> bool { - true - } -} - -struct SomeStruct {} -struct OtherStruct {} - -impl SomeTrait for SomeStruct {} -impl OtherTrait for SomeStruct {} -impl SomeTrait for OtherStruct {} -impl OtherTrait for OtherStruct {} - -// YOU MAY ONLY CHANGE THE NEXT LINE -fn some_func(item: ??) -> bool { - item.some_function() && item.other_function() -} - -fn main() { - some_func(SomeStruct {}); - some_func(OtherStruct {}); -} diff --git a/exercises/variables/variables1.rs b/exercises/variables/variables1.rs deleted file mode 100644 index f4d182accf..0000000000 --- a/exercises/variables/variables1.rs +++ /dev/null @@ -1,10 +0,0 @@ -// variables1.rs -// Make me compile! -// Execute `rustlings hint variables1` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -fn main() { - x = 5; - println!("x has the value {}", x); -} diff --git a/exercises/variables/variables3.rs b/exercises/variables/variables3.rs deleted file mode 100644 index 819b1bc791..0000000000 --- a/exercises/variables/variables3.rs +++ /dev/null @@ -1,9 +0,0 @@ -// variables3.rs -// Execute `rustlings hint variables3` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -fn main() { - let x: i32; - println!("Number {}", x); -} diff --git a/exercises/variables/variables4.rs b/exercises/variables/variables4.rs deleted file mode 100644 index 54491b0a20..0000000000 --- a/exercises/variables/variables4.rs +++ /dev/null @@ -1,11 +0,0 @@ -// variables4.rs -// Execute `rustlings hint variables4` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -fn main() { - let x = 3; - println!("Number {}", x); - x = 5; // don't change this line - println!("Number {}", x); -} diff --git a/exercises/variables/variables5.rs b/exercises/variables/variables5.rs deleted file mode 100644 index 0e670d2afe..0000000000 --- a/exercises/variables/variables5.rs +++ /dev/null @@ -1,11 +0,0 @@ -// variables5.rs -// Execute `rustlings hint variables5` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -fn main() { - let number = "T-H-R-E-E"; // don't change this line - println!("Spell a Number : {}", number); - number = 3; // don't rename this variable - println!("Number plus two is : {}", number + 2); -} diff --git a/exercises/variables/variables6.rs b/exercises/variables/variables6.rs deleted file mode 100644 index a8520122c5..0000000000 --- a/exercises/variables/variables6.rs +++ /dev/null @@ -1,9 +0,0 @@ -// variables6.rs -// Execute `rustlings hint variables6` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -const NUMBER = 3; -fn main() { - println!("Number {}", NUMBER); -} diff --git a/exercises/vecs/vecs1.rs b/exercises/vecs/vecs1.rs deleted file mode 100644 index 4e8c4cbbb7..0000000000 --- a/exercises/vecs/vecs1.rs +++ /dev/null @@ -1,25 +0,0 @@ -// vecs1.rs -// Your task is to create a `Vec` which holds the exact same elements -// as in the array `a`. -// Make me compile and pass the test! -// Execute `rustlings hint vecs1` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -fn array_and_vec() -> ([i32; 4], Vec) { - let a = [10, 20, 30, 40]; // a plain array - let v = // TODO: declare your vector here with the macro for vectors - - (a, v) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_array_and_vec_similarity() { - let (a, v) = array_and_vec(); - assert_eq!(a, v[..]); - } -} diff --git a/exercises/vecs/vecs2.rs b/exercises/vecs/vecs2.rs deleted file mode 100644 index 5bea09a2c2..0000000000 --- a/exercises/vecs/vecs2.rs +++ /dev/null @@ -1,49 +0,0 @@ -// vecs2.rs -// A Vec of even numbers is given. Your task is to complete the loop -// so that each number in the Vec is multiplied by 2. -// -// Make me pass the test! -// -// Execute `rustlings hint vecs2` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -fn vec_loop(mut v: Vec) -> Vec { - for i in v.iter_mut() { - // TODO: Fill this up so that each element in the Vec `v` is - // multiplied by 2. - ??? - } - - // At this point, `v` should be equal to [4, 8, 12, 16, 20]. - v -} - -fn vec_map(v: &Vec) -> Vec { - v.iter().map(|num| { - // TODO: Do the same thing as above - but instead of mutating the - // Vec, you can just return the new number! - ??? - }).collect() -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_vec_loop() { - let v: Vec = (1..).filter(|x| x % 2 == 0).take(5).collect(); - let ans = vec_loop(v.clone()); - - assert_eq!(ans, v.iter().map(|x| x * 2).collect::>()); - } - - #[test] - fn test_vec_map() { - let v: Vec = (1..).filter(|x| x % 2 == 0).take(5).collect(); - let ans = vec_map(&v); - - assert_eq!(ans, v.iter().map(|x| x * 2).collect::>()); - } -} diff --git a/info.toml b/info.toml deleted file mode 100644 index 060643d7ae..0000000000 --- a/info.toml +++ /dev/null @@ -1,1163 +0,0 @@ -# INTRO - -[[exercises]] -name = "intro1" -path = "exercises/intro/intro1.rs" -mode = "compile" -hint = """ -Remove the I AM NOT DONE comment in the exercises/intro/intro1.rs file -to move on to the next exercise.""" - -[[exercises]] -name = "intro2" -path = "exercises/intro/intro2.rs" -mode = "compile" -hint = """ -Add an argument after the format string.""" - -# VARIABLES - -[[exercises]] -name = "variables1" -path = "exercises/variables/variables1.rs" -mode = "compile" -hint = """ -The declaration on line 8 is missing a keyword that is needed in Rust -to create a new variable binding.""" - -[[exercises]] -name = "variables2" -path = "exercises/variables/variables2.rs" -mode = "compile" -hint = """ -The compiler message is saying that Rust cannot infer the type that the -variable binding `x` has with what is given here. -What happens if you annotate line 7 with a type annotation? -What if you give x a value? -What if you do both? -What type should x be, anyway? -What if x is the same type as 10? What if it's a different type?""" - -[[exercises]] -name = "variables3" -path = "exercises/variables/variables3.rs" -mode = "compile" -hint = """ -Oops! In this exercise, we have a variable binding that we've created on -line 7, and we're trying to use it on line 8, but we haven't given it a -value. We can't print out something that isn't there; try giving x a value! -This is an error that can cause bugs that's very easy to make in any -programming language -- thankfully the Rust compiler has caught this for us!""" - -[[exercises]] -name = "variables4" -path = "exercises/variables/variables4.rs" -mode = "compile" -hint = """ -In Rust, variable bindings are immutable by default. But here we're trying -to reassign a different value to x! There's a keyword we can use to make -a variable binding mutable instead.""" - -[[exercises]] -name = "variables5" -path = "exercises/variables/variables5.rs" -mode = "compile" -hint = """ -In variables4 we already learned how to make an immutable variable mutable -using a special keyword. Unfortunately this doesn't help us much in this exercise -because we want to assign a different typed value to an existing variable. Sometimes -you may also like to reuse existing variable names because you are just converting -values to different types like in this exercise. -Fortunately Rust has a powerful solution to this problem: 'Shadowing'! -You can read more about 'Shadowing' in the book's section 'Variables and Mutability': -https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html#shadowing -Try to solve this exercise afterwards using this technique.""" - -[[exercises]] -name = "variables6" -path = "exercises/variables/variables6.rs" -mode = "compile" -hint = """ -We know about variables and mutability, but there is another important type of -variable available: constants. -Constants are always immutable and they are declared with keyword 'const' rather -than keyword 'let'. -Constants types must also always be annotated. - -Read more about constants and the differences between variables and constants under 'Constants' in the book's section 'Variables and Mutability': -https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html#constants -""" - -# FUNCTIONS - -[[exercises]] -name = "functions1" -path = "exercises/functions/functions1.rs" -mode = "compile" -hint = """ -This main function is calling a function that it expects to exist, but the -function doesn't exist. It expects this function to have the name `call_me`. -It expects this function to not take any arguments and not return a value. -Sounds a lot like `main`, doesn't it?""" - -[[exercises]] -name = "functions2" -path = "exercises/functions/functions2.rs" -mode = "compile" -hint = """ -Rust requires that all parts of a function's signature have type annotations, -but `call_me` is missing the type annotation of `num`.""" - -[[exercises]] -name = "functions3" -path = "exercises/functions/functions3.rs" -mode = "compile" -hint = """ -This time, the function *declaration* is okay, but there's something wrong -with the place where we're calling the function. -As a reminder, you can freely play around with different solutions in Rustlings! -Watch mode will only jump to the next exercise if you remove the I AM NOT DONE comment.""" - -[[exercises]] -name = "functions4" -path = "exercises/functions/functions4.rs" -mode = "compile" -hint = """ -The error message points to line 17 and says it expects a type after the -`->`. This is where the function's return type should be -- take a look at -the `is_even` function for an example! - -Also: Did you figure out that, technically, u32 would be the more fitting type -for the prices here, since they can't be negative? If so, kudos!""" - -[[exercises]] -name = "functions5" -path = "exercises/functions/functions5.rs" -mode = "compile" -hint = """ -This is a really common error that can be fixed by removing one character. -It happens because Rust distinguishes between expressions and statements: expressions return a value based on their operand(s), and statements simply return a () type which behaves just like `void` in C/C++ language. -We want to return a value of `i32` type from the `square` function, but it is returning a `()` type... -They are not the same. There are two solutions: -1. Add a `return` ahead of `num * num;` -2. remove `;`, make it to be `num * num`""" - -# IF - -[[exercises]] -name = "if1" -path = "exercises/if/if1.rs" -mode = "test" -hint = """ -It's possible to do this in one line if you would like! -Some similar examples from other languages: -- In C(++) this would be: `a > b ? a : b` -- In Python this would be: `a if a > b else b` -Remember in Rust that: -- the `if` condition does not need to be surrounded by parentheses -- `if`/`else` conditionals are expressions -- Each condition is followed by a `{}` block.""" - -[[exercises]] -name = "if2" -path = "exercises/if/if2.rs" -mode = "test" -hint = """ -For that first compiler error, it's important in Rust that each conditional -block returns the same type! To get the tests passing, you will need a couple -conditions checking different input values.""" - -# QUIZ 1 - -[[exercises]] -name = "quiz1" -path = "exercises/quiz1.rs" -mode = "test" -hint = "No hints this time ;)" - -# PRIMITIVE TYPES - -[[exercises]] -name = "primitive_types1" -path = "exercises/primitive_types/primitive_types1.rs" -mode = "compile" -hint = "No hints this time ;)" - -[[exercises]] -name = "primitive_types2" -path = "exercises/primitive_types/primitive_types2.rs" -mode = "compile" -hint = "No hints this time ;)" - -[[exercises]] -name = "primitive_types3" -path = "exercises/primitive_types/primitive_types3.rs" -mode = "compile" -hint = """ -There's a shorthand to initialize Arrays with a certain size that does not -require you to type in 100 items (but you certainly can if you want!). -For example, you can do: -let array = ["Are we there yet?"; 10]; - -Bonus: what are some other things you could have that would return true -for `a.len() >= 100`?""" - -[[exercises]] -name = "primitive_types4" -path = "exercises/primitive_types/primitive_types4.rs" -mode = "test" -hint = """ -Take a look at the Understanding Ownership -> Slices -> Other Slices section of the book: -https://doc.rust-lang.org/book/ch04-03-slices.html -and use the starting and ending indices of the items in the Array -that you want to end up in the slice. - -If you're curious why the first argument of `assert_eq!` does not -have an ampersand for a reference since the second argument is a -reference, take a look at the coercion chapter of the nomicon: -https://doc.rust-lang.org/nomicon/coercions.html""" - -[[exercises]] -name = "primitive_types5" -path = "exercises/primitive_types/primitive_types5.rs" -mode = "compile" -hint = """ -Take a look at the Data Types -> The Tuple Type section of the book: -https://doc.rust-lang.org/book/ch03-02-data-types.html#the-tuple-type -Particularly the part about destructuring (second to last example in the section). -You'll need to make a pattern to bind `name` and `age` to the appropriate parts -of the tuple. You can do it!!""" - -[[exercises]] -name = "primitive_types6" -path = "exercises/primitive_types/primitive_types6.rs" -mode = "test" -hint = """ -While you could use a destructuring `let` for the tuple here, try -indexing into it instead, as explained in the last example of the -Data Types -> The Tuple Type section of the book: -https://doc.rust-lang.org/book/ch03-02-data-types.html#the-tuple-type -Now you have another tool in your toolbox!""" - -# VECS - -[[exercises]] -name = "vecs1" -path = "exercises/vecs/vecs1.rs" -mode = "test" -hint = """ -In Rust, there are two ways to define a Vector. -1. One way is to use the `Vec::new()` function to create a new vector - and fill it with the `push()` method. -2. The second way, which is simpler is to use the `vec![]` macro and - define your elements inside the square brackets. -Check this chapter: https://doc.rust-lang.org/stable/book/ch08-01-vectors.html -of the Rust book to learn more. -""" - -[[exercises]] -name = "vecs2" -path = "exercises/vecs/vecs2.rs" -mode = "test" -hint = """ -Hint 1: `i` is each element from the Vec as they are being iterated. Can you try -multiplying this? - -Hint 2: For the first function, there's a way to directly access the numbers stored -in the Vec, using the * dereference operator. You can both access and write to the -number that way. - -After you've completed both functions, decide for yourself which approach you like -better. What do you think is the more commonly used pattern under Rust developers? -""" - -# MOVE SEMANTICS - -[[exercises]] -name = "move_semantics1" -path = "exercises/move_semantics/move_semantics1.rs" -mode = "compile" -hint = """ -So you've got the "cannot borrow immutable local variable `vec1` as mutable" error on line 13, -right? The fix for this is going to be adding one keyword, and the addition is NOT on line 13 -where the error is. - -Also: Try accessing `vec0` after having called `fill_vec()`. See what happens!""" - -[[exercises]] -name = "move_semantics2" -path = "exercises/move_semantics/move_semantics2.rs" -mode = "compile" -hint = """ -So, `vec0` is passed into the `fill_vec` function as an argument. In Rust, -when an argument is passed to a function and it's not explicitly returned, -you can't use the original variable anymore. We call this "moving" a variable. -Variables that are moved into a function (or block scope) and aren't explicitly -returned get "dropped" at the end of that function. This is also what happens here. -There's a few ways to fix this, try them all if you want: -1. Make another, separate version of the data that's in `vec0` and pass that - to `fill_vec` instead. -2. Make `fill_vec` borrow its argument instead of taking ownership of it, - and then copy the data within the function in order to return an owned - `Vec` -3. Make `fill_vec` *mutably* borrow a reference to its argument (which will need to be - mutable), modify it directly, then not return anything. Then you can get rid - of `vec1` entirely -- note that this will change what gets printed by the - first `println!`""" - -[[exercises]] -name = "move_semantics3" -path = "exercises/move_semantics/move_semantics3.rs" -mode = "compile" -hint = """ -The difference between this one and the previous ones is that the first line -of `fn fill_vec` that had `let mut vec = vec;` is no longer there. You can, -instead of adding that line back, add `mut` in one place that will change -an existing binding to be a mutable binding instead of an immutable one :)""" - -[[exercises]] -name = "move_semantics4" -path = "exercises/move_semantics/move_semantics4.rs" -mode = "compile" -hint = """ -Stop reading whenever you feel like you have enough direction :) Or try -doing one step and then fixing the compiler errors that result! -So the end goal is to: - - get rid of the first line in main that creates the new vector - - so then `vec0` doesn't exist, so we can't pass it to `fill_vec` - - we don't want to pass anything to `fill_vec`, so its signature should - reflect that it does not take any arguments - - since we're not creating a new vec in `main` anymore, we need to create - a new vec in `fill_vec`, similarly to the way we did in `main`""" - -[[exercises]] -name = "move_semantics5" -path = "exercises/move_semantics/move_semantics5.rs" -mode = "compile" -hint = """ -Carefully reason about the range in which each mutable reference is in -scope. Does it help to update the value of referent (x) immediately after -the mutable reference is taken? Read more about 'Mutable References' -in the book's section References and Borrowing': -https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html#mutable-references. -""" - -[[exercises]] -name = "move_semantics6" -path = "exercises/move_semantics/move_semantics6.rs" -mode = "compile" -hint = """ -To find the answer, you can consult the book section "References and Borrowing": -https://doc.rust-lang.org/stable/book/ch04-02-references-and-borrowing.html -The first problem is that `get_char` is taking ownership of the string. -So `data` is moved and can't be used for `string_uppercase` -`data` is moved to `get_char` first, meaning that `string_uppercase` cannot manipulate the data. -Once you've fixed that, `string_uppercase`'s function signature will also need to be adjusted. -Can you figure out how? - -Another hint: it has to do with the `&` character.""" - -# STRUCTS - -[[exercises]] -name = "structs1" -path = "exercises/structs/structs1.rs" -mode = "test" -hint = """ -Rust has more than one type of struct. Three actually, all variants are used to package related data together. -There are normal (or classic) structs. These are named collections of related data stored in fields. -Tuple structs are basically just named tuples. -Finally, Unit-like structs. These don't have any fields and are useful for generics. - -In this exercise you need to complete and implement one of each kind. -Read more about structs in The Book: https://doc.rust-lang.org/book/ch05-01-defining-structs.html""" - -[[exercises]] -name = "structs2" -path = "exercises/structs/structs2.rs" -mode = "test" -hint = """ -Creating instances of structs is easy, all you need to do is assign some values to its fields. -There are however some shortcuts that can be taken when instantiating structs. -Have a look in The Book, to find out more: https://doc.rust-lang.org/stable/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax""" - -[[exercises]] -name = "structs3" -path = "exercises/structs/structs3.rs" -mode = "test" -hint = """ -The new method needs to panic if the weight is physically impossible :), how do we do that in Rust? - -For is_international: What makes a package international? Seems related to the places it goes through right? - -For calculate_transport_fees: Bigger is more expensive usually, we don't have size, but something may fit the bill here :) - -Have a look in The Book, to find out more about method implementations: https://doc.rust-lang.org/book/ch05-03-method-syntax.html""" - -# ENUMS - -[[exercises]] -name = "enums1" -path = "exercises/enums/enums1.rs" -mode = "compile" -hint = "No hints this time ;)" - -[[exercises]] -name = "enums2" -path = "exercises/enums/enums2.rs" -mode = "compile" -hint = """ -You can create enumerations that have different variants with different types -such as no data, anonymous structs, a single string, tuples, ...etc""" - -[[exercises]] -name = "enums3" -path = "exercises/enums/enums3.rs" -mode = "test" -hint = """ -As a first step, you can define enums to compile this code without errors. -and then create a match expression in `process()`. -Note that you need to deconstruct some message variants -in the match expression to get value in the variant.""" - -# STRINGS - -[[exercises]] -name = "strings1" -path = "exercises/strings/strings1.rs" -mode = "compile" -hint = """ -The `current_favorite_color` function is currently returning a string slice with the `'static` -lifetime. We know this because the data of the string lives in our code itself -- it doesn't -come from a file or user input or another program -- so it will live as long as our program -lives. But it is still a string slice. There's one way to create a `String` by converting a -string slice covered in the Strings chapter of the book, and another way that uses the `From` -trait.""" - -[[exercises]] -name = "strings2" -path = "exercises/strings/strings2.rs" -mode = "compile" -hint = """ -Yes, it would be really easy to fix this by just changing the value bound to `word` to be a -string slice instead of a `String`, wouldn't it?? There is a way to add one character to line -9, though, that will coerce the `String` into a string slice.""" - -[[exercises]] -name = "strings3" -path = "exercises/strings/strings3.rs" -mode = "test" -hint = """ -There's tons of useful standard library functions for strings. Let's try and use some of -them! - -For the compose_me method: You can either use the `format!` macro, or convert the string -slice into an owned string, which you can then freely extend.""" - -[[exercises]] -name = "strings4" -path = "exercises/strings/strings4.rs" -mode = "compile" -hint = "No hints this time ;)" - -# MODULES - -[[exercises]] -name = "modules1" -path = "exercises/modules/modules1.rs" -mode = "compile" -hint = """ -Everything is private in Rust by default-- but there's a keyword we can use -to make something public! The compiler error should point to the thing that -needs to be public.""" - -[[exercises]] -name = "modules2" -path = "exercises/modules/modules2.rs" -mode = "compile" -hint = """ -The delicious_snacks module is trying to present an external interface that is -different than its internal structure (the `fruits` and `veggies` modules and -associated constants). Complete the `use` statements to fit the uses in main and -find the one keyword missing for both constants.""" - -[[exercises]] -name = "modules3" -path = "exercises/modules/modules3.rs" -mode = "compile" -hint = """ -UNIX_EPOCH and SystemTime are declared in the std::time module. Add a use statement -for these two to bring them into scope. You can use nested paths or the glob -operator to bring these two in using only one line.""" - -# HASHMAPS - -[[exercises]] -name = "hashmaps1" -path = "exercises/hashmaps/hashmaps1.rs" -mode = "test" -hint = """ -Hint 1: Take a look at the return type of the function to figure out - the type for the `basket`. -Hint 2: Number of fruits should be at least 5. And you have to put - at least three different types of fruits. -""" - -[[exercises]] -name = "hashmaps2" -path = "exercises/hashmaps/hashmaps2.rs" -mode = "test" -hint = """ -Use the `entry()` and `or_insert()` methods of `HashMap` to achieve this. -Learn more at https://doc.rust-lang.org/stable/book/ch08-03-hash-maps.html#only-inserting-a-value-if-the-key-has-no-value -""" - -[[exercises]] -name = "hashmaps3" -path = "exercises/hashmaps/hashmaps3.rs" -mode = "test" -hint = """ -Hint 1: Use the `entry()` and `or_insert()` methods of `HashMap` to insert entries corresponding to each team in the scores table. -Learn more at https://doc.rust-lang.org/stable/book/ch08-03-hash-maps.html#only-inserting-a-value-if-the-key-has-no-value -Hint 2: If there is already an entry for a given key, the value returned by `entry()` can be updated based on the existing value. -Learn more at https://doc.rust-lang.org/book/ch08-03-hash-maps.html#updating-a-value-based-on-the-old-value -""" - -# QUIZ 2 - -[[exercises]] -name = "quiz2" -path = "exercises/quiz2.rs" -mode = "test" -hint = "No hints this time ;)" - -# OPTIONS - -[[exercises]] -name = "options1" -path = "exercises/options/options1.rs" -mode = "test" -hint = """ -Options can have a Some value, with an inner value, or a None value, without an inner value. -There's multiple ways to get at the inner value, you can use unwrap, or pattern match. Unwrapping -is the easiest, but how do you do it safely so that it doesn't panic in your face later?""" - -[[exercises]] -name = "options2" -path = "exercises/options/options2.rs" -mode = "test" -hint = """ -check out: -https://doc.rust-lang.org/rust-by-example/flow_control/if_let.html -https://doc.rust-lang.org/rust-by-example/flow_control/while_let.html - -Remember that Options can be stacked in if let and while let. -For example: Some(Some(variable)) = variable2 -Also see Option::flatten -""" - -[[exercises]] -name = "options3" -path = "exercises/options/options3.rs" -mode = "compile" -hint = """ -The compiler says a partial move happened in the `match` -statement. How can this be avoided? The compiler shows the correction -needed. After making the correction as suggested by the compiler, do -read: https://doc.rust-lang.org/std/keyword.ref.html""" - -# ERROR HANDLING - -[[exercises]] -name = "errors1" -path = "exercises/error_handling/errors1.rs" -mode = "test" -hint = """ -`Ok` and `Err` are one of the variants of `Result`, so what the tests are saying -is that `generate_nametag_text` should return a `Result` instead of an -`Option`. - -To make this change, you'll need to: - - update the return type in the function signature to be a Result that - could be the variants `Ok(String)` and `Err(String)` - - change the body of the function to return `Ok(stuff)` where it currently - returns `Some(stuff)` - - change the body of the function to return `Err(error message)` where it - currently returns `None`""" - -[[exercises]] -name = "errors2" -path = "exercises/error_handling/errors2.rs" -mode = "test" -hint = """ -One way to handle this is using a `match` statement on -`item_quantity.parse::()` where the cases are `Ok(something)` and -`Err(something)`. This pattern is very common in Rust, though, so there's -a `?` operator that does pretty much what you would make that match statement -do for you! Take a look at this section of the Error Handling chapter: -https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator -and give it a try!""" - -[[exercises]] -name = "errors3" -path = "exercises/error_handling/errors3.rs" -mode = "compile" -hint = """ -If other functions can return a `Result`, why shouldn't `main`? It's a fairly common -convention to return something like Result<(), ErrorType> from your main function. -The unit (`()`) type is there because nothing is really needed in terms of positive -results.""" - -[[exercises]] -name = "errors4" -path = "exercises/error_handling/errors4.rs" -mode = "test" -hint = """ -`PositiveNonzeroInteger::new` is always creating a new instance and returning an `Ok` result. -It should be doing some checking, returning an `Err` result if those checks fail, and only -returning an `Ok` result if those checks determine that everything is... okay :)""" - -[[exercises]] -name = "errors5" -path = "exercises/error_handling/errors5.rs" -mode = "compile" -hint = """ -There are two different possible `Result` types produced within `main()`, which are -propagated using `?` operators. How do we declare a return type from `main()` that allows both? - -Under the hood, the `?` operator calls `From::from` on the error value to convert it to a boxed -trait object, a `Box`. This boxed trait object is polymorphic, and since all -errors implement the `error:Error` trait, we can capture lots of different errors in one "Box" -object. - -Check out this section of the book: -https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator - -Read more about boxing errors: -https://doc.rust-lang.org/stable/rust-by-example/error/multiple_error_types/boxing_errors.html - -Read more about using the `?` operator with boxed errors: -https://doc.rust-lang.org/stable/rust-by-example/error/multiple_error_types/reenter_question_mark.html -""" - -[[exercises]] -name = "errors6" -path = "exercises/error_handling/errors6.rs" -mode = "test" -hint = """ -This exercise uses a completed version of `PositiveNonzeroInteger` from -errors4. - -Below the line that TODO asks you to change, there is an example of using -the `map_err()` method on a `Result` to transform one type of error into -another. Try using something similar on the `Result` from `parse()`. You -might use the `?` operator to return early from the function, or you might -use a `match` expression, or maybe there's another way! - -You can create another function inside `impl ParsePosNonzeroError` to use -with `map_err()`. - -Read more about `map_err()` in the `std::result` documentation: -https://doc.rust-lang.org/std/result/enum.Result.html#method.map_err""" - -# Generics - -[[exercises]] -name = "generics1" -path = "exercises/generics/generics1.rs" -mode = "compile" -hint = """ -Vectors in rust make use of generics to create dynamically sized arrays of any type. -You need to tell the compiler what type we are pushing onto this vector.""" - -[[exercises]] -name = "generics2" -path = "exercises/generics/generics2.rs" -mode = "test" -hint = """ -Currently we are wrapping only values of type 'u32'. -Maybe we could update the explicit references to this data type somehow? - -If you are still stuck https://doc.rust-lang.org/stable/book/ch10-01-syntax.html#in-method-definitions -""" - -# TRAITS - -[[exercises]] -name = "traits1" -path = "exercises/traits/traits1.rs" -mode = "test" -hint = """ -A discussion about Traits in Rust can be found at: -https://doc.rust-lang.org/book/ch10-02-traits.html -""" - -[[exercises]] -name = "traits2" -path = "exercises/traits/traits2.rs" -mode = "test" -hint = """ -Notice how the trait takes ownership of 'self',and returns `Self'. -Try mutating the incoming string vector. Have a look at the tests to see -what the result should look like! - -Vectors provide suitable methods for adding an element at the end. See -the documentation at: https://doc.rust-lang.org/std/vec/struct.Vec.html""" - -[[exercises]] -name = "traits3" -path = "exercises/traits/traits3.rs" -mode = "test" -hint = """ -Traits can have a default implementation for functions. Structs that implement -the trait can then use the default version of these functions if they choose not -implement the function themselves. - -See the documentation at: https://doc.rust-lang.org/book/ch10-02-traits.html#default-implementations -""" - -[[exercises]] -name = "traits4" -path = "exercises/traits/traits4.rs" -mode = "test" -hint = """ -Instead of using concrete types as parameters you can use traits. Try replacing the -'??' with 'impl ' - -See the documentation at: https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters -""" - -[[exercises]] -name = "traits5" -path = "exercises/traits/traits5.rs" -mode = "compile" -hint = """ -To ensure a parameter implements multiple traits use the '+ syntax'. Try replacing the -'??' with 'impl <> + <>'. - -See the documentation at: https://doc.rust-lang.org/book/ch10-02-traits.html#specifying-multiple-trait-bounds-with-the--syntax -""" - -# QUIZ 3 - -[[exercises]] -name = "quiz3" -path = "exercises/quiz3.rs" -mode = "test" -hint = """ -To find the best solution to this challenge you're going to need to think back to your -knowledge of traits, specifically Trait Bound Syntax - you may also need this: `use std::fmt::Display;`.""" - -# TESTS - -[[exercises]] -name = "tests1" -path = "exercises/tests/tests1.rs" -mode = "test" -hint = """ -You don't even need to write any code to test -- you can just test values and run that, even -though you wouldn't do that in real life :) `assert!` is a macro that needs an argument. -Depending on the value of the argument, `assert!` will do nothing (in which case the test will -pass) or `assert!` will panic (in which case the test will fail). So try giving different values -to `assert!` and see which ones compile, which ones pass, and which ones fail :)""" - -[[exercises]] -name = "tests2" -path = "exercises/tests/tests2.rs" -mode = "test" -hint = """ -Like the previous exercise, you don't need to write any code to get this test to compile and -run. `assert_eq!` is a macro that takes two arguments and compares them. Try giving it two -values that are equal! Try giving it two arguments that are different! Try giving it two values -that are of different types! Try switching which argument comes first and which comes second!""" - -[[exercises]] -name = "tests3" -path = "exercises/tests/tests3.rs" -mode = "test" -hint = """ -You can call a function right where you're passing arguments to `assert!` -- so you could do -something like `assert!(having_fun())`. If you want to check that you indeed get false, you -can negate the result of what you're doing using `!`, like `assert!(!having_fun())`.""" - -# LIFETIMES - -[[exercises]] -name = "lifetimes1" -path = "exercises/lifetimes/lifetimes1.rs" -mode = "compile" -hint = """ -Let the compiler guide you. Also take a look at the book if you need help: -https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html""" - -[[exercises]] -name = "lifetimes2" -path = "exercises/lifetimes/lifetimes2.rs" -mode = "compile" -hint = """ -Remember that the generic lifetime 'a will get the concrete lifetime that is equal to the smaller of the lifetimes of x and y. -You can take at least two paths to achieve the desired result while keeping the inner block: -1. Move the string2 declaration to make it live as long as string1 (how is result declared?) -2. Move println! into the inner block""" - -[[exercises]] -name = "lifetimes3" -path = "exercises/lifetimes/lifetimes3.rs" -mode = "compile" -hint = """ -If you use a lifetime annotation in a struct's fields, where else does it need to be added?""" - -# STANDARD LIBRARY TYPES - -[[exercises]] -name = "iterators1" -path = "exercises/standard_library_types/iterators1.rs" -mode = "compile" -hint = """ -Step 1: -We need to apply something to the collection `my_fav_fruits` before we start to go through -it. What could that be? Take a look at the struct definition for a vector for inspiration: -https://doc.rust-lang.org/std/vec/struct.Vec.html. -Step 2 & step 2.1: -Very similar to the lines above and below. You've got this! -Step 3: -An iterator goes through all elements in a collection, but what if we've run out of -elements? What should we expect here? If you're stuck, take a look at -https://doc.rust-lang.org/std/iter/trait.Iterator.html for some ideas. -""" - -[[exercises]] -name = "iterators2" -path = "exercises/standard_library_types/iterators2.rs" -mode = "test" -hint = """ -Step 1 -The variable `first` is a `char`. It needs to be capitalized and added to the -remaining characters in `c` in order to return the correct `String`. -The remaining characters in `c` can be viewed as a string slice using the -`as_str` method. -The documentation for `char` contains many useful methods. -https://doc.rust-lang.org/std/primitive.char.html - -Step 2 -Create an iterator from the slice. Transform the iterated values by applying -the `capitalize_first` function. Remember to collect the iterator. - -Step 3. -This is surprising similar to the previous solution. Collect is very powerful -and very general. Rust just needs to know the desired type.""" - -[[exercises]] -name = "iterators3" -path = "exercises/standard_library_types/iterators3.rs" -mode = "test" -hint = """ -The divide function needs to return the correct error when even division is not -possible. - -The division_results variable needs to be collected into a collection type. - -The result_with_list function needs to return a single Result where the success -case is a vector of integers and the failure case is a DivisionError. - -The list_of_results function needs to return a vector of results. - -See https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.collect for how -the `FromIterator` trait is used in `collect()`. This trait is REALLY powerful! It -can make the solution to this exercise infinitely easier.""" - -[[exercises]] -name = "iterators4" -path = "exercises/standard_library_types/iterators4.rs" -mode = "test" -hint = """ -In an imperative language, you might write a for loop that updates -a mutable variable. Or, you might write code utilizing recursion -and a match clause. In Rust you can take another functional -approach, computing the factorial elegantly with ranges and iterators. - -Hint 2: Check out the `fold` and `rfold` methods!""" - -[[exercises]] -name = "iterators5" -path = "exercises/standard_library_types/iterators5.rs" -mode = "test" -hint = """ -The documentation for the std::iter::Iterator trait contains numerous methods -that would be helpful here. - -Return 0 from count_collection_iterator to make the code compile in order to -test count_iterator. - -The collection variable in count_collection_iterator is a slice of HashMaps. It -needs to be converted into an iterator in order to use the iterator methods. - -The fold method can be useful in the count_collection_iterator function. - -For a further challenge, consult the documentation for Iterator to find -a different method that could make your code more compact than using fold.""" - -[[exercises]] -name = "box1" -path = "exercises/standard_library_types/box1.rs" -mode = "test" -hint = """ -Step 1 -The compiler's message should help: since we cannot store the value of the actual type -when working with recursive types, we need to store a reference (pointer) to its value. -We should, therefore, place our `List` inside a `Box`. More details in the book here: -https://doc.rust-lang.org/book/ch15-01-box.html#enabling-recursive-types-with-boxes - -Step 2 -Creating an empty list should be fairly straightforward (hint: peek at the assertions). -For a non-empty list keep in mind that we want to use our Cons "list builder". -Although the current list is one of integers (i32), feel free to change the definition -and try other types! -""" - -[[exercises]] -name = "arc1" -path = "exercises/standard_library_types/arc1.rs" -mode = "compile" -hint = """ -Make `shared_numbers` be an `Arc` from the numbers vector. Then, in order -to avoid creating a copy of `numbers`, you'll need to create `child_numbers` -inside the loop but still in the main thread. - -`child_numbers` should be a clone of the Arc of the numbers instead of a -thread-local copy of the numbers. - -This is a simple exercise if you understand the underlying concepts, but if this -is too much of a struggle, consider reading through all of Chapter 16 in the book: -https://doc.rust-lang.org/stable/book/ch16-00-concurrency.html -""" - -[[exercises]] -name = "rc1" -path = "exercises/standard_library_types/rc1.rs" -mode = "compile" -hint = """ -This is a straightforward exercise to use the Rc type. Each Planet has -ownership of the Sun, and uses Rc::clone() to increment the reference count of the Sun. -After using drop() to move the Planets out of scope individually, the reference count goes down. -In the end the sun only has one reference again, to itself. See more at: -https://doc.rust-lang.org/book/ch15-04-rc.html - -* Unforunately Pluto is no longer considered a planet :( -""" - -[[exercises]] -name = "cow1" -path = "exercises/standard_library_types/cow1.rs" -mode = "compile" -hint = """ -Since the vector is already owned, the `Cow` type doesn't need to clone it. - -Checkout https://doc.rust-lang.org/std/borrow/enum.Cow.html for documentation -on the `Cow` type. -""" - -# THREADS - -[[exercises]] -name = "threads1" -path = "exercises/threads/threads1.rs" -mode = "compile" -hint = """ -`JoinHandle` is a struct that is returned from a spawned thread: -https://doc.rust-lang.org/std/thread/fn.spawn.html - -A challenge with multi-threaded applications is that the main thread can -finish before the spawned threads are completed. -https://doc.rust-lang.org/book/ch16-01-threads.html#waiting-for-all-threads-to-finish-using-join-handle - -Collect the JoinHandles and wait for them to finish. -https://doc.rust-lang.org/std/thread/struct.JoinHandle.html -""" - -[[exercises]] -name = "threads2" -path = "exercises/threads/threads2.rs" -mode = "compile" -hint = """ -`Arc` is an Atomic Reference Counted pointer that allows safe, shared access -to **immutable** data. But we want to *change* the number of `jobs_completed` -so we'll need to also use another type that will only allow one thread to -mutate the data at a time. Take a look at this section of the book: -https://doc.rust-lang.org/book/ch16-03-shared-state.html#atomic-reference-counting-with-arct -and keep reading if you'd like more hints :) - - -Do you now have an `Arc` `Mutex` `JobStatus` at the beginning of main? Like: -`let status = Arc::new(Mutex::new(JobStatus { jobs_completed: 0 }));` -Similar to the code in the example in the book that happens after the text -that says "We can use Arc to fix this.". If not, give that a try! If you -do and would like more hints, keep reading!! - - -Make sure neither of your threads are holding onto the lock of the mutex -while they are sleeping, since this will prevent the other thread from -being allowed to get the lock. Locks are automatically released when -they go out of scope. - -If you've learned from the sample solutions, I encourage you to come -back to this exercise and try it again in a few days to reinforce -what you've learned :)""" - -[[exercises]] -name = "threads3" -path = "exercises/threads/threads3.rs" -mode = "compile" -hint = """ -An alternate way to handle concurrency between threads is to use -a mpsc (multiple producer, single consumer) channel to communicate. -With both a sending end and a receiving end, it's possible to -send values in one thread and receive them in another. -Multiple producers are possible by using clone() to create a duplicate -of the original sending end. -See https://doc.rust-lang.org/book/ch16-02-message-passing.html for more info. -""" - -# MACROS - -[[exercises]] -name = "macros1" -path = "exercises/macros/macros1.rs" -mode = "compile" -hint = """ -When you call a macro, you need to add something special compared to a -regular function call. If you're stuck, take a look at what's inside -`my_macro`.""" - -[[exercises]] -name = "macros2" -path = "exercises/macros/macros2.rs" -mode = "compile" -hint = """ -Macros don't quite play by the same rules as the rest of Rust, in terms of -what's available where. - -Unlike other things in Rust, the order of "where you define a macro" versus -"where you use it" actually matters.""" - -[[exercises]] -name = "macros3" -path = "exercises/macros/macros3.rs" -mode = "compile" -hint = """ -In order to use a macro outside of its module, you need to do something -special to the module to lift the macro out into its parent. - -The same trick also works on "extern crate" statements for crates that have -exported macros, if you've seen any of those around.""" - -[[exercises]] -name = "macros4" -path = "exercises/macros/macros4.rs" -mode = "compile" -hint = """ -You only need to add a single character to make this compile. -The way macros are written, it wants to see something between each -"macro arm", so it can separate them. - -That's all the macro exercises we have in here, but it's barely even -scratching the surface of what you can do with Rust's macros. For a more -thorough introduction, you can have a read through the little book of Rust -macros: https://veykril.github.io/tlborm/""" - -# CLIPPY - -[[exercises]] -name = "clippy1" -path = "exercises/clippy/clippy1.rs" -mode = "clippy" -hint = """ -Rust stores the highest precision version of any long or inifinite precision -mathematical constants in the rust standard library. -https://doc.rust-lang.org/stable/std/f32/consts/index.html - -We may be tempted to use our own approximations for certain mathematical constants, -but clippy recognizes those imprecise mathematical constants as a source of -potential error. -See the suggestions of the clippy warning in compile output and use the -appropriate replacement constant from std::f32::consts...""" - -[[exercises]] -name = "clippy2" -path = "exercises/clippy/clippy2.rs" -mode = "clippy" -hint = """ -`for` loops over Option values are more clearly expressed as an `if let`""" - -[[exercises]] -name = "clippy3" -path = "exercises/clippy/clippy3.rs" -mode = "clippy" -hint = "No hints this time!" - -# TYPE CONVERSIONS - -[[exercises]] -name = "using_as" -path = "exercises/conversions/using_as.rs" -mode = "test" -hint = """ -Use the `as` operator to cast one of the operands in the last line of the -`average` function into the expected return type.""" - -[[exercises]] -name = "from_into" -path = "exercises/conversions/from_into.rs" -mode = "test" -hint = """ -Follow the steps provided right before the `From` implementation""" - -[[exercises]] -name = "from_str" -path = "exercises/conversions/from_str.rs" -mode = "test" -hint = """ -The implementation of FromStr should return an Ok with a Person object, -or an Err with an error if the string is not valid. - -This is almost like the `from_into` exercise, but returning errors instead -of falling back to a default value. - -Look at the test cases to see which error variants to return. - -Another hint: You can use the `map_err` method of `Result` with a function -or a closure to wrap the error from `parse::`. - -Yet another hint: If you would like to propagate errors by using the `?` -operator in your solution, you might want to look at -https://doc.rust-lang.org/stable/rust-by-example/error/multiple_error_types/reenter_question_mark.html -""" - -[[exercises]] -name = "try_from_into" -path = "exercises/conversions/try_from_into.rs" -mode = "test" -hint = """ -Follow the steps provided right before the `TryFrom` implementation. -You can also use the example at https://doc.rust-lang.org/std/convert/trait.TryFrom.html - -Is there an implementation of `TryFrom` in the standard library that -can both do the required integer conversion and check the range of the input? - -Another hint: Look at the test cases to see which error variants to return. - -Yet another hint: You can use the `map_err` or `or` methods of `Result` to -convert errors. - -Yet another hint: If you would like to propagate errors by using the `?` -operator in your solution, you might want to look at -https://doc.rust-lang.org/stable/rust-by-example/error/multiple_error_types/reenter_question_mark.html - -Challenge: Can you make the `TryFrom` implementations generic over many integer types?""" - -[[exercises]] -name = "as_ref_mut" -path = "exercises/conversions/as_ref_mut.rs" -mode = "test" -hint = """ -Add AsRef as a trait bound to the functions.""" diff --git a/install.ps1 b/install.ps1 deleted file mode 100644 index 97980c5bee..0000000000 --- a/install.ps1 +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env pwsh - -#Requires -Version 5 -param($path = "$pwd/rustlings") - -Write-Host "Let's get you set up with Rustlings!" - -Write-Host "Checking requirements..." -if (Get-Command git -ErrorAction SilentlyContinue) { - Write-Host "SUCCESS: Git is installed" -} else { - Write-Host "WARNING: Git does not seem to be installed." - Write-Host "Please download Git using your package manager or over https://git-scm.com/!" - exit 1 -} - -if (Get-Command rustc -ErrorAction SilentlyContinue) { - Write-Host "SUCCESS: Rust is installed" -} else { - Write-Host "WARNING: Rust does not seem to be installed." - Write-Host "Please download Rust using https://rustup.rs!" - exit 1 -} - -if (Get-Command cargo -ErrorAction SilentlyContinue) { - Write-Host "SUCCESS: Cargo is installed" -} else { - Write-Host "WARNING: Cargo does not seem to be installed." - Write-Host "Please download Rust and Cargo using https://rustup.rs!" - exit 1 -} - -# Function that compares two versions strings v1 and v2 given in arguments (e.g 1.31 and 1.33.0). -# Returns 1 if v1 > v2, 0 if v1 == v2, 2 if v1 < v2. -function vercomp($v1, $v2) { - if ($v1 -eq $v2) { - return 0 - } - - $v1 = $v1.Replace(".", "0") - $v2 = $v2.Replace(".", "0") - if ($v1.Length -gt $v2.Length) { - $v2 = $v2.PadRight($v1.Length, "0") - } else { - $v1 = $v1.PadRight($v2.Length, "0") - } - - if ($v1 -gt $v2) { - return 1 - } else { - return 2 - } -} - -$rustVersion = $(rustc --version).Split(" ")[1] -$minRustVersion = "1.56" -if ((vercomp $rustVersion $minRustVersion) -eq 2) { - Write-Host "WARNING: Rust version is too old: $rustVersion - needs at least $minRustVersion" - Write-Host "Please update Rust with 'rustup update'" - exit 1 -} else { - Write-Host "SUCCESS: Rust is up to date" -} - -Write-Host "Cloning Rustlings at $path" -git clone -q https://github.com/rust-lang/rustlings $path -if (!($LASTEXITCODE -eq 0)) { - exit 1 -} - -# UseBasicParsing is deprecated, pwsh 6 or above will automatically use it, -# but anyone running pwsh 5 will have to pass the argument. -$version = Invoke-WebRequest -UseBasicParsing https://api.github.com/repos/rust-lang/rustlings/releases/latest ` - | ConvertFrom-Json | Select-Object -ExpandProperty tag_name - -Write-Host "Checking out version $version..." -Set-Location $path -git checkout -q tags/$version - -Write-Host "Installing the 'rustlings' executable..." -cargo install --force --path . -if (!(Get-Command rustlings -ErrorAction SilentlyContinue)) { - Write-Host "WARNING: Please check that you have '~/.cargo/bin' in your PATH environment variable!" -} - -# Checking whether Clippy is installed. -# Due to a bug in Cargo, this must be done with Rustup: https://github.com/rust-lang/rustup/issues/1514 -$clippy = (rustup component list | Select-String "clippy" | Select-String "installed") | Out-String -if (!$clippy) { - Write-Host "Installing the 'cargo-clippy' executable..." - rustup component add clippy -} - -Write-Host "All done! Run 'rustlings' to get started." diff --git a/install.sh b/install.sh deleted file mode 100755 index f3b3f33df7..0000000000 --- a/install.sh +++ /dev/null @@ -1,184 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -echo "Let's get you set up with Rustlings!" - -echo "Checking requirements..." -if [ -x "$(command -v git)" ] -then - echo "SUCCESS: Git is installed" -else - echo "ERROR: Git does not seem to be installed." - echo "Please download Git using your package manager or over https://git-scm.com/!" - exit 1 -fi - -if [ -x "$(command -v cc)" ] -then - echo "SUCCESS: cc is installed" -else - echo "ERROR: cc does not seem to be installed." - echo "Please download (g)cc using your package manager." - echo "OSX: xcode-select --install" - echo "Deb: sudo apt install gcc" - echo "Yum: sudo yum -y install gcc" - exit 1 -fi - -if [ -x "$(command -v rustup)" ] -then - echo "SUCCESS: rustup is installed" -else - echo "ERROR: rustup does not seem to be installed." - echo "Please download rustup using https://rustup.rs!" - exit 1 -fi - -if [ -x "$(command -v rustc)" ] -then - echo "SUCCESS: Rust is installed" -else - echo "ERROR: Rust does not seem to be installed." - echo "Please download Rust using rustup!" - exit 1 -fi - -if [ -x "$(command -v cargo)" ] -then - echo "SUCCESS: Cargo is installed" -else - echo "ERROR: Cargo does not seem to be installed." - echo "Please download Rust and Cargo using rustup!" - exit 1 -fi - -# Look up python installations, starting with 3 with a fallback of 2 -if [ -x "$(command -v python3)" ] -then - PY="$(command -v python3)" -elif [ -x "$(command -v python)" ] -then - PY="$(command -v python)" -elif [ -x "$(command -v python2)" ] -then - PY="$(command -v python2)" -else - echo "ERROR: No working python installation was found" - echo "Please install python and add it to the PATH variable" - exit 1 -fi - -# Function that compares two versions strings v1 and v2 given in arguments (e.g 1.31 and 1.33.0). -# Returns 1 if v1 > v2, 0 if v1 == v2, 2 if v1 < v2. -function vercomp() { - if [[ $1 == $2 ]] - then - return 0 - fi - v1=( ${1//./ } ) - v2=( ${2//./ } ) - len1=${#v1[@]} - len2=${#v2[@]} - max_len=$len1 - if [[ $max_len -lt $len2 ]] - then - max_len=$len2 - fi - - #pad right in short arr - if [[ len1 -gt len2 ]]; - then - for ((i = len2; i < len1; i++)); - do - v2[$i]=0 - done - else - for ((i = len1; i < len2; i++)); - do - v1[$i]=0 - done - fi - - for i in `seq 0 $max_len` - do - # Fill empty fields with zeros in v1 - if [ -z "${v1[$i]}" ] - then - v1[$i]=0 - fi - # And in v2 - if [ -z "${v2[$i]}" ] - then - v2[$i]=0 - fi - if [ ${v1[$i]} -gt ${v2[$i]} ] - then - return 1 - fi - if [ ${v1[$i]} -lt ${v2[$i]} ] - then - return 2 - fi - done - return 0 -} - -RustVersion=$(rustc --version | cut -d " " -f 2) -MinRustVersion=1.56 -vercomp "$RustVersion" $MinRustVersion || ec=$? -if [ ${ec:-0} -eq 2 ] -then - echo "ERROR: Rust version is too old: $RustVersion - needs at least $MinRustVersion" - echo "Please update Rust with 'rustup update'" - exit 1 -else - echo "SUCCESS: Rust is up to date" -fi - -Path=${1:-rustlings/} -echo "Cloning Rustlings at $Path..." -git clone -q https://github.com/rust-lang/rustlings "$Path" - -cd "$Path" - -Version=$(curl -s https://api.github.com/repos/rust-lang/rustlings/releases/latest | ${PY} -c "import json,sys;obj=json.load(sys.stdin);print(obj['tag_name']);") -CargoBin="${CARGO_HOME:-$HOME/.cargo}/bin" - -if [[ -z ${Version} ]] -then - echo "The latest tag version could not be fetched remotely." - echo "Using the local git repository..." - Version=$(ls -tr .git/refs/tags/ | tail -1) - if [[ -z ${Version} ]] - then - echo "No valid tag version found" - echo "Rustlings will be installed using the main branch" - Version="main" - else - Version="tags/${Version}" - fi -else - Version="tags/${Version}" -fi - -echo "Checking out version $Version..." -git checkout -q ${Version} - -echo "Installing the 'rustlings' executable..." -cargo install --force --path . - -if ! [ -x "$(command -v rustlings)" ] -then - echo "WARNING: Please check that you have '$CargoBin' in your PATH environment variable!" -fi - -# Checking whether Clippy is installed. -# Due to a bug in Cargo, this must be done with Rustup: https://github.com/rust-lang/rustup/issues/1514 -Clippy=$(rustup component list | grep "clippy" | grep "installed") -if [ -z "$Clippy" ] -then - echo "Installing the 'cargo-clippy' executable..." - rustup component add clippy -fi - -echo "All done! Run 'rustlings' to get started." diff --git a/release-hook.sh b/release-hook.sh new file mode 100755 index 0000000000..4934933793 --- /dev/null +++ b/release-hook.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +# Error out if any command fails +set -e + +typos +cargo upgrades + +# Similar to CI +cargo clippy -- --deny warnings +cargo fmt --all --check +cargo test --workspace +cargo dev check --require-solutions + +# MSRV +cargo +1.88 dev check --require-solutions diff --git a/rustlings-macros/Cargo.toml b/rustlings-macros/Cargo.toml new file mode 100644 index 0000000000..5df648b2d0 --- /dev/null +++ b/rustlings-macros/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "rustlings-macros" +description = "A macros crate intended to be used only by Rustlings" +version.workspace = true +authors.workspace = true +repository.workspace = true +license.workspace = true +edition.workspace = true +rust-version.workspace = true +include = [ + "/src/", + "/info.toml", +] + +[lib] +proc-macro = true + +[dependencies] +quote = "1.0" +serde.workspace = true +toml.workspace = true + +[lints] +workspace = true diff --git a/rustlings-macros/info.toml b/rustlings-macros/info.toml new file mode 100644 index 0000000000..e42b0f2629 --- /dev/null +++ b/rustlings-macros/info.toml @@ -0,0 +1,1202 @@ +format_version = 1 + +welcome_message = """ +Is this your first time? Don't worry, Rustlings is made for beginners! +We are going to teach you a lot of things about Rust, but before we can +get started, here are some notes about how Rustlings operates: + +1. The central concept behind Rustlings is that you solve exercises. These + exercises usually contain some compiler or logic errors which cause the + exercise to fail compilation or testing. It's your job to find all errors + and fix them! +2. Make sure to have your editor open in the `rustlings/` directory. Rustlings + will show you the path of the current exercise under the progress bar. Open + the exercise file in your editor, fix errors and save the file. Rustlings + will automatically detect the file change and rerun the exercise. If all + errors are fixed, Rustlings will ask you to move on to the next exercise. +3. If you're stuck on an exercise, enter `h` to show a hint. +4. If an exercise doesn't make sense to you, feel free to open an issue on + GitHub! (https://github.com/rust-lang/rustlings). We look at every issue, and + sometimes, other learners do too so you can help each other out!""" + +final_message = """ +We hope you enjoyed learning about the various aspects of Rust! +If you noticed any issues, don't hesitate to report them on GitHub. +You can also contribute your own exercises to help the greater community! + +Before reporting an issue or contributing, please read our guidelines: +https://github.com/rust-lang/rustlings/blob/main/CONTRIBUTING.md""" + +# INTRO + +[[exercises]] +name = "intro1" +dir = "00_intro" +test = false +skip_check_unsolved = true +hint = """ +Enter `n` to move on to the next exercise. +You might need to press ENTER after typing `n`.""" + +[[exercises]] +name = "intro2" +dir = "00_intro" +test = false +hint = """ +The compiler is informing us that we've got the name of the print macro wrong. +It also suggests an alternative.""" + +# VARIABLES + +[[exercises]] +name = "variables1" +dir = "01_variables" +test = false +hint = """ +The declaration in the `main` function is missing a keyword that is needed +in Rust to create a new variable binding.""" + +[[exercises]] +name = "variables2" +dir = "01_variables" +test = false +hint = """ +The compiler message is saying that Rust can't infer the type that the +variable binding `x` has with what is given here. + +What happens if you annotate the first line in the `main` function with a type +annotation? + +What if you give `x` a value? + +What if you do both? + +What type should `x` be, anyway? + +What if `x` is the same type as `10`? What if it's a different type?""" + +[[exercises]] +name = "variables3" +dir = "01_variables" +test = false +hint = """ +In this exercise, we have a variable binding that we've created in the `main` +function, and we're trying to use it in the next line, but we haven't given it +a value. + +We can't print out something that isn't there; try giving `x` a value! + +This is an error that can cause bugs that's very easy to make in any +programming language -- thankfully the Rust compiler has caught this for us!""" + +[[exercises]] +name = "variables4" +dir = "01_variables" +test = false +hint = """ +In Rust, variable bindings are immutable by default. But here, we're trying +to reassign a different value to `x`! There's a keyword we can use to make +a variable binding mutable instead.""" + +[[exercises]] +name = "variables5" +dir = "01_variables" +test = false +hint = """ +In `variables4` we already learned how to make an immutable variable mutable +using a special keyword. Unfortunately this doesn't help us much in this +exercise because we want to assign a different typed value to an existing +variable. Sometimes you may also like to reuse existing variable names because +you are just converting values to different types like in this exercise. + +Fortunately Rust has a powerful solution to this problem: 'Shadowing'! +You can read more about 'Shadowing' in the book's section 'Variables and +Mutability': +https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html#shadowing + +Try to solve this exercise afterwards using this technique.""" + +[[exercises]] +name = "variables6" +dir = "01_variables" +test = false +hint = """ +We know about variables and mutability, but there is another important type of +variable available: constants. + +Constants are always immutable. They are declared with the keyword `const` +instead of `let`. + +The type of Constants must always be annotated. + +Read more about constants and the differences between variables and constants +under 'Constants' in the book's section 'Variables and Mutability': +https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html#constants""" + +# FUNCTIONS + +[[exercises]] +name = "functions1" +dir = "02_functions" +test = false +hint = """ +This `main` function is calling a function that it expects to exist, but the +function doesn't exist. It expects this function to have the name `call_me`. +It also expects this function to not take any arguments and not return a value. +Sounds a lot like `main`, doesn't it?""" + +[[exercises]] +name = "functions2" +dir = "02_functions" +test = false +hint = """ +Rust requires that all parts of a function's signature have type annotations, +but `call_me` is missing the type annotation of `num`.""" + +[[exercises]] +name = "functions3" +dir = "02_functions" +test = false +hint = """ +This time, the function *declaration* is okay, but there's something wrong +with the place where we are calling the function.""" + +[[exercises]] +name = "functions4" +dir = "02_functions" +test = false +hint = """ +The error message points to the function `sale_price` and says it expects a type +after `->`. This is where the function's return type should be. +Take a look at the `is_even` function for an example!""" + +[[exercises]] +name = "functions5" +dir = "02_functions" +test = false +hint = """ +This is a really common error that can be fixed by removing one character. +It happens because Rust distinguishes between expressions and statements: +Expressions return a value based on their operand(s), and statements simply +return a `()` type which behaves just like `void` in C/C++. + +We want to return a value with the type `i32` from the `square` function, but +it is returning the type `()`. + +There are two solutions: +1. Add the `return` keyword before `num * num;` +2. Remove the semicolon `;` after `num * num`""" + +# IF + +[[exercises]] +name = "if1" +dir = "03_if" +hint = """ +It's possible to do this in one line if you would like! + +Some similar examples from other languages: +- In C(++) this would be: `a > b ? a : b` +- In Python this would be: `a if a > b else b` + +Remember in Rust that: +- The `if` condition does not need to be surrounded by parentheses +- `if`/`else` conditionals are expressions +- Each condition is followed by a `{}` block""" + +[[exercises]] +name = "if2" +dir = "03_if" +hint = """ +For that first compiler error, it's important in Rust that each conditional +block returns the same type! + +To get the tests passing, you will need a couple conditions checking different +input values. Read the tests to find out what they expect.""" + +[[exercises]] +name = "if3" +dir = "03_if" +hint = """ +In Rust, every arm of an `if` expression has to return the same type of value. +Make sure the type is consistent across all arms.""" + +# QUIZ 1 + +[[exercises]] +name = "quiz1" +dir = "quizzes" +hint = "No hints this time ;)" + +# PRIMITIVE TYPES + +[[exercises]] +name = "primitive_types1" +dir = "04_primitive_types" +test = false +hint = """ +In Rust, a boolean can be negated using the operator `!` before it. +Example: `!true == false` +This also works with boolean variables.""" + +[[exercises]] +name = "primitive_types2" +dir = "04_primitive_types" +test = false +hint = "No hints this time ;)" + +[[exercises]] +name = "primitive_types3" +dir = "04_primitive_types" +test = false +hint = """ +There's a shorthand to initialize arrays with a certain size that doesn't +require you to type in 100 items (but you certainly can if you want!). + +For example, you can do: +``` +let array = ["Are we there yet?"; 100]; +``` + +Bonus: what are some other things you could have that would return `true` +for `a.len() >= 100`?""" + +[[exercises]] +name = "primitive_types4" +dir = "04_primitive_types" +hint = """ +Take a look at the 'Understanding Ownership -> Slices -> Other Slices' section +of the book: https://doc.rust-lang.org/book/ch04-03-slices.html and use the +starting and ending (plus one) indices of the items in the array that you want +to end up in the slice. + +If you're curious why the first argument of `assert_eq!` does not have an +ampersand for a reference since the second argument is a reference, take a look +at the coercion chapter of the nomicon: +https://doc.rust-lang.org/nomicon/coercions.html""" + +[[exercises]] +name = "primitive_types5" +dir = "04_primitive_types" +test = false +hint = """ +Take a look at the 'Data Types -> The Tuple Type' section of the book: +https://doc.rust-lang.org/book/ch03-02-data-types.html#the-tuple-type +Particularly the part about destructuring (second to last example in the +section). + +You'll need to make a pattern to bind `name` and `age` to the appropriate parts +of the tuple.""" + +[[exercises]] +name = "primitive_types6" +dir = "04_primitive_types" +hint = """ +While you could use a destructuring `let` for the tuple here, try +indexing into it instead, as explained in the last example of the +'Data Types -> The Tuple Type' section of the book: +https://doc.rust-lang.org/book/ch03-02-data-types.html#the-tuple-type +Now, you have another tool in your toolbox!""" + +# VECS + +[[exercises]] +name = "vecs1" +dir = "05_vecs" +hint = """ +In Rust, there are two ways to define a Vector. +1. One way is to use the `Vec::new()` function to create a new vector + and fill it with the `push()` method. +2. The second way is to use the `vec![]` macro and define your elements + inside the square brackets. This way is simpler when you exactly know + the initial values. + +Check this chapter: https://doc.rust-lang.org/book/ch08-01-vectors.html +of the Rust book to learn more.""" + +[[exercises]] +name = "vecs2" +dir = "05_vecs" +hint = """ +Use the `.push()` method on the vector to push new elements to it.""" + +# MOVE SEMANTICS + +[[exercises]] +name = "move_semantics1" +dir = "06_move_semantics" +hint = """ +So you've got the "cannot borrow `vec` as mutable, as it is not declared as +mutable" error on the line where we push an element to the vector, right? + +The fix for this is going to be adding one keyword, and the addition is NOT on +the line where we push to the vector (where the error is). + +Try accessing `vec0` after having called `fill_vec()`. See what happens!""" + +[[exercises]] +name = "move_semantics2" +dir = "06_move_semantics" +hint = """ +When running this exercise for the first time, you'll notice an error about +"borrow of moved value". In Rust, when an argument is passed to a function and +it's not explicitly returned, you can't use the original variable anymore. +We call this "moving" a variable. When we pass `vec0` into `fill_vec`, it's +being "moved" into `vec1`, meaning we can't access `vec0` anymore. + +You could make another, separate version of the data that's in `vec0` and +pass it to `fill_vec` instead. This is called cloning in Rust.""" + +[[exercises]] +name = "move_semantics3" +dir = "06_move_semantics" +hint = """ +The difference between this one and the previous ones is that the first line +of `fn fill_vec` that had `let mut vec = vec;` is no longer there. You can, +instead of adding that line back, add `mut` in one place that will change +an existing binding to be a mutable binding instead of an immutable one :)""" + +[[exercises]] +name = "move_semantics4" +dir = "06_move_semantics" +hint = """ +Carefully reason about the range in which each mutable reference is in +scope. Does it help to update the value of `x` immediately after +the mutable reference is taken? +Read more about 'Mutable References' in the book's section 'References and +Borrowing': +https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html#mutable-references.""" + +[[exercises]] +name = "move_semantics5" +dir = "06_move_semantics" +test = false +hint = """ +To find the answer, you can consult the book section "References and Borrowing": +https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html + +The first problem is that `get_char` is taking ownership of the string. So +`data` is moved and can't be used for `string_uppercase`. `data` is moved to +`get_char` first, meaning that `string_uppercase` can't manipulate the data. + +Once you've fixed that, `string_uppercase`'s function signature will also need +to be adjusted.""" + +# STRUCTS + +[[exercises]] +name = "structs1" +dir = "07_structs" +hint = """ +Rust has more than one type of struct. Three actually, all variants are used to +package related data together. + +There are regular structs. These are named collections of related data stored in +fields. + +Tuple structs are basically just named tuples. + +Finally, unit structs. These don't have any fields and are useful for generics. + +In this exercise, you need to complete and implement one of each kind. +Read more about structs in The Book: +https://doc.rust-lang.org/book/ch05-01-defining-structs.html""" + +[[exercises]] +name = "structs2" +dir = "07_structs" +hint = """ +Creating instances of structs is easy, all you need to do is assign some values +to its fields. + +There are however some shortcuts that can be taken when instantiating structs. +Have a look in The Book to find out more: +https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax""" + +[[exercises]] +name = "structs3" +dir = "07_structs" +hint = """ +For `is_international`: What makes a package international? Seems related to +the places it goes through right? + +For `get_fees`: This method takes an additional argument, is there a field in +the `Package` struct that this relates to? + +Have a look in The Book to find out more about method implementations: +https://doc.rust-lang.org/book/ch05-03-method-syntax.html""" + +# ENUMS + +[[exercises]] +name = "enums1" +dir = "08_enums" +test = false +hint = "No hints this time ;)" + +[[exercises]] +name = "enums2" +dir = "08_enums" +test = false +hint = """ +You can create enumerations that have different variants with different types +such as anonymous structs, structs, a single string, tuples, no data, etc.""" + +[[exercises]] +name = "enums3" +dir = "08_enums" +hint = """ +As a first step, define enums to compile the code without errors. + +Then, create a match expression in `process()`. + +Note that you need to deconstruct some message variants in the match expression +to get the variant's values.""" + +# STRINGS + +[[exercises]] +name = "strings1" +dir = "09_strings" +test = false +hint = """ +The `current_favorite_color` function is currently returning a string slice +with the `'static` lifetime. We know this because the data of the string lives +in our code itself -- it doesn't come from a file or user input or another +program -- so it will live as long as our program lives. + +But it is still a string slice. There's one way to create a `String` by +converting a string slice covered in the Strings chapter of the book, and +another way that uses the `From` trait.""" + +[[exercises]] +name = "strings2" +dir = "09_strings" +test = false +hint = """ +Yes, it would be really easy to fix this by just changing the value bound to +`word` to be a string slice instead of a `String`, wouldn't it? There is a way +to add one character to the `if` statement, though, that will coerce the +`String` into a string slice. + +Side note: If you're interested in learning about how this kind of reference +conversion works, you can jump ahead in the book and read this part in the +smart pointers chapter: +https://doc.rust-lang.org/book/ch15-02-deref.html#implicit-deref-coercions-with-functions-and-methods""" + +[[exercises]] +name = "strings3" +dir = "09_strings" +hint = """ +There are many useful standard library functions for strings. Let's try and use +some of them: +https://doc.rust-lang.org/std/string/struct.String.html#method.trim + +For the `compose_me` method: You can either use the `format!` macro, or convert +the string slice into an owned string, which you can then freely extend. + +For the `replace_me` method, you can check out the `replace` method: +https://doc.rust-lang.org/std/string/struct.String.html#method.replace""" + +[[exercises]] +name = "strings4" +dir = "09_strings" +test = false +hint = """ +Replace `placeholder` with either `string` or `string_slice` in the `main` +function. + +Example: +`placeholder("blue");` +should become +`string_slice("blue");` +because "blue" is `&str`, not `String`.""" + +# MODULES + +[[exercises]] +name = "modules1" +dir = "10_modules" +test = false +hint = """ +Everything is private in Rust by default. But there's a keyword we can use +to make something public!""" + +[[exercises]] +name = "modules2" +dir = "10_modules" +test = false +hint = """ +The `delicious_snacks` module is trying to present an external interface that +is different than its internal structure (the `fruits` and `veggies` modules +and associated constants). Complete the `use` statements to fit the uses in +`main` and find the one keyword missing for both constants. + +Learn more in The Book: +https://doc.rust-lang.org/book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.html#re-exporting-names-with-pub-use""" + +[[exercises]] +name = "modules3" +dir = "10_modules" +test = false +hint = """ +`UNIX_EPOCH` and `SystemTime` are declared in the `std::time` module. Add a +`use` statement for these two to bring them into scope. You can use nested +paths to bring these two in using only one line.""" + +# HASHMAPS + +[[exercises]] +name = "hashmaps1" +dir = "11_hashmaps" +hint = """ +The number of fruits should be at least 5 and you have to put at least 3 +different types of fruits.""" + +[[exercises]] +name = "hashmaps2" +dir = "11_hashmaps" +hint = """ +Use the `entry()` and `or_insert()` methods of `HashMap` to achieve this. + +Learn more in The Book: +https://doc.rust-lang.org/book/ch08-03-hash-maps.html#only-inserting-a-value-if-the-key-has-no-value""" + +[[exercises]] +name = "hashmaps3" +dir = "11_hashmaps" +hint = """ +Hint 1: Use the `entry()` and `or_default()` methods of `HashMap` to insert the + default value of `TeamScores` if a team doesn't exist in the table yet. + +Hint 2: If there is already an entry for a given key, the value returned by + `entry()` can be updated based on the existing value. + +Learn more in The Book: +https://doc.rust-lang.org/book/ch08-03-hash-maps.html#updating-a-value-based-on-the-old-value""" + +# QUIZ 2 + +[[exercises]] +name = "quiz2" +dir = "quizzes" +hint = "The `+` operator can concatenate a `String` with a `&str`." + +# OPTIONS + +[[exercises]] +name = "options1" +dir = "12_options" +hint = """ +Options can have a `Some` value, with an inner value, or a `None` value, +without an inner value. + +There are multiple ways to get at the inner value, you can use `unwrap`, or +pattern match. Unwrapping is the easiest, but how do you do it safely so that +it doesn't panic in your face later?""" + +[[exercises]] +name = "options2" +dir = "12_options" +hint = """ +Check out: + +- https://doc.rust-lang.org/rust-by-example/flow_control/if_let.html +- https://doc.rust-lang.org/rust-by-example/flow_control/while_let.html + +Remember that `Option`s can be nested in if-let and while-let statements. + +For example: `if let Some(Some(x)) = y` + +Also see `Option::flatten`""" + +[[exercises]] +name = "options3" +dir = "12_options" +test = false +hint = """ +The compiler says a partial move happened in the `match` statement. How can +this be avoided? The compiler shows the correction needed. + +After making the correction as suggested by the compiler, read the related docs +page: +https://doc.rust-lang.org/std/keyword.ref.html""" + +# ERROR HANDLING + +[[exercises]] +name = "errors1" +dir = "13_error_handling" +hint = """ +`Ok` and `Err` are the two variants of `Result`, so what the tests are saying +is that `generate_nametag_text` should return a `Result` instead of an `Option`. + +To make this change, you'll need to: + - update the return type in the function signature to be a `Result` that could be the variants `Ok(String)` and `Err(String)` + - change the body of the function to return `Ok(…)` where it currently + returns `Some(…)` + - change the body of the function to return `Err(error message)` where it + currently returns `None`""" + +[[exercises]] +name = "errors2" +dir = "13_error_handling" +hint = """ +One way to handle this is using a `match` statement on +`item_quantity.parse::()` where the cases are `Ok(something)` and +`Err(something)`. + +This pattern is very common in Rust, though, so there's the `?` operator that +does pretty much what you would make that match statement do for you! + +Take a look at this section of the "Error Handling" chapter: +https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator""" + +[[exercises]] +name = "errors3" +dir = "13_error_handling" +test = false +hint = """ +If other functions can return a `Result`, why shouldn't `main`? It's a fairly +common convention to return something like `Result<(), ErrorType>` from your +`main` function. + +The unit type `()` is there because nothing is really needed in terms of a +positive result.""" + +[[exercises]] +name = "errors4" +dir = "13_error_handling" +hint = """ +`PositiveNonzeroInteger::new` is always creating a new instance and returning +an `Ok` result. But it should be doing some checking, returning an `Err` if +those checks fail, and only returning an `Ok` if those checks determine that +everything is… okay :)""" + +[[exercises]] +name = "errors5" +dir = "13_error_handling" +test = false +hint = """ +There are two different possible `Result` types produced within the `main` +function, which are propagated using the `?` operators. How do we declare a +return type for the `main` function that allows both? + +Under the hood, the `?` operator calls `From::from` on the error value to +convert it to a boxed trait object, a `Box`. This boxed trait object +is polymorphic, and since all errors implement the `Error` trait, we can capture +lots of different errors in one `Box` object. + +Check out this section of The Book: +https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator + +Read more about boxing errors: +https://doc.rust-lang.org/stable/rust-by-example/error/multiple_error_types/boxing_errors.html + +Read more about using the `?` operator with boxed errors: +https://doc.rust-lang.org/stable/rust-by-example/error/multiple_error_types/reenter_question_mark.html""" + +[[exercises]] +name = "errors6" +dir = "13_error_handling" +hint = """ +This exercise uses a completed version of `PositiveNonzeroInteger` from the +previous exercises. + +Below the line that `TODO` asks you to change, there is an example of using +the `map_err()` method on a `Result` to transform one type of error into +another. Try using something similar on the `Result` from `parse()`. You +can then use the `?` operator to return early. + +Read more about `map_err()` in the `std::result` documentation: +https://doc.rust-lang.org/std/result/enum.Result.html#method.map_err""" + +# Generics + +[[exercises]] +name = "generics1" +dir = "14_generics" +test = false +hint = """ +Vectors in Rust make use of generics to create dynamically sized arrays of any +type. +If the vector `numbers` has the type `Vec`, then we can only push values of +type `T` to it. By using `into()` before pushing, we ask the compiler to convert +`n1` and `n2` to `T`. But the compiler doesn't know what `T` is yet and needs a +type annotation. + +`u8` and `i8` can both be converted to `i16`, `i32` and `i64`. Choose one for +the generic of the vector.""" + +[[exercises]] +name = "generics2" +dir = "14_generics" +hint = """ +Related section in The Book: +https://doc.rust-lang.org/book/ch10-01-syntax.html#in-method-definitions""" + +# TRAITS + +[[exercises]] +name = "traits1" +dir = "15_traits" +hint = """ +More about traits in The Book: +https://doc.rust-lang.org/book/ch10-02-traits.html + +The `+` operator can concatenate a `String` with a `&str`.""" + +[[exercises]] +name = "traits2" +dir = "15_traits" +hint = """ +Notice how the trait takes ownership of `self` and returns `Self`. + +Although the signature of `append_bar` in the trait takes `self` as argument, +the implementation can take `mut self` instead. This is possible because the +value is owned anyway.""" + +[[exercises]] +name = "traits3" +dir = "15_traits" +hint = """ +Traits can have a default implementation for functions. Data types that +implement the trait can then use the default version of these functions +if they choose not to implement the function themselves. + +Related section in The Book: +https://doc.rust-lang.org/book/ch10-02-traits.html#default-implementations""" + +[[exercises]] +name = "traits4" +dir = "15_traits" +hint = """ +Instead of using concrete types as parameters you can use traits. Try replacing +`???` with `impl [what goes here?]`. + +Related section in The Book: +https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters""" + +[[exercises]] +name = "traits5" +dir = "15_traits" +hint = """ +To ensure a parameter implements multiple traits use the '+ syntax'. Try +replacing `???` with 'impl [what goes here?] + [what goes here?]'. + +Related section in The Book: +https://doc.rust-lang.org/book/ch10-02-traits.html#specifying-multiple-trait-bounds-with-the--syntax""" + +# QUIZ 3 + +[[exercises]] +name = "quiz3" +dir = "quizzes" +hint = """ +To find the best solution to this challenge, you need to recall your knowledge +of traits, specifically "Trait Bound Syntax": +https://doc.rust-lang.org/book/ch10-02-traits.html#trait-bound-syntax + +Here is how to specify a trait bound for an implementation block: +`impl for Foo { … }` + +You may need this: +`use std::fmt::Display;`""" + +# LIFETIMES + +[[exercises]] +name = "lifetimes1" +dir = "16_lifetimes" +hint = """ +Let the compiler guide you. Also take a look at The Book if you need help: +https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html""" + +[[exercises]] +name = "lifetimes2" +dir = "16_lifetimes" +test = false +hint = """ +Remember that the generic lifetime `'a` will get the concrete lifetime that is +equal to the smaller of the lifetimes of `x` and `y`. + +You can take at least two paths to achieve the desired result while keeping the +inner block: +1. Move the `string2` declaration to make it live as long as `string1` (how is + `result` declared?) +2. Move `println!` into the inner block""" + +[[exercises]] +name = "lifetimes3" +dir = "16_lifetimes" +test = false +hint = """Let the compiler guide you :)""" + +# TESTS + +[[exercises]] +name = "tests1" +dir = "17_tests" +hint = """ +`assert!` is a macro that needs an argument. Depending on the value of the +argument, `assert!` will do nothing (in which case the test will pass) or +`assert!` will panic (in which case the test will fail). + +So try giving different values to `assert!` and see which ones compile, which +ones pass, and which ones fail :) + +If you want to check for `false`, you can negate the result of what you're +checking using `!`, like `assert!(!…)`.""" + +[[exercises]] +name = "tests2" +dir = "17_tests" +hint = """ +`assert_eq!` is a macro that takes two arguments and compares them. Try giving +it two values that are equal! Try giving it two arguments that are different! +Try switching which argument comes first and which comes second!""" + +[[exercises]] +name = "tests3" +dir = "17_tests" +hint = """ +We expect the method `Rectangle::new` to panic for negative values. + +To handle that, you need to add a special attribute to the test function. + +You can refer to the docs: +https://doc.rust-lang.org/book/ch11-01-writing-tests.html#checking-for-panics-with-should_panic""" + +# STANDARD LIBRARY TYPES + +[[exercises]] +name = "iterators1" +dir = "18_iterators" +hint = """ +An iterator goes through all elements in a collection, but what if we've run +out of elements? What should we expect here? If you're stuck, take a look at +https://doc.rust-lang.org/std/iter/trait.Iterator.html""" + +[[exercises]] +name = "iterators2" +dir = "18_iterators" +hint = """ +`capitalize_first`: + +The variable `first` is a `char`. It needs to be capitalized and added to the +remaining characters in `chars` in order to return the correct `String`. + +The remaining characters in `chars` can be viewed as a string slice using the +`as_str` method. + +The documentation for `char` contains many useful methods. +https://doc.rust-lang.org/std/primitive.char.html + +Use `char::to_uppercase`. It returns an iterator that can be converted to a +`String`. + +`capitalize_words_vector`: + +Create an iterator from the slice. Transform the iterated values by applying +the `capitalize_first` function. Remember to `collect` the iterator. + +`capitalize_words_string`: + +This is surprisingly similar to the previous solution. `collect` is very +powerful and very general. Rust just needs to know the desired type.""" + +[[exercises]] +name = "iterators3" +dir = "18_iterators" +hint = """ +The `divide` function needs to return the correct error when the divisor is 0 or +when even division is not possible. + +The `division_results` variable needs to be collected into a collection type. + +The `result_with_list` function needs to return a single `Result` where the +success case is a vector of integers and the failure case is a `DivisionError`. + +The `list_of_results` function needs to return a vector of results. + +See https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.collect for +how the `FromIterator` trait is used in `collect()`. This trait is REALLY +powerful! It can make the solution to this exercise much easier.""" + +[[exercises]] +name = "iterators4" +dir = "18_iterators" +hint = """ +In an imperative language, you might write a `for` loop that updates a mutable +variable. Or, you might write code utilizing recursion and a match clause. In +Rust, you can take another functional approach, computing the factorial +elegantly with ranges and iterators. + +Check out the `fold` and `rfold` methods!""" + +[[exercises]] +name = "iterators5" +dir = "18_iterators" +hint = """ +The documentation for the `std::iter::Iterator` trait contains numerous methods +that would be helpful here. + +The `collection` variable in `count_collection_iterator` is a slice of +`HashMap`s. It needs to be converted into an iterator in order to use the +iterator methods. + +The `fold` method can be useful in the `count_collection_iterator` function. + +For a further challenge, consult the documentation for `Iterator` to find +a different method that could make your code more compact than using `fold`.""" + +# SMART POINTERS + +[[exercises]] +name = "box1" +dir = "19_smart_pointers" +hint = """ +The compiler's message should help: Since we cannot store the value of the +actual type when working with recursive types, we need to store a reference +(pointer) to its value. + +We should, therefore, place our `List` inside a `Box`. More details in The Book: +https://doc.rust-lang.org/book/ch15-01-box.html#enabling-recursive-types-with-boxes + +Creating an empty list should be fairly straightforward (Hint: Read the tests). + +For a non-empty list, keep in mind that we want to use our `Cons` list builder. +Although the current list is one of integers (`i32`), feel free to change the +definition and try other types!""" + +[[exercises]] +name = "rc1" +dir = "19_smart_pointers" +hint = """ +This is a straightforward exercise to use the `Rc` type. Each `Planet` has +ownership of the `Sun`, and uses `Rc::clone()` to increment the reference count +of the `Sun`. + +After using `drop()` to move the `Planet`s out of scope individually, the +reference count goes down. + +In the end, the `Sun` only has one reference again, to itself. + +See more at: https://doc.rust-lang.org/book/ch15-04-rc.html + +Unfortunately, Pluto is no longer considered a planet :(""" + +[[exercises]] +name = "arc1" +dir = "19_smart_pointers" +test = false +hint = """ +Make `shared_numbers` be an `Arc` from the `numbers` vector. Then, in order +to avoid creating a copy of `numbers`, you'll need to create `child_numbers` +inside the loop but still in the main thread. + +`child_numbers` should be a clone of the `Arc` of the numbers instead of a +thread-local copy of the numbers. + +This is a simple exercise if you understand the underlying concepts, but if this +is too much of a struggle, consider reading through all of Chapter 16 in The +Book: +https://doc.rust-lang.org/book/ch16-00-concurrency.html""" + +[[exercises]] +name = "cow1" +dir = "19_smart_pointers" +hint = """ +If `Cow` already owns the data, it doesn't need to clone it when `to_mut()` is +called. + +Check out the documentation of the `Cow` type: +https://doc.rust-lang.org/std/borrow/enum.Cow.html""" + +# THREADS + +[[exercises]] +name = "threads1" +dir = "20_threads" +test = false +hint = """ +`JoinHandle` is a struct that is returned from a spawned thread: +https://doc.rust-lang.org/std/thread/fn.spawn.html + +A challenge with multi-threaded applications is that the main thread can +finish before the spawned threads are done. +https://doc.rust-lang.org/book/ch16-01-threads.html#waiting-for-all-threads-to-finish-using-join-handles + +Use the `JoinHandle`s to wait for each thread to finish and collect their +results. + +https://doc.rust-lang.org/std/thread/struct.JoinHandle.html""" + +[[exercises]] +name = "threads2" +dir = "20_threads" +test = false +hint = """ +`Arc` is an Atomic Reference Counted pointer that allows safe, shared access +to **immutable** data. But we want to *change* the number of `jobs_done` so +we'll need to also use another type that will only allow one thread to mutate +the data at a time. Take a look at this section of the book: +https://doc.rust-lang.org/book/ch16-03-shared-state.html#atomic-reference-counting-with-arct + +Keep reading if you'd like more hints :) + +Do you now have an `Arc>` at the beginning of `main`? Like: +``` +let status = Arc::new(Mutex::new(JobStatus { jobs_done: 0 })); +``` + +Similar to the code in the following example in The Book: +https://doc.rust-lang.org/book/ch16-03-shared-state.html#sharing-a-mutext-between-multiple-threads""" + +[[exercises]] +name = "threads3" +dir = "20_threads" +hint = """ +An alternate way to handle concurrency between threads is to use an `mpsc` +(multiple producer, single consumer) channel to communicate. + +With both a sending end and a receiving end, it's possible to send values in +one thread and receive them in another. + +Multiple producers are possible by using `clone()` to create a duplicate of the +original sending end. + +Related section in The Book: +https://doc.rust-lang.org/book/ch16-02-message-passing.html""" + +# MACROS + +[[exercises]] +name = "macros1" +dir = "21_macros" +test = false +hint = """ +When you call a macro, you need to add something special compared to a regular +function call.""" + +[[exercises]] +name = "macros2" +dir = "21_macros" +test = false +hint = """ +Macros don't quite play by the same rules as the rest of Rust, in terms of +what's available where. + +Unlike other things in Rust, the order of "where you define a macro" versus +"where you use it" actually matters.""" + +[[exercises]] +name = "macros3" +dir = "21_macros" +test = false +hint = """ +In order to use a macro outside of its module, you need to do something +special to the module to lift the macro out into its parent.""" + +[[exercises]] +name = "macros4" +dir = "21_macros" +test = false +hint = """ +You only need to add a single character to make this compile. + +The way macros are written, it wants to see something between each "macro arm", +so it can separate them. + +That's all the macro exercises we have in here, but it's barely even scratching +the surface of what you can do with Rust's macros. For a more thorough +introduction, you can have a read through 'The Little Book of Rust Macros': +https://veykril.github.io/tlborm/""" + +# CLIPPY + +[[exercises]] +name = "clippy1" +dir = "22_clippy" +test = false +strict_clippy = true +hint = """ +Rust stores the highest precision version of some long or infinite precision +mathematical constants in the Rust standard library: +https://doc.rust-lang.org/stable/std/f32/consts/index.html + +We may be tempted to use our own approximations for certain mathematical +constants, but clippy recognizes those imprecise mathematical constants as a +source of potential error. + +See the suggestions of the Clippy warning in the compile output and use the +appropriate replacement constant from `std::f32::consts`.""" + +[[exercises]] +name = "clippy2" +dir = "22_clippy" +test = false +strict_clippy = true +hint = """ +`for` loops over `Option` values are more clearly expressed as an `if-let` +statement. + +Not required to solve this exercise, but if you are interested in when iterating +over `Option` can be useful, read the following section in the documentation: +https://doc.rust-lang.org/std/option/#iterating-over-option""" + +[[exercises]] +name = "clippy3" +dir = "22_clippy" +test = false +strict_clippy = true +hint = "No hints this time!" + +# TYPE CONVERSIONS + +[[exercises]] +name = "using_as" +dir = "23_conversions" +hint = """ +Use the `as` operator to cast one of the operands in the last line of the +`average` function into the expected return type.""" + +[[exercises]] +name = "from_into" +dir = "23_conversions" +hint = """ +Follow the steps provided right before the `From` implementation.""" + +[[exercises]] +name = "from_str" +dir = "23_conversions" +hint = """ +The implementation of `FromStr` should return an `Ok` with a `Person` object, +or an `Err` with an error if the string is not valid. + +This is almost like the previous `from_into` exercise, but returning errors +instead of falling back to a default value. + +Another hint: You can use the `map_err` method of `Result` with a function or a +closure to wrap the error from `parse::`. + +Yet another hint: If you would like to propagate errors by using the `?` +operator in your solution, you might want to look at +https://doc.rust-lang.org/stable/rust-by-example/error/multiple_error_types/reenter_question_mark.html""" + +[[exercises]] +name = "try_from_into" +dir = "23_conversions" +hint = """ +Is there an implementation of `TryFrom` in the standard library that can both do +the required integer conversion and check the range of the input? + +Challenge: Can you make the `TryFrom` implementations generic over many integer +types?""" + +[[exercises]] +name = "as_ref_mut" +dir = "23_conversions" +hint = """ +Add `AsRef` or `AsMut` as a trait bound to the functions.""" diff --git a/rustlings-macros/src/lib.rs b/rustlings-macros/src/lib.rs new file mode 100644 index 0000000000..b20c6f1d90 --- /dev/null +++ b/rustlings-macros/src/lib.rs @@ -0,0 +1,56 @@ +use proc_macro::TokenStream; +use quote::quote; +use serde::Deserialize; + +#[derive(Deserialize)] +struct ExerciseInfo { + name: String, + dir: String, +} + +#[derive(Deserialize)] +struct InfoFile { + exercises: Vec, +} + +#[proc_macro] +pub fn include_files(_: TokenStream) -> TokenStream { + let info_file = include_str!("../info.toml"); + let exercises = toml::de::from_str::(info_file) + .expect("Failed to parse `info.toml`") + .exercises; + + let exercise_files = exercises + .iter() + .map(|exercise| format!("../exercises/{}/{}.rs", exercise.dir, exercise.name)); + let solution_files = exercises + .iter() + .map(|exercise| format!("../solutions/{}/{}.rs", exercise.dir, exercise.name)); + + let mut dirs = Vec::with_capacity(32); + let mut dir_inds = vec![0; exercises.len()]; + + for (exercise, dir_ind) in exercises.iter().zip(&mut dir_inds) { + // The directory is often the last one inserted. + if let Some(ind) = dirs.iter().rev().position(|dir| *dir == exercise.dir) { + *dir_ind = dirs.len() - 1 - ind; + continue; + } + + dirs.push(exercise.dir.as_str()); + *dir_ind = dirs.len() - 1; + } + + let readmes = dirs + .iter() + .map(|dir| format!("../exercises/{dir}/README.md")); + + quote! { + EmbeddedFiles { + info_file: #info_file, + exercise_files: &[#(ExerciseFiles { exercise: include_bytes!(#exercise_files), solution: include_bytes!(#solution_files), dir_ind: #dir_inds }),*], + exercise_dirs: &[#(ExerciseDir { name: #dirs, readme: include_bytes!(#readmes) }),*] + } + } + .into() +} diff --git a/solutions/00_intro/intro1.rs b/solutions/00_intro/intro1.rs new file mode 100644 index 0000000000..4fe84549e0 --- /dev/null +++ b/solutions/00_intro/intro1.rs @@ -0,0 +1,5 @@ +fn main() { + // Congratulations, you finished the first exercise 🎉 + // As an introduction to Rustlings, the first exercise only required + // entering `n` in the terminal to go to the next exercise. +} diff --git a/solutions/00_intro/intro2.rs b/solutions/00_intro/intro2.rs new file mode 100644 index 0000000000..b8e031a08a --- /dev/null +++ b/solutions/00_intro/intro2.rs @@ -0,0 +1,4 @@ +fn main() { + // `println!` instead of `printline!`. + println!("Hello world!"); +} diff --git a/solutions/01_variables/variables1.rs b/solutions/01_variables/variables1.rs new file mode 100644 index 0000000000..58d046b2a1 --- /dev/null +++ b/solutions/01_variables/variables1.rs @@ -0,0 +1,6 @@ +fn main() { + // Declaring variables requires the `let` keyword. + let x = 5; + + println!("x has the value {x}"); +} diff --git a/solutions/01_variables/variables2.rs b/solutions/01_variables/variables2.rs new file mode 100644 index 0000000000..50b8d1b42f --- /dev/null +++ b/solutions/01_variables/variables2.rs @@ -0,0 +1,16 @@ +fn main() { + // The easiest way to fix the compiler error is to initialize the + // variable `x`. By setting its value to an integer, Rust infers its type + // as `i32` which is the default type for integers. + let x = 42; + + // But we can enforce a type different from the default `i32` by adding + // a type annotation: + // let x: u8 = 42; + + if x == 10 { + println!("x is ten!"); + } else { + println!("x is not ten!"); + } +} diff --git a/solutions/01_variables/variables3.rs b/solutions/01_variables/variables3.rs new file mode 100644 index 0000000000..15f6557ce7 --- /dev/null +++ b/solutions/01_variables/variables3.rs @@ -0,0 +1,15 @@ +#![allow(clippy::needless_late_init)] + +fn main() { + // Reading uninitialized variables isn't allowed in Rust! + // Therefore, we need to assign a value first. + let x: i32 = 42; + + println!("Number {x}"); + + // It is possible to declare a variable and initialize it later. + // But it can't be used before initialization. + let y: i32; + y = 42; + println!("Number {y}"); +} diff --git a/solutions/01_variables/variables4.rs b/solutions/01_variables/variables4.rs new file mode 100644 index 0000000000..7de6bcbf0c --- /dev/null +++ b/solutions/01_variables/variables4.rs @@ -0,0 +1,9 @@ +fn main() { + // In Rust, variables are immutable by default. + // Adding the `mut` keyword after `let` makes the declared variable mutable. + let mut x = 3; + println!("Number {x}"); + + x = 5; + println!("Number {x}"); +} diff --git a/solutions/01_variables/variables5.rs b/solutions/01_variables/variables5.rs new file mode 100644 index 0000000000..0ea3903013 --- /dev/null +++ b/solutions/01_variables/variables5.rs @@ -0,0 +1,9 @@ +fn main() { + let number = "T-H-R-E-E"; + println!("Spell a number: {number}"); + + // Using variable shadowing + // https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html#shadowing + let number = 3; + println!("Number plus two is: {}", number + 2); +} diff --git a/solutions/01_variables/variables6.rs b/solutions/01_variables/variables6.rs new file mode 100644 index 0000000000..25b7a1e43e --- /dev/null +++ b/solutions/01_variables/variables6.rs @@ -0,0 +1,6 @@ +// The type of constants must always be annotated. +const NUMBER: u64 = 3; + +fn main() { + println!("Number: {NUMBER}"); +} diff --git a/solutions/02_functions/functions1.rs b/solutions/02_functions/functions1.rs new file mode 100644 index 0000000000..dc52744648 --- /dev/null +++ b/solutions/02_functions/functions1.rs @@ -0,0 +1,8 @@ +// Some function with the name `call_me` without arguments or a return value. +fn call_me() { + println!("Hello world!"); +} + +fn main() { + call_me(); +} diff --git a/solutions/02_functions/functions2.rs b/solutions/02_functions/functions2.rs new file mode 100644 index 0000000000..f14ffa350c --- /dev/null +++ b/solutions/02_functions/functions2.rs @@ -0,0 +1,11 @@ +// The type of function arguments must be annotated. +// Added the type annotation `u64`. +fn call_me(num: u64) { + for i in 0..num { + println!("Ring! Call number {}", i + 1); + } +} + +fn main() { + call_me(3); +} diff --git a/solutions/02_functions/functions3.rs b/solutions/02_functions/functions3.rs new file mode 100644 index 0000000000..ce5fe8eb1b --- /dev/null +++ b/solutions/02_functions/functions3.rs @@ -0,0 +1,10 @@ +fn call_me(num: u8) { + for i in 0..num { + println!("Ring! Call number {}", i + 1); + } +} + +fn main() { + // `call_me` expects an argument. + call_me(5); +} diff --git a/solutions/02_functions/functions4.rs b/solutions/02_functions/functions4.rs new file mode 100644 index 0000000000..f823de24ef --- /dev/null +++ b/solutions/02_functions/functions4.rs @@ -0,0 +1,17 @@ +fn is_even(num: i64) -> bool { + num % 2 == 0 +} + +// The return type must always be annotated. +fn sale_price(price: i64) -> i64 { + if is_even(price) { + price - 10 + } else { + price - 3 + } +} + +fn main() { + let original_price = 51; + println!("Your sale price is {}", sale_price(original_price)); +} diff --git a/solutions/02_functions/functions5.rs b/solutions/02_functions/functions5.rs new file mode 100644 index 0000000000..677f32780e --- /dev/null +++ b/solutions/02_functions/functions5.rs @@ -0,0 +1,9 @@ +fn square(num: i32) -> i32 { + // Removed the semicolon `;` at the end of the line below to implicitly return the result. + num * num +} + +fn main() { + let answer = square(3); + println!("The square of 3 is {answer}"); +} diff --git a/solutions/03_if/if1.rs b/solutions/03_if/if1.rs new file mode 100644 index 0000000000..8512a60ff1 --- /dev/null +++ b/solutions/03_if/if1.rs @@ -0,0 +1,28 @@ +fn bigger(a: i32, b: i32) -> i32 { + if a > b { a } else { b } +} + +fn main() { + // You can optionally experiment here. +} + +// Don't mind this for now :) +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ten_is_bigger_than_eight() { + assert_eq!(10, bigger(10, 8)); + } + + #[test] + fn fortytwo_is_bigger_than_thirtytwo() { + assert_eq!(42, bigger(32, 42)); + } + + #[test] + fn equal_numbers() { + assert_eq!(42, bigger(42, 42)); + } +} diff --git a/solutions/03_if/if2.rs b/solutions/03_if/if2.rs new file mode 100644 index 0000000000..21c0dcd35c --- /dev/null +++ b/solutions/03_if/if2.rs @@ -0,0 +1,35 @@ +fn picky_eater(food: &str) -> &str { + if food == "strawberry" { + "Yummy!" + } else if food == "potato" { + "I guess I can eat that." + } else { + "No thanks!" + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn yummy_food() { + assert_eq!(picky_eater("strawberry"), "Yummy!"); + } + + #[test] + fn neutral_food() { + assert_eq!(picky_eater("potato"), "I guess I can eat that."); + } + + #[test] + fn default_disliked_food() { + assert_eq!(picky_eater("broccoli"), "No thanks!"); + assert_eq!(picky_eater("gummy bears"), "No thanks!"); + assert_eq!(picky_eater("literally anything"), "No thanks!"); + } +} diff --git a/solutions/03_if/if3.rs b/solutions/03_if/if3.rs new file mode 100644 index 0000000000..571644d423 --- /dev/null +++ b/solutions/03_if/if3.rs @@ -0,0 +1,53 @@ +fn animal_habitat(animal: &str) -> &str { + let identifier = if animal == "crab" { + 1 + } else if animal == "gopher" { + 2 + } else if animal == "snake" { + 3 + } else { + // Any unused identifier. + 4 + }; + + // Instead of such an identifier, you would use an enum in Rust. + // But we didn't get into enums yet. + if identifier == 1 { + "Beach" + } else if identifier == 2 { + "Burrow" + } else if identifier == 3 { + "Desert" + } else { + "Unknown" + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn gopher_lives_in_burrow() { + assert_eq!(animal_habitat("gopher"), "Burrow") + } + + #[test] + fn snake_lives_in_desert() { + assert_eq!(animal_habitat("snake"), "Desert") + } + + #[test] + fn crab_lives_on_beach() { + assert_eq!(animal_habitat("crab"), "Beach") + } + + #[test] + fn unknown_animal() { + assert_eq!(animal_habitat("dinosaur"), "Unknown") + } +} diff --git a/solutions/04_primitive_types/primitive_types1.rs b/solutions/04_primitive_types/primitive_types1.rs new file mode 100644 index 0000000000..fac6ec04a9 --- /dev/null +++ b/solutions/04_primitive_types/primitive_types1.rs @@ -0,0 +1,11 @@ +fn main() { + let is_morning = true; + if is_morning { + println!("Good morning!"); + } + + let is_evening = !is_morning; + if is_evening { + println!("Good evening!"); + } +} diff --git a/solutions/04_primitive_types/primitive_types2.rs b/solutions/04_primitive_types/primitive_types2.rs new file mode 100644 index 0000000000..eecc6802f9 --- /dev/null +++ b/solutions/04_primitive_types/primitive_types2.rs @@ -0,0 +1,21 @@ +fn main() { + let my_first_initial = 'C'; + if my_first_initial.is_alphabetic() { + println!("Alphabetical!"); + } else if my_first_initial.is_numeric() { + println!("Numerical!"); + } else { + println!("Neither alphabetic nor numeric!"); + } + + // Example with an emoji. + let your_character = '🦀'; + + if your_character.is_alphabetic() { + println!("Alphabetical!"); + } else if your_character.is_numeric() { + println!("Numerical!"); + } else { + println!("Neither alphabetic nor numeric!"); + } +} diff --git a/solutions/04_primitive_types/primitive_types3.rs b/solutions/04_primitive_types/primitive_types3.rs new file mode 100644 index 0000000000..8dd109f92e --- /dev/null +++ b/solutions/04_primitive_types/primitive_types3.rs @@ -0,0 +1,11 @@ +fn main() { + // An array with 100 elements of the value 42. + let a = [42; 100]; + + if a.len() >= 100 { + println!("Wow, that's a big array!"); + } else { + println!("Meh, I eat arrays like that for breakfast."); + panic!("Array not big enough, more elements needed"); + } +} diff --git a/solutions/04_primitive_types/primitive_types4.rs b/solutions/04_primitive_types/primitive_types4.rs new file mode 100644 index 0000000000..4807e66c64 --- /dev/null +++ b/solutions/04_primitive_types/primitive_types4.rs @@ -0,0 +1,23 @@ +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + #[test] + fn slice_out_of_array() { + let a = [1, 2, 3, 4, 5]; + // 0 1 2 3 4 <- indices + // ------- + // | + // +--- slice + + // Note that the upper index 4 is excluded. + let nice_slice = &a[1..4]; + assert_eq!([2, 3, 4], nice_slice); + + // The upper index can be included by using the syntax `..=` (with `=` sign) + let nice_slice = &a[1..=3]; + assert_eq!([2, 3, 4], nice_slice); + } +} diff --git a/solutions/04_primitive_types/primitive_types5.rs b/solutions/04_primitive_types/primitive_types5.rs new file mode 100644 index 0000000000..46d7ae87a1 --- /dev/null +++ b/solutions/04_primitive_types/primitive_types5.rs @@ -0,0 +1,8 @@ +fn main() { + let cat = ("Furry McFurson", 3.5); + + // Destructuring the tuple. + let (name, age) = cat; + + println!("{name} is {age} years old"); +} diff --git a/solutions/04_primitive_types/primitive_types6.rs b/solutions/04_primitive_types/primitive_types6.rs new file mode 100644 index 0000000000..9b7c277971 --- /dev/null +++ b/solutions/04_primitive_types/primitive_types6.rs @@ -0,0 +1,16 @@ +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + #[test] + fn indexing_tuple() { + let numbers = (1, 2, 3); + + // Tuple indexing syntax. + let second = numbers.1; + + assert_eq!(second, 2, "This is not the 2nd number in the tuple!"); + } +} diff --git a/solutions/05_vecs/vecs1.rs b/solutions/05_vecs/vecs1.rs new file mode 100644 index 0000000000..55b5676c0a --- /dev/null +++ b/solutions/05_vecs/vecs1.rs @@ -0,0 +1,23 @@ +fn array_and_vec() -> ([i32; 4], Vec) { + let a = [10, 20, 30, 40]; // Array + + // Used the `vec!` macro. + let v = vec![10, 20, 30, 40]; + + (a, v) +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_array_and_vec_similarity() { + let (a, v) = array_and_vec(); + assert_eq!(a, *v); + } +} diff --git a/solutions/05_vecs/vecs2.rs b/solutions/05_vecs/vecs2.rs new file mode 100644 index 0000000000..aae71038fa --- /dev/null +++ b/solutions/05_vecs/vecs2.rs @@ -0,0 +1,25 @@ +fn vec_loop(input: &[i32]) -> Vec { + let mut output = Vec::new(); + + for element in input { + output.push(2 * element); + } + + output +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_vec_loop() { + let input = [2, 4, 6, 8, 10]; + let ans = vec_loop(&input); + assert_eq!(ans, [4, 8, 12, 16, 20]); + } +} diff --git a/solutions/06_move_semantics/move_semantics1.rs b/solutions/06_move_semantics/move_semantics1.rs new file mode 100644 index 0000000000..ac34e7a07e --- /dev/null +++ b/solutions/06_move_semantics/move_semantics1.rs @@ -0,0 +1,25 @@ +fn fill_vec(vec: Vec) -> Vec { + let mut vec = vec; + // ^^^ added + + vec.push(88); + + vec +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn move_semantics1() { + let vec0 = vec![22, 44, 66]; + let vec1 = fill_vec(vec0); + // `vec0` can't be accessed anymore because it is moved to `fill_vec`. + assert_eq!(vec1, vec![22, 44, 66, 88]); + } +} diff --git a/solutions/06_move_semantics/move_semantics2.rs b/solutions/06_move_semantics/move_semantics2.rs new file mode 100644 index 0000000000..7bcd33a05d --- /dev/null +++ b/solutions/06_move_semantics/move_semantics2.rs @@ -0,0 +1,28 @@ +fn fill_vec(vec: Vec) -> Vec { + let mut vec = vec; + + vec.push(88); + + vec +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn move_semantics2() { + let vec0 = vec![22, 44, 66]; + + // Cloning `vec0` so that the clone is moved into `fill_vec`, not `vec0` + // itself. + let vec1 = fill_vec(vec0.clone()); + + assert_eq!(vec0, [22, 44, 66]); + assert_eq!(vec1, [22, 44, 66, 88]); + } +} diff --git a/solutions/06_move_semantics/move_semantics3.rs b/solutions/06_move_semantics/move_semantics3.rs new file mode 100644 index 0000000000..7ba4006b76 --- /dev/null +++ b/solutions/06_move_semantics/move_semantics3.rs @@ -0,0 +1,22 @@ +fn fill_vec(mut vec: Vec) -> Vec { + // ^^^ added + vec.push(88); + + vec +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn move_semantics3() { + let vec0 = vec![22, 44, 66]; + let vec1 = fill_vec(vec0); + assert_eq!(vec1, [22, 44, 66, 88]); + } +} diff --git a/solutions/06_move_semantics/move_semantics4.rs b/solutions/06_move_semantics/move_semantics4.rs new file mode 100644 index 0000000000..1a39d4fc8a --- /dev/null +++ b/solutions/06_move_semantics/move_semantics4.rs @@ -0,0 +1,19 @@ +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + #[test] + fn move_semantics4() { + let mut x = Vec::new(); + let y = &mut x; + // `y` used here. + y.push(42); + // The mutable reference `y` is not used anymore, + // therefore a new reference can be created. + let z = &mut x; + z.push(13); + assert_eq!(x, [42, 13]); + } +} diff --git a/solutions/06_move_semantics/move_semantics5.rs b/solutions/06_move_semantics/move_semantics5.rs new file mode 100644 index 0000000000..1410e913fa --- /dev/null +++ b/solutions/06_move_semantics/move_semantics5.rs @@ -0,0 +1,23 @@ +#![allow(clippy::ptr_arg)] + +// Borrows instead of taking ownership. +// It is recommended to use `&str` instead of `&String` here. But this is +// enough for now because we didn't handle strings yet. +fn get_char(data: &String) -> char { + data.chars().last().unwrap() +} + +// Takes ownership instead of borrowing. +fn string_uppercase(mut data: String) { + data = data.to_uppercase(); + + println!("{data}"); +} + +fn main() { + let data = "Rust is great!".to_string(); + + get_char(&data); + + string_uppercase(data); +} diff --git a/solutions/07_structs/structs1.rs b/solutions/07_structs/structs1.rs new file mode 100644 index 0000000000..98fafcc52a --- /dev/null +++ b/solutions/07_structs/structs1.rs @@ -0,0 +1,49 @@ +struct ColorRegularStruct { + red: u8, + green: u8, + blue: u8, +} + +struct ColorTupleStruct(u8, u8, u8); + +#[derive(Debug)] +struct UnitStruct; + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn regular_structs() { + let green = ColorRegularStruct { + red: 0, + green: 255, + blue: 0, + }; + + assert_eq!(green.red, 0); + assert_eq!(green.green, 255); + assert_eq!(green.blue, 0); + } + + #[test] + fn tuple_structs() { + let green = ColorTupleStruct(0, 255, 0); + + assert_eq!(green.0, 0); + assert_eq!(green.1, 255); + assert_eq!(green.2, 0); + } + + #[test] + fn unit_structs() { + let unit_struct = UnitStruct; + let message = format!("{unit_struct:?}s are fun!"); + + assert_eq!(message, "UnitStructs are fun!"); + } +} diff --git a/solutions/07_structs/structs2.rs b/solutions/07_structs/structs2.rs new file mode 100644 index 0000000000..589dd93315 --- /dev/null +++ b/solutions/07_structs/structs2.rs @@ -0,0 +1,51 @@ +#[derive(Debug)] +struct Order { + name: String, + year: u32, + made_by_phone: bool, + made_by_mobile: bool, + made_by_email: bool, + item_number: u32, + count: u32, +} + +fn create_order_template() -> Order { + Order { + name: String::from("Bob"), + year: 2019, + made_by_phone: false, + made_by_mobile: false, + made_by_email: true, + item_number: 123, + count: 0, + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn your_order() { + let order_template = create_order_template(); + + let your_order = Order { + name: String::from("Hacker in Rust"), + count: 1, + // Struct update syntax + ..order_template + }; + + assert_eq!(your_order.name, "Hacker in Rust"); + assert_eq!(your_order.year, order_template.year); + assert_eq!(your_order.made_by_phone, order_template.made_by_phone); + assert_eq!(your_order.made_by_mobile, order_template.made_by_mobile); + assert_eq!(your_order.made_by_email, order_template.made_by_email); + assert_eq!(your_order.item_number, order_template.item_number); + assert_eq!(your_order.count, 1); + } +} diff --git a/exercises/structs/structs3.rs b/solutions/07_structs/structs3.rs similarity index 60% rename from exercises/structs/structs3.rs rename to solutions/07_structs/structs3.rs index 0b3615f4cb..3f878cc86c 100644 --- a/exercises/structs/structs3.rs +++ b/solutions/07_structs/structs3.rs @@ -1,40 +1,40 @@ -// structs3.rs -// Structs contain data, but can also have logic. In this exercise we have -// defined the Package struct and we want to test some logic attached to it. -// Make the code compile and the tests pass! -// Execute `rustlings hint structs3` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - #[derive(Debug)] struct Package { sender_country: String, recipient_country: String, - weight_in_grams: i32, + weight_in_grams: u32, } impl Package { - fn new(sender_country: String, recipient_country: String, weight_in_grams: i32) -> Package { - if weight_in_grams <= 0 { - panic!("Can not ship a weightless package.") - } else { - Package { - sender_country, - recipient_country, - weight_in_grams, - } + fn new(sender_country: String, recipient_country: String, weight_in_grams: u32) -> Self { + if weight_in_grams < 10 { + // This isn't how you should handle errors in Rust, but we will + // learn about error handling later. + panic!("Can't ship a package with weight below 10 grams"); + } + + Self { + sender_country, + recipient_country, + weight_in_grams, } } - fn is_international(&self) -> ??? { - // Something goes here... + fn is_international(&self) -> bool { + // ^^^^^^^ added + self.sender_country != self.recipient_country } - fn get_fees(&self, cents_per_gram: i32) -> ??? { - // Something goes here... + fn get_fees(&self, cents_per_gram: u32) -> u32 { + // ^^^^^^ added + self.weight_in_grams * cents_per_gram } } +fn main() { + // You can optionally experiment here. +} + #[cfg(test)] mod tests { use super::*; @@ -45,7 +45,7 @@ mod tests { let sender_country = String::from("Spain"); let recipient_country = String::from("Austria"); - Package::new(sender_country, recipient_country, -2210); + Package::new(sender_country, recipient_country, 5); } #[test] @@ -78,5 +78,6 @@ mod tests { let package = Package::new(sender_country, recipient_country, 1500); assert_eq!(package.get_fees(cents_per_gram), 4500); + assert_eq!(package.get_fees(cents_per_gram * 2), 9000); } } diff --git a/solutions/08_enums/enums1.rs b/solutions/08_enums/enums1.rs new file mode 100644 index 0000000000..97a5cc0639 --- /dev/null +++ b/solutions/08_enums/enums1.rs @@ -0,0 +1,16 @@ +#[derive(Debug)] +enum Message { + Resize, + Move, + Echo, + ChangeColor, + Quit, +} + +fn main() { + println!("{:?}", Message::Resize); + println!("{:?}", Message::Move); + println!("{:?}", Message::Echo); + println!("{:?}", Message::ChangeColor); + println!("{:?}", Message::Quit); +} diff --git a/solutions/08_enums/enums2.rs b/solutions/08_enums/enums2.rs new file mode 100644 index 0000000000..07aee262f7 --- /dev/null +++ b/solutions/08_enums/enums2.rs @@ -0,0 +1,37 @@ +#[derive(Debug)] +struct Point { + x: u64, + y: u64, +} + +#[derive(Debug)] +enum Message { + Resize { width: u64, height: u64 }, + Move(Point), + Echo(String), + ChangeColor(u8, u8, u8), + Quit, +} + +impl Message { + fn call(&self) { + println!("{self:?}"); + } +} + +fn main() { + let messages = [ + Message::Resize { + width: 10, + height: 30, + }, + Message::Move(Point { x: 10, y: 15 }), + Message::Echo(String::from("hello world")), + Message::ChangeColor(200, 255, 255), + Message::Quit, + ]; + + for message in &messages { + message.call(); + } +} diff --git a/solutions/08_enums/enums3.rs b/solutions/08_enums/enums3.rs new file mode 100644 index 0000000000..94cf250f0a --- /dev/null +++ b/solutions/08_enums/enums3.rs @@ -0,0 +1,92 @@ +struct Point { + x: u64, + y: u64, +} + +enum Message { + Resize { width: u64, height: u64 }, + Move(Point), + Echo(String), + ChangeColor(u8, u8, u8), + Quit, +} + +struct State { + width: u64, + height: u64, + position: Point, + message: String, + color: (u8, u8, u8), + quit: bool, +} + +impl State { + fn resize(&mut self, width: u64, height: u64) { + self.width = width; + self.height = height; + } + + fn move_position(&mut self, point: Point) { + self.position = point; + } + + fn echo(&mut self, s: String) { + self.message = s; + } + + fn change_color(&mut self, red: u8, green: u8, blue: u8) { + self.color = (red, green, blue); + } + + fn quit(&mut self) { + self.quit = true; + } + + fn process(&mut self, message: Message) { + match message { + Message::Resize { width, height } => self.resize(width, height), + Message::Move(point) => self.move_position(point), + Message::Echo(string) => self.echo(string), + Message::ChangeColor(red, green, blue) => self.change_color(red, green, blue), + Message::Quit => self.quit(), + } + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_match_message_call() { + let mut state = State { + width: 0, + height: 0, + position: Point { x: 0, y: 0 }, + message: String::from("hello world"), + color: (0, 0, 0), + quit: false, + }; + + state.process(Message::Resize { + width: 10, + height: 30, + }); + state.process(Message::Move(Point { x: 10, y: 15 })); + state.process(Message::Echo(String::from("Hello world!"))); + state.process(Message::ChangeColor(255, 0, 255)); + state.process(Message::Quit); + + assert_eq!(state.width, 10); + assert_eq!(state.height, 30); + assert_eq!(state.position.x, 10); + assert_eq!(state.position.y, 15); + assert_eq!(state.message, "Hello world!"); + assert_eq!(state.color, (255, 0, 255)); + assert!(state.quit); + } +} diff --git a/solutions/09_strings/strings1.rs b/solutions/09_strings/strings1.rs new file mode 100644 index 0000000000..f7ba8114ae --- /dev/null +++ b/solutions/09_strings/strings1.rs @@ -0,0 +1,9 @@ +fn current_favorite_color() -> String { + // Equivalent to `String::from("blue")` + "blue".to_string() +} + +fn main() { + let answer = current_favorite_color(); + println!("My current favorite color is {answer}"); +} diff --git a/solutions/09_strings/strings2.rs b/solutions/09_strings/strings2.rs new file mode 100644 index 0000000000..7de311fff9 --- /dev/null +++ b/solutions/09_strings/strings2.rs @@ -0,0 +1,15 @@ +fn is_a_color_word(attempt: &str) -> bool { + attempt == "green" || attempt == "blue" || attempt == "red" +} + +fn main() { + let word = String::from("green"); + + if is_a_color_word(&word) { + // ^ added to have `&String` which is automatically + // coerced to `&str` by the compiler. + println!("That is a color word I know!"); + } else { + println!("That is not a color word I know."); + } +} diff --git a/solutions/09_strings/strings3.rs b/solutions/09_strings/strings3.rs new file mode 100644 index 0000000000..ee6b56afe1 --- /dev/null +++ b/solutions/09_strings/strings3.rs @@ -0,0 +1,49 @@ +fn trim_me(input: &str) -> &str { + input.trim() +} + +fn compose_me(input: &str) -> String { + // The macro `format!` has the same syntax as `println!`, but it returns a + // string instead of printing it to the terminal. + // Equivalent to `input.to_string() + " world!"` + format!("{input} world!") +} + +fn replace_me(input: &str) -> String { + input.replace("cars", "balloons") +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn trim_a_string() { + assert_eq!(trim_me("Hello! "), "Hello!"); + assert_eq!(trim_me(" What's up!"), "What's up!"); + assert_eq!(trim_me(" Hola! "), "Hola!"); + assert_eq!(trim_me("Hi!"), "Hi!"); + } + + #[test] + fn compose_a_string() { + assert_eq!(compose_me("Hello"), "Hello world!"); + assert_eq!(compose_me("Goodbye"), "Goodbye world!"); + } + + #[test] + fn replace_a_string() { + assert_eq!( + replace_me("I think cars are cool"), + "I think balloons are cool", + ); + assert_eq!( + replace_me("I love to look at cars"), + "I love to look at balloons", + ); + } +} diff --git a/solutions/09_strings/strings4.rs b/solutions/09_strings/strings4.rs new file mode 100644 index 0000000000..087b0386d4 --- /dev/null +++ b/solutions/09_strings/strings4.rs @@ -0,0 +1,38 @@ +fn string_slice(arg: &str) { + println!("{arg}"); +} + +fn string(arg: String) { + println!("{arg}"); +} + +fn main() { + string_slice("blue"); + + string("red".to_string()); + + string(String::from("hi")); + + string("rust is fun!".to_owned()); + + // Here, both answers work. + // `.into()` converts a type into an expected type. + // If it is called where `String` is expected, it will convert `&str` to `String`. + string("nice weather".into()); + // But if it is called where `&str` is expected, then `&str` is kept as `&str` since no conversion is needed. + // If you remove the `#[allow(…)]` line, then Clippy will tell you to remove `.into()` below since it is a useless conversion. + #[allow(clippy::useless_conversion)] + string_slice("nice weather".into()); + + string(format!("Interpolation {}", "Station")); + + // WARNING: This is byte indexing, not character indexing. + // Character indexing can be done using `s.chars().nth(INDEX)`. + string_slice(&String::from("abc")[0..1]); + + string_slice(" hello there ".trim()); + + string("Happy Monday!".replace("Mon", "Tues")); + + string("mY sHiFt KeY iS sTiCkY".to_lowercase()); +} diff --git a/solutions/10_modules/modules1.rs b/solutions/10_modules/modules1.rs new file mode 100644 index 0000000000..873b4127e6 --- /dev/null +++ b/solutions/10_modules/modules1.rs @@ -0,0 +1,15 @@ +mod sausage_factory { + fn get_secret_recipe() -> String { + String::from("Ginger") + } + + // Added `pub` before `fn` to make the function accessible outside the module. + pub fn make_sausage() { + get_secret_recipe(); + println!("sausage!"); + } +} + +fn main() { + sausage_factory::make_sausage(); +} diff --git a/solutions/10_modules/modules2.rs b/solutions/10_modules/modules2.rs new file mode 100644 index 0000000000..55c316d706 --- /dev/null +++ b/solutions/10_modules/modules2.rs @@ -0,0 +1,23 @@ +mod delicious_snacks { + // Added `pub` and used the expected alias after `as`. + pub use self::fruits::PEAR as fruit; + pub use self::veggies::CUCUMBER as veggie; + + mod fruits { + pub const PEAR: &str = "Pear"; + pub const APPLE: &str = "Apple"; + } + + mod veggies { + pub const CUCUMBER: &str = "Cucumber"; + pub const CARROT: &str = "Carrot"; + } +} + +fn main() { + println!( + "favorite snacks: {} and {}", + delicious_snacks::fruit, + delicious_snacks::veggie, + ); +} diff --git a/solutions/10_modules/modules3.rs b/solutions/10_modules/modules3.rs new file mode 100644 index 0000000000..99ff5a77ff --- /dev/null +++ b/solutions/10_modules/modules3.rs @@ -0,0 +1,8 @@ +use std::time::{SystemTime, UNIX_EPOCH}; + +fn main() { + match SystemTime::now().duration_since(UNIX_EPOCH) { + Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()), + Err(_) => panic!("SystemTime before UNIX EPOCH!"), + } +} diff --git a/solutions/11_hashmaps/hashmaps1.rs b/solutions/11_hashmaps/hashmaps1.rs new file mode 100644 index 0000000000..0a654b88da --- /dev/null +++ b/solutions/11_hashmaps/hashmaps1.rs @@ -0,0 +1,42 @@ +// A basket of fruits in the form of a hash map needs to be defined. The key +// represents the name of the fruit and the value represents how many of that +// particular fruit is in the basket. You have to put at least 3 different +// types of fruits (e.g. apple, banana, mango) in the basket and the total count +// of all the fruits should be at least 5. + +use std::collections::HashMap; + +fn fruit_basket() -> HashMap { + // Declare the hash map. + let mut basket = HashMap::new(); + + // Two bananas are already given for you :) + basket.insert(String::from("banana"), 2); + + // Put more fruits in your basket. + basket.insert(String::from("apple"), 3); + basket.insert(String::from("mango"), 1); + + basket +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn at_least_three_types_of_fruits() { + let basket = fruit_basket(); + assert!(basket.len() >= 3); + } + + #[test] + fn at_least_five_fruits() { + let basket = fruit_basket(); + assert!(basket.values().sum::() >= 5); + } +} diff --git a/solutions/11_hashmaps/hashmaps2.rs b/solutions/11_hashmaps/hashmaps2.rs new file mode 100644 index 0000000000..75e6ec2cfc --- /dev/null +++ b/solutions/11_hashmaps/hashmaps2.rs @@ -0,0 +1,96 @@ +// We're collecting different fruits to bake a delicious fruit cake. For this, +// we have a basket, which we'll represent in the form of a hash map. The key +// represents the name of each fruit we collect and the value represents how +// many of that particular fruit we have collected. Three types of fruits - +// Apple (4), Mango (2) and Lychee (5) are already in the basket hash map. You +// must add fruit to the basket so that there is at least one of each kind and +// more than 11 in total - we have a lot of mouths to feed. You are not allowed +// to insert any more of the fruits that are already in the basket (Apple, +// Mango, and Lychee). + +use std::collections::HashMap; + +#[derive(Hash, PartialEq, Eq, Debug)] +enum Fruit { + Apple, + Banana, + Mango, + Lychee, + Pineapple, +} + +fn fruit_basket(basket: &mut HashMap) { + let fruit_kinds = [ + Fruit::Apple, + Fruit::Banana, + Fruit::Mango, + Fruit::Lychee, + Fruit::Pineapple, + ]; + + for fruit in fruit_kinds { + // If fruit doesn't exist, insert it with some value. + basket.entry(fruit).or_insert(5); + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + // Don't modify this function! + fn get_fruit_basket() -> HashMap { + let content = [(Fruit::Apple, 4), (Fruit::Mango, 2), (Fruit::Lychee, 5)]; + HashMap::from_iter(content) + } + + #[test] + fn test_given_fruits_are_not_modified() { + let mut basket = get_fruit_basket(); + fruit_basket(&mut basket); + assert_eq!(*basket.get(&Fruit::Apple).unwrap(), 4); + assert_eq!(*basket.get(&Fruit::Mango).unwrap(), 2); + assert_eq!(*basket.get(&Fruit::Lychee).unwrap(), 5); + } + + #[test] + fn at_least_five_types_of_fruits() { + let mut basket = get_fruit_basket(); + fruit_basket(&mut basket); + let count_fruit_kinds = basket.len(); + assert!(count_fruit_kinds >= 5); + } + + #[test] + fn greater_than_eleven_fruits() { + let mut basket = get_fruit_basket(); + fruit_basket(&mut basket); + let count = basket.values().sum::(); + assert!(count > 11); + } + + #[test] + fn all_fruit_types_in_basket() { + let fruit_kinds = [ + Fruit::Apple, + Fruit::Banana, + Fruit::Mango, + Fruit::Lychee, + Fruit::Pineapple, + ]; + + let mut basket = get_fruit_basket(); + fruit_basket(&mut basket); + + for fruit_kind in fruit_kinds { + let Some(amount) = basket.get(&fruit_kind) else { + panic!("Fruit kind {fruit_kind:?} was not found in basket"); + }; + assert!(*amount > 0); + } + } +} diff --git a/solutions/11_hashmaps/hashmaps3.rs b/solutions/11_hashmaps/hashmaps3.rs new file mode 100644 index 0000000000..485bf83034 --- /dev/null +++ b/solutions/11_hashmaps/hashmaps3.rs @@ -0,0 +1,85 @@ +// A list of scores (one per line) of a soccer match is given. Each line is of +// the form ",,," +// Example: "England,France,4,2" (England scored 4 goals, France 2). +// +// You have to build a scores table containing the name of the team, the total +// number of goals the team scored, and the total number of goals the team +// conceded. + +use std::collections::HashMap; + +// A structure to store the goal details of a team. +#[derive(Default)] +struct TeamScores { + goals_scored: u8, + goals_conceded: u8, +} + +fn build_scores_table(results: &str) -> HashMap<&str, TeamScores> { + // The name of the team is the key and its associated struct is the value. + let mut scores = HashMap::<&str, TeamScores>::new(); + + for line in results.lines() { + let mut split_iterator = line.split(','); + // NOTE: We use `unwrap` because we didn't deal with error handling yet. + let team_1_name = split_iterator.next().unwrap(); + let team_2_name = split_iterator.next().unwrap(); + let team_1_score: u8 = split_iterator.next().unwrap().parse().unwrap(); + let team_2_score: u8 = split_iterator.next().unwrap().parse().unwrap(); + + // Insert the default with zeros if a team doesn't exist yet. + let team_1 = scores.entry(team_1_name).or_default(); + // Update the values. + team_1.goals_scored += team_1_score; + team_1.goals_conceded += team_2_score; + + // Similarly for the second team. + let team_2 = scores.entry(team_2_name).or_default(); + team_2.goals_scored += team_2_score; + team_2.goals_conceded += team_1_score; + } + + scores +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + const RESULTS: &str = "England,France,4,2 +France,Italy,3,1 +Poland,Spain,2,0 +Germany,England,2,1 +England,Spain,1,0"; + + #[test] + fn build_scores() { + let scores = build_scores_table(RESULTS); + + assert!( + ["England", "France", "Germany", "Italy", "Poland", "Spain"] + .into_iter() + .all(|team_name| scores.contains_key(team_name)) + ); + } + + #[test] + fn validate_team_score_1() { + let scores = build_scores_table(RESULTS); + let team = scores.get("England").unwrap(); + assert_eq!(team.goals_scored, 6); + assert_eq!(team.goals_conceded, 4); + } + + #[test] + fn validate_team_score_2() { + let scores = build_scores_table(RESULTS); + let team = scores.get("Spain").unwrap(); + assert_eq!(team.goals_scored, 0); + assert_eq!(team.goals_conceded, 3); + } +} diff --git a/solutions/12_options/options1.rs b/solutions/12_options/options1.rs new file mode 100644 index 0000000000..a8e6457d19 --- /dev/null +++ b/solutions/12_options/options1.rs @@ -0,0 +1,39 @@ +// This function returns how much ice cream there is left in the fridge. +// If it's before 22:00 (24-hour system), then 5 scoops are left. At 22:00, +// someone eats it all, so no ice cream is left (value 0). Return `None` if +// `hour_of_day` is higher than 23. +fn maybe_ice_cream(hour_of_day: u16) -> Option { + match hour_of_day { + 0..=21 => Some(5), + 22..=23 => Some(0), + _ => None, + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn raw_value() { + // Using `unwrap` is fine in a test. + let ice_creams = maybe_ice_cream(12).unwrap(); + + assert_eq!(ice_creams, 5); + } + + #[test] + fn check_ice_cream() { + assert_eq!(maybe_ice_cream(0), Some(5)); + assert_eq!(maybe_ice_cream(9), Some(5)); + assert_eq!(maybe_ice_cream(18), Some(5)); + assert_eq!(maybe_ice_cream(22), Some(0)); + assert_eq!(maybe_ice_cream(23), Some(0)); + assert_eq!(maybe_ice_cream(24), None); + assert_eq!(maybe_ice_cream(25), None); + } +} diff --git a/solutions/12_options/options2.rs b/solutions/12_options/options2.rs new file mode 100644 index 0000000000..0f24665ff5 --- /dev/null +++ b/solutions/12_options/options2.rs @@ -0,0 +1,37 @@ +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + #[test] + fn simple_option() { + let target = "rustlings"; + let optional_target = Some(target); + + // if-let + if let Some(word) = optional_target { + assert_eq!(word, target); + } + } + + #[test] + fn layered_option() { + let range = 10; + let mut optional_integers: Vec> = vec![None]; + + for i in 1..=range { + optional_integers.push(Some(i)); + } + + let mut cursor = range; + + // while-let with nested pattern matching + while let Some(Some(integer)) = optional_integers.pop() { + assert_eq!(integer, cursor); + cursor -= 1; + } + + assert_eq!(cursor, 0); + } +} diff --git a/solutions/12_options/options3.rs b/solutions/12_options/options3.rs new file mode 100644 index 0000000000..c918f711dc --- /dev/null +++ b/solutions/12_options/options3.rs @@ -0,0 +1,27 @@ +#[derive(Debug)] +struct Point { + x: i32, + y: i32, +} + +fn main() { + let optional_point = Some(Point { x: 100, y: 200 }); + + // Solution 1: Matching over the `Option` (not `&Option`) but without moving + // out of the `Some` variant. + match optional_point { + Some(ref p) => println!("Coordinates are {},{}", p.x, p.y), + // ^^^ added + _ => panic!("No match!"), + } + + // Solution 2: Matching over a reference (`&Option`) by added `&` before + // `optional_point`. + match &optional_point { + //^ added + Some(p) => println!("Coordinates are {},{}", p.x, p.y), + _ => panic!("No match!"), + } + + println!("{optional_point:?}"); +} diff --git a/solutions/13_error_handling/errors1.rs b/solutions/13_error_handling/errors1.rs new file mode 100644 index 0000000000..f552ca7f6a --- /dev/null +++ b/solutions/13_error_handling/errors1.rs @@ -0,0 +1,37 @@ +fn generate_nametag_text(name: String) -> Result { + // ^^^^^^ ^^^^^^ + if name.is_empty() { + // `Err(String)` instead of `None`. + Err("Empty names aren't allowed".to_string()) + } else { + // `Ok` instead of `Some`. + Ok(format!("Hi! My name is {name}")) + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn generates_nametag_text_for_a_nonempty_name() { + assert_eq!( + generate_nametag_text("Beyoncé".to_string()).as_deref(), + Ok("Hi! My name is Beyoncé"), + ); + } + + #[test] + fn explains_why_generating_nametag_text_fails() { + assert_eq!( + generate_nametag_text(String::new()) + .as_ref() + .map_err(|e| e.as_str()), + Err("Empty names aren't allowed"), + ); + } +} diff --git a/solutions/13_error_handling/errors2.rs b/solutions/13_error_handling/errors2.rs new file mode 100644 index 0000000000..f0e144e746 --- /dev/null +++ b/solutions/13_error_handling/errors2.rs @@ -0,0 +1,58 @@ +// Say we're writing a game where you can buy items with tokens. All items cost +// 5 tokens, and whenever you purchase items there is a processing fee of 1 +// token. A player of the game will type in how many items they want to buy, and +// the `total_cost` function will calculate the total cost of the items. Since +// the player typed in the quantity, we get it as a string. They might have +// typed anything, not just numbers! +// +// Right now, this function isn't handling the error case at all. What we want +// to do is: If we call the `total_cost` function on a string that is not a +// number, that function will return a `ParseIntError`. In that case, we want to +// immediately return that error from our function and not try to multiply and +// add. +// +// There are at least two ways to implement this that are both correct. But one +// is a lot shorter! + +use std::num::ParseIntError; + +#[allow(unused_variables, clippy::question_mark)] +fn total_cost(item_quantity: &str) -> Result { + let processing_fee = 1; + let cost_per_item = 5; + + // Added `?` to propagate the error. + let qty = item_quantity.parse::()?; + // ^ added + + // Equivalent to this verbose version: + let qty = match item_quantity.parse::() { + Ok(v) => v, + Err(e) => return Err(e), + }; + + Ok(qty * cost_per_item + processing_fee) +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + use std::num::IntErrorKind; + + #[test] + fn item_quantity_is_a_valid_number() { + assert_eq!(total_cost("34"), Ok(171)); + } + + #[test] + fn item_quantity_is_an_invalid_number() { + assert_eq!( + total_cost("beep boop").unwrap_err().kind(), + &IntErrorKind::InvalidDigit, + ); + } +} diff --git a/solutions/13_error_handling/errors3.rs b/solutions/13_error_handling/errors3.rs new file mode 100644 index 0000000000..63f4aba182 --- /dev/null +++ b/solutions/13_error_handling/errors3.rs @@ -0,0 +1,32 @@ +// This is a program that is trying to use a completed version of the +// `total_cost` function from the previous exercise. It's not working though! +// Why not? What should we do to fix it? + +use std::num::ParseIntError; + +// Don't change this function. +fn total_cost(item_quantity: &str) -> Result { + let processing_fee = 1; + let cost_per_item = 5; + let qty = item_quantity.parse::()?; + + Ok(qty * cost_per_item + processing_fee) +} + +fn main() -> Result<(), ParseIntError> { + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ added + let mut tokens = 100; + let pretend_user_input = "8"; + + let cost = total_cost(pretend_user_input)?; + + if cost > tokens { + println!("You can't afford that many!"); + } else { + tokens -= cost; + println!("You now have {tokens} tokens."); + } + + // Added this line to return the `Ok` variant of the expected `Result`. + Ok(()) +} diff --git a/solutions/13_error_handling/errors4.rs b/solutions/13_error_handling/errors4.rs new file mode 100644 index 0000000000..70c5f1caa1 --- /dev/null +++ b/solutions/13_error_handling/errors4.rs @@ -0,0 +1,42 @@ +use std::cmp::Ordering; + +#[derive(PartialEq, Debug)] +enum CreationError { + Negative, + Zero, +} + +#[derive(PartialEq, Debug)] +struct PositiveNonzeroInteger(u64); + +impl PositiveNonzeroInteger { + fn new(value: i64) -> Result { + match value.cmp(&0) { + Ordering::Less => Err(CreationError::Negative), + Ordering::Equal => Err(CreationError::Zero), + Ordering::Greater => Ok(Self(value as u64)), + } + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_creation() { + assert_eq!( + PositiveNonzeroInteger::new(10), + Ok(PositiveNonzeroInteger(10)), + ); + assert_eq!( + PositiveNonzeroInteger::new(-10), + Err(CreationError::Negative), + ); + assert_eq!(PositiveNonzeroInteger::new(0), Err(CreationError::Zero)); + } +} diff --git a/solutions/13_error_handling/errors5.rs b/solutions/13_error_handling/errors5.rs new file mode 100644 index 0000000000..93ab3b9d77 --- /dev/null +++ b/solutions/13_error_handling/errors5.rs @@ -0,0 +1,54 @@ +// This exercise is an altered version of the `errors4` exercise. It uses some +// concepts that we won't get to until later in the course, like `Box` and the +// `From` trait. It's not important to understand them in detail right now, but +// you can read ahead if you like. For now, think of the `Box` type as +// an "I want anything that does ???" type. +// +// In short, this particular use case for boxes is for when you want to own a +// value and you care only that it is a type which implements a particular +// trait. To do so, the `Box` is declared as of type `Box` where +// `Trait` is the trait the compiler looks for on any value used in that +// context. For this exercise, that context is the potential errors which +// can be returned in a `Result`. + +use std::error::Error; +use std::fmt; + +#[derive(PartialEq, Debug)] +enum CreationError { + Negative, + Zero, +} + +// This is required so that `CreationError` can implement `Error`. +impl fmt::Display for CreationError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let description = match *self { + CreationError::Negative => "number is negative", + CreationError::Zero => "number is zero", + }; + f.write_str(description) + } +} + +impl Error for CreationError {} + +#[derive(PartialEq, Debug)] +struct PositiveNonzeroInteger(u64); + +impl PositiveNonzeroInteger { + fn new(value: i64) -> Result { + match value { + x if x < 0 => Err(CreationError::Negative), + 0 => Err(CreationError::Zero), + x => Ok(PositiveNonzeroInteger(x as u64)), + } + } +} + +fn main() -> Result<(), Box> { + let pretend_user_input = "42"; + let x: i64 = pretend_user_input.parse()?; + println!("output={:?}", PositiveNonzeroInteger::new(x)?); + Ok(()) +} diff --git a/solutions/13_error_handling/errors6.rs b/solutions/13_error_handling/errors6.rs new file mode 100644 index 0000000000..ce18073afb --- /dev/null +++ b/solutions/13_error_handling/errors6.rs @@ -0,0 +1,106 @@ +// Using catch-all error types like `Box` isn't recommended for +// library code where callers might want to make decisions based on the error +// content instead of printing it out or propagating it further. Here, we define +// a custom error type to make it possible for callers to decide what to do next +// when our function returns an error. + +use std::num::ParseIntError; + +#[derive(PartialEq, Debug)] +enum CreationError { + Negative, + Zero, +} + +// A custom error type that we will be using in `PositiveNonzeroInteger::parse`. +#[derive(PartialEq, Debug)] +enum ParsePosNonzeroError { + Creation(CreationError), + ParseInt(ParseIntError), +} + +impl ParsePosNonzeroError { + fn from_creation(err: CreationError) -> Self { + Self::Creation(err) + } + + fn from_parse_int(err: ParseIntError) -> Self { + Self::ParseInt(err) + } +} + +// As an alternative solution, implementing the `From` trait allows for the +// automatic conversion from a `ParseIntError` into a `ParsePosNonzeroError` +// using the `?` operator, without the need to call `map_err`. +// +// ``` +// let x: i64 = s.parse()?; +// ``` +// +// Traits like `From` will be dealt with in later exercises. +impl From for ParsePosNonzeroError { + fn from(err: ParseIntError) -> Self { + ParsePosNonzeroError::ParseInt(err) + } +} + +#[derive(PartialEq, Debug)] +struct PositiveNonzeroInteger(u64); + +impl PositiveNonzeroInteger { + fn new(value: i64) -> Result { + match value { + x if x < 0 => Err(CreationError::Negative), + 0 => Err(CreationError::Zero), + x => Ok(Self(x as u64)), + } + } + + fn parse(s: &str) -> Result { + // Return an appropriate error instead of panicking when `parse()` + // returns an error. + let x: i64 = s.parse().map_err(ParsePosNonzeroError::from_parse_int)?; + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + Self::new(x).map_err(ParsePosNonzeroError::from_creation) + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_parse_error() { + assert!(matches!( + PositiveNonzeroInteger::parse("not a number"), + Err(ParsePosNonzeroError::ParseInt(_)), + )); + } + + #[test] + fn test_negative() { + assert_eq!( + PositiveNonzeroInteger::parse("-555"), + Err(ParsePosNonzeroError::Creation(CreationError::Negative)), + ); + } + + #[test] + fn test_zero() { + assert_eq!( + PositiveNonzeroInteger::parse("0"), + Err(ParsePosNonzeroError::Creation(CreationError::Zero)), + ); + } + + #[test] + fn test_positive() { + let x = PositiveNonzeroInteger::new(42).unwrap(); + assert_eq!(x.0, 42); + assert_eq!(PositiveNonzeroInteger::parse("42"), Ok(x)); + } +} diff --git a/solutions/14_generics/generics1.rs b/solutions/14_generics/generics1.rs new file mode 100644 index 0000000000..e2195fd360 --- /dev/null +++ b/solutions/14_generics/generics1.rs @@ -0,0 +1,17 @@ +// `Vec` is generic over the type `T`. In most cases, the compiler is able to +// infer `T`, for example after pushing a value with a concrete type to the vector. +// But in this exercise, the compiler needs some help through a type annotation. + +fn main() { + // `u8` and `i8` can both be converted to `i16`. + let mut numbers: Vec = Vec::new(); + // ^^^^^^^^^^ added + + // Don't change the lines below. + let n1: u8 = 42; + numbers.push(n1.into()); + let n2: i8 = -1; + numbers.push(n2.into()); + + println!("{numbers:?}"); +} diff --git a/solutions/14_generics/generics2.rs b/solutions/14_generics/generics2.rs new file mode 100644 index 0000000000..14f3f7afea --- /dev/null +++ b/solutions/14_generics/generics2.rs @@ -0,0 +1,28 @@ +struct Wrapper { + value: T, +} + +impl Wrapper { + fn new(value: T) -> Self { + Wrapper { value } + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn store_u32_in_wrapper() { + assert_eq!(Wrapper::new(42).value, 42); + } + + #[test] + fn store_str_in_wrapper() { + assert_eq!(Wrapper::new("Foo").value, "Foo"); + } +} diff --git a/solutions/15_traits/traits1.rs b/solutions/15_traits/traits1.rs new file mode 100644 index 0000000000..790873f4da --- /dev/null +++ b/solutions/15_traits/traits1.rs @@ -0,0 +1,32 @@ +// The trait `AppendBar` has only one function which appends "Bar" to any object +// implementing this trait. +trait AppendBar { + fn append_bar(self) -> Self; +} + +impl AppendBar for String { + fn append_bar(self) -> Self { + self + "Bar" + } +} + +fn main() { + let s = String::from("Foo"); + let s = s.append_bar(); + println!("s: {s}"); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn is_foo_bar() { + assert_eq!(String::from("Foo").append_bar(), "FooBar"); + } + + #[test] + fn is_bar_bar() { + assert_eq!(String::from("").append_bar().append_bar(), "BarBar"); + } +} diff --git a/solutions/15_traits/traits2.rs b/solutions/15_traits/traits2.rs new file mode 100644 index 0000000000..0db93e0f4f --- /dev/null +++ b/solutions/15_traits/traits2.rs @@ -0,0 +1,27 @@ +trait AppendBar { + fn append_bar(self) -> Self; +} + +impl AppendBar for Vec { + fn append_bar(mut self) -> Self { + // ^^^ this is important + self.push(String::from("Bar")); + self + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn is_vec_pop_eq_bar() { + let mut foo = vec![String::from("Foo")].append_bar(); + assert_eq!(foo.pop().unwrap(), "Bar"); + assert_eq!(foo.pop().unwrap(), "Foo"); + } +} diff --git a/solutions/15_traits/traits3.rs b/solutions/15_traits/traits3.rs new file mode 100644 index 0000000000..3d8ec85ead --- /dev/null +++ b/solutions/15_traits/traits3.rs @@ -0,0 +1,36 @@ +trait Licensed { + fn licensing_info(&self) -> String { + "Default license".to_string() + } +} + +struct SomeSoftware { + version_number: i32, +} + +struct OtherSoftware { + version_number: String, +} + +impl Licensed for SomeSoftware {} +impl Licensed for OtherSoftware {} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn is_licensing_info_the_same() { + let licensing_info = "Default license"; + let some_software = SomeSoftware { version_number: 1 }; + let other_software = OtherSoftware { + version_number: "v2.0.0".to_string(), + }; + assert_eq!(some_software.licensing_info(), licensing_info); + assert_eq!(other_software.licensing_info(), licensing_info); + } +} diff --git a/solutions/15_traits/traits4.rs b/solutions/15_traits/traits4.rs new file mode 100644 index 0000000000..3675b8dfe1 --- /dev/null +++ b/solutions/15_traits/traits4.rs @@ -0,0 +1,35 @@ +trait Licensed { + fn licensing_info(&self) -> String { + "Default license".to_string() + } +} + +struct SomeSoftware; +struct OtherSoftware; + +impl Licensed for SomeSoftware {} +impl Licensed for OtherSoftware {} + +fn compare_license_types(software1: impl Licensed, software2: impl Licensed) -> bool { + // ^^^^^^^^^^^^^ ^^^^^^^^^^^^^ + software1.licensing_info() == software2.licensing_info() +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn compare_license_information() { + assert!(compare_license_types(SomeSoftware, OtherSoftware)); + } + + #[test] + fn compare_license_information_backwards() { + assert!(compare_license_types(OtherSoftware, SomeSoftware)); + } +} diff --git a/solutions/15_traits/traits5.rs b/solutions/15_traits/traits5.rs new file mode 100644 index 0000000000..1fb426a474 --- /dev/null +++ b/solutions/15_traits/traits5.rs @@ -0,0 +1,39 @@ +trait SomeTrait { + fn some_function(&self) -> bool { + true + } +} + +trait OtherTrait { + fn other_function(&self) -> bool { + true + } +} + +struct SomeStruct; +impl SomeTrait for SomeStruct {} +impl OtherTrait for SomeStruct {} + +struct OtherStruct; +impl SomeTrait for OtherStruct {} +impl OtherTrait for OtherStruct {} + +fn some_func(item: impl SomeTrait + OtherTrait) -> bool { + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + item.some_function() && item.other_function() +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_some_func() { + assert!(some_func(SomeStruct)); + assert!(some_func(OtherStruct)); + } +} diff --git a/solutions/16_lifetimes/lifetimes1.rs b/solutions/16_lifetimes/lifetimes1.rs new file mode 100644 index 0000000000..4f56834f9d --- /dev/null +++ b/solutions/16_lifetimes/lifetimes1.rs @@ -0,0 +1,24 @@ +// The Rust compiler needs to know how to check whether supplied references are +// valid, so that it can let the programmer know if a reference is at risk of +// going out of scope before it is used. Remember, references are borrows and do +// not own their own data. What if their owner goes out of scope? + +fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { + // ^^^^ ^^ ^^ ^^ + if x.len() > y.len() { x } else { y } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_longest() { + assert_eq!(longest("abcd", "123"), "abcd"); + assert_eq!(longest("abc", "1234"), "1234"); + } +} diff --git a/solutions/16_lifetimes/lifetimes2.rs b/solutions/16_lifetimes/lifetimes2.rs new file mode 100644 index 0000000000..412c60216a --- /dev/null +++ b/solutions/16_lifetimes/lifetimes2.rs @@ -0,0 +1,29 @@ +fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { + if x.len() > y.len() { x } else { y } +} + +fn main() { + let string1 = String::from("long string is long"); + // Solution 1: You can move `strings2` out of the inner block so that it is + // not dropped before the print statement. + let string2 = String::from("xyz"); + let result; + { + result = longest(&string1, &string2); + } + println!("The longest string is '{result}'"); + // `string2` dropped at the end of the function. + + // ========================================================================= + + let string1 = String::from("long string is long"); + let result; + { + let string2 = String::from("xyz"); + result = longest(&string1, &string2); + // Solution 2: You can move the print statement into the inner block so + // that it is executed before `string2` is dropped. + println!("The longest string is '{result}'"); + // `string2` dropped here (end of the inner scope). + } +} diff --git a/solutions/16_lifetimes/lifetimes3.rs b/solutions/16_lifetimes/lifetimes3.rs new file mode 100644 index 0000000000..16a5a6840c --- /dev/null +++ b/solutions/16_lifetimes/lifetimes3.rs @@ -0,0 +1,18 @@ +// Lifetimes are also needed when structs hold references. + +struct Book<'a> { + // ^^^^ added a lifetime annotation + author: &'a str, + // ^^ + title: &'a str, + // ^^ +} + +fn main() { + let book = Book { + author: "George Orwell", + title: "1984", + }; + + println!("{} by {}", book.title, book.author); +} diff --git a/solutions/17_tests/tests1.rs b/solutions/17_tests/tests1.rs new file mode 100644 index 0000000000..c52b8b16d7 --- /dev/null +++ b/solutions/17_tests/tests1.rs @@ -0,0 +1,24 @@ +// Tests are important to ensure that your code does what you think it should +// do. + +fn is_even(n: i64) -> bool { + n % 2 == 0 +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + // When writing unit tests, it is common to import everything from the outer + // module (`super`) using a wildcard. + use super::*; + + #[test] + fn you_can_assert() { + assert!(is_even(0)); + assert!(!is_even(-1)); + // ^ You can assert `false` using the negation operator `!`. + } +} diff --git a/solutions/17_tests/tests2.rs b/solutions/17_tests/tests2.rs new file mode 100644 index 0000000000..39a0005e8e --- /dev/null +++ b/solutions/17_tests/tests2.rs @@ -0,0 +1,22 @@ +// Calculates the power of 2 using a bit shift. +// `1 << n` is equivalent to "2 to the power of n". +fn power_of_2(n: u8) -> u64 { + 1 << n +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn you_can_assert_eq() { + assert_eq!(power_of_2(0), 1); + assert_eq!(power_of_2(1), 2); + assert_eq!(power_of_2(2), 4); + assert_eq!(power_of_2(3), 8); + } +} diff --git a/solutions/17_tests/tests3.rs b/solutions/17_tests/tests3.rs new file mode 100644 index 0000000000..487fdc66ea --- /dev/null +++ b/solutions/17_tests/tests3.rs @@ -0,0 +1,45 @@ +struct Rectangle { + width: i32, + height: i32, +} + +impl Rectangle { + // Don't change this function. + fn new(width: i32, height: i32) -> Self { + if width <= 0 || height <= 0 { + // Returning a `Result` would be better here. But we want to learn + // how to test functions that can panic. + panic!("Rectangle width and height must be positive"); + } + + Rectangle { width, height } + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn correct_width_and_height() { + let rect = Rectangle::new(10, 20); + assert_eq!(rect.width, 10); // Check width + assert_eq!(rect.height, 20); // Check height + } + + #[test] + #[should_panic] // Added this attribute to check that the test panics. + fn negative_width() { + let _rect = Rectangle::new(-10, 10); + } + + #[test] + #[should_panic] // Added this attribute to check that the test panics. + fn negative_height() { + let _rect = Rectangle::new(10, -10); + } +} diff --git a/solutions/18_iterators/iterators1.rs b/solutions/18_iterators/iterators1.rs new file mode 100644 index 0000000000..93a6008aa5 --- /dev/null +++ b/solutions/18_iterators/iterators1.rs @@ -0,0 +1,26 @@ +// When performing operations on elements within a collection, iterators are +// essential. This module helps you get familiar with the structure of using an +// iterator and how to go through elements within an iterable collection. + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + #[test] + fn iterators() { + let my_fav_fruits = ["banana", "custard apple", "avocado", "peach", "raspberry"]; + + // Create an iterator over the array. + let mut fav_fruits_iterator = my_fav_fruits.iter(); + + assert_eq!(fav_fruits_iterator.next(), Some(&"banana")); + assert_eq!(fav_fruits_iterator.next(), Some(&"custard apple")); + assert_eq!(fav_fruits_iterator.next(), Some(&"avocado")); + assert_eq!(fav_fruits_iterator.next(), Some(&"peach")); + assert_eq!(fav_fruits_iterator.next(), Some(&"raspberry")); + assert_eq!(fav_fruits_iterator.next(), None); + // ^^^^ reached the end + } +} diff --git a/exercises/standard_library_types/iterators2.rs b/solutions/18_iterators/iterators2.rs similarity index 62% rename from exercises/standard_library_types/iterators2.rs rename to solutions/18_iterators/iterators2.rs index 29c53afb28..db05f293d7 100644 --- a/exercises/standard_library_types/iterators2.rs +++ b/solutions/18_iterators/iterators2.rs @@ -1,35 +1,31 @@ -// iterators2.rs // In this exercise, you'll learn some of the unique advantages that iterators -// can offer. Follow the steps to complete the exercise. -// Execute `rustlings hint iterators2` or use the `hint` watch subcommand for a hint. +// can offer. -// I AM NOT DONE - -// Step 1. -// Complete the `capitalize_first` function. // "hello" -> "Hello" -pub fn capitalize_first(input: &str) -> String { - let mut c = input.chars(); - match c.next() { +fn capitalize_first(input: &str) -> String { + let mut chars = input.chars(); + match chars.next() { None => String::new(), - Some(first) => ???, + Some(first) => first.to_uppercase().to_string() + chars.as_str(), } } -// Step 2. // Apply the `capitalize_first` function to a slice of string slices. // Return a vector of strings. // ["hello", "world"] -> ["Hello", "World"] -pub fn capitalize_words_vector(words: &[&str]) -> Vec { - vec![] +fn capitalize_words_vector(words: &[&str]) -> Vec { + words.iter().map(|word| capitalize_first(word)).collect() } -// Step 3. -// Apply the `capitalize_first` function again to a slice of string slices. -// Return a single string. +// Apply the `capitalize_first` function again to a slice of string +// slices. Return a single string. // ["hello", " ", "world"] -> "Hello World" -pub fn capitalize_words_string(words: &[&str]) -> String { - String::new() +fn capitalize_words_string(words: &[&str]) -> String { + words.iter().map(|word| capitalize_first(word)).collect() +} + +fn main() { + // You can optionally experiment here. } #[cfg(test)] diff --git a/solutions/18_iterators/iterators3.rs b/solutions/18_iterators/iterators3.rs new file mode 100644 index 0000000000..1d5d67f29f --- /dev/null +++ b/solutions/18_iterators/iterators3.rs @@ -0,0 +1,88 @@ +#[derive(Debug, PartialEq, Eq)] +enum DivisionError { + // Example: 42 / 0 + DivideByZero, + // Only case for `i64`: `i64::MIN / -1` because the result is `i64::MAX + 1` + IntegerOverflow, + // Example: 5 / 2 = 2.5 + NotDivisible, +} + +fn divide(a: i64, b: i64) -> Result { + if b == 0 { + return Err(DivisionError::DivideByZero); + } + + if a == i64::MIN && b == -1 { + return Err(DivisionError::IntegerOverflow); + } + + if a % b != 0 { + return Err(DivisionError::NotDivisible); + } + + Ok(a / b) +} + +fn result_with_list() -> Result, DivisionError> { + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + let numbers = [27, 297, 38502, 81]; + let division_results = numbers.into_iter().map(|n| divide(n, 27)); + // Collects to the expected return type. Returns the first error in the + // division results (if one exists). + division_results.collect() +} + +fn list_of_results() -> Vec> { + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + let numbers = [27, 297, 38502, 81]; + let division_results = numbers.into_iter().map(|n| divide(n, 27)); + // Collects to the expected return type. + division_results.collect() +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_success() { + assert_eq!(divide(81, 9), Ok(9)); + assert_eq!(divide(81, -1), Ok(-81)); + assert_eq!(divide(i64::MIN, i64::MIN), Ok(1)); + } + + #[test] + fn test_divide_by_0() { + assert_eq!(divide(81, 0), Err(DivisionError::DivideByZero)); + } + + #[test] + fn test_integer_overflow() { + assert_eq!(divide(i64::MIN, -1), Err(DivisionError::IntegerOverflow)); + } + + #[test] + fn test_not_divisible() { + assert_eq!(divide(81, 6), Err(DivisionError::NotDivisible)); + } + + #[test] + fn test_divide_0_by_something() { + assert_eq!(divide(0, 81), Ok(0)); + } + + #[test] + fn test_result_with_list() { + assert_eq!(result_with_list().unwrap(), [1, 11, 1426, 3]); + } + + #[test] + fn test_list_of_results() { + assert_eq!(list_of_results(), [Ok(1), Ok(11), Ok(1426), Ok(3)]); + } +} diff --git a/solutions/18_iterators/iterators4.rs b/solutions/18_iterators/iterators4.rs new file mode 100644 index 0000000000..4168835afc --- /dev/null +++ b/solutions/18_iterators/iterators4.rs @@ -0,0 +1,72 @@ +// 3 possible solutions are presented. + +// With `for` loop and a mutable variable. +fn factorial_for(num: u64) -> u64 { + let mut result = 1; + + for x in 2..=num { + result *= x; + } + + result +} + +// Equivalent to `factorial_for` but shorter and without a `for` loop and +// mutable variables. +fn factorial_fold(num: u64) -> u64 { + // Case num==0: The iterator 2..=0 is empty + // -> The initial value of `fold` is returned which is 1. + // Case num==1: The iterator 2..=1 is also empty + // -> The initial value 1 is returned. + // Case num==2: The iterator 2..=2 contains one element + // -> The initial value 1 is multiplied by 2 and the result + // is returned. + // Case num==3: The iterator 2..=3 contains 2 elements + // -> 1 * 2 is calculated, then the result 2 is multiplied by + // the second element 3 so the result 6 is returned. + // And so on… + #[allow(clippy::unnecessary_fold)] + (2..=num).fold(1, |acc, x| acc * x) +} + +// Equivalent to `factorial_fold` but with a built-in method that is suggested +// by Clippy. +fn factorial_product(num: u64) -> u64 { + (2..=num).product() +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn factorial_of_0() { + assert_eq!(factorial_for(0), 1); + assert_eq!(factorial_fold(0), 1); + assert_eq!(factorial_product(0), 1); + } + + #[test] + fn factorial_of_1() { + assert_eq!(factorial_for(1), 1); + assert_eq!(factorial_fold(1), 1); + assert_eq!(factorial_product(1), 1); + } + #[test] + fn factorial_of_2() { + assert_eq!(factorial_for(2), 2); + assert_eq!(factorial_fold(2), 2); + assert_eq!(factorial_product(2), 2); + } + + #[test] + fn factorial_of_4() { + assert_eq!(factorial_for(4), 24); + assert_eq!(factorial_fold(4), 24); + assert_eq!(factorial_product(4), 24); + } +} diff --git a/solutions/18_iterators/iterators5.rs b/solutions/18_iterators/iterators5.rs new file mode 100644 index 0000000000..067a117b92 --- /dev/null +++ b/solutions/18_iterators/iterators5.rs @@ -0,0 +1,168 @@ +// Let's define a simple model to track Rustlings' exercise progress. Progress +// will be modelled using a hash map. The name of the exercise is the key and +// the progress is the value. Two counting functions were created to count the +// number of exercises with a given progress. Recreate this counting +// functionality using iterators. Try to not use imperative loops (for/while). + +use std::collections::HashMap; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Progress { + None, + Some, + Complete, +} + +fn count_for(map: &HashMap, value: Progress) -> usize { + let mut count = 0; + for val in map.values() { + if *val == value { + count += 1; + } + } + count +} + +fn count_iterator(map: &HashMap, value: Progress) -> usize { + // `map` is a hash map with `String` keys and `Progress` values. + // map = { "variables1": Complete, "from_str": None, … } + map.values().filter(|val| **val == value).count() +} + +fn count_collection_for(collection: &[HashMap], value: Progress) -> usize { + let mut count = 0; + for map in collection { + count += count_for(map, value); + } + count +} + +fn count_collection_iterator(collection: &[HashMap], value: Progress) -> usize { + // `collection` is a slice of hash maps. + // collection = [{ "variables1": Complete, "from_str": None, … }, + // { "variables2": Complete, … }, … ] + collection + .iter() + .map(|map| count_iterator(map, value)) + .sum() +} + +// Equivalent to `count_collection_iterator` and `count_iterator`, iterating as +// if the collection was a single container instead of a container of containers +// (and more accurately, a single iterator instead of an iterator of iterators). +fn count_collection_iterator_flat( + collection: &[HashMap], + value: Progress, +) -> usize { + // `collection` is a slice of hash maps. + // collection = [{ "variables1": Complete, "from_str": None, … }, + // { "variables2": Complete, … }, … ] + collection + .iter() + .flat_map(HashMap::values) // or just `.flatten()` when wanting the default iterator (`HashMap::iter`) + .filter(|val| **val == value) + .count() +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + use Progress::*; + + fn get_map() -> HashMap { + let mut map = HashMap::new(); + map.insert(String::from("variables1"), Complete); + map.insert(String::from("functions1"), Complete); + map.insert(String::from("hashmap1"), Complete); + map.insert(String::from("arc1"), Some); + map.insert(String::from("as_ref_mut"), None); + map.insert(String::from("from_str"), None); + + map + } + + fn get_vec_map() -> Vec> { + let map = get_map(); + + let mut other = HashMap::new(); + other.insert(String::from("variables2"), Complete); + other.insert(String::from("functions2"), Complete); + other.insert(String::from("if1"), Complete); + other.insert(String::from("from_into"), None); + other.insert(String::from("try_from_into"), None); + + vec![map, other] + } + + #[test] + fn count_complete() { + let map = get_map(); + assert_eq!(count_iterator(&map, Complete), 3); + } + + #[test] + fn count_some() { + let map = get_map(); + assert_eq!(count_iterator(&map, Some), 1); + } + + #[test] + fn count_none() { + let map = get_map(); + assert_eq!(count_iterator(&map, None), 2); + } + + #[test] + fn count_complete_equals_for() { + let map = get_map(); + let progress_states = [Complete, Some, None]; + for progress_state in progress_states { + assert_eq!( + count_for(&map, progress_state), + count_iterator(&map, progress_state), + ); + } + } + + #[test] + fn count_collection_complete() { + let collection = get_vec_map(); + assert_eq!(count_collection_iterator(&collection, Complete), 6); + assert_eq!(count_collection_iterator_flat(&collection, Complete), 6); + } + + #[test] + fn count_collection_some() { + let collection = get_vec_map(); + assert_eq!(count_collection_iterator(&collection, Some), 1); + assert_eq!(count_collection_iterator_flat(&collection, Some), 1); + } + + #[test] + fn count_collection_none() { + let collection = get_vec_map(); + assert_eq!(count_collection_iterator(&collection, None), 4); + assert_eq!(count_collection_iterator_flat(&collection, None), 4); + } + + #[test] + fn count_collection_equals_for() { + let collection = get_vec_map(); + let progress_states = [Complete, Some, None]; + + for progress_state in progress_states { + assert_eq!( + count_collection_for(&collection, progress_state), + count_collection_iterator(&collection, progress_state), + ); + assert_eq!( + count_collection_for(&collection, progress_state), + count_collection_iterator_flat(&collection, progress_state), + ); + } + } +} diff --git a/solutions/19_smart_pointers/arc1.rs b/solutions/19_smart_pointers/arc1.rs new file mode 100644 index 0000000000..bd76189fee --- /dev/null +++ b/solutions/19_smart_pointers/arc1.rs @@ -0,0 +1,45 @@ +// In this exercise, we are given a `Vec` of `u32` called `numbers` with values +// ranging from 0 to 99. We would like to use this set of numbers within 8 +// different threads simultaneously. Each thread is going to get the sum of +// every eighth value with an offset. +// +// The first thread (offset 0), will sum 0, 8, 16, … +// The second thread (offset 1), will sum 1, 9, 17, … +// The third thread (offset 2), will sum 2, 10, 18, … +// … +// The eighth thread (offset 7), will sum 7, 15, 23, … +// +// Each thread should own a reference-counting pointer to the vector of +// numbers. But `Rc` isn't thread-safe. Therefore, we need to use `Arc`. +// +// Don't get distracted by how threads are spawned and joined. We will practice +// that later in the exercises about threads. + +// Don't change the lines below. +#![forbid(unused_imports)] +use std::{sync::Arc, thread}; + +fn main() { + let numbers: Vec<_> = (0..100u32).collect(); + + let shared_numbers = Arc::new(numbers); + // ^^^^^^^^^^^^^^^^^ + + let mut join_handles = Vec::new(); + + for offset in 0..8 { + let child_numbers = Arc::clone(&shared_numbers); + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + let handle = thread::spawn(move || { + let sum: u32 = child_numbers.iter().filter(|&&n| n % 8 == offset).sum(); + println!("Sum of offset {offset} is {sum}"); + }); + + join_handles.push(handle); + } + + for handle in join_handles.into_iter() { + handle.join().unwrap(); + } +} diff --git a/solutions/19_smart_pointers/box1.rs b/solutions/19_smart_pointers/box1.rs new file mode 100644 index 0000000000..189cc5623a --- /dev/null +++ b/solutions/19_smart_pointers/box1.rs @@ -0,0 +1,47 @@ +// At compile time, Rust needs to know how much space a type takes up. This +// becomes problematic for recursive types, where a value can have as part of +// itself another value of the same type. To get around the issue, we can use a +// `Box` - a smart pointer used to store data on the heap, which also allows us +// to wrap a recursive type. +// +// The recursive type we're implementing in this exercise is the "cons list", a +// data structure frequently found in functional programming languages. Each +// item in a cons list contains two elements: The value of the current item and +// the next item. The last item is a value called `Nil`. + +#[derive(PartialEq, Debug)] +enum List { + Cons(i32, Box), + Nil, +} + +fn create_empty_list() -> List { + List::Nil +} + +fn create_non_empty_list() -> List { + List::Cons(42, Box::new(List::Nil)) +} + +fn main() { + println!("This is an empty cons list: {:?}", create_empty_list()); + println!( + "This is a non-empty cons list: {:?}", + create_non_empty_list(), + ); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_create_empty_list() { + assert_eq!(create_empty_list(), List::Nil); + } + + #[test] + fn test_create_non_empty_list() { + assert_ne!(create_empty_list(), create_non_empty_list()); + } +} diff --git a/solutions/19_smart_pointers/cow1.rs b/solutions/19_smart_pointers/cow1.rs new file mode 100644 index 0000000000..461143be86 --- /dev/null +++ b/solutions/19_smart_pointers/cow1.rs @@ -0,0 +1,69 @@ +// This exercise explores the `Cow` (Clone-On-Write) smart pointer. It can +// enclose and provide immutable access to borrowed data and clone the data +// lazily when mutation or ownership is required. The type is designed to work +// with general borrowed data via the `Borrow` trait. + +use std::borrow::Cow; + +fn abs_all(input: &mut Cow<[i32]>) { + for ind in 0..input.len() { + let value = input[ind]; + if value < 0 { + // Clones into a vector if not already owned. + input.to_mut()[ind] = -value; + } + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reference_mutation() { + // Clone occurs because `input` needs to be mutated. + let vec = vec![-1, 0, 1]; + let mut input = Cow::from(&vec); + abs_all(&mut input); + assert!(matches!(input, Cow::Owned(_))); + } + + #[test] + fn reference_no_mutation() { + // No clone occurs because `input` doesn't need to be mutated. + let vec = vec![0, 1, 2]; + let mut input = Cow::from(&vec); + abs_all(&mut input); + assert!(matches!(input, Cow::Borrowed(_))); + // ^^^^^^^^^^^^^^^^ + } + + #[test] + fn owned_no_mutation() { + // We can also pass `vec` without `&` so `Cow` owns it directly. In this + // case, no mutation occurs (all numbers are already absolute) and thus + // also no clone. But the result is still owned because it was never + // borrowed or mutated. + let vec = vec![0, 1, 2]; + let mut input = Cow::from(vec); + abs_all(&mut input); + assert!(matches!(input, Cow::Owned(_))); + // ^^^^^^^^^^^^^ + } + + #[test] + fn owned_mutation() { + // Of course this is also the case if a mutation does occur (not all + // numbers are absolute). In this case, the call to `to_mut()` in the + // `abs_all` function returns a reference to the same data as before. + let vec = vec![-1, 0, 1]; + let mut input = Cow::from(vec); + abs_all(&mut input); + assert!(matches!(input, Cow::Owned(_))); + // ^^^^^^^^^^^^^ + } +} diff --git a/solutions/19_smart_pointers/rc1.rs b/solutions/19_smart_pointers/rc1.rs new file mode 100644 index 0000000000..edf40ebe11 --- /dev/null +++ b/solutions/19_smart_pointers/rc1.rs @@ -0,0 +1,102 @@ +// In this exercise, we want to express the concept of multiple owners via the +// `Rc` type. This is a model of our solar system - there is a `Sun` type and +// multiple `Planet`s. The planets take ownership of the sun, indicating that +// they revolve around the sun. + +use std::rc::Rc; + +#[derive(Debug)] +struct Sun; + +#[derive(Debug)] +enum Planet { + Mercury(Rc), + Venus(Rc), + Earth(Rc), + Mars(Rc), + Jupiter(Rc), + Saturn(Rc), + Uranus(Rc), + Neptune(Rc), +} + +impl Planet { + fn details(&self) { + println!("Hi from {self:?}!"); + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rc1() { + let sun = Rc::new(Sun); + println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference + + let mercury = Planet::Mercury(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 2 references + mercury.details(); + + let venus = Planet::Venus(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 3 references + venus.details(); + + let earth = Planet::Earth(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 4 references + earth.details(); + + let mars = Planet::Mars(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 5 references + mars.details(); + + let jupiter = Planet::Jupiter(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 6 references + jupiter.details(); + + let saturn = Planet::Saturn(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 7 references + saturn.details(); + + let uranus = Planet::Uranus(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 8 references + uranus.details(); + + let neptune = Planet::Neptune(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 9 references + neptune.details(); + + assert_eq!(Rc::strong_count(&sun), 9); + + drop(neptune); + println!("reference count = {}", Rc::strong_count(&sun)); // 8 references + + drop(uranus); + println!("reference count = {}", Rc::strong_count(&sun)); // 7 references + + drop(saturn); + println!("reference count = {}", Rc::strong_count(&sun)); // 6 references + + drop(jupiter); + println!("reference count = {}", Rc::strong_count(&sun)); // 5 references + + drop(mars); + println!("reference count = {}", Rc::strong_count(&sun)); // 4 references + + drop(earth); + println!("reference count = {}", Rc::strong_count(&sun)); // 3 references + + drop(venus); + println!("reference count = {}", Rc::strong_count(&sun)); // 2 references + + drop(mercury); + println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference + + assert_eq!(Rc::strong_count(&sun), 1); + } +} diff --git a/solutions/20_threads/threads1.rs b/solutions/20_threads/threads1.rs new file mode 100644 index 0000000000..1fc5bc9c06 --- /dev/null +++ b/solutions/20_threads/threads1.rs @@ -0,0 +1,37 @@ +// This program spawns multiple threads that each runs for at least 250ms, and +// each thread returns how much time it took to complete. The program should +// wait until all the spawned threads have finished and should collect their +// return values into a vector. + +use std::{ + thread, + time::{Duration, Instant}, +}; + +fn main() { + let mut handles = Vec::new(); + for i in 0..10 { + let handle = thread::spawn(move || { + let start = Instant::now(); + thread::sleep(Duration::from_millis(250)); + println!("Thread {i} done"); + start.elapsed().as_millis() + }); + handles.push(handle); + } + + let mut results = Vec::new(); + for handle in handles { + // Collect the results of all threads into the `results` vector. + results.push(handle.join().unwrap()); + } + + if results.len() != 10 { + panic!("Oh no! Some thread isn't done yet!"); + } + + println!(); + for (i, result) in results.into_iter().enumerate() { + println!("Thread {i} took {result}ms"); + } +} diff --git a/solutions/20_threads/threads2.rs b/solutions/20_threads/threads2.rs new file mode 100644 index 0000000000..bc268d63f6 --- /dev/null +++ b/solutions/20_threads/threads2.rs @@ -0,0 +1,41 @@ +// Building on the last exercise, we want all of the threads to complete their +// work. But this time, the spawned threads need to be in charge of updating a +// shared value: `JobStatus.jobs_done` + +use std::{ + sync::{Arc, Mutex}, + thread, + time::Duration, +}; + +struct JobStatus { + jobs_done: u32, +} + +fn main() { + // `Arc` isn't enough if you want a **mutable** shared state. + // We need to wrap the value with a `Mutex`. + let status = Arc::new(Mutex::new(JobStatus { jobs_done: 0 })); + // ^^^^^^^^^^^ ^ + + let mut handles = Vec::new(); + for _ in 0..10 { + let status_shared = Arc::clone(&status); + let handle = thread::spawn(move || { + thread::sleep(Duration::from_millis(250)); + + // Lock before you update a shared value. + status_shared.lock().unwrap().jobs_done += 1; + // ^^^^^^^^^^^^^^^^ + }); + handles.push(handle); + } + + // Waiting for all jobs to complete. + for handle in handles { + handle.join().unwrap(); + } + + println!("Jobs done: {}", status.lock().unwrap().jobs_done); + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +} diff --git a/solutions/20_threads/threads3.rs b/solutions/20_threads/threads3.rs new file mode 100644 index 0000000000..7ceefea016 --- /dev/null +++ b/solutions/20_threads/threads3.rs @@ -0,0 +1,62 @@ +use std::{sync::mpsc, thread, time::Duration}; + +struct Queue { + first_half: Vec, + second_half: Vec, +} + +impl Queue { + fn new() -> Self { + Self { + first_half: vec![1, 2, 3, 4, 5], + second_half: vec![6, 7, 8, 9, 10], + } + } +} + +fn send_tx(q: Queue, tx: mpsc::Sender) { + // Clone the sender `tx` first. + let tx_clone = tx.clone(); + thread::spawn(move || { + for val in q.first_half { + println!("Sending {val:?}"); + // Then use the clone in the first thread. This means that + // `tx_clone` is moved to the first thread and `tx` to the second. + tx_clone.send(val).unwrap(); + thread::sleep(Duration::from_millis(250)); + } + }); + + thread::spawn(move || { + for val in q.second_half { + println!("Sending {val:?}"); + tx.send(val).unwrap(); + thread::sleep(Duration::from_millis(250)); + } + }); +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn threads3() { + let (tx, rx) = mpsc::channel(); + let queue = Queue::new(); + + send_tx(queue, tx); + + let mut received = Vec::with_capacity(10); + for value in rx { + received.push(value); + } + + received.sort(); + assert_eq!(received, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); + } +} diff --git a/solutions/21_macros/macros1.rs b/solutions/21_macros/macros1.rs new file mode 100644 index 0000000000..1b861564be --- /dev/null +++ b/solutions/21_macros/macros1.rs @@ -0,0 +1,10 @@ +macro_rules! my_macro { + () => { + println!("Check out my macro!"); + }; +} + +fn main() { + my_macro!(); + // ^ +} diff --git a/solutions/21_macros/macros2.rs b/solutions/21_macros/macros2.rs new file mode 100644 index 0000000000..b6fd5d2c56 --- /dev/null +++ b/solutions/21_macros/macros2.rs @@ -0,0 +1,10 @@ +// Moved the macro definition to be before its call. +macro_rules! my_macro { + () => { + println!("Check out my macro!"); + }; +} + +fn main() { + my_macro!(); +} diff --git a/solutions/21_macros/macros3.rs b/solutions/21_macros/macros3.rs new file mode 100644 index 0000000000..9d574f894a --- /dev/null +++ b/solutions/21_macros/macros3.rs @@ -0,0 +1,13 @@ +// Added the `macro_use` attribute. +#[macro_use] +mod macros { + macro_rules! my_macro { + () => { + println!("Check out my macro!"); + }; + } +} + +fn main() { + my_macro!(); +} diff --git a/solutions/21_macros/macros4.rs b/solutions/21_macros/macros4.rs new file mode 100644 index 0000000000..41bcad166a --- /dev/null +++ b/solutions/21_macros/macros4.rs @@ -0,0 +1,15 @@ +// Added semicolons to separate the macro arms. +#[rustfmt::skip] +macro_rules! my_macro { + () => { + println!("Check out my macro!"); + }; + ($val:expr) => { + println!("Look at this other macro: {}", $val); + }; +} + +fn main() { + my_macro!(); + my_macro!(7777); +} diff --git a/solutions/22_clippy/clippy1.rs b/solutions/22_clippy/clippy1.rs new file mode 100644 index 0000000000..b9d1ec1729 --- /dev/null +++ b/solutions/22_clippy/clippy1.rs @@ -0,0 +1,17 @@ +// The Clippy tool is a collection of lints to analyze your code so you can +// catch common mistakes and improve your Rust code. +// +// For these exercises, the code will fail to compile when there are Clippy +// warnings. Check Clippy's suggestions from the output to solve the exercise. + +use std::f32::consts::PI; + +fn main() { + // Use the more accurate `PI` constant. + let pi = PI; + let radius: f32 = 5.0; + + let area = pi * radius.powi(2); + + println!("The area of a circle with radius {radius:.2} is {area:.5}"); +} diff --git a/solutions/22_clippy/clippy2.rs b/solutions/22_clippy/clippy2.rs new file mode 100644 index 0000000000..7f6356285e --- /dev/null +++ b/solutions/22_clippy/clippy2.rs @@ -0,0 +1,10 @@ +fn main() { + let mut res = 42; + let option = Some(12); + // Use `if-let` instead of iteration. + if let Some(x) = option { + res += x; + } + + println!("{res}"); +} diff --git a/solutions/22_clippy/clippy3.rs b/solutions/22_clippy/clippy3.rs new file mode 100644 index 0000000000..8fc267041a --- /dev/null +++ b/solutions/22_clippy/clippy3.rs @@ -0,0 +1,31 @@ +use std::mem; + +#[allow(unused_variables, unused_assignments)] +fn main() { + let my_option: Option<&str> = None; + // `unwrap` of an `Option` after checking if it is `None` will panic. + // Use `if-let` instead. + if let Some(value) = my_option { + println!("{value}"); + } + + // A comma was missing. + #[rustfmt::skip] + let my_arr = &[ + -1, -2, -3, + -4, -5, -6, + ]; + println!("My array! Here it is: {my_arr:?}"); + + let mut my_vec = vec![1, 2, 3, 4, 5]; + // `resize` mutates a vector instead of returning a new one. + // `resize(0, …)` clears a vector, so it is better to use `clear`. + my_vec.clear(); + println!("This Vec is empty, see? {my_vec:?}"); + + let mut value_a = 45; + let mut value_b = 66; + // Use `mem::swap` to correctly swap two values. + mem::swap(&mut value_a, &mut value_b); + println!("value a: {value_a}; value b: {value_b}"); +} diff --git a/solutions/23_conversions/as_ref_mut.rs b/solutions/23_conversions/as_ref_mut.rs new file mode 100644 index 0000000000..a5d2d4fa57 --- /dev/null +++ b/solutions/23_conversions/as_ref_mut.rs @@ -0,0 +1,60 @@ +// AsRef and AsMut allow for cheap reference-to-reference conversions. Read more +// about them at https://doc.rust-lang.org/std/convert/trait.AsRef.html and +// https://doc.rust-lang.org/std/convert/trait.AsMut.html, respectively. + +// Obtain the number of bytes (not characters) in the given argument +// (`.len()` returns the number of bytes in a string). +fn byte_counter>(arg: T) -> usize { + arg.as_ref().len() +} + +// Obtain the number of characters (not bytes) in the given argument. +fn char_counter>(arg: T) -> usize { + arg.as_ref().chars().count() +} + +// Squares a number using `as_mut()`. +fn num_sq>(arg: &mut T) { + let arg = arg.as_mut(); + *arg *= *arg; +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn different_counts() { + let s = "Café au lait"; + assert_ne!(char_counter(s), byte_counter(s)); + } + + #[test] + fn same_counts() { + let s = "Cafe au lait"; + assert_eq!(char_counter(s), byte_counter(s)); + } + + #[test] + fn different_counts_using_string() { + let s = String::from("Café au lait"); + assert_ne!(char_counter(s.clone()), byte_counter(s)); + } + + #[test] + fn same_counts_using_string() { + let s = String::from("Cafe au lait"); + assert_eq!(char_counter(s.clone()), byte_counter(s)); + } + + #[test] + fn mut_box() { + let mut num: Box = Box::new(3); + num_sq(&mut num); + assert_eq!(*num, 9); + } +} diff --git a/solutions/23_conversions/from_into.rs b/solutions/23_conversions/from_into.rs new file mode 100644 index 0000000000..cec23cb4be --- /dev/null +++ b/solutions/23_conversions/from_into.rs @@ -0,0 +1,136 @@ +// The `From` trait is used for value-to-value conversions. If `From` is +// implemented, an implementation of `Into` is automatically provided. +// You can read more about it in the documentation: +// https://doc.rust-lang.org/std/convert/trait.From.html + +#[derive(Debug)] +struct Person { + name: String, + age: u8, +} + +// We implement the Default trait to use it as a fallback when the provided +// string is not convertible into a `Person` object. +impl Default for Person { + fn default() -> Self { + Self { + name: String::from("John"), + age: 30, + } + } +} + +impl From<&str> for Person { + fn from(s: &str) -> Self { + let mut split = s.split(','); + let (Some(name), Some(age), None) = (split.next(), split.next(), split.next()) else { + // ^^^^ there should be no third element + return Self::default(); + }; + + if name.is_empty() { + return Self::default(); + } + + let Ok(age) = age.parse() else { + return Self::default(); + }; + + Self { + name: name.into(), + age, + } + } +} + +fn main() { + // Use the `from` function. + let p1 = Person::from("Mark,20"); + println!("{p1:?}"); + + // Since `From` is implemented for Person, we are able to use `Into`. + let p2: Person = "Gerald,70".into(); + println!("{p2:?}"); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_default() { + let dp = Person::default(); + assert_eq!(dp.name, "John"); + assert_eq!(dp.age, 30); + } + + #[test] + fn test_bad_convert() { + let p = Person::from(""); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 30); + } + + #[test] + fn test_good_convert() { + let p = Person::from("Mark,20"); + assert_eq!(p.name, "Mark"); + assert_eq!(p.age, 20); + } + + #[test] + fn test_bad_age() { + let p = Person::from("Mark,twenty"); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 30); + } + + #[test] + fn test_missing_comma_and_age() { + let p: Person = Person::from("Mark"); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 30); + } + + #[test] + fn test_missing_age() { + let p: Person = Person::from("Mark,"); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 30); + } + + #[test] + fn test_missing_name() { + let p: Person = Person::from(",1"); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 30); + } + + #[test] + fn test_missing_name_and_age() { + let p: Person = Person::from(","); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 30); + } + + #[test] + fn test_missing_name_and_invalid_age() { + let p: Person = Person::from(",one"); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 30); + } + + #[test] + fn test_trailing_comma() { + let p: Person = Person::from("Mike,32,"); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 30); + } + + #[test] + fn test_trailing_comma_and_some_string() { + let p: Person = Person::from("Mike,32,dog"); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 30); + } +} diff --git a/solutions/23_conversions/from_str.rs b/solutions/23_conversions/from_str.rs new file mode 100644 index 0000000000..005b50125a --- /dev/null +++ b/solutions/23_conversions/from_str.rs @@ -0,0 +1,117 @@ +// This is similar to the previous `from_into` exercise. But this time, we'll +// implement `FromStr` and return errors instead of falling back to a default +// value. Additionally, upon implementing `FromStr`, you can use the `parse` +// method on strings to generate an object of the implementor type. You can read +// more about it in the documentation: +// https://doc.rust-lang.org/std/str/trait.FromStr.html + +use std::num::ParseIntError; +use std::str::FromStr; + +#[derive(Debug, PartialEq)] +struct Person { + name: String, + age: u8, +} + +// We will use this error type for the `FromStr` implementation. +#[derive(Debug, PartialEq)] +enum ParsePersonError { + // Incorrect number of fields + BadLen, + // Empty name field + NoName, + // Wrapped error from parse::() + ParseInt(ParseIntError), +} + +impl FromStr for Person { + type Err = ParsePersonError; + + fn from_str(s: &str) -> Result { + let mut split = s.split(','); + let (Some(name), Some(age), None) = (split.next(), split.next(), split.next()) else { + // ^^^^ there should be no third element + return Err(ParsePersonError::BadLen); + }; + + if name.is_empty() { + return Err(ParsePersonError::NoName); + } + + let age = age.parse().map_err(ParsePersonError::ParseInt)?; + + Ok(Self { + name: name.into(), + age, + }) + } +} + +fn main() { + let p = "Mark,20".parse::(); + println!("{p:?}"); +} + +#[cfg(test)] +mod tests { + use super::*; + use ParsePersonError::*; + + #[test] + fn empty_input() { + assert_eq!("".parse::(), Err(BadLen)); + } + + #[test] + fn good_input() { + let p = "John,32".parse::(); + assert!(p.is_ok()); + let p = p.unwrap(); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 32); + } + + #[test] + fn missing_age() { + assert!(matches!("John,".parse::(), Err(ParseInt(_)))); + } + + #[test] + fn invalid_age() { + assert!(matches!("John,twenty".parse::(), Err(ParseInt(_)))); + } + + #[test] + fn missing_comma_and_age() { + assert_eq!("John".parse::(), Err(BadLen)); + } + + #[test] + fn missing_name() { + assert_eq!(",1".parse::(), Err(NoName)); + } + + #[test] + fn missing_name_and_age() { + assert!(matches!(",".parse::(), Err(NoName | ParseInt(_)))); + } + + #[test] + fn missing_name_and_invalid_age() { + assert!(matches!( + ",one".parse::(), + Err(NoName | ParseInt(_)), + )); + } + + #[test] + fn trailing_comma() { + assert_eq!("John,32,".parse::(), Err(BadLen)); + } + + #[test] + fn trailing_comma_and_some_string() { + assert_eq!("John,32,man".parse::(), Err(BadLen)); + } +} diff --git a/exercises/conversions/try_from_into.rs b/solutions/23_conversions/try_from_into.rs similarity index 53% rename from exercises/conversions/try_from_into.rs rename to solutions/23_conversions/try_from_into.rs index fa98bc90da..ee802eb06e 100644 --- a/exercises/conversions/try_from_into.rs +++ b/solutions/23_conversions/try_from_into.rs @@ -1,10 +1,10 @@ -// try_from_into.rs -// TryFrom is a simple and safe type conversion that may fail in a controlled way under some circumstances. -// Basically, this is the same as From. The main difference is that this should return a Result type -// instead of the target type itself. -// You can read more about it at https://doc.rust-lang.org/std/convert/trait.TryFrom.html -// Execute `rustlings hint try_from_into` or use the `hint` watch subcommand for a hint. +// `TryFrom` is a simple and safe type conversion that may fail in a controlled +// way under some circumstances. Basically, this is the same as `From`. The main +// difference is that this should return a `Result` type instead of the target +// type itself. You can read more about it in the documentation: +// https://doc.rust-lang.org/std/convert/trait.TryFrom.html +#![allow(clippy::useless_vec)] use std::convert::{TryFrom, TryInto}; #[derive(Debug, PartialEq)] @@ -14,7 +14,7 @@ struct Color { blue: u8, } -// We will use this error type for these `TryFrom` conversions. +// We will use this error type for the `TryFrom` conversions. #[derive(Debug, PartialEq)] enum IntoColorError { // Incorrect length of slice @@ -23,81 +23,83 @@ enum IntoColorError { IntConversion, } -// I AM NOT DONE - -// Your task is to complete this implementation -// and return an Ok result of inner type Color. -// You need to create an implementation for a tuple of three integers, -// an array of three integers, and a slice of integers. -// -// Note that the implementation for tuple and array will be checked at compile time, -// but the slice implementation needs to check the slice length! -// Also note that correct RGB color values must be integers in the 0..=255 range. - -// Tuple implementation impl TryFrom<(i16, i16, i16)> for Color { type Error = IntoColorError; + fn try_from(tuple: (i16, i16, i16)) -> Result { + let (Ok(red), Ok(green), Ok(blue)) = ( + u8::try_from(tuple.0), + u8::try_from(tuple.1), + u8::try_from(tuple.2), + ) else { + return Err(IntoColorError::IntConversion); + }; + + Ok(Self { red, green, blue }) } } -// Array implementation impl TryFrom<[i16; 3]> for Color { type Error = IntoColorError; + fn try_from(arr: [i16; 3]) -> Result { + // Reuse the implementation for a tuple. + Self::try_from((arr[0], arr[1], arr[2])) } } -// Slice implementation impl TryFrom<&[i16]> for Color { type Error = IntoColorError; + fn try_from(slice: &[i16]) -> Result { + // Check the length. + if slice.len() != 3 { + return Err(IntoColorError::BadLen); + } + + // Reuse the implementation for a tuple. + Self::try_from((slice[0], slice[1], slice[2])) } } fn main() { - // Use the `try_from` function + // Using the `try_from` function. let c1 = Color::try_from((183, 65, 14)); - println!("{:?}", c1); + println!("{c1:?}"); - // Since TryFrom is implemented for Color, we should be able to use TryInto + // Since `TryFrom` is implemented for `Color`, we can use `TryInto`. let c2: Result = [183, 65, 14].try_into(); - println!("{:?}", c2); + println!("{c2:?}"); let v = vec![183, 65, 14]; - // With slice we should use `try_from` function + // With slice we should use the `try_from` function let c3 = Color::try_from(&v[..]); - println!("{:?}", c3); - // or take slice within round brackets and use TryInto + println!("{c3:?}"); + // or put the slice within round brackets and use `try_into`. let c4: Result = (&v[..]).try_into(); - println!("{:?}", c4); + println!("{c4:?}"); } #[cfg(test)] mod tests { use super::*; + use IntoColorError::*; #[test] fn test_tuple_out_of_range_positive() { - assert_eq!( - Color::try_from((256, 1000, 10000)), - Err(IntoColorError::IntConversion) - ); + assert_eq!(Color::try_from((256, 1000, 10000)), Err(IntConversion)); } + #[test] fn test_tuple_out_of_range_negative() { - assert_eq!( - Color::try_from((-1, -10, -256)), - Err(IntoColorError::IntConversion) - ); + assert_eq!(Color::try_from((-1, -10, -256)), Err(IntConversion)); } + #[test] fn test_tuple_sum() { - assert_eq!( - Color::try_from((-1, 255, 255)), - Err(IntoColorError::IntConversion) - ); + assert_eq!(Color::try_from((-1, 255, 255)), Err(IntConversion)); } + #[test] fn test_tuple_correct() { let c: Result = (183, 65, 14).try_into(); @@ -107,25 +109,29 @@ mod tests { Color { red: 183, green: 65, - blue: 14 + blue: 14, } ); } + #[test] fn test_array_out_of_range_positive() { let c: Result = [1000, 10000, 256].try_into(); - assert_eq!(c, Err(IntoColorError::IntConversion)); + assert_eq!(c, Err(IntConversion)); } + #[test] fn test_array_out_of_range_negative() { let c: Result = [-10, -256, -1].try_into(); - assert_eq!(c, Err(IntoColorError::IntConversion)); + assert_eq!(c, Err(IntConversion)); } + #[test] fn test_array_sum() { let c: Result = [-1, 255, 255].try_into(); - assert_eq!(c, Err(IntoColorError::IntConversion)); + assert_eq!(c, Err(IntConversion)); } + #[test] fn test_array_correct() { let c: Result = [183, 65, 14].try_into(); @@ -139,30 +145,25 @@ mod tests { } ); } + #[test] fn test_slice_out_of_range_positive() { let arr = [10000, 256, 1000]; - assert_eq!( - Color::try_from(&arr[..]), - Err(IntoColorError::IntConversion) - ); + assert_eq!(Color::try_from(&arr[..]), Err(IntConversion)); } + #[test] fn test_slice_out_of_range_negative() { let arr = [-256, -1, -10]; - assert_eq!( - Color::try_from(&arr[..]), - Err(IntoColorError::IntConversion) - ); + assert_eq!(Color::try_from(&arr[..]), Err(IntConversion)); } + #[test] fn test_slice_sum() { let arr = [-1, 255, 255]; - assert_eq!( - Color::try_from(&arr[..]), - Err(IntoColorError::IntConversion) - ); + assert_eq!(Color::try_from(&arr[..]), Err(IntConversion)); } + #[test] fn test_slice_correct() { let v = vec![183, 65, 14]; @@ -173,18 +174,20 @@ mod tests { Color { red: 183, green: 65, - blue: 14 + blue: 14, } ); } + #[test] fn test_slice_excess_length() { let v = vec![0, 0, 0, 0]; - assert_eq!(Color::try_from(&v[..]), Err(IntoColorError::BadLen)); + assert_eq!(Color::try_from(&v[..]), Err(BadLen)); } + #[test] fn test_slice_insufficient_length() { let v = vec![0, 0]; - assert_eq!(Color::try_from(&v[..]), Err(IntoColorError::BadLen)); + assert_eq!(Color::try_from(&v[..]), Err(BadLen)); } } diff --git a/solutions/23_conversions/using_as.rs b/solutions/23_conversions/using_as.rs new file mode 100644 index 0000000000..14b92ebf05 --- /dev/null +++ b/solutions/23_conversions/using_as.rs @@ -0,0 +1,24 @@ +// Type casting in Rust is done via the usage of the `as` operator. +// Note that the `as` operator is not only used when type casting. It also helps +// with renaming imports. + +fn average(values: &[f64]) -> f64 { + let total = values.iter().sum::(); + total / values.len() as f64 + // ^^^^^^ +} + +fn main() { + let values = [3.5, 0.3, 13.0, 11.7]; + println!("{}", average(&values)); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn returns_proper_type_and_value() { + assert_eq!(average(&[3.5, 0.3, 13.0, 11.7]), 7.125); + } +} diff --git a/solutions/README.md b/solutions/README.md new file mode 100644 index 0000000000..5b5176b636 --- /dev/null +++ b/solutions/README.md @@ -0,0 +1,6 @@ +# Official Rustlings solutions + +Before you finish an exercise, its solution file will only contain an empty `main` function. +The content of this file will be automatically replaced by the actual solution once you finish the exercise. + +Note that these solutions are often only _one possibility_ to solve an exercise. diff --git a/solutions/quizzes/quiz1.rs b/solutions/quizzes/quiz1.rs new file mode 100644 index 0000000000..5503c8c742 --- /dev/null +++ b/solutions/quizzes/quiz1.rs @@ -0,0 +1,30 @@ +// Mary is buying apples. The price of an apple is calculated as follows: +// - An apple costs 2 rustbucks. +// - However, if Mary buys more than 40 apples, the price of each apple in the +// entire order is reduced to only 1 rustbuck! + +fn calculate_price_of_apples(n_apples: u64) -> u64 { + if n_apples > 40 { + n_apples + } else { + 2 * n_apples + } +} + +fn main() { + // You can optionally experiment here. +} + +// Don't change the tests! +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn verify_test() { + assert_eq!(calculate_price_of_apples(35), 70); + assert_eq!(calculate_price_of_apples(40), 80); + assert_eq!(calculate_price_of_apples(41), 41); + assert_eq!(calculate_price_of_apples(65), 65); + } +} diff --git a/solutions/quizzes/quiz2.rs b/solutions/quizzes/quiz2.rs new file mode 100644 index 0000000000..8b073b1867 --- /dev/null +++ b/solutions/quizzes/quiz2.rs @@ -0,0 +1,90 @@ +// Let's build a little machine in the form of a function. As input, we're going +// to give a list of strings and commands. These commands determine what action +// is going to be applied to the string. It can either be: +// - Uppercase the string +// - Trim the string +// - Append "bar" to the string a specified amount of times +// +// The exact form of this will be: +// - The input is going to be a vector of 2-length tuples, +// the first element is the string, the second one is the command. +// - The output element is going to be a vector of strings. + +enum Command { + Uppercase, + Trim, + Append(usize), +} + +mod my_module { + use super::Command; + + // The solution with a loop. Check out `transformer_iter` for a version + // with iterators. + pub fn transformer(input: Vec<(String, Command)>) -> Vec { + let mut output = Vec::new(); + + for (string, command) in input { + // Create the new string. + let new_string = match command { + Command::Uppercase => string.to_uppercase(), + Command::Trim => string.trim().to_string(), + Command::Append(n) => string + &"bar".repeat(n), + }; + + // Push the new string to the output vector. + output.push(new_string); + } + + output + } + + // Equivalent to `transform` but uses an iterator instead of a loop for + // comparison. Don't worry, we will practice iterators later ;) + pub fn transformer_iter(input: Vec<(String, Command)>) -> Vec { + input + .into_iter() + .map(|(string, command)| match command { + Command::Uppercase => string.to_uppercase(), + Command::Trim => string.trim().to_string(), + Command::Append(n) => string + &"bar".repeat(n), + }) + .collect() + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + // Import `transformer`. + use super::my_module::transformer; + + use super::Command; + use super::my_module::transformer_iter; + + #[test] + fn it_works() { + for transformer in [transformer, transformer_iter] { + let input = vec![ + ("hello".to_string(), Command::Uppercase), + (" all roads lead to rome! ".to_string(), Command::Trim), + ("foo".to_string(), Command::Append(1)), + ("bar".to_string(), Command::Append(5)), + ]; + let output = transformer(input); + + assert_eq!( + output, + [ + "HELLO", + "all roads lead to rome!", + "foobar", + "barbarbarbarbarbar", + ] + ); + } + } +} diff --git a/solutions/quizzes/quiz3.rs b/solutions/quizzes/quiz3.rs new file mode 100644 index 0000000000..7b9127820d --- /dev/null +++ b/solutions/quizzes/quiz3.rs @@ -0,0 +1,65 @@ +// An imaginary magical school has a new report card generation system written +// in Rust! Currently, the system only supports creating report cards where the +// student's grade is represented numerically (e.g. 1.0 -> 5.5). However, the +// school also issues alphabetical grades (A+ -> F-) and needs to be able to +// print both types of report card! +// +// Make the necessary code changes in the struct `ReportCard` and the impl +// block to support alphabetical report cards in addition to numerical ones. + +use std::fmt::Display; + +// Make the struct generic over `T`. +struct ReportCard { + // ^^^ + grade: T, + // ^ + student_name: String, + student_age: u8, +} + +// To be able to print the grade, it has to implement the `Display` trait. +impl ReportCard { + // ^^^^^^^ require that `T` implements `Display`. + fn print(&self) -> String { + format!( + "{} ({}) - achieved a grade of {}", + &self.student_name, &self.student_age, &self.grade, + ) + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn generate_numeric_report_card() { + let report_card = ReportCard { + grade: 2.1, + student_name: "Tom Wriggle".to_string(), + student_age: 12, + }; + assert_eq!( + report_card.print(), + "Tom Wriggle (12) - achieved a grade of 2.1", + ); + } + + #[test] + fn generate_alphabetic_report_card() { + let report_card = ReportCard { + grade: "A+", + student_name: "Gary Plotter".to_string(), + student_age: 11, + }; + assert_eq!( + report_card.print(), + "Gary Plotter (11) - achieved a grade of A+", + ); + } +} diff --git a/src/app_state.rs b/src/app_state.rs new file mode 100644 index 0000000000..d654d0425d --- /dev/null +++ b/src/app_state.rs @@ -0,0 +1,650 @@ +use anyhow::{Context, Error, Result, bail}; +use crossterm::{QueueableCommand, cursor, terminal}; +use std::{ + collections::HashSet, + env, + fs::{File, OpenOptions}, + io::{Read, Seek, StdoutLock, Write}, + path::{MAIN_SEPARATOR_STR, Path}, + process::{Command, Stdio}, + sync::{ + atomic::{AtomicUsize, Ordering::Relaxed}, + mpsc, + }, + thread, +}; + +use crate::{ + clear_terminal, + cmd::CmdRunner, + embedded::EMBEDDED_FILES, + exercise::{Exercise, RunnableExercise}, + info_file::ExerciseInfo, + term::{self, CheckProgressVisualizer}, +}; + +const STATE_FILE_NAME: &str = ".rustlings-state.txt"; +const DEFAULT_CHECK_PARALLELISM: usize = 8; + +#[must_use] +pub enum ExercisesProgress { + // All exercises are done. + AllDone, + // A new exercise is now pending. + NewPending, + // The current exercise is still pending. + CurrentPending, +} + +pub enum StateFileStatus { + Read, + NotRead, +} + +#[derive(Clone, Copy)] +pub enum CheckProgress { + None, + Checking, + Done, + Pending, +} + +pub struct AppState { + current_exercise_ind: usize, + exercises: Vec, + // Caches the number of done exercises to avoid iterating over all exercises every time. + n_done: u16, + final_message: String, + state_file: File, + // Preallocated buffer for reading and writing the state file. + file_buf: Vec, + official_exercises: bool, + cmd_runner: CmdRunner, + emit_file_links: bool, +} + +impl AppState { + pub fn new( + exercise_infos: Vec, + final_message: String, + ) -> Result<(Self, StateFileStatus)> { + let cmd_runner = CmdRunner::build()?; + let mut state_file = OpenOptions::new() + .create(true) + .read(true) + .write(true) + .truncate(false) + .open(STATE_FILE_NAME) + .with_context(|| { + format!("Failed to open or create the state file {STATE_FILE_NAME}") + })?; + + let dir_canonical_path = term::canonicalize("exercises"); + let mut exercises = exercise_infos + .into_iter() + .map(|exercise_info| { + // Leaking to be able to borrow in the watch mode `Table`. + // Leaking is not a problem because the `AppState` instance lives until + // the end of the program. + let path = exercise_info.path().leak(); + let name = exercise_info.name.leak(); + let dir = exercise_info.dir.map(|dir| &*dir.leak()); + let hint = exercise_info.hint.leak().trim_ascii(); + + let canonical_path = dir_canonical_path.as_deref().map(|dir_canonical_path| { + let mut canonical_path; + if let Some(dir) = dir { + canonical_path = String::with_capacity( + 2 + dir_canonical_path.len() + dir.len() + name.len(), + ); + canonical_path.push_str(dir_canonical_path); + canonical_path.push_str(MAIN_SEPARATOR_STR); + canonical_path.push_str(dir); + } else { + canonical_path = + String::with_capacity(1 + dir_canonical_path.len() + name.len()); + canonical_path.push_str(dir_canonical_path); + } + + canonical_path.push_str(MAIN_SEPARATOR_STR); + canonical_path.push_str(name); + canonical_path.push_str(".rs"); + canonical_path + }); + + Exercise { + dir, + name, + path, + canonical_path, + test: exercise_info.test, + strict_clippy: exercise_info.strict_clippy, + hint, + // Updated below. + done: false, + } + }) + .collect::>(); + + let mut current_exercise_ind = 0; + let mut n_done = 0; + let mut file_buf = Vec::with_capacity(2048); + let state_file_status = 'block: { + if state_file.read_to_end(&mut file_buf).is_err() { + break 'block StateFileStatus::NotRead; + } + + // See `Self::write` for more information about the file format. + let mut lines = file_buf.split(|c| *c == b'\n').skip(2); + + let Some(current_exercise_name) = lines.next() else { + break 'block StateFileStatus::NotRead; + }; + + if current_exercise_name.is_empty() || lines.next().is_none() { + break 'block StateFileStatus::NotRead; + } + + let mut done_exercises = HashSet::with_capacity(exercises.len()); + + for done_exercise_name in lines { + if done_exercise_name.is_empty() { + break; + } + done_exercises.insert(done_exercise_name); + } + + for (ind, exercise) in exercises.iter_mut().enumerate() { + if done_exercises.contains(exercise.name.as_bytes()) { + exercise.done = true; + n_done += 1; + } + + if exercise.name.as_bytes() == current_exercise_name { + current_exercise_ind = ind; + } + } + + StateFileStatus::Read + }; + + file_buf.clear(); + file_buf.extend_from_slice(STATE_FILE_HEADER); + + let slf = Self { + current_exercise_ind, + exercises, + n_done, + final_message, + state_file, + file_buf, + official_exercises: !Path::new("info.toml").exists(), + cmd_runner, + // VS Code has its own file link handling + emit_file_links: env::var_os("TERM_PROGRAM").is_none_or(|v| v != "vscode"), + }; + + Ok((slf, state_file_status)) + } + + #[inline] + pub fn current_exercise_ind(&self) -> usize { + self.current_exercise_ind + } + + #[inline] + pub fn exercises(&self) -> &[Exercise] { + &self.exercises + } + + #[inline] + pub fn n_done(&self) -> u16 { + self.n_done + } + + #[inline] + pub fn n_pending(&self) -> u16 { + self.exercises.len() as u16 - self.n_done + } + + #[inline] + pub fn current_exercise(&self) -> &Exercise { + &self.exercises[self.current_exercise_ind] + } + + #[inline] + pub fn cmd_runner(&self) -> &CmdRunner { + &self.cmd_runner + } + + #[inline] + pub fn emit_file_links(&self) -> bool { + self.emit_file_links + } + + // Write the state file. + // The file's format is very simple: + // - The first line is a comment. + // - The second line is an empty line. + // - The third line is the name of the current exercise. It must end with `\n` even if there + // are no done exercises. + // - The fourth line is an empty line. + // - All remaining lines are the names of done exercises. + fn write(&mut self) -> Result<()> { + self.file_buf.truncate(STATE_FILE_HEADER.len()); + + self.file_buf + .extend_from_slice(self.current_exercise().name.as_bytes()); + self.file_buf.push(b'\n'); + + for exercise in &self.exercises { + if exercise.done { + self.file_buf.push(b'\n'); + self.file_buf.extend_from_slice(exercise.name.as_bytes()); + } + } + + self.state_file + .rewind() + .with_context(|| format!("Failed to rewind the state file {STATE_FILE_NAME}"))?; + self.state_file + .set_len(0) + .with_context(|| format!("Failed to truncate the state file {STATE_FILE_NAME}"))?; + self.state_file + .write_all(&self.file_buf) + .with_context(|| format!("Failed to write the state file {STATE_FILE_NAME}"))?; + + Ok(()) + } + + pub fn set_current_exercise_ind(&mut self, exercise_ind: usize) -> Result<()> { + if exercise_ind == self.current_exercise_ind { + return Ok(()); + } + + if exercise_ind >= self.exercises.len() { + bail!(BAD_INDEX_ERR); + } + + self.current_exercise_ind = exercise_ind; + + self.write() + } + + pub fn set_current_exercise_by_name(&mut self, name: &str) -> Result<()> { + // O(N) is fine since this method is used only once until the program exits. + // Building a hashmap would have more overhead. + self.current_exercise_ind = self + .exercises + .iter() + .position(|exercise| exercise.name == name) + .with_context(|| format!("No exercise found for '{name}'!"))?; + + self.write() + } + + // Set the status of an exercise without saving. Returns `true` if the + // status actually changed (and thus needs saving later). + pub fn set_status(&mut self, exercise_ind: usize, done: bool) -> Result { + let exercise = self + .exercises + .get_mut(exercise_ind) + .context(BAD_INDEX_ERR)?; + + if exercise.done == done { + return Ok(false); + } + + exercise.done = done; + if done { + self.n_done += 1; + } else { + self.n_done -= 1; + } + + Ok(true) + } + + // Set the status of an exercise to "pending" and save. + pub fn set_pending(&mut self, exercise_ind: usize) -> Result<()> { + if self.set_status(exercise_ind, false)? { + self.write()?; + } + + Ok(()) + } + + // Official exercises: Dump the original file from the binary. + // Community exercises: Reset the exercise file with `git stash`. + fn reset(&self, exercise_ind: usize, path: &str) -> Result<()> { + if self.official_exercises { + return EMBEDDED_FILES + .write_exercise_to_disk(exercise_ind, path) + .with_context(|| format!("Failed to reset the exercise {path}")); + } + + let output = Command::new("git") + .arg("stash") + .arg("push") + .arg("--") + .arg(path) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .output() + .with_context(|| format!("Failed to run `git stash push -- {path}`"))?; + + if !output.status.success() { + bail!( + "`git stash push -- {path}` didn't run successfully: {}", + String::from_utf8_lossy(&output.stderr), + ); + } + + Ok(()) + } + + pub fn reset_current_exercise(&mut self) -> Result<&'static str> { + self.set_pending(self.current_exercise_ind)?; + let exercise = self.current_exercise(); + self.reset(self.current_exercise_ind, exercise.path)?; + + Ok(exercise.path) + } + + // Reset the exercise by index and return its name. + pub fn reset_exercise_by_ind(&mut self, exercise_ind: usize) -> Result<&'static str> { + if exercise_ind >= self.exercises.len() { + bail!(BAD_INDEX_ERR); + } + + self.set_pending(exercise_ind)?; + let exercise = &self.exercises[exercise_ind]; + self.reset(exercise_ind, exercise.path)?; + + Ok(exercise.name) + } + + // Return the index of the next pending exercise or `None` if all exercises are done. + fn next_pending_exercise_ind(&self) -> Option { + let next_ind = self.current_exercise_ind + 1; + self.exercises + // If the exercise done isn't the last, search for pending exercises after it. + .get(next_ind..) + .and_then(|later_exercises| { + later_exercises + .iter() + .position(|exercise| !exercise.done) + .map(|ind| next_ind + ind) + }) + // Search from the start. + .or_else(|| { + self.exercises[..self.current_exercise_ind] + .iter() + .position(|exercise| !exercise.done) + }) + } + + /// Official exercises: Dump the solution file from the binary and return its path. + /// Community exercises: Check if a solution file exists and return its path in that case. + pub fn current_solution_path(&self) -> Result> { + if cfg!(debug_assertions) { + return Ok(None); + } + + let current_exercise = self.current_exercise(); + + if self.official_exercises { + EMBEDDED_FILES + .write_solution_to_disk(self.current_exercise_ind, current_exercise.name) + .map(Some) + } else { + let sol_path = current_exercise.sol_path(); + + if Path::new(&sol_path).exists() { + return Ok(Some(sol_path)); + } + + Ok(None) + } + } + + fn check_all_exercises_impl(&mut self, stdout: &mut StdoutLock) -> Result> { + let term_width = terminal::size() + .context("Failed to get the terminal size")? + .0; + let mut progress_visualizer = CheckProgressVisualizer::build(stdout, term_width)?; + + let next_exercise_ind = AtomicUsize::new(0); + let mut progresses = vec![CheckProgress::None; self.exercises.len()]; + + thread::scope(|s| { + let (exercise_progress_sender, exercise_progress_receiver) = mpsc::channel(); + let n_threads = thread::available_parallelism() + .map_or(DEFAULT_CHECK_PARALLELISM, |count| count.get()); + + for _ in 0..n_threads { + let exercise_progress_sender = exercise_progress_sender.clone(); + let next_exercise_ind = &next_exercise_ind; + let slf = &self; + thread::Builder::new() + .spawn_scoped(s, move || { + loop { + let exercise_ind = next_exercise_ind.fetch_add(1, Relaxed); + let Some(exercise) = slf.exercises.get(exercise_ind) else { + // No more exercises. + break; + }; + + if exercise_progress_sender + .send((exercise_ind, CheckProgress::Checking)) + .is_err() + { + break; + }; + + let success = exercise.run_exercise(None, &slf.cmd_runner); + let progress = match success { + Ok(true) => CheckProgress::Done, + Ok(false) => CheckProgress::Pending, + Err(_) => CheckProgress::None, + }; + + if exercise_progress_sender + .send((exercise_ind, progress)) + .is_err() + { + break; + } + } + }) + .context("Failed to spawn a thread to check all exercises")?; + } + + // Drop this sender to detect when the last thread is done. + drop(exercise_progress_sender); + + while let Ok((exercise_ind, progress)) = exercise_progress_receiver.recv() { + progresses[exercise_ind] = progress; + progress_visualizer.update(&progresses)?; + } + + Ok::<_, Error>(()) + })?; + + let mut first_pending_exercise_ind = None; + for exercise_ind in 0..progresses.len() { + match progresses[exercise_ind] { + CheckProgress::Done => { + self.set_status(exercise_ind, true)?; + } + CheckProgress::Pending => { + self.set_status(exercise_ind, false)?; + if first_pending_exercise_ind.is_none() { + first_pending_exercise_ind = Some(exercise_ind); + } + } + CheckProgress::None | CheckProgress::Checking => { + // If we got an error while checking all exercises in parallel, + // it could be because we exceeded the limit of open file descriptors. + // Therefore, try running exercises with errors sequentially. + progresses[exercise_ind] = CheckProgress::Checking; + progress_visualizer.update(&progresses)?; + + let exercise = &self.exercises[exercise_ind]; + let success = exercise.run_exercise(None, &self.cmd_runner)?; + if success { + progresses[exercise_ind] = CheckProgress::Done; + } else { + progresses[exercise_ind] = CheckProgress::Pending; + if first_pending_exercise_ind.is_none() { + first_pending_exercise_ind = Some(exercise_ind); + } + } + self.set_status(exercise_ind, success)?; + progress_visualizer.update(&progresses)?; + } + } + } + + self.write()?; + + Ok(first_pending_exercise_ind) + } + + // Return the exercise index of the first pending exercise found. + pub fn check_all_exercises(&mut self, stdout: &mut StdoutLock) -> Result> { + stdout.queue(cursor::Hide)?; + let res = self.check_all_exercises_impl(stdout); + stdout.queue(cursor::Show)?; + + res + } + + /// Mark the current exercise as done and move on to the next pending exercise if one exists. + /// If all exercises are marked as done, run all of them to make sure that they are actually + /// done. If an exercise which is marked as done fails, mark it as pending and continue on it. + pub fn done_current_exercise( + &mut self, + stdout: &mut StdoutLock, + ) -> Result { + let exercise = &mut self.exercises[self.current_exercise_ind]; + if !exercise.done { + exercise.done = true; + self.n_done += 1; + } + + if let Some(ind) = self.next_pending_exercise_ind() { + self.set_current_exercise_ind(ind)?; + return Ok(ExercisesProgress::NewPending); + } + + if CLEAR_BEFORE_FINAL_CHECK { + clear_terminal(stdout)?; + } else { + stdout.write_all(b"\n")?; + } + + if let Some(first_pending_exercise_ind) = self.check_all_exercises(stdout)? { + self.set_current_exercise_ind(first_pending_exercise_ind)?; + + return Ok(ExercisesProgress::NewPending); + } + + self.render_final_message(stdout)?; + + Ok(ExercisesProgress::AllDone) + } + + pub fn render_final_message(&self, stdout: &mut StdoutLock) -> Result<()> { + clear_terminal(stdout)?; + stdout.write_all(FENISH_LINE.as_bytes())?; + + let final_message = self.final_message.trim_ascii(); + if !final_message.is_empty() { + stdout.write_all(final_message.as_bytes())?; + stdout.write_all(b"\n")?; + } + + Ok(()) + } +} + +const BAD_INDEX_ERR: &str = "The current exercise index is higher than the number of exercises"; +const STATE_FILE_HEADER: &[u8] = b"DON'T EDIT THIS FILE!\n\n"; +const FENISH_LINE: &str = "+----------------------------------------------------+ +| You made it to the Fe-nish line! | ++-------------------------- ------------------------+ + \\/\x1b[31m + ▒▒ ▒▒▒▒▒▒▒▒ ▒▒▒▒▒▒▒▒ ▒▒ + ▒▒▒▒ ▒▒ ▒▒ ▒▒ ▒▒ ▒▒ ▒▒ ▒▒▒▒ + ▒▒▒▒ ▒▒ ▒▒ ▒▒ ▒▒ ▒▒ ▒▒▒▒ + ░░▒▒▒▒░░▒▒ ▒▒ ▒▒ ▒▒ ▒▒░░▒▒▒▒ + ▓▓▓▓▓▓▓▓ ▓▓ ▓▓██ ▓▓ ▓▓██ ▓▓ ▓▓▓▓▓▓▓▓ + ▒▒▒▒ ▒▒ ████ ▒▒ ████ ▒▒░░ ▒▒▒▒ + ▒▒ ▒▒▒▒▒▒ ▒▒▒▒▒▒ ▒▒▒▒▒▒ ▒▒ + ▒▒▒▒▒▒▒▒▒▒▓▓▓▓▓▓▒▒▒▒▒▒▒▒▓▓▓▓▓▓▒▒▒▒▒▒▒▒ + ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ + ▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒ + ▒▒ ▒▒▒▒▒▒▒▒▒▒██████▒▒▒▒▒▒▒▒▒▒ ▒▒ + ▒▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒ + ▒▒ ▒▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒ ▒▒ + ▒▒ ▒▒ ▒▒ ▒▒ ▒▒ ▒▒ + ▒▒ ▒▒ ▒▒ ▒▒\x1b[0m + +"; + +#[cfg(test)] +mod tests { + use super::*; + + fn dummy_exercise() -> Exercise { + Exercise { + dir: None, + name: "0", + path: "exercises/0.rs", + canonical_path: None, + test: false, + strict_clippy: false, + hint: "", + done: false, + } + } + + #[test] + fn next_pending_exercise() { + let mut app_state = AppState { + current_exercise_ind: 0, + exercises: vec![dummy_exercise(), dummy_exercise(), dummy_exercise()], + n_done: 0, + final_message: String::new(), + state_file: tempfile::tempfile().unwrap(), + file_buf: Vec::new(), + official_exercises: true, + cmd_runner: CmdRunner::build().unwrap(), + emit_file_links: true, + }; + + let mut assert = |done: [bool; 3], expected: [Option; 3]| { + for (exercise, done) in app_state.exercises.iter_mut().zip(done) { + exercise.done = done; + } + for (ind, expected) in expected.into_iter().enumerate() { + app_state.current_exercise_ind = ind; + assert_eq!( + app_state.next_pending_exercise_ind(), + expected, + "done={done:?}, ind={ind}", + ); + } + }; + + assert([true, true, true], [None, None, None]); + assert([false, false, false], [Some(1), Some(2), Some(0)]); + assert([false, true, true], [None, Some(0), Some(0)]); + assert([true, false, true], [Some(1), None, Some(1)]); + assert([true, true, false], [Some(2), Some(2), None]); + assert([true, false, false], [Some(1), Some(2), Some(1)]); + assert([false, true, false], [Some(2), Some(2), Some(0)]); + assert([false, false, true], [Some(1), Some(0), Some(0)]); + } +} diff --git a/src/cargo_toml.rs b/src/cargo_toml.rs new file mode 100644 index 0000000000..ce0dfd0cf3 --- /dev/null +++ b/src/cargo_toml.rs @@ -0,0 +1,153 @@ +use anyhow::{Context, Result}; +use std::path::Path; + +use crate::{exercise::RunnableExercise, info_file::ExerciseInfo}; + +/// Initial capacity of the bins buffer. +pub const BINS_BUFFER_CAPACITY: usize = 1 << 14; + +/// Return the start and end index of the content of the list `bin = […]`. +/// bin = [xxxxxxxxxxxxxxxxx] +/// |start_ind | +/// |end_ind +pub fn bins_start_end_ind(cargo_toml: &str) -> Result<(usize, usize)> { + let start_ind = cargo_toml + .find("bin = [") + .context("Failed to find the start of the `bin` list (`bin = [`)")? + + 7; + let end_ind = start_ind + + cargo_toml + .get(start_ind..) + .and_then(|slice| slice.as_bytes().iter().position(|c| *c == b']')) + .context("Failed to find the end of the `bin` list (`]`)")?; + + Ok((start_ind, end_ind)) +} + +/// Generate and append the content of the `bin` list in `Cargo.toml`. +/// The `exercise_path_prefix` is the prefix of the `path` field of every list entry. +pub fn append_bins( + buf: &mut Vec, + exercise_infos: &[ExerciseInfo], + exercise_path_prefix: &[u8], +) { + buf.push(b'\n'); + for exercise_info in exercise_infos { + buf.extend_from_slice(b" { name = \""); + buf.extend_from_slice(exercise_info.name.as_bytes()); + buf.extend_from_slice(b"\", path = \""); + buf.extend_from_slice(exercise_path_prefix); + buf.extend_from_slice(b"exercises/"); + if let Some(dir) = &exercise_info.dir { + buf.extend_from_slice(dir.as_bytes()); + buf.push(b'/'); + } + buf.extend_from_slice(exercise_info.name.as_bytes()); + buf.extend_from_slice(b".rs\" },\n"); + + let sol_path = exercise_info.sol_path(); + if !Path::new(&sol_path).exists() { + continue; + } + + buf.extend_from_slice(b" { name = \""); + buf.extend_from_slice(exercise_info.name.as_bytes()); + buf.extend_from_slice(b"_sol"); + buf.extend_from_slice(b"\", path = \""); + buf.extend_from_slice(exercise_path_prefix); + buf.extend_from_slice(b"solutions/"); + if let Some(dir) = &exercise_info.dir { + buf.extend_from_slice(dir.as_bytes()); + buf.push(b'/'); + } + buf.extend_from_slice(exercise_info.name.as_bytes()); + buf.extend_from_slice(b".rs\" },\n"); + } +} + +/// Update the `bin` list and leave everything else unchanged. +pub fn updated_cargo_toml( + exercise_infos: &[ExerciseInfo], + current_cargo_toml: &str, + exercise_path_prefix: &[u8], +) -> Result> { + let (bins_start_ind, bins_end_ind) = bins_start_end_ind(current_cargo_toml)?; + + let mut updated_cargo_toml = Vec::with_capacity(BINS_BUFFER_CAPACITY); + updated_cargo_toml.extend_from_slice(¤t_cargo_toml.as_bytes()[..bins_start_ind]); + append_bins( + &mut updated_cargo_toml, + exercise_infos, + exercise_path_prefix, + ); + updated_cargo_toml.extend_from_slice(¤t_cargo_toml.as_bytes()[bins_end_ind..]); + + Ok(updated_cargo_toml) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_bins_start_end_ind() { + assert_eq!(bins_start_end_ind("").ok(), None); + assert_eq!(bins_start_end_ind("[]").ok(), None); + assert_eq!(bins_start_end_ind("bin = [").ok(), None); + assert_eq!(bins_start_end_ind("bin = ]").ok(), None); + assert_eq!(bins_start_end_ind("bin = []").ok(), Some((7, 7))); + assert_eq!(bins_start_end_ind("bin= []").ok(), None); + assert_eq!(bins_start_end_ind("bin =[]").ok(), None); + assert_eq!(bins_start_end_ind("bin=[]").ok(), None); + assert_eq!(bins_start_end_ind("bin = [\nxxx\n]").ok(), Some((7, 12))); + } + + #[test] + fn test_bins() { + let exercise_infos = [ + ExerciseInfo { + name: String::from("1"), + dir: None, + test: true, + strict_clippy: true, + hint: String::new(), + skip_check_unsolved: false, + }, + ExerciseInfo { + name: String::from("2"), + dir: Some(String::from("d")), + test: false, + strict_clippy: false, + hint: String::new(), + skip_check_unsolved: false, + }, + ]; + + let mut buf = Vec::with_capacity(128); + append_bins(&mut buf, &exercise_infos, b""); + assert_eq!( + buf, + br#" + { name = "1", path = "exercises/1.rs" }, + { name = "2", path = "exercises/d/2.rs" }, +"#, + ); + + assert_eq!( + updated_cargo_toml( + &exercise_infos, + "abc\n\ + bin = [xxx]\n\ + 123", + b"../" + ) + .unwrap(), + br#"abc +bin = [ + { name = "1", path = "../exercises/1.rs" }, + { name = "2", path = "../exercises/d/2.rs" }, +] +123"#, + ); + } +} diff --git a/src/cmd.rs b/src/cmd.rs new file mode 100644 index 0000000000..b2c58f6abb --- /dev/null +++ b/src/cmd.rs @@ -0,0 +1,163 @@ +use anyhow::{Context, Result, bail}; +use serde::Deserialize; +use std::{ + io::{Read, pipe}, + path::PathBuf, + process::{Command, Stdio}, +}; + +/// Run a command with a description for a possible error and append the merged stdout and stderr. +/// The boolean in the returned `Result` is true if the command's exit status is success. +fn run_cmd(mut cmd: Command, description: &str, output: Option<&mut Vec>) -> Result { + let spawn = |mut cmd: Command| { + // NOTE: The closure drops `cmd` which prevents a pipe deadlock. + cmd.stdin(Stdio::null()) + .spawn() + .with_context(|| format!("Failed to run the command `{description}`")) + }; + + let mut handle = if let Some(output) = output { + let (mut reader, writer) = pipe().with_context(|| { + format!("Failed to create a pipe to run the command `{description}``") + })?; + + let writer_clone = writer.try_clone().with_context(|| { + format!("Failed to clone the pipe writer for the command `{description}`") + })?; + + cmd.stdout(writer_clone).stderr(writer); + let handle = spawn(cmd)?; + + reader + .read_to_end(output) + .with_context(|| format!("Failed to read the output of the command `{description}`"))?; + + output.push(b'\n'); + + handle + } else { + cmd.stdout(Stdio::null()).stderr(Stdio::null()); + spawn(cmd)? + }; + + handle + .wait() + .with_context(|| format!("Failed to wait on the command `{description}` to exit")) + .map(|status| status.success()) +} + +// Parses parts of the output of `cargo metadata`. +#[derive(Deserialize)] +struct CargoMetadata { + target_directory: PathBuf, +} + +pub struct CmdRunner { + target_dir: PathBuf, +} + +impl CmdRunner { + pub fn build() -> Result { + // Get the target directory from Cargo. + let metadata_output = Command::new("cargo") + .arg("metadata") + .arg("-q") + .arg("--format-version") + .arg("1") + .arg("--no-deps") + .stdin(Stdio::null()) + .stderr(Stdio::inherit()) + .output() + .context(CARGO_METADATA_ERR)?; + + if !metadata_output.status.success() { + bail!("The command `cargo metadata …` failed. Are you in the `rustlings/` directory?"); + } + + let metadata: CargoMetadata = serde_json::de::from_slice(&metadata_output.stdout) + .context( + "Failed to read the field `target_directory` from the output of the command `cargo metadata …`", + )?; + + Ok(Self { + target_dir: metadata.target_directory, + }) + } + + pub fn cargo<'out>( + &self, + subcommand: &str, + bin_name: &str, + output: Option<&'out mut Vec>, + ) -> CargoSubcommand<'out> { + let mut cmd = Command::new("cargo"); + cmd.arg(subcommand).arg("-q").arg("--bin").arg(bin_name); + + // A hack to make `cargo run` work when developing Rustlings. + #[cfg(debug_assertions)] + cmd.arg("--manifest-path") + .arg("dev/Cargo.toml") + .arg("--target-dir") + .arg(&self.target_dir); + + if output.is_some() { + cmd.arg("--color").arg("always"); + } + + CargoSubcommand { cmd, output } + } + + /// The boolean in the returned `Result` is true if the command's exit status is success. + pub fn run_debug_bin(&self, bin_name: &str, output: Option<&mut Vec>) -> Result { + // 7 = "/debug/".len() + let mut bin_path = + PathBuf::with_capacity(self.target_dir.as_os_str().len() + 7 + bin_name.len()); + bin_path.push(&self.target_dir); + bin_path.push("debug"); + bin_path.push(bin_name); + + run_cmd(Command::new(&bin_path), &bin_path.to_string_lossy(), output) + } +} + +pub struct CargoSubcommand<'out> { + cmd: Command, + output: Option<&'out mut Vec>, +} + +impl CargoSubcommand<'_> { + #[inline] + pub fn args<'arg, I>(&mut self, args: I) -> &mut Self + where + I: IntoIterator, + { + self.cmd.args(args); + self + } + + /// The boolean in the returned `Result` is true if the command's exit status is success. + #[inline] + pub fn run(self, description: &str) -> Result { + run_cmd(self.cmd, description, self.output) + } +} + +const CARGO_METADATA_ERR: &str = "Failed to run the command `cargo metadata …` +Did you already install Rust? +Try running `cargo --version` to diagnose the problem."; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_run_cmd() { + let mut cmd = Command::new("echo"); + cmd.arg("Hello"); + + let mut output = Vec::with_capacity(8); + run_cmd(cmd, "echo …", Some(&mut output)).unwrap(); + + assert_eq!(output, b"Hello\n\n"); + } +} diff --git a/src/dev.rs b/src/dev.rs new file mode 100644 index 0000000000..41fddbeb98 --- /dev/null +++ b/src/dev.rs @@ -0,0 +1,46 @@ +use anyhow::{Context, Result, bail}; +use clap::Subcommand; +use std::path::PathBuf; + +mod check; +mod new; +mod update; + +#[derive(Subcommand)] +pub enum DevCommands { + /// Create a new project for community exercises + New { + /// The path to create the project in + path: PathBuf, + /// Don't try to initialize a Git repository in the project directory + #[arg(long)] + no_git: bool, + }, + /// Run checks on the exercises + Check { + /// Require that every exercise has a solution + #[arg(short, long)] + require_solutions: bool, + }, + /// Update the `Cargo.toml` file for the exercises + Update, +} + +impl DevCommands { + pub fn run(self) -> Result<()> { + match self { + Self::New { path, no_git } => { + if cfg!(debug_assertions) { + bail!("Disabled in the debug build"); + } + + new::new(&path, no_git).context(INIT_ERR) + } + Self::Check { require_solutions } => check::check(require_solutions), + Self::Update => update::update(), + } + } +} + +const INIT_ERR: &str = "Initialization failed. +After resolving the issue, delete the `rustlings` directory (if it was created) and try again"; diff --git a/src/dev/check.rs b/src/dev/check.rs new file mode 100644 index 0000000000..f71110630d --- /dev/null +++ b/src/dev/check.rs @@ -0,0 +1,398 @@ +use anyhow::{Context, Error, Result, anyhow, bail}; +use std::{ + cmp::Ordering, + collections::HashSet, + fs::{self, OpenOptions, read_dir}, + io::{self, Read, Write}, + path::{Path, PathBuf}, + process::{Command, Stdio}, + thread, +}; + +use crate::{ + CURRENT_FORMAT_VERSION, + cargo_toml::{BINS_BUFFER_CAPACITY, append_bins, bins_start_end_ind}, + cmd::CmdRunner, + exercise::{OUTPUT_CAPACITY, RunnableExercise}, + info_file::{ExerciseInfo, InfoFile}, + term::ProgressCounter, +}; + +const MAX_N_EXERCISES: usize = 999; +const MAX_EXERCISE_NAME_LEN: usize = 32; + +// Find a char that isn't allowed in the exercise's `name` or `dir`. +fn forbidden_char(input: &str) -> Option { + input.chars().find(|c| !c.is_alphanumeric() && *c != '_') +} + +// Check that the `Cargo.toml` file is up-to-date. +fn check_cargo_toml( + exercise_infos: &[ExerciseInfo], + cargo_toml_path: &str, + exercise_path_prefix: &[u8], +) -> Result<()> { + let current_cargo_toml = fs::read_to_string(cargo_toml_path) + .with_context(|| format!("Failed to read the file `{cargo_toml_path}`"))?; + + let (bins_start_ind, bins_end_ind) = bins_start_end_ind(¤t_cargo_toml)?; + + let old_bins = ¤t_cargo_toml.as_bytes()[bins_start_ind..bins_end_ind]; + let mut new_bins = Vec::with_capacity(BINS_BUFFER_CAPACITY); + append_bins(&mut new_bins, exercise_infos, exercise_path_prefix); + + if old_bins != new_bins { + if cfg!(debug_assertions) { + bail!( + "The file `dev/Cargo.toml` is outdated. Run `cargo dev update` to update it. Then run `cargo run -- dev check` again" + ); + } + + bail!( + "The file `Cargo.toml` is outdated. Run `rustlings dev update` to update it. Then run `rustlings dev check` again" + ); + } + + Ok(()) +} + +// Check the info of all exercises and return their paths in a set. +fn check_info_file_exercises(info_file: &InfoFile) -> Result> { + let mut names = HashSet::with_capacity(info_file.exercises.len()); + let mut paths = HashSet::with_capacity(info_file.exercises.len()); + + let mut file_buf = String::with_capacity(1 << 14); + for exercise_info in &info_file.exercises { + let name = exercise_info.name.as_str(); + if name.is_empty() { + bail!("Found an empty exercise name in `info.toml`"); + } + if name.len() > MAX_EXERCISE_NAME_LEN { + bail!( + "The length of the exercise name `{name}` is bigger than the maximum {MAX_EXERCISE_NAME_LEN}" + ); + } + if let Some(c) = forbidden_char(name) { + bail!("Char `{c}` in the exercise name `{name}` is not allowed"); + } + + if let Some(dir) = &exercise_info.dir { + if dir.is_empty() { + bail!("The exercise `{name}` has an empty dir name in `info.toml`"); + } + if let Some(c) = forbidden_char(dir) { + bail!("Char `{c}` in the exercise dir `{dir}` is not allowed"); + } + } + + if exercise_info.hint.trim_ascii().is_empty() { + bail!( + "The exercise `{name}` has an empty hint. Please provide a hint or at least tell the user why a hint isn't needed for this exercise" + ); + } + + if !names.insert(name) { + bail!("The exercise name `{name}` is duplicated. Exercise names must all be unique"); + } + + let path = exercise_info.path(); + + OpenOptions::new() + .read(true) + .open(&path) + .with_context(|| format!("Failed to open the file {path}"))? + .read_to_string(&mut file_buf) + .with_context(|| format!("Failed to read the file {path}"))?; + + if !file_buf.contains("fn main()") { + bail!( + "The `main` function is missing in the file `{path}`.\n\ + Create at least an empty `main` function to avoid language server errors" + ); + } + + if !file_buf.contains("// TODO") { + bail!( + "Didn't find any `// TODO` comment in the file `{path}`.\n\ + You need to have at least one such comment to guide the user." + ); + } + + let contains_tests = file_buf.contains("#[test]\n"); + if exercise_info.test { + if !contains_tests { + bail!( + "The file `{path}` doesn't contain any tests. If you don't want to add tests to this exercise, set `test = false` for this exercise in the `info.toml` file" + ); + } + } else if contains_tests { + bail!( + "The file `{path}` contains tests annotated with `#[test]` but the exercise `{name}` has `test = false` in the `info.toml` file" + ); + } + + file_buf.clear(); + + paths.insert(PathBuf::from(path)); + } + + Ok(paths) +} + +// Check `dir` for unexpected files. +// Only Rust files in `allowed_rust_files` and `README.md` files are allowed. +// Only one level of directory nesting is allowed. +fn check_unexpected_files(dir: &str, allowed_rust_files: &HashSet) -> Result<()> { + let unexpected_file = |path: &Path| { + anyhow!( + "Found the file `{}`. Only `README.md` and Rust files related to an exercise in `info.toml` are allowed in the `{dir}` directory", + path.display() + ) + }; + + for entry in read_dir(dir).with_context(|| format!("Failed to open the `{dir}` directory"))? { + let entry = entry.with_context(|| format!("Failed to read the `{dir}` directory"))?; + + if entry.file_type().unwrap().is_file() { + let path = entry.path(); + let file_name = path.file_name().unwrap(); + if file_name == "README.md" { + continue; + } + + if !allowed_rust_files.contains(&path) { + return Err(unexpected_file(&path)); + } + + continue; + } + + let dir_path = entry.path(); + for entry in read_dir(&dir_path) + .with_context(|| format!("Failed to open the directory {}", dir_path.display()))? + { + let entry = entry + .with_context(|| format!("Failed to read the directory {}", dir_path.display()))?; + let path = entry.path(); + + if !entry.file_type().unwrap().is_file() { + bail!( + "Found `{}` but expected only files. Only one level of exercise nesting is allowed", + path.display() + ); + } + + let file_name = path.file_name().unwrap(); + if file_name == "README.md" { + continue; + } + + if !allowed_rust_files.contains(&path) { + return Err(unexpected_file(&path)); + } + } + } + + Ok(()) +} + +fn check_exercises_unsolved( + info_file: &'static InfoFile, + cmd_runner: &'static CmdRunner, +) -> Result<()> { + let mut stdout = io::stdout().lock(); + stdout.write_all(b"Running all exercises to check that they aren't already solved...\n")?; + + let handles = info_file + .exercises + .iter() + .filter_map(|exercise_info| { + if exercise_info.skip_check_unsolved { + return None; + } + + Some( + thread::Builder::new() + .spawn(|| exercise_info.run_exercise(None, cmd_runner)) + .map(|handle| (exercise_info.name.as_str(), handle)), + ) + }) + .collect::, _>>() + .context("Failed to spawn a thread to check if an exercise is already solved")?; + + let mut progress_counter = ProgressCounter::new(&mut stdout, handles.len())?; + + for (exercise_name, handle) in handles { + let Ok(result) = handle.join() else { + bail!("Panic while trying to run the exercise {exercise_name}"); + }; + + match result { + Ok(true) => { + bail!( + "The exercise {exercise_name} is already solved.\n\ + {SKIP_CHECK_UNSOLVED_HINT}", + ) + } + Ok(false) => (), + Err(e) => return Err(e), + } + + progress_counter.increment()?; + } + + Ok(()) +} + +fn check_exercises(info_file: &'static InfoFile, cmd_runner: &'static CmdRunner) -> Result<()> { + match info_file.format_version.cmp(&CURRENT_FORMAT_VERSION) { + Ordering::Less => bail!( + "`format_version` < {CURRENT_FORMAT_VERSION} (supported version)\n\ + Please migrate to the latest format version" + ), + Ordering::Greater => bail!( + "`format_version` > {CURRENT_FORMAT_VERSION} (supported version)\n\ + Try updating the Rustlings program" + ), + Ordering::Equal => (), + } + + let handle = thread::Builder::new() + .spawn(move || check_exercises_unsolved(info_file, cmd_runner)) + .context("Failed to spawn a thread to check if any exercise is already solved")?; + + let info_file_paths = check_info_file_exercises(info_file)?; + check_unexpected_files("exercises", &info_file_paths)?; + + handle.join().unwrap() +} + +enum SolutionCheck { + Success { sol_path: String }, + MissingOptional, + RunFailure { output: Vec }, + Err(Error), +} + +fn check_solutions( + require_solutions: bool, + info_file: &'static InfoFile, + cmd_runner: &'static CmdRunner, +) -> Result<()> { + let mut stdout = io::stdout().lock(); + stdout.write_all(b"Running all solutions...\n")?; + + let handles = info_file + .exercises + .iter() + .map(|exercise_info| { + thread::Builder::new().spawn(move || { + let sol_path = exercise_info.sol_path(); + if !Path::new(&sol_path).exists() { + if require_solutions { + return SolutionCheck::Err(anyhow!( + "The solution of the exercise {} is missing", + exercise_info.name, + )); + } + + return SolutionCheck::MissingOptional; + } + + let mut output = Vec::with_capacity(OUTPUT_CAPACITY); + match exercise_info.run_solution(Some(&mut output), cmd_runner) { + Ok(true) => SolutionCheck::Success { sol_path }, + Ok(false) => SolutionCheck::RunFailure { output }, + Err(e) => SolutionCheck::Err(e), + } + }) + }) + .collect::, _>>() + .context("Failed to spawn a thread to check a solution")?; + + let mut sol_paths = HashSet::with_capacity(info_file.exercises.len()); + let mut fmt_cmd = Command::new("rustfmt"); + fmt_cmd + .arg("--check") + .arg("--edition") + .arg("2024") + .arg("--color") + .arg("always") + .stdin(Stdio::null()); + + let mut progress_counter = ProgressCounter::new(&mut stdout, handles.len())?; + + for (exercise_info, handle) in info_file.exercises.iter().zip(handles) { + let Ok(check_result) = handle.join() else { + bail!( + "Panic while trying to run the solution of the exercise {}", + exercise_info.name, + ); + }; + + match check_result { + SolutionCheck::Success { sol_path } => { + fmt_cmd.arg(&sol_path); + sol_paths.insert(PathBuf::from(sol_path)); + } + SolutionCheck::MissingOptional => (), + SolutionCheck::RunFailure { output } => { + drop(progress_counter); + stdout.write_all(&output)?; + bail!( + "Running the solution of the exercise {} failed with the error above", + exercise_info.name, + ); + } + SolutionCheck::Err(e) => return Err(e), + } + + progress_counter.increment()?; + } + + let n_solutions = sol_paths.len(); + let handle = thread::Builder::new() + .spawn(move || check_unexpected_files("solutions", &sol_paths)) + .context( + "Failed to spawn a thread to check for unexpected files in the solutions directory", + )?; + + if n_solutions > 0 + && !fmt_cmd + .status() + .context("Failed to run `rustfmt` on all solution files")? + .success() + { + bail!("Some solutions aren't formatted. Run `rustfmt` on them"); + } + + handle.join().unwrap() +} + +pub fn check(require_solutions: bool) -> Result<()> { + let info_file = InfoFile::parse()?; + + if info_file.exercises.len() > MAX_N_EXERCISES { + bail!("The maximum number of exercises is {MAX_N_EXERCISES}"); + } + + if cfg!(debug_assertions) { + // A hack to make `cargo dev check` work when developing Rustlings. + check_cargo_toml(&info_file.exercises, "dev/Cargo.toml", b"../")?; + } else { + check_cargo_toml(&info_file.exercises, "Cargo.toml", b"")?; + } + + // Leaking is fine since they are used until the end of the program. + let cmd_runner = Box::leak(Box::new(CmdRunner::build()?)); + let info_file = Box::leak(Box::new(info_file)); + + check_exercises(info_file, cmd_runner)?; + check_solutions(require_solutions, info_file, cmd_runner)?; + + println!("Everything looks fine!"); + + Ok(()) +} + +const SKIP_CHECK_UNSOLVED_HINT: &str = "If this is an introduction exercise that is intended to be already solved, add `skip_check_unsolved = true` to the exercise's metadata in the `info.toml` file"; diff --git a/src/dev/new.rs b/src/dev/new.rs new file mode 100644 index 0000000000..7c72a6b700 --- /dev/null +++ b/src/dev/new.rs @@ -0,0 +1,148 @@ +use anyhow::{Context, Result, bail}; +use std::{ + env::set_current_dir, + fs::{self, create_dir}, + path::Path, + process::Command, +}; + +use crate::{CURRENT_FORMAT_VERSION, init::RUST_ANALYZER_TOML}; + +// Create a directory relative to the current directory and print its path. +fn create_rel_dir(dir_name: &str, current_dir: &str) -> Result<()> { + create_dir(dir_name) + .with_context(|| format!("Failed to create the directory {current_dir}/{dir_name}"))?; + println!("Created the directory {current_dir}/{dir_name}"); + Ok(()) +} + +// Write a file relative to the current directory and print its path. +fn write_rel_file(file_name: &str, current_dir: &str, content: C) -> Result<()> +where + C: AsRef<[u8]>, +{ + fs::write(file_name, content) + .with_context(|| format!("Failed to create the file {current_dir}/{file_name}"))?; + // Space to align with `create_rel_dir`. + println!("Created the file {current_dir}/{file_name}"); + Ok(()) +} + +pub fn new(path: &Path, no_git: bool) -> Result<()> { + let dir_path_str = path.to_string_lossy(); + + create_dir(path).with_context(|| format!("Failed to create the directory {dir_path_str}"))?; + println!("Created the directory {dir_path_str}"); + + set_current_dir(path) + .with_context(|| format!("Failed to set {dir_path_str} as the current directory"))?; + + if !no_git + && !Command::new("git") + .arg("init") + .status() + .context("Failed to run `git init`")? + .success() + { + bail!("`git init` didn't run successfully. See the possible error message above"); + } + + write_rel_file(".gitignore", &dir_path_str, GITIGNORE)?; + + create_rel_dir("exercises", &dir_path_str)?; + create_rel_dir("solutions", &dir_path_str)?; + + write_rel_file( + "info.toml", + &dir_path_str, + format!( + "{INFO_FILE_BEFORE_FORMAT_VERSION}{CURRENT_FORMAT_VERSION}{INFO_FILE_AFTER_FORMAT_VERSION}" + ), + )?; + + write_rel_file("Cargo.toml", &dir_path_str, CARGO_TOML)?; + + write_rel_file("README.md", &dir_path_str, README)?; + + write_rel_file("rust-analyzer.toml", &dir_path_str, RUST_ANALYZER_TOML)?; + + create_rel_dir(".vscode", &dir_path_str)?; + write_rel_file( + ".vscode/extensions.json", + &dir_path_str, + crate::init::VS_CODE_EXTENSIONS_JSON, + )?; + + println!("\nInitialization done ✓"); + + Ok(()) +} + +pub const GITIGNORE: &[u8] = b"Cargo.lock +target/ +.vscode/ +!.vscode/extensions.json +"; + +const INFO_FILE_BEFORE_FORMAT_VERSION: &str = + "# The format version is an indicator of the compatibility of community exercises with the +# Rustlings program. +# The format version is not the same as the version of the Rustlings program. +# In case Rustlings makes an unavoidable breaking change to the expected format of community +# exercises, you would need to raise this version and adapt to the new format. +# Otherwise, the newest version of the Rustlings program won't be able to run these exercises. +format_version = "; + +const INFO_FILE_AFTER_FORMAT_VERSION: &str = r#" + +# Optional multi-line message to be shown to users when just starting with the exercises. +welcome_message = """Welcome to these community Rustlings exercises.""" + +# Optional multi-line message to be shown to users after finishing all exercises. +final_message = """We hope that you found the exercises helpful :D""" + +# Repeat this section for every exercise. +[[exercises]] +# Exercise name which is the exercise file name without the `.rs` extension. +name = "???" + +# Optional directory name to be provided if you want to organize exercises in directories. +# If `dir` is specified, the exercise path is `exercises/DIR/NAME.rs` +# Otherwise, the path is `exercises/NAME.rs` +# dir = "???" + +# Rustlings expects the exercise to contain tests and run them. +# You can optionally disable testing by setting `test` to `false` (the default is `true`). +# In that case, the exercise will be considered done when it just successfully compiles. +# test = true + +# Rustlings will always run Clippy on exercises. +# You can optionally set `strict_clippy` to `true` (the default is `false`) to only consider +# the exercise as done when there are no warnings left. +# strict_clippy = false + +# A multi-line hint to be shown to users on request. +hint = """???""" +"#; + +const CARGO_TOML: &[u8] = + br#"# Don't edit the `bin` list manually! It is updated by `rustlings dev update` +bin = [] + +[package] +name = "exercises" +edition = "2024" +# Don't publish the exercises on crates.io! +publish = false + +[dependencies] +"#; + +const README: &str = "# Rustlings 🦀 + +Welcome to these community Rustlings exercises 😃 + +First, [install Rustlings using the official instructions](https://github.com/rust-lang/rustlings) ✅ + +Then, clone this repository, open a terminal in this directory and run `rustlings` to get started with the exercises 🚀 +"; diff --git a/src/dev/update.rs b/src/dev/update.rs new file mode 100644 index 0000000000..e0855a0e93 --- /dev/null +++ b/src/dev/update.rs @@ -0,0 +1,44 @@ +use anyhow::{Context, Result}; +use std::fs; + +use crate::{ + cargo_toml::updated_cargo_toml, + info_file::{ExerciseInfo, InfoFile}, +}; + +// Update the `Cargo.toml` file. +fn update_cargo_toml( + exercise_infos: &[ExerciseInfo], + cargo_toml_path: &str, + exercise_path_prefix: &[u8], +) -> Result<()> { + let current_cargo_toml = fs::read_to_string(cargo_toml_path) + .with_context(|| format!("Failed to read the file `{cargo_toml_path}`"))?; + + let updated_cargo_toml = + updated_cargo_toml(exercise_infos, ¤t_cargo_toml, exercise_path_prefix)?; + + fs::write(cargo_toml_path, updated_cargo_toml) + .context("Failed to write the `Cargo.toml` file")?; + + Ok(()) +} + +pub fn update() -> Result<()> { + let info_file = InfoFile::parse()?; + + if cfg!(debug_assertions) { + // A hack to make `cargo dev update` work when developing Rustlings. + update_cargo_toml(&info_file.exercises, "dev/Cargo.toml", b"../") + .context("Failed to update the file `dev/Cargo.toml`")?; + + println!("Updated `dev/Cargo.toml`"); + } else { + update_cargo_toml(&info_file.exercises, "Cargo.toml", &[]) + .context("Failed to update the file `Cargo.toml`")?; + + println!("Updated `Cargo.toml`"); + } + + Ok(()) +} diff --git a/src/embedded.rs b/src/embedded.rs new file mode 100644 index 0000000000..61a5f581e2 --- /dev/null +++ b/src/embedded.rs @@ -0,0 +1,168 @@ +use anyhow::{Context, Error, Result}; +use std::{ + fs::{self, create_dir}, + io, +}; + +use crate::info_file::ExerciseInfo; + +/// Contains all embedded files. +pub static EMBEDDED_FILES: EmbeddedFiles = rustlings_macros::include_files!(); + +// Files related to one exercise. +struct ExerciseFiles { + // The content of the exercise file. + exercise: &'static [u8], + // The content of the solution file. + solution: &'static [u8], + // Index of the related `ExerciseDir` in `EmbeddedFiles::exercise_dirs`. + dir_ind: usize, +} + +fn create_dir_if_not_exists(path: &str) -> Result<()> { + if let Err(e) = create_dir(path) + && e.kind() != io::ErrorKind::AlreadyExists + { + return Err(Error::from(e).context(format!("Failed to create the directory {path}"))); + } + + Ok(()) +} + +// A directory in the `exercises/` directory. +pub struct ExerciseDir { + pub name: &'static str, + readme: &'static [u8], +} + +impl ExerciseDir { + fn init_on_disk(&self) -> Result<()> { + // 20 = 10 + 10 + // exercises/ + /README.md + let mut dir_path = String::with_capacity(20 + self.name.len()); + dir_path.push_str("exercises/"); + dir_path.push_str(self.name); + create_dir_if_not_exists(&dir_path)?; + + let mut readme_path = dir_path; + readme_path.push_str("/README.md"); + + fs::write(&readme_path, self.readme) + .with_context(|| format!("Failed to write the file {readme_path}")) + } +} + +/// All embedded files. +pub struct EmbeddedFiles { + /// The content of the `info.toml` file. + pub info_file: &'static str, + exercise_files: &'static [ExerciseFiles], + pub exercise_dirs: &'static [ExerciseDir], +} + +impl EmbeddedFiles { + /// Dump all the embedded files of the `exercises/` directory. + pub fn init_exercises_dir(&self, exercise_infos: &[ExerciseInfo]) -> Result<()> { + create_dir("exercises").context("Failed to create the directory `exercises`")?; + + fs::write( + "exercises/README.md", + include_bytes!("../exercises/README.md"), + ) + .context("Failed to write the file exercises/README.md")?; + + for dir in self.exercise_dirs { + dir.init_on_disk()?; + } + + let mut exercise_path = String::with_capacity(64); + let prefix = "exercises/"; + exercise_path.push_str(prefix); + + for (exercise_info, exercise_files) in exercise_infos.iter().zip(self.exercise_files) { + let dir = &self.exercise_dirs[exercise_files.dir_ind]; + + exercise_path.truncate(prefix.len()); + exercise_path.push_str(dir.name); + exercise_path.push('/'); + exercise_path.push_str(&exercise_info.name); + exercise_path.push_str(".rs"); + + fs::write(&exercise_path, exercise_files.exercise) + .with_context(|| format!("Failed to write the exercise file {exercise_path}"))?; + } + + Ok(()) + } + + pub fn write_exercise_to_disk(&self, exercise_ind: usize, path: &str) -> Result<()> { + let exercise_files = &self.exercise_files[exercise_ind]; + let dir = &self.exercise_dirs[exercise_files.dir_ind]; + + dir.init_on_disk()?; + fs::write(path, exercise_files.exercise) + .with_context(|| format!("Failed to write the exercise file {path}")) + } + + /// Write the solution file to disk and return its path. + pub fn write_solution_to_disk( + &self, + exercise_ind: usize, + exercise_name: &str, + ) -> Result { + create_dir_if_not_exists("solutions")?; + + let exercise_files = &self.exercise_files[exercise_ind]; + let dir = &self.exercise_dirs[exercise_files.dir_ind]; + + // 14 = 10 + 1 + 3 + // solutions/ + / + .rs + let mut dir_path = String::with_capacity(14 + dir.name.len() + exercise_name.len()); + dir_path.push_str("solutions/"); + dir_path.push_str(dir.name); + create_dir_if_not_exists(&dir_path)?; + + let mut solution_path = dir_path; + solution_path.push('/'); + solution_path.push_str(exercise_name); + solution_path.push_str(".rs"); + + fs::write(&solution_path, exercise_files.solution) + .with_context(|| format!("Failed to write the solution file {solution_path}"))?; + + Ok(solution_path) + } +} + +#[cfg(test)] +mod tests { + use serde::Deserialize; + + use super::*; + + #[derive(Deserialize)] + struct ExerciseInfo { + dir: String, + } + + #[derive(Deserialize)] + struct InfoFile { + exercises: Vec, + } + + #[test] + fn dirs() { + let exercises = toml::de::from_str::(EMBEDDED_FILES.info_file) + .expect("Failed to parse `info.toml`") + .exercises; + + assert_eq!(exercises.len(), EMBEDDED_FILES.exercise_files.len()); + + for (exercise, exercise_files) in exercises.iter().zip(EMBEDDED_FILES.exercise_files) { + assert_eq!( + exercise.dir, + EMBEDDED_FILES.exercise_dirs[exercise_files.dir_ind].name, + ); + } + } +} diff --git a/src/exercise.rs b/src/exercise.rs index 4be3a2ccdd..a0596b5b9e 100644 --- a/src/exercise.rs +++ b/src/exercise.rs @@ -1,345 +1,223 @@ -use regex::Regex; -use serde::Deserialize; -use std::env; -use std::fmt::{self, Display, Formatter}; -use std::fs::{self, remove_file, File}; -use std::io::Read; -use std::path::PathBuf; -use std::process::{self, Command}; - -const RUSTC_COLOR_ARGS: &[&str] = &["--color", "always"]; -const I_AM_DONE_REGEX: &str = r"(?m)^\s*///?\s*I\s+AM\s+NOT\s+DONE"; -const CONTEXT: usize = 2; -const CLIPPY_CARGO_TOML_PATH: &str = "./exercises/clippy/Cargo.toml"; - -// Get a temporary file name that is hopefully unique -#[inline] -fn temp_file() -> String { - let thread_id: String = format!("{:?}", std::thread::current().id()) - .chars() - .filter(|c| c.is_alphanumeric()) - .collect(); - - format!("./temp_{}_{}", process::id(), thread_id) -} - -// The mode of the exercise. -#[derive(Deserialize, Copy, Clone, Debug)] -#[serde(rename_all = "lowercase")] -pub enum Mode { - // Indicates that the exercise should be compiled as a binary - Compile, - // Indicates that the exercise should be compiled as a test harness - Test, - // Indicates that the exercise should be linted with clippy - Clippy, -} - -#[derive(Deserialize)] -pub struct ExerciseList { - pub exercises: Vec, -} - -// A representation of a rustlings exercise. -// This is deserialized from the accompanying info.toml file -#[derive(Deserialize, Debug)] -pub struct Exercise { - // Name of the exercise - pub name: String, - // The path to the file containing the exercise's source code - pub path: PathBuf, - // The mode of the exercise (Test, Compile, or Clippy) - pub mode: Mode, - // The hint text associated with the exercise - pub hint: String, -} - -// An enum to track of the state of an Exercise. -// An Exercise can be either Done or Pending -#[derive(PartialEq, Debug)] -pub enum State { - // The state of the exercise once it's been completed - Done, - // The state of the exercise while it's not completed yet - Pending(Vec), -} - -// The context information of a pending exercise -#[derive(PartialEq, Debug)] -pub struct ContextLine { - // The source code that is still pending completion - pub line: String, - // The line number of the source code still pending completion - pub number: usize, - // Whether or not this is important - pub important: bool, +use anyhow::Result; +use crossterm::{ + QueueableCommand, + style::{Attribute, Color, ResetColor, SetAttribute, SetForegroundColor}, +}; +use std::io::{self, StdoutLock, Write}; + +use crate::{ + cmd::CmdRunner, + term::{self, CountedWrite, file_path, terminal_file_link, write_ansi}, +}; + +/// The initial capacity of the output buffer. +pub const OUTPUT_CAPACITY: usize = 1 << 14; + +pub fn solution_link_line( + stdout: &mut StdoutLock, + solution_path: &str, + emit_file_links: bool, +) -> io::Result<()> { + stdout.queue(SetAttribute(Attribute::Bold))?; + stdout.write_all(b"Solution")?; + stdout.queue(ResetColor)?; + stdout.write_all(b" for comparison: ")?; + file_path(stdout, Color::Cyan, |writer| { + if emit_file_links && let Some(canonical_path) = term::canonicalize(solution_path) { + terminal_file_link(writer, solution_path, &canonical_path) + } else { + writer.stdout().write_all(solution_path.as_bytes()) + } + })?; + stdout.write_all(b"\n") } -// The result of compiling an exercise -pub struct CompiledExercise<'a> { - exercise: &'a Exercise, - _handle: FileHandle, -} +// Run an exercise binary and append its output to the `output` buffer. +// Compilation must be done before calling this method. +fn run_bin( + bin_name: &str, + mut output: Option<&mut Vec>, + cmd_runner: &CmdRunner, +) -> Result { + if let Some(output) = output.as_deref_mut() { + write_ansi(output, SetAttribute(Attribute::Underlined)); + output.extend_from_slice(b"Output"); + write_ansi(output, ResetColor); + output.push(b'\n'); + } -impl<'a> CompiledExercise<'a> { - // Run the compiled exercise - pub fn run(&self) -> Result { - self.exercise.run() + let success = cmd_runner.run_debug_bin(bin_name, output.as_deref_mut())?; + + if let Some(output) = output + && !success + { + // This output is important to show the user that something went wrong. + // Otherwise, calling something like `exit(1)` in an exercise without further output + // leaves the user confused about why the exercise isn't done yet. + write_ansi(output, SetAttribute(Attribute::Bold)); + write_ansi(output, SetForegroundColor(Color::Red)); + output.extend_from_slice(b"The exercise didn't run successfully (nonzero exit code)"); + write_ansi(output, ResetColor); + output.push(b'\n'); } -} -// A representation of an already executed binary -#[derive(Debug)] -pub struct ExerciseOutput { - // The textual contents of the standard output of the binary - pub stdout: String, - // The textual contents of the standard error of the binary - pub stderr: String, + Ok(success) } -struct FileHandle; - -impl Drop for FileHandle { - fn drop(&mut self) { - clean(); - } +/// See `info_file::ExerciseInfo` +pub struct Exercise { + pub dir: Option<&'static str>, + pub name: &'static str, + /// Path of the exercise file starting with the `exercises/` directory. + pub path: &'static str, + pub canonical_path: Option, + pub test: bool, + pub strict_clippy: bool, + pub hint: &'static str, + pub done: bool, } impl Exercise { - pub fn compile(&self) -> Result { - let cmd = match self.mode { - Mode::Compile => Command::new("rustc") - .args(&[self.path.to_str().unwrap(), "-o", &temp_file()]) - .args(RUSTC_COLOR_ARGS) - .output(), - Mode::Test => Command::new("rustc") - .args(&["--test", self.path.to_str().unwrap(), "-o", &temp_file()]) - .args(RUSTC_COLOR_ARGS) - .output(), - Mode::Clippy => { - let cargo_toml = format!( - r#"[package] -name = "{}" -version = "0.0.1" -edition = "2021" -[[bin]] -name = "{}" -path = "{}.rs""#, - self.name, self.name, self.name - ); - let cargo_toml_error_msg = if env::var("NO_EMOJI").is_ok() { - "Failed to write Clippy Cargo.toml file." - } else { - "Failed to write 📎 Clippy 📎 Cargo.toml file." - }; - fs::write(CLIPPY_CARGO_TOML_PATH, cargo_toml).expect(cargo_toml_error_msg); - // To support the ability to run the clippy exercises, build - // an executable, in addition to running clippy. With a - // compilation failure, this would silently fail. But we expect - // clippy to reflect the same failure while compiling later. - Command::new("rustc") - .args(&[self.path.to_str().unwrap(), "-o", &temp_file()]) - .args(RUSTC_COLOR_ARGS) - .output() - .expect("Failed to compile!"); - // Due to an issue with Clippy, a cargo clean is required to catch all lints. - // See https://github.com/rust-lang/rust-clippy/issues/2604 - // This is already fixed on Clippy's master branch. See this issue to track merging into Cargo: - // https://github.com/rust-lang/rust-clippy/issues/3837 - Command::new("cargo") - .args(&["clean", "--manifest-path", CLIPPY_CARGO_TOML_PATH]) - .args(RUSTC_COLOR_ARGS) - .output() - .expect("Failed to run 'cargo clean'"); - Command::new("cargo") - .args(&["clippy", "--manifest-path", CLIPPY_CARGO_TOML_PATH]) - .args(RUSTC_COLOR_ARGS) - .args(&["--", "-D", "warnings","-D","clippy::float_cmp"]) - .output() + pub fn terminal_file_link<'a>( + &self, + writer: &mut impl CountedWrite<'a>, + emit_file_links: bool, + ) -> io::Result<()> { + file_path(writer, Color::Blue, |writer| { + if emit_file_links && let Some(canonical_path) = self.canonical_path.as_deref() { + terminal_file_link(writer, self.path, canonical_path) + } else { + writer.write_str(self.path) } - } - .expect("Failed to run 'compile' command."); - - if cmd.status.success() { - Ok(CompiledExercise { - exercise: self, - _handle: FileHandle, - }) - } else { - clean(); - Err(ExerciseOutput { - stdout: String::from_utf8_lossy(&cmd.stdout).to_string(), - stderr: String::from_utf8_lossy(&cmd.stderr).to_string(), - }) - } + }) } +} - fn run(&self) -> Result { - let arg = match self.mode { - Mode::Test => "--show-output", - _ => "", - }; - let cmd = Command::new(&temp_file()) - .arg(arg) - .output() - .expect("Failed to run 'run' command"); - - let output = ExerciseOutput { - stdout: String::from_utf8_lossy(&cmd.stdout).to_string(), - stderr: String::from_utf8_lossy(&cmd.stderr).to_string(), - }; - - if cmd.status.success() { - Ok(output) - } else { - Err(output) +pub trait RunnableExercise { + fn name(&self) -> &str; + fn dir(&self) -> Option<&str>; + fn strict_clippy(&self) -> bool; + fn test(&self) -> bool; + + // Compile, check and run the exercise or its solution (depending on `bin_name´). + // The output is written to the `output` buffer after clearing it. + fn run( + &self, + bin_name: &str, + mut output: Option<&mut Vec>, + cmd_runner: &CmdRunner, + ) -> Result { + if let Some(output) = output.as_deref_mut() { + output.clear(); } - } - pub fn state(&self) -> State { - let mut source_file = - File::open(&self.path).expect("We were unable to open the exercise file!"); + let build_success = cmd_runner + .cargo("build", bin_name, output.as_deref_mut()) + .run("cargo build …")?; + if !build_success { + return Ok(false); + } - let source = { - let mut s = String::new(); - source_file - .read_to_string(&mut s) - .expect("We were unable to read the exercise file!"); - s - }; + // Discard the compiler output because it will be shown again by `cargo test` or Clippy. + if let Some(output) = output.as_deref_mut() { + output.clear(); + } - let re = Regex::new(I_AM_DONE_REGEX).unwrap(); + if self.test() { + let output_is_some = output.is_some(); + let mut test_cmd = cmd_runner.cargo("test", bin_name, output.as_deref_mut()); + if output_is_some { + test_cmd.args(["--", "--color", "always", "--format", "pretty"]); + } + let test_success = test_cmd.run("cargo test …")?; + if !test_success { + run_bin(bin_name, output, cmd_runner)?; + return Ok(false); + } - if !re.is_match(&source) { - return State::Done; + // Discard the compiler output because it will be shown again by Clippy. + if let Some(output) = output.as_deref_mut() { + output.clear(); + } } - let matched_line_index = source - .lines() - .enumerate() - .find_map(|(i, line)| if re.is_match(line) { Some(i) } else { None }) - .expect("This should not happen at all"); + let mut clippy_cmd = cmd_runner.cargo("clippy", bin_name, output.as_deref_mut()); - let min_line = ((matched_line_index as i32) - (CONTEXT as i32)).max(0) as usize; - let max_line = matched_line_index + CONTEXT; + // `--profile test` is required to also check code with `#[cfg(test)]`. + if FORCE_STRICT_CLIPPY || self.strict_clippy() { + clippy_cmd.args(["--profile", "test", "--", "-D", "warnings"]); + } else { + clippy_cmd.args(["--profile", "test"]); + } - let context = source - .lines() - .enumerate() - .filter(|&(i, _)| i >= min_line && i <= max_line) - .map(|(i, line)| ContextLine { - line: line.to_string(), - number: i + 1, - important: i == matched_line_index, - }) - .collect(); + let clippy_success = clippy_cmd.run("cargo clippy …")?; + let run_success = run_bin(bin_name, output, cmd_runner)?; - State::Pending(context) + Ok(clippy_success && run_success) } - // Check that the exercise looks to be solved using self.state() - // This is not the best way to check since - // the user can just remove the "I AM NOT DONE" string from the file - // without actually having solved anything. - // The only other way to truly check this would to compile and run - // the exercise; which would be both costly and counterintuitive - pub fn looks_done(&self) -> bool { - self.state() == State::Done + /// Compile, check and run the exercise. + /// The output is written to the `output` buffer after clearing it. + #[inline] + fn run_exercise(&self, output: Option<&mut Vec>, cmd_runner: &CmdRunner) -> Result { + self.run::(self.name(), output, cmd_runner) } -} -impl Display for Exercise { - fn fmt(&self, f: &mut Formatter) -> fmt::Result { - write!(f, "{}", self.path.to_str().unwrap()) - } -} - -#[inline] -fn clean() { - let _ignored = remove_file(&temp_file()); -} + /// Compile, check and run the exercise's solution. + /// The output is written to the `output` buffer after clearing it. + fn run_solution(&self, output: Option<&mut Vec>, cmd_runner: &CmdRunner) -> Result { + let name = self.name(); + let mut bin_name = String::with_capacity(name.len() + 4); + bin_name.push_str(name); + bin_name.push_str("_sol"); -#[cfg(test)] -mod test { - use super::*; - use std::path::Path; - - #[test] - fn test_clean() { - File::create(&temp_file()).unwrap(); - let exercise = Exercise { - name: String::from("example"), - path: PathBuf::from("tests/fixture/state/pending_exercise.rs"), - mode: Mode::Compile, - hint: String::from(""), - }; - let compiled = exercise.compile().unwrap(); - drop(compiled); - assert!(!Path::new(&temp_file()).exists()); + self.run::(&bin_name, output, cmd_runner) } - #[test] - fn test_pending_state() { - let exercise = Exercise { - name: "pending_exercise".into(), - path: PathBuf::from("tests/fixture/state/pending_exercise.rs"), - mode: Mode::Compile, - hint: String::new(), + fn sol_path(&self) -> String { + let name = self.name(); + + let mut path = if let Some(dir) = self.dir() { + // 14 = 10 + 1 + 3 + // solutions/ + / + .rs + let mut path = String::with_capacity(14 + dir.len() + name.len()); + path.push_str("solutions/"); + path.push_str(dir); + path.push('/'); + path + } else { + // 13 = 10 + 3 + // solutions/ + .rs + let mut path = String::with_capacity(13 + name.len()); + path.push_str("solutions/"); + path }; - let state = exercise.state(); - let expected = vec![ - ContextLine { - line: "// fake_exercise".to_string(), - number: 1, - important: false, - }, - ContextLine { - line: "".to_string(), - number: 2, - important: false, - }, - ContextLine { - line: "// I AM NOT DONE".to_string(), - number: 3, - important: true, - }, - ContextLine { - line: "".to_string(), - number: 4, - important: false, - }, - ContextLine { - line: "fn main() {".to_string(), - number: 5, - important: false, - }, - ]; + path.push_str(name); + path.push_str(".rs"); - assert_eq!(state, State::Pending(expected)); + path } +} - #[test] - fn test_finished_exercise() { - let exercise = Exercise { - name: "finished_exercise".into(), - path: PathBuf::from("tests/fixture/state/finished_exercise.rs"), - mode: Mode::Compile, - hint: String::new(), - }; +impl RunnableExercise for Exercise { + #[inline] + fn name(&self) -> &str { + self.name + } - assert_eq!(exercise.state(), State::Done); + #[inline] + fn dir(&self) -> Option<&str> { + self.dir } - #[test] - fn test_exercise_with_output() { - let exercise = Exercise { - name: "exercise_with_output".into(), - path: PathBuf::from("tests/fixture/success/testSuccess.rs"), - mode: Mode::Test, - hint: String::new(), - }; - let out = exercise.compile().unwrap().run().unwrap(); - assert!(out.stdout.contains("THIS TEST TOO SHALL PASS")); + #[inline] + fn strict_clippy(&self) -> bool { + self.strict_clippy + } + + #[inline] + fn test(&self) -> bool { + self.test } } diff --git a/src/info_file.rs b/src/info_file.rs new file mode 100644 index 0000000000..04e5d644a2 --- /dev/null +++ b/src/info_file.rs @@ -0,0 +1,119 @@ +use anyhow::{Context, Error, Result, bail}; +use serde::Deserialize; +use std::{fs, io::ErrorKind}; + +use crate::{embedded::EMBEDDED_FILES, exercise::RunnableExercise}; + +/// Deserialized from the `info.toml` file. +#[derive(Deserialize)] +pub struct ExerciseInfo { + /// Exercise's unique name. + pub name: String, + /// Exercise's directory name inside the `exercises/` directory. + pub dir: Option, + /// Run `cargo test` on the exercise. + #[serde(default = "default_true")] + pub test: bool, + /// Deny all Clippy warnings. + #[serde(default)] + pub strict_clippy: bool, + /// The exercise's hint to be shown to the user on request. + pub hint: String, + /// The exercise is already solved. Ignore it when checking that all exercises are unsolved. + #[serde(default)] + pub skip_check_unsolved: bool, +} +#[inline(always)] +const fn default_true() -> bool { + true +} + +impl ExerciseInfo { + /// Path to the exercise file starting with the `exercises/` directory. + pub fn path(&self) -> String { + let mut path = if let Some(dir) = &self.dir { + // 14 = 10 + 1 + 3 + // exercises/ + / + .rs + let mut path = String::with_capacity(14 + dir.len() + self.name.len()); + path.push_str("exercises/"); + path.push_str(dir); + path.push('/'); + path + } else { + // 13 = 10 + 3 + // exercises/ + .rs + let mut path = String::with_capacity(13 + self.name.len()); + path.push_str("exercises/"); + path + }; + + path.push_str(&self.name); + path.push_str(".rs"); + + path + } +} + +impl RunnableExercise for ExerciseInfo { + #[inline] + fn name(&self) -> &str { + &self.name + } + + #[inline] + fn dir(&self) -> Option<&str> { + self.dir.as_deref() + } + + #[inline] + fn strict_clippy(&self) -> bool { + self.strict_clippy + } + + #[inline] + fn test(&self) -> bool { + self.test + } +} + +/// The deserialized `info.toml` file. +#[derive(Deserialize)] +pub struct InfoFile { + /// For possible breaking changes in the future for community exercises. + pub format_version: u8, + /// Shown to users when starting with the exercises. + pub welcome_message: Option, + /// Shown to users after finishing all exercises. + pub final_message: Option, + /// List of all exercises. + pub exercises: Vec, +} + +impl InfoFile { + /// Official exercises: Parse the embedded `info.toml` file. + /// Community exercises: Parse the `info.toml` file in the current directory. + pub fn parse() -> Result { + // Read a local `info.toml` if it exists. + let slf = match fs::read_to_string("info.toml") { + Ok(file_content) => toml::de::from_str::(&file_content) + .context("Failed to parse the `info.toml` file")?, + Err(e) => { + if e.kind() == ErrorKind::NotFound { + return toml::de::from_str(EMBEDDED_FILES.info_file) + .context("Failed to parse the embedded `info.toml` file"); + } + + return Err(Error::from(e).context("Failed to read the `info.toml` file")); + } + }; + + if slf.exercises.is_empty() { + bail!("{NO_EXERCISES_ERR}"); + } + + Ok(slf) + } +} + +const NO_EXERCISES_ERR: &str = "There are no exercises yet! +Add at least one exercise before testing."; diff --git a/src/init.rs b/src/init.rs new file mode 100644 index 0000000000..16ea35e8b7 --- /dev/null +++ b/src/init.rs @@ -0,0 +1,224 @@ +use anyhow::{Context, Result, bail}; +use crossterm::{ + QueueableCommand, + style::{Attribute, Color, ResetColor, SetAttribute, SetForegroundColor}, +}; +use serde::Deserialize; +use std::{ + env::set_current_dir, + fs::{self, create_dir}, + io::{self, Write}, + path::{Path, PathBuf}, + process::{Command, Stdio}, +}; + +use crate::{ + cargo_toml::updated_cargo_toml, embedded::EMBEDDED_FILES, exercise::RunnableExercise, + info_file::InfoFile, term::press_enter_prompt, +}; + +#[derive(Deserialize)] +struct CargoLocateProject { + root: PathBuf, +} + +pub fn init() -> Result<()> { + let rustlings_dir = Path::new("rustlings"); + if rustlings_dir.exists() { + bail!(RUSTLINGS_DIR_ALREADY_EXISTS_ERR); + } + + let locate_project_output = Command::new("cargo") + .arg("locate-project") + .arg("-q") + .arg("--workspace") + .stdin(Stdio::null()) + .stderr(Stdio::null()) + .output() + .context( + "Failed to run the command `cargo locate-project …`\n\ + Did you already install Rust?\n\ + Try running `cargo --version` to diagnose the problem.", + )?; + + if !Command::new("cargo") + .arg("clippy") + .arg("--version") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .context("Failed to run the command `cargo clippy --version`")? + .success() + { + bail!( + "Clippy, the official Rust linter, is missing.\n\ + Please install it first before initializing Rustlings." + ) + } + + let mut stdout = io::stdout().lock(); + let mut init_git = true; + + if locate_project_output.status.success() { + if Path::new("exercises").exists() && Path::new("solutions").exists() { + bail!(IN_INITIALIZED_DIR_ERR); + } + + let workspace_manifest = + serde_json::de::from_slice::(&locate_project_output.stdout) + .context( + "Failed to read the field `root` from the output of `cargo locate-project …`", + )? + .root; + + let workspace_manifest_content = fs::read_to_string(&workspace_manifest) + .with_context(|| format!("Failed to read the file {}", workspace_manifest.display()))?; + if !workspace_manifest_content.contains("[workspace]") + && !workspace_manifest_content.contains("workspace.") + { + bail!( + "The current directory is already part of a Cargo project.\n\ + Please initialize Rustlings in a different directory" + ); + } + + stdout.write_all(b"This command will create the directory `rustlings/` as a member of this Cargo workspace.\n\ + Press ENTER to continue ")?; + press_enter_prompt(&mut stdout)?; + + // Make sure "rustlings" is added to `workspace.members` by making + // Cargo initialize a new project. + let status = Command::new("cargo") + .arg("new") + .arg("-q") + .arg("--vcs") + .arg("none") + .arg("rustlings") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .status()?; + if !status.success() { + bail!( + "Failed to initialize a new Cargo workspace member.\n\ + Please initialize Rustlings in a different directory" + ); + } + + stdout.write_all(b"The directory `rustlings` has been added to `workspace.members` in the `Cargo.toml` file of this Cargo workspace.\n")?; + fs::remove_dir_all("rustlings") + .context("Failed to remove the temporary directory `rustlings/`")?; + init_git = false; + } else { + stdout.write_all(b"This command will create the directory `rustlings/` which will contain the exercises.\n\ + Press ENTER to continue ")?; + press_enter_prompt(&mut stdout)?; + } + + create_dir(rustlings_dir).context("Failed to create the `rustlings/` directory")?; + set_current_dir(rustlings_dir) + .context("Failed to change the current directory to `rustlings/`")?; + + let info_file = InfoFile::parse()?; + EMBEDDED_FILES + .init_exercises_dir(&info_file.exercises) + .context("Failed to initialize the `rustlings/exercises` directory")?; + + create_dir("solutions").context("Failed to create the `solutions/` directory")?; + fs::write( + "solutions/README.md", + include_bytes!("../solutions/README.md"), + ) + .context("Failed to create the file rustlings/solutions/README.md")?; + for dir in EMBEDDED_FILES.exercise_dirs { + let mut dir_path = String::with_capacity(10 + dir.name.len()); + dir_path.push_str("solutions/"); + dir_path.push_str(dir.name); + create_dir(&dir_path) + .with_context(|| format!("Failed to create the directory {dir_path}"))?; + } + for exercise_info in &info_file.exercises { + let solution_path = exercise_info.sol_path(); + fs::write(&solution_path, INIT_SOLUTION_FILE) + .with_context(|| format!("Failed to create the file {solution_path}"))?; + } + + let current_cargo_toml = include_str!("../dev-Cargo.toml"); + // Skip the first line (comment). + let newline_ind = current_cargo_toml + .as_bytes() + .iter() + .position(|c| *c == b'\n') + .context("The embedded `Cargo.toml` is empty or contains only one line")?; + let current_cargo_toml = current_cargo_toml + .get(newline_ind + 1..) + .context("The embedded `Cargo.toml` contains only one line")?; + let updated_cargo_toml = updated_cargo_toml(&info_file.exercises, current_cargo_toml, b"") + .context("Failed to generate `Cargo.toml`")?; + fs::write("Cargo.toml", updated_cargo_toml) + .context("Failed to create the file `rustlings/Cargo.toml`")?; + + fs::write("rust-analyzer.toml", RUST_ANALYZER_TOML) + .context("Failed to create the file `rustlings/rust-analyzer.toml`")?; + + fs::write(".gitignore", GITIGNORE) + .context("Failed to create the file `rustlings/.gitignore`")?; + + create_dir(".vscode").context("Failed to create the directory `rustlings/.vscode`")?; + fs::write(".vscode/extensions.json", VS_CODE_EXTENSIONS_JSON) + .context("Failed to create the file `rustlings/.vscode/extensions.json`")?; + + if init_git { + // Ignore any Git error because Git initialization is not required. + let _ = Command::new("git") + .arg("init") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); + } + + stdout.queue(SetForegroundColor(Color::Green))?; + stdout.write_all("Initialization done ✓".as_bytes())?; + stdout.queue(ResetColor)?; + stdout.write_all(b"\n\n")?; + + stdout.queue(SetAttribute(Attribute::Bold))?; + stdout.write_all(POST_INIT_MSG)?; + stdout.queue(ResetColor)?; + + Ok(()) +} + +const INIT_SOLUTION_FILE: &[u8] = b"fn main() { + // DON'T EDIT THIS SOLUTION FILE! + // It will be automatically filled after you finish the exercise. +} +"; + +pub const RUST_ANALYZER_TOML: &[u8] = br#"check.command = "clippy" +check.extraArgs = ["--profile", "test"] +cargo.targetDir = true +"#; + +const GITIGNORE: &[u8] = b"Cargo.lock +target/ +.vscode/ +"; + +pub const VS_CODE_EXTENSIONS_JSON: &[u8] = br#"{"recommendations":["rust-lang.rust-analyzer"]}"#; + +const IN_INITIALIZED_DIR_ERR: &str = "It looks like Rustlings is already initialized in this directory. + +If you already initialized Rustlings, run the command `rustlings` for instructions on getting started with the exercises. +Otherwise, please run `rustlings init` again in a different directory."; + +const RUSTLINGS_DIR_ALREADY_EXISTS_ERR: &str = + "A directory with the name `rustlings` already exists in the current directory. +You probably already initialized Rustlings. +Run `cd rustlings` +Then run `rustlings` again"; + +const POST_INIT_MSG: &[u8] = b"Run `cd rustlings` to go into the generated directory. +Then run `rustlings` to get started. +"; diff --git a/src/list.rs b/src/list.rs new file mode 100644 index 0000000000..a2eee9e16a --- /dev/null +++ b/src/list.rs @@ -0,0 +1,134 @@ +use anyhow::{Context, Result}; +use crossterm::{ + QueueableCommand, cursor, + event::{ + self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind, MouseEventKind, + }, + terminal::{ + DisableLineWrap, EnableLineWrap, EnterAlternateScreen, LeaveAlternateScreen, + disable_raw_mode, enable_raw_mode, + }, +}; +use std::io::{self, StdoutLock, Write}; + +use crate::app_state::AppState; + +use self::state::{Filter, ListState}; + +mod scroll_state; +mod state; + +fn handle_list(app_state: &mut AppState, stdout: &mut StdoutLock) -> Result<()> { + let mut list_state = ListState::build(app_state, stdout)?; + let mut is_searching = false; + + loop { + match event::read().context("Failed to read terminal event")? { + Event::Key(key) => { + match key.kind { + KeyEventKind::Release => continue, + KeyEventKind::Press | KeyEventKind::Repeat => (), + } + + list_state.message.clear(); + + if is_searching { + match key.code { + KeyCode::Esc | KeyCode::Enter => { + is_searching = false; + list_state.search_query.clear(); + } + KeyCode::Char(c) => { + list_state.search_query.push(c); + list_state.apply_search_query(); + } + KeyCode::Backspace => { + list_state.search_query.pop(); + list_state.apply_search_query(); + } + _ => continue, + } + + list_state.draw(stdout)?; + continue; + } + + match key.code { + KeyCode::Char('q') => return Ok(()), + KeyCode::Down | KeyCode::Char('j') => list_state.select_next(), + KeyCode::Up | KeyCode::Char('k') => list_state.select_previous(), + KeyCode::Home | KeyCode::Char('g') => list_state.select_first(), + KeyCode::End | KeyCode::Char('G') => list_state.select_last(), + KeyCode::Char('d') => { + if list_state.filter() == Filter::Done { + list_state.set_filter(Filter::None); + list_state.message.push_str("Disabled filter DONE"); + } else { + list_state.set_filter(Filter::Done); + list_state.message.push_str( + "Enabled filter DONE │ Press d again to disable the filter", + ); + } + } + KeyCode::Char('p') => { + if list_state.filter() == Filter::Pending { + list_state.set_filter(Filter::None); + list_state.message.push_str("Disabled filter PENDING"); + } else { + list_state.set_filter(Filter::Pending); + list_state.message.push_str( + "Enabled filter PENDING │ Press p again to disable the filter", + ); + } + } + KeyCode::Char('r') => list_state.reset_selected()?, + KeyCode::Char('c') => { + if list_state.selected_to_current_exercise()? { + return Ok(()); + } + } + KeyCode::Char('s' | '/') => { + is_searching = true; + list_state.apply_search_query(); + } + // Redraw to remove the message. + KeyCode::Esc => (), + _ => continue, + } + } + Event::Mouse(event) => match event.kind { + MouseEventKind::ScrollDown => list_state.select_next(), + MouseEventKind::ScrollUp => list_state.select_previous(), + _ => continue, + }, + Event::Resize(width, height) => list_state.set_term_size(width, height), + // Ignore + Event::FocusGained | Event::FocusLost => continue, + } + + list_state.draw(stdout)?; + } +} + +pub fn list(app_state: &mut AppState) -> Result<()> { + let mut stdout = io::stdout().lock(); + stdout + .queue(EnterAlternateScreen)? + .queue(cursor::Hide)? + .queue(DisableLineWrap)? + .queue(EnableMouseCapture)?; + enable_raw_mode()?; + + let res = handle_list(app_state, &mut stdout); + + // Restore the terminal even if we got an error. + stdout + .queue(LeaveAlternateScreen)? + .queue(cursor::Show)? + .queue(EnableLineWrap)? + .queue(DisableMouseCapture)? + .flush()?; + disable_raw_mode()?; + + res +} diff --git a/src/list/scroll_state.rs b/src/list/scroll_state.rs new file mode 100644 index 0000000000..2c02ed4f7e --- /dev/null +++ b/src/list/scroll_state.rs @@ -0,0 +1,104 @@ +pub struct ScrollState { + n_rows: usize, + max_n_rows_to_display: usize, + selected: Option, + offset: usize, + scroll_padding: usize, + max_scroll_padding: usize, +} + +impl ScrollState { + pub fn new(n_rows: usize, selected: Option, max_scroll_padding: usize) -> Self { + Self { + n_rows, + max_n_rows_to_display: 0, + selected, + offset: selected.map_or(0, |selected| selected.saturating_sub(max_scroll_padding)), + scroll_padding: 0, + max_scroll_padding, + } + } + + #[inline] + pub fn offset(&self) -> usize { + self.offset + } + + fn update_offset(&mut self) { + let Some(selected) = self.selected else { + return; + }; + + let min_offset = (selected + self.scroll_padding) + .saturating_sub(self.max_n_rows_to_display.saturating_sub(1)); + let max_offset = selected.saturating_sub(self.scroll_padding); + let global_max_offset = self.n_rows.saturating_sub(self.max_n_rows_to_display); + + self.offset = self + .offset + .max(min_offset) + .min(max_offset) + .min(global_max_offset); + } + + #[inline] + pub fn selected(&self) -> Option { + self.selected + } + + pub fn set_selected(&mut self, selected: usize) { + self.selected = Some(selected); + self.update_offset(); + } + + pub fn select_next(&mut self) { + if let Some(selected) = self.selected { + self.set_selected((selected + 1).min(self.n_rows - 1)); + } + } + + pub fn select_previous(&mut self) { + if let Some(selected) = self.selected { + self.set_selected(selected.saturating_sub(1)); + } + } + + pub fn select_first(&mut self) { + if self.n_rows > 0 { + self.set_selected(0); + } + } + + pub fn select_last(&mut self) { + if self.n_rows > 0 { + self.set_selected(self.n_rows - 1); + } + } + + pub fn set_n_rows(&mut self, n_rows: usize) { + self.n_rows = n_rows; + + if self.n_rows == 0 { + self.selected = None; + return; + } + + self.set_selected(self.selected.map_or(0, |selected| selected.min(n_rows - 1))); + } + + #[inline] + fn update_scroll_padding(&mut self) { + self.scroll_padding = (self.max_n_rows_to_display / 4).min(self.max_scroll_padding); + } + + #[inline] + pub fn max_n_rows_to_display(&self) -> usize { + self.max_n_rows_to_display + } + + pub fn set_max_n_rows_to_display(&mut self, max_n_rows_to_display: usize) { + self.max_n_rows_to_display = max_n_rows_to_display; + self.update_scroll_padding(); + self.update_offset(); + } +} diff --git a/src/list/state.rs b/src/list/state.rs new file mode 100644 index 0000000000..4fd1301d6b --- /dev/null +++ b/src/list/state.rs @@ -0,0 +1,417 @@ +use anyhow::{Context, Result}; +use crossterm::{ + QueueableCommand, + cursor::{MoveTo, MoveToNextLine}, + style::{ + Attribute, Attributes, Color, ResetColor, SetAttribute, SetAttributes, SetForegroundColor, + }, + terminal::{self, BeginSynchronizedUpdate, Clear, ClearType, EndSynchronizedUpdate}, +}; +use std::{ + fmt::Write as _, + io::{self, StdoutLock, Write}, +}; + +use crate::{ + app_state::AppState, + exercise::Exercise, + term::{CountedWrite, MaxLenWriter, progress_bar}, +}; + +use super::scroll_state::ScrollState; + +const COL_SPACING: usize = 2; +const SELECTED_ROW_ATTRIBUTES: Attributes = Attributes::none() + .with(Attribute::Reverse) + .with(Attribute::Bold); + +fn next_ln(stdout: &mut StdoutLock) -> io::Result<()> { + stdout + .queue(Clear(ClearType::UntilNewLine))? + .queue(MoveToNextLine(1))?; + Ok(()) +} + +#[derive(Copy, Clone, PartialEq, Eq)] +pub enum Filter { + Done, + Pending, + None, +} + +pub struct ListState<'a> { + /// Footer message to be displayed if not empty. + pub message: String, + pub search_query: String, + app_state: &'a mut AppState, + scroll_state: ScrollState, + name_col_padding: Vec, + path_col_padding: Vec, + filter: Filter, + term_width: u16, + term_height: u16, + show_footer: bool, +} + +impl<'a> ListState<'a> { + pub fn build(app_state: &'a mut AppState, stdout: &mut StdoutLock) -> Result { + stdout.queue(Clear(ClearType::All))?; + + let name_col_title_len = 4; + let path_col_title_len = 4; + let (name_col_width, path_col_width) = app_state.exercises().iter().fold( + (name_col_title_len, path_col_title_len), + |(name_col_width, path_col_width), exercise| { + ( + name_col_width.max(exercise.name.len()), + path_col_width.max(exercise.path.len()), + ) + }, + ); + let name_col_padding = vec![b' '; name_col_width + COL_SPACING]; + let path_col_padding = vec![b' '; path_col_width]; + + let filter = Filter::None; + let n_rows_with_filter = app_state.exercises().len(); + let selected = app_state.current_exercise_ind(); + + let (width, height) = terminal::size().context("Failed to get the terminal size")?; + let scroll_state = ScrollState::new(n_rows_with_filter, Some(selected), 5); + + let mut slf = Self { + message: String::with_capacity(128), + search_query: String::new(), + app_state, + scroll_state, + name_col_padding, + path_col_padding, + filter, + // Set by `set_term_size` + term_width: 0, + term_height: 0, + show_footer: true, + }; + + slf.set_term_size(width, height); + slf.draw(stdout)?; + + Ok(slf) + } + + pub fn set_term_size(&mut self, width: u16, height: u16) { + self.term_width = width; + self.term_height = height; + + if height == 0 { + return; + } + + let header_height = 1; + // 1 progress bar, 2 footer message lines. + let footer_height = 3; + self.show_footer = height > header_height + footer_height; + + self.scroll_state.set_max_n_rows_to_display( + height.saturating_sub(header_height + u16::from(self.show_footer) * footer_height) + as usize, + ); + } + + fn draw_exercise_name(&self, writer: &mut MaxLenWriter, exercise: &Exercise) -> io::Result<()> { + if !self.search_query.is_empty() + && let Some((pre_highlight, highlight, post_highlight)) = exercise + .name + .find(&self.search_query) + .and_then(|ind| exercise.name.split_at_checked(ind)) + .and_then(|(pre_highlight, rest)| { + rest.split_at_checked(self.search_query.len()) + .map(|x| (pre_highlight, x.0, x.1)) + }) + { + writer.write_str(pre_highlight)?; + writer.stdout.queue(SetForegroundColor(Color::Magenta))?; + writer.write_str(highlight)?; + writer.stdout.queue(SetForegroundColor(Color::Reset))?; + return writer.write_str(post_highlight); + } + + writer.write_str(exercise.name) + } + + fn draw_rows( + &self, + stdout: &mut StdoutLock, + filtered_exercises: impl Iterator, + ) -> io::Result { + let current_exercise_ind = self.app_state.current_exercise_ind(); + let row_offset = self.scroll_state.offset(); + let mut n_displayed_rows = 0; + + for (exercise_ind, exercise) in filtered_exercises + .skip(row_offset) + .take(self.scroll_state.max_n_rows_to_display()) + { + let mut writer = MaxLenWriter::new(stdout, self.term_width as usize); + + if self.scroll_state.selected() == Some(row_offset + n_displayed_rows) { + // The crab emoji has the width of two ascii chars. + writer.add_to_len(2); + writer.stdout.write_all("🦀".as_bytes())?; + writer + .stdout + .queue(SetAttributes(SELECTED_ROW_ATTRIBUTES))?; + } else { + writer.write_ascii(b" ")?; + } + + if exercise_ind == current_exercise_ind { + writer.stdout.queue(SetForegroundColor(Color::Red))?; + writer.write_ascii(b">>>>>>> ")?; + } else { + writer.write_ascii(b" ")?; + } + + if exercise.done { + writer.stdout.queue(SetForegroundColor(Color::Green))?; + writer.write_ascii(b"DONE ")?; + } else { + writer.stdout.queue(SetForegroundColor(Color::Yellow))?; + writer.write_ascii(b"PENDING")?; + } + writer.stdout.queue(SetForegroundColor(Color::Reset))?; + writer.write_ascii(b" ")?; + + self.draw_exercise_name(&mut writer, exercise)?; + + writer.write_ascii(&self.name_col_padding[exercise.name.len()..])?; + + exercise.terminal_file_link(&mut writer, self.app_state.emit_file_links())?; + + writer.write_ascii(&self.path_col_padding[exercise.path.len()..])?; + + next_ln(stdout)?; + stdout.queue(ResetColor)?; + n_displayed_rows += 1; + } + + Ok(n_displayed_rows) + } + + pub fn draw(&mut self, stdout: &mut StdoutLock) -> io::Result<()> { + if self.term_height == 0 { + return Ok(()); + } + + stdout.queue(BeginSynchronizedUpdate)?.queue(MoveTo(0, 0))?; + + // Header + let mut writer = MaxLenWriter::new(stdout, self.term_width as usize); + writer.write_ascii(b" Current State Name")?; + writer.write_ascii(&self.name_col_padding[4..])?; + writer.write_ascii(b"Path")?; + next_ln(stdout)?; + + // Rows + let iter = self.app_state.exercises().iter().enumerate(); + let n_displayed_rows = match self.filter { + Filter::Done => self.draw_rows(stdout, iter.filter(|(_, exercise)| exercise.done))?, + Filter::Pending => { + self.draw_rows(stdout, iter.filter(|(_, exercise)| !exercise.done))? + } + Filter::None => self.draw_rows(stdout, iter)?, + }; + + for _ in 0..self.scroll_state.max_n_rows_to_display() - n_displayed_rows { + next_ln(stdout)?; + } + + if self.show_footer { + progress_bar( + &mut MaxLenWriter::new(stdout, self.term_width as usize), + self.app_state.n_done(), + self.app_state.exercises().len() as u16, + self.term_width, + )?; + next_ln(stdout)?; + + let mut writer = MaxLenWriter::new(stdout, self.term_width as usize); + if self.message.is_empty() { + // Help footer message + if self.scroll_state.selected().is_some() { + writer.write_str("↓/j ↑/k home/g end/G | ontinue at | eset exercise")?; + next_ln(stdout)?; + writer = MaxLenWriter::new(stdout, self.term_width as usize); + + writer.write_ascii(b"earch | filter ")?; + } else { + // Nothing selected (and nothing shown), so only display filter and quit. + writer.write_ascii(b"filter ")?; + } + + match self.filter { + Filter::Done => { + writer + .stdout + .queue(SetForegroundColor(Color::Magenta))? + .queue(SetAttribute(Attribute::Underlined))?; + writer.write_ascii(b"one")?; + writer.stdout.queue(ResetColor)?; + writer.write_ascii(b"/

ending")?; + } + Filter::Pending => { + writer.write_ascii(b"one/")?; + writer + .stdout + .queue(SetForegroundColor(Color::Magenta))? + .queue(SetAttribute(Attribute::Underlined))?; + writer.write_ascii(b"

ending")?; + writer.stdout.queue(ResetColor)?; + } + Filter::None => writer.write_ascii(b"one/

ending")?, + } + + writer.write_ascii(b" | uit list")?; + } else { + writer.stdout.queue(SetForegroundColor(Color::Magenta))?; + writer.write_str(&self.message)?; + stdout.queue(ResetColor)?; + next_ln(stdout)?; + } + + next_ln(stdout)?; + } + + stdout.queue(EndSynchronizedUpdate)?.flush() + } + + fn update_rows(&mut self) { + let n_rows = match self.filter { + Filter::Done => self + .app_state + .exercises() + .iter() + .filter(|exercise| exercise.done) + .count(), + Filter::Pending => self + .app_state + .exercises() + .iter() + .filter(|exercise| !exercise.done) + .count(), + Filter::None => self.app_state.exercises().len(), + }; + + self.scroll_state.set_n_rows(n_rows); + } + + #[inline] + pub fn filter(&self) -> Filter { + self.filter + } + + pub fn set_filter(&mut self, filter: Filter) { + self.filter = filter; + self.update_rows(); + } + + #[inline] + pub fn select_next(&mut self) { + self.scroll_state.select_next(); + } + + #[inline] + pub fn select_previous(&mut self) { + self.scroll_state.select_previous(); + } + + #[inline] + pub fn select_first(&mut self) { + self.scroll_state.select_first(); + } + + #[inline] + pub fn select_last(&mut self) { + self.scroll_state.select_last(); + } + + fn selected_to_exercise_ind(&self, selected: usize) -> Result { + match self.filter { + Filter::Done => self + .app_state + .exercises() + .iter() + .enumerate() + .filter(|(_, exercise)| exercise.done) + .nth(selected) + .context("Invalid selection index") + .map(|(ind, _)| ind), + Filter::Pending => self + .app_state + .exercises() + .iter() + .enumerate() + .filter(|(_, exercise)| !exercise.done) + .nth(selected) + .context("Invalid selection index") + .map(|(ind, _)| ind), + Filter::None => Ok(selected), + } + } + + pub fn reset_selected(&mut self) -> Result<()> { + let Some(selected) = self.scroll_state.selected() else { + self.message.push_str("Nothing selected to reset!"); + return Ok(()); + }; + + let exercise_ind = self.selected_to_exercise_ind(selected)?; + let exercise_name = self.app_state.reset_exercise_by_ind(exercise_ind)?; + self.update_rows(); + write!( + self.message, + "The exercise `{exercise_name}` has been reset", + )?; + + Ok(()) + } + + pub fn apply_search_query(&mut self) { + self.message.push_str("search:"); + self.message.push_str(&self.search_query); + self.message.push('|'); + + if self.search_query.is_empty() { + return; + } + + let is_search_result = |exercise: &Exercise| exercise.name.contains(&self.search_query); + let mut iter = self.app_state.exercises().iter(); + let ind = match self.filter { + Filter::None => iter.position(is_search_result), + Filter::Done => iter + .filter(|exercise| exercise.done) + .position(is_search_result), + Filter::Pending => iter + .filter(|exercise| !exercise.done) + .position(is_search_result), + }; + + match ind { + Some(exercise_ind) => self.scroll_state.set_selected(exercise_ind), + None => self.message.push_str(" (not found)"), + } + } + + // Return `true` if there was something to select. + pub fn selected_to_current_exercise(&mut self) -> Result { + let Some(selected) = self.scroll_state.selected() else { + self.message.push_str("Nothing selected to continue at!"); + return Ok(false); + }; + + let exercise_ind = self.selected_to_exercise_ind(selected)?; + self.app_state.set_current_exercise_ind(exercise_ind)?; + + Ok(true) + } +} diff --git a/src/main.rs b/src/main.rs index 8eebc08660..ffd2dfa75b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,475 +1,217 @@ -use crate::exercise::{Exercise, ExerciseList}; -use crate::project::RustAnalyzerProject; -use crate::run::{reset, run}; -use crate::verify::verify; -use argh::FromArgs; -use console::Emoji; -use notify::DebouncedEvent; -use notify::{RecommendedWatcher, RecursiveMode, Watcher}; -use std::ffi::OsStr; -use std::fs; -use std::io::{self, prelude::*}; -use std::path::Path; -use std::process::{Command, Stdio}; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::mpsc::{channel, RecvTimeoutError}; -use std::sync::{Arc, Mutex}; -use std::thread; -use std::time::Duration; - -#[macro_use] -mod ui; - +use anyhow::{Context, Result, bail}; +use app_state::StateFileStatus; +use clap::{Parser, Subcommand}; +use std::{ + io::{self, IsTerminal, Write}, + path::Path, + process::ExitCode, +}; +use term::{clear_terminal, press_enter_prompt}; + +use self::{app_state::AppState, dev::DevCommands, info_file::InfoFile}; + +mod app_state; +mod cargo_toml; +mod cmd; +mod dev; +mod embedded; mod exercise; -mod project; +mod info_file; +mod init; +mod list; mod run; -mod verify; +mod term; +mod watch; -// In sync with crate version -const VERSION: &str = "5.2.0"; +const CURRENT_FORMAT_VERSION: u8 = 1; -#[derive(FromArgs, PartialEq, Debug)] /// Rustlings is a collection of small exercises to get you used to writing and reading Rust code +#[derive(Parser)] +#[command(version)] struct Args { - /// show outputs from the test exercises - #[argh(switch)] - nocapture: bool, - /// show the executable version - #[argh(switch, short = 'v')] - version: bool, - #[argh(subcommand)] - nested: Option, + #[command(subcommand)] + command: Option, + /// Manually run the current exercise using `r` in the watch mode. + /// Only use this if Rustlings fails to detect exercise file changes. + #[arg(long)] + manual_run: bool, } -#[derive(FromArgs, PartialEq, Debug)] -#[argh(subcommand)] +#[derive(Subcommand)] enum Subcommands { - Verify(VerifyArgs), - Watch(WatchArgs), - Run(RunArgs), - Reset(ResetArgs), - Hint(HintArgs), - List(ListArgs), - Lsp(LspArgs), -} - -#[derive(FromArgs, PartialEq, Debug)] -#[argh(subcommand, name = "verify")] -/// Verifies all exercises according to the recommended order -struct VerifyArgs {} - -#[derive(FromArgs, PartialEq, Debug)] -#[argh(subcommand, name = "watch")] -/// Reruns `verify` when files were edited -struct WatchArgs {} - -#[derive(FromArgs, PartialEq, Debug)] -#[argh(subcommand, name = "run")] -/// Runs/Tests a single exercise -struct RunArgs { - #[argh(positional)] - /// the name of the exercise - name: String, -} - -#[derive(FromArgs, PartialEq, Debug)] -#[argh(subcommand, name = "reset")] -/// Resets a single exercise using "git stash -- " -struct ResetArgs { - #[argh(positional)] - /// the name of the exercise - name: String, + /// Initialize the official Rustlings exercises + Init, + /// Run a single exercise. Runs the next pending exercise if the exercise name is not specified + Run { + /// The name of the exercise + name: Option, + }, + /// Check all the exercises, marking them as done or pending accordingly. + CheckAll, + /// Reset a single exercise + Reset { + /// The name of the exercise + name: String, + }, + /// Show a hint. Shows the hint of the next pending exercise if the exercise name is not specified + Hint { + /// The name of the exercise + name: Option, + }, + /// Commands for developing (community) Rustlings exercises + #[command(subcommand)] + Dev(DevCommands), } -#[derive(FromArgs, PartialEq, Debug)] -#[argh(subcommand, name = "hint")] -/// Returns a hint for the given exercise -struct HintArgs { - #[argh(positional)] - /// the name of the exercise - name: String, -} - -#[derive(FromArgs, PartialEq, Debug)] -#[argh(subcommand, name = "lsp")] -/// Enable rust-analyzer for exercises -struct LspArgs {} +fn main() -> Result { + let args = Args::parse(); -#[derive(FromArgs, PartialEq, Debug)] -#[argh(subcommand, name = "list")] -/// Lists the exercises available in Rustlings -struct ListArgs { - #[argh(switch, short = 'p')] - /// show only the paths of the exercises - paths: bool, - #[argh(switch, short = 'n')] - /// show only the names of the exercises - names: bool, - #[argh(option, short = 'f')] - /// provide a string to match exercise names - /// comma separated patterns are acceptable - filter: Option, - #[argh(switch, short = 'u')] - /// display only exercises not yet solved - unsolved: bool, - #[argh(switch, short = 's')] - /// display only exercises that have been solved - solved: bool, -} + if cfg!(not(debug_assertions)) && Path::new("dev/rustlings-repo.txt").exists() { + bail!("{OLD_METHOD_ERR}"); + } -fn main() { - let args: Args = argh::from_env(); + 'priority_cmd: { + match args.command { + Some(Subcommands::Init) => init::init().context("Initialization failed")?, + Some(Subcommands::Dev(dev_command)) => dev_command.run()?, + _ => break 'priority_cmd, + } - if args.version { - println!("v{}", VERSION); - std::process::exit(0); + return Ok(ExitCode::SUCCESS); } - if args.nested.is_none() { - println!("\n{}\n", WELCOME); + if !Path::new("exercises").is_dir() { + println!("{PRE_INIT_MSG}"); + return Ok(ExitCode::FAILURE); } - if !Path::new("info.toml").exists() { - println!( - "{} must be run from the rustlings directory", - std::env::current_exe().unwrap().to_str().unwrap() - ); - println!("Try `cd rustlings/`!"); - std::process::exit(1); - } + let info_file = InfoFile::parse()?; - if !rustc_exists() { - println!("We cannot find `rustc`."); - println!("Try running `rustc --version` to diagnose your problem."); - println!("For instructions on how to install Rust, check the README."); - std::process::exit(1); + if info_file.format_version > CURRENT_FORMAT_VERSION { + bail!(FORMAT_VERSION_HIGHER_ERR); } - let toml_str = &fs::read_to_string("info.toml").unwrap(); - let exercises = toml::from_str::(toml_str).unwrap().exercises; - let verbose = args.nocapture; - - let command = args.nested.unwrap_or_else(|| { - println!("{}\n", DEFAULT_OUT); - std::process::exit(0); - }); - match command { - Subcommands::List(subargs) => { - if !subargs.paths && !subargs.names { - println!("{:<17}\t{:<46}\t{:<7}", "Name", "Path", "Status"); + let (mut app_state, state_file_status) = AppState::new( + info_file.exercises, + info_file.final_message.unwrap_or_default(), + )?; + + // Show the welcome message if the state file doesn't exist yet. + if let Some(welcome_message) = info_file.welcome_message { + match state_file_status { + StateFileStatus::NotRead => { + let mut stdout = io::stdout().lock(); + clear_terminal(&mut stdout)?; + + let welcome_message = welcome_message.trim_ascii(); + write!( + stdout, + "{welcome_message}\n\n\ + Press ENTER to continue " + )?; + press_enter_prompt(&mut stdout)?; + clear_terminal(&mut stdout)?; + // Flush to be able to show errors occurring before printing a newline to stdout. + stdout.flush()?; } - let mut exercises_done: u16 = 0; - let filters = subargs.filter.clone().unwrap_or_default().to_lowercase(); - exercises.iter().for_each(|e| { - let fname = format!("{}", e.path.display()); - let filter_cond = filters - .split(',') - .filter(|f| !f.trim().is_empty()) - .any(|f| e.name.contains(&f) || fname.contains(&f)); - let status = if e.looks_done() { - exercises_done += 1; - "Done" - } else { - "Pending" - }; - let solve_cond = { - (e.looks_done() && subargs.solved) - || (!e.looks_done() && subargs.unsolved) - || (!subargs.solved && !subargs.unsolved) - }; - if solve_cond && (filter_cond || subargs.filter.is_none()) { - let line = if subargs.paths { - format!("{}\n", fname) - } else if subargs.names { - format!("{}\n", e.name) - } else { - format!("{:<17}\t{:<46}\t{:<7}\n", e.name, fname, status) - }; - // Somehow using println! leads to the binary panicking - // when its output is piped. - // So, we're handling a Broken Pipe error and exiting with 0 anyway - let stdout = std::io::stdout(); - { - let mut handle = stdout.lock(); - handle.write_all(line.as_bytes()).unwrap_or_else(|e| { - match e.kind() { - std::io::ErrorKind::BrokenPipe => std::process::exit(0), - _ => std::process::exit(1), - }; - }); - } - } - }); - let percentage_progress = exercises_done as f32 / exercises.len() as f32 * 100.0; - println!( - "Progress: You completed {} / {} exercises ({:.2} %).", - exercises_done, - exercises.len(), - percentage_progress - ); - std::process::exit(0); - } - - Subcommands::Run(subargs) => { - let exercise = find_exercise(&subargs.name, &exercises); - - run(exercise, verbose).unwrap_or_else(|_| std::process::exit(1)); - } - - Subcommands::Reset(subargs) => { - let exercise = find_exercise(&subargs.name, &exercises); - - reset(exercise).unwrap_or_else(|_| std::process::exit(1)); - } - - Subcommands::Hint(subargs) => { - let exercise = find_exercise(&subargs.name, &exercises); - - println!("{}", exercise.hint); - } - - Subcommands::Verify(_subargs) => { - verify(&exercises, (0, exercises.len()), verbose) - .unwrap_or_else(|_| std::process::exit(1)); + StateFileStatus::Read => (), } + } - Subcommands::Lsp(_subargs) => { - let mut project = RustAnalyzerProject::new(); - project - .get_sysroot_src() - .expect("Couldn't find toolchain path, do you have `rustc` installed?"); - project - .exercies_to_json() - .expect("Couldn't parse rustlings exercises files"); + match args.command { + None => { + if !io::stdout().is_terminal() { + bail!("Unsupported or missing terminal/TTY"); + } - if project.crates.is_empty() { - println!("Failed find any exercises, make sure you're in the `rustlings` folder"); - } else if project.write_to_disk().is_err() { - println!("Failed to write rust-project.json to disk for rust-analyzer"); + let notify_exercise_names = if args.manual_run { + None } else { - println!("Successfully generated rust-project.json"); - println!("rust-analyzer will now parse exercises, restart your language server or editor") - } + // For the notify event handler thread. + // Leaking is not a problem because the slice lives until the end of the program. + Some( + &*app_state + .exercises() + .iter() + .map(|exercise| exercise.name.as_bytes()) + .collect::>() + .leak(), + ) + }; + + watch::watch(&mut app_state, notify_exercise_names)?; } - - Subcommands::Watch(_subargs) => match watch(&exercises, verbose) { - Err(e) => { - println!( - "Error: Could not watch your progress. Error message was {:?}.", - e - ); - println!("Most likely you've run out of disk space or your 'inotify limit' has been reached."); - std::process::exit(1); - } - Ok(WatchStatus::Finished) => { - println!( - "{emoji} All exercises completed! {emoji}", - emoji = Emoji("🎉", "★") - ); - println!("\n{}\n", FENISH_LINE); + Some(Subcommands::Run { name }) => { + if let Some(name) = name { + app_state.set_current_exercise_by_name(&name)?; } - Ok(WatchStatus::Unfinished) => { - println!("We hope you're enjoying learning about Rust!"); - println!("If you want to continue working on the exercises at a later point, you can simply run `rustlings watch` again"); - } - }, - } -} + return run::run(&mut app_state); + } + Some(Subcommands::CheckAll) => { + let mut stdout = io::stdout().lock(); + if let Some(first_pending_exercise_ind) = app_state.check_all_exercises(&mut stdout)? { + if app_state.current_exercise().done { + app_state.set_current_exercise_ind(first_pending_exercise_ind)?; + } -fn spawn_watch_shell( - failed_exercise_hint: &Arc>>, - should_quit: Arc, -) { - let failed_exercise_hint = Arc::clone(failed_exercise_hint); - println!("Welcome to watch mode! You can type 'help' to get an overview of the commands you can use here."); - thread::spawn(move || loop { - let mut input = String::new(); - match io::stdin().read_line(&mut input) { - Ok(_) => { - let input = input.trim(); - if input == "hint" { - if let Some(hint) = &*failed_exercise_hint.lock().unwrap() { - println!("{}", hint); - } - } else if input == "clear" { - println!("\x1B[2J\x1B[1;1H"); - } else if input.eq("quit") { - should_quit.store(true, Ordering::SeqCst); - println!("Bye!"); - } else if input.eq("help") { - println!("Commands available to you in watch mode:"); - println!(" hint - prints the current exercise's hint"); - println!(" clear - clears the screen"); - println!(" quit - quits watch mode"); - println!(" help - displays this help message"); - println!(); - println!("Watch mode automatically re-evaluates the current exercise"); - println!("when you edit a file's contents.") + stdout.write_all(b"\n\n")?; + let pending = app_state.n_pending(); + if pending == 1 { + stdout.write_all(b"One exercise pending: ")?; } else { - println!("unknown command: {}", input); + write!( + stdout, + "{pending}/{} exercises pending. The first: ", + app_state.exercises().len(), + )?; } - } - Err(error) => println!("error reading command: {}", error), - } - }); -} - -fn find_exercise<'a>(name: &str, exercises: &'a [Exercise]) -> &'a Exercise { - if name.eq("next") { - exercises - .iter() - .find(|e| !e.looks_done()) - .unwrap_or_else(|| { - println!("🎉 Congratulations! You have done all the exercises!"); - println!("🔚 There are no more exercises to do next!"); - std::process::exit(1) - }) - } else { - exercises - .iter() - .find(|e| e.name == name) - .unwrap_or_else(|| { - println!("No exercise found for '{}'!", name); - std::process::exit(1) - }) - } -} - -enum WatchStatus { - Finished, - Unfinished, -} + app_state + .current_exercise() + .terminal_file_link(&mut stdout, app_state.emit_file_links())?; + stdout.write_all(b"\n")?; -fn watch(exercises: &[Exercise], verbose: bool) -> notify::Result { - /* Clears the terminal with an ANSI escape code. - Works in UNIX and newer Windows terminals. */ - fn clear_screen() { - println!("\x1Bc"); - } - - let (tx, rx) = channel(); - let should_quit = Arc::new(AtomicBool::new(false)); - - let mut watcher: RecommendedWatcher = Watcher::new(tx, Duration::from_secs(2))?; - watcher.watch(Path::new("./exercises"), RecursiveMode::Recursive)?; - - clear_screen(); - - let to_owned_hint = |t: &Exercise| t.hint.to_owned(); - let failed_exercise_hint = match verify(exercises.iter(), (0, exercises.len()), verbose) { - Ok(_) => return Ok(WatchStatus::Finished), - Err(exercise) => Arc::new(Mutex::new(Some(to_owned_hint(exercise)))), - }; - spawn_watch_shell(&failed_exercise_hint, Arc::clone(&should_quit)); - loop { - match rx.recv_timeout(Duration::from_secs(1)) { - Ok(event) => match event { - DebouncedEvent::Create(b) | DebouncedEvent::Chmod(b) | DebouncedEvent::Write(b) => { - if b.extension() == Some(OsStr::new("rs")) && b.exists() { - let filepath = b.as_path().canonicalize().unwrap(); - let pending_exercises = exercises - .iter() - .find(|e| filepath.ends_with(&e.path)) - .into_iter() - .chain( - exercises - .iter() - .filter(|e| !e.looks_done() && !filepath.ends_with(&e.path)), - ); - let num_done = exercises.iter().filter(|e| e.looks_done()).count(); - clear_screen(); - match verify(pending_exercises, (num_done, exercises.len()), verbose) { - Ok(_) => return Ok(WatchStatus::Finished), - Err(exercise) => { - let mut failed_exercise_hint = failed_exercise_hint.lock().unwrap(); - *failed_exercise_hint = Some(to_owned_hint(exercise)); - } - } - } - } - _ => {} - }, - Err(RecvTimeoutError::Timeout) => { - // the timeout expired, just check the `should_quit` variable below then loop again + return Ok(ExitCode::FAILURE); + } else { + app_state.render_final_message(&mut stdout)?; } - Err(e) => println!("watch error: {:?}", e), } - // Check if we need to exit - if should_quit.load(Ordering::SeqCst) { - return Ok(WatchStatus::Unfinished); + Some(Subcommands::Reset { name }) => { + app_state.set_current_exercise_by_name(&name)?; + let exercise_path = app_state.reset_current_exercise()?; + println!("The exercise {exercise_path} has been reset"); + } + Some(Subcommands::Hint { name }) => { + if let Some(name) = name { + app_state.set_current_exercise_by_name(&name)?; + } + println!("{}", app_state.current_exercise().hint); } + // Handled in an earlier match. + Some(Subcommands::Init | Subcommands::Dev(_)) => (), } -} -fn rustc_exists() -> bool { - Command::new("rustc") - .args(&["--version"]) - .stdout(Stdio::null()) - .spawn() - .and_then(|mut child| child.wait()) - .map(|status| status.success()) - .unwrap_or(false) + Ok(ExitCode::SUCCESS) } -const DEFAULT_OUT: &str = r#"Thanks for installing Rustlings! - -Is this your first time? Don't worry, Rustlings was made for beginners! We are -going to teach you a lot of things about Rust, but before we can get -started, here's a couple of notes about how Rustlings operates: - -1. The central concept behind Rustlings is that you solve exercises. These - exercises usually have some sort of syntax error in them, which will cause - them to fail compilation or testing. Sometimes there's a logic error instead - of a syntax error. No matter what error, it's your job to find it and fix it! - You'll know when you fixed it because then, the exercise will compile and - Rustlings will be able to move on to the next exercise. -2. If you run Rustlings in watch mode (which we recommend), it'll automatically - start with the first exercise. Don't get confused by an error message popping - up as soon as you run Rustlings! This is part of the exercise that you're - supposed to solve, so open the exercise file in an editor and start your - detective work! -3. If you're stuck on an exercise, there is a helpful hint you can view by typing - 'hint' (in watch mode), or running `rustlings hint exercise_name`. -4. If an exercise doesn't make sense to you, feel free to open an issue on GitHub! - (https://github.com/rust-lang/rustlings/issues/new). We look at every issue, - and sometimes, other learners do too so you can help each other out! -5. If you want to use `rust-analyzer` with exercises, which provides features like - autocompletion, run the command `rustlings lsp`. - -Got all that? Great! To get started, run `rustlings watch` in order to get the first -exercise. Make sure to have your editor open!"#; +const OLD_METHOD_ERR: &str = + "You are trying to run Rustlings using the old method before version 6. +The new method doesn't include cloning the Rustlings' repository. +Please follow the instructions in `README.md`: +https://github.com/rust-lang/rustlings#getting-started"; -const FENISH_LINE: &str = r#"+----------------------------------------------------+ -| You made it to the Fe-nish line! | -+-------------------------- ------------------------+ - \\/ - ▒▒ ▒▒▒▒▒▒▒▒ ▒▒▒▒▒▒▒▒ ▒▒ - ▒▒▒▒ ▒▒ ▒▒ ▒▒ ▒▒ ▒▒ ▒▒ ▒▒▒▒ - ▒▒▒▒ ▒▒ ▒▒ ▒▒ ▒▒ ▒▒ ▒▒▒▒ - ░░▒▒▒▒░░▒▒ ▒▒ ▒▒ ▒▒ ▒▒░░▒▒▒▒ - ▓▓▓▓▓▓▓▓ ▓▓ ▓▓██ ▓▓ ▓▓██ ▓▓ ▓▓▓▓▓▓▓▓ - ▒▒▒▒ ▒▒ ████ ▒▒ ████ ▒▒░░ ▒▒▒▒ - ▒▒ ▒▒▒▒▒▒ ▒▒▒▒▒▒ ▒▒▒▒▒▒ ▒▒ - ▒▒▒▒▒▒▒▒▒▒▓▓▓▓▓▓▒▒▒▒▒▒▒▒▓▓▒▒▓▓▒▒▒▒▒▒▒▒ - ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ - ▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒ - ▒▒ ▒▒▒▒▒▒▒▒▒▒██████▒▒▒▒▒▒▒▒▒▒ ▒▒ - ▒▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒ - ▒▒ ▒▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒ ▒▒ - ▒▒ ▒▒ ▒▒ ▒▒ ▒▒ ▒▒ - ▒▒ ▒▒ ▒▒ ▒▒ +const FORMAT_VERSION_HIGHER_ERR: &str = + "The format version specified in the `info.toml` file is higher than the last one supported. +It is possible that you have an outdated version of Rustlings. +Try to install the latest Rustlings version first."; -We hope you enjoyed learning about the various aspects of Rust! -If you noticed any issues, please don't hesitate to report them to our repo. -You can also contribute your own exercises to help the greater community! - -Before reporting an issue or contributing, please read our guidelines: -https://github.com/rust-lang/rustlings/blob/main/CONTRIBUTING.md"#; - -const WELCOME: &str = r#" welcome to... +const PRE_INIT_MSG: &str = r" + Welcome to... _ _ _ _ __ _ _ ___| |_| (_)_ __ __ _ ___ | '__| | | / __| __| | | '_ \ / _` / __| | | | |_| \__ \ |_| | | | | | (_| \__ \ |_| \__,_|___/\__|_|_|_| |_|\__, |___/ - |___/"#; + |___/ + +The `exercises/` directory couldn't be found in the current directory. +If you are just starting with Rustlings, run the command `rustlings init` to initialize it."; diff --git a/src/project.rs b/src/project.rs deleted file mode 100644 index 0df00b9a2d..0000000000 --- a/src/project.rs +++ /dev/null @@ -1,90 +0,0 @@ -use glob::glob; -use serde::{Deserialize, Serialize}; -use std::error::Error; -use std::process::Command; - -/// Contains the structure of resulting rust-project.json file -/// and functions to build the data required to create the file -#[derive(Serialize, Deserialize)] -pub struct RustAnalyzerProject { - sysroot_src: String, - pub crates: Vec, -} - -#[derive(Serialize, Deserialize)] -pub struct Crate { - root_module: String, - edition: String, - deps: Vec, - cfg: Vec, -} - -impl RustAnalyzerProject { - pub fn new() -> RustAnalyzerProject { - RustAnalyzerProject { - sysroot_src: String::new(), - crates: Vec::new(), - } - } - - /// Write rust-project.json to disk - pub fn write_to_disk(&self) -> Result<(), std::io::Error> { - std::fs::write( - "./rust-project.json", - serde_json::to_vec(&self).expect("Failed to serialize to JSON"), - )?; - Ok(()) - } - - /// If path contains .rs extension, add a crate to `rust-project.json` - fn path_to_json(&mut self, path: String) { - if let Some((_, ext)) = path.split_once('.') { - if ext == "rs" { - self.crates.push(Crate { - root_module: path, - edition: "2021".to_string(), - deps: Vec::new(), - // This allows rust_analyzer to work inside #[test] blocks - cfg: vec!["test".to_string()], - }) - } - } - } - - /// Parse the exercises folder for .rs files, any matches will create - /// a new `crate` in rust-project.json which allows rust-analyzer to - /// treat it like a normal binary - pub fn exercies_to_json(&mut self) -> Result<(), Box> { - for e in glob("./exercises/**/*")? { - let path = e?.to_string_lossy().to_string(); - self.path_to_json(path); - } - Ok(()) - } - - /// Use `rustc` to determine the default toolchain - pub fn get_sysroot_src(&mut self) -> Result<(), Box> { - let toolchain = Command::new("rustc") - .arg("--print") - .arg("sysroot") - .output()? - .stdout; - - let toolchain = String::from_utf8_lossy(&toolchain); - let mut whitespace_iter = toolchain.split_whitespace(); - - let toolchain = whitespace_iter.next().unwrap_or(&toolchain); - - println!("Determined toolchain: {}\n", &toolchain); - - self.sysroot_src = (std::path::Path::new(&*toolchain) - .join("lib") - .join("rustlib") - .join("src") - .join("rust") - .join("library") - .to_string_lossy()) - .to_string(); - Ok(()) - } -} diff --git a/src/run.rs b/src/run.rs index 826f00a638..b473fc2062 100644 --- a/src/run.rs +++ b/src/run.rs @@ -1,73 +1,60 @@ -use std::process::Command; - -use crate::exercise::{Exercise, Mode}; -use crate::verify::test; -use indicatif::ProgressBar; - -// Invoke the rust compiler on the path of the given exercise, -// and run the ensuing binary. -// The verbose argument helps determine whether or not to show -// the output from the test harnesses (if the mode of the exercise is test) -pub fn run(exercise: &Exercise, verbose: bool) -> Result<(), ()> { - match exercise.mode { - Mode::Test => test(exercise, verbose)?, - Mode::Compile => compile_and_run(exercise)?, - Mode::Clippy => compile_and_run(exercise)?, +use anyhow::Result; +use crossterm::{ + QueueableCommand, + style::{Color, ResetColor, SetForegroundColor}, +}; +use std::{ + io::{self, Write}, + process::ExitCode, +}; + +use crate::{ + app_state::{AppState, ExercisesProgress}, + exercise::{OUTPUT_CAPACITY, RunnableExercise, solution_link_line}, +}; + +pub fn run(app_state: &mut AppState) -> Result { + let exercise = app_state.current_exercise(); + let mut output = Vec::with_capacity(OUTPUT_CAPACITY); + let success = exercise.run_exercise(Some(&mut output), app_state.cmd_runner())?; + + let mut stdout = io::stdout().lock(); + stdout.write_all(&output)?; + + if !success { + app_state.set_pending(app_state.current_exercise_ind())?; + + stdout.write_all(b"Ran ")?; + app_state + .current_exercise() + .terminal_file_link(&mut stdout, app_state.emit_file_links())?; + stdout.write_all(b" with errors\n")?; + + return Ok(ExitCode::FAILURE); } - Ok(()) -} -// Resets the exercise by stashing the changes. -pub fn reset(exercise: &Exercise) -> Result<(), ()> { - let command = Command::new("git") - .args(["stash", "--"]) - .arg(&exercise.path) - .spawn(); + stdout.queue(SetForegroundColor(Color::Green))?; + stdout.write_all("✓ Successfully ran ".as_bytes())?; + stdout.write_all(exercise.path.as_bytes())?; + stdout.queue(ResetColor)?; + stdout.write_all(b"\n")?; - match command { - Ok(_) => Ok(()), - Err(_) => Err(()), + if let Some(solution_path) = app_state.current_solution_path()? { + stdout.write_all(b"\n")?; + solution_link_line(&mut stdout, &solution_path, app_state.emit_file_links())?; + stdout.write_all(b"\n")?; } -} - -// Invoke the rust compiler on the path of the given exercise -// and run the ensuing binary. -// This is strictly for non-test binaries, so output is displayed -fn compile_and_run(exercise: &Exercise) -> Result<(), ()> { - let progress_bar = ProgressBar::new_spinner(); - progress_bar.set_message(format!("Compiling {}...", exercise)); - progress_bar.enable_steady_tick(100); - let compilation_result = exercise.compile(); - let compilation = match compilation_result { - Ok(compilation) => compilation, - Err(output) => { - progress_bar.finish_and_clear(); - warn!( - "Compilation of {} failed!, Compiler error message:\n", - exercise - ); - println!("{}", output.stderr); - return Err(()); - } - }; - - progress_bar.set_message(format!("Running {}...", exercise)); - let result = compilation.run(); - progress_bar.finish_and_clear(); - - match result { - Ok(output) => { - println!("{}", output.stdout); - success!("Successfully ran {}", exercise); - Ok(()) - } - Err(output) => { - println!("{}", output.stdout); - println!("{}", output.stderr); - - warn!("Ran {} with errors", exercise); - Err(()) + match app_state.done_current_exercise::(&mut stdout)? { + ExercisesProgress::NewPending | ExercisesProgress::CurrentPending => { + stdout.write_all(b"Next exercise: ")?; + app_state + .current_exercise() + .terminal_file_link(&mut stdout, app_state.emit_file_links())?; + stdout.write_all(b"\n")?; } + ExercisesProgress::AllDone => (), } + + Ok(ExitCode::SUCCESS) } diff --git a/src/term.rs b/src/term.rs new file mode 100644 index 0000000000..3d149b33e8 --- /dev/null +++ b/src/term.rs @@ -0,0 +1,319 @@ +use crossterm::{ + Command, QueueableCommand, + cursor::MoveTo, + style::{Attribute, Color, ResetColor, SetAttribute, SetForegroundColor}, + terminal::{Clear, ClearType}, +}; +use std::{ + fmt, fs, + io::{self, BufRead, StdoutLock, Write}, +}; + +use crate::app_state::CheckProgress; + +pub struct MaxLenWriter<'a, 'lock> { + pub stdout: &'a mut StdoutLock<'lock>, + len: usize, + max_len: usize, +} + +impl<'a, 'lock> MaxLenWriter<'a, 'lock> { + #[inline] + pub fn new(stdout: &'a mut StdoutLock<'lock>, max_len: usize) -> Self { + Self { + stdout, + len: 0, + max_len, + } + } + + // Additional is for emojis that take more space. + #[inline] + pub fn add_to_len(&mut self, additional: usize) { + self.len += additional; + } +} + +pub trait CountedWrite<'lock> { + fn write_ascii(&mut self, ascii: &[u8]) -> io::Result<()>; + fn write_str(&mut self, unicode: &str) -> io::Result<()>; + fn stdout(&mut self) -> &mut StdoutLock<'lock>; +} + +impl<'lock> CountedWrite<'lock> for MaxLenWriter<'_, 'lock> { + fn write_ascii(&mut self, ascii: &[u8]) -> io::Result<()> { + let n = ascii.len().min(self.max_len.saturating_sub(self.len)); + if n > 0 { + self.stdout.write_all(&ascii[..n])?; + self.len += n; + } + Ok(()) + } + + fn write_str(&mut self, unicode: &str) -> io::Result<()> { + if let Some((ind, c)) = unicode + .char_indices() + .take(self.max_len.saturating_sub(self.len)) + .last() + { + self.stdout + .write_all(&unicode.as_bytes()[..ind + c.len_utf8()])?; + self.len += ind + 1; + } + + Ok(()) + } + + #[inline] + fn stdout(&mut self) -> &mut StdoutLock<'lock> { + self.stdout + } +} + +impl<'a> CountedWrite<'a> for StdoutLock<'a> { + #[inline] + fn write_ascii(&mut self, ascii: &[u8]) -> io::Result<()> { + self.write_all(ascii) + } + + #[inline] + fn write_str(&mut self, unicode: &str) -> io::Result<()> { + self.write_all(unicode.as_bytes()) + } + + #[inline] + fn stdout(&mut self) -> &mut StdoutLock<'a> { + self + } +} + +pub struct CheckProgressVisualizer<'a, 'lock> { + stdout: &'a mut StdoutLock<'lock>, + n_cols: usize, +} + +impl<'a, 'lock> CheckProgressVisualizer<'a, 'lock> { + const CHECKING_COLOR: Color = Color::Blue; + const DONE_COLOR: Color = Color::Green; + const PENDING_COLOR: Color = Color::Red; + + pub fn build(stdout: &'a mut StdoutLock<'lock>, term_width: u16) -> io::Result { + clear_terminal(stdout)?; + stdout.write_all("Checking all exercises…\n".as_bytes())?; + + // Legend + stdout.write_all(b"Color of exercise number: ")?; + stdout.queue(SetForegroundColor(Self::CHECKING_COLOR))?; + stdout.write_all(b"Checking")?; + stdout.queue(ResetColor)?; + stdout.write_all(b" - ")?; + stdout.queue(SetForegroundColor(Self::DONE_COLOR))?; + stdout.write_all(b"Done")?; + stdout.queue(ResetColor)?; + stdout.write_all(b" - ")?; + stdout.queue(SetForegroundColor(Self::PENDING_COLOR))?; + stdout.write_all(b"Pending")?; + stdout.queue(ResetColor)?; + stdout.write_all(b"\n")?; + + // Exercise numbers with up to 3 digits. + // +1 because the last column doesn't end with a whitespace. + let n_cols = usize::from(term_width + 1) / 4; + + Ok(Self { stdout, n_cols }) + } + + pub fn update(&mut self, progresses: &[CheckProgress]) -> io::Result<()> { + self.stdout.queue(MoveTo(0, 2))?; + + let mut exercise_num = 1; + for exercise_progress in progresses { + match exercise_progress { + CheckProgress::None => (), + CheckProgress::Checking => { + self.stdout + .queue(SetForegroundColor(Self::CHECKING_COLOR))?; + } + CheckProgress::Done => { + self.stdout.queue(SetForegroundColor(Self::DONE_COLOR))?; + } + CheckProgress::Pending => { + self.stdout.queue(SetForegroundColor(Self::PENDING_COLOR))?; + } + } + + write!(self.stdout, "{exercise_num:<3}")?; + self.stdout.queue(ResetColor)?; + + if exercise_num != progresses.len() { + if exercise_num % self.n_cols == 0 { + self.stdout.write_all(b"\n")?; + } else { + self.stdout.write_all(b" ")?; + } + + exercise_num += 1; + } + } + + self.stdout.flush() + } +} + +pub struct ProgressCounter<'a, 'lock> { + stdout: &'a mut StdoutLock<'lock>, + total: usize, + counter: usize, +} + +impl<'a, 'lock> ProgressCounter<'a, 'lock> { + pub fn new(stdout: &'a mut StdoutLock<'lock>, total: usize) -> io::Result { + write!(stdout, "Progress: 0/{total}")?; + stdout.flush()?; + + Ok(Self { + stdout, + total, + counter: 0, + }) + } + + pub fn increment(&mut self) -> io::Result<()> { + self.counter += 1; + write!(self.stdout, "\rProgress: {}/{}", self.counter, self.total)?; + self.stdout.flush() + } +} + +impl Drop for ProgressCounter<'_, '_> { + fn drop(&mut self) { + let _ = self.stdout.write_all(b"\n\n"); + } +} + +pub fn progress_bar<'a>( + writer: &mut impl CountedWrite<'a>, + progress: u16, + total: u16, + term_width: u16, +) -> io::Result<()> { + debug_assert!(total <= 999); + debug_assert!(progress <= total); + + const PREFIX: &[u8] = b"Progress: ["; + const PREFIX_WIDTH: u16 = PREFIX.len() as u16; + const POSTFIX_WIDTH: u16 = "] xxx/xxx".len() as u16; + const WRAPPER_WIDTH: u16 = PREFIX_WIDTH + POSTFIX_WIDTH; + const MIN_LINE_WIDTH: u16 = WRAPPER_WIDTH + 4; + + if term_width < MIN_LINE_WIDTH { + writer.write_ascii(b"Progress: ")?; + // Integers are in ASCII. + return writer.write_ascii(format!("{progress}/{total}").as_bytes()); + } + + let stdout = writer.stdout(); + stdout.write_all(PREFIX)?; + + let width = term_width - WRAPPER_WIDTH; + let filled = (width * progress) / total; + + stdout.queue(SetForegroundColor(Color::Green))?; + for _ in 0..filled { + stdout.write_all(b"#")?; + } + + if filled < width { + stdout.write_all(b">")?; + } + + let width_minus_filled = width - filled; + if width_minus_filled > 1 { + let red_part_width = width_minus_filled - 1; + stdout.queue(SetForegroundColor(Color::Red))?; + for _ in 0..red_part_width { + stdout.write_all(b"-")?; + } + } + + stdout.queue(SetForegroundColor(Color::Reset))?; + + write!(stdout, "] {progress:>3}/{total}") +} + +pub fn clear_terminal(stdout: &mut StdoutLock) -> io::Result<()> { + stdout + .queue(MoveTo(0, 0))? + .queue(Clear(ClearType::All))? + .queue(Clear(ClearType::Purge)) + .map(|_| ()) +} + +pub fn press_enter_prompt(stdout: &mut StdoutLock) -> io::Result<()> { + stdout.flush()?; + io::stdin().lock().read_until(b'\n', &mut Vec::new())?; + stdout.write_all(b"\n") +} + +/// Canonicalize, convert to string and remove verbatim part on Windows. +pub fn canonicalize(path: &str) -> Option { + fs::canonicalize(path) + .ok()? + .into_os_string() + .into_string() + .ok() + .map(|mut path| { + // Windows itself can't handle its verbatim paths. + if cfg!(windows) && path.as_bytes().starts_with(br"\\?\") { + path.drain(..4); + } + + path + }) +} + +pub fn file_path<'a, W: CountedWrite<'a>>( + writer: &mut W, + color: Color, + f: impl FnOnce(&mut W) -> io::Result<()>, +) -> io::Result<()> { + writer + .stdout() + .queue(SetForegroundColor(color))? + .queue(SetAttribute(Attribute::Underlined))?; + + f(writer)?; + + writer + .stdout() + .queue(SetForegroundColor(Color::Reset))? + .queue(SetAttribute(Attribute::NoUnderline))?; + + Ok(()) +} + +pub fn terminal_file_link<'a>( + writer: &mut impl CountedWrite<'a>, + path: &str, + canonical_path: &str, +) -> io::Result<()> { + writer.stdout().write_all(b"\x1b]8;;file://")?; + writer.stdout().write_all(canonical_path.as_bytes())?; + writer.stdout().write_all(b"\x1b\\")?; + // Only this part is visible. + writer.write_str(path)?; + writer.stdout().write_all(b"\x1b]8;;\x1b\\") +} + +pub fn write_ansi(output: &mut Vec, command: impl Command) { + struct FmtWriter<'a>(&'a mut Vec); + + impl fmt::Write for FmtWriter<'_> { + fn write_str(&mut self, s: &str) -> fmt::Result { + self.0.extend_from_slice(s.as_bytes()); + Ok(()) + } + } + + let _ = command.write_ansi(&mut FmtWriter(output)); +} diff --git a/src/ui.rs b/src/ui.rs deleted file mode 100644 index 1ee463168d..0000000000 --- a/src/ui.rs +++ /dev/null @@ -1,33 +0,0 @@ -macro_rules! warn { - ($fmt:literal, $ex:expr) => {{ - use console::{style, Emoji}; - use std::env; - let formatstr = format!($fmt, $ex); - if env::var("NO_EMOJI").is_ok() { - println!("{} {}", style("!").red(), style(formatstr).red()); - } else { - println!( - "{} {}", - style(Emoji("⚠️ ", "!")).red(), - style(formatstr).red() - ); - } - }}; -} - -macro_rules! success { - ($fmt:literal, $ex:expr) => {{ - use console::{style, Emoji}; - use std::env; - let formatstr = format!($fmt, $ex); - if env::var("NO_EMOJI").is_ok() { - println!("{} {}", style("✓").green(), style(formatstr).green()); - } else { - println!( - "{} {}", - style(Emoji("✅", "✓")).green(), - style(formatstr).green() - ); - } - }}; -} diff --git a/src/verify.rs b/src/verify.rs deleted file mode 100644 index 6f877831dc..0000000000 --- a/src/verify.rs +++ /dev/null @@ -1,208 +0,0 @@ -use crate::exercise::{CompiledExercise, Exercise, Mode, State}; -use console::style; -use indicatif::{ProgressBar, ProgressStyle}; -use std::env; - -// Verify that the provided container of Exercise objects -// can be compiled and run without any failures. -// Any such failures will be reported to the end user. -// If the Exercise being verified is a test, the verbose boolean -// determines whether or not the test harness outputs are displayed. -pub fn verify<'a>( - exercises: impl IntoIterator, - progress: (usize, usize), - verbose: bool, -) -> Result<(), &'a Exercise> { - let (num_done, total) = progress; - let bar = ProgressBar::new(total as u64); - bar.set_style(ProgressStyle::default_bar() - .template("Progress: [{bar:60.green/red}] {pos}/{len}") - .progress_chars("#>-") - ); - bar.set_position(num_done as u64); - for exercise in exercises { - let compile_result = match exercise.mode { - Mode::Test => compile_and_test(exercise, RunMode::Interactive, verbose), - Mode::Compile => compile_and_run_interactively(exercise), - Mode::Clippy => compile_only(exercise), - }; - if !compile_result.unwrap_or(false) { - return Err(exercise); - } - bar.inc(1); - } - Ok(()) -} - -enum RunMode { - Interactive, - NonInteractive, -} - -// Compile and run the resulting test harness of the given Exercise -pub fn test(exercise: &Exercise, verbose: bool) -> Result<(), ()> { - compile_and_test(exercise, RunMode::NonInteractive, verbose)?; - Ok(()) -} - -// Invoke the rust compiler without running the resulting binary -fn compile_only(exercise: &Exercise) -> Result { - let progress_bar = ProgressBar::new_spinner(); - progress_bar.set_message(format!("Compiling {}...", exercise)); - progress_bar.enable_steady_tick(100); - - let _ = compile(exercise, &progress_bar)?; - progress_bar.finish_and_clear(); - - Ok(prompt_for_completion(exercise, None)) -} - -// Compile the given Exercise and run the resulting binary in an interactive mode -fn compile_and_run_interactively(exercise: &Exercise) -> Result { - let progress_bar = ProgressBar::new_spinner(); - progress_bar.set_message(format!("Compiling {}...", exercise)); - progress_bar.enable_steady_tick(100); - - let compilation = compile(exercise, &progress_bar)?; - - progress_bar.set_message(format!("Running {}...", exercise)); - let result = compilation.run(); - progress_bar.finish_and_clear(); - - let output = match result { - Ok(output) => output, - Err(output) => { - warn!("Ran {} with errors", exercise); - println!("{}", output.stdout); - println!("{}", output.stderr); - return Err(()); - } - }; - - Ok(prompt_for_completion(exercise, Some(output.stdout))) -} - -// Compile the given Exercise as a test harness and display -// the output if verbose is set to true -fn compile_and_test(exercise: &Exercise, run_mode: RunMode, verbose: bool) -> Result { - let progress_bar = ProgressBar::new_spinner(); - progress_bar.set_message(format!("Testing {}...", exercise)); - progress_bar.enable_steady_tick(100); - - let compilation = compile(exercise, &progress_bar)?; - let result = compilation.run(); - progress_bar.finish_and_clear(); - - match result { - Ok(output) => { - if verbose { - println!("{}", output.stdout); - } - if let RunMode::Interactive = run_mode { - Ok(prompt_for_completion(exercise, None)) - } else { - Ok(true) - } - } - Err(output) => { - warn!( - "Testing of {} failed! Please try again. Here's the output:", - exercise - ); - println!("{}", output.stdout); - Err(()) - } - } -} - -// Compile the given Exercise and return an object with information -// about the state of the compilation -fn compile<'a, 'b>( - exercise: &'a Exercise, - progress_bar: &'b ProgressBar, -) -> Result, ()> { - let compilation_result = exercise.compile(); - - match compilation_result { - Ok(compilation) => Ok(compilation), - Err(output) => { - progress_bar.finish_and_clear(); - warn!( - "Compiling of {} failed! Please try again. Here's the output:", - exercise - ); - println!("{}", output.stderr); - Err(()) - } - } -} - -fn prompt_for_completion(exercise: &Exercise, prompt_output: Option) -> bool { - let context = match exercise.state() { - State::Done => return true, - State::Pending(context) => context, - }; - - match exercise.mode { - Mode::Compile => success!("Successfully ran {}!", exercise), - Mode::Test => success!("Successfully tested {}!", exercise), - Mode::Clippy => success!("Successfully compiled {}!", exercise), - } - - let no_emoji = env::var("NO_EMOJI").is_ok(); - - let clippy_success_msg = if no_emoji { - "The code is compiling, and Clippy is happy!" - } else { - "The code is compiling, and 📎 Clippy 📎 is happy!" - }; - - let success_msg = match exercise.mode { - Mode::Compile => "The code is compiling!", - Mode::Test => "The code is compiling, and the tests pass!", - Mode::Clippy => clippy_success_msg, - }; - - println!(); - if no_emoji { - println!("~*~ {} ~*~", success_msg) - } else { - println!("🎉 🎉 {} 🎉 🎉", success_msg) - } - println!(); - - if let Some(output) = prompt_output { - println!("Output:"); - println!("{}", separator()); - println!("{}", output); - println!("{}", separator()); - println!(); - } - - println!("You can keep working on this exercise,"); - println!( - "or jump into the next one by removing the {} comment:", - style("`I AM NOT DONE`").bold() - ); - println!(); - for context_line in context { - let formatted_line = if context_line.important { - format!("{}", style(context_line.line).bold()) - } else { - context_line.line.to_string() - }; - - println!( - "{:>2} {} {}", - style(context_line.number).blue().bold(), - style("|").blue(), - formatted_line - ); - } - - false -} - -fn separator() -> console::StyledObject<&'static str> { - style("====================").bold() -} diff --git a/src/watch.rs b/src/watch.rs new file mode 100644 index 0000000000..3a56b4b65b --- /dev/null +++ b/src/watch.rs @@ -0,0 +1,190 @@ +use anyhow::{Error, Result}; +use notify::{Config, RecommendedWatcher, RecursiveMode, Watcher}; +use std::{ + io::{self, Write}, + path::Path, + sync::{ + atomic::{AtomicBool, Ordering::Relaxed}, + mpsc::channel, + }, + time::Duration, +}; + +use crate::{ + app_state::{AppState, ExercisesProgress}, + list, +}; + +use self::{notify_event::NotifyEventHandler, state::WatchState, terminal_event::InputEvent}; + +mod notify_event; +mod state; +mod terminal_event; + +static EXERCISE_RUNNING: AtomicBool = AtomicBool::new(false); + +// Private unit type to force using the constructor function. +#[must_use = "When the guard is dropped, the input is unpaused"] +pub struct InputPauseGuard(()); + +impl InputPauseGuard { + #[inline] + pub fn scoped_pause() -> Self { + EXERCISE_RUNNING.store(true, Relaxed); + Self(()) + } +} + +impl Drop for InputPauseGuard { + #[inline] + fn drop(&mut self) { + EXERCISE_RUNNING.store(false, Relaxed); + } +} + +enum WatchEvent { + Input(InputEvent), + FileChange { exercise_ind: usize }, + TerminalResize { width: u16 }, + NotifyErr(notify::Error), + TerminalEventErr(io::Error), +} + +/// Returned by the watch mode to indicate what to do afterwards. +#[must_use] +enum WatchExit { + /// Exit the program. + Shutdown, + /// Enter the list mode and restart the watch mode afterwards. + List, +} + +fn run_watch( + app_state: &mut AppState, + notify_exercise_names: Option<&'static [&'static [u8]]>, +) -> Result { + let (watch_event_sender, watch_event_receiver) = channel(); + + let mut manual_run = false; + // Prevent dropping the guard until the end of the function. + // Otherwise, the file watcher exits. + let _watcher_guard = if let Some(exercise_names) = notify_exercise_names { + let notify_event_handler = + NotifyEventHandler::build(watch_event_sender.clone(), exercise_names)?; + + let mut watcher = RecommendedWatcher::new( + notify_event_handler, + Config::default() + .with_follow_symlinks(false) + .with_poll_interval(Duration::from_secs(1)), + ) + .inspect_err(|_| eprintln!("{NOTIFY_ERR}"))?; + + watcher + .watch(Path::new("exercises"), RecursiveMode::Recursive) + .inspect_err(|_| eprintln!("{NOTIFY_ERR}"))?; + + Some(watcher) + } else { + manual_run = true; + None + }; + + let mut watch_state = WatchState::build(app_state, watch_event_sender, manual_run)?; + let mut stdout = io::stdout().lock(); + + watch_state.run_current_exercise(&mut stdout)?; + + while let Ok(event) = watch_event_receiver.recv() { + match event { + WatchEvent::Input(InputEvent::Next) => match watch_state.next_exercise(&mut stdout)? { + ExercisesProgress::AllDone => break, + ExercisesProgress::NewPending => watch_state.run_current_exercise(&mut stdout)?, + ExercisesProgress::CurrentPending => (), + }, + WatchEvent::Input(InputEvent::Run) => watch_state.run_current_exercise(&mut stdout)?, + WatchEvent::Input(InputEvent::Hint) => watch_state.show_hint(&mut stdout)?, + WatchEvent::Input(InputEvent::List) => return Ok(WatchExit::List), + WatchEvent::Input(InputEvent::CheckAll) => match watch_state + .check_all_exercises(&mut stdout)? + { + ExercisesProgress::AllDone => break, + ExercisesProgress::NewPending => watch_state.run_current_exercise(&mut stdout)?, + ExercisesProgress::CurrentPending => watch_state.render(&mut stdout)?, + }, + WatchEvent::Input(InputEvent::Reset) => watch_state.reset_exercise(&mut stdout)?, + WatchEvent::Input(InputEvent::Quit) => { + stdout.write_all(QUIT_MSG)?; + break; + } + WatchEvent::FileChange { exercise_ind } => { + watch_state.handle_file_change(exercise_ind, &mut stdout)?; + } + WatchEvent::TerminalResize { width } => { + watch_state.update_term_width(width, &mut stdout)?; + } + WatchEvent::NotifyErr(e) => return Err(Error::from(e).context(NOTIFY_ERR)), + WatchEvent::TerminalEventErr(e) => { + return Err(Error::from(e).context("Terminal event listener failed")); + } + } + } + + Ok(WatchExit::Shutdown) +} + +fn watch_list_loop( + app_state: &mut AppState, + notify_exercise_names: Option<&'static [&'static [u8]]>, +) -> Result<()> { + loop { + match run_watch(app_state, notify_exercise_names)? { + WatchExit::Shutdown => break Ok(()), + // It is much easier to exit the watch mode, launch the list mode and then restart + // the watch mode instead of trying to pause the watch threads and correct the + // watch state. + WatchExit::List => list::list(app_state)?, + } + } +} + +/// `notify_exercise_names` as None activates the manual run mode. +pub fn watch( + app_state: &mut AppState, + notify_exercise_names: Option<&'static [&'static [u8]]>, +) -> Result<()> { + #[cfg(not(windows))] + { + let stdin_fd = rustix::stdio::stdin(); + let mut termios = rustix::termios::tcgetattr(stdin_fd)?; + let original_local_modes = termios.local_modes; + // Disable stdin line buffering and hide input. + termios.local_modes -= + rustix::termios::LocalModes::ICANON | rustix::termios::LocalModes::ECHO; + rustix::termios::tcsetattr(stdin_fd, rustix::termios::OptionalActions::Now, &termios)?; + + let res = watch_list_loop(app_state, notify_exercise_names); + + termios.local_modes = original_local_modes; + rustix::termios::tcsetattr(stdin_fd, rustix::termios::OptionalActions::Now, &termios)?; + + res + } + + #[cfg(windows)] + watch_list_loop(app_state, notify_exercise_names) +} + +const QUIT_MSG: &[u8] = b" + +We hope you're enjoying learning Rust! +If you want to continue working on the exercises at a later point, you can simply run `rustlings` again in this directory. +"; + +const NOTIFY_ERR: &str = " +The automatic detection of exercise file changes failed :( +Please try running `rustlings` again. + +If you keep getting this error, run `rustlings --manual-run` to deactivate the file watcher. +You need to manually trigger running the current exercise using `r` then. +"; diff --git a/src/watch/notify_event.rs b/src/watch/notify_event.rs new file mode 100644 index 0000000000..9c05f10dad --- /dev/null +++ b/src/watch/notify_event.rs @@ -0,0 +1,132 @@ +use anyhow::{Context, Result}; +use notify::{ + Event, EventKind, + event::{AccessKind, AccessMode, MetadataKind, ModifyKind, RenameMode}, +}; +use std::{ + sync::{ + atomic::Ordering::Relaxed, + mpsc::{RecvTimeoutError, Sender, SyncSender, sync_channel}, + }, + thread, + time::Duration, +}; + +use super::{EXERCISE_RUNNING, WatchEvent}; + +const DEBOUNCE_DURATION: Duration = Duration::from_millis(200); + +pub struct NotifyEventHandler { + error_sender: Sender, + // Sends the index of the updated exercise. + update_sender: SyncSender, + // Used to report which exercise was modified. + exercise_names: &'static [&'static [u8]], +} + +impl NotifyEventHandler { + pub fn build( + watch_event_sender: Sender, + exercise_names: &'static [&'static [u8]], + ) -> Result { + let (update_sender, update_receiver) = sync_channel(0); + let error_sender = watch_event_sender.clone(); + + // Debouncer + thread::Builder::new() + .spawn(move || { + let mut exercise_updated = vec![false; exercise_names.len()]; + + loop { + match update_receiver.recv_timeout(DEBOUNCE_DURATION) { + Ok(exercise_ind) => exercise_updated[exercise_ind] = true, + Err(RecvTimeoutError::Timeout) => { + for (exercise_ind, updated) in exercise_updated.iter_mut().enumerate() { + if *updated { + if watch_event_sender + .send(WatchEvent::FileChange { exercise_ind }) + .is_err() + { + break; + } + + *updated = false; + } + } + } + Err(RecvTimeoutError::Disconnected) => break, + } + } + }) + .context("Failed to spawn a thread to debounce file changes")?; + + Ok(Self { + error_sender, + update_sender, + exercise_names, + }) + } +} + +impl notify::EventHandler for NotifyEventHandler { + fn handle_event(&mut self, input_event: notify::Result) { + if EXERCISE_RUNNING.load(Relaxed) { + return; + } + + let input_event = match input_event { + Ok(v) => v, + Err(e) => { + // An error occurs when the receiver is dropped. + // After dropping the receiver, the watcher guard should also be dropped. + let _ = self.error_sender.send(WatchEvent::NotifyErr(e)); + return; + } + }; + + match input_event.kind { + EventKind::Any => (), + EventKind::Modify(modify_kind) => match modify_kind { + ModifyKind::Any | ModifyKind::Data(_) => (), + ModifyKind::Name(rename_mode) => match rename_mode { + RenameMode::Any | RenameMode::To => (), + RenameMode::From | RenameMode::Both | RenameMode::Other => return, + }, + ModifyKind::Metadata(metadata_kind) => match metadata_kind { + MetadataKind::Any | MetadataKind::WriteTime => (), + MetadataKind::AccessTime + | MetadataKind::Permissions + | MetadataKind::Ownership + | MetadataKind::Extended + | MetadataKind::Other => return, + }, + ModifyKind::Other => return, + }, + EventKind::Access(access_kind) => match access_kind { + AccessKind::Any => (), + AccessKind::Close(access_mode) => match access_mode { + AccessMode::Any | AccessMode::Write => (), + AccessMode::Execute | AccessMode::Read | AccessMode::Other => return, + }, + AccessKind::Read | AccessKind::Open(_) | AccessKind::Other => return, + }, + EventKind::Create(_) | EventKind::Remove(_) | EventKind::Other => return, + } + + let _ = input_event + .paths + .into_iter() + .filter_map(|path| { + let file_name = path.file_name()?.to_str()?.as_bytes(); + + let [file_name_without_ext @ .., b'.', b'r', b's'] = file_name else { + return None; + }; + + self.exercise_names + .iter() + .position(|exercise_name| *exercise_name == file_name_without_ext) + }) + .try_for_each(|exercise_ind| self.update_sender.send(exercise_ind)); + } +} diff --git a/src/watch/state.rs b/src/watch/state.rs new file mode 100644 index 0000000000..a92dd2d6d7 --- /dev/null +++ b/src/watch/state.rs @@ -0,0 +1,299 @@ +use anyhow::{Context, Result}; +use crossterm::{ + QueueableCommand, + style::{ + Attribute, Attributes, Color, ResetColor, SetAttribute, SetAttributes, SetForegroundColor, + }, + terminal, +}; +use std::{ + io::{self, Read, StdoutLock, Write}, + sync::mpsc::{Sender, SyncSender, sync_channel}, + thread, +}; + +use crate::{ + app_state::{AppState, ExercisesProgress}, + clear_terminal, + exercise::{OUTPUT_CAPACITY, RunnableExercise, solution_link_line}, + term::progress_bar, +}; + +use super::{InputPauseGuard, WatchEvent, terminal_event::terminal_event_handler}; + +const HEADING_ATTRIBUTES: Attributes = Attributes::none() + .with(Attribute::Bold) + .with(Attribute::Underlined); + +#[derive(PartialEq, Eq)] +enum DoneStatus { + DoneWithSolution(String), + DoneWithoutSolution, + Pending, +} + +pub struct WatchState<'a> { + app_state: &'a mut AppState, + output: Vec, + show_hint: bool, + done_status: DoneStatus, + manual_run: bool, + term_width: u16, + terminal_event_unpause_sender: SyncSender<()>, +} + +impl<'a> WatchState<'a> { + pub fn build( + app_state: &'a mut AppState, + watch_event_sender: Sender, + manual_run: bool, + ) -> Result { + let term_width = terminal::size() + .context("Failed to get the terminal size")? + .0; + + let (terminal_event_unpause_sender, terminal_event_unpause_receiver) = sync_channel(0); + + thread::Builder::new() + .spawn(move || { + terminal_event_handler( + watch_event_sender, + terminal_event_unpause_receiver, + manual_run, + ) + }) + .context("Failed to spawn a thread to handle terminal events")?; + + Ok(Self { + app_state, + output: Vec::with_capacity(OUTPUT_CAPACITY), + show_hint: false, + done_status: DoneStatus::Pending, + manual_run, + term_width, + terminal_event_unpause_sender, + }) + } + + pub fn run_current_exercise(&mut self, stdout: &mut StdoutLock) -> Result<()> { + // Ignore any input until running the exercise is done. + let _input_pause_guard = InputPauseGuard::scoped_pause(); + + self.show_hint = false; + + writeln!( + stdout, + "\nChecking the exercise `{}`. Please wait…", + self.app_state.current_exercise().name, + )?; + + let success = self + .app_state + .current_exercise() + .run_exercise(Some(&mut self.output), self.app_state.cmd_runner())?; + self.output.push(b'\n'); + if success { + self.done_status = + if let Some(solution_path) = self.app_state.current_solution_path()? { + DoneStatus::DoneWithSolution(solution_path) + } else { + DoneStatus::DoneWithoutSolution + }; + } else { + self.app_state + .set_pending(self.app_state.current_exercise_ind())?; + + self.done_status = DoneStatus::Pending; + } + + self.render(stdout)?; + Ok(()) + } + + pub fn reset_exercise(&mut self, stdout: &mut StdoutLock) -> Result<()> { + clear_terminal(stdout)?; + + stdout.write_all(b"Resetting will undo all your changes to the file ")?; + stdout.write_all(self.app_state.current_exercise().path.as_bytes())?; + stdout.write_all(b"\nReset (y/n)? ")?; + stdout.flush()?; + + { + let mut stdin = io::stdin().lock(); + let mut answer = [0]; + loop { + stdin + .read_exact(&mut answer) + .context("Failed to read the user's input")?; + + match answer[0] { + b'y' | b'Y' => { + self.app_state.reset_current_exercise()?; + + // The file watcher reruns the exercise otherwise. + if self.manual_run { + self.run_current_exercise(stdout)?; + } + } + b'n' | b'N' => self.render(stdout)?, + _ => continue, + } + + break; + } + } + + self.terminal_event_unpause_sender.send(())?; + + Ok(()) + } + + pub fn handle_file_change( + &mut self, + exercise_ind: usize, + stdout: &mut StdoutLock, + ) -> Result<()> { + if self.app_state.current_exercise_ind() != exercise_ind { + return Ok(()); + } + + self.run_current_exercise(stdout) + } + + /// Move on to the next exercise if the current one is done. + pub fn next_exercise(&mut self, stdout: &mut StdoutLock) -> Result { + match self.done_status { + DoneStatus::DoneWithSolution(_) | DoneStatus::DoneWithoutSolution => (), + DoneStatus::Pending => return Ok(ExercisesProgress::CurrentPending), + } + + self.app_state.done_current_exercise::(stdout) + } + + fn show_prompt(&self, stdout: &mut StdoutLock) -> io::Result<()> { + if self.done_status != DoneStatus::Pending { + stdout.queue(SetAttribute(Attribute::Bold))?; + stdout.write_all(b"n")?; + stdout.queue(ResetColor)?; + stdout.write_all(b":")?; + stdout.queue(SetAttribute(Attribute::Underlined))?; + stdout.write_all(b"next")?; + stdout.queue(ResetColor)?; + stdout.write_all(b" / ")?; + } + + let mut show_key = |key, postfix| { + stdout.queue(SetAttribute(Attribute::Bold))?; + stdout.write_all(&[key])?; + stdout.queue(ResetColor)?; + stdout.write_all(postfix) + }; + + if self.manual_run { + show_key(b'r', b":run / ")?; + } + + if !self.show_hint { + show_key(b'h', b":hint / ")?; + } + + show_key(b'l', b":list / ")?; + show_key(b'c', b":check all / ")?; + show_key(b'x', b":reset / ")?; + show_key(b'q', b":quit ? ")?; + + stdout.flush() + } + + pub fn render(&self, stdout: &mut StdoutLock) -> io::Result<()> { + // Prevent having the first line shifted if clearing wasn't successful. + stdout.write_all(b"\n")?; + clear_terminal(stdout)?; + + stdout.write_all(&self.output)?; + + if self.show_hint { + stdout + .queue(SetAttributes(HEADING_ATTRIBUTES))? + .queue(SetForegroundColor(Color::Cyan))?; + stdout.write_all(b"Hint")?; + stdout.queue(ResetColor)?; + stdout.write_all(b"\n")?; + + stdout.write_all(self.app_state.current_exercise().hint.as_bytes())?; + stdout.write_all(b"\n\n")?; + } + + if self.done_status != DoneStatus::Pending { + stdout + .queue(SetAttribute(Attribute::Bold))? + .queue(SetForegroundColor(Color::Green))?; + stdout.write_all("Exercise done ✓".as_bytes())?; + stdout.queue(ResetColor)?; + stdout.write_all(b"\n")?; + + if let DoneStatus::DoneWithSolution(solution_path) = &self.done_status { + solution_link_line(stdout, solution_path, self.app_state.emit_file_links())?; + } + + stdout.write_all( + "When done experimenting, enter `n` to move on to the next exercise 🦀\n\n" + .as_bytes(), + )?; + } + + progress_bar( + stdout, + self.app_state.n_done(), + self.app_state.exercises().len() as u16, + self.term_width, + )?; + + stdout.write_all(b"\nCurrent exercise: ")?; + self.app_state + .current_exercise() + .terminal_file_link(stdout, self.app_state.emit_file_links())?; + stdout.write_all(b"\n\n")?; + + self.show_prompt(stdout)?; + + Ok(()) + } + + pub fn show_hint(&mut self, stdout: &mut StdoutLock) -> io::Result<()> { + if !self.show_hint { + self.show_hint = true; + self.render(stdout)?; + } + + Ok(()) + } + + pub fn check_all_exercises(&mut self, stdout: &mut StdoutLock) -> Result { + // Ignore any input until checking all exercises is done. + let _input_pause_guard = InputPauseGuard::scoped_pause(); + + if let Some(first_pending_exercise_ind) = self.app_state.check_all_exercises(stdout)? { + // Only change exercise if the current one is done. + if self.app_state.current_exercise().done { + self.app_state + .set_current_exercise_ind(first_pending_exercise_ind)?; + Ok(ExercisesProgress::NewPending) + } else { + Ok(ExercisesProgress::CurrentPending) + } + } else { + self.app_state.render_final_message(stdout)?; + Ok(ExercisesProgress::AllDone) + } + } + + pub fn update_term_width(&mut self, width: u16, stdout: &mut StdoutLock) -> io::Result<()> { + if self.term_width != width { + self.term_width = width; + self.render(stdout)?; + } + + Ok(()) + } +} diff --git a/src/watch/terminal_event.rs b/src/watch/terminal_event.rs new file mode 100644 index 0000000000..2400a3df54 --- /dev/null +++ b/src/watch/terminal_event.rs @@ -0,0 +1,73 @@ +use crossterm::event::{self, Event, KeyCode, KeyEventKind}; +use std::sync::{ + atomic::Ordering::Relaxed, + mpsc::{Receiver, Sender}, +}; + +use super::{EXERCISE_RUNNING, WatchEvent}; + +pub enum InputEvent { + Next, + Run, + Hint, + List, + CheckAll, + Reset, + Quit, +} + +pub fn terminal_event_handler( + sender: Sender, + unpause_receiver: Receiver<()>, + manual_run: bool, +) { + let last_watch_event = loop { + match event::read() { + Ok(Event::Key(key)) => { + match key.kind { + KeyEventKind::Release | KeyEventKind::Repeat => continue, + KeyEventKind::Press => (), + } + + if EXERCISE_RUNNING.load(Relaxed) { + continue; + } + + let input_event = match key.code { + KeyCode::Char('n') => InputEvent::Next, + KeyCode::Char('r') if manual_run => InputEvent::Run, + KeyCode::Char('h') => InputEvent::Hint, + KeyCode::Char('l') => break WatchEvent::Input(InputEvent::List), + KeyCode::Char('c') => InputEvent::CheckAll, + KeyCode::Char('x') => { + if sender.send(WatchEvent::Input(InputEvent::Reset)).is_err() { + return; + } + + // Pause input until quitting the confirmation prompt. + if unpause_receiver.recv().is_err() { + return; + }; + + continue; + } + KeyCode::Char('q') => break WatchEvent::Input(InputEvent::Quit), + _ => continue, + }; + + if sender.send(WatchEvent::Input(input_event)).is_err() { + return; + } + } + Ok(Event::Resize(width, _)) => { + if sender.send(WatchEvent::TerminalResize { width }).is_err() { + return; + } + } + Ok(Event::FocusGained | Event::FocusLost | Event::Mouse(_)) => continue, + Err(e) => break WatchEvent::TerminalEventErr(e), + } + }; + + let _ = sender.send(last_watch_event); +} diff --git a/tests/fixture/failure/compNoExercise.rs b/tests/fixture/failure/compNoExercise.rs deleted file mode 100644 index f79c691f08..0000000000 --- a/tests/fixture/failure/compNoExercise.rs +++ /dev/null @@ -1,2 +0,0 @@ -fn main() { -} diff --git a/tests/fixture/failure/info.toml b/tests/fixture/failure/info.toml deleted file mode 100644 index e5949f9be1..0000000000 --- a/tests/fixture/failure/info.toml +++ /dev/null @@ -1,11 +0,0 @@ -[[exercises]] -name = "compFailure" -path = "compFailure.rs" -mode = "compile" -hint = "" - -[[exercises]] -name = "testFailure" -path = "testFailure.rs" -mode = "test" -hint = "Hello!" diff --git a/tests/fixture/failure/testFailure.rs b/tests/fixture/failure/testFailure.rs deleted file mode 100644 index b33a5d2891..0000000000 --- a/tests/fixture/failure/testFailure.rs +++ /dev/null @@ -1,4 +0,0 @@ -#[test] -fn passing() { - asset!(true); -} diff --git a/tests/fixture/failure/testNotPassed.rs b/tests/fixture/failure/testNotPassed.rs deleted file mode 100644 index a9fe88ddc8..0000000000 --- a/tests/fixture/failure/testNotPassed.rs +++ /dev/null @@ -1,4 +0,0 @@ -#[test] -fn not_passing() { - assert!(false); -} diff --git a/tests/fixture/state/finished_exercise.rs b/tests/fixture/state/finished_exercise.rs deleted file mode 100644 index 016b827c89..0000000000 --- a/tests/fixture/state/finished_exercise.rs +++ /dev/null @@ -1,5 +0,0 @@ -// fake_exercise - -fn main() { - -} diff --git a/tests/fixture/state/info.toml b/tests/fixture/state/info.toml deleted file mode 100644 index 547b3a48e7..0000000000 --- a/tests/fixture/state/info.toml +++ /dev/null @@ -1,18 +0,0 @@ -[[exercises]] -name = "pending_exercise" -path = "pending_exercise.rs" -mode = "compile" -hint = """""" - -[[exercises]] -name = "pending_test_exercise" -path = "pending_test_exercise.rs" -mode = "test" -hint = """""" - -[[exercises]] -name = "finished_exercise" -path = "finished_exercise.rs" -mode = "compile" -hint = """""" - diff --git a/tests/fixture/state/pending_exercise.rs b/tests/fixture/state/pending_exercise.rs deleted file mode 100644 index f579d0b4b4..0000000000 --- a/tests/fixture/state/pending_exercise.rs +++ /dev/null @@ -1,7 +0,0 @@ -// fake_exercise - -// I AM NOT DONE - -fn main() { - -} diff --git a/tests/fixture/state/pending_test_exercise.rs b/tests/fixture/state/pending_test_exercise.rs deleted file mode 100644 index 8756f02dbb..0000000000 --- a/tests/fixture/state/pending_test_exercise.rs +++ /dev/null @@ -1,4 +0,0 @@ -// I AM NOT DONE - -#[test] -fn it_works() {} diff --git a/tests/fixture/success/compSuccess.rs b/tests/fixture/success/compSuccess.rs deleted file mode 100644 index f79c691f08..0000000000 --- a/tests/fixture/success/compSuccess.rs +++ /dev/null @@ -1,2 +0,0 @@ -fn main() { -} diff --git a/tests/fixture/success/info.toml b/tests/fixture/success/info.toml deleted file mode 100644 index 68d35388ee..0000000000 --- a/tests/fixture/success/info.toml +++ /dev/null @@ -1,11 +0,0 @@ -[[exercises]] -name = "compSuccess" -path = "compSuccess.rs" -mode = "compile" -hint = """""" - -[[exercises]] -name = "testSuccess" -path = "testSuccess.rs" -mode = "test" -hint = """""" diff --git a/tests/fixture/success/testSuccess.rs b/tests/fixture/success/testSuccess.rs deleted file mode 100644 index 7139b50b06..0000000000 --- a/tests/fixture/success/testSuccess.rs +++ /dev/null @@ -1,5 +0,0 @@ -#[test] -fn passing() { - println!("THIS TEST TOO SHALL PASS"); - assert!(true); -} diff --git a/tests/integration_tests.rs b/tests/integration_tests.rs index 1a729232f6..bb3a084b22 100644 --- a/tests/integration_tests.rs +++ b/tests/integration_tests.rs @@ -1,266 +1,182 @@ -use assert_cmd::prelude::*; -use glob::glob; -use predicates::boolean::PredicateBooleanExt; -use std::fs::File; -use std::io::Read; -use std::process::Command; +use std::{ + env::{self, consts::EXE_SUFFIX}, + process::{Command, Stdio}, + str::from_utf8, +}; -#[test] -fn runs_without_arguments() { - let mut cmd = Command::cargo_bin("rustlings").unwrap(); - cmd.assert().success(); +enum Output<'a> { + FullStdout(&'a str), + PartialStdout(&'a str), + PartialStderr(&'a str), } -#[test] -fn fails_when_in_wrong_dir() { - Command::cargo_bin("rustlings") - .unwrap() - .current_dir("tests/") - .assert() - .code(1); -} +use Output::*; -#[test] -fn verify_all_success() { - Command::cargo_bin("rustlings") - .unwrap() - .arg("verify") - .current_dir("tests/fixture/success") - .assert() - .success(); +#[derive(Default)] +struct Cmd<'a> { + current_dir: Option<&'a str>, + args: &'a [&'a str], + output: Option>, } -#[test] -fn verify_fails_if_some_fails() { - Command::cargo_bin("rustlings") - .unwrap() - .arg("verify") - .current_dir("tests/fixture/failure") - .assert() - .code(1); -} +impl<'a> Cmd<'a> { + #[inline] + fn current_dir(&mut self, current_dir: &'a str) -> &mut Self { + self.current_dir = Some(current_dir); + self + } -#[test] -fn run_single_compile_success() { - Command::cargo_bin("rustlings") - .unwrap() - .args(&["run", "compSuccess"]) - .current_dir("tests/fixture/success/") - .assert() - .success(); -} + #[inline] + fn args(&mut self, args: &'a [&'a str]) -> &mut Self { + self.args = args; + self + } -#[test] -fn run_single_compile_failure() { - Command::cargo_bin("rustlings") - .unwrap() - .args(&["run", "compFailure"]) - .current_dir("tests/fixture/failure/") - .assert() - .code(1); -} + #[inline] + fn output(&mut self, output: Output<'a>) -> &mut Self { + self.output = Some(output); + self + } -#[test] -fn run_single_test_success() { - Command::cargo_bin("rustlings") - .unwrap() - .args(&["run", "testSuccess"]) - .current_dir("tests/fixture/success/") - .assert() - .success(); -} + fn assert(&self, success: bool) { + let rustlings_bin = { + let mut path = env::current_exe().unwrap(); + // Pop test binary name + path.pop(); + // Pop `/deps` + path.pop(); + + path.push("rustlings"); + let mut path = path.into_os_string(); + path.push(EXE_SUFFIX); + path + }; -#[test] -fn run_single_test_failure() { - Command::cargo_bin("rustlings") - .unwrap() - .args(&["run", "testFailure"]) - .current_dir("tests/fixture/failure/") - .assert() - .code(1); -} + let mut cmd = Command::new(rustlings_bin); -#[test] -fn run_single_test_not_passed() { - Command::cargo_bin("rustlings") - .unwrap() - .args(&["run", "testNotPassed.rs"]) - .current_dir("tests/fixture/failure/") - .assert() - .code(1); -} + if let Some(current_dir) = self.current_dir { + cmd.current_dir(current_dir); + } -#[test] -fn run_single_test_no_filename() { - Command::cargo_bin("rustlings") - .unwrap() - .arg("run") - .current_dir("tests/fixture/") - .assert() - .code(1); -} + cmd.args(self.args).stdin(Stdio::null()); + + let status = match self.output { + None => cmd + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .unwrap(), + Some(FullStdout(stdout)) => { + let output = cmd.stderr(Stdio::null()).output().unwrap(); + assert_eq!(from_utf8(&output.stdout).unwrap(), stdout); + output.status + } + Some(PartialStdout(stdout)) => { + let output = cmd.stderr(Stdio::null()).output().unwrap(); + assert!(from_utf8(&output.stdout).unwrap().contains(stdout)); + output.status + } + Some(PartialStderr(stderr)) => { + let output = cmd.stdout(Stdio::null()).output().unwrap(); + assert!(from_utf8(&output.stderr).unwrap().contains(stderr)); + output.status + } + }; -#[test] -fn run_single_test_no_exercise() { - Command::cargo_bin("rustlings") - .unwrap() - .args(&["run", "compNoExercise.rs"]) - .current_dir("tests/fixture/failure") - .assert() - .code(1); -} + assert_eq!(status.success(), success, "{cmd:?}"); + } -#[test] -fn reset_single_exercise() { - Command::cargo_bin("rustlings") - .unwrap() - .args(&["reset", "intro1"]) - .assert() - .code(0); -} + #[inline] + fn success(&self) { + self.assert(true); + } -#[test] -fn reset_no_exercise() { - Command::cargo_bin("rustlings") - .unwrap() - .arg("reset") - .assert() - .code(1) - .stderr(predicates::str::contains( - "positional arguments not provided", - )); + #[inline] + fn fail(&self) { + self.assert(false); + } } #[test] -fn get_hint_for_single_test() { - Command::cargo_bin("rustlings") - .unwrap() - .args(&["hint", "testFailure"]) - .current_dir("tests/fixture/failure") - .assert() - .code(0) - .stdout("Hello!\n"); +fn run_compilation_success() { + Cmd::default() + .current_dir("tests/test_exercises") + .args(&["run", "compilation_success"]) + .success(); } #[test] -fn all_exercises_require_confirmation() { - for exercise in glob("exercises/**/*.rs").unwrap() { - let path = exercise.unwrap(); - if path.file_name().unwrap() == "mod.rs" { - continue; - } - let source = { - let mut file = File::open(&path).unwrap(); - let mut s = String::new(); - file.read_to_string(&mut s).unwrap(); - s - }; - source - .matches("// I AM NOT DONE") - .next() - .unwrap_or_else(|| { - panic!( - "There should be an `I AM NOT DONE` annotation in {:?}", - path - ) - }); - } +fn run_compilation_failure() { + Cmd::default() + .current_dir("tests/test_exercises") + .args(&["run", "compilation_failure"]) + .fail(); } #[test] -fn run_compile_exercise_does_not_prompt() { - Command::cargo_bin("rustlings") - .unwrap() - .args(&["run", "pending_exercise"]) - .current_dir("tests/fixture/state") - .assert() - .code(0) - .stdout(predicates::str::contains("I AM NOT DONE").not()); +fn run_test_success() { + Cmd::default() + .current_dir("tests/test_exercises") + .args(&["run", "test_success"]) + .output(PartialStdout("\nOutput from `main` function\n")) + .success(); } #[test] -fn run_test_exercise_does_not_prompt() { - Command::cargo_bin("rustlings") - .unwrap() - .args(&["run", "pending_test_exercise"]) - .current_dir("tests/fixture/state") - .assert() - .code(0) - .stdout(predicates::str::contains("I AM NOT DONE").not()); +fn run_test_failure() { + Cmd::default() + .current_dir("tests/test_exercises") + .args(&["run", "test_failure"]) + .fail(); } #[test] -fn run_single_test_success_with_output() { - Command::cargo_bin("rustlings") - .unwrap() - .args(&["--nocapture", "run", "testSuccess"]) - .current_dir("tests/fixture/success/") - .assert() - .code(0) - .stdout(predicates::str::contains("THIS TEST TOO SHALL PASS")); +fn run_exercise_not_in_info() { + Cmd::default() + .current_dir("tests/test_exercises") + .args(&["run", "not_in_info"]) + .fail(); } #[test] -fn run_single_test_success_without_output() { - Command::cargo_bin("rustlings") - .unwrap() - .args(&["run", "testSuccess"]) - .current_dir("tests/fixture/success/") - .assert() - .code(0) - .stdout(predicates::str::contains("THIS TEST TOO SHALL PASS").not()); +fn reset_without_exercise_name() { + Cmd::default().args(&["reset"]).fail(); } #[test] -fn run_rustlings_list() { - Command::cargo_bin("rustlings") - .unwrap() - .args(&["list"]) - .current_dir("tests/fixture/success") - .assert() +fn hint() { + Cmd::default() + .current_dir("tests/test_exercises") + .args(&["hint", "test_failure"]) + .output(FullStdout("The answer to everything: 42\n")) .success(); } #[test] -fn run_rustlings_list_no_pending() { - Command::cargo_bin("rustlings") - .unwrap() - .args(&["list"]) - .current_dir("tests/fixture/success") - .assert() - .success() - .stdout(predicates::str::contains("Pending").not()); -} +fn init() { + let test_dir = tempfile::TempDir::new().unwrap(); + let test_dir = test_dir.path().to_str().unwrap(); -#[test] -fn run_rustlings_list_both_done_and_pending() { - Command::cargo_bin("rustlings") - .unwrap() - .args(&["list"]) - .current_dir("tests/fixture/state") - .assert() - .success() - .stdout(predicates::str::contains("Done").and(predicates::str::contains("Pending"))); -} + Cmd::default().current_dir(test_dir).fail(); -#[test] -fn run_rustlings_list_without_pending() { - Command::cargo_bin("rustlings") - .unwrap() - .args(&["list", "--solved"]) - .current_dir("tests/fixture/state") - .assert() - .success() - .stdout(predicates::str::contains("Pending").not()); -} + Cmd::default() + .current_dir(test_dir) + .args(&["init"]) + .success(); -#[test] -fn run_rustlings_list_without_done() { - Command::cargo_bin("rustlings") - .unwrap() - .args(&["list", "--unsolved"]) - .current_dir("tests/fixture/state") - .assert() - .success() - .stdout(predicates::str::contains("Done").not()); + // Running `init` after a successful initialization. + Cmd::default() + .current_dir(test_dir) + .args(&["init"]) + .output(PartialStderr("`cd rustlings`")) + .fail(); + + let initialized_dir = format!("{test_dir}/rustlings"); + + // Running `init` in the initialized directory. + Cmd::default() + .current_dir(&initialized_dir) + .args(&["init"]) + .output(PartialStderr("already initialized")) + .fail(); } diff --git a/tests/test_exercises/dev/Cargo.toml b/tests/test_exercises/dev/Cargo.toml new file mode 100644 index 0000000000..74dcc20ade --- /dev/null +++ b/tests/test_exercises/dev/Cargo.toml @@ -0,0 +1,11 @@ +bin = [ + { name = "compilation_success", path = "../exercises/compilation_success.rs" }, + { name = "compilation_failure", path = "../exercises/compilation_failure.rs" }, + { name = "test_success", path = "../exercises/test_success.rs" }, + { name = "test_failure", path = "../exercises/test_failure.rs" }, +] + +[package] +name = "test_exercises" +edition = "2024" +publish = false diff --git a/tests/fixture/failure/compFailure.rs b/tests/test_exercises/exercises/compilation_failure.rs similarity index 100% rename from tests/fixture/failure/compFailure.rs rename to tests/test_exercises/exercises/compilation_failure.rs diff --git a/tests/test_exercises/exercises/compilation_success.rs b/tests/test_exercises/exercises/compilation_success.rs new file mode 100644 index 0000000000..f328e4d9d0 --- /dev/null +++ b/tests/test_exercises/exercises/compilation_success.rs @@ -0,0 +1 @@ +fn main() {} diff --git a/tests/test_exercises/exercises/not_in_info.rs b/tests/test_exercises/exercises/not_in_info.rs new file mode 100644 index 0000000000..f328e4d9d0 --- /dev/null +++ b/tests/test_exercises/exercises/not_in_info.rs @@ -0,0 +1 @@ +fn main() {} diff --git a/tests/test_exercises/exercises/test_failure.rs b/tests/test_exercises/exercises/test_failure.rs new file mode 100644 index 0000000000..8c8d59d807 --- /dev/null +++ b/tests/test_exercises/exercises/test_failure.rs @@ -0,0 +1,9 @@ +fn main() {} + +#[cfg(test)] +mod tests { + #[test] + fn fails() { + assert!(false); + } +} diff --git a/tests/test_exercises/exercises/test_success.rs b/tests/test_exercises/exercises/test_success.rs new file mode 100644 index 0000000000..8c8a3c61d0 --- /dev/null +++ b/tests/test_exercises/exercises/test_success.rs @@ -0,0 +1,9 @@ +fn main() { + println!("Output from `main` function"); +} + +#[cfg(test)] +mod tests { + #[test] + fn passes() {} +} diff --git a/tests/test_exercises/info.toml b/tests/test_exercises/info.toml new file mode 100644 index 0000000000..d91094c0ea --- /dev/null +++ b/tests/test_exercises/info.toml @@ -0,0 +1,19 @@ +format_version = 1 + +[[exercises]] +name = "compilation_success" +test = false +hint = "" + +[[exercises]] +name = "compilation_failure" +test = false +hint = "" + +[[exercises]] +name = "test_success" +hint = "" + +[[exercises]] +name = "test_failure" +hint = "The answer to everything: 42" diff --git a/website/.gitignore b/website/.gitignore new file mode 100644 index 0000000000..648e07746e --- /dev/null +++ b/website/.gitignore @@ -0,0 +1,7 @@ +/node_modules/ +/package-lock.json + +/public/ + +/static/main.css +/static/processed_images/ diff --git a/website/config.toml b/website/config.toml new file mode 100644 index 0000000000..0c01dc7d26 --- /dev/null +++ b/website/config.toml @@ -0,0 +1,41 @@ +base_url = "https://rustlings.rust-lang.org" +title = "Rustlings" +description = "Small exercises to get you used to reading and writing Rust code!" + +compile_sass = false +build_search_index = false + +[markdown] +highlight_code = true +highlight_theme = "dracula" + +insert_anchor_links = "heading" + +[extra] +logo_path = "images/happy_ferris.svg" + +[[extra.menu_items]] +name = "Rustlings" +url = "@/_index.md" +[[extra.menu_items]] +name = "Setup" +url = "@/setup/index.md" +[[extra.menu_items]] +name = "Usage" +url = "@/usage/index.md" +[[extra.menu_items]] +name = "Community Exercises" +url = "@/community-exercises/index.md" +[[extra.menu_items]] +name = "Q&A" +url = "https://github.com/rust-lang/rustlings/discussions/categories/q-a?discussions_q=" + +[[extra.footer_items]] +name = "Repository" +url = "https://github.com/rust-lang/rustlings" +[[extra.footer_items]] +name = "Changelog" +url = "https://github.com/rust-lang/rustlings/blob/main/CHANGELOG.md" +[[extra.footer_items]] +name = "MIT License" +url = "https://github.com/rust-lang/rustlings/blob/main/LICENSE" diff --git a/website/content/_index.md b/website/content/_index.md new file mode 100644 index 0000000000..4bb4483b5c --- /dev/null +++ b/website/content/_index.md @@ -0,0 +1,21 @@ ++++ ++++ + +Small exercises to get you used to reading and writing [Rust](https://www.rust-lang.org) code - _Recommended in parallel to reading [the official Rust book](https://doc.rust-lang.org/book) 📚️_ + + + +## Quick start + +```bash +# Installation +cargo install rustlings +# Initialization +rustlings init +# Moving into new directory +cd rustlings +# Starting Rustlings +rustlings +``` + +Visit the [**setup**](@/setup/index.md) page for more details 🧰 diff --git a/website/content/community-exercises/index.md b/website/content/community-exercises/index.md new file mode 100644 index 0000000000..0f713d7cc7 --- /dev/null +++ b/website/content/community-exercises/index.md @@ -0,0 +1,73 @@ ++++ +title = "Community Exercises" ++++ + +## List of Community Exercises + +- 🇯🇵 [Japanese Rustlings](https://github.com/sotanengel/rustlings-jp):A Japanese translation of the Rustlings exercises. +- 🇨🇳 [Simplified Chinese Rustlings](https://github.com/SandmeyerX/rustlings-zh-cn): A simplified Chinese translation of the Rustlings exercises. + +> You can use the same `rustlings` program that you installed with `cargo install rustlings` to run community exercises. + +## Creating Community Exercises + +Rustling's support for community exercises allows you to create your own exercises to focus on some specific topic. +You could also offer a translation of the original Rustlings exercises as community exercises. + +### Getting Started + +To create community exercises, install Rustlings and run `rustlings dev new PROJECT_NAME`. +This command will, similar to `cargo new PROJECT_NAME`, create the template directory `PROJECT_NAME` with all what you need to get started. + +_Read the comments_ in the generated `info.toml` file to understand its format. +It allows you to set a custom welcome and final message and specify the metadata of every exercise. + +### Creating an Exercise + +Here is an example of the metadata of one exercise: + +```toml +[[exercises]] +name = "intro1" +hint = """ +To finish this exercise, you need to … +These links might help you …""" +``` + +After entering this in `info.toml`, create the file `intro1.rs` in the `exercises/` directory. +The exercise needs to contain a `main` function, but it can be empty. +Adding tests is recommended. +Look at the official Rustlings exercises for inspiration. + +You can optionally add a solution file `intro1.rs` to the `solutions/` directory. + +Now, run `rustlings dev check`. +It will tell you about any issues with your exercises. +For example, it will tell you to run `rustlings dev update` to update the `Cargo.toml` file to include the new exercise `intro1`. + +`rustlings dev check` will also run your solutions (if you have any) to make sure that they run successfully. + +That's it! +You finished your first exercise 🎉 + +### Cargo.toml + +Except of the `bin` list, you can modify the `Cargo.toml` file as you want. + +> The `bin` list is automatically updated by running `rustlings dev update` + +- You can add dependencies in the `[dependencies]` table. +- You might want to [configure some lints](https://doc.rust-lang.org/cargo/reference/manifest.html#the-lints-section) for all exercises. You can do so in the `[lints.rust]` and `[lints.clippy]` tables. + +### Publishing + +Now, add more exercises and publish them as a Git repository. + +Users just have to clone that repository and run `rustlings` in it to start working on your exercises (just like the official ones). + +One difference to the official exercises is that the solution files will not be hidden until the user finishes an exercise. +But you can trust your users to not open the solution too early 😉 + +### Sharing + +After publishing your community exercises, open an issue or a pull request in the [official Rustlings repository](https://github.com/rust-lang/rustlings) to add your project to the [list of community exercises](#list-of-community-exercises) 😃 diff --git a/website/content/setup/index.md b/website/content/setup/index.md new file mode 100644 index 0000000000..54551ada7c --- /dev/null +++ b/website/content/setup/index.md @@ -0,0 +1,78 @@ ++++ +title = "Setup" ++++ + + + +## Installing Rust + +Before installing Rustlings, you must have the **latest version of Rust** installed. +Visit [www.rust-lang.org/tools/install](https://www.rust-lang.org/tools/install) for further instructions. +This will also install _Cargo_, Rust's package/project manager. + +> 🐧 If you are on **Linux**, make sure you have `gcc` installed (_for a linker_). +> +> Debian: `sudo apt install gcc`\ +> Fedora: `sudo dnf install gcc` + +> 🍎 If you are on **MacOS**, make sure you have _Xcode and its developer tools_ installed: `xcode-select --install` + +## Installing Rustlings + +The following command will download and compile Rustlings: + +```bash +cargo install rustlings +``` + +{% details(summary="If the installation fails…") %} + +- Make sure you have the latest Rust version by running `rustup update` +- Try adding the `--locked` flag: `cargo install rustlings --locked` +- Otherwise, please [report the issue](https://github.com/rust-lang/rustlings/issues/new) + +{% end %} + +## Initialization + +After installing Rustlings, run the following command to initialize the `rustlings/` directory: + +```bash +rustlings init +``` + +{% details(summary="If the command rustlings can't be found…") %} + +You are probably using Linux and installed Rust using your package manager. + +Cargo installs binaries to the directory `~/.cargo/bin`. +Sadly, package managers often don't add `~/.cargo/bin` to your `PATH` environment variable. + +- Either add `~/.cargo/bin` manually to `PATH` +- Or uninstall Rust from the package manager and [install it using the official way with `rustup`](https://www.rust-lang.org/tools/install) + +{% end %} + +Now, go into the newly initialized directory and launch Rustlings for further instructions on getting started with the exercises: + +```bash +cd rustlings/ +rustlings +``` + +## Working environment + +### Editor + +Our general recommendation is [VS Code](https://code.visualstudio.com/) with the [rust-analyzer plugin](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer). +But any editor that supports [rust-analyzer](https://rust-analyzer.github.io/) should be enough for working on the exercises. + +### Terminal + +While working with Rustlings, please use a modern terminal for the best user experience. +The default terminal on Linux and Mac should be sufficient. +On Windows, we recommend the [Windows Terminal](https://aka.ms/terminal). + +## Usage + +After being done with the setup, visit the [**usage**](@/usage/index.md) page for some info about using Rustlings 🚀 diff --git a/website/content/usage/index.md b/website/content/usage/index.md new file mode 100644 index 0000000000..88dabf4ae4 --- /dev/null +++ b/website/content/usage/index.md @@ -0,0 +1,55 @@ ++++ +title = "Usage" ++++ + + + +## Doing exercises + +The exercises are sorted by topic and can be found in the subdirectory `exercises/`. +For every topic, there is an additional `README.md` file with some resources to get you started on the topic. +We highly recommend that you have a look at them before you start 📚️ + +Most exercises contain an error that keeps them from compiling, and it's up to you to fix it! +Some exercises contain tests that need to pass for the exercise to be done ✅ + +Search for `TODO` and `todo!()` to find out what you need to change. +Ask for hints by entering `h` in the _watch mode_ 💡 + +## Watch Mode + +After the [initialization](@/setup/index.md#initialization), Rustlings can be launched by simply running the command `rustlings`. + +This will start the _watch mode_ which walks you through the exercises in a predefined order (what we think is best for newcomers). +It will rerun the current exercise automatically every time you change the exercise's file in the `exercises/` directory. + +{% details(summary="If detecting file changes in the exercises/ directory fails…") %} + +You can add the **`--manual-run`** flag (`rustlings --manual-run`) to manually rerun the current exercise by entering `r` in the watch mode. + +Please [report the issue](https://github.com/rust-lang/rustlings/issues/new) with some information about your operating system and whether you run Rustlings in a container or a virtual machine (e.g. WSL). + +{% end %} + +## Exercise List + +In the [watch mode](#watch-mode) (after launching `rustlings`), you can enter `l` to open the interactive exercise list. + +The list allows you to… + +- See the status of all exercises (done or pending) +- `c`: Continue at another exercise (temporarily skip some exercises or go back to a previous one) +- `r`: Reset status and file of the selected exercise (you need to _reload/reopen_ its file in your editor afterwards) + +See the footer of the list for all possible keys. + +## Questions? + +If you need any help while doing the exercises and the builtin hints aren't helpful, feel free to ask in the [_Q&A_ discussions](https://github.com/rust-lang/rustlings/discussions/categories/q-a?discussions_q=) if your question isn't answered there 💡 + +## Continuing On + +Once you've completed Rustlings, put your new knowledge to good use! +Continue practicing your Rust skills by building your own projects, contributing to Rustlings, or finding other open-source projects to contribute to. + +> If you want to create your own Rustlings exercises, visit the [**community exercises**](@/community-exercises/index.md) page 🏗️ diff --git a/website/input.css b/website/input.css new file mode 100644 index 0000000000..af0675d8b7 --- /dev/null +++ b/website/input.css @@ -0,0 +1,54 @@ +@import 'tailwindcss'; + +@layer base { + h1 { + @apply text-4xl mt-3 mb-3 font-bold; + } + h2 { + @apply text-3xl mt-4 mb-1.5 font-bold; + } + h3 { + @apply text-2xl mt-5 mb-1.5 font-bold; + } + h4 { + @apply text-xl mt-6 mb-1.5 font-bold; + } + p { + @apply mb-2; + } + a { + @apply text-[#FFC832] underline hover:decoration-orange-400 transition duration-300; + } + ul { + @apply mt-2 mb-3 ml-1 list-disc list-inside marker:text-sky-600; + } + ol { + @apply mt-2 mb-3 ml-1 list-decimal list-inside marker:text-sky-500; + } + li { + @apply my-0.5; + } + code { + @apply bg-white/10 px-1 pb-px pt-1 rounded-md; + } + pre code { + @apply bg-inherit p-0 text-inherit; + } + hr { + @apply my-5 rounded-full; + } + img { + @apply md:w-3/4 lg:w-3/5; + } + blockquote { + @apply px-3 pt-2 pb-0.5 mb-4 mt-2 border-s-4 border-white/80 bg-white/7 rounded-sm; + } + + pre { + @apply px-2 pt-2 pb-px overflow-x-auto text-sm sm:text-base rounded-sm mt-2 mb-4 after:content-[attr(data-lang)] after:text-[8px] after:opacity-40 selection:bg-white/15; + } + pre code mark { + @apply pb-0.5 pt-1 pr-px text-inherit rounded-xs; + } +} + diff --git a/website/justfile b/website/justfile new file mode 100644 index 0000000000..7efc3ef9ca --- /dev/null +++ b/website/justfile @@ -0,0 +1,5 @@ +zola: + zola serve --open + +tailwind: + npx @tailwindcss/cli -w -i input.css -o static/main.css diff --git a/website/package.json b/website/package.json new file mode 100644 index 0000000000..38dd27e995 --- /dev/null +++ b/website/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "@tailwindcss/cli": "^4.1" + } +} diff --git a/website/static/images/happy_ferris.svg b/website/static/images/happy_ferris.svg new file mode 100644 index 0000000000..c7f240dd97 --- /dev/null +++ b/website/static/images/happy_ferris.svg @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/website/static/images/panic.svg b/website/static/images/panic.svg new file mode 100644 index 0000000000..be55f5e09b --- /dev/null +++ b/website/static/images/panic.svg @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/website/static/images/rust_logo.svg b/website/static/images/rust_logo.svg new file mode 100644 index 0000000000..3b42cfe034 --- /dev/null +++ b/website/static/images/rust_logo.svg @@ -0,0 +1,61 @@ + + + diff --git a/website/templates/404.html b/website/templates/404.html new file mode 100644 index 0000000000..eb9d4691a7 --- /dev/null +++ b/website/templates/404.html @@ -0,0 +1,14 @@ +{% extends "base.html" %} + +{% block content %} +

+

DON'T PANIC!

+

404: Page not found!

+ + + + Back to homepage +
+{% endblock %} diff --git a/website/templates/anchor-link.html b/website/templates/anchor-link.html new file mode 100644 index 0000000000..c8644d96f7 --- /dev/null +++ b/website/templates/anchor-link.html @@ -0,0 +1,2 @@ + diff --git a/website/templates/base.html b/website/templates/base.html new file mode 100644 index 0000000000..1a55aebf67 --- /dev/null +++ b/website/templates/base.html @@ -0,0 +1,92 @@ + + + + + + + {%- set timestamp = now(timestamp=true) -%} + + {%- if page.title -%} + {% set_global title = page.title %} + {%- elif section.title -%} + {% set_global title = section.title %} + {%- else -%} + {% set_global title = config.title %} + {%- endif -%} + + {%- if page.description -%} + {% set_global description = page.description %} + {%- elif section.description -%} + {% set_global description = section.description %} + {%- else -%} + {% set_global description = config.description %} + {%- endif -%} + + {%- if page.permalink -%} + {% set_global permalink = page.permalink %} + {%- elif section.permalink -%} + {% set_global permalink = section.permalink %} + {%- endif %} + + {%- block title -%}{{- title -}}{%- endblock -%} + + + + + + + + + + + {% if permalink %}{% endif %} + + + +
+ + + +
+ +
+ {% block content %}{% endblock %} +
+ +
+
+ +
Rustlings is an official Rust project
+
+ + +
+ + diff --git a/website/templates/index.html b/website/templates/index.html new file mode 100644 index 0000000000..0d2b2e3986 --- /dev/null +++ b/website/templates/index.html @@ -0,0 +1,9 @@ +{% extends "base.html" %} + +{% block content %} +
+

Rustlings

+ + {{ section.content | safe }} +
+{% endblock %} diff --git a/website/templates/page.html b/website/templates/page.html new file mode 100644 index 0000000000..b2f6c019c6 --- /dev/null +++ b/website/templates/page.html @@ -0,0 +1,39 @@ +{% extends "base.html" %} + +{% block content %} +
+

{{ page.title }}

+ +
+ +
+ + {{ page.content | safe }} +
+{% endblock %} diff --git a/website/templates/shortcodes/details.html b/website/templates/shortcodes/details.html new file mode 100644 index 0000000000..1c07778c00 --- /dev/null +++ b/website/templates/shortcodes/details.html @@ -0,0 +1,9 @@ +
+ + {{ summary | safe }} (click to expand) + + +
+ {{ body | markdown | safe }} +
+