chore: transfer all KBs to single one

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2022-11-05 15:24:54 +01:00
parent d207e870d4
commit 7427475022
Signed by: mfocko
GPG key ID: 7C47D46246790496
159 changed files with 28847 additions and 0 deletions

0
static/.nojekyll Normal file
View file

View file

@ -0,0 +1,104 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<!-- Generated by graphviz version 2.40.1 (20161225.0304)
-->
<!-- Title: %0 Pages: 1 -->
<svg width="189pt" height="404pt" viewBox="0.00 0.00 189.00 404.00" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="graph0" class="graph" transform="scale(1 1) rotate(0) translate(4 400)">
<title>%0</title>
<polygon fill="#ffffff" stroke="transparent" points="-4,4 -4,-400 185,-400 185,4 -4,4"/>
<!-- a -->
<g id="node1" class="node">
<title>a</title>
<ellipse fill="none" stroke="#000000" cx="126" cy="-378" rx="27" ry="18"/>
<text text-anchor="middle" x="126" y="-373.8" font-family="Times,serif" font-size="14.00" fill="#000000">a</text>
</g>
<!-- c -->
<g id="node2" class="node">
<title>c</title>
<ellipse fill="none" stroke="#000000" cx="99" cy="-306" rx="27" ry="18"/>
<text text-anchor="middle" x="99" y="-301.8" font-family="Times,serif" font-size="14.00" fill="#000000">c</text>
</g>
<!-- a&#45;&#45;c -->
<g id="edge1" class="edge">
<title>a--c</title>
<path fill="none" stroke="#000000" d="M119.3258,-360.2022C115.1407,-349.0419 109.7679,-334.7143 105.5974,-323.593"/>
</g>
<!-- e -->
<g id="node3" class="node">
<title>e</title>
<ellipse fill="none" stroke="#000000" cx="154" cy="-162" rx="27" ry="18"/>
<text text-anchor="middle" x="154" y="-157.8" font-family="Times,serif" font-size="14.00" fill="#000000">e</text>
</g>
<!-- a&#45;&#45;e -->
<g id="edge2" class="edge">
<title>a--e</title>
<path fill="none" stroke="#000000" d="M129.2182,-360.0337C131.0409,-349.5449 133.2909,-336.0449 135,-324 142.3994,-271.8513 149.0765,-209.9625 152.1748,-180.0161"/>
</g>
<!-- i -->
<g id="node4" class="node">
<title>i</title>
<ellipse fill="none" stroke="#000000" cx="27" cy="-234" rx="27" ry="18"/>
<text text-anchor="middle" x="27" y="-229.8" font-family="Times,serif" font-size="14.00" fill="#000000">i</text>
</g>
<!-- c&#45;&#45;i -->
<g id="edge3" class="edge">
<title>c--i</title>
<path fill="none" stroke="#000000" d="M83.7307,-290.7307C71.512,-278.512 54.4602,-261.4602 42.2473,-249.2473"/>
</g>
<!-- b -->
<g id="node5" class="node">
<title>b</title>
<ellipse fill="none" stroke="#000000" cx="99" cy="-234" rx="27" ry="18"/>
<text text-anchor="middle" x="99" y="-229.8" font-family="Times,serif" font-size="14.00" fill="#000000">b</text>
</g>
<!-- c&#45;&#45;b -->
<g id="edge4" class="edge">
<title>c--b</title>
<path fill="none" stroke="#000000" d="M99,-287.8314C99,-277 99,-263.2876 99,-252.4133"/>
</g>
<!-- j -->
<g id="node6" class="node">
<title>j</title>
<ellipse fill="none" stroke="#000000" cx="126" cy="-18" rx="27" ry="18"/>
<text text-anchor="middle" x="126" y="-13.8" font-family="Times,serif" font-size="14.00" fill="#000000">j</text>
</g>
<!-- e&#45;&#45;j -->
<g id="edge5" class="edge">
<title>e--j</title>
<path fill="none" stroke="#000000" d="M150.5104,-144.0535C145.1449,-116.4592 134.9255,-63.9026 129.5336,-36.1727"/>
</g>
<!-- d -->
<g id="node7" class="node">
<title>d</title>
<ellipse fill="none" stroke="#000000" cx="36" cy="-162" rx="27" ry="18"/>
<text text-anchor="middle" x="36" y="-157.8" font-family="Times,serif" font-size="14.00" fill="#000000">d</text>
</g>
<!-- i&#45;&#45;d -->
<g id="edge6" class="edge">
<title>i--d</title>
<path fill="none" stroke="#000000" d="M29.2711,-215.8314C30.625,-205 32.3391,-191.2876 33.6983,-180.4133"/>
</g>
<!-- h -->
<g id="node8" class="node">
<title>h</title>
<ellipse fill="none" stroke="#000000" cx="99" cy="-90" rx="27" ry="18"/>
<text text-anchor="middle" x="99" y="-85.8" font-family="Times,serif" font-size="14.00" fill="#000000">h</text>
</g>
<!-- b&#45;&#45;h -->
<g id="edge7" class="edge">
<title>b--h</title>
<path fill="none" stroke="#000000" d="M99,-215.7623C99,-188.0633 99,-135.7005 99,-108.0896"/>
</g>
<!-- d&#45;&#45;h -->
<g id="edge8" class="edge">
<title>d--h</title>
<path fill="none" stroke="#000000" d="M49.6701,-146.3771C60.2373,-134.3003 74.7961,-117.6616 85.3566,-105.5924"/>
</g>
<!-- h&#45;&#45;j -->
<g id="edge9" class="edge">
<title>h--j</title>
<path fill="none" stroke="#000000" d="M105.6742,-72.2022C109.8593,-61.0419 115.2321,-46.7143 119.4026,-35.593"/>
</g>
</g>
</svg>

After

(image error) Size: 4.2 KiB

View file

@ -0,0 +1,109 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<!-- Generated by graphviz version 2.40.1 (20161225.0304)
-->
<!-- Title: %0 Pages: 1 -->
<svg width="189pt" height="404pt" viewBox="0.00 0.00 189.00 404.00" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="graph0" class="graph" transform="scale(1 1) rotate(0) translate(4 400)">
<title>%0</title>
<polygon fill="#ffffff" stroke="transparent" points="-4,4 -4,-400 185,-400 185,4 -4,4"/>
<!-- a -->
<g id="node1" class="node">
<title>a</title>
<ellipse fill="none" stroke="#000000" cx="126" cy="-378" rx="27" ry="18"/>
<text text-anchor="middle" x="126" y="-373.8" font-family="Times,serif" font-size="14.00" fill="#000000">a</text>
</g>
<!-- c -->
<g id="node2" class="node">
<title>c</title>
<ellipse fill="none" stroke="#000000" cx="99" cy="-306" rx="27" ry="18"/>
<text text-anchor="middle" x="99" y="-301.8" font-family="Times,serif" font-size="14.00" fill="#000000">c</text>
</g>
<!-- a&#45;&#45;c -->
<g id="edge1" class="edge">
<title>a--c</title>
<path fill="none" stroke="#000000" d="M119.3258,-360.2022C115.1407,-349.0419 109.7679,-334.7143 105.5974,-323.593"/>
</g>
<!-- e -->
<g id="node3" class="node">
<title>e</title>
<ellipse fill="none" stroke="#000000" cx="154" cy="-162" rx="27" ry="18"/>
<text text-anchor="middle" x="154" y="-157.8" font-family="Times,serif" font-size="14.00" fill="#000000">e</text>
</g>
<!-- a&#45;&#45;e -->
<g id="edge2" class="edge">
<title>a--e</title>
<path fill="none" stroke="#000000" d="M129.2182,-360.0337C131.0409,-349.5449 133.2909,-336.0449 135,-324 142.3994,-271.8513 149.0765,-209.9625 152.1748,-180.0161"/>
</g>
<!-- i -->
<g id="node4" class="node">
<title>i</title>
<ellipse fill="none" stroke="#000000" cx="27" cy="-234" rx="27" ry="18"/>
<text text-anchor="middle" x="27" y="-229.8" font-family="Times,serif" font-size="14.00" fill="#000000">i</text>
</g>
<!-- c&#45;&#45;i -->
<g id="edge3" class="edge">
<title>c--i</title>
<path fill="none" stroke="#000000" d="M83.7307,-290.7307C71.512,-278.512 54.4602,-261.4602 42.2473,-249.2473"/>
</g>
<!-- b -->
<g id="node5" class="node">
<title>b</title>
<ellipse fill="none" stroke="#000000" cx="99" cy="-234" rx="27" ry="18"/>
<text text-anchor="middle" x="99" y="-229.8" font-family="Times,serif" font-size="14.00" fill="#000000">b</text>
</g>
<!-- c&#45;&#45;b -->
<g id="edge4" class="edge">
<title>c--b</title>
<path fill="none" stroke="#000000" d="M99,-287.8314C99,-277 99,-263.2876 99,-252.4133"/>
</g>
<!-- j -->
<g id="node6" class="node">
<title>j</title>
<ellipse fill="none" stroke="#000000" cx="126" cy="-18" rx="27" ry="18"/>
<text text-anchor="middle" x="126" y="-13.8" font-family="Times,serif" font-size="14.00" fill="#000000">j</text>
</g>
<!-- e&#45;&#45;j -->
<g id="edge5" class="edge">
<title>e--j</title>
<path fill="none" stroke="#000000" d="M150.5104,-144.0535C145.1449,-116.4592 134.9255,-63.9026 129.5336,-36.1727"/>
</g>
<!-- h -->
<g id="node7" class="node">
<title>h</title>
<ellipse fill="none" stroke="#000000" cx="99" cy="-90" rx="27" ry="18"/>
<text text-anchor="middle" x="99" y="-85.8" font-family="Times,serif" font-size="14.00" fill="#000000">h</text>
</g>
<!-- e&#45;&#45;h -->
<g id="edge6" class="edge">
<title>e--h</title>
<path fill="none" stroke="#000000" d="M141.5196,-145.6621C132.5186,-133.8788 120.4207,-118.0416 111.431,-106.2733"/>
</g>
<!-- d -->
<g id="node8" class="node">
<title>d</title>
<ellipse fill="none" stroke="#000000" cx="35" cy="-162" rx="27" ry="18"/>
<text text-anchor="middle" x="35" y="-157.8" font-family="Times,serif" font-size="14.00" fill="#000000">d</text>
</g>
<!-- i&#45;&#45;d -->
<g id="edge7" class="edge">
<title>i--d</title>
<path fill="none" stroke="#000000" d="M29.0187,-215.8314C30.2222,-205 31.7458,-191.2876 32.9541,-180.4133"/>
</g>
<!-- b&#45;&#45;h -->
<g id="edge8" class="edge">
<title>b--h</title>
<path fill="none" stroke="#000000" d="M99,-215.7623C99,-188.0633 99,-135.7005 99,-108.0896"/>
</g>
<!-- h&#45;&#45;j -->
<g id="edge10" class="edge">
<title>h--j</title>
<path fill="none" stroke="#000000" d="M105.6742,-72.2022C109.8593,-61.0419 115.2321,-46.7143 119.4026,-35.593"/>
</g>
<!-- d&#45;&#45;h -->
<g id="edge9" class="edge">
<title>d--h</title>
<path fill="none" stroke="#000000" d="M48.887,-146.3771C59.622,-134.3003 74.4119,-117.6616 85.1401,-105.5924"/>
</g>
</g>
</svg>

After

(image error) Size: 4.4 KiB

View file

@ -0,0 +1,101 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<!-- Generated by graphviz version 2.40.1 (20161225.0304)
-->
<!-- Title: %0 Pages: 1 -->
<svg width="206pt" height="260pt" viewBox="0.00 0.00 206.00 260.00" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="graph0" class="graph" transform="scale(1 1) rotate(0) translate(4 256)">
<title>%0</title>
<polygon fill="#ffffff" stroke="transparent" points="-4,4 -4,-256 202,-256 202,4 -4,4"/>
<!-- a -->
<g id="node1" class="node">
<title>a</title>
<ellipse fill="none" stroke="#000000" cx="135" cy="-234" rx="27" ry="18"/>
<text text-anchor="middle" x="135" y="-229.8" font-family="Times,serif" font-size="14.00" fill="#000000">a</text>
</g>
<!-- c -->
<g id="node2" class="node">
<title>c</title>
<ellipse fill="none" stroke="#000000" cx="99" cy="-162" rx="27" ry="18"/>
<text text-anchor="middle" x="99" y="-157.8" font-family="Times,serif" font-size="14.00" fill="#000000">c</text>
</g>
<!-- a&#45;&gt;c -->
<g id="edge1" class="edge">
<title>a-&gt;c</title>
<path fill="none" stroke="#000000" d="M126.2854,-216.5708C122.0403,-208.0807 116.8464,-197.6929 112.1337,-188.2674"/>
<polygon fill="#000000" stroke="#000000" points="115.237,-186.6477 107.6343,-179.2687 108.976,-189.7782 115.237,-186.6477"/>
</g>
<!-- e -->
<g id="node3" class="node">
<title>e</title>
<ellipse fill="none" stroke="#000000" cx="171" cy="-162" rx="27" ry="18"/>
<text text-anchor="middle" x="171" y="-157.8" font-family="Times,serif" font-size="14.00" fill="#000000">e</text>
</g>
<!-- a&#45;&gt;e -->
<g id="edge2" class="edge">
<title>a-&gt;e</title>
<path fill="none" stroke="#000000" d="M143.7146,-216.5708C147.9597,-208.0807 153.1536,-197.6929 157.8663,-188.2674"/>
<polygon fill="#000000" stroke="#000000" points="161.024,-189.7782 162.3657,-179.2687 154.763,-186.6477 161.024,-189.7782"/>
</g>
<!-- b -->
<g id="node4" class="node">
<title>b</title>
<ellipse fill="none" stroke="#000000" cx="27" cy="-90" rx="27" ry="18"/>
<text text-anchor="middle" x="27" y="-85.8" font-family="Times,serif" font-size="14.00" fill="#000000">b</text>
</g>
<!-- c&#45;&gt;b -->
<g id="edge3" class="edge">
<title>c-&gt;b</title>
<path fill="none" stroke="#000000" d="M83.7307,-146.7307C73.803,-136.803 60.6847,-123.6847 49.5637,-112.5637"/>
<polygon fill="#000000" stroke="#000000" points="51.7933,-109.8436 42.2473,-105.2473 46.8436,-114.7933 51.7933,-109.8436"/>
</g>
<!-- i -->
<g id="node5" class="node">
<title>i</title>
<ellipse fill="none" stroke="#000000" cx="99" cy="-90" rx="27" ry="18"/>
<text text-anchor="middle" x="99" y="-85.8" font-family="Times,serif" font-size="14.00" fill="#000000">i</text>
</g>
<!-- c&#45;&gt;i -->
<g id="edge4" class="edge">
<title>c-&gt;i</title>
<path fill="none" stroke="#000000" d="M99,-143.8314C99,-136.131 99,-126.9743 99,-118.4166"/>
<polygon fill="#000000" stroke="#000000" points="102.5001,-118.4132 99,-108.4133 95.5001,-118.4133 102.5001,-118.4132"/>
</g>
<!-- j -->
<g id="node6" class="node">
<title>j</title>
<ellipse fill="none" stroke="#000000" cx="171" cy="-90" rx="27" ry="18"/>
<text text-anchor="middle" x="171" y="-85.8" font-family="Times,serif" font-size="14.00" fill="#000000">j</text>
</g>
<!-- e&#45;&gt;j -->
<g id="edge5" class="edge">
<title>e-&gt;j</title>
<path fill="none" stroke="#000000" d="M171,-143.8314C171,-136.131 171,-126.9743 171,-118.4166"/>
<polygon fill="#000000" stroke="#000000" points="174.5001,-118.4132 171,-108.4133 167.5001,-118.4133 174.5001,-118.4132"/>
</g>
<!-- h -->
<g id="node7" class="node">
<title>h</title>
<ellipse fill="none" stroke="#000000" cx="27" cy="-18" rx="27" ry="18"/>
<text text-anchor="middle" x="27" y="-13.8" font-family="Times,serif" font-size="14.00" fill="#000000">h</text>
</g>
<!-- b&#45;&gt;h -->
<g id="edge6" class="edge">
<title>b-&gt;h</title>
<path fill="none" stroke="#000000" d="M27,-71.8314C27,-64.131 27,-54.9743 27,-46.4166"/>
<polygon fill="#000000" stroke="#000000" points="30.5001,-46.4132 27,-36.4133 23.5001,-46.4133 30.5001,-46.4132"/>
</g>
<!-- d -->
<g id="node8" class="node">
<title>d</title>
<ellipse fill="none" stroke="#000000" cx="99" cy="-18" rx="27" ry="18"/>
<text text-anchor="middle" x="99" y="-13.8" font-family="Times,serif" font-size="14.00" fill="#000000">d</text>
</g>
<!-- i&#45;&gt;d -->
<g id="edge7" class="edge">
<title>i-&gt;d</title>
<path fill="none" stroke="#000000" d="M99,-71.8314C99,-64.131 99,-54.9743 99,-46.4166"/>
<polygon fill="#000000" stroke="#000000" points="102.5001,-46.4132 99,-36.4133 95.5001,-46.4133 102.5001,-46.4132"/>
</g>
</g>
</svg>

After

(image error) Size: 4.6 KiB

View file

