88import me .jddev0 .module .lang .LangInterpreter .*;
99
1010public class IOModule extends LangNativeModule {
11- private final Map <Integer , File > openedFiles = new HashMap <>();
12- private int currentFileID ;
13-
14- public IOModule () {
15- currentFileID = 0 ;
16- }
11+ private final ObjectIDMap <File > openedFiles = new ObjectIDMap <>(file -> file .getAbsolutePath ().hashCode ());
1712
1813 @ Override
1914 public DataObject load (List <DataObject > args , final int SCOPE_ID ) {
@@ -39,9 +34,8 @@ private void exportFileFunctions() {
3934 path = interpreter .getCurrentCallStackElement ().getLangPath () + File .separator + path ;
4035
4136 File file = new File (path );
42- final int FILE_ID = generateNextFileID (file );
4337
44- openedFiles .put ( FILE_ID , file );
38+ final int FILE_ID = openedFiles .add ( file );
4539
4640 return createDataObject (FILE_ID );
4741 })));
@@ -417,7 +411,7 @@ public DataObject unload(List<DataObject> args, final int SCOPE_ID) {
417411 createDataObject ("The files which were not be closed will be returned as an array of arrays in the format [[fileID1, filePath1], [fileID2, filePath2], ...]." )
418412 ), SCOPE_ID );
419413
420- DataObject [] notYetClosedFiles = openedFiles .entrySet ().stream ().map (entry -> {
414+ DataObject [] notYetClosedFiles = openedFiles .entries ().stream ().map (entry -> {
421415 int id = entry .getKey ();
422416 File file = entry .getValue ();
423417
@@ -454,29 +448,8 @@ private DataObject createFileFunctionPointerVarArg(FileFunctionPointerVarArg fun
454448 return createDataObject (new DataObject .FunctionPointerObject (func ));
455449 }
456450
457- /**
458- * Should prevent devs from introducing bugs by guessing or calculating file ids [THIS IS NO SECURITY FEATURE]
459- */
460- private int generateNextFileID (File file ) {
461- do {
462- int selfHashCode = hashCode ();
463- do {
464- selfHashCode += (int )System .currentTimeMillis () + (int )System .nanoTime ();
465- }while (selfHashCode == 0 );
466-
467- int pathHashCode = file .getAbsolutePath ().hashCode ();
468- do {
469- selfHashCode += (int )System .currentTimeMillis () + (int )System .nanoTime ();
470- }while (selfHashCode == 0 );
471-
472- this .currentFileID += pathHashCode % selfHashCode + selfHashCode ;
473- }while (openedFiles .containsKey (this .currentFileID ));
474-
475- return currentFileID ;
476- }
477-
478451 private DataObject checkFileOpened (int fileID , final int SCOPE_ID ) {
479- if (!openedFiles .containsKey (fileID ))
452+ if (!openedFiles .containsId (fileID ))
480453 return throwError (InterpretingError .FILE_NOT_FOUND , "The file with the ID " + fileID + " was not opened" , SCOPE_ID );
481454
482455 return null ;
0 commit comments