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

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
+354
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>
+180
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>
+197
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>
+174
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>