@ -0,0 +1,101 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<!-- Generated by graphviz version 2.40.1 (20161225.0304)
-->
<!-- Title: %0 Pages: 1 -->
<svg width="278pt" height="260pt" viewBox="0.00 0.00 278.00 260.00" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="graph0" class="graph" transform="scale(1 1) rotate(0) translate(4 256)">
<title>%0</title>
<polygon fill="#ffffff" stroke="transparent" points="-4,4 -4,-256 274,-256 274,4 -4,4"/>
<!-- a -->
<g id="node1" class="node">
<title>a</title>
<ellipse fill="none" stroke="#000000" cx="135" cy="-234" rx="27" ry="18"/>
<text text-anchor="middle" x="135" y="-229.8" font-family="Times,serif" font-size="14.00" fill="#000000">a</text>
</g>
<!-- c -->
<g id="node2" class="node">
<title>c</title>
<ellipse fill="none" stroke="#000000" cx="99" cy="-162" rx="27" ry="18"/>
<text text-anchor="middle" x="99" y="-157.8" font-family="Times,serif" font-size="14.00" fill="#000000">c</text>
</g>
<!-- a&#45;&gt;c -->
<g id="edge1" class="edge">
<title>a-&gt;c</title>
<path fill="none" stroke="#000000" d="M126.2854,-216.5708C122.0403,-208.0807 116.8464,-197.6929 112.1337,-188.2674"/>
<polygon fill="#000000" stroke="#000000" points="115.237,-186.6477 107.6343,-179.2687 108.976,-189.7782 115.237,-186.6477"/>
</g>
<!-- e -->
<g id="node3" class="node">
<title>e</title>
<ellipse fill="none" stroke="#000000" cx="171" cy="-162" rx="27" ry="18"/>
<text text-anchor="middle" x="171" y="-157.8" font-family="Times,serif" font-size="14.00" fill="#000000">e</text>
</g>
<!-- a&#45;&gt;e -->
<g id="edge2" class="edge">
<title>a-&gt;e</title>
<path fill="none" stroke="#000000" d="M143.7146,-216.5708C147.9597,-208.0807 153.1536,-197.6929 157.8663,-188.2674"/>
<polygon fill="#000000" stroke="#000000" points="161.024,-189.7782 162.3657,-179.2687 154.763,-186.6477 161.024,-189.7782"/>
</g>
<!-- b -->
<g id="node4" class="node">
<title>b</title>
<ellipse fill="none" stroke="#000000" cx="27" cy="-90" rx="27" ry="18"/>
<text text-anchor="middle" x="27" y="-85.8" font-family="Times,serif" font-size="14.00" fill="#000000">b</text>
</g>
<!-- c&#45;&gt;b -->
<g id="edge3" class="edge">
<title>c-&gt;b</title>
<path fill="none" stroke="#000000" d="M83.7307,-146.7307C73.803,-136.803 60.6847,-123.6847 49.5637,-112.5637"/>
<polygon fill="#000000" stroke="#000000" points="51.7933,-109.8436 42.2473,-105.2473 46.8436,-114.7933 51.7933,-109.8436"/>
</g>
<!-- i -->
<g id="node5" class="node">
<title>i</title>
<ellipse fill="none" stroke="#000000" cx="99" cy="-90" rx="27" ry="18"/>
<text text-anchor="middle" x="99" y="-85.8" font-family="Times,serif" font-size="14.00" fill="#000000">i</text>
</g>
<!-- c&#45;&gt;i -->
<g id="edge4" class="edge">
<title>c-&gt;i</title>
<path fill="none" stroke="#000000" d="M99,-143.8314C99,-136.131 99,-126.9743 99,-118.4166"/>
<polygon fill="#000000" stroke="#000000" points="102.5001,-118.4132 99,-108.4133 95.5001,-118.4133 102.5001,-118.4132"/>
</g>
<!-- h -->
<g id="node6" class="node">
<title>h</title>
<ellipse fill="none" stroke="#000000" cx="171" cy="-90" rx="27" ry="18"/>
<text text-anchor="middle" x="171" y="-85.8" font-family="Times,serif" font-size="14.00" fill="#000000">h</text>
</g>
<!-- e&#45;&gt;h -->
<g id="edge5" class="edge">
<title>e-&gt;h</title>
<path fill="none" stroke="#000000" d="M171,-143.8314C171,-136.131 171,-126.9743 171,-118.4166"/>
<polygon fill="#000000" stroke="#000000" points="174.5001,-118.4132 171,-108.4133 167.5001,-118.4133 174.5001,-118.4132"/>
</g>
<!-- j -->
<g id="node7" class="node">
<title>j</title>
<ellipse fill="none" stroke="#000000" cx="243" cy="-90" rx="27" ry="18"/>
<text text-anchor="middle" x="243" y="-85.8" font-family="Times,serif" font-size="14.00" fill="#000000">j</text>
</g>
<!-- e&#45;&gt;j -->
<g id="edge6" class="edge">
<title>e-&gt;j</title>
<path fill="none" stroke="#000000" d="M186.2693,-146.7307C196.197,-136.803 209.3153,-123.6847 220.4363,-112.5637"/>
<polygon fill="#000000" stroke="#000000" points="223.1564,-114.7933 227.7527,-105.2473 218.2067,-109.8436 223.1564,-114.7933"/>
</g>
<!-- d -->
<g id="node8" class="node">
<title>d</title>
<ellipse fill="none" stroke="#000000" cx="99" cy="-18" rx="27" ry="18"/>
<text text-anchor="middle" x="99" y="-13.8" font-family="Times,serif" font-size="14.00" fill="#000000">d</text>
</g>
<!-- i&#45;&gt;d -->
<g id="edge7" class="edge">
<title>i-&gt;d</title>
<path fill="none" stroke="#000000" d="M99,-71.8314C99,-64.131 99,-54.9743 99,-46.4166"/>
<polygon fill="#000000" stroke="#000000" points="102.5001,-46.4132 99,-36.4133 95.5001,-46.4133 102.5001,-46.4132"/>
</g>
</g>
</svg>

After

(image error) Size: 4.6 KiB

View file

@ -0,0 +1,142 @@
#include "dynlist.h"
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
void dynamic_array_init(struct dynamic_array_t *arr, size_t size)
{
if (arr == NULL)
{
return;
}
arr->data = NULL;
arr->count = 0;
arr->capacity = 0;
arr->size = size;
}
void dynamic_array_destroy(struct dynamic_array_t *arr)
{
if (arr == NULL)
{
return;
}
if (arr->data != NULL)
{
free(arr->data);
arr->data = NULL;
}
arr->count = 0;
arr->capacity = 0;
}
void *dynamic_array_at(struct dynamic_array_t *arr, size_t index)
{
if (arr == NULL || index >= arr->count)
{
return NULL;
}
return arr->data + index * arr->size;
}
void *dynamic_array_front(struct dynamic_array_t *arr)
{
if (arr == NULL || arr->count < 1)
{
return NULL;
}
return arr->data;
}
void *dynamic_array_back(struct dynamic_array_t *arr)
{
if (arr == NULL || arr->count < 1)
{
return NULL;
}
return arr->data + (arr->count - 1) * arr->size;
}
/**
* @brief Resize the dynamic array when needed.
* @param arr Array to be resized.
* @returns <code>true</code> if resizing was successful or array was not resized,
* <code>false</code> otherwise.
*/
static bool dynamic_array_resize(struct dynamic_array_t *arr)
{
if (arr == NULL || arr->count < arr->capacity)
{
return true;
}
size_t new_capacity = arr->capacity ? (arr->capacity * 2) : 16;
void *new_data = realloc(arr->data, new_capacity * arr->size);
if (new_data == NULL)
{
// failed to reallocate memory
return false;
}
arr->data = new_data;
arr->capacity = new_capacity;
return true;
}
bool dynamic_array_push_back(struct dynamic_array_t *arr, void *data)
{
if (arr == NULL || data == NULL)
{
return false;
}
if (!dynamic_array_resize(arr))
{
// failed to reallocate memory
return false;
}
memcpy(dynamic_array_at(arr, arr->count), data, arr->size);
arr->count++;
return true;
}
void dynamic_array_pop_back(struct dynamic_array_t *arr)
{
if (arr == NULL || arr->count < 1)
{
return;
}
arr->count--;
}
void dynamic_array_extend(struct dynamic_array_t *arr, struct dynamic_array_t *src)
{
if (arr == NULL || src == NULL)
{
return;
}
for (size_t i = 0; i < src->count; i++)
{
dynamic_array_push_back(arr, dynamic_array_at(src, i));
}
}
void dynamic_array_clear(struct dynamic_array_t *arr)
{
if (arr == NULL)
{
return;
}
arr->count = 0;
}

View file

@ -0,0 +1,76 @@
#include <stdbool.h>
#include <stdlib.h>
struct dynamic_array_t
{
char *data;
size_t count;
size_t capacity;
size_t size;
};
/**
* @brief Initializes dynamic array. Sets size of single element and zeroes
* everything else.
* @param arr Array to be initialized.
* @param size Size of one element in the array.
*/
void dynamic_array_init(struct dynamic_array_t *arr, size_t size);
/**
* @brief Destroys dynamic array. Deallocates all the memory and resets fields.
* @param arr Array to be destroyed.
*/
void dynamic_array_destroy(struct dynamic_array_t *arr);
/**
* @brief Returns pointer to the element on the given index.
* @param arr Array containing the element.
* @param index Index of the element.
* @returns Pointer to the element, <code>NULL</code> if index is out of bounds.
*/
void *dynamic_array_at(struct dynamic_array_t *arr, size_t index);
/**
* @brief Returns pointer to the first element of the array.
* @param arr Array containing the element.
* @returns Pointer to the first element, <code>NULL</code> if no elements are
* present.
*/
void *dynamic_array_front(struct dynamic_array_t *arr);
/**
* @brief Returns pointer to the last element of the array.
* @param arr Array containing the element.
* @returns Pointer to the last element, <code>NULL</code> if no elements are
* present.
*/
void *dynamic_array_back(struct dynamic_array_t *arr);
/**
* @brief Adds element to the end of the array.
* @param arr Array where the element is to be added.
* @param data Pointer to the data, that are to be copied into the array.
* @returns <code>true</code> if element added successfully, <code>false</code>
* otherwise.
*/
bool dynamic_array_push_back(struct dynamic_array_t *arr, void *data);
/**
* @brief Removes last element from the array.
* @param arr Array from which the last element is to be removed.
*/
void dynamic_array_pop_back(struct dynamic_array_t *arr);
/**
* @brief Extends array with the elements from another array.
* @param arr Array to be extended.
* @param src Array from which the elements are copied.
*/
void dynamic_array_extend(struct dynamic_array_t *arr, struct dynamic_array_t *src);
/**
* @brief Clears out the array.
* @param arr Array to be cleared.
*/
void dynamic_array_clear(struct dynamic_array_t *arr);

View file

@ -0,0 +1,192 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<!-- Generated by graphviz version 2.40.1 (20161225.0304)
-->
<!-- Title: G Pages: 1 -->
<svg width="638pt" height="209pt" viewBox="0.00 0.00 638.00 208.80" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="graph0" class="graph" transform="scale(1 1) rotate(0) translate(4 204.8)">
<title>G</title>
<polygon fill="#ffffff" stroke="transparent" points="-4,4 -4,-204.8 634,-204.8 634,4 -4,4"/>
<!-- a_node -->
<g id="node1" class="node">
<title>a_node</title>
<polygon fill="none" stroke="#000000" points="211.5,-164.3 211.5,-200.3 418.5,-200.3 418.5,-164.3 211.5,-164.3"/>
<text text-anchor="middle" x="223" y="-178.1" font-family="Times,serif" font-size="14.00" fill="#000000">1</text>
<polyline fill="none" stroke="#000000" points="234.5,-164.3 234.5,-200.3 "/>
<text text-anchor="middle" x="246" y="-178.1" font-family="Times,serif" font-size="14.00" fill="#000000">2</text>
<polyline fill="none" stroke="#000000" points="257.5,-164.3 257.5,-200.3 "/>
<text text-anchor="middle" x="269" y="-178.1" font-family="Times,serif" font-size="14.00" fill="#000000">3</text>
<polyline fill="none" stroke="#000000" points="280.5,-164.3 280.5,-200.3 "/>
<text text-anchor="middle" x="292" y="-178.1" font-family="Times,serif" font-size="14.00" fill="#000000">4</text>
<polyline fill="none" stroke="#000000" points="303.5,-164.3 303.5,-200.3 "/>
<text text-anchor="middle" x="315" y="-178.1" font-family="Times,serif" font-size="14.00" fill="#000000">5</text>
<polyline fill="none" stroke="#000000" points="326.5,-164.3 326.5,-200.3 "/>
<text text-anchor="middle" x="338" y="-178.1" font-family="Times,serif" font-size="14.00" fill="#000000">6</text>
<polyline fill="none" stroke="#000000" points="349.5,-164.3 349.5,-200.3 "/>
<text text-anchor="middle" x="361" y="-178.1" font-family="Times,serif" font-size="14.00" fill="#000000">7</text>
<polyline fill="none" stroke="#000000" points="372.5,-164.3 372.5,-200.3 "/>
<text text-anchor="middle" x="384" y="-178.1" font-family="Times,serif" font-size="14.00" fill="#000000">8</text>
<polyline fill="none" stroke="#000000" points="395.5,-164.3 395.5,-200.3 "/>
<text text-anchor="middle" x="407" y="-178.1" font-family="Times,serif" font-size="14.00" fill="#000000">9</text>
</g>
<!-- b_node -->
<g id="node2" class="node">
<title>b_node</title>
<polygon fill="none" stroke="#000000" points="100.5,-74.5 100.5,-110.5 169.5,-110.5 169.5,-74.5 100.5,-74.5"/>
<text text-anchor="middle" x="112" y="-88.3" font-family="Times,serif" font-size="14.00" fill="#000000">1</text>
<polyline fill="none" stroke="#000000" points="123.5,-74.5 123.5,-110.5 "/>
<text text-anchor="middle" x="135" y="-88.3" font-family="Times,serif" font-size="14.00" fill="#000000">2</text>
<polyline fill="none" stroke="#000000" points="146.5,-74.5 146.5,-110.5 "/>
<text text-anchor="middle" x="158" y="-88.3" font-family="Times,serif" font-size="14.00" fill="#000000">3</text>
</g>
<!-- a_node&#45;&gt;b_node -->
<g id="edge1" class="edge">
<title>a_node-&gt;b_node</title>
<path fill="none" stroke="#000000" d="M278.5743,-164.1276C249.7143,-149.7297 209.2985,-129.5667 178.6975,-114.3002"/>
<polygon fill="#000000" stroke="#000000" points="180.0501,-111.0637 169.5394,-109.7313 176.9252,-117.3274 180.0501,-111.0637"/>
<text text-anchor="middle" x="246.6683" y="-133.2" font-family="Times,serif" font-size="14.00" fill="#000000">B</text>
</g>
<!-- c_node -->
<g id="node3" class="node">
<title>c_node</title>
<polygon fill="none" stroke="#000000" points="280.5,-74.5 280.5,-110.5 349.5,-110.5 349.5,-74.5 280.5,-74.5"/>
<text text-anchor="middle" x="292" y="-88.3" font-family="Times,serif" font-size="14.00" fill="#000000">4</text>
<polyline fill="none" stroke="#000000" points="303.5,-74.5 303.5,-110.5 "/>
<text text-anchor="middle" x="315" y="-88.3" font-family="Times,serif" font-size="14.00" fill="#000000">5</text>
<polyline fill="none" stroke="#000000" points="326.5,-74.5 326.5,-110.5 "/>
<text text-anchor="middle" x="338" y="-88.3" font-family="Times,serif" font-size="14.00" fill="#000000">6</text>
</g>
<!-- a_node&#45;&gt;c_node -->
<g id="edge2" class="edge">
<title>a_node-&gt;c_node</title>
<path fill="none" stroke="#000000" d="M315,-164.1276C315,-151.7124 315,-135.0106 315,-120.8579"/>
<polygon fill="#000000" stroke="#000000" points="318.5001,-120.6453 315,-110.6453 311.5001,-120.6454 318.5001,-120.6453"/>
<text text-anchor="middle" x="319.6683" y="-133.2" font-family="Times,serif" font-size="14.00" fill="#000000">C</text>
</g>
<!-- d_node -->
<g id="node4" class="node">
<title>d_node</title>
<polygon fill="none" stroke="#000000" points="460.5,-74.5 460.5,-110.5 529.5,-110.5 529.5,-74.5 460.5,-74.5"/>
<text text-anchor="middle" x="472" y="-88.3" font-family="Times,serif" font-size="14.00" fill="#000000">7</text>
<polyline fill="none" stroke="#000000" points="483.5,-74.5 483.5,-110.5 "/>
<text text-anchor="middle" x="495" y="-88.3" font-family="Times,serif" font-size="14.00" fill="#000000">8</text>
<polyline fill="none" stroke="#000000" points="506.5,-74.5 506.5,-110.5 "/>
<text text-anchor="middle" x="518" y="-88.3" font-family="Times,serif" font-size="14.00" fill="#000000">9</text>
</g>
<!-- a_node&#45;&gt;d_node -->
<g id="edge3" class="edge">
<title>a_node-&gt;d_node</title>
<path fill="none" stroke="#000000" d="M351.4257,-164.1276C380.2857,-149.7297 420.7015,-129.5667 451.3025,-114.3002"/>
<polygon fill="#000000" stroke="#000000" points="453.0748,-117.3274 460.4606,-109.7313 449.9499,-111.0637 453.0748,-117.3274"/>
<text text-anchor="middle" x="426.0533" y="-133.2" font-family="Times,serif" font-size="14.00" fill="#000000">D</text>
</g>
<!-- 1 -->
<g id="node5" class="node">
<title>1</title>
<polygon fill="none" stroke="#000000" points="0,-.5 0,-36.5 54,-36.5 54,-.5 0,-.5"/>
<text text-anchor="middle" x="27" y="-14.3" font-family="Times,serif" font-size="14.00" fill="#000000">1</text>
</g>
<!-- b_node&#45;&gt;1 -->
<g id="edge4" class="edge">
<title>b_node-&gt;1</title>
<path fill="none" stroke="#000000" d="M108.5802,-74.3976C94.59,-64.8117 77.2236,-52.9125 62.1142,-42.5597"/>
<polygon fill="#000000" stroke="#000000" points="63.749,-39.4371 53.5213,-36.672 59.7923,-45.2116 63.749,-39.4371"/>
</g>
<!-- 2 -->
<g id="node6" class="node">
<title>2</title>
<polygon fill="none" stroke="#000000" points="72,-.5 72,-36.5 126,-36.5 126,-.5 72,-.5"/>
<text text-anchor="middle" x="99" y="-14.3" font-family="Times,serif" font-size="14.00" fill="#000000">2</text>
</g>
<!-- b_node&#45;&gt;2 -->
<g id="edge5" class="edge">
<title>b_node-&gt;2</title>
<path fill="none" stroke="#000000" d="M126.1011,-74.2079C121.916,-65.6051 116.8401,-55.1713 112.2178,-45.6699"/>
<polygon fill="#000000" stroke="#000000" points="115.3186,-44.0429 107.7965,-36.5817 109.0239,-47.1052 115.3186,-44.0429"/>
</g>
<!-- 3 -->
<g id="node7" class="node">
<title>3</title>
<polygon fill="none" stroke="#000000" points="144,-.5 144,-36.5 198,-36.5 198,-.5 144,-.5"/>
<text text-anchor="middle" x="171" y="-14.3" font-family="Times,serif" font-size="14.00" fill="#000000">3</text>
</g>
<!-- b_node&#45;&gt;3 -->
<g id="edge6" class="edge">
<title>b_node-&gt;3</title>
<path fill="none" stroke="#000000" d="M143.8989,-74.2079C148.084,-65.6051 153.1599,-55.1713 157.7822,-45.6699"/>
<polygon fill="#000000" stroke="#000000" points="160.9761,-47.1052 162.2035,-36.5817 154.6814,-44.0429 160.9761,-47.1052"/>
</g>
<!-- 4 -->
<g id="node8" class="node">
<title>4</title>
<polygon fill="none" stroke="#000000" points="216,-.5 216,-36.5 270,-36.5 270,-.5 216,-.5"/>
<text text-anchor="middle" x="243" y="-14.3" font-family="Times,serif" font-size="14.00" fill="#000000">4</text>
</g>
<!-- c_node&#45;&gt;4 -->
<g id="edge7" class="edge">
<title>c_node-&gt;4</title>
<path fill="none" stroke="#000000" d="M297.2022,-74.2079C288.3088,-65.0674 277.4042,-53.8599 267.7135,-43.9"/>
<polygon fill="#000000" stroke="#000000" points="270.0752,-41.3083 260.593,-36.5817 265.0581,-46.1898 270.0752,-41.3083"/>
</g>
<!-- 5 -->
<g id="node9" class="node">
<title>5</title>
<polygon fill="none" stroke="#000000" points="288,-.5 288,-36.5 342,-36.5 342,-.5 288,-.5"/>
<text text-anchor="middle" x="315" y="-14.3" font-family="Times,serif" font-size="14.00" fill="#000000">5</text>
</g>
<!-- c_node&#45;&gt;5 -->
<g id="edge8" class="edge">
<title>c_node-&gt;5</title>
<path fill="none" stroke="#000000" d="M315,-74.2079C315,-65.9635 315,-56.0376 315,-46.8622"/>
<polygon fill="#000000" stroke="#000000" points="318.5001,-46.5817 315,-36.5817 311.5001,-46.5818 318.5001,-46.5817"/>
</g>
<!-- 6 -->
<g id="node10" class="node">
<title>6</title>
<polygon fill="none" stroke="#000000" points="360,-.5 360,-36.5 414,-36.5 414,-.5 360,-.5"/>
<text text-anchor="middle" x="387" y="-14.3" font-family="Times,serif" font-size="14.00" fill="#000000">6</text>
</g>
<!-- c_node&#45;&gt;6 -->
<g id="edge9" class="edge">
<title>c_node-&gt;6</title>
<path fill="none" stroke="#000000" d="M332.7978,-74.2079C341.6912,-65.0674 352.5958,-53.8599 362.2865,-43.9"/>
<polygon fill="#000000" stroke="#000000" points="364.9419,-46.1898 369.407,-36.5817 359.9248,-41.3083 364.9419,-46.1898"/>
</g>
<!-- 7 -->
<g id="node11" class="node">
<title>7</title>
<polygon fill="none" stroke="#000000" points="432,-.5 432,-36.5 486,-36.5 486,-.5 432,-.5"/>
<text text-anchor="middle" x="459" y="-14.3" font-family="Times,serif" font-size="14.00" fill="#000000">7</text>
</g>
<!-- d_node&#45;&gt;7 -->
<g id="edge10" class="edge">
<title>d_node-&gt;7</title>
<path fill="none" stroke="#000000" d="M486.1011,-74.2079C481.916,-65.6051 476.8401,-55.1713 472.2178,-45.6699"/>
<polygon fill="#000000" stroke="#000000" points="475.3186,-44.0429 467.7965,-36.5817 469.0239,-47.1052 475.3186,-44.0429"/>
</g>
<!-- 8 -->
<g id="node12" class="node">
<title>8</title>
<polygon fill="none" stroke="#000000" points="504,-.5 504,-36.5 558,-36.5 558,-.5 504,-.5"/>
<text text-anchor="middle" x="531" y="-14.3" font-family="Times,serif" font-size="14.00" fill="#000000">8</text>
</g>
<!-- d_node&#45;&gt;8 -->
<g id="edge11" class="edge">
<title>d_node-&gt;8</title>
<path fill="none" stroke="#000000" d="M503.8989,-74.2079C508.084,-65.6051 513.1599,-55.1713 517.7822,-45.6699"/>
<polygon fill="#000000" stroke="#000000" points="520.9761,-47.1052 522.2035,-36.5817 514.6814,-44.0429 520.9761,-47.1052"/>
</g>
<!-- 9 -->
<g id="node13" class="node">
<title>9</title>
<polygon fill="none" stroke="#000000" points="576,-.5 576,-36.5 630,-36.5 630,-.5 576,-.5"/>
<text text-anchor="middle" x="603" y="-14.3" font-family="Times,serif" font-size="14.00" fill="#000000">9</text>
</g>
<!-- d_node&#45;&gt;9 -->
<g id="edge12" class="edge">
<title>d_node-&gt;9</title>
<path fill="none" stroke="#000000" d="M521.4198,-74.3976C535.41,-64.8117 552.7764,-52.9125 567.8858,-42.5597"/>
<polygon fill="#000000" stroke="#000000" points="570.2077,-45.2116 576.4787,-36.672 566.251,-39.4371 570.2077,-45.2116"/>
</g>
</g>
</svg>

