Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support NSCoding #62

Merged
merged 2 commits into from
Oct 8, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
format_code:
python Script/formatCode.py
15 changes: 15 additions & 0 deletions Script/formatCode.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import os.path
path = os.getcwd()

for root, dirs, files in os.walk(path):
if root.endswith("/aes") or root.endswith("/openssl"):
continue
for name in files:
if (name.endswith(".h") or name.endswith(".m") or name.endswith(".mm") or name.endswith(".hpp") or name.endswith(".cpp")):
localpath = root + '/' + name
print localpath
os.system("clang-format -i %s -style=File" %(localpath))
4 changes: 2 additions & 2 deletions iOS/MMKV/MMKV/MMKV.h
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ NS_ASSUME_NONNULL_BEGIN
- (BOOL)reKey:(nullable NSData *)newKey NS_SWIFT_NAME(reset(cryptKey:));
- (nullable NSData *)cryptKey;

// object: NSString/NSData/NSDate
// object: NSString/NSData/NSDate/id<NSCoding>
- (BOOL)setObject:(id)object forKey:(NSString *)key NS_SWIFT_NAME(set(_:forKey:));

- (BOOL)setBool:(BOOL)value forKey:(NSString *)key NS_SWIFT_NAME(set(_:forKey:));
Expand Down Expand Up @@ -72,7 +72,7 @@ NS_ASSUME_NONNULL_BEGIN

- (uint64_t)getUInt64ForKey:(NSString *)key NS_SWIFT_NAME(uint64(forKey:));
- (uint64_t)getUInt64ForKey:(NSString *)key defaultValue:(uint64_t)defaultValue NS_SWIFT_NAME(uint64(forKey:defaultValue:));

- (float)getFloatForKey:(NSString *)key NS_SWIFT_NAME(float(forKey:));
- (float)getFloatForKey:(NSString *)key defaultValue:(float)defaultValue NS_SWIFT_NAME(float(forKey:defaultValue:));

Expand Down
82 changes: 49 additions & 33 deletions iOS/MMKV/MMKV/MMKV.mm
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
static NSRecursiveLock *g_instanceLock;

#define DEFAULT_MMAP_ID @"mmkv.default"
#define CRC_FILE_SIZE 4
#define CRC_FILE_SIZE 4

