BS 0.0.1 EasySave完成

This commit is contained in:
2025-06-29 01:46:32 +08:00
parent e5bc6a2592
commit 0385ffbd29
15 changed files with 1869 additions and 1992 deletions

View File

@@ -1,7 +1,11 @@
using System; using System;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Field | AttributeTargets.Property)] namespace Convention.EasySave
public class EasySaved : Attribute{} {
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Field | AttributeTargets.Property)] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Field | AttributeTargets.Property)]
public class EasySaveIgnored : Attribute { } public class EasySaved : Attribute { }
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Field | AttributeTargets.Property)]
public class EasySaveIgnored : Attribute { }
}

View File

@@ -2,6 +2,7 @@
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using Convention.EasySave.Internal; using Convention.EasySave.Internal;
using Convention.EasySave.Types;
namespace Convention.EasySave namespace Convention.EasySave
{ {
@@ -260,81 +261,6 @@ namespace Convention.EasySave
stream.Write(bytes, 0, bytes.Length); stream.Write(bytes, 0, bytes.Length);
} }
/// <summary>Saves a Texture2D as a PNG or JPG, depending on the file extension used for the filePath.</summary>
/// <param name="texture">The Texture2D we want to save as a JPG or PNG.</param>
/// <param name="imagePath">The relative or absolute path of the PNG or JPG file we want to create.</param>
public static void SaveImage(Texture2D texture, string imagePath)
{
SaveImage(texture, new EasySaveSettings(imagePath));
}
/// <summary>Saves a Texture2D as a PNG or JPG, depending on the file extension used for the filePath.</summary>
/// <param name="texture">The Texture2D we want to save as a JPG or PNG.</param>
/// <param name="imagePath">The relative or absolute path of the PNG or JPG file we want to create.</param>
public static void SaveImage(Texture2D texture, string imagePath, EasySaveSettings settings)
{
SaveImage(texture, new EasySaveSettings(imagePath, settings));
}
/// <summary>Saves a Texture2D as a PNG or JPG, depending on the file extension used for the filePath.</summary>
/// <param name="texture">The Texture2D we want to save as a JPG or PNG.</param>
/// <param name="settings">The settings we want to use to override the default settings.</param>
public static void SaveImage(Texture2D texture, EasySaveSettings settings)
{
SaveImage(texture, 75, settings);
}
/// <summary>Saves a Texture2D as a PNG or JPG, depending on the file extension used for the filePath.</summary>
/// <param name="texture">The Texture2D we want to save as a JPG or PNG.</param>
/// <param name="quality">Quality to encode with, where 1 is minimum and 100 is maximum. Note that this only applies to JPGs.</param>
/// <param name="imagePath">The relative or absolute path of the PNG or JPG file we want to create.</param>
public static void SaveImage(Texture2D texture, int quality, string imagePath)
{
SaveImage(texture, quality, new EasySaveSettings(imagePath));
}
/// <summary>Saves a Texture2D as a PNG or JPG, depending on the file extension used for the filePath.</summary>
/// <param name="texture">The Texture2D we want to save as a JPG or PNG.</param>
/// <param name="quality">Quality to encode with, where 1 is minimum and 100 is maximum. Note that this only applies to JPGs.</param>
/// <param name="imagePath">The relative or absolute path of the PNG or JPG file we want to create.</param>
public static void SaveImage(Texture2D texture, int quality, string imagePath, EasySaveSettings settings)
{
SaveImage(texture, quality, new EasySaveSettings(imagePath, settings));
}
/// <summary>Saves a Texture2D as a PNG or JPG, depending on the file extension used for the filePath.</summary>
/// <param name="texture">The Texture2D we want to save as a JPG or PNG.</param>
/// <param name="quality">Quality to encode with, where 1 is minimum and 100 is maximum. Note that this only applies to JPGs.</param>
/// <param name="settings">The settings we want to use to override the default settings.</param>
public static void SaveImage(Texture2D texture, int quality, EasySaveSettings settings)
{
// Get the file extension to determine what format we want to save the image as.
string extension = EasySaveIO.GetExtension(settings.path).ToLower();
if (string.IsNullOrEmpty(extension))
throw new System.ArgumentException("File path must have a file extension when using EasySave.SaveImage.");
byte[] bytes;
if (extension == ".jpg" || extension == ".jpeg")
bytes = texture.EncodeToJPG(quality);
else if (extension == ".png")
bytes = texture.EncodeToPNG();
else
throw new System.ArgumentException("File path must have extension of .png, .jpg or .jpeg when using EasySave.SaveImage.");
EasySave.SaveRaw(bytes, settings);
}
/// <summary>Saves a Texture2D as a PNG or JPG, depending on the file extension used for the filePath.</summary>
/// <param name="texture">The Texture2D we want to save as a JPG or PNG.</param>
/// <param name="quality">Quality to encode with, where 1 is minimum and 100 is maximum. Note that this only applies to JPGs.</param>
public static byte[] SaveImageToBytes(Texture2D texture, int quality, EasySave.ImageType imageType)
{
if (imageType == ImageType.JPEG)
return texture.EncodeToJPG(quality);
else
return texture.EncodeToPNG();
}
#endregion #endregion
#region EasySave.Load<T> #region EasySave.Load<T>
@@ -720,7 +646,7 @@ namespace Convention.EasySave
return Serialize(value, EasySaveTypeMgr.GetOrCreateEasySaveType(typeof(T)), settings); return Serialize(value, EasySaveTypeMgr.GetOrCreateEasySaveType(typeof(T)), settings);
} }
internal static byte[] Serialize(object value, Convention.EasySave.Types.EasySaveType type, EasySaveSettings settings = null) internal static byte[] Serialize(object value, EasySaveType type, EasySaveSettings settings = null)
{ {
if (settings == null) settings = new EasySaveSettings(); if (settings == null) settings = new EasySaveSettings();
@@ -745,7 +671,7 @@ namespace Convention.EasySave
return (T)Deserialize(EasySaveTypeMgr.GetOrCreateEasySaveType(typeof(T)), bytes, settings); return (T)Deserialize(EasySaveTypeMgr.GetOrCreateEasySaveType(typeof(T)), bytes, settings);
} }
internal static object Deserialize(Convention.EasySave.Types.EasySaveType type, byte[] bytes, EasySaveSettings settings = null) internal static object Deserialize(EasySaveType type, byte[] bytes, EasySaveSettings settings = null)
{ {
if (settings == null) if (settings == null)
settings = new EasySaveSettings(); settings = new EasySaveSettings();
@@ -761,7 +687,7 @@ namespace Convention.EasySave
DeserializeInto(EasySaveTypeMgr.GetOrCreateEasySaveType(typeof(T)), bytes, obj, settings); DeserializeInto(EasySaveTypeMgr.GetOrCreateEasySaveType(typeof(T)), bytes, obj, settings);
} }
public static void DeserializeInto<T>(Convention.EasySave.Types.EasySaveType type, byte[] bytes, T obj, EasySaveSettings settings = null) where T : class public static void DeserializeInto<T>(EasySaveType type, byte[] bytes, T obj, EasySaveSettings settings = null) where T : class
{ {
if (settings == null) if (settings == null)
settings = new EasySaveSettings(); settings = new EasySaveSettings();

View File

@@ -6,9 +6,12 @@ using Convention.EasySave.Types;
using Convention.EasySave.Internal; using Convention.EasySave.Internal;
using System.Linq; using System.Linq;
/// <summary>Represents a cached file which can be saved to and loaded from, and commited to storage when necessary.</summary> namespace Convention.EasySave
public class EasySaveFile
{ {
/// <summary>Represents a cached file which can be saved to and loaded from, and commited to storage when necessary.</summary>
public class EasySaveFile
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static Dictionary<string, EasySaveFile> cachedFiles = new Dictionary<string, EasySaveFile>(); public static Dictionary<string, EasySaveFile> cachedFiles = new Dictionary<string, EasySaveFile>();
@@ -491,10 +494,10 @@ public class EasySaveFile
return new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc); return new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
return cachedFile.timestamp; return cachedFile.timestamp;
} }
} }
namespace Convention.EasySave.Internal namespace Internal
{ {
public struct EasySaveData public struct EasySaveData
{ {
public EasySaveType type; public EasySaveType type;
@@ -512,4 +515,5 @@ namespace Convention.EasySave.Internal
this.bytes = bytes; this.bytes = bytes;
} }
} }
}
} }