After

(image error) Size: 11 KiB

View file

@ -0,0 +1,206 @@
# Remove the line below if you want to inherit .editorconfig settings from higher directories
root = true
# C# files
[*.cs]
#### Core EditorConfig Options ####
# Indentation and spacing
indent_size = 4
indent_style = space
tab_width = 4
# New line preferences
end_of_line = lf
insert_final_newline = true
#### .NET Coding Conventions ####
# Organize usings
dotnet_separate_import_directive_groups = false
dotnet_sort_system_directives_first = false
file_header_template = unset
# this. and Me. preferences
dotnet_style_qualification_for_event = false:silent
dotnet_style_qualification_for_field = false:silent
dotnet_style_qualification_for_method = false:silent
dotnet_style_qualification_for_property = false:silent
# Language keywords vs BCL types preferences
dotnet_style_predefined_type_for_locals_parameters_members = true:silent
dotnet_style_predefined_type_for_member_access = true:silent
# Parentheses preferences
dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent
dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent
dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent
dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent
# Modifier preferences
dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent
# Expression-level preferences
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_collection_initializer = true:suggestion
dotnet_style_explicit_tuple_names = true:suggestion
dotnet_style_null_propagation = true:suggestion
dotnet_style_object_initializer = true:suggestion
dotnet_style_operator_placement_when_wrapping = beginning_of_line
dotnet_style_prefer_auto_properties = true:silent
dotnet_style_prefer_compound_assignment = true:suggestion
dotnet_style_prefer_conditional_expression_over_assignment = true:silent
dotnet_style_prefer_conditional_expression_over_return = true:silent
dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
dotnet_style_prefer_inferred_tuple_names = true:suggestion
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion
dotnet_style_prefer_simplified_boolean_expressions = true:suggestion
dotnet_style_prefer_simplified_interpolation = true:suggestion
# Field preferences
dotnet_style_readonly_field = true:suggestion
# Parameter preferences
dotnet_code_quality_unused_parameters = all:suggestion
# Suppression preferences
dotnet_remove_unnecessary_suppression_exclusions = none
#### C# Coding Conventions ####
# var preferences
csharp_style_var_elsewhere = false:silent
csharp_style_var_for_built_in_types = false:silent
csharp_style_var_when_type_is_apparent = false:silent
# Expression-bodied members
csharp_style_expression_bodied_accessors = true:silent
csharp_style_expression_bodied_constructors = false:silent
csharp_style_expression_bodied_indexers = true:silent
csharp_style_expression_bodied_lambdas = true:silent
csharp_style_expression_bodied_local_functions = false:silent
csharp_style_expression_bodied_methods = false:silent
csharp_style_expression_bodied_operators = false:silent
csharp_style_expression_bodied_properties = true:silent
# Pattern matching preferences
csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
csharp_style_prefer_not_pattern = true:suggestion
csharp_style_prefer_pattern_matching = true:silent
csharp_style_prefer_switch_expression = true:suggestion
# Null-checking preferences
csharp_style_conditional_delegate_call = true:suggestion
# Modifier preferences
csharp_prefer_static_local_function = true:suggestion
csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:silent
# Code-block preferences
csharp_prefer_braces = true:silent
csharp_prefer_simple_using_statement = true:suggestion
# Expression-level preferences
csharp_prefer_simple_default_expression = true:suggestion
csharp_style_deconstructed_variable_declaration = true:suggestion
csharp_style_inlined_variable_declaration = true:suggestion
csharp_style_pattern_local_over_anonymous_function = true:suggestion
csharp_style_prefer_index_operator = true:suggestion
csharp_style_prefer_range_operator = true:suggestion
csharp_style_throw_expression = true:suggestion
csharp_style_unused_value_assignment_preference = discard_variable:suggestion
csharp_style_unused_value_expression_statement_preference = discard_variable:silent
# 'using' directive preferences
csharp_using_directive_placement = inside_namespace:silent
#### C# Formatting Rules ####
# New line preferences
csharp_new_line_before_catch = false
csharp_new_line_before_else = false
csharp_new_line_before_finally = false
csharp_new_line_before_members_in_anonymous_types = false
csharp_new_line_before_members_in_object_initializers = false
csharp_new_line_before_open_brace = none
csharp_new_line_between_query_expression_clauses = true
# Indentation preferences
csharp_indent_block_contents = true
csharp_indent_braces = false
csharp_indent_case_contents = true
csharp_indent_case_contents_when_block = true
csharp_indent_labels = one_less_than_current
csharp_indent_switch_labels = true
# Space preferences
csharp_space_after_cast = false
csharp_space_after_colon_in_inheritance_clause = true
csharp_space_after_comma = true
csharp_space_after_dot = false
csharp_space_after_keywords_in_control_flow_statements = true
csharp_space_after_semicolon_in_for_statement = true
csharp_space_around_binary_operators = before_and_after
csharp_space_around_declaration_statements = false
csharp_space_before_colon_in_inheritance_clause = true
csharp_space_before_comma = false
csharp_space_before_dot = false
csharp_space_before_open_square_brackets = false
csharp_space_before_semicolon_in_for_statement = false
csharp_space_between_empty_square_brackets = false
csharp_space_between_method_call_empty_parameter_list_parentheses = false
csharp_space_between_method_call_name_and_opening_parenthesis = false
csharp_space_between_method_call_parameter_list_parentheses = false
csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
csharp_space_between_method_declaration_name_and_open_parenthesis = false
csharp_space_between_method_declaration_parameter_list_parentheses = false
csharp_space_between_parentheses = false
csharp_space_between_square_brackets = false
# Wrapping preferences
csharp_preserve_single_line_blocks = true
csharp_preserve_single_line_statements = true
#### Naming styles ####
# Naming rules
dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion
dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i
dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.types_should_be_pascal_case.symbols = types
dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case
dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members
dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case
# Symbol specifications
dotnet_naming_symbols.interface.applicable_kinds = interface
dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.interface.required_modifiers =
dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum
dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.types.required_modifiers =
dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.non_field_members.required_modifiers =
# Naming styles
dotnet_naming_style.pascal_case.required_prefix =
dotnet_naming_style.pascal_case.required_suffix =
dotnet_naming_style.pascal_case.word_separator =
dotnet_naming_style.pascal_case.capitalization = pascal_case
dotnet_naming_style.begins_with_i.required_prefix = I
dotnet_naming_style.begins_with_i.required_suffix =
dotnet_naming_style.begins_with_i.word_separator =
dotnet_naming_style.begins_with_i.capitalization = pascal_case

View file

@ -0,0 +1,448 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# Tye
.tye/
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*[.json, .xml, .info]
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# Ionide - VsCode extension for F# Support
.ionide/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
##
## Visual studio for Mac
##
# globs
Makefile.in
*.userprefs
*.usertasks
config.make
config.status
aclocal.m4
install-sh
autom4te.cache/
*.tar.gz
tarballs/
test-results/
# Mac bundle stuff
*.dmg
*.app
# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore
# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
# JetBrains Rider
.idea/
*.sln.iml
##
## Visual Studio Code
##
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json

View file

@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View file

@ -0,0 +1,66 @@
using System.Collections.Generic;
namespace graphs {
class BFS<T> where T : notnull {
private Graph<T> graph;
private Dictionary<T, int> Distance = new Dictionary<T, int>();
private Dictionary<T, T?> Parent = new Dictionary<T, T?>();
private Dictionary<T, Color> State = new Dictionary<T, Color>();
public BFS(Graph<T> graph) {
this.graph = graph;
}
public BFS<T> Run() {
foreach (var vertex in graph.Vertices) {
if (ColorOf(vertex) == Color.White) {
RunFrom(vertex);
}
}
return this;
}
public BFS<T> RunFrom(T start) {
State[start] = Color.Gray;
Distance[start] = 0;
Parent[start] = default(T);
var queue = new Queue<T>();
queue.Enqueue(start);
while (queue.Count > 0) {
var u = queue.Dequeue();
for (var iterator = graph.GetEdgesFrom(u); iterator.MoveNext();) {
var v = iterator.Current;
if (GetOrDefault(State, v, Color.White) == Color.White) {
State[v] = Color.Gray;
Distance[v] = Distance[u] + 1;
Parent[v] = u;
queue.Enqueue(v);
}
}
State[u] = Color.Black;
}
return this;
}
private static V GetOrDefault<U, V>(Dictionary<U, V> flags, U u, V defaultValue)
where U : notnull {
if (flags.TryGetValue(u, out var flag)) {
return flag;
}
return defaultValue;
}
public int DistanceTo(T u) => GetOrDefault(Distance, u, 0);
public T? ParentOf(T u) => GetOrDefault(Parent, u, default(T));
public Color ColorOf(T u) => GetOrDefault(State, u, Color.White);
}
}

View file

@ -0,0 +1,68 @@
using System.Collections.Generic;
namespace graphs {
class DFS<T> where T : notnull {
private Graph<T> graph;
private int time;
private Dictionary<T, int> Discovered = new Dictionary<T, int>();
private Dictionary<T, int> Finished = new Dictionary<T, int>();
private Dictionary<T, Color> State = new Dictionary<T, Color>();
public DFS(Graph<T> graph) {
this.graph = graph;
}
public DFS<T> Run() {
time = 0;
foreach (var vertex in graph.Vertices) {
if (ColorOf(vertex) == Color.White) {
RunFrom(vertex, false);
}
}
return this;
}
public DFS<T> RunFrom(T start, bool reset = true) {
var path = new Stack<(T, IEnumerator<T>)>();
if (reset) {
time = 0;
}
(Discovered[start], State[start]) = (++time, Color.Gray);
path.Push((start, graph.GetEdgesFrom(start)));
while (path.Count > 0) {
var (lastVertex, successors) = path.Peek();
if (!successors.MoveNext()) {
path.Pop();
(Finished[lastVertex], State[lastVertex]) = (++time, Color.Black);
} else if (ColorOf(successors.Current) == Color.White) {
var nextVertex = successors.Current;
(Discovered[nextVertex], State[nextVertex]) = (++time, Color.Gray);
path.Push((nextVertex, graph.GetEdgesFrom(nextVertex)));
}
}
return this;
}
private static V GetOrDefault<U, V>(Dictionary<U, V> flags, U u, V defaultValue)
where U : notnull
where V : notnull {
if (flags.TryGetValue(u, out var flag)) {
return flag;
}
return defaultValue;
}
public int DiscoveredAt(T u) => GetOrDefault(Discovered, u, 0);
public int FinishedAt(T u) => GetOrDefault(Finished, u, 0);
public Color ColorOf(T u) => GetOrDefault(State, u, Color.White);
}
}

View file

@ -0,0 +1,44 @@
using System.Collections.Generic;
using System.Linq;
namespace graphs {
enum Color {
White, Gray, Black
}
class Graph<T> where T : notnull {
private SortedSet<T> vertices = new SortedSet<T>();
private SortedDictionary<T, SortedSet<T>> edges = new SortedDictionary<T, SortedSet<T>>();
public SortedSet<T> Vertices {
get => vertices;
}
public void AddVertex(T u) {
vertices.Add(u);
edges.Add(u, new SortedSet<T>());
}
public void AddEdge(T u, T v) {
if (edges.TryGetValue(u, out var edgesFromU)) {
edgesFromU.Add(v);
}
}
public bool HasEdge(T u, T v) {
if (edges.TryGetValue(u, out var edgesFromU)) {
return edgesFromU.Contains(v);
}
return false;
}
public IEnumerator<T> GetEdgesFrom(T u) {
if (edges.TryGetValue(u, out var edgesFromU)) {
return edgesFromU.GetEnumerator();
}
return Enumerable.Empty<T>().GetEnumerator();
}
}
}

View file

@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
namespace graphs {
class Program {
static Graph<string> CreateExampleGraph() {
var vertices = new List<string>() {
"s", "q", "t", "y", "r", "v", "w", "x", "z", "u"
};
var graph = new Graph<string>();
foreach (var vertex in vertices) {
graph.AddVertex(vertex);
}
graph.AddEdge("s", "v");
graph.AddEdge("q", "s");
graph.AddEdge("q", "w");
graph.AddEdge("q", "t");
graph.AddEdge("t", "y");
graph.AddEdge("t", "x");
graph.AddEdge("y", "q");
graph.AddEdge("r", "y");
graph.AddEdge("r", "u");
graph.AddEdge("v", "w");
graph.AddEdge("w", "s");
graph.AddEdge("x", "w");
graph.AddEdge("x", "z");
graph.AddEdge("z", "x");
graph.AddEdge("u", "y");
return graph;
}
static void Main(string[] args) {
var graph = CreateExampleGraph();
var dfsTraversal = new DFS<string>(graph).Run();
foreach (var vertex in graph.Vertices) {
Console.WriteLine($"{vertex}(d: {dfsTraversal.DiscoveredAt(vertex)}, f: {dfsTraversal.FinishedAt(vertex)})");
}
}
}
}

View file

@ -0,0 +1,139 @@
from hypothesis import given, settings
from hypothesis.strategies import integers, lists
import pytest
import itertools
def compare_by_value(pair):
"""
Takes a pair from enumerate in form: `index, value` and returns the value
Args:
pair (Tuple[int, T]): Index and element from the iterator at the index.
Returns:
Element from the pair.
"""
index, value = pair
return value
def maximum(arr, n):
"""
Finds index of maximum element of first n elements in list.
Args:
arr (List): List of values.
n (int): Upper bound of index where to search for maximum (inclusive).
Returns:
Index of a maximum element in `arr[:n]`.
"""
first_n_elements = itertools.islice(enumerate(arr), n)
index, value = max(first_n_elements, key=compare_by_value)
return index
# Precondition: n = |A|
# Loop invariant:
# A[i + 1 : n] is sorted AND
# all elements of A[i + 1 : n] are bigger or equal to the other elements
# Postcondition: A is sorted
def select_sort(arr, n):
"""
Sorts list `arr` using select sort algorithm.
Args:
arr (List): List of values.
n (int): Size of the list.
Returns:
Sorted list `arr`.
"""
assert n == len(arr)
check_loop_invariant(arr, n, n)
for i in reversed(range(1, n)):
j = maximum(arr, i + 1)
arr[i], arr[j] = arr[j], arr[i]
check_loop_invariant(arr, n, i)
return arr
def broken_select_sort(arr, n):
assert n == len(arr)
if not arr:
return
max_value = max(arr)
check_loop_invariant(arr, n, n)
for i in reversed(range(n)):
arr[i] = max_value + i
check_loop_invariant(arr, n, i)
return arr
def check_loop_invariant(arr, n, i):
# A[i + 1 : n] is sorted
for x, y in zip(itertools.islice(arr, i + 1, n), itertools.islice(arr, i + 2, n)):
assert x <= y
# all elements of A[i + 1 : n] are bigger or equal to the other elements
if i + 1 >= n:
# in case there are no elements
return
# otherwise, since the "tail" is sorted, we can assume that it is enough to
# check the other elements to the smallest value of the tail
smallest = arr[i + 1]
for element in itertools.islice(arr, i + 1):
assert smallest >= element
def check_vague_postcondition(original_arr, arr):
if not arr:
return
# check ordering
for x, y in zip(arr, itertools.islice(arr, 1, len(arr))):
assert x <= y
def check_postcondition(original_arr, arr):
if not arr:
return
# check ordering
for x, y in zip(arr, itertools.islice(arr, 1, len(arr))):
assert x <= y
# get counts from original list
original_counts = {}
for value in original_arr:
original_counts[value] = 1 + original_counts.get(value, 0)
# get counts from resulting list
counts = {}
for value in arr:
counts[value] = 1 + counts.get(value, 0)
# if arr is permutation of original_arr then all counts must be the same
assert counts == original_counts
@given(lists(integers()))
@settings(max_examples=1000)
@pytest.mark.parametrize(
"postcondition", [check_vague_postcondition, check_postcondition]
)
@pytest.mark.parametrize("sorting_function", [select_sort, broken_select_sort])
def test_select_sort(sorting_function, postcondition, numbers):
result = sorting_function(numbers[:], len(numbers))
postcondition(numbers, result)