@implementation MMKV {
NSRecursiveLock *m_lock;
Expand Down Expand Up @@ -387,35 +387,35 @@ - (void)clearMemoryCache {
}

- (BOOL)protectFromBackgroundWritting:(size_t)size writeBlock:(void (^)(MiniCodedOutputData *output))block {
m_isInBackground = YES;
if (m_isInBackground) {
static const int offset = pbFixed32Size(0);
static const int pagesize = getpagesize();
size_t realOffset = offset + m_actualSize - size;
size_t pageOffset = (realOffset / pagesize) * pagesize;
size_t pointerOffset = realOffset - pageOffset;
size_t mmapSize = offset + m_actualSize - pageOffset;
char *ptr = m_ptr + pageOffset;
if (mlock(ptr, mmapSize) != 0) {
MMKVError(@"fail to mlock [%@], %s", m_mmapID, strerror(errno));
// just fail on this condition, otherwise app will crash anyway
//block(m_output);
return NO;
} else {
@try {
MiniCodedOutputData output(ptr + pointerOffset, size);
block(&output);
m_output->seek(size);
} @catch (NSException *exception) {
MMKVError(@"%@", exception);
return NO;
} @finally {
munlock(ptr, mmapSize);
}
}
} else {
block(m_output);
}
m_isInBackground = YES;
if (m_isInBackground) {
static const int offset = pbFixed32Size(0);
static const int pagesize = getpagesize();
size_t realOffset = offset + m_actualSize - size;
size_t pageOffset = (realOffset / pagesize) * pagesize;
size_t pointerOffset = realOffset - pageOffset;
size_t mmapSize = offset + m_actualSize - pageOffset;
char *ptr = m_ptr + pageOffset;
if (mlock(ptr, mmapSize) != 0) {
MMKVError(@"fail to mlock [%@], %s", m_mmapID, strerror(errno));
// just fail on this condition, otherwise app will crash anyway
//block(m_output);
return NO;
} else {
@try {
MiniCodedOutputData output(ptr + pointerOffset, size);
block(&output);
m_output->seek(size);
} @catch (NSException *exception) {
MMKVError(@"%@", exception);
return NO;
} @finally {
munlock(ptr, mmapSize);
}
}
} else {
block(m_output);
}

return YES;
}
Expand Down Expand Up @@ -543,7 +543,7 @@ - (BOOL)setData:(NSData *)data forKey:(NSString *)key {
- (BOOL)appendData:(NSData *)data forKey:(NSString *)key {
size_t keyLength = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
size_t size = keyLength + pbRawVarint32Size((int32_t) keyLength); // size needed to encode the key
size += data.length + pbRawVarint32Size((int32_t) data.length); // size needed to encode the value
size += data.length + pbRawVarint32Size((int32_t) data.length); // size needed to encode the value

BOOL hasEnoughSize = [self ensureMemorySize:size];
if (hasEnoughSize == NO || [self isFileValid] == NO) {
Expand Down Expand Up @@ -809,7 +809,16 @@ - (BOOL)setObject:(id)object forKey:(NSString *)key {
if (object == nil || key.length <= 0) {
return NO;
}
NSData *data = [MiniPBCoder encodeDataWithObject:object];

NSData *data;
if ([MiniPBCoder isMiniPBCoderCompatibleObject:object]) {
data = [MiniPBCoder encodeDataWithObject:object];
} else {
if ([[object class] conformsToProtocol:@protocol(NSCoding)]) {
data = [NSKeyedArchiver archivedDataWithRootObject:object];
}
}

return [self setData:data forKey:key];
}

Expand Down Expand Up @@ -903,7 +912,14 @@ - (id)getObjectOfClass:(Class)cls forKey:(NSString *)key {
}
NSData *data = [self getDataForKey:key];
if (data.length > 0) {
return [MiniPBCoder decodeObjectOfClass:cls fromData:data];

if ([MiniPBCoder isMiniPBCoderCompatibleType:cls]) {
return [MiniPBCoder decodeObjectOfClass:cls fromData:data];
} else {
if ([cls conformsToProtocol:@protocol(NSCoding)]) {
return [NSKeyedUnarchiver unarchiveObjectWithData:data];
}
}
}
return nil;
}
Expand Down
74 changes: 37 additions & 37 deletions iOS/MMKV/MMKV/MemoryFile.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,52 +27,52 @@
extern const int DEFAULT_MMAP_SIZE;

class MemoryFile {
NSString *m_name;
int m_fd;
size_t m_size;

struct Segment {
uint8_t *ptr;
size_t size;
size_t offset;

Segment(void *source, size_t size, size_t offset) noexcept;
Segment(Segment &&other) noexcept;
~Segment();

private:
// just forbid it for possibly misuse
Segment(const Segment &other) = delete;
Segment &operator=(const Segment &other) = delete;
};
std::shared_ptr<Segment> m_ptr;
uint32_t offset2index(size_t offset) const;
// index -> segment
LRUCache<uint32_t, std::shared_ptr<Segment>> m_segmentCache;
std::shared_ptr<Segment> tryGetSegment(uint32_t index);
void prepareSegments();

// just forbid it for possibly misuse
MemoryFile(const MemoryFile &other) = delete;
MemoryFile &operator=(const MemoryFile &other) = delete;
NSString *m_name;
int m_fd;
size_t m_size;

struct Segment {
uint8_t *ptr;
size_t size;
size_t offset;

Segment(void *source, size_t size, size_t offset) noexcept;
Segment(Segment &&other) noexcept;
~Segment();

private:
// just forbid it for possibly misuse
Segment(const Segment &other) = delete;
Segment &operator=(const Segment &other) = delete;
};
std::shared_ptr<Segment> m_ptr;
uint32_t offset2index(size_t offset) const;
// index -> segment
LRUCache<uint32_t, std::shared_ptr<Segment>> m_segmentCache;
std::shared_ptr<Segment> tryGetSegment(uint32_t index);
void prepareSegments();

// just forbid it for possibly misuse
MemoryFile(const MemoryFile &other) = delete;
MemoryFile &operator=(const MemoryFile &other) = delete;

public:
MemoryFile(NSString *path);
~MemoryFile();
MemoryFile(NSString *path);
~MemoryFile();

size_t getFileSize() { return m_size; }
size_t getFileSize() { return m_size; }

NSString *getName() { return m_name; }
NSString *getName() { return m_name; }

int getFd() { return m_fd; }
int getFd() { return m_fd; }

NSData *read(size_t offset, size_t size);
NSData *read(size_t offset, size_t size);

bool write(size_t offset, const void *source, size_t size);
bool write(size_t offset, const void *source, size_t size);

bool innerMemcpy(size_t targetOffset, size_t sourceOffset, size_t size);
bool innerMemcpy(size_t targetOffset, size_t sourceOffset, size_t size);

bool ftruncate(size_t size);
bool ftruncate(size_t size);
};

extern bool isFileExist(NSString *nsFilePath);
Expand Down
42 changes: 21 additions & 21 deletions iOS/MMKV/MMKV/MiniCodedInputData.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,46 +23,46 @@
#import <Foundation/Foundation.h>

class MiniCodedInputData {
uint8_t *m_ptr;
int32_t m_size;
int32_t m_position;
uint8_t *m_ptr;
int32_t m_size;
int32_t m_position;

int8_t readRawByte();
int8_t readRawByte();

int32_t readRawVarint32();
int32_t readRawVarint32();

int64_t readRawVarint64();
int64_t readRawVarint64();

int32_t readRawLittleEndian32();
int32_t readRawLittleEndian32();

int64_t readRawLittleEndian64();
int64_t readRawLittleEndian64();

public:
MiniCodedInputData(NSData *oData);
MiniCodedInputData(NSData *oData);

~MiniCodedInputData();
~MiniCodedInputData();

bool isAtEnd() { return m_position == m_size; };
bool isAtEnd() { return m_position == m_size; };

BOOL readBool();
BOOL readBool();

Float64 readDouble();
Float64 readDouble();

Float32 readFloat();
Float32 readFloat();

uint64_t readUInt64();
uint64_t readUInt64();

uint32_t readUInt32();
uint32_t readUInt32();

int64_t readInt64();
int64_t readInt64();

int32_t readInt32();
int32_t readInt32();

int32_t readFixed32();
int32_t readFixed32();

NSString *readString();
NSString *readString();

NSData *readData();
NSData *readData();
};

#endif
50 changes: 25 additions & 25 deletions iOS/MMKV/MMKV/MiniCodedOutputData.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,54 +23,54 @@
#import <Foundation/Foundation.h>

class MiniCodedOutputData {
uint8_t *m_ptr;
size_t m_size;
int32_t m_position;
uint8_t *m_ptr;
size_t m_size;
int32_t m_position;

void writeRawByte(uint8_t value);
void writeRawByte(uint8_t value);

void writeRawLittleEndian32(int32_t value);
void writeRawLittleEndian32(int32_t value);

void writeRawLittleEndian64(int64_t value);
void writeRawLittleEndian64(int64_t value);

void writeRawVarint64(int64_t value);
void writeRawVarint64(int64_t value);

void writeRawData(NSData *data, int32_t offset, int32_t length);
void writeRawData(NSData *data, int32_t offset, int32_t length);

public:
MiniCodedOutputData(void *ptr, size_t len);
MiniCodedOutputData(void *ptr, size_t len);

MiniCodedOutputData(NSMutableData *odata);
MiniCodedOutputData(NSMutableData *odata);

~MiniCodedOutputData();
~MiniCodedOutputData();

int32_t spaceLeft();
int32_t spaceLeft();

void seek(size_t addedSize);
void seek(size_t addedSize);

void writeBool(BOOL value);
void writeBool(BOOL value);

void writeRawVarint32(int32_t value);
void writeRawVarint32(int32_t value);

void writeInt32(int32_t value);
void writeInt32(int32_t value);

void writeInt64(int64_t value);
void writeInt64(int64_t value);

void writeFloat(Float32 value);
void writeFloat(Float32 value);

void writeUInt32(uint32_t value);
void writeUInt32(uint32_t value);

void writeUInt64(uint64_t value);
void writeUInt64(uint64_t value);

void writeFixed32(int32_t value);
void writeFixed32(int32_t value);

void writeDouble(Float64 value);
void writeDouble(Float64 value);

void writeString(NSString *value);
void writeString(NSString *value);

void writeRawData(NSData *data);
void writeRawData(NSData *data);

void writeData(NSData *value);
void writeData(NSData *value);
};

#endif
Loading