Добавлены уроки и инструменты для редактирования байт

This commit is contained in:
belred 2025-12-08 19:04:13 +03:00
parent 5e75f2d84b
commit 3c1c263c41
8 changed files with 1076 additions and 10 deletions

View File

@ -0,0 +1,354 @@
<script>
export let buffer;
export let onBufferChange;
export let startIndex = 0;
export let byteLength = 1; // 1, 2, 4, 6, 8
export let endianness = 'big'; // 'big' или 'little'
export let numberFormat = 'hex'; // 'bin', 'oct', 'dec', 'hex'
export let readOnlyRanges = [];
let inputValue = '';
let error = '';
function isByteReadOnly(index) {
return readOnlyRanges.some(range =>
index >= range.start && index <= range.end
);
}
$: {
if (buffer && startIndex + byteLength <= buffer.length) {
updateInputFromBuffer();
} else {
error = 'Выход за границы буфера';
}
}
function updateInputFromBuffer() {
try {
const bytes = buffer.slice(startIndex, startIndex + byteLength);
const value = bytesToBigInt(bytes, endianness);
inputValue = formatValueWithLeadingZeros(value);
error = '';
} catch (e) {
error = e.message;
}
}
function bytesToBigInt(bytes, endian) {
let result = 0n;
if (endian === 'big') {
for (let i = 0; i < bytes.length; i++) {
result = (result << 8n) | BigInt(bytes[i]);
}
} else {
for (let i = bytes.length - 1; i >= 0; i--) {
result = (result << 8n) | BigInt(bytes[i]);
}
}
return result;
}
function bigIntToBytes(num, length, endian) {
const bytes = new Uint8Array(length);
let temp = num;
if (endian === 'big') {
for (let i = length - 1; i >= 0; i--) {
bytes[i] = Number(temp & 0xFFn);
temp >>= 8n;
}
} else {
for (let i = 0; i < length; i++) {
bytes[i] = Number(temp & 0xFFn);
temp >>= 8n;
}
}
return bytes;
}
function handleInputChange(e) {
const value = e.target.value.trim().toUpperCase();
inputValue = value;
try {
let bigIntValue;
switch (numberFormat) {
case 'bin':
const binValue = value.replace(/^0b|[\s_]/g, '');
if (!/^[01]*$/.test(binValue)) {
throw new Error('Только 0 и 1 для binary');
}
bigIntValue = binValue === '' ? 0n : BigInt('0b' + binValue);
break;
case 'oct':
const octValue = value.replace(/^0o|[\s_]/g, '');
if (!/^[0-7]*$/.test(octValue)) {
throw new Error('Только цифры 0-7 для octal');
}
bigIntValue = octValue === '' ? 0n : BigInt('0o' + octValue);
break;
case 'dec':
const decValue = value.replace(/[\s_]/g, '');
if (!/^\d*$/.test(decValue)) {
throw new Error('Только цифры для decimal');
}
bigIntValue = decValue === '' ? 0n : BigInt(decValue);
break;
case 'hex':
const hexValue = value.replace(/^0x|[\s_]/g, '');
if (!/^[0-9A-F]*$/.test(hexValue)) {
throw new Error('Только hex цифры (0-9, A-F)');
}
bigIntValue = hexValue === '' ? 0n : BigInt('0x' + hexValue);
break;
default:
throw new Error('Неизвестный формат');
}
const maxBits = 8n * BigInt(byteLength);
const maxValue = (1n << maxBits) - 1n;
if (bigIntValue > maxValue) {
throw new Error(`Максимальное значение: ${formatValueWithLeadingZeros(maxValue)}`);
}
const newBytes = bigIntToBytes(bigIntValue, byteLength, endianness);
const newBuffer = new Uint8Array(buffer);
for (let i = 0; i < byteLength; i++) {
const byteIndex = startIndex + i;
if (isByteReadOnly(byteIndex)) {
throw new Error(`Байт ${byteIndex} защищен от записи`);
}
newBuffer[byteIndex] = newBytes[i];
}
onBufferChange(newBuffer);
error = '';
inputValue = formatValueWithLeadingZeros(bigIntValue);
} catch (e) {
error = e.message;
}
}
function formatValueWithLeadingZeros(val) {
switch (numberFormat) {
case 'bin':
return val.toString(2).padStart(byteLength * 8, '0');
case 'oct':
const octDigits = Math.ceil(byteLength * 8 / 3);
return val.toString(8).padStart(octDigits, '0');
case 'dec':
return val.toString(10);
case 'hex':
return val.toString(16).toUpperCase().padStart(byteLength * 2, '0');
default:
return val.toString(16).toUpperCase().padStart(byteLength * 2, '0');
}
}
function handleFormatChange(e) {
numberFormat = e.target.value;
updateInputFromBuffer();
}
function handleEndiannessChange(e) {
endianness = e.target.value;
updateInputFromBuffer();
}
</script>
<div class="byte-editor">
<h4>Редактор {byteLength} байт</h4>
<div class="controls">
<div class="control-group">
<label>Формат:</label>
<select value={numberFormat} on:change={handleFormatChange}>
<option value="hex">Hex</option>
<option value="dec">Decimal</option>
<option value="bin">Binary</option>
<option value="oct">Octal</option>
</select>
</div>
{#if byteLength > 1}
<div class="control-group">
<label>Порядок байт:</label>
<select value={endianness} on:change={handleEndiannessChange}>
<option value="big">Big Endian</option>
<option value="little">Little Endian</option>
</select>
</div>
{/if}
</div>
<div class="value-input">
<label>Значение:</label>
<div class="input-wrapper">
<input
type="text"
bind:value={inputValue}
on:input={handleInputChange}
class:error={error}
placeholder="Введите значение"
/>
</div>
{#if error}
<div class="error-text">{error}</div>
{/if}
</div>
<div class="byte-preview">
<div class="preview-header">Байты в памяти:</div>
<div class="bytes">
{#if buffer && startIndex + byteLength <= buffer.length}
{#each Array.from({length: byteLength}, (_, i) => i) as i}
<div class="byte">
<span class="index">[{startIndex + i}]</span>
<span class="hex">0x{buffer[startIndex + i].toString(16).padStart(2, '0').toUpperCase()}</span>
<span class="dec">({buffer[startIndex + i]})</span>
</div>
{/each}
{/if}
</div>
</div>
</div>
<style>
.byte-editor {
border: 1px solid #ddd;
border-radius: 8px;
padding: 16px;
margin: 16px 0;
min-width: 400px;
}
.controls {
display: flex;
gap: 16px;
margin-bottom: 16px;
flex-wrap: wrap;
}
.control-group {
display: flex;
flex-direction: column;
gap: 4px;
min-width: 120px;
}
.control-group label {
font-weight: bold;
font-size: 0.9em;
white-space: nowrap;
}
.control-group select {
padding: 6px 10px;
border: 1px solid #ccc;
border-radius: 4px;
font-family: 'Courier New', monospace;
min-width: 100px;
}
.value-input {
margin-bottom: 16px;
}
.value-input label {
display: block;
font-weight: bold;
margin-bottom: 4px;
}
.input-wrapper {
width: 100%;
}
.value-input input {
width: 100%;
min-width: 200px;
padding: 8px 12px;
border: 2px solid #2196F3;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 1em;
box-sizing: border-box;
}
.value-input input.error {
border-color: #f44336;
background-color: #ffebee;
}
.error-text {
color: #f44336;
font-size: 0.9em;
margin-top: 4px;
min-height: 1.2em;
}
.byte-preview {
background: #f5f5f5;
padding: 12px;
border-radius: 4px;
overflow-x: auto;
}
.preview-header {
font-weight: bold;
margin-bottom: 8px;
color: #666;
white-space: nowrap;
}
.bytes {
display: flex;
gap: 8px;
flex-wrap: wrap;
}
.byte {
background: white;
padding: 8px 12px;
border: 1px solid #ddd;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 0.9em;
min-width: 80px;
text-align: center;
flex-shrink: 0;
}
.byte .index {
display: block;
color: #666;
font-size: 0.8em;
margin-bottom: 2px;
}
.byte .hex {
display: block;
font-weight: bold;
font-size: 1em;
}
.byte .dec {
display: block;
color: #2196F3;
font-size: 0.9em;
}
</style>

View File

@ -0,0 +1,180 @@
<script>
import ToolSelector from './ToolSelector.svelte';
import { onMount } from 'svelte';
export let buffer;
export let onBufferChange;
export let readOnlyRanges = []; // [{start, end}]
let selectedByteIndex = -1;
let showToolSelector = false;
let toolPosition = { x: 0, y: 0 };
let containerRef;
onMount(() => {
if (containerRef) {
updateCenterPosition();
}
});
function isByteReadOnly(index) {
return readOnlyRanges.some(range =>
index >= range.start && index <= range.end
);
}
function updateCenterPosition() {
if (!containerRef) return;
const rect = containerRef.getBoundingClientRect();
const centerX = rect.left + rect.width / 2;
const centerY = rect.top + rect.height / 2;
toolPosition = {
x: Math.max(20, centerX - 200),
y: Math.max(20, centerY - 150)
};
}
function selectByte(index, event) {
if (isByteReadOnly(index)) return;
updateCenterPosition();
selectedByteIndex = index;
if (!showToolSelector) {
showToolSelector = true;
}
}
function clearBuffer() {
let newBuffer = new Uint8Array(buffer.length);
readOnlyRanges.forEach(range => {
for (let i = range.start; i <= range.end; i++) {
if (i < buffer.length) {
newBuffer[i] = buffer[i];
}
}
});
onBufferChange(newBuffer);
selectedByteIndex = -1;
showToolSelector = false;
}
$: hexString = Array.from(buffer)
.map((byte, index) => {
const hex = byte.toString(16).padStart(2, '0').toUpperCase();
return { hex, index };
});
</script>
<div class="hex-editor">
<h3>Редактор буфера:</h3>
<div class="hex-view">
{#each hexString as {hex, index}}
<button
class:selected={selectedByteIndex === index}
class:read-only={isByteReadOnly(index)}
class="byte-button"
on:click={(e) => selectByte(index, e)}
>
{'0x'+hex}
</button>
{/each}
</div>
<div class="controls">
<button on:click={clearBuffer} class="clear-button">
Очистить все
</button>
</div>
{#if showToolSelector && selectedByteIndex >= 0 && !isByteReadOnly(selectedByteIndex)}
<ToolSelector
bind:show={showToolSelector}
buffer={buffer}
onBufferChange={onBufferChange}
startIndex={selectedByteIndex}
position={toolPosition}
{readOnlyRanges}
/>
{/if}
</div>
<style>
.hex-editor {
border: 1px solid #ddd;
border-radius: 8px;
padding: 20px;
margin: 16px 0;
}
.hex-view {
display: flex;
gap: 8px;
flex-wrap: wrap;
margin-bottom: 16px;
padding: 16px;
background: white;
border: 1px solid #ddd;
border-radius: 6px;
}
.byte-button {
padding: 8px 12px;
border: 2px solid #2196F3;
background: white;
border-radius: 6px;
cursor: pointer;
font-family: 'Courier New', monospace;
font-weight: bold;
transition: all 0.2s;
position: relative;
min-width: 70px;
}
.byte-button:hover {
background: #e3f2fd;
transform: translateY(-2px);
}
.byte-button.selected {
background: #2196F3;
color: white;
border-color: #1976D2;
}
.byte-button.read-only {
border-color: #9e9e9e;
background: #f5f5f5;
color: #757575;
cursor: not-allowed;
}
.byte-button.read-only:hover {
background: #f5f5f5;
transform: none;
}
.controls {
margin-top: 16px;
}
.clear-button {
padding: 8px 16px;
background: #ffebee;
border: 2px solid #f44336;
border-radius: 6px;
color: #c62828;
cursor: pointer;
font-weight: bold;
}
.clear-button:hover {
background: #ffcdd2;
}
</style>

View File

@ -0,0 +1,197 @@
<script>
import ByteEditor from './ByteEditor.svelte';
import BitEditor from './BitEditor.svelte';
export let buffer;
export let onBufferChange;
export let startIndex = 0;
export let show = false;
export let readOnlyRanges = [];
let selectedTool = 'bit'; // 'bit', 'byte', '2bytes', '4bytes', '6bytes', '8bytes'
function isToolValid(tool, startIndex) {
for (let i = 0; i < tool.bytes; i++) {
const byteIndex = startIndex + i;
if (byteIndex >= buffer.length) return false;
const isReadOnly = readOnlyRanges.some(range =>
byteIndex >= range.start && byteIndex <= range.end
);
if (isReadOnly) return false;
}
return true;
}
$: availableTools = getAvailableTools();
$: if (availableTools.length > 0 && !availableTools.find(t => t.id === selectedTool)){
selectedTool = availableTools[0].id;
}
function getAvailableTools() {
const tools = [
{ id: 'bit', name: 'Битовый редактор', bytes: 1 },
{ id: 'byte', name: '1 байт', bytes: 1 },
{ id: '2bytes', name: '2 байта', bytes: 2 },
{ id: '4bytes', name: '4 байта', bytes: 4 },
{ id: '6bytes', name: '6 байта', bytes: 6 },
{ id: '8bytes', name: '8 байт', bytes: 8 }
];
return tools.filter(tool =>
startIndex + tool.bytes <= buffer.length &&
isToolValid(tool, startIndex)
);
}
function selectTool(toolId) {
selectedTool = toolId;
}
$: selectedToolData = availableTools.find(t => t.id === selectedTool);
</script>
{#if show}
<div
class="tool-selector-overlay"
style="position: fixed; left: 0; top: 0; right: 0; bottom: 0; z-index: 1000;"
>
<div
class="tool-selector-popup"
style="
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
max-width: 90vw;
max-height: 90vh;
"
>
<div class="tool-header">
<h4>Редактирование байта {startIndex}</h4>
</div>
<div class="tool-selection">
{#each availableTools as tool}
<button
class:selected={selectedTool === tool.id}
class="tool-button"
on:click={() => selectTool(tool.id)}
>
{tool.name}
</button>
{/each}
</div>
<div class="tool-content">
{#if selectedTool === 'bit'}
<BitEditor
buffer={new Uint8Array([buffer[startIndex]])}
onBufferChange={(newByte) => {
const newBuffer = new Uint8Array(buffer);
newBuffer[startIndex] = newByte[0];
onBufferChange(newBuffer);
}}
/>
{:else if selectedToolData}
<ByteEditor
buffer={buffer}
onBufferChange={onBufferChange}
startIndex={startIndex}
byteLength={selectedToolData.bytes}
/>
{/if}
</div>
<div class="tool-footer">
<button on:click={() => show = false} class="close-button">
Закрыть
</button>
</div>
</div>
</div>
{/if}
<style>
.tool-selector-overlay {
background: rgba(0, 0, 0, 0.3);
display: flex;
justify-content: center;
align-items: center;
}
.tool-selector-popup {
background: white;
border: 2px solid #2196F3;
border-radius: 12px;
padding: 24px;
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.2);
overflow-y: auto;
min-width: 400px;
}
.tool-header {
margin-bottom: 16px;
border-bottom: 1px solid #eee;
padding-bottom: 12px;
text-align: center;
}
.tool-header h4 {
margin: 0 0 4px 0;
color: #2196F3;
}
.tool-selection {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-bottom: 20px;
justify-content: center;
}
.tool-button {
padding: 8px 16px;
border: 2px solid #e0e0e0;
background: white;
border-radius: 6px;
cursor: pointer;
font-size: 0.9em;
transition: all 0.2s;
}
.tool-button:hover {
background: #f0f7ff;
border-color: #90caf9;
}
.tool-button.selected {
background: #2196F3;
color: white;
border-color: #1976D2;
}
.tool-content {
max-height: 60vh;
overflow-y: auto;
margin-bottom: 16px;
}
.tool-footer {
text-align: center;
}
.close-button {
padding: 8px 24px;
background: #f5f5f5;
border: 2px solid #ddd;
border-radius: 6px;
color: #333;
cursor: pointer;
font-weight: bold;
}
.close-button:hover {
background: #e0e0e0;
}
</style>

View File

@ -0,0 +1,174 @@
<script>
export let data = new Uint8Array([]);
$: destinationMAC = data.slice(0, 6);
$: sourceMAC = data.slice(6, 12);
$: etherType = data.slice(12, 14);
$: frameData = data.slice(14, 60);
$: fcs = data.slice(60, 64);
function formatMAC(bytes) {
return Array.from(bytes)
.map(b => b.toString(16).padStart(2, '0').toUpperCase())
.join(':');
}
function formatHex(bytes) {
if (bytes.length === 0) return 'N/A';
return '0x' + Array.from(bytes)
.map(b => b.toString(16).padStart(2, '0').toUpperCase())
.join(' ');
}
function formatEtherType(bytes) {
if (bytes.length < 2) return 'N/A';
const value = (bytes[0] << 8) | bytes[1];
const types = {
0x0800: 'IPv4',
0x0806: 'ARP',
0x86DD: 'IPv6'
};
return `${types[value] || 'Unknown'} (0x${value.toString(16).padStart(4, '0').toUpperCase()})`;
}
</script>
<div class="wireshark-view">
<h3>Структура Ethernet кадра</h3>
<div class="fields">
<div class="field">
<label>Destination MAC:</label>
<div class="value">{formatMAC(destinationMAC)}</div>
<span class="hint">MAC адрес получателя</span>
</div>
<div class="field">
<label>Source MAC:</label>
<div class="value">{formatMAC(sourceMAC)}</div>
<span class="hint">MAC адрес отправителя</span>
</div>
<div class="field">
<label>EtherType:</label>
<div class="value">{formatEtherType(etherType)}</div>
<span class="hint">Тип протокола</span>
</div>
<div class="field">
<label>Data:</label>
<div class="value data-field">{formatHex(frameData)}</div>
<span class="hint">Полезная нагрузка</span>
</div>
<div class="field">
<label>FCS (Frame Check Sequence):</label>
<div class="value checksum-field">{formatHex(fcs)}</div>
<span class="hint">Контрольная сумма</span>
</div>
</div>
<div class="frame-preview">
<h4>Структура кадра (64 байта):</h4>
<div class="frame-layout">
<div class="frame-field" style="background: #e3f2fd;">
<span>Destination MAC</span>
<small>6 bytes</small>
</div>
<div class="frame-field" style="background: #fff3e0;">
<span>Source MAC</span>
<small>6 bytes</small>
</div>
<div class="frame-field" style="background: #e8f5e8;">
<span>EtherType</span>
<small>2 bytes</small>
</div>
<div class="frame-field" style="background: #f3e5f5;">
<span>Data</span>
<small>46 bytes</small>
</div>
<div class="frame-field" style="background: #ffebee;">
<span>FCS</span>
<small>4 bytes</small>
</div>
</div>
</div>
</div>
<style>
.wireshark-view {
border: 1px solid #ddd;
border-radius: 8px;
padding: 20px;
margin: 16px 0;
background: #fdfdfd;
}
.fields {
margin-bottom: 20px;
}
.field {
margin: 15px 0;
display: flex;
flex-direction: column;
gap: 5px;
}
.field label {
font-weight: bold;
color: #333;
}
.value {
background: white;
padding: 8px 12px;
border-radius: 4px;
border: 1px solid #ddd;
font-family: 'Courier New', monospace;
font-size: 0.9em;
}
.data-field, .checksum-field {
background: #f5f5f5;
}
.hint {
font-size: 0.8em;
color: #666;
font-style: italic;
}
.frame-preview {
margin-top: 20px;
padding-top: 15px;
border-top: 1px solid #eee;
}
.frame-layout {
display: flex;
border: 1px solid #ccc;
border-radius: 4px;
overflow: hidden;
}
.frame-field {
flex: 1;
padding: 10px;
text-align: center;
border-right: 1px solid #ccc;
font-size: 0.9em;
}
.frame-field:last-child {
border-right: none;
}
.frame-field span {
display: block;
font-weight: bold;
}
.frame-field small {
color: #666;
}
</style>

View File

@ -6,6 +6,7 @@ export const lessons = [
category: 'Основы', category: 'Основы',
difficulty: 'Начинающий', difficulty: 'Начинающий',
component: 'BitEditor', component: 'BitEditor',
additionalComponents: ['HexViewer'],
theory: ` theory: `
<div style="max-width: 1000px; margin: 0 auto; line-height: 1.6;"> <div style="max-width: 1000px; margin: 0 auto; line-height: 1.6;">
<h2 style="color: #2196F3; border-bottom: 2px solid #2196F3; padding-bottom: 10px;"> <h2 style="color: #2196F3; border-bottom: 2px solid #2196F3; padding-bottom: 10px;">
@ -99,12 +100,90 @@ export const lessons = [
}, },
{ {
id: 2, id: 2,
slug: 'mac-address-edit',
title: 'MAC адреса - редактирование 6 байт',
category: 'Ethernet',
difficulty: 'Начинающий',
component: 'HexEditor',
theory: `
<div style="max-width: 1000px; margin: 0 auto; line-height: 1.6;">
<h2 style="color: #2196F3; border-bottom: 2px solid #2196F3; padding-bottom: 10px;">
MAC адреса
</h2>
<div style="background: #f9fcff; padding: 20px; border-radius: 8px; margin: 20px 0;">
<h3 style="color: #1976D2; margin-top: 0;">Что такое MAC адрес?</h3>
<ul>
<li><strong>MAC адрес</strong> - уникальный идентификатор сетевого устройства</li>
<li><strong>Формат:</strong> XX:XX:XX:XX:XX:XX (6 байтов)</li>
<li><strong>Пример:</strong> <code>12:34:56:78:9A:BC</code></li>
<li>Первые 3 байта - идентификатор производителя (OUI)</li>
<li>Последние 3 байта - серийный номер устройства</li>
</ul>
</div>
<div style="background: #f9fcff; padding: 20px; border-radius: 8px; margin: 20px 0;">
<h3 style="color: #1976D2; margin-top: 0;">Как редактировать MAC-адрес?</h2>
<h3 style="color: #1976D2; margin-top: 0;">Форматы представления чисел:</h3>
<ul>
<li><strong>Hex (16-ричный):</strong> 0xFF, 0x1A3B</li>
<li><strong>Decimal (10-ричный):</strong> 255, 6715</li>
<li><strong>Binary (2-ичный):</strong> 11111111, 110100011011</li>
<li><strong>Octal (8-ричный):</strong> 377, 15073</li>
</ul>
<h3 style="color: #1976D2; margin-top: 0;">Endianness (порядок байт):</h3>
<ul>
<li><strong>Big Endian:</strong> старший байт по младшему адресу (сетевой порядок)</li>
<li><strong>Little Endian:</strong> младший байт по младшему адресу (x86, ARM)</li>
<li><strong>Пример:</strong> 0x12345678
<ul>
<li>Big Endian: 12 34 56 78</li>
<li>Little Endian: 78 56 34 12</li>
</ul>
</li>
</ul>
</div>
</div>
`,
objective: 'Установите MAC адрес 12:34:56:78:9A:BC',
initialBuffer: new Uint8Array(6),
validate: (buffer) => {
const expectedMAC = [0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC];
return expectedMAC.every((expected, i) => buffer[i] === expected);
},
hints: [
'Для HEX: разделите байт на две половинки по 4 бита. 0x34 = 00110100 → 0011(3) 0100(4)',
'Кликайте на байты в HexView чтобы редактировать их',
'Степени двойки по битам: 128,64,32,16,8,4,2,1'
]
},
{
id: 3,
slug: 'ethernet-frame', slug: 'ethernet-frame',
title: 'Структура Ethernet кадра', title: 'Структура Ethernet кадра',
category: 'Ethernet', category: 'Ethernet',
difficulty: 'Начинающий', difficulty: 'Начинающий',
component: 'EthernetBuilder', component: 'HexEditor',
additionalComponents: ['WiresharkView'],
wiresharkFields: [
{ name: 'Destination MAC', start: 0, length: 6, format: 'mac', color: '#e3f2fd' },
{ name: 'Source MAC', start: 6, length: 6, format: 'mac', color: '#fff3e0' },
{ name: 'EtherType', start: 12, length: 2, format: 'ethertype', color: '#e8f5e8' },
{ name: 'Data', start: 14, length: 46, format: 'hex', color: '#f3e5f5' },
{ name: 'FCS', start: 60, length: 4, format: 'hex', color: '#ffebee' }
],
readOnlyRanges: [
{ start: 14, end: 59 }, //Data (46 байт)
{ start: 60, end: 63 } //FCS (4 байта) - рассчитывается автоматически
],
theory: ` theory: `
<div style="max-width: 1000px; margin: 0 auto; line-height: 1.6;"> <div style="max-width: 1000px; margin: 0 auto; line-height: 1.6;">
<h2 style="color: #2196F3; border-bottom: 2px solid #2196F3; padding-bottom: 10px;"> <h2 style="color: #2196F3; border-bottom: 2px solid #2196F3; padding-bottom: 10px;">

View File

@ -0,0 +1,10 @@
import { updateEthernetBuffer } from './protocols/ethernet.js';
export function processBuffer(buffer, lessonId) {
switch(lessonId) {
case 3: //Ethernet frame lesson
return updateEthernetBuffer(buffer);
default:
return buffer;
}
}

View File

@ -0,0 +1,38 @@
//функции для работы с Ethernet
export function calculateFCS(headerBuffer) {
//упрощенная имитация CRC32
let sum = 0;
for (let i = 0; i < headerBuffer.length; i++) {
sum = (sum + headerBuffer[i]) & 0xFFFFFFFF;
}
for (let i = 0; i < 46; i++) {
sum = (sum + 0x00) & 0xFFFFFFFF;
}
return [
(sum >> 24) & 0xFF,
(sum >> 16) & 0xFF,
(sum >> 8) & 0xFF,
sum & 0xFF
];
}
export function updateEthernetBuffer(buffer, changes = {}) {
const updatedBuffer = new Uint8Array(buffer);
Object.keys(changes).forEach(key => {
const index = parseInt(key);
if (index >= 0 && index < updatedBuffer.length) {
updatedBuffer[index] = changes[key];
}
});
const headerBuffer = updatedBuffer.slice(0, 14);
const fcs = calculateFCS(headerBuffer);
fcs.forEach((byte, i) => {
updatedBuffer[60 + i] = byte;
});
return updatedBuffer;
}

View File

@ -3,13 +3,16 @@
import { lessons } from '$lib/data/lessons'; import { lessons } from '$lib/data/lessons';
import { progressStorage } from '$lib/utils/storage'; import { progressStorage } from '$lib/utils/storage';
import { onMount, afterUpdate } from 'svelte'; import { onMount, afterUpdate } from 'svelte';
import { processBuffer } from '$lib/utils/bufferProcessor';
import HexViewer from '$lib/components/HexViewer.svelte'; import HexViewer from '$lib/components/HexViewer.svelte';
import LessonLayout from '$lib/components/LessonLayout.svelte'; import LessonLayout from '$lib/components/LessonLayout.svelte';
import Notification from '$lib/components/Notification.svelte'; import Notification from '$lib/components/Notification.svelte';
import BitEditor from '$lib/components/BitEditor.svelte'; import BitEditor from '$lib/components/BitEditor.svelte';
import EthernetBuilder from '$lib/components/EthernetBuilder.svelte'; //import EthernetBuilder from '$lib/components/EthernetBuilder.svelte';
import HexEditor from '$lib/components/HexEditor.svelte';
import WiresharkView from '$lib/components/WiresharkView.svelte';
let currentBuffer; let currentBuffer;
let isCompleted = false; let isCompleted = false;
@ -18,6 +21,8 @@
let notification = { show: false, message: '', type: 'success' }; let notification = { show: false, message: '', type: 'success' };
let lesson = null; let lesson = null;
let lessonComponent = null; let lessonComponent = null;
let additionalComponents = [];
let readOnlyRanges = [];
afterUpdate(() => { afterUpdate(() => {
if ($page.params.slug) { if ($page.params.slug) {
@ -25,6 +30,8 @@
if (lesson) { if (lesson) {
lessonComponent = getLessonComponent(lesson.component); lessonComponent = getLessonComponent(lesson.component);
additionalComponents = getAdditionalComponents(lesson.additionalComponents || []);
readOnlyRanges = lesson.readOnlyRanges || [];
} }
} }
}); });
@ -33,13 +40,26 @@
switch(componentName) { switch(componentName) {
case 'BitEditor': case 'BitEditor':
return BitEditor; return BitEditor;
case 'EthernetBuilder': case 'HexEditor':
return EthernetBuilder; return HexEditor;
default: default:
return; return null;
} }
} }
function getAdditionalComponents(componentNames) {
return componentNames.map(name => {
switch(name) {
case 'HexViewer':
return HexViewer;
case 'WiresharkView':
return WiresharkView;
default:
return null;
}
}).filter(Boolean);
}
onMount(() => { onMount(() => {
//инициализация при загрузке на клиенте //инициализация при загрузке на клиенте
if ($page.params.slug) { if ($page.params.slug) {
@ -47,6 +67,8 @@
if (lesson) { if (lesson) {
lessonComponent = getLessonComponent(lesson.component); lessonComponent = getLessonComponent(lesson.component);
additionalComponents = getAdditionalComponents(lesson.additionalComponents || []);
readOnlyRanges = lesson.readOnlyRanges || [];
currentBuffer = new Uint8Array(lesson.initialBuffer); currentBuffer = new Uint8Array(lesson.initialBuffer);
isCompleted = progressStorage.isCompleted(lesson.id.toString()); isCompleted = progressStorage.isCompleted(lesson.id.toString());
} }
@ -54,7 +76,13 @@
}); });
function handleBufferChange(newBuffer) { function handleBufferChange(newBuffer) {
currentBuffer = newBuffer; //обрабатываем буфер через отдельный процессор
if (lesson) {
const processedBuffer = processBuffer(newBuffer, lesson.id);
currentBuffer = processedBuffer;
} else {
currentBuffer = newBuffer;
}
} }
function showNextHint() { function showNextHint() {
@ -92,11 +120,17 @@
this={lessonComponent} this={lessonComponent}
bind:buffer={currentBuffer} bind:buffer={currentBuffer}
onBufferChange={handleBufferChange} onBufferChange={handleBufferChange}
readOnlyRanges={readOnlyRanges || []}
/> />
{#if currentBuffer} {#each additionalComponents as Component}
<HexViewer data={currentBuffer} /> {#if currentBuffer}
{/if} <svelte:component
this={Component}
data={currentBuffer}
/>
{/if}
{/each}
<div class="controls"> <div class="controls">
<button on:click={checkSolution} class="check-button"> <button on:click={checkSolution} class="check-button">