View file

View file

View file

@ -0,0 +1,264 @@
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* If you want to see arrays before and after sorting, uncomment next line */
// #define DEBUG_OUTPUT
/**
* @brief Swaps two elements at given addresses of given size.
* @param left Pointer to the first element.
* @param right Pointer to the second element.
* @param size Size of the memory one element takes.
*/
void swap(void *left, void *right, size_t size)
{
/* TODO */
}
/**
* @brief Get index of biggest element in the array.
* @param ptr Pointer to the first element of the array.
* @param count Count of the elements in the array.
* @param size Size of one element in the array.
* @param comp Comparator that is used to decide ordering of the elements.
* @returns Index of the biggest element given the ordering.
*/
size_t maximum(void *ptr, size_t count, size_t size, int (*comp)(const void *, const void *))
{
/* Pseudocode:
* ===========
* max_index <- 0
* FOR i <- 1 TO n - 1 DO
* IF A[i] > A[max_index] THEN
* max_index <- i
* FI
* OD
* RETURN max_index
*/
/* TODO */
return 0;
}
/**
* @brief Sort array in-situ using select-sort.
* @param ptr Pointer to the first element of the array.
* @param count Count of the elements in the array.
* @param size Size of one element in the array.
* @param comp Comparator that is used to decide ordering of the elements.
*/
void select_sort(void *ptr, size_t count, size_t size, int (*comp)(const void *, const void *))
{
/* Pseudocode:
* ===========
* FOR i <- n - 1 DOWNTO 1 DO
* j <- MAXIMUM(A, i + 1)
* SWAP(A, i, j)
* OD
*/
/* TODO */
}
/**
* @brief Compares two integers that are given through generic pointers.
* @param x Pointer to the integer x.
* @param y Pointer to the integer y.
* @returns 0 if x == y, <0 if x < y, >0 otherwise.
*/
static int int_comparator(const void *x, const void *y)
{
/* TODO */
return 1;
}
/**
* @brief Compares two characters by ASCII value.
* @param x Pointer to the character x.
* @param y Pointer to the character y.
* @returns 0 if x == y, <0 if x < y, >0 otherwise.
*/
static int char_comparator(const void *x, const void *y)
{
char x_value = *(const char *) x;
char y_value = *(const char *) y;
return x_value - y_value;
}
/**
* @brief Compares two characters by ASCII value in a reversed order.
* @param x Pointer to the character x.
* @param y Pointer to the character y.
* @returns 0 if x == y, >0 if x < y, <0 otherwise.
*/
static int char_reversed_comparator(const void *x, const void *y)
{
char x_value = *(const char *) x;
char y_value = *(const char *) y;
return y_value - x_value;
}
// #pragma region TESTS
/**
* @brief Check if array is sorted.
* @param ptr Pointer to the first element of the array.
* @param count Count of the elements in the array.
* @param size Size of one element in the array.
* @param comp Comparator that is used to decide ordering of the elements.
*/
static void check_if_sorted(void *ptr, size_t count, size_t size, int (*comp)(const void *, const void *))
{
char *left = ptr;
char *right = (char *) ptr + size;
for (size_t i = 0; i < count - 1; i++) {
assert(comp(left, right) <= 0);
left += size;
right += size;
}
}
#ifdef DEBUG_OUTPUT
/**
* @brief Print numbers from an array.
* @param array Pointer to the first element of the array.
* @param count Count of the elements in the array.
*/
static void print_numbers(int *array, size_t count)
{
for (size_t i = 0; i < count; i++) {
printf(" %d", array[i]);
}
}
#endif
/**
* @brief Run some basic tests on integer arrays.
*/
static void check_int_arrays()
{
/* You are free to add any other examples you like, in case you want to add
* array with more than 10 elements, please adjust the size.
*/
size_t examples_count = 5;
int examples[][10] = {
{ -1, 50, -10, 20, 30, 0, -100 },
{ -100, 0, 30, 20, -10, 50, -1 },
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
{ -1, -2, -3, -4, -5, -6, -7, -8, -9, -10 },
{ 0, 0, 0, 0, 0, 0, 0, 0 }
};
printf("[TEST] Integer arrays\n");
for (size_t i = 0; i < examples_count; i++) {
size_t count = sizeof(examples[i]) / sizeof(int);
#ifdef DEBUG_OUTPUT
printf("Before sorting:");
print_numbers(examples[i], count);
putchar('\n');
#endif
select_sort(examples[i], count, sizeof(int), int_comparator);
#ifdef DEBUG_OUTPUT
printf("After sorting:");
print_numbers(examples[i], count);
printf("\n\n");
#endif
check_if_sorted(examples[i], count, sizeof(int), int_comparator);
}
printf("[PASS] Tests passed.\n\n");
}
/**
* @brief Run some basic tests on strings. Also with reversed ordering.
*/
static void check_char_arrays()
{
#define MAX_SIZE 20
/* You are free to add any other examples you like, in case you want to add
* strings with more than 10 characters, please adjust the size.
* mind the terminator ;)
*/
const size_t examples_count = 5;
char examples[][MAX_SIZE] = {
"Hello World!",
"hi",
"aloha",
"LET US SORT",
"LeT uS sOrT"
};
printf("[TEST] Char arrays\n");
for (size_t i = 0; i < examples_count; i++) {
size_t count = strlen(examples[i]);
char temp_array[MAX_SIZE];
strncpy(temp_array, examples[i], MAX_SIZE);
select_sort(temp_array, count, 1, char_comparator);
#ifdef DEBUG_OUTPUT
printf("Before sorting: \"%s\"\n", examples[i]);
printf("After sorting: \"%s\"\n\n", temp_array);
#endif
check_if_sorted(temp_array, count, 1, char_comparator);
}
printf("[PASS] Tests passed.\n\n");
printf("[TEST] Char arrays reversed\n");
for (size_t i = 0; i < examples_count; i++) {
size_t count = strlen(examples[i]);
char temp_array[MAX_SIZE];
strncpy(temp_array, examples[i], MAX_SIZE);
select_sort(temp_array, count, 1, char_reversed_comparator);
#ifdef DEBUG_OUTPUT
printf("Before sorting: \"%s\"\n", examples[i]);
printf("After sorting: \"%s\"\n\n", temp_array);
#endif
check_if_sorted(temp_array, count, 1, char_reversed_comparator);
}
printf("[PASS] Tests passed.\n\n");
#undef MAX_SIZE
}
static void annotate(const char *description, bool result)
{
printf("[TEST] %s\n", description);
assert(result);
printf("[PASS] Test passed.\n\n");
}
static void check_int_comparator()
{
int a = 5, b = -10, c = -10;
annotate("Test comparator for: a > b", int_comparator(&a, &b) > 0);
annotate("Test comparator for: b < a", int_comparator(&b, &a) < 0);
annotate("Test comparator for: b = c", int_comparator(&b, &c) == 0);
annotate("Test comparator for: a = a", int_comparator(&a, &a) == 0);
annotate("Test comparator for: b = b", int_comparator(&b, &b) == 0);
annotate("Test comparator for: c = c", int_comparator(&c, &c) == 0);
}
// #pragma endregion TESTS
int main(void)
{
/* Neither of those tests check for bad behaviour, like overwriting array
* with elements satisfying ordering. **I** check those :scheming:
*/
check_int_comparator();
check_int_arrays();
check_char_arrays();
return 0;
}

View file

@ -0,0 +1,141 @@
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* If you want to see arrays before and after sorting, uncomment next line */
// #define DEBUG_OUTPUT
/**
* @brief Swaps two elements at given addresses.
* @param left Pointer to the first element.
* @param right Pointer to the second element.
*/
void swap(int *left, int *right)
{
/* TODO */
}
/**
* @brief Get index of biggest element in the array.
* @param ptr Pointer to the first element of the array.
* @param count Count of the elements in the array.
* @returns Index of the biggest element given the ordering.
*/
size_t maximum(int *ptr, size_t count)
{
/* Pseudocode:
* ===========
* max_index <- 0
* FOR i <- 1 TO n - 1 DO
* IF A[i] > A[max_index] THEN
* max_index <- i
* FI
* OD
* RETURN max_index
*/
/* TODO */
return 0;
}
/**
* @brief Sort array in-situ using select-sort.
* @param ptr Pointer to the first element of the array.
* @param count Count of the elements in the array.
*/
void select_sort(int *ptr, size_t count)
{
/* Pseudocode:
* ===========
* FOR i <- n - 1 DOWNTO 1 DO
* j <- MAXIMUM(A, i + 1)
* SWAP(A, i, j)
* OD
*/
/* TODO */
}
// #pragma region TESTS
/**
* @brief Check if array is sorted.
* @param ptr Pointer to the first element of the array.
* @param count Count of the elements in the array.
*/
static void check_if_sorted(int *ptr, size_t count)
{
int *left = ptr;
int *right = ptr + 1;
for (size_t i = 0; i < count - 1; i++) {
assert(*left <= *right);
left++;
right++;
}
}
#ifdef DEBUG_OUTPUT
/**
* @brief Print numbers from an array.
* @param array Pointer to the first element of the array.
* @param count Count of the elements in the array.
*/
static void print_numbers(int *array, size_t count)
{
for (size_t i = 0; i < count; i++) {
printf(" %d", array[i]);
}
}
#endif
/**
* @brief Run some basic tests on integer arrays.
*/
static void check_int_arrays()
{
/* You are free to add any other examples you like, in case you want to add
* array with more than 10 elements, please adjust the size.
*/
size_t examples_count = 5;
int examples[][10] = {
{ -1, 50, -10, 20, 30, 0, -100 },
{ -100, 0, 30, 20, -10, 50, -1 },
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
{ -1, -2, -3, -4, -5, -6, -7, -8, -9, -10 },
{ 0, 0, 0, 0, 0, 0, 0, 0 }
};
printf("[TEST] Integer arrays\n");
for (size_t i = 0; i < examples_count; i++) {
size_t count = sizeof(examples[i]) / sizeof(int);
#ifdef DEBUG_OUTPUT
printf("Before sorting:");
print_numbers(examples[i], count);
putchar('\n');
#endif
select_sort(examples[i], count);
#ifdef DEBUG_OUTPUT
printf("After sorting:");
print_numbers(examples[i], count);
printf("\n\n");
#endif
check_if_sorted(examples[i], count);
}
printf("[PASS] Tests passed.\n\n");
}
// #pragma endregion TESTS
int main(void)
{
/* Neither of those tests check for bad behaviour, like overwriting array
* with elements satisfying ordering. **I** check those :scheming:
*/
check_int_arrays();
return 0;
}

View file

@ -0,0 +1,12 @@
CC=gcc
CFLAGS=-std=c99 -Wall -Wextra -Werror -Wpedantic
main:
$(CC) $(CFLAGS) main.c -o main
main_light:
$(CC) $(CFLAGS) main_light.c -o main_light
check: main main_light
valgrind ./main
valgrind ./main_light

View file

@ -0,0 +1,25 @@
cmake_minimum_required(VERSION 3.0)
# Project configuration
project(seminar04-bonus-maze)
set(SOURCES maze.h maze.c)
set(EXECUTABLE maze)
# Executable
add_executable(maze ${SOURCES} main.c)
add_executable(test_maze ${SOURCES} cut.h test_maze.c)
# Configure compiler warnings
if (CMAKE_C_COMPILER_ID MATCHES Clang OR ${CMAKE_C_COMPILER_ID} STREQUAL GNU)
# using regular Clang, AppleClang or GCC
# Strongly suggested: neable -Werror
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=gnu11 -Wall -Wextra -pedantic")
elseif (${CMAKE_C_COMPILER_ID} STREQUAL MSVC)
# using Visual Studio C++
target_compile_definitions(${EXECUTABLE} PRIVATE _CRT_SECURE_NO_DEPRECATE)
set(CMAKE_CXX_FLAGS "/permissive- /W4 /EHsc")
endif()
if(MINGW)
target_compile_definitions(${EXECUTABLE} PRIVATE __USE_MINGW_ANSI_STDIO=1)
endif()

View file

@ -0,0 +1,8 @@
#include "maze.h"
#include <stdio.h>
int main(void)
{
return 0;
}

View file

@ -0,0 +1,84 @@
#include "maze.h"
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
/**
* @brief Checks if pointer points inside the memory specified by upper and lower
* bound.
* @param first Start of the allocated memory.
* @param last First address that is not included in the allocated memory.
* @param pos Pointer to memory.
* @returns <code>true</code> if pos points to the memory [first, last), <code>
* false</code> otherwise.
*/
static bool within_bounds(const char *first, const char *last, const char *pos)
{
/* TODO */
}
/**
* @brief Sets 2D coordinates of the pointer.
* @param map Start of the 2D memory.
* @param position Pointer to the map.
* @param width Width of one row of the map.
* @param row Output variable where the row is set.
* @param col Output variable where the column is set.
*/
static void set_coordinates(const char *map, char *position, size_t width, size_t *row, size_t *col)
{
/* TODO */
}
/**
* @brief Checks if indices are within bounds of the 2D map.
* @param width Width of the map.
* @param height Height of the map.
* @param row Row to be checked.
* @param col Column to be checked.
* @returns <code>true</code> if row,col are within bounds of the map,.<code>false
* </code> otherwise.
*/
static bool within_bounds_by_index(size_t width, size_t height, size_t row, size_t col)
{
/* TODO */
}
void print_maze(const char *map, char *position, char direction, size_t width, size_t height)
{
printf("Maze:\n");
for (size_t row = 0; row < height; row++) {
for (size_t col = 0; col < width; col++) {
const char *current = &map[row * width + col];
if (current == position) {
switch (direction) {
case '^':
putchar('N');
break;
case 'v':
putchar('S');
break;
case '>':
putchar('E');
break;
case '<':
putchar('W');
break;
}
continue;
}
putchar(*current);
}
putchar('\n');
}
putchar('\n');
}
enum end_state_t walk(const char *map, char *position, char direction, size_t width, size_t height)
{
/* TODO */
return NONE;
}

View file

@ -0,0 +1,33 @@
#include <stdlib.h>
enum end_state_t
{
NONE,
FOUND_KEY,
FOUND_TREASURE,
OUT_OF_BOUNDS,
INFINITE_LOOP,
};
/**
* @brief Prints maze and the robot within it.
* @param map Map of the maze.
* @param position Current position of the robot.
* @param direction Direction the robot is facing, one of "^v<>".
* @param width Width of the map.
* @param height Height of the map.
*/
void print_maze(const char *map, char *position, char direction, size_t width, size_t height);
/**
* @brief Get end state of the robot after his walk.
* @param map Map of the maze.
* @param position Initial position of the robot in the maze.
* @param direction Direction the robot is facing at the beginning. You can assume
* correctness of this value.
* @param width Width of the maze. You can assume correctness of this value.
* @param height Height of the maze. You can assume correctness of this value.
* @returns End state of the robot after his walk is finished or has been terminated
* manually.
*/
enum end_state_t walk(const char *map, char *position, char direction, size_t width, size_t height);

View file

@ -0,0 +1,246 @@
#include "maze.h"
#define CUT_MAIN
#include "cut.h"
static void check_result(char *map, size_t position, char direction, size_t width, size_t height, enum end_state_t expected)
{
enum end_state_t state = walk(map, &map[position], direction, width, height);
ASSERT(state == expected);
}
TEST(basic)
{
SUBTEST(spawns_on_treasure)
{
check_result(("T."
".."),
0,
'>',
2,
2,
FOUND_TREASURE);
}
SUBTEST(spawns_on_key)
{
check_result(("K."
".."),
0,
'^',
2,
2,
FOUND_KEY);
}
SUBTEST(spawns_on_treasure_in_middle)
{
check_result(("..."
".T."
"..."),
4,
'v',
3,
3,
FOUND_TREASURE);
}
}
TEST(some_walking)
{
SUBTEST(straight_up)
{
check_result((".T."
"..."
"..."),
7,
'^',
3,
3,
FOUND_TREASURE);
}
SUBTEST(down)
{
check_result(("..........................T"), 7, 'v', 1, 27, FOUND_TREASURE);
}
SUBTEST(to_right)
{
check_result(("..........................K"), 2, '>', 27, 1, FOUND_KEY);
}
SUBTEST(to_left)
{
check_result(("K.........................."), 15, '<', 27, 1, FOUND_KEY);
}
}
TEST(follows_directions)
{
SUBTEST(basic)
{
check_result((">..v"
"...."
"...K"
"^..<"),
12,
'>',
4,
4,
FOUND_KEY);
}
SUBTEST(no_way_to_avoid)
{
const char *directions = "<>^v";
for (size_t row = 0; row < 5; row++) {
for (size_t col = 0; col < 5; col++) {
for (size_t dir = 0; dir < 4; dir++) {
check_result((">>>>v"
"^>>vv"
"^^T<v"
"^^<<<"
"^<<<<"),
row * 5 + col,
directions[dir],
5,
5,
FOUND_TREASURE);
}
}
}
}
}
TEST(follows_directions_even_to_doom)
{
SUBTEST(to_right)
{
check_result((".>.."
"^KTK"
".TvT"
"...<"),
1,
'>',
4,
4,
OUT_OF_BOUNDS);
}
SUBTEST(to_up)
{
check_result((".>.."
"^KTK"
".TvT"
"...<"),
4,
'>',
4,
4,
OUT_OF_BOUNDS);
}
SUBTEST(to_down)
{
check_result((".>.."
"^KTK"
".TvT"
"...<"),
10,
'>',
4,
4,
OUT_OF_BOUNDS);
}
SUBTEST(to_left)
{
check_result((".>.."
"^KTK"
".TvT"
"...<"),
15,
'>',
4,
4,
OUT_OF_BOUNDS);
}
}
TEST(mean)
{
SUBTEST(out_of_bounds_at_the_beginning)
{
check_result((".."
".."),
4,
'v',
2,
2,
OUT_OF_BOUNDS);
check_result((".."
".."),
5,
'v',
2,
2,
OUT_OF_BOUNDS);
check_result((".."
".."),
(size_t) -1,
'v',
2,
2,
OUT_OF_BOUNDS);
check_result((">T<"
"..."
"^.^"),
10,
'^',
3,
3,
OUT_OF_BOUNDS);
}
}
TEST(infinite_bonus)
{
SUBTEST(easy)
{
check_result((">.v"
"..."
"^.<"),
0,
'v',
3,
3,
INFINITE_LOOP);
}
SUBTEST(medium)
{
check_result((">v"
"^<"),
2,
'v',
2,
2,
INFINITE_LOOP);
}
SUBTEST(hard)
{
check_result(("v.v"
"..."
"^.^"),
0,
'>',
3,
3,
INFINITE_LOOP);
}
SUBTEST(harder)
{
check_result((">.v.."
"....."
"^...<"
"....."
"..>.^"),
4,
'v',
5,
5,
INFINITE_LOOP);
}
}

