Skip to content

Commit 0ea5e95

Browse files
committed
windows: cache write buffer allocated for small user buffers
1 parent de08a4f commit 0ea5e95

File tree

1 file changed

+7
-7
lines changed

1 file changed

+7
-7
lines changed

windows/hid.c

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,7 @@ struct hid_device_ {
144144
HANDLE device_handle;
145145
BOOL blocking;
146146
USHORT output_report_length;
147+
unsigned char *write_buf;
147148
size_t input_report_length;
148149
USHORT feature_report_length;
149150
unsigned char *feature_buf;
@@ -161,6 +162,7 @@ static hid_device *new_hid_device()
161162
dev->device_handle = INVALID_HANDLE_VALUE;
162163
dev->blocking = TRUE;
163164
dev->output_report_length = 0;
165+
dev->write_buf = NULL;
164166
dev->input_report_length = 0;
165167
dev->feature_report_length = 0;
166168
dev->feature_buf = NULL;
@@ -182,6 +184,7 @@ static void free_hid_device(hid_device *dev)
182184
CloseHandle(dev->write_ol.hEvent);
183185
CloseHandle(dev->device_handle);
184186
LocalFree(dev->last_error_str);
187+
free(dev->write_buf);
185188
free(dev->feature_buf);
186189
free(dev->read_buf);
187190
free(dev);
@@ -661,14 +664,14 @@ int HID_API_EXPORT HID_API_CALL hid_write(hid_device *dev, const unsigned char *
661664
one for the report number) bytes even if the data is a report
662665
which is shorter than that. Windows gives us this value in
663666
caps.OutputReportByteLength. If a user passes in fewer bytes than this,
664-
create a temporary buffer which is the proper size. */
667+
use cached temporary buffer which is the proper size. */
665668
if (length >= dev->output_report_length) {
666669
/* The user passed the right number of bytes. Use the buffer as-is. */
667670
buf = (unsigned char *) data;
668671
} else {
669-
/* Create a temporary buffer and copy the user's data
670-
into it, padding the rest with zeros. */
671-
buf = (unsigned char *) malloc(dev->output_report_length);
672+
if (dev->write_buf == NULL)
673+
dev->write_buf = (unsigned char *) malloc(dev->output_report_length);
674+
buf = dev->write_buf;
672675
memcpy(buf, data, length);
673676
memset(buf + length, 0, dev->output_report_length - length);
674677
length = dev->output_report_length;
@@ -708,9 +711,6 @@ int HID_API_EXPORT HID_API_CALL hid_write(hid_device *dev, const unsigned char *
708711
}
709712

710713
end_of_function:
711-
if (buf != data)
712-
free(buf);
713-
714714
return function_result;
715715
}
716716

0 commit comments

Comments
 (0)