{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "cell-23-17-00",
   "metadata": {},
   "source": [
    "# 23-17 · Hash zawartości po częściach\n",
    "\n",
    "Praktyka do sekcji [„SHA-256 i skrót zawartości pliku” `projects/python/safesort/src/safesort/duplicates.py`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-23-17-01",
   "metadata": {},
   "source": [
    "## Cel\n",
    "\n",
    "Sztuka `sha256_file()` — blokowy odczyt pliku — i sprawdź wynik za pomocą `hashlib.sha256()`obliczane bezpośrednio na całej zawartości."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-23-17-02",
   "metadata": {},
   "source": [
    "## Example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-23-17-03",
   "metadata": {},
   "outputs": [],
   "source": [
    "import hashlib\n",
    "from pathlib import Path\n",
    "\n",
    "DEFAULT_CHUNK_SIZE = 1024 * 1024\n",
    "\n",
    "\n",
    "def sha256_file(path, chunk_size=DEFAULT_CHUNK_SIZE):\n",
    "    digest = hashlib.sha256()\n",
    "    with path.open(\"rb\") as file:\n",
    "        while chunk := file.read(chunk_size):\n",
    "            digest.update(chunk)\n",
    "    return digest.hexdigest()\n",
    "\n",
    "\n",
    "soderzhimoe = (\"тестовое содержимое файла для проверки sha256_file \" * 50).encode(\"utf-8\")\n",
    "put = Path(\"proverka_sha256.bin\")\n",
    "put.write_bytes(soderzhimoe)\n",
    "\n",
    "print(\"Размер файла:\", put.stat().st_size, \"байт\")\n",
    "print(\"Дайджест:\", sha256_file(put))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-23-17-04",
   "metadata": {},
   "source": [
    "## Sprawdzenie wyniku"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-23-17-05",
   "metadata": {},
   "outputs": [],
   "source": [
    "ozhidaemyj = hashlib.sha256(soderzhimoe).hexdigest()\n",
    "\n",
    "assert sha256_file(put) == ozhidaemyj\n",
    "assert sha256_file(put, chunk_size=16) == ozhidaemyj  # тот же результат при маленьком размере блока\n",
    "print(\"Верно: результат sha256_file совпадает с hashlib.sha256() напрямую — при любом размере блока.\")\n",
    "\n",
    "put.unlink()  # временный файл больше не нужен -- дальше работаем только с soderzhimoe (bytes)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-23-17-06",
   "metadata": {},
   "source": [
    "## Starter\n",
    "\n",
    "Wypełnij zaznaczone miejsce. Niezmieniony starter nie przechodzi tests."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "task-23-17",
   "metadata": {
    "tags": [
     "exercise",
     "starter"
    ]
   },
   "outputs": [],
   "source": [
    "def digest_posle_zameny(data: bytes, index: int, new_byte: int) -> str:\n",
    "    # TODO: build changed bytes and return hashlib.sha256(...).hexdigest().\n",
    "    raise NotImplementedError\n",
    "\n",
    "\n",
    "digest_izmenennogo = digest_posle_zameny(soderzhimoe, 0, ord(\"x\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-23-17-08",
   "metadata": {},
   "source": [
    "## Task\n",
    "\n",
    "Napisz funkcję, która zastępuje jeden bajt i zwraca SHA-256 zmienionych danych bez zmiany oryginalnego bytes."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-23-17-09",
   "metadata": {},
   "source": [
    "## Tests\n",
    "\n",
    "Run After task cell: jest podstawowy przykład i przynajmniej jeden skrajny przypadek."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "tests-23-17",
   "metadata": {
    "tags": [
     "exercise-tests"
    ]
   },
   "outputs": [],
   "source": [
    "assert digest_izmenennogo != hashlib.sha256(soderzhimoe).hexdigest()\n",
    "assert digest_posle_zameny(b\"abc\", 1, ord(\"b\")) == hashlib.sha256(b\"abc\").hexdigest()\n",
    "assert soderzhimoe[0] != ord(\"x\")\n",
    "print(\"Tests passed\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-23-17-11",
   "metadata": {},
   "source": [
    "## Hint\n",
    "\n",
    "Przekonwertować bytes na `bytearray`, odłóż przedmiot, a potem go zwróć `bytes(changed)` w hashlib."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-23-17-12",
   "metadata": {},
   "source": [
    "## Solution\n",
    "\n",
    "Pokaż rozwiązanie po własnej próbie</summary>\n",
    "\n",
    "```python\n",
    "def digest_posle_zameny(data: bytes, index: int, new_byte: int) -> str:\n",
    "    changed = bytearray(data)\n",
    "    changed[index] = new_byte\n",
    "    return hashlib.sha256(bytes(changed)).hexdigest()\n",
    "\n",
    "\n",
    "digest_izmenennogo = digest_posle_zameny(soderzhimoe, 0, ord(\"x\"))\n",
    "```\n",
    "\n",
    "</details>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Cartesian Python 3.14",
   "language": "python",
   "name": "cartesian-python314"
  },
  "language_info": {
   "name": "python",
   "version": "3.14.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