View file

@ -0,0 +1,25 @@
cmake_minimum_required(VERSION 3.0)
# Project configuration
project(seminar05-06-bonus-bmp)
set(SOURCES bmp.h bmp.c)
set(EXECUTABLE bmp)
# Executable
add_executable(bmp ${SOURCES} main.c)
add_executable(test_bmp ${SOURCES} cut.h test_bmp.c)
# Configure compiler warnings
if (CMAKE_C_COMPILER_ID MATCHES Clang OR ${CMAKE_C_COMPILER_ID} STREQUAL GNU)
# using regular Clang, AppleClang or GCC
# Strongly suggested: neable -Werror
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=gnu11 -Wall -Wextra -pedantic")
elseif (${CMAKE_C_COMPILER_ID} STREQUAL MSVC)
# using Visual Studio C++
target_compile_definitions(${EXECUTABLE} PRIVATE _CRT_SECURE_NO_DEPRECATE)
set(CMAKE_CXX_FLAGS "/permissive- /W4 /EHsc")
endif()
if(MINGW)
target_compile_definitions(${EXECUTABLE} PRIVATE __USE_MINGW_ANSI_STDIO=1)
endif()

View file

@ -0,0 +1,153 @@
#include "bmp.h"
#include <ctype.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#define UNUSED(var) ((void) (var))
/**
* Return reversed string.
*
* Function returns a pointer to the reversed string, which has been created
* from the input parameter. If the input string is NULL or memory could not be
* allocated, function returns NULL.
*
* @param text input string
* @return reversed representation of input string, or NULL, if the string could
* not be created.
*/
char *reverse(const char *text)
{
/* TODO */
UNUSED(text);
return NULL;
}
/**
* @brief Checks if key is valid.
* @param key String that is used as a key
* @returns true, if key is valid; false otherwise
*/
static bool check_key(const char *key)
{
/* TODO */
UNUSED(key);
return false;
}
/**
* Function for encrypting the given plaintext by applying the Vigenère cipher.
*
* @param key Pointer to a string representing the key which will be used
* for encrypting the plaintext. The key is represented by a single
* case-insensitive word consisting of only alphabetical characters.
* @param text Pointer to a string representing the plaintext to be
* encrypted.
* @return the address of a copy of the ciphertext encrypted by the Vigenère
* cipher, or NULL if the encryption was not successful.
*/
char *vigenere_encrypt(const char *key, const char *text)
{
/* TODO */
UNUSED(key);
UNUSED(text);
return NULL;
}
/**
* Function for decrypting the given ciphertext by applying the Vigenère cipher.
*
* @param key Pointer to a string representing the key which has been used
* for encrypting the ciphertext. The key is represented by a single
* case-insensitive word consisting of only alphabetical characters.
* @param text Pointer to a string representing the ciphertext to be
* decrypted.
* @return the address of a copy of the plaintext decrypted by the Vigenère
* cipher, or NULL if the decryption was not successful.
*/
char *vigenere_decrypt(const char *key, const char *text)
{
/* TODO */
UNUSED(key);
UNUSED(text);
return NULL;
}
/**
* Function for bitwise encryption according to the following process:
* The character about to be encrypted is divided in half (4 bits + 4 bits).
* Subsequently, the bits in the left half are divided into two pairs and the
* values inside each pair are swapped. The four bits created by this way are
* then used in a bitwise XOR operation with the remaining 4 bits.
*
* @param text String representing the plaintext to be encrypted.
* @return a pointer to a newly created string containing the ciphertext
* produced by encrypting the plaintext, or NULL if the encryption was not
* successful.
*/
unsigned char *bit_encrypt(const char *text)
{
/* TODO */
UNUSED(text);
return NULL;
}
/**
* Function for bitwise decryption - it is the inverse of the bitwise encryption
* function.
*
* @param text String representing the ciphertext to be decrypted.
* @return a pointer to a newly created string containing the plaintext produced
* by decrypting the ciphertext, or NULL if the decryption was not successful.
*/
char *bit_decrypt(const unsigned char *text)
{
/* TODO */
UNUSED(text);
return NULL;
}
/**
* Function for encrypting the given plaintext by applying the BMP cipher.
* The process of encrypting by BMP:
* <ol>
* <li> the provided input string is encrypted by function reverse()
* <li> the acquired string is encrypted by function vigenere_encrypt()
* <li> function bit_encrypt() is applied on the resulting string
* </ol>
*
* @param key Pointer to a string representing the key which will be used
* for encrypting the plaintext. The key is represented by a single
* case-insensitive word consisting of only alphabetical characters.
* @param text String representing the plaintext to be encrypted.
* @return the address of a copy of the ciphertext encrypted by the BMP cipher,
* or NULL if the encryption was not successful.
*/
unsigned char *bmp_encrypt(const char *key, const char *text)
{
/* TODO */
UNUSED(key);
UNUSED(text);
return NULL;
}
/**
* Function for decrypting the given ciphertext by applying the BMP cipher.
* The process of decrypting by BMP is the opposite of BMP encryption.
*
* @param key Pointer to a string representing the key which has been used
* for encrypting the ciphertext. The key is represented by a single
* case-insensitive word consisting of only alphabetical characters.
* @param text String representing the ciphertext to be decrypted.
* @return the address of a copy of the plaintext decrypted by the BMP cipher,
* or NULL if the decryption was not successful.
*/
char *bmp_decrypt(const char *key, const unsigned char *text)
{
/* TODO */
UNUSED(key);
UNUSED(text);
return NULL;
}

View file

@ -0,0 +1,98 @@
#ifndef _BMP_H
#define _BMP_H
/**
* Return reversed string.
*
* Function returns a pointer to the reversed string, which has been created
* from the input parameter. If the input string is NULL or memory could not be
* allocated, function returns NULL.
*
* @param text input string
* @return reversed representation of input string, or NULL, if the string could
* not be created.
*/
char *reverse(const char *text);
/**
* Function for encrypting the given plaintext by applying the Vigenère cipher.
*
* @param key Pointer to a string representing the key which will be used
* for encrypting the plaintext. The key is represented by a single
* case-insensitive word consisting of only alphabetical characters.
* @param text Pointer to a string representing the plaintext to be
* encrypted.
* @return the address of a copy of the ciphertext encrypted by the Vigenère
* cipher, or NULL if the encryption was not successful.
*/
char *vigenere_encrypt(const char *key, const char *text);
/**
* Function for decrypting the given ciphertext by applying the Vigenère cipher.
*
* @param key Pointer to a string representing the key which has been used
* for encrypting the ciphertext. The key is represented by a single
* case-insensitive word consisting of only alphabetical characters.
* @param text Pointer to a string representing the ciphertext to be
* decrypted.
* @return the address of a copy of the plaintext decrypted by the Vigenère
* cipher, or NULL if the decryption was not successful.
*/
char *vigenere_decrypt(const char *key, const char *text);
/**
* Function for bitwise encryption according to the following process:
* The character about to be encrypted is divided in half (4 bits + 4 bits).
* Subsequently, the bits in the left half are divided into two pairs and the
* values inside each pair are swapped. The four bits created by this way are
* then used in a bitwise XOR operation with the remaining 4 bits.
*
* @param text String representing the plaintext to be encrypted.
* @return a pointer to a newly created string containing the ciphertext
* produced by encrypting the plaintext, or NULL if the encryption was not
* successful.
*/
unsigned char *bit_encrypt(const char *text);
/**
* Function for bitwise decryption - it is the inverse of the bitwise encryption
* function.
*
* @param text String representing the ciphertext to be decrypted.
* @return a pointer to a newly created string containing the plaintext produced
* by decrypting the ciphertext, or NULL if the decryption was not successful.
*/
char *bit_decrypt(const unsigned char *text);
/**
* Function for encrypting the given plaintext by applying the BMP cipher.
* The process of encrypting by BMP:
* <ol>
* <li> the provided input string is encrypted by function reverse()
* <li> the acquired string is encrypted by function vigenere_encrypt()
* <li> function bit_encrypt() is applied on the resulting string
* </ol>
*
* @param key Pointer to a string representing the key which will be used
* for encrypting the plaintext. The key is represented by a single
* case-insensitive word consisting of only alphabetical characters.
* @param text String representing the plaintext to be encrypted.
* @return the address of a copy of the ciphertext encrypted by the BMP cipher,
* or NULL if the encryption was not successful.
*/
unsigned char *bmp_encrypt(const char *key, const char *text);
/**
* Function for decrypting the given ciphertext by applying the BMP cipher.
* The process of decrypting by BMP is the opposite of BMP encryption.
*
* @param key Pointer to a string representing the key which has been used
* for encrypting the ciphertext. The key is represented by a single
* case-insensitive word consisting of only alphabetical characters.
* @param text String representing the ciphertext to be decrypted.
* @return the address of a copy of the plaintext decrypted by the BMP cipher,
* or NULL if the decryption was not successful.
*/
char *bmp_decrypt(const char *key, const unsigned char *text);
#endif

View file

@ -0,0 +1,8 @@
#include "playfair.h"
#include <stdio.h>
int main(void)
{
return 0;
}

View file

@ -0,0 +1,251 @@
#include "bmp.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#define CUT_MAIN
#include "cut.h"
void test_reverse(const char *input, const char *output)
{
char *reversed = reverse(input);
// check if not NULL
ASSERT(reversed != NULL);
int result = strcmp(reversed, output);
if (result != 0) {
DEBUG_MSG("Expected: %s, but got: %s\n", output, reversed);
}
ASSERT(strcmp(reversed, output) == 0);
free(reversed);
}
TEST(REVERSE)
{
SUBTEST(ABCD)
{
test_reverse("ABCD", "DCBA");
}
SUBTEST(BADACAD)
{
test_reverse("BADACAD", "DACADAB");
}
SUBTEST(qqsfyCCDAADQWQLLLlccaasq)
{
test_reverse("qqsfyCCDAADQWQLLLlccaasq", "QSAACCLLLLQWQDAADCCYFSQQ");
}
SUBTEST(NULL)
{
ASSERT(reverse(NULL) == NULL);
}
SUBTEST(EMPTY)
{
char *result = reverse("");
ASSERT(result[0] == '\0');
free(result);
}
SUBTEST(RANDOM)
{
test_reverse("hello", "OLLEH");
test_reverse("malloc", "COLLAM");
test_reverse("calloc", "COLLAC");
test_reverse("realloc", "COLLAER");
test_reverse("everything", "GNIHTYREVE");
test_reverse("failing", "GNILIAF");
test_reverse("LOL", "LOL");
test_reverse("1273912739&^%$$*((", "((*$$%^&9372193721");
}
}
void test_bit(const char *input, const unsigned char *output, size_t length)
{
unsigned char *encrypted = bit_encrypt(input);
char *decrypted = bit_decrypt(encrypted);
for (size_t i = 0; i < length; i++) {
ASSERT(encrypted[i] == output[i]);
ASSERT(decrypted[i] == input[i]);
}
free(decrypted);
free(encrypted);
}
TEST(BIT)
{
SUBTEST(HELLO_WORLD)
{
const unsigned char output[] = { 0x80, 0x9c, 0x95, 0x95, 0x96, 0x11, 0xbc, 0x96, 0xb9, 0x95, 0x9d, 0x10 };
test_bit("Hello world!", output, 12);
}
SUBTEST(MALLOC)
{
const unsigned char output[] = { 0x94, 0x98, 0x95, 0x95, 0x96, 0x9a };
test_bit("malloc", output, 6);
}
SUBTEST(CALLOC)
{
const unsigned char output[] = { 0x9a, 0x98, 0x95, 0x95, 0x96, 0x9a };
test_bit("calloc", output, 6);
}
SUBTEST(REALLOC)
{
const unsigned char output[] = { 0xb9, 0x9c, 0x98, 0x95, 0x95, 0x96, 0x9a };
test_bit("realloc", output, 7);
}
SUBTEST(EVERYTHING)
{
const unsigned char output[] = { 0x9c, 0xbd, 0x9c, 0xb9, 0xb2, 0xbf, 0x91, 0x90, 0x97, 0x9e };
test_bit("everything", output, 10);
}
SUBTEST(FAILING)
{
const unsigned char output[] = { 0x9f, 0x98, 0x90, 0x95, 0x90, 0x97, 0x9e };
test_bit("failing", output, 7);
}
SUBTEST(LOL)
{
const unsigned char output[] = { 0x84, 0x87, 0x84 };
test_bit("LOL", output, 3);
}
SUBTEST(GARBAGE)
{
const unsigned char output[] = { 0x32, 0x31, 0x34, 0x30, 0x3a, 0x32, 0x31, 0x34, 0x30, 0x3a, 0x17, 0xa4, 0x14, 0x15, 0x15, 0x1b, 0x19, 0x19 };
test_bit("1273912739&^%$$*((", output, 18);
}
SUBTEST(HELLO_FI)
{
const unsigned char output[] = { 0x91, 0x9c, 0x95, 0x95, 0x96 };
test_bit("hello", output, 5);
}
SUBTEST(BYE_FI)
{
const unsigned char output[] = { 0x9b, 0xb2, 0x9c };
test_bit("bye", output, 3);
}
}
void test_vigenere(const char *key, const char *input, const char *output, size_t length)
{
char *encrypted = vigenere_encrypt(key, input);
char *decrypted = vigenere_decrypt(key, encrypted);
ASSERT(encrypted != NULL);
ASSERT(decrypted != NULL);
for (size_t i = 0; i < length; i++) {
ASSERT(encrypted[i] == output[i]);
ASSERT(decrypted[i] == toupper(input[i]));
}
free(encrypted);
free(decrypted);
}
TEST(VIGENERE)
{
SUBTEST(HELLO_WORLD)
{
test_vigenere("CoMPuTeR", "Hello world!", "JSXAI PSINR!", 12);
}
SUBTEST(MALLOC)
{
test_vigenere("fails", "malloc", "RATWGH", 6);
}
SUBTEST(CALLOC)
{
test_vigenere("fails", "calloc", "HATWGH", 6);
}
SUBTEST(REALLOC)
{
test_vigenere("fails", "realloc", "WEIWDTC", 7);
}
SUBTEST(EVERYTHING)
{
test_vigenere("FAILS", "everything", "JVMCQYHQYY", 10);
}
SUBTEST(FAILING)
{
test_vigenere("fails", "failing", "KAQWASG", 7);
}
SUBTEST(LOL)
{
test_vigenere("oopsie", "LOL", "ZCA", 3);
}
SUBTEST(GARBAGE)
{
test_vigenere("fi", "1273912739&^%$$*((", "1273912739&^%$$*((", 18);
}
SUBTEST(HELLO_FI)
{
test_vigenere("fi", "hello", "MMQTT", 5);
}
SUBTEST(BYE_FI)
{
test_vigenere("fi", "bye", "GGJ", 3);
}
}
void test_bmp(const char *key, const char *input, const unsigned char *encrypted_expected, const char *decrypted_expected, size_t length)
{
unsigned char *encrypted = bmp_encrypt(key, input);
char *decrypted = bmp_decrypt(key, encrypted);
ASSERT(encrypted != NULL);
ASSERT(decrypted != NULL);
for (size_t i = 0; i < length; i++) {
ASSERT(encrypted[i] == encrypted_expected[i]);
ASSERT(decrypted[i] == decrypted_expected[i]);
}
free(encrypted);
free(decrypted);
}
TEST(BMP)
{
SUBTEST(HELLO)
{
const unsigned char encrypted_expected[] = { 0xae, 0xae, 0xab, 0x85, 0x85 };
test_bmp("fi", "hello", encrypted_expected, "HELLO", 5);
}
SUBTEST(FI)
{
const unsigned char encrypted_expected[] = { 0xaa, 0x82 };
test_bmp("hello", "fi", encrypted_expected, "FI", 2);
}
SUBTEST(RANDOM)
{
const unsigned char encrypted_expected[] = { 0xa9, 0x87, 0xaf, 0x87, 0x89, 0xa2 };
test_bmp("garbage", "random", encrypted_expected, "RANDOM", 6);
}
SUBTEST(LETS)
{
const unsigned char encrypted_expected[] = { 0x83, 0xa2, 0x81, 0x8c };
test_bmp("see", "lets", encrypted_expected, "LETS", 4);
}
SUBTEST(how)
{
const unsigned char encrypted_expected[] = { 0x8d, 0x80, 0xaa };
test_bmp("it", "how", encrypted_expected, "HOW", 3);
}
SUBTEST(works)
{
const unsigned char encrypted_expected[] = { 0xa9, 0x8b, 0x89, 0xa8, 0x80 };
test_bmp("asjdljasdja", "works", encrypted_expected, "WORKS", 5);
}
SUBTEST(NOSPACES)
{
const unsigned char encrypted_expected[] = { 0x8d, 0x81, 0x82, 0x85, 0xae, 0xa0, 0x89, 0xa8, 0xa0, 0x85, 0x84, 0x89, 0x85, 0x84, 0x89, 0x8e, 0x8a, 0x84, 0x8e, 0xac, 0x84, 0xa9, 0xa8, 0xac, 0xa2 };
test_bmp("meh", "longerTextThatHasNoSpaces", encrypted_expected, "LONGERTEXTTHATHASNOSPACES", 25);
}
SUBTEST(ayaya)
{
const unsigned char encrypted_expected[] = { 0x80, 0xa9, 0x80, 0x8e, 0xaf, 0x8e, 0x80, 0xa9, 0x80, 0x8e, 0xaf, 0x8e, 0x80, 0xa9, 0x80, 0x8e, 0xaf, 0x8e, 0x80, 0xa9, 0x80, 0x8e, 0xaf, 0x8e, 0x80, 0xa9, 0x80, 0x8e, 0xaf, 0x8e, 0x80, 0xa9, 0x80 };
test_bmp("HUH", "ayayayayayayayayayayayayayayayaya", encrypted_expected, "AYAYAYAYAYAYAYAYAYAYAYAYAYAYAYAYA", 33);
}
}

View file

@ -0,0 +1,24 @@
cmake_minimum_required(VERSION 3.0)
# Project configuration
project(seminar08-bonus)
set(SOURCES counting.c trees.c)
# Executable
add_executable(counting counting.c)
add_executable(trees trees.c)
# Configure compiler warnings
if (CMAKE_C_COMPILER_ID MATCHES Clang OR ${CMAKE_C_COMPILER_ID} STREQUAL GNU)
# using regular Clang, AppleClang or GCC
# Strongly suggested: neable -Werror
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=gnu11 -Wall -Wextra -pedantic")
elseif (${CMAKE_C_COMPILER_ID} STREQUAL MSVC)
# using Visual Studio C++
target_compile_definitions(${EXECUTABLE} PRIVATE _CRT_SECURE_NO_DEPRECATE)
set(CMAKE_CXX_FLAGS "/permissive- /W4 /EHsc")
endif()
if(MINGW)
target_compile_definitions(${EXECUTABLE} PRIVATE __USE_MINGW_ANSI_STDIO=1)
endif()

View file

