MCPcopy Create free account
hub / github.com/tensorflow/tfjs / slice

Method slice

tfjs-core/src/io/composite_array_buffer.ts:101–150  ·  view source on GitHub ↗
(start = 0, end = this.byteLength)

Source from the content-addressed store, hash-verified

99 }
100
101 slice(start = 0, end = this.byteLength): ArrayBuffer {
102 // If there are no shards, then the CompositeArrayBuffer was initialized
103 // with no data.
104 if (this.shards.length === 0) {
105 return new ArrayBuffer(0);
106 }
107
108 // NaN is treated as zero for slicing. This matches ArrayBuffer's behavior.
109 start = isNaN(Number(start)) ? 0 : start;
110 end = isNaN(Number(end)) ? 0 : end;
111
112 // Fix the bounds to within the array.
113 start = Math.max(0, start);
114 end = Math.min(this.byteLength, end);
115 if (end <= start) {
116 return new ArrayBuffer(0);
117 }
118
119 const startShardIndex = this.findShardForByte(start);
120 if (startShardIndex === -1) {
121 // This should not happen since the start and end indices are always
122 // within 0 and the composite array's length.
123 throw new Error(`Could not find start shard for byte ${start}`);
124 }
125
126 const size = end - start;
127 const outputBuffer = new ArrayBuffer(size);
128 const outputArray = new Uint8Array(outputBuffer);
129 let sliced = 0;
130 for (let i = startShardIndex; i < this.shards.length; i++) {
131 const shard = this.shards[i];
132
133 const globalStart = start + sliced;
134 const localStart = globalStart - shard.start;
135 const outputStart = sliced;
136
137 const globalEnd = Math.min(end, shard.end);
138 const localEnd = globalEnd - shard.start;
139
140 const outputSlice = new Uint8Array(shard.buffer, localStart,
141 localEnd - localStart);
142 outputArray.set(outputSlice, outputStart);
143 sliced += outputSlice.length;
144
145 if (end < shard.end) {
146 break;
147 }
148 }
149 return outputBuffer;
150 }
151
152 /**
153 * Get the index of the shard that contains the byte at `byteIndex`.

Callers 2

decodeWeightsFunction · 0.95
weightsLoaderFactoryFunction · 0.95

Calls 4

findShardForByteMethod · 0.95
maxMethod · 0.80
minMethod · 0.80
setMethod · 0.45

Tested by

no test coverage detected