View File

@@ -52,7 +52,7 @@ namespace Convention.EasySave.Internal
// This obviously won't work if exceptions are disabled. // This obviously won't work if exceptions are disabled.
try try
{ {
if (assemblyNames.Contains(assembly.GetName().Name)) //if (assemblyNames.Contains(assembly.GetName().Name))
assemblyList.Add(assembly); assemblyList.Add(assembly);
} }
catch { } catch { }

View File

@@ -3,8 +3,10 @@ using System.Collections.Generic;
using System.IO; using System.IO;
using Convention.EasySave.Internal; using Convention.EasySave.Internal;
public class EasySaveSpreadsheet namespace Convention.EasySave
{ {
public class EasySaveSpreadsheet
{
private int cols = 0; private int cols = 0;
private int rows = 0; private int rows = 0;
private Dictionary<Index, string> cells = new Dictionary<Index, string>(); private Dictionary<Index, string> cells = new Dictionary<Index, string>();
@@ -18,12 +20,12 @@ public class EasySaveSpreadsheet
public int ColumnCount public int ColumnCount
{ {
get{ return cols; } get { return cols; }
} }
public int RowCount public int RowCount
{ {
get{ return rows; } get { return rows; }
} }
public int GetColumnLength(int col) public int GetColumnLength(int col)
@@ -33,11 +35,11 @@ public class EasySaveSpreadsheet
int maxRow = -1; int maxRow = -1;
foreach(var index in cells.Keys) foreach (var index in cells.Keys)
if (index.col == col && index.row > maxRow) if (index.col == col && index.row > maxRow)
maxRow = index.row; maxRow = index.row;
return maxRow+1; return maxRow + 1;
} }
public int GetRowLength(int row) public int GetRowLength(int row)
@@ -80,11 +82,11 @@ public class EasySaveSpreadsheet
private void SetCellString(int col, int row, string value) private void SetCellString(int col, int row, string value)
{ {
cells [new Index (col, row)] = value; cells[new Index(col, row)] = value;
// Expand the spreadsheet if necessary. // Expand the spreadsheet if necessary.
if(col >= cols) if (col >= cols)
cols = (col+1); cols = (col + 1);
if (row >= rows) if (row >= rows)
rows = (row + 1); rows = (row + 1);
} }
@@ -123,12 +125,12 @@ public class EasySaveSpreadsheet
public void Load(string filePath) public void Load(string filePath)
{ {
Load(new EasySaveSettings (filePath)); Load(new EasySaveSettings(filePath));
} }
public void Load(string filePath, EasySaveSettings settings) public void Load(string filePath, EasySaveSettings settings)
{ {
Load(new EasySaveSettings (filePath, settings)); Load(new EasySaveSettings(filePath, settings));
} }
public void Load(EasySaveSettings settings) public void Load(EasySaveSettings settings)
@@ -138,12 +140,12 @@ public class EasySaveSpreadsheet
public void LoadRaw(string str) public void LoadRaw(string str)
{ {
Load(new MemoryStream (((new EasySaveSettings ()).encoding).GetBytes(str)), new EasySaveSettings()); Load(new MemoryStream(((new EasySaveSettings()).encoding).GetBytes(str)), new EasySaveSettings());
} }
public void LoadRaw(string str, EasySaveSettings settings) public void LoadRaw(string str, EasySaveSettings settings)
{ {
Load(new MemoryStream ((settings.encoding).GetBytes(str)), settings); Load(new MemoryStream((settings.encoding).GetBytes(str)), settings);
} }
private void Load(Stream stream, EasySaveSettings settings) private void Load(Stream stream, EasySaveSettings settings)
@@ -157,20 +159,20 @@ public class EasySaveSpreadsheet
int row = 0; int row = 0;
// Read until the end of the stream. // Read until the end of the stream.
while(true) while (true)
{ {
c_int = reader.Read(); c_int = reader.Read();
c = (char)c_int; c = (char)c_int;
if(c == QUOTE_CHAR) if (c == QUOTE_CHAR)
{ {
while (true) while (true)
{ {
c = (char)reader.Read(); c = (char)reader.Read();
if(c == QUOTE_CHAR) if (c == QUOTE_CHAR)
{ {
// If this quote isn't escaped by another, it is the last quote, so we should stop parsing this value. // If this quote isn't escaped by another, it is the last quote, so we should stop parsing this value.
if(((char)reader.Peek()) != QUOTE_CHAR) if (((char)reader.Peek()) != QUOTE_CHAR)
break; break;
else else
c = (char)reader.Read(); c = (char)reader.Read();
@@ -179,13 +181,13 @@ public class EasySaveSpreadsheet
} }
} }
// If this is the end of a column, row, or the stream, add the value to the spreadsheet. // If this is the end of a column, row, or the stream, add the value to the spreadsheet.
else if(c == COMMA_CHAR || c == NEWLINE_CHAR || c_int == -1) else if (c == COMMA_CHAR || c == NEWLINE_CHAR || c_int == -1)
{ {
SetCell(col, row, value); SetCell(col, row, value);
value = ""; value = "";
if(c == COMMA_CHAR) if (c == COMMA_CHAR)
col++; col++;
else if(c == NEWLINE_CHAR) else if (c == NEWLINE_CHAR)
{ {
col = 0; col = 0;
row++; row++;
@@ -201,12 +203,12 @@ public class EasySaveSpreadsheet
public void Save(string filePath) public void Save(string filePath)
{ {
Save(new EasySaveSettings (filePath), false); Save(new EasySaveSettings(filePath), false);
} }
public void Save(string filePath, EasySaveSettings settings) public void Save(string filePath, EasySaveSettings settings)
{ {
Save(new EasySaveSettings (filePath, settings), false); Save(new EasySaveSettings(filePath, settings), false);
} }
public void Save(EasySaveSettings settings) public void Save(EasySaveSettings settings)
@@ -216,12 +218,12 @@ public class EasySaveSpreadsheet
public void Save(string filePath, bool append) public void Save(string filePath, bool append)
{ {
Save(new EasySaveSettings (filePath), append); Save(new EasySaveSettings(filePath), append);
} }
public void Save(string filePath, EasySaveSettings settings, bool append) public void Save(string filePath, EasySaveSettings settings, bool append)
{ {
Save(new EasySaveSettings (filePath, settings), append); Save(new EasySaveSettings(filePath, settings), append);
} }
public void Save(EasySaveSettings settings, bool append) public void Save(EasySaveSettings settings, bool append)
@@ -229,51 +231,51 @@ public class EasySaveSpreadsheet
using (var writer = new StreamWriter(EasySaveStream.CreateStream(settings, append ? EasySaveFileMode.Append : EasySaveFileMode.Write))) using (var writer = new StreamWriter(EasySaveStream.CreateStream(settings, append ? EasySaveFileMode.Append : EasySaveFileMode.Write)))
{ {
// If data already exists and we're appending, we need to prepend a newline. // If data already exists and we're appending, we need to prepend a newline.
if(append && EasySave.FileExists(settings)) if (append && EasySave.FileExists(settings))
writer.Write(NEWLINE_CHAR); writer.Write(NEWLINE_CHAR);
var array = ToArray(); var array = ToArray();
for(int row = 0; row < rows; row++) for (int row = 0; row < rows; row++)
{ {
if(row != 0) if (row != 0)
writer.Write(NEWLINE_CHAR); writer.Write(NEWLINE_CHAR);
for(int col = 0; col < cols; col++) for (int col = 0; col < cols; col++)
{ {
if(col != 0) if (col != 0)
writer.Write(COMMA_CHAR); writer.Write(COMMA_CHAR);
writer.Write( Escape(array [col, row]) ); writer.Write(Escape(array[col, row]));
} }
} }
} }
if(!append) if (!append)
EasySaveIO.CommitBackup(settings); EasySaveIO.CommitBackup(settings);
} }
private static string Escape(string str, bool isAlreadyWrappedInQuotes=false) private static string Escape(string str, bool isAlreadyWrappedInQuotes = false)
{ {
if (str == "") if (str == "")
return "\"\""; return "\"\"";
else if(str == null) else if (str == null)
return null; return null;
// Now escape any other quotes. // Now escape any other quotes.
if(str.Contains(QUOTE)) if (str.Contains(QUOTE))
str = str.Replace(QUOTE, ESCAPED_QUOTE); str = str.Replace(QUOTE, ESCAPED_QUOTE);
// If there's chars to escape, wrap the value in quotes. // If there's chars to escape, wrap the value in quotes.
if(str.IndexOfAny(CHARS_TO_ESCAPE) > -1) if (str.IndexOfAny(CHARS_TO_ESCAPE) > -1)
str = QUOTE + str + QUOTE; str = QUOTE + str + QUOTE;
return str; return str;
} }
private static string Unescape(string str) private static string Unescape(string str)
{ {
if(str.StartsWith(QUOTE) && str.EndsWith(QUOTE)) if (str.StartsWith(QUOTE) && str.EndsWith(QUOTE))
{ {
str = str.Substring(1, str.Length-2); str = str.Substring(1, str.Length - 2);
if(str.Contains(ESCAPED_QUOTE)) if (str.Contains(ESCAPED_QUOTE))
str = str.Replace(ESCAPED_QUOTE, QUOTE); str = str.Replace(ESCAPED_QUOTE, QUOTE);
} }
return str; return str;
@@ -283,7 +285,7 @@ public class EasySaveSpreadsheet
{ {
var array = new string[cols, rows]; var array = new string[cols, rows];
foreach (var cell in cells) foreach (var cell in cells)
array [cell.Key.col, cell.Key.row] = cell.Value; array[cell.Key.col, cell.Key.row] = cell.Value;
return array; return array;
} }
@@ -298,4 +300,5 @@ public class EasySaveSpreadsheet
this.row = row; this.row = row;
} }
} }
}
} }

View File

@@ -6,8 +6,10 @@ using System.ComponentModel;
using Convention.EasySave.Types; using Convention.EasySave.Types;
using Convention.EasySave.Internal; using Convention.EasySave.Internal;
public abstract class EasySaveReader : System.IDisposable namespace Convention.EasySave
{ {
public abstract class EasySaveReader : System.IDisposable
{
/// <summary>The settings used to create this reader.</summary> /// <summary>The settings used to create this reader.</summary>
public EasySaveSettings settings; public EasySaveSettings settings;
@@ -37,7 +39,7 @@ public abstract class EasySaveReader : System.IDisposable
protected abstract Type ReadKeyPrefix(bool ignore = false); protected abstract Type ReadKeyPrefix(bool ignore = false);
protected abstract void ReadKeySuffix(); protected abstract void ReadKeySuffix();
internal abstract byte[] ReadElement(bool skip=false); internal abstract byte[] ReadElement(bool skip = false);
/// <summary>Disposes of the reader and it's underlying stream.</summary> /// <summary>Disposes of the reader and it's underlying stream.</summary>
public abstract void Dispose(); public abstract void Dispose();
@@ -95,7 +97,7 @@ public abstract class EasySaveReader : System.IDisposable
{ {
get get
{ {
return new EasySaveReaderPropertyEnumerator (this); return new EasySaveReaderPropertyEnumerator(this);
} }
} }
@@ -103,7 +105,7 @@ public abstract class EasySaveReader : System.IDisposable
{ {
get get
{ {
return new EasySaveReaderRawEnumerator (this); return new EasySaveReaderRawEnumerator(this);
} }
} }
@@ -180,8 +182,8 @@ public abstract class EasySaveReader : System.IDisposable
public object SetPrivateField(string name, object value, object objectContainingField) public object SetPrivateField(string name, object value, object objectContainingField)
{ {
var field = EasySaveReflection.GetEasySaveReflectedMember(objectContainingField.GetType(), name); var field = EasySaveReflection.GetEasySaveReflectedMember(objectContainingField.GetType(), name);
if(field.IsNull) if (field.IsNull)
throw new MissingMemberException("A private field named "+ name + " does not exist in the type "+objectContainingField.GetType()); throw new MissingMemberException("A private field named " + name + " does not exist in the type " + objectContainingField.GetType());
field.SetValue(objectContainingField, value); field.SetValue(objectContainingField, value);
return objectContainingField; return objectContainingField;
} }
@@ -192,8 +194,8 @@ public abstract class EasySaveReader : System.IDisposable
/// <param name="key">The key which uniquely identifies our value.</param> /// <param name="key">The key which uniquely identifies our value.</param>
public virtual T Read<T>(string key) public virtual T Read<T>(string key)
{ {
if(!Goto(key)) if (!Goto(key))
throw new KeyNotFoundException("Key \"" + key + "\" was not found in file \""+settings.FullPath+"\". Use Load<T>(key, defaultValue) if you want to return a default value if the key does not exist."); throw new KeyNotFoundException("Key \"" + key + "\" was not found in file \"" + settings.FullPath + "\". Use Load<T>(key, defaultValue) if you want to return a default value if the key does not exist.");
Type type = ReadTypeFromHeader<T>(); Type type = ReadTypeFromHeader<T>();
@@ -208,7 +210,7 @@ public abstract class EasySaveReader : System.IDisposable
/// <param name="defaultValue">The value we want to return if this key does not exist in the reader.</param> /// <param name="defaultValue">The value we want to return if this key does not exist in the reader.</param>
public virtual T Read<T>(string key, T defaultValue) public virtual T Read<T>(string key, T defaultValue)
{ {
if(!Goto(key)) if (!Goto(key))
return defaultValue; return defaultValue;
Type type = ReadTypeFromHeader<T>(); Type type = ReadTypeFromHeader<T>();
@@ -223,8 +225,8 @@ public abstract class EasySaveReader : System.IDisposable
/// <param name="obj">The object we want to load the value into.</param> /// <param name="obj">The object we want to load the value into.</param>
public virtual void ReadInto<T>(string key, T obj) where T : class public virtual void ReadInto<T>(string key, T obj) where T : class
{ {
if(!Goto(key)) if (!Goto(key))
throw new KeyNotFoundException("Key \"" + key + "\" was not found in file \""+settings.FullPath+"\""); throw new KeyNotFoundException("Key \"" + key + "\" was not found in file \"" + settings.FullPath + "\"");
Type type = ReadTypeFromHeader<T>(); Type type = ReadTypeFromHeader<T>();
@@ -236,7 +238,7 @@ public abstract class EasySaveReader : System.IDisposable
protected virtual void ReadObject<T>(object obj, EasySaveType type) protected virtual void ReadObject<T>(object obj, EasySaveType type)
{ {
// Check for null. // Check for null.
if(StartReadObject()) if (StartReadObject())
return; return;
type.ReadInto<T>(this, obj); type.ReadInto<T>(this, obj);
@@ -246,7 +248,7 @@ public abstract class EasySaveReader : System.IDisposable
protected virtual T ReadObject<T>(EasySaveType type) protected virtual T ReadObject<T>(EasySaveType type)
{ {
if(StartReadObject()) if (StartReadObject())
return default(T); return default(T);
object obj = type.Read<T>(this); object obj = type.Read<T>(this);
@@ -284,12 +286,12 @@ public abstract class EasySaveReader : System.IDisposable
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public virtual void ReadInto<T>(object obj, EasySaveType type) public virtual void ReadInto<T>(object obj, EasySaveType type)
{ {
if(type == null || type.isUnsupported) if (type == null || type.isUnsupported)
throw new NotSupportedException("Type of "+obj.GetType()+" is not currently supported, and could not be loaded using reflection."); throw new NotSupportedException("Type of " + obj.GetType() + " is not currently supported, and could not be loaded using reflection.");
else if(type.isCollection) else if (type.isCollection)
((ECollectionType)type).ReadInto(this, obj); ((ECollectionType)type).ReadInto(this, obj);
else if(type.isDictionary) else if (type.isDictionary)
((EasySaveDictionaryType)type).ReadInto(this, obj); ((EasySaveDictionaryType)type).ReadInto(this, obj);
else else
ReadObject<T>(obj, type); ReadObject<T>(obj, type);
@@ -301,13 +303,13 @@ public abstract class EasySaveReader : System.IDisposable
internal Type ReadTypeFromHeader<T>() internal Type ReadTypeFromHeader<T>()
{ {
// Check whether we need to determine the type by reading the header. // Check whether we need to determine the type by reading the header.
if(typeof(T) == typeof(object)) if (typeof(T) == typeof(object))
return ReadKeyPrefix(); return ReadKeyPrefix();
else if(settings.typeChecking) else if (settings.typeChecking)
{ {
Type type = ReadKeyPrefix(); Type type = ReadKeyPrefix();
if(type != typeof(T)) if (type != typeof(T))
throw new InvalidOperationException("Trying to load data of type "+typeof(T)+", but data contained in file is type of "+type+"."); throw new InvalidOperationException("Trying to load data of type " + typeof(T) + ", but data contained in file is type of " + type + ".");
return type; return type;
} }
else else
@@ -343,7 +345,7 @@ public abstract class EasySaveReader : System.IDisposable
public static EasySaveReader Create(EasySaveSettings settings) public static EasySaveReader Create(EasySaveSettings settings)
{ {
Stream stream = EasySaveStream.CreateStream(settings, EasySaveFileMode.Read); Stream stream = EasySaveStream.CreateStream(settings, EasySaveFileMode.Read);
if(stream == null) if (stream == null)
return null; return null;
// Get the baseWriter using the given Stream. // Get the baseWriter using the given Stream.
@@ -363,11 +365,11 @@ public abstract class EasySaveReader : System.IDisposable
public static EasySaveReader Create(byte[] bytes, EasySaveSettings settings) public static EasySaveReader Create(byte[] bytes, EasySaveSettings settings)
{ {
Stream stream = EasySaveStream.CreateStream(new MemoryStream(bytes), settings, EasySaveFileMode.Read); Stream stream = EasySaveStream.CreateStream(new MemoryStream(bytes), settings, EasySaveFileMode.Read);
if(stream == null) if (stream == null)
return null; return null;
// Get the baseWriter using the given Stream. // Get the baseWriter using the given Stream.
if(settings.format == EasySave.Format.JSON) if (settings.format == EasySave.Format.JSON)
return new EasySaveJSONReader(stream, settings); return new EasySaveJSONReader(stream, settings);
return null; return null;
} }
@@ -377,7 +379,7 @@ public abstract class EasySaveReader : System.IDisposable
stream = EasySaveStream.CreateStream(stream, settings, EasySaveFileMode.Read); stream = EasySaveStream.CreateStream(stream, settings, EasySaveFileMode.Read);
// Get the baseWriter using the given Stream. // Get the baseWriter using the given Stream.
if(settings.format == EasySave.Format.JSON) if (settings.format == EasySave.Format.JSON)
return new EasySaveJSONReader(stream, settings); return new EasySaveJSONReader(stream, settings);
return null; return null;
} }
@@ -385,7 +387,7 @@ public abstract class EasySaveReader : System.IDisposable
internal static EasySaveReader Create(Stream stream, EasySaveSettings settings, bool readHeaderAndFooter) internal static EasySaveReader Create(Stream stream, EasySaveSettings settings, bool readHeaderAndFooter)
{ {
// Get the baseWriter using the given Stream. // Get the baseWriter using the given Stream.
if(settings.format == EasySave.Format.JSON) if (settings.format == EasySave.Format.JSON)
return new EasySaveJSONReader(stream, settings, readHeaderAndFooter); return new EasySaveJSONReader(stream, settings, readHeaderAndFooter);
return null; return null;
} }
@@ -403,10 +405,10 @@ public abstract class EasySaveReader : System.IDisposable
public IEnumerator GetEnumerator() public IEnumerator GetEnumerator()
{ {
string propertyName; string propertyName;
while(true) while (true)
{ {
// Allows us to repeat a property name or insert one of our own. // Allows us to repeat a property name or insert one of our own.
if(reader.overridePropertiesName != null) if (reader.overridePropertiesName != null)
{ {
string tempName = reader.overridePropertiesName; string tempName = reader.overridePropertiesName;
reader.overridePropertiesName = null; reader.overridePropertiesName = null;
@@ -414,7 +416,7 @@ public abstract class EasySaveReader : System.IDisposable
} }
else else
{ {
if((propertyName = reader.ReadPropertyName()) == null) if ((propertyName = reader.ReadPropertyName()) == null)
yield break; yield break;
yield return propertyName; yield return propertyName;
} }
@@ -434,10 +436,10 @@ public abstract class EasySaveReader : System.IDisposable
public IEnumerator GetEnumerator() public IEnumerator GetEnumerator()
{ {
while(true) while (true)
{ {
string key = reader.ReadPropertyName(); string key = reader.ReadPropertyName();
if(key == null) if (key == null)
yield break; yield break;
Type type = reader.ReadTypeFromHeader<object>(); Type type = reader.ReadTypeFromHeader<object>();
@@ -446,8 +448,9 @@ public abstract class EasySaveReader : System.IDisposable
reader.ReadKeySuffix(); reader.ReadKeySuffix();
if(type != null) if (type != null)
yield return new KeyValuePair<string,EasySaveData>(key, new EasySaveData(type, bytes)); yield return new KeyValuePair<string, EasySaveData>(key, new EasySaveData(type, bytes));
}
} }
} }
} }

View File

@@ -1,6 +1,10 @@
public class EasySaveDefaults using Convention.EasySave;
namespace Convention.EasySave
{ {
public EasySaveSerializableSettings settings = new EasySaveSerializableSettings(); public class EasySaveDefaults
{
public EasySaveSettings settings = new EasySaveSerializableSettings();
public bool addMgrToSceneAutomatically = false; public bool addMgrToSceneAutomatically = false;
public bool autoUpdateReferences = true; public bool autoUpdateReferences = true;
@@ -15,4 +19,5 @@
public bool logDebugInfo = false; public bool logDebugInfo = false;
public bool logWarnings = true; public bool logWarnings = true;
public bool logErrors = true; public bool logErrors = true;
}
} }

View File

@@ -1,7 +1,9 @@
using Convention.EasySave.Internal; using Convention.EasySave.Internal;
public class EasySaveSettings : System.ICloneable namespace Convention.EasySave
{ {
public class EasySaveSettings : System.ICloneable
{
#region Default settings #region Default settings
private static EasySaveSettings _defaults = null; private static EasySaveSettings _defaults = null;
@@ -14,35 +16,7 @@ public class EasySaveSettings : System.ICloneable
{ {
if (_defaultSettingsScriptableObject == null) if (_defaultSettingsScriptableObject == null)
{ {
_defaultSettingsScriptableObject = Resources.Load<EasySaveDefaults>(defaultSettingsPath); _defaultSettingsScriptableObject = new();
#if UNITY_EDITOR
if (_defaultSettingsScriptableObject == null)
{
_defaultSettingsScriptableObject = ScriptableObject.CreateInstance<ES3Defaults>();
// If this is the version being submitted to the Asset Store, don't include ES3Defaults.
if (Application.productName.Contains("EasySave Release"))
{
Debug.Log("This has been identified as a release build as the title contains 'EasySave Release', so ES3Defaults will not be created.");
return _defaultSettingsScriptableObject;
}
// Convert the old settings to the new settings if necessary.
var oldSettings = GetOldSettings();
if (oldSettings != null)
{
oldSettings.CopyInto(_defaultSettingsScriptableObject.settings);
// Only enable warning logs by default for new installs as this may look like unexpected behaviour to some.
_defaultSettingsScriptableObject.logWarnings = false;
RemoveOldSettings();
}
CreateDefaultSettingsFolder();
AssetDatabase.CreateAsset(_defaultSettingsScriptableObject, PathToDefaultSettings());
AssetDatabase.SaveAssets();
}
#endif
} }
return _defaultSettingsScriptableObject; return _defaultSettingsScriptableObject;
} }
@@ -52,9 +26,9 @@ public class EasySaveSettings : System.ICloneable
{ {
get get
{ {
if(_defaults == null) if (_defaults == null)
{ {
if(defaultSettingsScriptableObject != null) if (defaultSettingsScriptableObject != null)
_defaults = defaultSettingsScriptableObject.settings; _defaults = defaultSettingsScriptableObject.settings;
} }
return _defaults; return _defaults;
@@ -76,20 +50,17 @@ public class EasySaveSettings : System.ICloneable
#region Fields #region Fields
private static readonly string[] resourcesExtensions = new string[]{".txt", ".htm", ".html", ".xml", ".bytes", ".json", ".csv", ".yaml", ".fnt" }; private static readonly string[] resourcesExtensions = new string[] { ".txt", ".htm", ".html", ".xml", ".bytes", ".json", ".csv", ".yaml", ".fnt" };
[SerializeField]
private EasySave.Location _location; private EasySave.Location _location;
/// <summary>The location where we wish to store data. As it's not possible to save/load from File in WebGL, if the default location is File it will use PlayerPrefs instead.</summary> /// <summary>The location where we wish to store data. As it's not possible to save/load from File in WebGL, if the default location is File it will use PlayerPrefs instead.</summary>
public EasySave.Location location public EasySave.Location location
{ {
get get
{ {
if(_location == EasySave.Location.File && (Application.platform == RuntimePlatform.WebGLPlayer || Application.platform == RuntimePlatform.tvOS))
return EasySave.Location.PlayerPrefs;
return _location; return _location;
} }
set{ _location = value; } set { _location = value; }
} }
/// <summary>The path associated with this EasySaveSettings object, if any.</summary> /// <summary>The path associated with this EasySaveSettings object, if any.</summary>
@@ -135,7 +106,7 @@ public class EasySaveSettings : System.ICloneable
/// <summary>The names of the Assemblies we should try to load our Convention.EasySave.Types from.</summary> /// <summary>The names of the Assemblies we should try to load our Convention.EasySave.Types from.</summary>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public string[] assemblyNames = new string[] { "Assembly-CSharp-firstpass", "Assembly-CSharp"}; public string[] assemblyNames = new string[] { "Assembly-CSharp-firstpass", "Assembly-CSharp" };
/// <summary>Gets the full, absolute path which this EasySaveSettings object identifies.</summary> /// <summary>Gets the full, absolute path which this EasySaveSettings object identifies.</summary>
public string FullPath public string FullPath
@@ -145,37 +116,16 @@ public class EasySaveSettings : System.ICloneable
if (path == null) if (path == null)
throw new System.NullReferenceException("The 'path' field of this EasySaveSettings is null, indicating that it was not possible to load the default settings from Resources. Please check that the EasySave Default Settings.prefab exists in Assets/Plugins/Resources/EasySave/"); throw new System.NullReferenceException("The 'path' field of this EasySaveSettings is null, indicating that it was not possible to load the default settings from Resources. Please check that the EasySave Default Settings.prefab exists in Assets/Plugins/Resources/EasySave/");
if(IsAbsolute(path)) if (IsAbsolute(path))
return path; return path;
if(location == EasySave.Location.File) if (location == EasySave.Location.File)
{ {
if(directory == EasySave.Directory.PersistentDataPath) if (directory == EasySave.Directory.PersistentDataPath)
return EasySaveIO.persistentDataPath + "/" + path; return EasySaveIO.persistentDataPath + "/" + path;
if(directory == EasySave.Directory.DataPath) if (directory == EasySave.Directory.DataPath)
return Application.dataPath + "/" + path; return PlatformIndicator.DataPath + "/" + path;
throw new System.NotImplementedException("File directory \""+directory+"\" has not been implemented."); throw new System.NotImplementedException("File directory \"" + directory + "\" has not been implemented.");
}
if(location == EasySave.Location.Resources)
{
// Check that it has valid extension
var extension = System.IO.Path.GetExtension(path);
bool hasValidExtension = false;
foreach (var ext in resourcesExtensions)
{
if (extension == ext)
{
hasValidExtension = true;
break;
}
}
if(!hasValidExtension)
throw new System.ArgumentException("Extension of file in Resources must be .json, .bytes, .txt, .csv, .htm, .html, .xml, .yaml or .fnt, but path given was \"" + path + "\"");
// Remove extension
string resourcesPath = path.Replace(extension, "");
return resourcesPath;
} }
return path; return path;
} }
@@ -356,18 +306,19 @@ public class EasySaveSettings : System.ICloneable
} }
#endregion #endregion
} }
/* /*
* A serializable version of the settings we can use as a field in the Editor, which doesn't automatically * A serializable version of the settings we can use as a field in the Editor, which doesn't automatically
* assign defaults to itself, so we get no serialization errors. * assign defaults to itself, so we get no serialization errors.
*/ */
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[System.Serializable] [System.Serializable]
public class EasySaveSerializableSettings : EasySaveSettings public class EasySaveSerializableSettings : EasySaveSettings
{ {
public EasySaveSerializableSettings() : base(false){} public EasySaveSerializableSettings() : base(false) { }
public EasySaveSerializableSettings(bool applyDefaults) : base(applyDefaults){} public EasySaveSerializableSettings(bool applyDefaults) : base(applyDefaults) { }
public EasySaveSerializableSettings(string path) : base(false) { this.path = path; } public EasySaveSerializableSettings(string path) : base(false) { this.path = path; }
public EasySaveSerializableSettings(string path, EasySave.Location location) : base(false) { this.location = location; } public EasySaveSerializableSettings(string path, EasySave.Location location) : base(false) { this.location = location; }
}
} }

View File

@@ -32,7 +32,7 @@ namespace Convention.EasySave.Internal
return CreateStream(stream, settings, fileMode); return CreateStream(stream, settings, fileMode);
} }
catch(System.Exception e) catch(Exception)
{ {
if (stream != null) if (stream != null)
stream.Dispose(); stream.Dispose();

View File

@@ -60,9 +60,6 @@ namespace Convention.EasySave.Types
{ {
var collection = (IList)obj; var collection = (IList)obj;
if (collection.Count == 0)
ES3Debug.LogWarning("LoadInto/ReadInto expects a collection containing instances to load data in to, but the collection is empty.");
if(reader.StartReadCollection()) if(reader.StartReadCollection())
throw new NullReferenceException("The Collection we are trying to load is stored as null, which is not allowed when using ReadInto methods."); throw new NullReferenceException("The Collection we are trying to load is stored as null, which is not allowed when using ReadInto methods.");

View File

@@ -32,7 +32,7 @@ namespace Convention.EasySave.Types
{ {
var array = ReadAsArray(reader); var array = ReadAsArray(reader);
return EasySaveReflection.CreateInstance(type, new object[] { array, Allocator.Persistent }); return EasySaveReflection.CreateInstance(type, new object[] { array/*, Allocator.Persistent*/ });
} }
public override object Read<T>(EasySaveReader reader) public override object Read<T>(EasySaveReader reader)

View File

@@ -19,7 +19,6 @@ namespace Convention.EasySave.Types
public bool isDictionary = false; public bool isDictionary = false;
public bool isTuple = false; public bool isTuple = false;
public bool isEnum = false; public bool isEnum = false;
public bool isES3TypeUnityObject = false;
public bool isReflectedType = false; public bool isReflectedType = false;
public bool isUnsupported = false; public bool isUnsupported = false;
public int priority = 0; public int priority = 0;

View File

@@ -88,8 +88,6 @@ namespace Convention.EasySave.Internal
es3Type = new EasySaveStackType(type); es3Type = new EasySaveStackType(type);
else if (genericType == typeof(HashSet<>)) else if (genericType == typeof(HashSet<>))
es3Type = new EasySaveHashSetType(type); es3Type = new EasySaveHashSetType(type);
else if (genericType == typeof(Unity.Collections.NativeArray<>))
es3Type = new EasySaveNativeArrayType(type);
else if (throwException) else if (throwException)
throw new NotSupportedException("Generic type \"" + type.ToString() + "\" is not supported by Easy Save."); throw new NotSupportedException("Generic type \"" + type.ToString() + "\" is not supported by Easy Save.");
else else
@@ -104,20 +102,8 @@ namespace Convention.EasySave.Internal
} }
else else
{ {
if (EasySaveReflection.IsAssignableFrom(typeof(Component), type)) if (type.Name.StartsWith("Tuple`"))
es3Type = new ES3ReflectedComponentType(type);
else if (EasySaveReflection.IsValueType(type))
es3Type = new EasySaveReflectedValueType(type);
else if (EasySaveReflection.IsAssignableFrom(typeof(ScriptableObject), type))
es3Type = new ES3ReflectedScriptableObjectType(type);
else if (EasySaveReflection.IsAssignableFrom(typeof(UnityEngine.Object), type))
es3Type = new ES3ReflectedUnityObjectType(type);
/*else if (EasySaveReflection.HasParameterlessConstructor(type) || EasySaveReflection.IsAbstract(type) || EasySaveReflection.IsInterface(type))
es3Type = new EasySaveReflectedObjectType(type);*/
else if (type.Name.StartsWith("Tuple`"))
es3Type = new EasySaveTupleType(type); es3Type = new EasySaveTupleType(type);
/*else if (throwException)
throw new NotSupportedException("Type of " + type + " is not supported as it does not have a parameterless constructor. Only value types, Components or ScriptableObjects are supportable without a parameterless constructor. However, you may be able to create an EasySaveType script to add support for it.");*/
else else
es3Type = new EasySaveReflectedObjectType(type); es3Type = new EasySaveReflectedObjectType(type);
} }

View File

@@ -5,8 +5,10 @@ using System;
using Convention.EasySave.Types; using Convention.EasySave.Types;
using Convention.EasySave.Internal; using Convention.EasySave.Internal;
public abstract class EasySaveWriter : IDisposable namespace Convention.EasySave
{ {
public abstract class EasySaveWriter : IDisposable
{
public EasySaveSettings settings; public EasySaveSettings settings;
protected HashSet<string> keysToDelete = new HashSet<string>(); protected HashSet<string> keysToDelete = new HashSet<string>();
@@ -121,7 +123,7 @@ public abstract class EasySaveWriter : IDisposable
/// <param name="value">The value we want to write.</param> /// <param name="value">The value we want to write.</param>
public virtual void Write<T>(string key, object value) public virtual void Write<T>(string key, object value)
{ {
if(typeof(T) == typeof(object)) if (typeof(T) == typeof(object))
Write(value.GetType(), key, value); Write(value.GetType(), key, value);
else else
Write(typeof(T), key, value); Write(typeof(T), key, value);
@@ -153,7 +155,7 @@ public abstract class EasySaveWriter : IDisposable
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public virtual void Write(object value, EasySave.ReferenceMode memberReferenceMode = EasySave.ReferenceMode.ByRef) public virtual void Write(object value, EasySave.ReferenceMode memberReferenceMode = EasySave.ReferenceMode.ByRef)
{ {
if(value == null){ WriteNull(); return; } if (value == null) { WriteNull(); return; }
var type = EasySaveTypeMgr.GetOrCreateEasySaveType(value.GetType()); var type = EasySaveTypeMgr.GetOrCreateEasySaveType(value.GetType());
Write(value, type, memberReferenceMode); Write(value, type, memberReferenceMode);
@@ -176,7 +178,7 @@ public abstract class EasySaveWriter : IDisposable
var valueType = value.GetType(); var valueType = value.GetType();
type = EasySaveTypeMgr.GetOrCreateEasySaveType(valueType); type = EasySaveTypeMgr.GetOrCreateEasySaveType(valueType);
if(type == null) if (type == null)
throw new NotSupportedException("Types of " + valueType + " are not supported. Please see the Supported Types guide for more information: https://docs.moodkie.com/easy-save-3/es3-supported-types/"); throw new NotSupportedException("Types of " + valueType + " are not supported. Please see the Supported Types guide for more information: https://docs.moodkie.com/easy-save-3/es3-supported-types/");
if (!type.isCollection && !type.isDictionary) if (!type.isCollection && !type.isDictionary)
@@ -191,11 +193,11 @@ public abstract class EasySaveWriter : IDisposable
} }
} }
if(type == null) if (type == null)
throw new ArgumentNullException("EasySaveType argument cannot be null."); throw new ArgumentNullException("EasySaveType argument cannot be null.");
if (type.isUnsupported) if (type.isUnsupported)
{ {
if(type.isCollection || type.isDictionary) if (type.isCollection || type.isDictionary)
throw new NotSupportedException(type.type + " is not supported because it's element type is not supported. Please see the Supported Types guide for more information: https://docs.moodkie.com/easy-save-3/es3-supported-types/"); throw new NotSupportedException(type.type + " is not supported because it's element type is not supported. Please see the Supported Types guide for more information: https://docs.moodkie.com/easy-save-3/es3-supported-types/");
else else
throw new NotSupportedException("Types of " + type.type + " are not supported. Please see the Supported Types guide for more information: https://docs.moodkie.com/easy-save-3/es3-supported-types/"); throw new NotSupportedException("Types of " + type.type + " are not supported. Please see the Supported Types guide for more information: https://docs.moodkie.com/easy-save-3/es3-supported-types/");
@@ -217,17 +219,9 @@ public abstract class EasySaveWriter : IDisposable
} }
else else
{ {
throw new NotImplementedException(); StartWriteObject(null);
//if (type.type == typeof(GameObject)) type.Write(value, this);
// ((ES3Type_GameObject)type).saveChildren = settings.saveChildren; EndWriteObject(null);
//StartWriteObject(null);
//if (type.isES3TypeUnityObject)
// ((ES3UnityObjectType)type).WriteObject(value, this, memberReferenceMode);
//else
// type.Write(value, this);
//EndWriteObject(null);
} }
} }
@@ -287,8 +281,8 @@ public abstract class EasySaveWriter : IDisposable
public void WritePrivateProperty(string name, object objectContainingProperty) public void WritePrivateProperty(string name, object objectContainingProperty)
{ {
var property = EasySaveReflection.GetEasySaveReflectedProperty(objectContainingProperty.GetType(), name); var property = EasySaveReflection.GetEasySaveReflectedProperty(objectContainingProperty.GetType(), name);
if(property.IsNull) if (property.IsNull)
throw new MissingMemberException("A private property named "+ name + " does not exist in the type "+objectContainingProperty.GetType()); throw new MissingMemberException("A private property named " + name + " does not exist in the type " + objectContainingProperty.GetType());
WriteProperty(name, property.GetValue(objectContainingProperty), EasySaveTypeMgr.GetOrCreateEasySaveType(property.MemberType)); WriteProperty(name, property.GetValue(objectContainingProperty), EasySaveTypeMgr.GetOrCreateEasySaveType(property.MemberType));
} }
@@ -298,17 +292,17 @@ public abstract class EasySaveWriter : IDisposable
public void WritePrivateField(string name, object objectContainingField) public void WritePrivateField(string name, object objectContainingField)
{ {
var field = EasySaveReflection.GetEasySaveReflectedMember(objectContainingField.GetType(), name); var field = EasySaveReflection.GetEasySaveReflectedMember(objectContainingField.GetType(), name);
if(field.IsNull) if (field.IsNull)
throw new MissingMemberException("A private field named "+ name + " does not exist in the type "+objectContainingField.GetType()); throw new MissingMemberException("A private field named " + name + " does not exist in the type " + objectContainingField.GetType());
WriteProperty(name,field.GetValue(objectContainingField), EasySaveTypeMgr.GetOrCreateEasySaveType(field.MemberType)); WriteProperty(name, field.GetValue(objectContainingField), EasySaveTypeMgr.GetOrCreateEasySaveType(field.MemberType));
} }
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public void WritePrivateProperty(string name, object objectContainingProperty, EasySaveType type) public void WritePrivateProperty(string name, object objectContainingProperty, EasySaveType type)
{ {
var property = EasySaveReflection.GetEasySaveReflectedProperty(objectContainingProperty.GetType(), name); var property = EasySaveReflection.GetEasySaveReflectedProperty(objectContainingProperty.GetType(), name);
if(property.IsNull) if (property.IsNull)
throw new MissingMemberException("A private property named "+ name + " does not exist in the type "+objectContainingProperty.GetType()); throw new MissingMemberException("A private property named " + name + " does not exist in the type " + objectContainingProperty.GetType());
WriteProperty(name, property.GetValue(objectContainingProperty), type); WriteProperty(name, property.GetValue(objectContainingProperty), type);
} }
@@ -316,9 +310,9 @@ public abstract class EasySaveWriter : IDisposable
public void WritePrivateField(string name, object objectContainingField, EasySaveType type) public void WritePrivateField(string name, object objectContainingField, EasySaveType type)
{ {
var field = EasySaveReflection.GetEasySaveReflectedMember(objectContainingField.GetType(), name); var field = EasySaveReflection.GetEasySaveReflectedMember(objectContainingField.GetType(), name);
if(field.IsNull) if (field.IsNull)
throw new MissingMemberException("A private field named "+ name + " does not exist in the type "+objectContainingField.GetType()); throw new MissingMemberException("A private field named " + name + " does not exist in the type " + objectContainingField.GetType());
WriteProperty(name,field.GetValue(objectContainingField), type); WriteProperty(name, field.GetValue(objectContainingField), type);
} }
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
@@ -350,7 +344,7 @@ public abstract class EasySaveWriter : IDisposable
internal static EasySaveWriter Create(EasySaveSettings settings, bool writeHeaderAndFooter, bool overwriteKeys, bool append) internal static EasySaveWriter Create(EasySaveSettings settings, bool writeHeaderAndFooter, bool overwriteKeys, bool append)
{ {
var stream = EasySaveStream.CreateStream(settings, (append ? EasySaveFileMode.Append : EasySaveFileMode.Write)); var stream = EasySaveStream.CreateStream(settings, (append ? EasySaveFileMode.Append : EasySaveFileMode.Write));
if(stream == null) if (stream == null)
return null; return null;
return Create(stream, settings, writeHeaderAndFooter, overwriteKeys); return Create(stream, settings, writeHeaderAndFooter, overwriteKeys);
} }
@@ -359,14 +353,14 @@ public abstract class EasySaveWriter : IDisposable
internal static EasySaveWriter Create(Stream stream, EasySaveSettings settings, bool writeHeaderAndFooter, bool overwriteKeys) internal static EasySaveWriter Create(Stream stream, EasySaveSettings settings, bool writeHeaderAndFooter, bool overwriteKeys)
{ {
if(stream.GetType() == typeof(MemoryStream)) if (stream.GetType() == typeof(MemoryStream))
{ {
settings = (EasySaveSettings)settings.Clone(); settings = (EasySaveSettings)settings.Clone();
settings.location = EasySave.Location.InternalMS; settings.location = EasySave.Location.InternalMS;
} }
// Get the baseWriter using the given Stream. // Get the baseWriter using the given Stream.
if(settings.format == EasySave.Format.JSON) if (settings.format == EasySave.Format.JSON)
return new EasySaveJSONWriter(stream, settings, writeHeaderAndFooter, overwriteKeys); return new EasySaveJSONWriter(stream, settings, writeHeaderAndFooter, overwriteKeys);
else else
return null; return null;
@@ -404,9 +398,9 @@ public abstract class EasySaveWriter : IDisposable
*/ */
protected void Merge() protected void Merge()
{ {
using(var reader = EasySaveReader.Create(settings)) using (var reader = EasySaveReader.Create(settings))
{ {
if(reader == null) if (reader == null)
return; return;
Merge(reader); Merge(reader);
} }
@@ -418,8 +412,8 @@ public abstract class EasySaveWriter : IDisposable
*/ */
protected void Merge(EasySaveReader reader) protected void Merge(EasySaveReader reader)
{ {
foreach(KeyValuePair<string,EasySaveData> kvp in reader.RawEnumerator) foreach (KeyValuePair<string, EasySaveData> kvp in reader.RawEnumerator)
if(!keysToDelete.Contains(kvp.Key) || kvp.Value.type == null) // Don't add keys whose data is of a type which no longer exists in the project. if (!keysToDelete.Contains(kvp.Key) || kvp.Value.type == null) // Don't add keys whose data is of a type which no longer exists in the project.
Write(kvp.Key, kvp.Value.type.type, kvp.Value.bytes); Write(kvp.Key, kvp.Value.type.type, kvp.Value.bytes);
} }
@@ -433,14 +427,15 @@ public abstract class EasySaveWriter : IDisposable
/// <param name="overwriteKeys">Whether we should overwrite existing keys.</param> /// <param name="overwriteKeys">Whether we should overwrite existing keys.</param>
public virtual void Save(bool overwriteKeys) public virtual void Save(bool overwriteKeys)
{ {
if(overwriteKeys) if (overwriteKeys)
Merge(); Merge();
EndWriteFile(); EndWriteFile();
Dispose(); Dispose();
// If we're writing to a location which can become corrupted, rename the backup file to the file we want. // If we're writing to a location which can become corrupted, rename the backup file to the file we want.
// This prevents corrupt data. // This prevents corrupt data.
if(settings.location == EasySave.Location.File) if (settings.location == EasySave.Location.File)
EasySaveIO.CommitBackup(settings); EasySaveIO.CommitBackup(settings);
} }
}
} }

View File

@@ -1,7 +1,9 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Threading; using System.Threading;
using Convention; using Convention;
using Convention.EasySave;
public class Program public class Program
{ {
@@ -17,6 +19,8 @@ public class Program
static void Main(string[] args) static void Main(string[] args)
{ {
Directory.CreateDirectory(PlatformIndicator.PersistentDataPath);
Console.WriteLine(PlatformIndicator.PersistentDataPath);
EasySave.Save("key", new Vector2X2() EasySave.Save("key", new Vector2X2()
{ {
x = 10, x = 10,