@ -0,0 +1,10 @@
check-counting:
python3 test-bonus.py test counting
check-counting-bonus:
python3 test-bonus.py test counting --no-global-config
check: check-counting check-counting-bonus
clean:
rm -rf test-*/*.out_produced

View file

@ -0,0 +1,60 @@
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#define UNUSED(x) ((void) (x))
/**
* @brief Counts occurences of any substring in the file.
* @param file File where the substring is to be counted in.
* @param substring Substring to be counted.
* @returns Count of occurences of the substring the given file.
*/
long count_anything(FILE *file, const char *substring)
{
/* TODO */
UNUSED(file);
UNUSED(substring);
return 0;
}
/**
* @brief Counts ananas. Nothing more to it.
* @param file File where the ananas is to be counted in.
* @returns Count of occurences of ananas.
*/
long count_ananas(FILE *file)
{
return count_anything(file, "ananas");
}
/**
* @brief Writes given number to the file, character by character.
* @param file File where the number is supposed to be written.
* @param number Number to be written.
*/
void write_number(FILE *file, long number)
{
/* TODO */
UNUSED(file);
UNUSED(number);
}
/**
* @brief Main function of a program.
* @returns Exit code that denotes following:
* 0 in case of success
* 1 in case of invalid usage
* 2 in case of failure on input file
* 3 in case of failure on output file
*/
int main(int argc, char **argv)
{
if (argc < 3 || argc > 4) {
printf("Usage: %s <input-file> <output-file> [string-to-be-counted]\n", argv[0]);
return 1;
}
/* TODO */
return 0;
}

View file

@ -0,0 +1,4 @@
{
"args": ["{test_case}.in", "{test_case}.out_produced"],
"specialized_test": ["diff", "{test_case}.out", "{test_case}.out_produced"]
}

View file

@ -0,0 +1 @@
../../test-bonus.py

View file

@ -0,0 +1 @@
ananas

View file

@ -0,0 +1 @@
1

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1 @@
1747627

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1 @@
0

View file

@ -0,0 +1,65 @@
FGETC(3) Linux Programmer's Manual FGETC(3)
NAME
fgetc, fgets, getc, getchar, ungetc - input of characters and strings
SYNOPSIS
#include <stdio.h>
int fgetc(FILE *stream);
char *fgets(char *s, int size, FILE *stream);
int getc(FILE *stream);
int getchar(void);
int ungetc(int c, FILE *stream);
DESCRIPTION
fgetc() reads the next character from stream and returns it as an unsigned char cast to an int, or EOF on end of file or error.
getc() is equivalent to fgetc() except that it may be implemented as a macro which evaluates stream more than once.
getchar() is equivalent to getc(stdin).
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buf
fer. A terminating null byte ('\0') is stored after the last character in the buffer.
ungetc() pushes c back to stream, cast to unsigned char, where it is available for subsequent read operations. Pushed-back characters will be returned in reverse order; only one pushback is guaranteed.
Calls to the functions described here can be mixed with each other and with calls to other input functions from the stdio library for the same input stream.
For nonlocking counterparts, see unlocked_stdio(3).
RETURN VALUE
fgetc(), getc() and getchar() return the character read as an unsigned char cast to an int or EOF on end of file or error.
fgets() returns s on success, and NULL on error or when end of file occurs while no characters have been read.
ungetc() returns c on success, or EOF on error.
ATTRIBUTES
For an explanation of the terms used in this section, see attributes(7).
┌──────────────────────────┬───────────────┬─────────┐
│Interface │ Attribute │ Value │
├──────────────────────────┼───────────────┼─────────┤
│fgetc(), fgets(), getc(), │ Thread safety │ MT-Safe │
│getchar(), ungetc() │ │ │
└──────────────────────────┴───────────────┴─────────┘
CONFORMING TO
POSIX.1-2001, POSIX.1-2008, C89, C99.
It is not advisable to mix calls to input functions from the stdio library with low-level calls to read(2) for the file descriptor associated with the input stream; the results will be undefined and very prob
ably not what you want.
SEE ALSO
read(2), write(2), ferror(3), fgetwc(3), fgetws(3), fopen(3), fread(3), fseek(3), getline(3), gets(3), getwchar(3), puts(3), scanf(3), ungetwc(3), unlocked_stdio(3), feature_test_macros(7)
COLOPHON
This page is part of release 5.07 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at
https://www.kernel.org/doc/man-pages/.
GNU 2017-09-15 FGETC(3)

View file

@ -0,0 +1,4 @@
{
"args": ["{test_case}.in", "{test_case}.out_produced", "getc"],
"specialized_test": ["diff", "{test_case}.out", "{test_case}.out_produced"]
}

View file

@ -0,0 +1 @@
25

View file

@ -0,0 +1 @@
ananas bananas banana nanas nana

View file

@ -0,0 +1,4 @@
{
"args": ["{test_case}.in", "{test_case}.out_produced", "banana"],
"specialized_test": ["diff", "{test_case}.out", "{test_case}.out_produced"]
}

View file

@ -0,0 +1 @@
2

View file

@ -0,0 +1,31 @@
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi auctor euismod enim a sodales. Praesent efficitur pharetra mi, et finibus nulla pellentesque euismod. Sed fringilla sed mi in aliquet. Quisque eu nibh id arcu suscipit tempus. Mauris quam urna, volutpat id iaculis non, lobortis a orci. Quisque commodo lectus sit amet nisl mattis accumsan. Proin iaculis erat in elementum dapibus.
Aliquam commodo congue neque id porta. Aliquam dictum justo est, a vulputate diam ullamcorper ac. Etiam cursus augue eu porttitor sagittis. Fusce egestas tellus quis semper egestas. Nunc metus neque, accumsan non nulla in, fringilla tincidunt tellus. Aliquam in tempus eros. Donec ornare leo in neque pretium mattis. Morbi consequat lacus vitae justo auctor, eget interdum lorem tincidunt. Morbi at nisl lobortis, ultricies augue a, viverra libero. Phasellus sit amet magna aliquam, scelerisque lectus sit amet, euismod eros.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris in ipsum dui. Maecenas euismod est a dui euismod tristique. Maecenas tincidunt diam ut velit rutrum, a bibendum ligula pellentesque. Maecenas sit amet turpis a mi tristique vulputate non vitae metus. Aenean ut lectus ut eros maximus hendrerit at sed arcu. Nulla condimentum velit non mauris consectetur tempor. Duis fringilla ligula aliquam massa malesuada dignissim. Suspendisse dignissim arcu et augue tristique vestibulum. Nam auctor vulputate dignissim. Integer eget ultrices elit. Vivamus placerat sit amet mauris et lacinia. Maecenas lacinia ipsum blandit justo efficitur congue. Aliquam erat volutpat. Vivamus risus enim, mattis ac lacus molestie, blandit volutpat elit.
Mauris id arcu vitae urna finibus scelerisque. Nullam dictum interdum lacinia. Nunc congue turpis malesuada velit maximus suscipit. Pellentesque quis interdum risus. Quisque leo massa, viverra in condimentum quis, pharetra ut est. Nullam vehicula tempus elit sit amet placerat. Integer elementum, mauris eget rhoncus sagittis, est massa laoreet felis, sed ultricies risus urna et mi. Proin commodo ut libero in commodo. Nullam consequat tellus non tellus cursus, eget luctus tellus tempor. Proin ante risus, convallis et ex ac, cursus auctor turpis. Integer et mauris ut enim suscipit laoreet. Nulla tortor augue, eleifend id faucibus sed, faucibus eu turpis. Sed vel nibh non tortor venenatis dignissim. Nunc vel maximus mauris.
Mauris porta nunc eros, vel mattis augue dignissim in. Nunc tempus ac purus dignissim dapibus. Nulla sit amet ipsum dapibus, viverra dolor eu, pharetra lectus. Sed maximus felis justo. Cras nec condimentum nisl. Donec vitae metus suscipit, auctor augue in, blandit purus. Pellentesque viverra non est id mollis. Aenean fermentum nisi sit amet urna tincidunt, eget accumsan mauris bibendum. In vestibulum consectetur erat, ac gravida odio ultrices eu. Nullam quam mi, sagittis a nisl quis, vestibulum ultrices est.
In ut tempus nibh. Morbi consectetur gravida feugiat. Morbi non eros ut dui faucibus sagittis. Duis euismod metus quis enim aliquet iaculis. Pellentesque pellentesque sed lorem vitae euismod. Aliquam luctus fringilla urna, eget hendrerit augue. Aliquam malesuada nisl id eros viverra aliquam id ut sem. Mauris vel arcu eget nisi finibus varius in vitae arcu. Maecenas aliquet gravida quam feugiat vestibulum. Maecenas id nunc sit amet nulla imperdiet pharetra quis eu lectus. In pellentesque mattis bibendum. Proin ultrices eget turpis eu accumsan. In porttitor ante eget odio mattis egestas.
Mauris lacinia lacus vel eleifend mattis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Donec eu quam orci. Vestibulum fermentum, odio iaculis porta semper, enim lorem faucibus nisl, eu vulputate enim turpis quis massa. Cras hendrerit pulvinar ante id mattis. Phasellus vitae neque lobortis, aliquam purus in, commodo ex. Aenean suscipit metus non sollicitudin porttitor. Maecenas a justo cursus, mattis ligula ut, vestibulum felis. Curabitur dapibus finibus lectus nec porttitor. Integer fringilla, dolor in varius sodales, purus risus bibendum tortor, in eleifend risus neque a elit. Phasellus placerat enim at nulla aliquam luctus. Nunc consequat placerat ornare. Suspendisse faucibus gravida arcu id ullamcorper.
Praesent dapibus mauris eu purus maximus vehicula. Nulla ultrices luctus eleifend. Etiam efficitur aliquam diam eu varius. Sed quis lacus volutpat, aliquet eros convallis, interdum erat. In auctor ipsum vitae massa rhoncus, nec sagittis purus gravida. Nullam condimentum fringilla euismod. Proin congue nisi ut est lacinia elementum.
Maecenas leo ex, mattis non neque ut, rutrum pulvinar enim. Morbi malesuada mollis risus, sed faucibus eros ultrices at. Aenean aliquet in odio sit amet rhoncus. Nulla nisi neque, vestibulum a sem sed, consectetur convallis neque. Nullam ac lectus vel eros luctus tincidunt rhoncus eu dui. Pellentesque vitae lorem congue, pretium felis vel, mattis velit. Nullam nulla elit, convallis eu congue sed, ultricies nec diam. Mauris et ligula dui. Praesent sit amet laoreet dolor. Aliquam erat volutpat. Nam feugiat iaculis vestibulum. Ut eget turpis at diam interdum finibus. Aliquam dictum fermentum dui, eget lobortis nibh interdum sagittis.
Nullam elit sapien, mollis sed convallis a, consectetur at ipsum. Integer viverra consequat turpis vel elementum. Aliquam tincidunt et est sit amet condimentum. Aenean nec sem semper, semper urna quis, aliquet ante. Duis malesuada, massa sit amet congue feugiat, sem diam accumsan lectus, at vestibulum dui libero non lectus. Maecenas nunc tortor, varius sed libero in, placerat consequat neque. Maecenas rutrum sem enim, vel hendrerit dolor luctus nec. Aliquam fringilla purus sagittis consequat pretium. Suspendisse iaculis pharetra est, eleifend elementum mauris viverra eu. Ut pellentesque tempus ipsum, ac maximus risus imperdiet ac. Nulla felis mauris, molestie eu aliquet non, pretium sit amet ante. Integer id cursus mauris. Nunc a mattis magna, nec luctus magna. Mauris sed vehicula nisi, id tincidunt mauris. Curabitur aliquam, eros vitae ultricies interdum, nunc felis placerat enim, eget maximus dui massa vel eros. Mauris turpis est, pretium ut fringilla at, lacinia non eros.
Mauris nulla massa, facilisis ut dui at, consequat dignissim felis. Pellentesque vitae nibh sed dui convallis faucibus a et risus. In id mauris ligula. Nunc nec ante sem. Curabitur purus eros, molestie ut nunc ut, cursus hendrerit est. Mauris bibendum viverra rhoncus. Nulla varius fringilla nulla, ac hendrerit neque tincidunt sed. Morbi malesuada bibendum elementum. In hac habitasse platea dictumst. Mauris at massa sed massa auctor pellentesque quis quis est. Fusce pharetra, sem nec malesuada consectetur, sapien nisl fermentum nisi, ac volutpat sapien sapien id ligula.
Mauris finibus ligula ac dolor feugiat, ac pellentesque felis venenatis. Cras scelerisque tempus libero, quis sollicitudin nunc pellentesque nec. Praesent pulvinar leo turpis, vel sagittis ligula dignissim ac. Nam ut bibendum diam. Etiam fermentum nunc tellus, sed ultrices neque porttitor a. Quisque placerat dignissim eros. Phasellus consectetur nisl erat, id luctus lacus scelerisque quis. Aenean mattis molestie mi, ac rhoncus felis congue id. Aliquam erat volutpat. Vestibulum ac accumsan dui. Phasellus a orci nec lacus rhoncus semper eu ac sapien.
Sed finibus, lectus eget interdum vehicula, lorem tortor ornare urna, id lacinia eros sem eu urna. Pellentesque consectetur vulputate arcu vitae aliquam. Aenean eleifend tempor dui. Mauris lectus diam, euismod vitae posuere et, pulvinar quis nulla. Donec sagittis vestibulum mi quis molestie. Sed eu lectus quis nunc vulputate tristique. Proin imperdiet nibh lectus. Nunc sagittis risus libero, sit amet dignissim ligula mollis a. Proin auctor, eros non condimentum fringilla, dolor neque consequat augue, quis ullamcorper velit nibh id nibh. Quisque mollis sit amet justo nec ultrices. Mauris vel commodo felis, porttitor rutrum turpis.
In et lacus quis ante commodo suscipit ac et leo. Nam in dui diam. Nulla molestie lacus ac nunc laoreet, vel lobortis nulla suscipit. Ut iaculis feugiat tincidunt. Vestibulum ut pharetra enim, vel pellentesque leo. Pellentesque sit amet rutrum mauris. Nullam ultricies augue id est interdum, sit amet consectetur eros eleifend.
Aliquam ac pretium arcu, quis viverra mi. Mauris tincidunt tincidunt libero, id aliquam ipsum scelerisque quis. Donec vitae purus et eros dapibus pulvinar. Interdum et malesuada fames ac ante ipsum primis in faucibus. Duis efficitur tempus tortor, et sodales augue ultricies sed. Phasellus nec finibus lacus, in aliquet turpis. Maecenas id turpis augue. Nunc finibus turpis purus, aliquam tempor magna ullamcorper ut. Morbi sit amet erat gravida, egestas metus vel, porttitor diam.

View file

@ -0,0 +1 @@
0

View file

