diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 764a2f0..0000000 Binary files a/.DS_Store and /dev/null differ diff --git a/.gitignore b/.gitignore index 15f1b77..891603a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,10 @@ /bin/ +/build/ /charImg/ +.gradle/ + .DS_Store + +# IDEs +.idea/ +.vscode/ \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..14cf5b2 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,47 @@ +// Tell gradle that this is in fact a java project +plugins { + java +} + +// Add maven central as the repository to resolve dependencies +repositories { + mavenCentral() +} + +// Set java version to Java 21 +java { + toolchain { + languageVersion.set(JavaLanguageVersion.of(21)) + } +} + +dependencies { + testImplementation(platform("org.junit:junit-bom:5.13.2")) // Make sure junit versions are compatible + testImplementation("org.junit.jupiter:junit-jupiter") // JUnit 5 api + testImplementation("org.assertj:assertj-core:3.27.3") // AssertJ for fluent assertions + + testRuntimeOnly("org.junit.platform:junit-platform-launcher") // JUnit 5 runtime support +} + +// Add 'src/' as a source directory +// TODO: Sources should be move to src/main/java +sourceSets.main { + java { + srcDirs("src") + } + resources { + srcDirs("resources") + } +} + +// Add 'test/' as a test source directory +// TODO: Tests should be moved to src/test/java +sourceSets.test { + java { + srcDirs("test") + } +} + +tasks.test { + useJUnitPlatform() // Use JUnit 5 for testing +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..64debcc --- /dev/null +++ b/gradle.properties @@ -0,0 +1,3 @@ +# Speedup build by enabling caching +org.gradle.caching=true +org.gradle.configuration-cache=true \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e644113 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..23449a2 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..b740cf1 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..25da30d --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..5f4958c --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,4 @@ +plugins { + // Automatically resolve and download required JDK + id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0" +} \ No newline at end of file diff --git a/src/Bus.java b/src/Bus.java index 03ae48f..494a3a4 100644 --- a/src/Bus.java +++ b/src/Bus.java @@ -4,7 +4,7 @@ public class Bus { public static byte read(short address) { if (Short.toUnsignedInt(address) >= 0x8000) { - return EaterEmulator.rom.read((short)(address-0x8000)); + return EaterEmulator.rom.read(address); } else if (Short.toUnsignedInt(address) <= VIA_ADDRESS+16 && Short.toUnsignedInt(address) >= VIA_ADDRESS) { return EaterEmulator.via.read(address); } else if (Short.toUnsignedInt(address) <= ACIA_ADDRESS+3 && Short.toUnsignedInt(address) >= ACIA_ADDRESS) { diff --git a/src/RAM.java b/src/RAM.java index 703f760..8c1b831 100644 --- a/src/RAM.java +++ b/src/RAM.java @@ -1,55 +1,38 @@ -public class RAM { - private byte[] array; - public String RAMString = ""; +import memory.RandomAccessMemory; + +public class RAM extends RandomAccessMemory { + public String RAMString; public RAM() { - array = new byte[0x8000]; - for (int i = 0; i<0x8000; i++) { - array[i] = (byte)0x00; - } - RAMString = this.toString(8, true); + super(0x8000); + RAMString = this.formatToString(); } public RAM(byte[] theArray) { - array = theArray; - RAMString = this.toString(8, true); + super(theArray); + RAMString = this.formatToString(); } + /** + * @deprecated Use {@link #getData()} instead to retrieve the RAM array. + */ + @Deprecated public byte[] getRAMArray() { - return array; + return getData(); } + /** + * @deprecated Avoid replacing the entire RAM array. Create a new instance if needed. + */ + @Deprecated public void setRAMArray(byte[] array) { - this.array = array; - RAMString = this.toString(8, true); - } - - public byte read(short address) { - return array[Short.toUnsignedInt(address)]; + this.data = array; + RAMString = this.formatToString(); } - + + @Override public void write(short address, byte data) { - array[Short.toUnsignedInt(address)] = data; - RAMString = this.toString(8, true); - } - - public String toString(int bytesPerLine, boolean addresses) { - StringBuilder sb = new StringBuilder(); - - if (addresses) - sb.append("0000: "); - - for (int i = 1; i <= array.length; i++) { - if ((i%bytesPerLine != 0) || (i == 0)) { - sb.append(ROMLoader.byteToHexString(array[i-1])+" "); - } else { - String zeroes = "0000"; - sb.append(ROMLoader.byteToHexString(array[i-1])+"\n"); - if (addresses) - sb.append(zeroes.substring(0, Math.max(0, 4-Integer.toHexString(i).length()))+Integer.toHexString(i)+": "); - } - } - - return sb.toString(); + super.write(address, data); + RAMString = this.formatToString(); } } diff --git a/src/ROM.java b/src/ROM.java index 071ec9b..987cfa1 100644 --- a/src/ROM.java +++ b/src/ROM.java @@ -1,63 +1,24 @@ -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; +import memory.ReadOnlyMemory; -public class ROM { - private byte[] array; +public class ROM extends ReadOnlyMemory { public String ROMString = ""; public ROM() { - array = new byte[0x8000]; - for (int i = 0; i < 0x8000; i++) { - array[i] = (byte) 0x00; - } - ROMString = this.toStringWithOffset(8, 0x8000, true); + super(0x8000, (short) 0x8000); + ROMString = this.formatToString(8, true); } public ROM(byte[] theArray) { - array = theArray; - ROMString = this.toStringWithOffset(8, 0x8000, true); - } - - public byte[] getROMArray() { - return array; + super(theArray, (short) 0x8000); + ROMString = this.formatToString(8, true); } public void setROMArray(byte[] array) { - this.array = array; - ROMString = this.toStringWithOffset(8, 0x8000, true); - } - - public byte read(short address) { - return array[Short.toUnsignedInt(address)]; + this.data = array; + ROMString = this.formatToString(8, true); } public String toString(int bytesPerLine, boolean addresses) { - return toStringWithOffset(bytesPerLine, 0, addresses); - } - - public String toStringWithOffset(int bytesPerLine, int addressOffset, boolean addresses) { - List chunks = new ArrayList<>(); - int chunkAmount = (int) Math.ceil(array.length / (double) bytesPerLine); - - for (int i = 0; i < chunkAmount; i++) { - int end = Math.min(array.length, (i + 1) * bytesPerLine); - byte[] chunk = Arrays.copyOfRange(array, i * bytesPerLine, end); - chunks.add(chunk); - } - - var lines = CollectionUtils.withIndex(chunks).stream().map(indexedValue -> { - var localSb = new StringBuilder(); - Byte[] chunk = CollectionUtils.toBoxedArray(indexedValue.value()); - - if (addresses) - localSb.append(String.format("%04X: ", (indexedValue.index() * bytesPerLine) + addressOffset)); - - localSb.append(String.join(" ", CollectionUtils.mapArray(chunk, (b -> String.format("%02X", b))))); - return localSb.toString(); - } - ).toList(); - - return String.join(System.lineSeparator(), lines); + return formatToString(bytesPerLine, addresses); } } diff --git a/src/memory/RandomAccessMemory.java b/src/memory/RandomAccessMemory.java new file mode 100644 index 0000000..537404d --- /dev/null +++ b/src/memory/RandomAccessMemory.java @@ -0,0 +1,24 @@ +package memory; + +public class RandomAccessMemory extends ReadOnlyMemory { + public RandomAccessMemory(byte[] data) { + super(data); + } + + public RandomAccessMemory(byte[] data, short addressOffset) { + super(data, addressOffset); + } + + public RandomAccessMemory(int size) { + super(size); + } + + public RandomAccessMemory(int size, short addressOffset) { + super(size, addressOffset); + } + + public void write(short address, byte data) { + int internalAddress = addressConverter.toInternalAddress(address); + this.data[internalAddress] = data; + } +} diff --git a/src/memory/ReadOnlyMemory.java b/src/memory/ReadOnlyMemory.java new file mode 100644 index 0000000..ce67225 --- /dev/null +++ b/src/memory/ReadOnlyMemory.java @@ -0,0 +1,116 @@ +package memory; + +import utils.AddressConverter; +import utils.CollectionUtils; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class ReadOnlyMemory { + protected byte[] data; + protected final int addressOffset; + protected final AddressConverter addressConverter; + + /** + * Constructor for ReadOnlyMemory with specified data and no address offset. + * @param data Byte array containing the initial data for the memory. + */ + public ReadOnlyMemory(byte[] data) { + this(data, (short) 0); + } + + /** + * Constructor for ReadOnlyMemory with specified data and address offset. + * @param data Byte array containing the initial data for the memory. + * @param addressOffset Offset of the memory in the address space. + */ + public ReadOnlyMemory(byte[] data, short addressOffset) { + this.data = data.clone(); + this.addressOffset = Short.toUnsignedInt(addressOffset); + this.addressConverter = new AddressConverter(this.addressOffset); + } + + /** + * Default constructor for ReadOnlyMemory with no address offset. + * @param size Size of the memory in bytes. + */ + public ReadOnlyMemory(int size) { + this(size, (short) 0); + } + + /** + * Constructor for ReadOnlyMemory with specified size and address offset. + * @param size Size of the memory in bytes. + * @param addressOffset Offset of the memory in the address space. + */ + public ReadOnlyMemory(int size, short addressOffset) { + this(new byte[size], addressOffset); + Arrays.fill(data, (byte) 0); + } + + public byte read(short address) { + return read(address, 1)[0]; + }; + + byte[] read(short address, int length) { + int startAddress = addressConverter.toInternalAddress(address); + + if (startAddress < 0) { + throw new IndexOutOfBoundsException("Address cannot be negative: " + address); + } + + if (startAddress + length > data.length) { + throw new IndexOutOfBoundsException("Read exceeds memory bounds: %04X + %d".formatted(address, length)); + } + + return Arrays.copyOfRange(data, startAddress, startAddress+length); + }; + + /** + * Returns a copy of the data in this memory. + * @return A byte array containing the data in this memory. + */ + public byte[] getData() { + return data.clone(); + } + + /** + * Returns a hex dump representation of the memory. + * @param bytesPerLine Number of bytes to display per line. + * @param addresses Whether to include addresses in the output. + * @return A string representation of the memory in hex format. + */ + public String formatToString(int bytesPerLine, boolean addresses) { + List chunks = new ArrayList<>(); + int chunkAmount = (int) Math.ceil(data.length / (double) bytesPerLine); + + for (int i = 0; i < chunkAmount; i++) { + int end = Math.min(data.length, (i + 1) * bytesPerLine); + byte[] chunk = Arrays.copyOfRange(data, i * bytesPerLine, end); + chunks.add(chunk); + } + + var lines = CollectionUtils.withIndex(chunks).stream().map(indexedValue -> { + var localSb = new StringBuilder(); + Byte[] chunk = CollectionUtils.toBoxedArray(indexedValue.value()); + + if (addresses) + localSb.append(String.format("%04X: ", addressConverter.toExternalAddress(indexedValue.index() * bytesPerLine))); + + localSb.append(String.join(" ", CollectionUtils.mapArray(chunk, (b -> String.format("%02X", b))))); + return localSb.toString(); + } + ).toList(); + + return String.join(System.lineSeparator(), lines); + } + + /** + * Returns a hex dump representation of the memory with default parameters. (8 bytes per line, addresses included). + * @return A string representation of the memory in hex format. + */ + public String formatToString() { + return formatToString(8, true); + } +} diff --git a/src/utils/AddressConverter.java b/src/utils/AddressConverter.java new file mode 100644 index 0000000..8a47635 --- /dev/null +++ b/src/utils/AddressConverter.java @@ -0,0 +1,34 @@ +package utils; + +public class AddressConverter { + private final int addressOffset; + + public AddressConverter(int addressOffset) { + this.addressOffset = addressOffset; + } + + /** + * Converts an external address (short) to the component internal address space (int) dealing making sure the returned value is non-negative. + * @param address External address to convert. + * @return Internal address as an integer. Shifted by the address offset. + */ + public int toInternalAddress(short address) { + int convertedAddress = Short.toUnsignedInt(address) - addressOffset; + if (convertedAddress < 0) { + throw new IndexOutOfBoundsException("Given address is smaller than address offset: " + convertedAddress); + } + return convertedAddress; + } + + /** + * Converts an internal address (int) to the external address space (short). + * @param internalAddress Internal address to convert. + * @return External address as a short. Shifted by the address offset. + */ + public short toExternalAddress(int internalAddress) { + if (internalAddress < 0) { + throw new IndexOutOfBoundsException("Internal address cannot be negative: " + internalAddress); + } + return (short) (internalAddress + addressOffset); + } +} diff --git a/src/CollectionUtils.java b/src/utils/CollectionUtils.java similarity index 97% rename from src/CollectionUtils.java rename to src/utils/CollectionUtils.java index 2aaaa85..4a29011 100644 --- a/src/CollectionUtils.java +++ b/src/utils/CollectionUtils.java @@ -1,3 +1,5 @@ +package utils; + import java.util.Arrays; import java.util.List; import java.util.function.Function; diff --git a/test/RomTest.java b/test/RomTest.java new file mode 100644 index 0000000..b8294a9 --- /dev/null +++ b/test/RomTest.java @@ -0,0 +1,71 @@ +import org.junit.jupiter.api.Test; + +import java.util.function.Function; + +import static org.assertj.core.api.Assertions.assertThat; + +public class RomTest { + @Test + public void shouldInitializeROM() { + ROM rom = new ROM(); + + assertThat(rom.getData()).hasSize(0x8000); + for (byte b : rom.getData()) { + assertThat(b).isEqualTo((byte) 0); + } + } + + @Test + public void shouldSetRomFromArray() { + byte[] testArray = createTestArray(0x8); + ROM rom = new ROM(testArray); + + assertThat(rom.getData()).isEqualTo(testArray); + } + + @Test + public void shouldReadByteFromROM() { + byte[] testArray = createTestArray(0x8000); + ROM rom = new ROM(testArray); + + assertThat(rom.read((short) 0x8000)).isEqualTo((byte) 0); + assertThat(rom.read((short) 0x8001)).isEqualTo((byte) 1); + assertThat(rom.read((short) 0x80FF)).isEqualTo((byte) 255); + assertThat(rom.read((short) 0x8100)).isEqualTo((byte) 0); + } + + @Test + public void shouldConvertROMToString() { + byte[] testArray = createTestArray(0x8); + ROM rom = new ROM(testArray); + + String romString = rom.formatToString(8, true); + assertThat(romString).isEqualTo("8000: 00 01 02 03 04 05 06 07"); + } + + @Test + public void shouldConvertROMToStringWithPartialLines() { + byte[] testArray = createTestArray(0x6); + ROM rom = new ROM(testArray); + + String romString = rom.formatToString(8, true); + assertThat(romString).isEqualTo("8000: 00 01 02 03 04 05"); + } + + @Test + public void shouldConvertROMToStringWithoutAddresses() { + byte[] testArray = createTestArray(0x8); + ROM rom = new ROM(testArray); + + String romString = rom.formatToString(8, false); + assertThat(romString).isEqualTo("00 01 02 03 04 05 06 07"); + } + + private byte[] createTestArray(int size) { + byte[] testArray = new byte[size]; + for (int i1 = 0; i1 < testArray.length; i1++) { + testArray[i1] = ((Function) i -> (byte) (i % 256)).apply(i1); + } + return testArray; + } +} diff --git a/test/memory/ReadOnlyMemoryTest.java b/test/memory/ReadOnlyMemoryTest.java new file mode 100644 index 0000000..9764941 --- /dev/null +++ b/test/memory/ReadOnlyMemoryTest.java @@ -0,0 +1,95 @@ +package memory; + +import org.junit.jupiter.api.Test; + +import java.util.function.Function; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ReadOnlyMemoryTest { + @Test + public void shouldInitializeROM() { + ReadOnlyMemory rom = new ReadOnlyMemory(0x8000); + + assertThat(rom.getData()).hasSize(0x8000); + for (byte b : rom.getData()) { + assertThat(b).isEqualTo((byte) 0); + } + } + + @Test + public void shouldSetRomFromArray() { + byte[] testArray = createTestArray(0x8); + ReadOnlyMemory rom = new ReadOnlyMemory(testArray); + + assertThat(rom.getData()).isEqualTo(testArray); + } + + @Test + public void shouldReadByteFromROM() { + byte[] testArray = createTestArray(0x8000); + ReadOnlyMemory rom = new ReadOnlyMemory(testArray); + + assertThat(rom.read((short) 0)).isEqualTo((byte) 0); + assertThat(rom.read((short) 1)).isEqualTo((byte) 1); + assertThat(rom.read((short) 255)).isEqualTo((byte) 255); + assertThat(rom.read((short) 256)).isEqualTo((byte) 0); + } + + @Test + public void shouldReadMultipleBytesFromROM() { + byte[] testArray = createTestArray(0x8000); + ReadOnlyMemory rom = new ReadOnlyMemory(testArray); + + assertThat(rom.read((short) 0, 10)) + .hasSize(10) + .containsExactly( + (byte) 0, (byte) 1, (byte) 2, (byte) 3, (byte) 4, + (byte) 5, (byte) 6, (byte) 7, (byte) 8, (byte) 9 + ); + } + + @Test + public void shouldConvertROMToString() { + byte[] testArray = createTestArray(0x8); + ReadOnlyMemory rom = new ReadOnlyMemory(testArray); + + String romString = rom.formatToString(8, true); + assertThat(romString).isEqualTo("0000: 00 01 02 03 04 05 06 07"); + } + + @Test + public void shouldConvertROMToStringWithPartialLines() { + byte[] testArray = createTestArray(0x6); + ReadOnlyMemory rom = new ReadOnlyMemory(testArray); + + String romString = rom.formatToString(8, true); + assertThat(romString).isEqualTo("0000: 00 01 02 03 04 05"); + } + + @Test + public void shouldConvertROMToStringWithoutAddresses() { + byte[] testArray = createTestArray(0x8); + ReadOnlyMemory rom = new ReadOnlyMemory(testArray); + + String romString = rom.formatToString(8, false); + assertThat(romString).isEqualTo("00 01 02 03 04 05 06 07"); + } + + @Test + public void shouldConvertROMToStringWithOffset() { + byte[] testArray = createTestArray(0x8); + ReadOnlyMemory rom = new ReadOnlyMemory(testArray, (short) 0x8000); + + String romString = rom.formatToString(8, true); + assertThat(romString).isEqualTo("8000: 00 01 02 03 04 05 06 07"); + } + + private byte[] createTestArray(int size) { + byte[] testArray = new byte[size]; + for (int i1 = 0; i1 < testArray.length; i1++) { + testArray[i1] = ((Function) i -> (byte) (i % 256)).apply(i1); + } + return testArray; + } +} diff --git a/test/utils/AddressConverterTest.java b/test/utils/AddressConverterTest.java new file mode 100644 index 0000000..910707a --- /dev/null +++ b/test/utils/AddressConverterTest.java @@ -0,0 +1,78 @@ +package utils; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.List; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class AddressConverterTest { + public static Stream testDataProvider() { + return Stream.of( + Arguments.of((short) 0, 0), + Arguments.of((short) 1, 1), + Arguments.of((short) 255, 255), + Arguments.of((short) 256, 256), + Arguments.of(Short.MAX_VALUE, 32767), + Arguments.of((short) -1, 65535), + Arguments.of((short) 0xFFFF, 65535) + + ); + } + + public static Stream externalToInternalAddressWithOffsetProvider() { + return Stream.of( + List.of((short) 0x8000, 0), + List.of((short) 0x8FFF, 0x0FFF) + ).map(args -> Arguments.argumentSet( + "internal: 0x%04X -> external: 0x%04X".formatted(args.getFirst(), args.get(1)), + args.getFirst(), + args.get(1)) + ); + } + + @ParameterizedTest + @MethodSource("testDataProvider") + void testConvertToInternalAddress(short externalAddress, int expectedInternalAddress) { + final AddressConverter converter = new AddressConverter(0); + assertThat(converter.toInternalAddress(externalAddress)).isEqualTo(expectedInternalAddress); + } + + @ParameterizedTest + @MethodSource("testDataProvider") + void testConvertToExternalAddress(short expectedExternalAddress, int internalAddress) { + final AddressConverter converter = new AddressConverter(0); + assertThat(converter.toExternalAddress(internalAddress)).isEqualTo(expectedExternalAddress); + } + + @ParameterizedTest + @MethodSource("externalToInternalAddressWithOffsetProvider") + void convertWithOffsetToInternal(short externalAddress, int expectedInternalAddress) { + final int addressOffset = 0x8000; + final AddressConverter converter = new AddressConverter(addressOffset); + + assertThat(converter.toInternalAddress(externalAddress)).isEqualTo(expectedInternalAddress); + } + + @ParameterizedTest + @MethodSource("externalToInternalAddressWithOffsetProvider") + void convertWithOffsetToExternal(short expectedExternalAddress, int internalAddress) { + final int addressOffset = 0x8000; + final AddressConverter converter = new AddressConverter(addressOffset); + + assertThat(converter.toExternalAddress(internalAddress)).isEqualTo(expectedExternalAddress); + } + + @Test + void throwExceptionOnTooSmallInputAddress() { + final AddressConverter converter = new AddressConverter(0x8000); + assertThatThrownBy(() -> converter.toInternalAddress((short) 0x7FFF)) + .isInstanceOf(IndexOutOfBoundsException.class) + .hasMessageContaining("Given address is smaller than address offset:"); + } +} \ No newline at end of file