Copy a portion of an input stream into a MemoryBlock


#1

I’ve written a small binary serialization utility, and at one point I want to create an isolated InputStream from a segment of a parent InputStream, so that implementing classes can’t access any data they’re not supposed to.

After struggling to get this to work with juce’s MemoryBlock and MemoryInputStream, this is what I came up with:

	// read the input data into a separate buffer,
	// so that other parts of the input stream can't
	// be accessed from within deserialize()
	void *data = malloc(sizeIn);
	if (!data) return ERROR;

	Result result = ERROR;
	
	if (in.read(data, sizeIn) == sizeIn) {
		// deserialize data
		juce::MemoryInputStream tmp(data, sizeIn, false);
		result = deserialize(tmp).result;
	}

	free(data);
	return result;

However, I would really like to get this to work using JUCE classes, so I don’t have to do malloc and free myself. This is my original code:

	// read the input data into a separate buffer,
	// so that other parts of the input stream can't
	// be accessed from within deserialize()
	juce::MemoryBlock data;
	if (in.readIntoMemoryBlock(data, sizeIn) != sizeIn) return ERROR;

	// deserialize data
	juce::MemoryInputStream tmp(data, false);
	return deserialize(tmp).result;

When reading from the MemoryInputStream which should basically access the MemoryBlock containing the relevant segment of data, I did not get the same values as when reading from the MemoryInputStream on the malloc'd data block.

What am I missing?


#2

Looks OK to me… Most likely there’s something else in your other code that is relevant to it not working. Maybe try to create a standalone chunk of code that we could try, and in the process of trying to do that you may find what’s wrong.