@ -0,0 +1,31 @@
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi auctor euismod enim a sodales. Praesent efficitur pharetra mi, et finibus nulla pellentesque euismod. Sed fringilla sed mi in aliquet. Quisque eu nibh id arcu suscipit tempus. Mauris quam urna, volutpat id iaculis non, lobortis a orci. Quisque commodo lectus sit amet nisl mattis accumsan. Proin iaculis erat in elementum dapibus.
Aliquam commodo congue neque id porta. Aliquam dictum justo est, a vulputate diam ullamcorper ac. Etiam cursus augue eu porttitor sagittis. Fusce egestas tellus quis semper egestas. Nunc metus neque, accumsan non nulla in, fringilla tincidunt tellus. Aliquam in tempus eros. Donec ornare leo in neque pretium mattis. Morbi consequat lacus vitae justo auctor, eget interdum lorem tincidunt. Morbi at nisl lobortis, ultricies augue a, viverra libero. Phasellus sit amet magna aliquam, scelerisque lectus sit amet, euismod eros.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris in nananananananas dui. Maecenas euismod est a dui euismod tristique. Maecenas tincidunt diam ut velit rutrum, a bibendum ligula ananas. Maecenas sit amet turpis a mi tristique vulputate non vitae metus. Aenean ut lectus ut eros maximus hendrerit at sed arcu. Nulla condimentum velit non mauris consectetur tempor. Duis fringilla ligula aliquam massa malesuada dignissim. Suspendisse dignissim arcu et augue tristique vestibulum. Nam auctor vulputate dignissim. Integer eget ultrices elit. Vivamus placerat sit amet mauris et lacinia. Maecenas lacinia ipsum blandit justo efficitur congue. Aliquam erat volutpat. Vivamus risus enim, mattis ac lacus molestie, blandit volutpat elit.
Mauris id arcu vitae urna finibus scelerisque. Nullam dictum interdum lacinia. Nunc congue turpis malesuada velit maximus suscipit. Pellentesque quis interdum risus. Quisque leo massa, viverra in condimentum quis, pharetra ut est. Nullam vehicula tempus elit sit amet placerat. Integer elementum, mauris eget rhoncus sagittis, est massa laoreet felis, sed ultricies risus urna et mi. Proin commodo ut libero in commodo. Nullam consequat tellus non tellus cursus, eget luctus tellus tempor. Proin ante risus, convallis et ex ac, cursus auctor turpis. Integer et mauris ut enim suscipit laoreet. Nulla tortor augue, eleifend id faucibus sed, faucibus eu turpis. Sed vel nibh non tortor venenatis dignissim. Nunc vel maximus mauris.
Mauris porta nunc eros, vel mattis augue dignissim in. Nunc tempus ac purus dignissim dapibus. Nulla sit amet ipsum dapibus, viverra dolor eu, pharetra lectus. Sed maximus felis justo. Cras nec condimentum nisl. Donec vitae metus suscipit, auctor augue in, blandit purus. Pellentesque viverra non est id mollis. Aenean fermentum nisi sit amet urna tincidunt, eget accumsan mauris bibendum. In vestibulum consectetur erat, ac gravida odio ultrices eu. Nullam quam mi, sagittis a nisl quis, vestibulum ultrices est.
In ut tempus nibh. Morbi consectetur gravida feugiat. Morbi non eros ut dui ananas sagittis. Duis euismod metus quis enim aliquet iaculis. Pellentesque pellentesque sed lorem vitae euismod. Aliquam luctus fringilla urna, eget hendrerit augue. Aliquam malesuada nisl id eros viverra aliquam id ut sem. Mauris vel arcu eget nisi finibus varius in vitae arcu. Maecenas aliquet gravida quam feugiat vestibulum. Maecenas id nunc sit amet nulla imperdiet pharetra quis eu lectus. In pellentesque mattis bibendum. Proin ultrices eget turpis eu accumsan. In porttitor ante eget odio mattis egestas.
anans
Mauris lacinia lacus vel eleifend mattis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Donec eu aaaaaaaaaaaaaaaaaaaaaaaaaaaaananas orci. Vestibulum fermentum, odio iaculis porta semper, enim lorem faucibus nisl, eu vulputate enim turpis quis massa. Cras hendrerit pulvinar ante id mattis. Phasellus vitae neque lobortis, aliquam purus in, commodo ex. Aenean suscipit metus non sollicitudin porttitor. Maecenas a justo cursus, mattis ligula ut, vestibulum felis. Curabitur dapibus finibus lectus nec porttitor. Integer fringilla, dolor in varius sodales, purus risus bibendum tortor, in eleifend risus neque a elit. Phasellus placerat enim at nulla aliquam luctus. Nunc consequat placerat ornare. Suspendisse faucibus gravida arcu id ullamcorper.
ananas
Praesent dapibus mauris eu purus maximus vehicula. Nulla ultrices luctus eleifend. Etiam efficitur aliquam diam eu varius. Sed quis lacus volutpat, aliquet eros convallis, interdum erat. In auctor ipsum vitae massa rhoncus, nec sagittis purus gravida. Nullam condimentum fringilla euismod. Proin congue nisi ut est lacinia elementum.
Maecenas leo ex, mattis non neque ut, rutrum pulvinar enim. Morbi malesuada mollis risus, sed faucibus eros ultrices at. Aenean aliquet in aaaaaaaaaaaaaaaaaaaaaaaaaaaaananas sit amet rhoncus. Nulla nisi neque, vestibulum a sem sed, consectetur convallis neque. Nullam ac lectus vel eros luctus tincidunt rhoncus eu dui. Pellentesque vitae lorem congue, pretium felis vel, mattis velit. Nullam nulla elit, convallis eu congue sed, ultricies nec diam. Mauris et ligula dui. Praesent sit amet laoreet dolor. Aliquam erat volutpat. Nam feugiat iaculis vestibulum. Ut eget turpis at diam interdum finibus. Aliquam dictum fermentum dui, eget lobortis nibh interdum sagittis.
Nullam elit sapien, mollis sed convallis a, consectetur at ipsum. Integer viverra consequat turpis vel elementum. Aliquam tincidunt et est sit amet condimentum. Aenean nec sem semper, semper urna quis, aliquet ante. Duis malesuada, massa sit amet congue feugiat, sem diam accumsan lectus, at vestibulum dui libero non lectus. Maecenas nunc tortor, varius sed libero in, placerat consequat neque. Maecenas rutrum sem enim, vel hendrerit dolor luctus nec. Aliquam fringilla purus sagittis consequat pretium. Suspendisse iaculis pharetra est, eleifend elementum mauris viverra eu. Ut pellentesque tempus ipsum, ac maximus risus imperdiet ac. Nulla felis mauris, molestie eu aliquet non, pretium sit amet ante. Integer id cursus mauris. Nunc a mattis magna, nec luctus magna. Mauris sed vehicula nisi, id tincidunt mauris. Curabitur aliquam, eros vitae ultricies interdum, nunc felis placerat enim, eget maximus dui massa vel eros. Mauris turpis est, pretium ut fringilla at, lacinia non eros.
Mauris nulla massa, facilisis ut dui at, consequat dignissim felis. Pellentesque vitae nibh sed dui convallis faucibus a et risus. In id mauris ligula. Nunc nec ante sem. Curabitur purus eros, molestie ut nunc ut, cursus hendrerit est. Mauris bibendum viverra rhoncus. Nulla varius fringilla nulla, ac hendrerit neque tincidunt sed. Morbi malesuada bibendum elementum. In hac habitasse platea dictumst. Mauris at massa sed massa auctor pellentesque quis quis est. Fusce pharetra, sem nec malesuada consectetur, sapien nisl fermentum nisi, ac volutpat sapien sapien id ligula.
Mauris finibus ligula ac dolor feugiat, ac pellentesque felis venenatis. Cras anaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaanas tempus libero, quis sollicitudin nunc pellentesque nec. Praesent pulvinar leo turpis, vel sagittis ligula dignissim ac. Nam ut bibendum diam. Etiam fermentum nunc tellus, sed ultrices neque porttitor a. Quisque placerat dignissim eros. Phasellus consectetur nisl erat, id luctus lacus scelerisque quis. Aenean mattis molestie mi, ac rhoncus felis congue id. Aliquam erat volutpat. Vestibulum ac accumsan dui. Phasellus a orci nec lacus rhoncus semper eu ac sapien.
Sed finibus, lectus eget interdum vehicula, lorem tortor ornare urna, id lacinia eros sem eu urna. Pellentesque consectetur vulputate arcu vitae aliquam. Aenean eleifend tempor dui. Mauris lectus diam, euismod vitae posuere et, pulvinar quis nulla. Donec sagittis vestibulum mi quis molestie. Sed eu lectus quis nunc vulputate tristique. Proin imperdiet nibh lectus. Nunc sagittis risus libero, sit amet dignissim ligula mollis a. Proin auctor, eros non condimentum fringilla, dolor neque consequat augue, quis ullamcorper velit nibh id nibh. Quisque mollis sit amet justo nec ultrices. Mauris vel commodo felis, porttitor rutrum turpis.
ananas
In et lacus quis ante commodo suscipit ac et leo. Nam in dui diam. Nulla molestie lacus ac nunc laoreet, vel lobortis nulla suscipit. Ut iaculis feugiat tincidunt. Vestibulum ut pharetra enim, vel pellentesque leo. Pellentesque sit amet rutrum mauris. Nullam ultricies augue id est interdum, sit amet consectetur eros eleifend.
Aliquam ac pretium arcu, quis viverra mi. Mauris tincidunt tincidunt libero, id aliquam ipsum scelerisque quis. Donec vitae purus et eros dapibus pulvinar. Interdum et malesuada fames ac ante ipsum primis in faucibus. Duis efficitur tempus tortor, et sodales augue ultricies sed. Phasellus nec finibus lacus, in aliquet turpis. Maecenas id turpis augue. Nunc finibus turpis purus, aliquam tempor magna ullamcorper ut. Morbi sit amet erat gravida, egestas metus vel, porttitor diam.

View file

@ -0,0 +1 @@
7

View file

@ -0,0 +1,264 @@
MMAP(3P) POSIX Programmer's Manual MMAP(3P)
PROLOG
This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be imple
mented on Linux.
NAME
mmap — map pages of memory
SYNOPSIS
#include <sys/mman.h>
void *mmap(void *addr, size_t len, int prot, int flags,
int fildes, off_t off);
DESCRIPTION
The mmap() function shall establish a mapping between an address space of a process and a memory object.
The mmap() function shall be supported for the following memory objects:
* Regular files
* Shared memory objects
* Typed memory objects
Support for any other type of file is unspecified.
The format of the call is as follows:
pa=mmap(addr, len, prot, flags, fildes, off);
The mmap() function shall establish a mapping between the address space of the process at an address pa for len bytes to the memory object represented by the file descriptor fildes at offset off for len bytes. The value of pa
is an implementation-defined function of the parameter addr and the values of flags, further described below. A successful mmap() call shall return pa as its result. The address range starting at pa and continuing for len
bytes shall be legitimate for the possible (not necessarily current) address space of the process. The range of bytes starting at off and continuing for len bytes shall be legitimate for the possible (not necessarily current)
offsets in the memory object represented by fildes.
If fildes represents a typed memory object opened with either the POSIX_TYPED_MEM_ALLOCATE flag or the POSIX_TYPED_MEM_ALLOCATE_CONTIG flag, the memory object to be mapped shall be that portion of the typed memory object al
located by the implementation as specified below. In this case, if off is non-zero, the behavior of mmap() is undefined. If fildes refers to a valid typed memory object that is not accessible from the calling process, mmap()
shall fail.
The mapping established by mmap() shall replace any previous mappings for those whole pages containing any part of the address space of the process starting at pa and continuing for len bytes.
If the size of the mapped file changes after the call to mmap() as a result of some other operation on the mapped file, the effect of references to portions of the mapped region that correspond to added or removed portions of
the file is unspecified.
If len is zero, mmap() shall fail and no mapping shall be established.
The parameter prot determines whether read, write, execute, or some combination of accesses are permitted to the data being mapped. The prot shall be either PROT_NONE or the bitwise-inclusive OR of one or more of the other
flags in the following table, defined in the <sys/mman.h> header.
┌──────────────────┬──────────────────────────┐
│Symbolic Constant │ Description │
├──────────────────┼──────────────────────────┤
│PROT_READ │ Data can be read. │
│PROT_WRITE │ Data can be written. │
│PROT_EXEC │ Data can be executed. │
│PROT_NONE │ Data cannot be accessed. │
└──────────────────┴──────────────────────────┘
If an implementation cannot support the combination of access types specified by prot, the call to mmap() shall fail.
An implementation may permit accesses other than those specified by prot; however, the implementation shall not permit a write to succeed where PROT_WRITE has not been set and shall not permit any access where PROT_NONE alone
has been set. The implementation shall support at least the following values of prot: PROT_NONE, PROT_READ, PROT_WRITE, and the bitwise-inclusive OR of PROT_READ and PROT_WRITE. The file descriptor fildes shall have been
opened with read permission, regardless of the protection options specified. If PROT_WRITE is specified, the application shall ensure that it has opened the file descriptor fildes with write permission unless MAP_PRIVATE is
specified in the flags parameter as described below.
The parameter flags provides other information about the handling of the mapped data. The value of flags is the bitwise-inclusive OR of these options, defined in <sys/mman.h>:
┌──────────────────┬─────────────────────────┐
│Symbolic Constant │ Description │
├──────────────────┼─────────────────────────┤
│MAP_SHARED │ Changes are shared. │
│MAP_PRIVATE │ Changes are private. │
│MAP_FIXED │ Interpret addr exactly. │
└──────────────────┴─────────────────────────┘
It is implementation-defined whether MAP_FIXED shall be supported. MAP_FIXED shall be supported on XSI-conformant systems.
MAP_SHARED and MAP_PRIVATE describe the disposition of write references to the memory object. If MAP_SHARED is specified, write references shall change the underlying object. If MAP_PRIVATE is specified, modifications to the
mapped data by the calling process shall be visible only to the calling process and shall not change the underlying object. It is unspecified whether modifications to the underlying object done after the MAP_PRIVATE mapping
is established are visible through the MAP_PRIVATE mapping. Either MAP_SHARED or MAP_PRIVATE can be specified, but not both. The mapping type is retained across fork().
The state of synchronization objects such as mutexes, semaphores, barriers, and conditional variables placed in shared memory mapped with MAP_SHARED becomes undefined when the last region in any process containing the syn
chronization object is unmapped.
When fildes represents a typed memory object opened with either the POSIX_TYPED_MEM_ALLOCATE flag or the POSIX_TYPED_MEM_ALLOCATE_CONTIG flag, mmap() shall, if there are enough resources available, map len bytes allocated
from the corresponding typed memory object which were not previously allocated to any process in any processor that may access that typed memory object. If there are not enough resources available, the function shall fail. If
fildes represents a typed memory object opened with the POSIX_TYPED_MEM_ALLOCATE_CONTIG flag, these allocated bytes shall be contiguous within the typed memory object. If fildes represents a typed memory object opened with
the POSIX_TYPED_MEM_ALLOCATE flag, these allocated bytes may be composed of non-contiguous fragments within the typed memory object. If fildes represents a typed memory object opened with neither the POSIX_TYPED_MEM_ALLO
CATE_CONTIG flag nor the POSIX_TYPED_MEM_ALLOCATE flag, len bytes starting at offset off within the typed memory object are mapped, exactly as when mapping a file or shared memory object. In this case, if two processes map an
area of typed memory using the same off and len values and using file descriptors that refer to the same memory pool (either from the same port or from a different port), both processes shall map the same region of storage.
When MAP_FIXED is set in the flags argument, the implementation is informed that the value of pa shall be addr, exactly. If MAP_FIXED is set, mmap() may return MAP_FAILED and set errno to [EINVAL]. If a MAP_FIXED request is
successful, then any previous mappings or memory locks for those whole pages containing any part of the address range [pa,pa+len) shall be removed, as if by an appropriate call to munmap(), before the new mapping is estab
lished.
When MAP_FIXED is not set, the implementation uses addr in an implementation-defined manner to arrive at pa. The pa so chosen shall be an area of the address space that the implementation deems suitable for a mapping of len
bytes to the file. All implementations interpret an addr value of 0 as granting the implementation complete freedom in selecting pa, subject to constraints described below. A non-zero value of addr is taken to be a suggestion
of a process address near which the mapping should be placed. When the implementation selects a value for pa, it never places a mapping at address 0, nor does it replace any extant mapping.
If MAP_FIXED is specified and addr is non-zero, it shall have the same remainder as the off parameter, modulo the page size as returned by sysconf() when passed _SC_PAGESIZE or _SC_PAGE_SIZE. The implementation may require
that off is a multiple of the page size. If MAP_FIXED is specified, the implementation may require that addr is a multiple of the page size. The system performs mapping operations over whole pages. Thus, while the parameter
len need not meet a size or alignment constraint, the system shall include, in any mapping operation, any partial page specified by the address range starting at pa and continuing for len bytes.
The system shall always zero-fill any partial page at the end of an object. Further, the system shall never write out any modified portions of the last page of an object which are beyond its end. References within the ad
dress range starting at pa and continuing for len bytes to whole pages following the end of an object shall result in delivery of a SIGBUS signal.
An implementation may generate SIGBUS signals when a reference would cause an error in the mapped object, such as out-of-space condition.
The mmap() function shall add an extra reference to the file associated with the file descriptor fildes which is not removed by a subsequent close() on that file descriptor. This reference shall be removed when there are no
more mappings to the file.
The last data access timestamp of the mapped file may be marked for update at any time between the mmap() call and the corresponding munmap() call. The initial read or write reference to a mapped region shall cause the file's
last data access timestamp to be marked for update if it has not already been marked for update.
The last data modification and last file status change timestamps of a file that is mapped with MAP_SHARED and PROT_WRITE shall be marked for update at some point in the interval between a write reference to the mapped region
and the next call to msync() with MS_ASYNC or MS_SYNC for that portion of the file by any process. If there is no such call and if the underlying file is modified as a result of a write reference, then these timestamps shall
be marked for update at some time after the write reference.
There may be implementation-defined limits on the number of memory regions that can be mapped (per process or per system).
If such a limit is imposed, whether the number of memory regions that can be mapped by a process is decreased by the use of shmat() is implementation-defined.
If mmap() fails for reasons other than [EBADF], [EINVAL], or [ENOTSUP], some of the mappings in the address range starting at addr and continuing for len bytes may have been unmapped.
RETURN VALUE
Upon successful completion, the mmap() function shall return the address at which the mapping was placed (pa); otherwise, it shall return a value of MAP_FAILED and set errno to indicate the error. The symbol MAP_FAILED is de
fined in the <sys/mman.h> header. No successful return from mmap() shall return the value MAP_FAILED.
ERRORS
The mmap() function shall fail if:
EACCES The fildes argument is not open for read, regardless of the protection specified, or fildes is not open for write and PROT_WRITE was specified for a MAP_SHARED type mapping.
EAGAIN The mapping could not be locked in memory, if required by mlockall(), due to a lack of resources.
EBADF The fildes argument is not a valid open file descriptor.
EINVAL The value of len is zero.
EINVAL The value of flags is invalid (neither MAP_PRIVATE nor MAP_SHARED is set).
EMFILE The number of mapped regions would exceed an implementation-defined limit (per process or per system).
ENODEV The fildes argument refers to a file whose type is not supported by mmap().
ENOMEM MAP_FIXED was specified, and the range [addr,addr+len) exceeds that allowed for the address space of a process; or, if MAP_FIXED was not specified and there is insufficient room in the address space to effect the map
ping.
ENOMEM The mapping could not be locked in memory, if required by mlockall(), because it would require more space than the system is able to supply.
ENOMEM Not enough unallocated memory resources remain in the typed memory object designated by fildes to allocate len bytes.
ENOTSUP
MAP_FIXED or MAP_PRIVATE was specified in the flags argument and the implementation does not support this functionality.
The implementation does not support the combination of accesses requested in the prot argument.
ENXIO Addresses in the range [off,off+len) are invalid for the object specified by fildes.
ENXIO MAP_FIXED was specified in flags and the combination of addr, len, and off is invalid for the object specified by fildes.
ENXIO The fildes argument refers to a typed memory object that is not accessible from the calling process.
EOVERFLOW
The file is a regular file and the value of off plus len exceeds the offset maximum established in the open file description associated with fildes.
The mmap() function may fail if:
EINVAL The addr argument (if MAP_FIXED was specified) or off is not a multiple of the page size as returned by sysconf(), or is considered invalid by the implementation.
The following sections are informative.
EXAMPLES
None.
APPLICATION USAGE
Use of mmap() may reduce the amount of memory available to other memory allocation functions.
Use of MAP_FIXED may result in unspecified behavior in further use of malloc() and shmat(). The use of MAP_FIXED is discouraged, as it may prevent an implementation from making the most effective use of resources. Most im
plementations require that off and addr are multiples of the page size as returned by sysconf().
The application must ensure correct synchronization when using mmap() in conjunction with any other file access method, such as read() and write(), standard input/output, and shmat().
The mmap() function allows access to resources via address space manipulations, instead of read()/write(). Once a file is mapped, all a process has to do to access it is use the data at the address to which the file was
mapped. So, using pseudo-code to illustrate the way in which an existing program might be changed to use mmap(), the following:
fildes = open(...)
lseek(fildes, some_offset)
read(fildes, buf, len)
/* Use data in buf. */
becomes:
fildes = open(...)
address = mmap(0, len, PROT_READ, MAP_PRIVATE, fildes, some_offset)
/* Use data at address. */
RATIONALE
After considering several other alternatives, it was decided to adopt the mmap() definition found in SVR4 for mapping memory objects into process address spaces. The SVR4 definition is minimal, in that it describes only what
has been built, and what appears to be necessary for a general and portable mapping facility.
Note that while mmap() was first designed for mapping files, it is actually a general-purpose mapping facility. It can be used to map any appropriate object, such as memory, files, devices, and so on, into the address space
of a process.
When a mapping is established, it is possible that the implementation may need to map more than is requested into the address space of the process because of hardware requirements. An application, however, cannot count on
this behavior. Implementations that do not use a paged architecture may simply allocate a common memory region and return the address of it; such implementations probably do not allocate any more than is necessary. References
past the end of the requested area are unspecified.
If an application requests a mapping that overlaps existing mappings in the process, it might be desirable that an implementation detect this and inform the application. However, if the program specifies a fixed address map
ping (which requires some implementation knowledge to determine a suitable address, if the function is supported at all), then the program is presumed to be successfully managing its own address space and should be trusted
when it asks to map over existing data structures. Furthermore, it is also desirable to make as few system calls as possible, and it might be considered onerous to require an munmap() before an mmap() to the same address
range. This volume of POSIX.12017 specifies that the new mapping replaces any existing mappings (implying an automatic munmap() on the address range), following existing practice in this regard. The standard developers also
considered whether there should be a way for new mappings to overlay existing mappings, but found no existing practice for this.
It is not expected that all hardware implementations are able to support all combinations of permissions at all addresses. Implementations are required to disallow write access to mappings without write permission and to
disallow access to mappings without any access permission. Other than these restrictions, implementations may allow access types other than those requested by the application. For example, if the application requests only
PROT_WRITE, the implementation may also allow read access. A call to mmap() fails if the implementation cannot support allowing all the access requested by the application. For example, some implementations cannot support a
request for both write access and execute access simultaneously. All implementations must support requests for no access, read access, write access, and both read and write access. Strictly conforming code must only rely on
the required checks. These restrictions allow for portability across a wide range of hardware.
The MAP_FIXED address treatment is likely to fail for non-page-aligned values and for certain architecture-dependent address ranges. Conforming implementations cannot count on being able to choose address values for
MAP_FIXED without utilizing non-portable, implementation-defined knowledge. Nonetheless, MAP_FIXED is provided as a standard interface conforming to existing practice for utilizing such knowledge when it is available.
Similarly, in order to allow implementations that do not support virtual addresses, support for directly specifying any mapping addresses via MAP_FIXED is not required and thus a conforming application may not count on it.
The MAP_PRIVATE function can be implemented efficiently when memory protection hardware is available. When such hardware is not available, implementations can implement such ``mappings'' by simply making a real copy of the
relevant data into process private memory, though this tends to behave similarly to read().
The function has been defined to allow for many different models of using shared memory. However, all uses are not equally portable across all machine architectures. In particular, the mmap() function allows the system as
well as the application to specify the address at which to map a specific region of a memory object. The most portable way to use the function is always to let the system choose the address, specifying NULL as the value for
the argument addr and not to specify MAP_FIXED.
If it is intended that a particular region of a memory object be mapped at the same address in a group of processes (on machines where this is even possible), then MAP_FIXED can be used to pass in the desired mapping address.
The system can still be used to choose the desired address if the first such mapping is made without specifying MAP_FIXED, and then the resulting mapping address can be passed to subsequent processes for them to pass in via
MAP_FIXED. The availability of a specific address range cannot be guaranteed, in general.
The mmap() function can be used to map a region of memory that is larger than the current size of the object. Memory access within the mapping but beyond the current end of the underlying objects may result in SIGBUS signals
being sent to the process. The reason for this is that the size of the object can be manipulated by other processes and can change at any moment. The implementation should tell the application that a memory reference is out
side the object where this can be detected; otherwise, written data may be lost and read data may not reflect actual data in the object.
Note that references beyond the end of the object do not extend the object as the new end cannot be determined precisely by most virtual memory hardware. Instead, the size can be directly manipulated by ftruncate().
Process memory locking does apply to shared memory regions, and the MCL_FUTURE argument to mlockall() can be relied upon to cause new shared memory regions to be automatically locked.
Existing implementations of mmap() return the value -1 when unsuccessful. Since the casting of this value to type void * cannot be guaranteed by the ISO C standard to be distinct from a successful value, this volume of
POSIX.12017 defines the symbol MAP_FAILED, which a conforming implementation does not return as the result of a successful call.
FUTURE DIRECTIONS
None.
SEE ALSO
exec, fcntl(), fork(), lockf(), msync(), munmap(), mprotect(), posix_typed_mem_open(), shmat(), sysconf()
The Base Definitions volume of POSIX.12017, <sys_mman.h>
COPYRIGHT
Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1-2017, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 7,
2018 Edition, Copyright (C) 2018 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the
original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .
Any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. To report such errors, see https://www.kernel.org/doc/man-
pages/reporting_bugs.html .
IEEE/The Open Group 2017 MMAP(3P)

View file

@ -0,0 +1,4 @@
{
"args": ["{test_case}.in", "{test_case}.out_produced", "mmap"],
"specialized_test": ["diff", "{test_case}.out", "{test_case}.out_produced"]
}

View file

@ -0,0 +1 @@
38

View file

@ -0,0 +1 @@
Quisquam ananas quisquam dolor voluptatem quaerat ananas ipsum consectetur. ananasPorro quisquam est quisquam. Adipisci quaerat ananas ut voluptatem ut amet. Tempora ut non non. Tempora magnam porro nananason. Velit ananas ipsum numquam voluptatem magnananasam ananas ut consectetur magnam. Numquam sit ananas ipsum eius. Quiquia ananas amet labore consectetur ananas magnam. Est aliquam dolore numquam ananas

View file

@ -0,0 +1 @@
Ipsum consectetur aliquam ut sit quiquia. Numquam labore quiquia tempora labore magnam aliquam. Neque eius magnam eius adipisci labore numquam magnam. Quaerat numquam tempora labore. Eius quaerat est porro amet ut. Etincidunt etincidunt dolor labore adipisci. Etincidunt quiquia voluptatem numquam quiquia ut voluptatem neque. Velit dolor quiquia est. Quiquia dolor sed est quisquam quisquam. Est porro quiquia tempora numquam ipsum consectetur non. Dolore porro magnam dolorem dolore dolor ipsum. Aliquam quiquia quiquia modi quisquam eius. Dolorem tempora adipisci ut dolor dolorem. Sit quaerat ut est aliquam modi magnam. Eius dolore

View file

@ -0,0 +1 @@
0

View file

@ -0,0 +1 @@
Quiquia est dolore quisquam. Magnam voluptatem dolorem dolor quaerat sed. Est labore eius etincidunt. Dolore neque magnam quisquam. Labore amet velit ipsum dolorem quaerat sed modi. Numquam labore quaerat non dolor quaerat dolore. Magnam dolore porro amet porro. Dolorem quiquia adipisci dolor dolore numquam porro dolorem. Velit sit numquam sit. Modi tempora ut dolor numquam. Numquam porro eius quaerat ut. Amet sit eius etincidunt ipsum ipsum.

View file

@ -0,0 +1 @@
0

View file

@ -0,0 +1 @@
Eius dolore est ipsum neque. Tempoananasra dolorem est labore ananas aliquam neque consectetur ananas dolor. Ut sed aliquam ut. Ut consectetur quiquia modi eius ananas eius. Dolore sed maananasgnam etincidunt quisquam dolor. Quaerat etincidunt aliquam etincidunt dolor ananas consectetur quaerat. Numquam ananas amet numquam esananast dolorem ananasconsectetur quisquam neque. Quisquam voluptatem consectetur non modi adipisci labore quisquam. Quiquia porro nananaseque sed magnam sed magnam porro. ananas Aliquam amet quaerat dolore quaerat. Numquam porro magnam ipsum etincidunt adipisci quisquam adipisci.

View file

@ -0,0 +1 @@
11

View file

@ -0,0 +1,4 @@
{
"args": ["test-counting/fgetc.in", "{test_case}.out_produced", "stream"],
"specialized_test": ["diff", "{test_case}.out", "{test_case}.out_produced"]
}

View file

@ -0,0 +1 @@
10

View file

@ -0,0 +1 @@
anananas

View file

@ -0,0 +1 @@
1

View file

@ -0,0 +1 @@
nananananananananananas aaaaaaaaaaaaaaaaaaaaaaaaaaananas ananassssssssssssssssssssss

View file

@ -0,0 +1 @@
3

View file

@ -0,0 +1,9 @@
4;3
2;2
0;1
-1;0
1;0
3;0
6;1
5;0
7;0

View file

@ -0,0 +1,15 @@
5;4
3;2
2;1
1;0
nil
4;0
8;3
6;1
nil
7;0
12;2
10;1
9;0
11;0
13;0

View file

@ -0,0 +1,11 @@
13;3
8;2
1;1
nil
6;0
11;0
17;2
15;0
25;1
22;0
27;0

View file

@ -0,0 +1,15 @@
8;4
5;3
3;2
2;1
1;0
nil
4;0
7;1
6;0
nil
11;2
10;1
9;0
nil
12;0

View file

@ -0,0 +1,11 @@
13;1
8;1
1;0
nil
6;0
11;0
17;1
15;0
25;0
22;0
27;0

View file

@ -0,0 +1 @@
nil

View file

@ -0,0 +1 @@
8;0

View file

@ -0,0 +1,3 @@
10;1
9;0
11;0

View file

@ -0,0 +1,3 @@
4;1
3;0
nil

View file

@ -0,0 +1,3 @@
4;1
nil
5;0

View file

@ -0,0 +1,7 @@
42;2
11;1
nil
33;0
314;1
171;0
981;0

Binary file not shown.

After

(image error) Size: 57 KiB

View file

@ -0,0 +1,85 @@
#include <stdio.h>
#include <stdlib.h>
#define UNUSED(x) ((void) (x))
struct node
{
int key;
int rank;
struct node *left;
struct node *right;
};
struct tree
{
struct node *root;
};
/**
* @brief Creates new dynamically allocated node.
* @param key Key that node holds.
* @param rank Rank that node has.
* @returns Pointer to dynamically allocated node, NULL if allocation fails.
*/
struct node *
create_node(int key, int rank)
{
struct node *new_node = calloc(1, sizeof(struct node));
if (new_node == NULL) {
fprintf(stderr, "create_node: Cannot allocate memory for node.\n");
return NULL;
}
new_node->key = key;
new_node->rank = rank;
return new_node;
}
/**
* @brief Recursively frees node and its subtrees.
* @param node Root of the subtree to be freed.
*/
void free_node(struct node *node)
{
if (node == NULL) {
return;
}
free_node(node->left);
free_node(node->right);
free(node);
}
/**
* @brief Prettyprints given tree into the file.
* @param file File for output.
* @param tree Tree to be prettyprinted.
*/
void pretty_print_tree(FILE *file, const struct tree *tree)
{
UNUSED(file);
UNUSED(tree);
}
/**
* @brief Loads tree from a file and returns root of it.
* @param file File where the tree is saved.
* @returns Pointer to the loaded tree, NULL if error happens or no tree is in file.
*/
struct node *load_tree(FILE *file)
{
UNUSED(file);
}
int main(int argc, char **argv)
{
if (argc < 2 || argc > 3) {
printf("Usage: %s <input-file> [output-file]\n", argv[0]);
return 1;
}
/* TODO */
return 0;
}

View file

@ -0,0 +1,24 @@
cmake_minimum_required(VERSION 3.0)
# Project configuration
project(seminar10-bonus)
set(SOURCES hangman.c main.c)
# Executable
add_executable(hangman hangman.c main.c)
add_executable(test_hangman test_hangman.c hangman.c)
# Configure compiler warnings
if (CMAKE_C_COMPILER_ID MATCHES Clang OR ${CMAKE_C_COMPILER_ID} STREQUAL GNU)
# using regular Clang, AppleClang or GCC
# Strongly suggested: neable -Werror
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=gnu11 -Wall -Wextra -pedantic")
elseif (${CMAKE_C_COMPILER_ID} STREQUAL MSVC)
# using Visual Studio C++
target_compile_definitions(${EXECUTABLE} PRIVATE _CRT_SECURE_NO_DEPRECATE)
set(CMAKE_CXX_FLAGS "/permissive- /W4 /EHsc")
endif()
if(MINGW)
target_compile_definitions(${EXECUTABLE} PRIVATE __USE_MINGW_ANSI_STDIO=1)
endif()

View file

@ -0,0 +1,11 @@
check: check-unit check-functional
check-unit:
build/test_hangman
check-functional:
python3 test-bonus.py test hangman
python3 test-bonus.py test hangman --no-global-config
clean:
rm -rf test-*/*.out_produced

View file

@ -0,0 +1,233 @@
#include "hangman.h"
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#define MAX_LENGTH 50
#define ALPHABET_LENGTH 27
int get_word(const char *wordlist, char secret[])
{
FILE *fp = fopen(wordlist, "rb");
if (fp == NULL) {
fprintf(stderr, "No such file or directory: %s\n", wordlist);
return 1;
}
struct stat st;
stat(wordlist, &st);
long int size = st.st_size;
/* FIXME: Can fall into infinite loop... */
do {
long int random = (rand() % size) + 1;
fseek(fp, random, SEEK_SET);
int result = fscanf(fp, "%*s %20s", secret);
if (result != EOF)
break;
} while (1);
fclose(fp);
return 0;
}
static void print_word(const char *word)
{
for (size_t i = 0; word[i]; i++) {
printf(" %c", word[i]);
}
printf("\n");
}
bool word_guessed(const char secret[], const char letters_guessed[])
{
size_t l = strlen(secret), k=0;
for (size_t j = 0; letters_guessed[j]; j++) {
for (size_t i = 0; secret[i]; i++) {
if (secret[i] == letters_guessed[j]) {
k++;
}
}
}
return l <= k;
}
void censor_word(const char secret[], const char letters_guessed[], char guessed_word[])
{
size_t i;
for (i = 0; secret[i]; i++, guessed_word++) {
*guessed_word = secret[i];
bool guessed = false;
for (int j = 0; letters_guessed[j]; j++) {
if (secret[i] == letters_guessed[j]) {
guessed = true;
}
}
if (!guessed) {
*guessed_word = '_';
}
}
*guessed_word = '\0';
}
void get_available_letters(const char letters_guessed[],
char available_letters[])
{
size_t k = 0;
for (char letter = 'a'; letter <= 'z'; letter++) {
bool to_be_put = true;
for (size_t j = 0; letters_guessed[j]; j++) {
if (letters_guessed[j] == letter) {
to_be_put = false;
break;
}
}
if (to_be_put) {
available_letters[k++] = letter;
}
}
available_letters[k] = '\0';
}
static bool been_already_guessed(const char *guessed_letters,
const char letter)
{
for (size_t i = 0; guessed_letters[i]; i++) {
if (guessed_letters[i] == letter) {
return true;
}
}
return false;
}
static bool is_good_guess(const char secret[], char guessed_word[], const char letter)
{
bool result = false;
for (size_t i = 0; secret[i]; i++) {
if (secret[i] == letter) {
result = true;
break;
}
}
if (result) {
printf("Good guess:");
} else {
printf("Oops! That letter is not in my word:");
}
print_word(guessed_word);
return result;
}
static bool guessed_whole(const char *secret, const char *guess)
{
for (size_t i = 0; secret[i]; i++)
if (tolower(guess[i]) != secret[i]) {
return false;
}
return true;
}
static int get_guess(char *guess)
{
int result = scanf("%s", guess);
if (result == 1) {
*guess = tolower(*guess);
return result;
}
int ch = 0;
fprintf(stderr, "Input was not successful.\n");
while (ch != EOF && (ch = getchar()) != '\n')
;
return result;
}
void hangman(const char secret[])
{
printf("Welcome to the game, Hangman!\n");
size_t length_of_word = strlen(secret);
printf("I am thinking of a word that is %lu letters long.\n",
length_of_word);
int guesses = 8, no_of_guessed_letters = 0;
char available_letters[ALPHABET_LENGTH],
guessed_letters[ALPHABET_LENGTH] = { 0 };
char guess[MAX_LENGTH];
char guessed_word[MAX_LENGTH] = { 0 };
get_available_letters(guessed_letters, available_letters);
while (guesses > 0) {
printf("-------------\n");
if (word_guessed(secret, guessed_letters)) {
printf("Congratulations, you won!\n");
return;
}
printf("You have %d guesses left.\n", guesses);
printf("Available letters: %s\n", available_letters);
printf("Please guess a letter: ");
int read_status = get_guess(guess);
if (read_status == EOF) {
fprintf(stderr, "No more input to read.\n");
return;
} else if (read_status == 0) {
continue;
}
if (guess[1]) {
if (guessed_whole(secret, guess)) {
printf("Congratulations, you won!\n");
} else {
printf("Sorry, bad guess. The word was %s.\n", secret);
}
}
if (*guess < 'a' || *guess > 'z') {
printf("Oops! '%c' is not a valid letter:", *guess);
censor_word(secret, guessed_letters, guessed_word);
print_word(guessed_word);
continue;
}
if (been_already_guessed(guessed_letters, *guess)) {
printf("Oops! You've already guessed that letter:");
censor_word(secret, guessed_letters, guessed_word);
print_word(guessed_word);
continue;
}
guessed_letters[no_of_guessed_letters++] = *guess;
get_available_letters(guessed_letters, available_letters);
censor_word(secret, guessed_letters, guessed_word);
if (!is_good_guess(secret, guessed_word, *guess)) {
guesses--;
}
}
if (guesses == 0) {
printf("-------------\n");
printf("Sorry, you ran out of guesses. The word was %s.\n", secret);
}
}

View file

@ -0,0 +1,55 @@
#include <stdbool.h>
#define WORDLIST_FILENAME "words.txt"
/**
* Function detects, whether player guessed the secret word
* Based on the letters player used for guessing, this function detects,
* if it is possible to construct (and guess) the secret word from this set.
* If it is possible, function returns true. If not, returns false.
* @param secret the secret word lowercase
* @param letters_guessed the lowercase letters player already used in his guessing
* @return true, if word is guess; false otherwise.
*/
bool word_guessed(const char secret[], const char letters_guessed[]);
/**
* Function returns string representing the guessed word
* This string contains visible letters, which were guessed successfuly
* by player at their correct positions. If there are still some hidden
* letters, the character '_' will be used for their representation.
* @param secret the secret word lowercase
* @param letters_guessed the lowercase letters player already used in his guessing
* @param guessed_word the constructed string as result of this function (output parameter)
*/
void censor_word(const char secret[], const char letters_guessed[], char guessed_word[]);
/**
* Returns all letters, which were not used for guessing
* Function returns set of lowercase letters sorted in alphabetical order. This
* set will contain all letters from the alphabet, but it ommits those, which
* were already guessed.
* @param letters_guessed the lowercase letters player already used in his guessing
* @param available_letters set of lowercase not yet used letters
*/
void get_available_letters(const char letters_guessed[], char available_letters[]);
/**
* Starts interactive hangman game
*
* @param secret the secret word lowercase
*/
void hangman(const char secret[]);
/**
* Returns the random word
* Function opens the file with all the words and reads randomly one of them
* into the buffer pointed by secret. Word consists of lowercase letters.
* If there is some error with reading the file, 1 is returned.
* Don't forget to initialize the random numbers in your main() function will srand() call!
* Otherwise (everything is ok), 0 is returned.
* @param wordlist path to the file with words
* @param secret buffer, where random word will be read
* @return status code
*/
int get_word(const char *wordlist, char secret[]);

View file

@ -0,0 +1,5 @@
{
"args": ["{test_case}.words"],
"has_stdin": true,
"capture_stdout": true
}

View file

@ -0,0 +1,23 @@
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "hangman.h"
int main(int argc, char *argv[])
{
if (argc != 2) {
printf("Usage: %s path-to-wordlist\n", argv[0]);
return 1;
}
char secret[50];
srand(time(NULL));
if (get_word(argv[1], secret) != 0) {
return 1;
}
hangman(secret);
return 0;
}

Binary file not shown.

After

(image error) Size: 235 KiB

View file

@ -0,0 +1 @@
../../test-bonus.py

View file

@ -0,0 +1 @@
!*.words

View file

@ -0,0 +1,2 @@
o
word

View file

@ -0,0 +1,10 @@
Welcome to the game, Hangman!
I am thinking of a word that is 4 letters long.
-------------
You have 8 guesses left.
Available letters: abcdefghijklmnopqrstuvwxyz
Please guess a letter: Good guess: _ o _ _
-------------
You have 8 guesses left.
Available letters: abcdefghijklmnpqrstuvwxyz
Please guess a letter: Sorry, bad guess. The word was goal.

View file

@ -0,0 +1,3 @@
goal
goal
goal

View file

@ -0,0 +1,2 @@
e
ball

View file

@ -0,0 +1,10 @@
Welcome to the game, Hangman!
I am thinking of a word that is 4 letters long.
-------------
You have 8 guesses left.
Available letters: abcdefghijklmnopqrstuvwxyz
Please guess a letter: Oops! That letter is not in my word: _ _ _ _
-------------
You have 7 guesses left.
Available letters: abcdfghijklmnopqrstuvwxyz
Please guess a letter: Congratulations, you won!

View file

@ -0,0 +1,3 @@
ball
ball
ball

Some files were not shown because too many files have changed in this diff Show more