How to use buffer method in Best

Best JavaScript code snippet using best

tokenize.js

Source:tokenize.js Github

copy

Full Screen

1var Marker = require('./marker');2var Token = require('./token');3var formatPosition = require('../utils/format-position');4var Level = {5 BLOCK: 'block',6 COMMENT: 'comment',7 DOUBLE_QUOTE: 'double-quote',8 RULE: 'rule',9 SINGLE_QUOTE: 'single-quote'10};11var AT_RULES = [12 '@charset',13 '@import'14];15var BLOCK_RULES = [16 '@-moz-document',17 '@document',18 '@-moz-keyframes',19 '@-ms-keyframes',20 '@-o-keyframes',21 '@-webkit-keyframes',22 '@keyframes',23 '@media',24 '@supports'25];26var IGNORE_END_COMMENT_PATTERN = /\/\* clean\-css ignore:end \*\/$/;27var IGNORE_START_COMMENT_PATTERN = /^\/\* clean\-css ignore:start \*\//;28var PAGE_MARGIN_BOXES = [29 '@bottom-center',30 '@bottom-left',31 '@bottom-left-corner',32 '@bottom-right',33 '@bottom-right-corner',34 '@left-bottom',35 '@left-middle',36 '@left-top',37 '@right-bottom',38 '@right-middle',39 '@right-top',40 '@top-center',41 '@top-left',42 '@top-left-corner',43 '@top-right',44 '@top-right-corner'45];46var EXTRA_PAGE_BOXES = [47 '@footnote',48 '@footnotes',49 '@left',50 '@page-float-bottom',51 '@page-float-top',52 '@right'53];54var REPEAT_PATTERN = /^\[\s{0,31}\d+\s{0,31}\]$/;55var RULE_WORD_SEPARATOR_PATTERN = /[\s\(]/;56var TAIL_BROKEN_VALUE_PATTERN = /[\s|\}]*$/;57function tokenize(source, externalContext) {58 var internalContext = {59 level: Level.BLOCK,60 position: {61 source: externalContext.source || undefined,62 line: 1,63 column: 0,64 index: 065 }66 };67 return intoTokens(source, externalContext, internalContext, false);68}69function intoTokens(source, externalContext, internalContext, isNested) {70 var allTokens = [];71 var newTokens = allTokens;72 var lastToken;73 var ruleToken;74 var ruleTokens = [];75 var propertyToken;76 var metadata;77 var metadatas = [];78 var level = internalContext.level;79 var levels = [];80 var buffer = [];81 var buffers = [];82 var serializedBuffer;83 var serializedBufferPart;84 var roundBracketLevel = 0;85 var isQuoted;86 var isSpace;87 var isNewLineNix;88 var isNewLineWin;89 var isCarriageReturn;90 var isCommentStart;91 var wasCommentStart = false;92 var isCommentEnd;93 var wasCommentEnd = false;94 var isCommentEndMarker;95 var isEscaped;96 var wasEscaped = false;97 var isRaw = false;98 var seekingValue = false;99 var seekingPropertyBlockClosing = false;100 var position = internalContext.position;101 var lastCommentStartAt;102 for (; position.index < source.length; position.index++) {103 var character = source[position.index];104 isQuoted = level == Level.SINGLE_QUOTE || level == Level.DOUBLE_QUOTE;105 isSpace = character == Marker.SPACE || character == Marker.TAB;106 isNewLineNix = character == Marker.NEW_LINE_NIX;107 isNewLineWin = character == Marker.NEW_LINE_NIX && source[position.index - 1] == Marker.CARRIAGE_RETURN;108 isCarriageReturn = character == Marker.CARRIAGE_RETURN && source[position.index + 1] && source[position.index + 1] != Marker.NEW_LINE_NIX;109 isCommentStart = !wasCommentEnd && level != Level.COMMENT && !isQuoted && character == Marker.ASTERISK && source[position.index - 1] == Marker.FORWARD_SLASH;110 isCommentEndMarker = !wasCommentStart && !isQuoted && character == Marker.FORWARD_SLASH && source[position.index - 1] == Marker.ASTERISK;111 isCommentEnd = level == Level.COMMENT && isCommentEndMarker;112 roundBracketLevel = Math.max(roundBracketLevel, 0);113 metadata = buffer.length === 0 ?114 [position.line, position.column, position.source] :115 metadata;116 if (isEscaped) {117 // previous character was a backslash118 buffer.push(character);119 } else if (!isCommentEnd && level == Level.COMMENT) {120 buffer.push(character);121 } else if (!isCommentStart && !isCommentEnd && isRaw) {122 buffer.push(character);123 } else if (isCommentStart && (level == Level.BLOCK || level == Level.RULE) && buffer.length > 1) {124 // comment start within block preceded by some content, e.g. div/*<--125 metadatas.push(metadata);126 buffer.push(character);127 buffers.push(buffer.slice(0, buffer.length - 2));128 buffer = buffer.slice(buffer.length - 2);129 metadata = [position.line, position.column - 1, position.source];130 levels.push(level);131 level = Level.COMMENT;132 } else if (isCommentStart) {133 // comment start, e.g. /*<--134 levels.push(level);135 level = Level.COMMENT;136 buffer.push(character);137 } else if (isCommentEnd && isIgnoreStartComment(buffer)) {138 // ignore:start comment end, e.g. /* clean-css ignore:start */<--139 serializedBuffer = buffer.join('').trim() + character;140 lastToken = [Token.COMMENT, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]];141 newTokens.push(lastToken);142 isRaw = true;143 metadata = metadatas.pop() || null;144 buffer = buffers.pop() || [];145 } else if (isCommentEnd && isIgnoreEndComment(buffer)) {146 // ignore:start comment end, e.g. /* clean-css ignore:end */<--147 serializedBuffer = buffer.join('') + character;148 lastCommentStartAt = serializedBuffer.lastIndexOf(Marker.FORWARD_SLASH + Marker.ASTERISK);149 serializedBufferPart = serializedBuffer.substring(0, lastCommentStartAt);150 lastToken = [Token.RAW, serializedBufferPart, [originalMetadata(metadata, serializedBufferPart, externalContext)]];151 newTokens.push(lastToken);152 serializedBufferPart = serializedBuffer.substring(lastCommentStartAt);153 metadata = [position.line, position.column - serializedBufferPart.length + 1, position.source];154 lastToken = [Token.COMMENT, serializedBufferPart, [originalMetadata(metadata, serializedBufferPart, externalContext)]];155 newTokens.push(lastToken);156 isRaw = false;157 level = levels.pop();158 metadata = metadatas.pop() || null;159 buffer = buffers.pop() || [];160 } else if (isCommentEnd) {161 // comment end, e.g. /* comment */<--162 serializedBuffer = buffer.join('').trim() + character;163 lastToken = [Token.COMMENT, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]];164 newTokens.push(lastToken);165 level = levels.pop();166 metadata = metadatas.pop() || null;167 buffer = buffers.pop() || [];168 } else if (isCommentEndMarker && source[position.index + 1] != Marker.ASTERISK) {169 externalContext.warnings.push('Unexpected \'*/\' at ' + formatPosition([position.line, position.column, position.source]) + '.');170 buffer = [];171 } else if (character == Marker.SINGLE_QUOTE && !isQuoted) {172 // single quotation start, e.g. a[href^='https<--173 levels.push(level);174 level = Level.SINGLE_QUOTE;175 buffer.push(character);176 } else if (character == Marker.SINGLE_QUOTE && level == Level.SINGLE_QUOTE) {177 // single quotation end, e.g. a[href^='https'<--178 level = levels.pop();179 buffer.push(character);180 } else if (character == Marker.DOUBLE_QUOTE && !isQuoted) {181 // double quotation start, e.g. a[href^="<--182 levels.push(level);183 level = Level.DOUBLE_QUOTE;184 buffer.push(character);185 } else if (character == Marker.DOUBLE_QUOTE && level == Level.DOUBLE_QUOTE) {186 // double quotation end, e.g. a[href^="https"<--187 level = levels.pop();188 buffer.push(character);189 } else if (!isCommentStart && !isCommentEnd && character != Marker.CLOSE_ROUND_BRACKET && character != Marker.OPEN_ROUND_BRACKET && level != Level.COMMENT && !isQuoted && roundBracketLevel > 0) {190 // character inside any function, e.g. hsla(.<--191 buffer.push(character);192 } else if (character == Marker.OPEN_ROUND_BRACKET && !isQuoted && level != Level.COMMENT && !seekingValue) {193 // round open bracket, e.g. @import url(<--194 buffer.push(character);195 roundBracketLevel++;196 } else if (character == Marker.CLOSE_ROUND_BRACKET && !isQuoted && level != Level.COMMENT && !seekingValue) {197 // round open bracket, e.g. @import url(test.css)<--198 buffer.push(character);199 roundBracketLevel--;200 } else if (character == Marker.SEMICOLON && level == Level.BLOCK && buffer[0] == Marker.AT) {201 // semicolon ending rule at block level, e.g. @import '...';<--202 serializedBuffer = buffer.join('').trim();203 allTokens.push([Token.AT_RULE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);204 buffer = [];205 } else if (character == Marker.COMMA && level == Level.BLOCK && ruleToken) {206 // comma separator at block level, e.g. a,div,<--207 serializedBuffer = buffer.join('').trim();208 ruleToken[1].push([tokenScopeFrom(ruleToken[0]), serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext, ruleToken[1].length)]]);209 buffer = [];210 } else if (character == Marker.COMMA && level == Level.BLOCK && tokenTypeFrom(buffer) == Token.AT_RULE) {211 // comma separator at block level, e.g. @import url(...) screen,<--212 // keep iterating as end semicolon will create the token213 buffer.push(character);214 } else if (character == Marker.COMMA && level == Level.BLOCK) {215 // comma separator at block level, e.g. a,<--216 ruleToken = [tokenTypeFrom(buffer), [], []];217 serializedBuffer = buffer.join('').trim();218 ruleToken[1].push([tokenScopeFrom(ruleToken[0]), serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext, 0)]]);219 buffer = [];220 } else if (character == Marker.OPEN_CURLY_BRACKET && level == Level.BLOCK && ruleToken && ruleToken[0] == Token.NESTED_BLOCK) {221 // open brace opening at-rule at block level, e.g. @media{<--222 serializedBuffer = buffer.join('').trim();223 ruleToken[1].push([Token.NESTED_BLOCK_SCOPE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);224 allTokens.push(ruleToken);225 levels.push(level);226 position.column++;227 position.index++;228 buffer = [];229 ruleToken[2] = intoTokens(source, externalContext, internalContext, true);230 ruleToken = null;231 } else if (character == Marker.OPEN_CURLY_BRACKET && level == Level.BLOCK && tokenTypeFrom(buffer) == Token.NESTED_BLOCK) {232 // open brace opening at-rule at block level, e.g. @media{<--233 serializedBuffer = buffer.join('').trim();234 ruleToken = ruleToken || [Token.NESTED_BLOCK, [], []];235 ruleToken[1].push([Token.NESTED_BLOCK_SCOPE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);236 allTokens.push(ruleToken);237 levels.push(level);238 position.column++;239 position.index++;240 buffer = [];241 ruleToken[2] = intoTokens(source, externalContext, internalContext, true);242 ruleToken = null;243 } else if (character == Marker.OPEN_CURLY_BRACKET && level == Level.BLOCK) {244 // open brace opening rule at block level, e.g. div{<--245 serializedBuffer = buffer.join('').trim();246 ruleToken = ruleToken || [tokenTypeFrom(buffer), [], []];247 ruleToken[1].push([tokenScopeFrom(ruleToken[0]), serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext, ruleToken[1].length)]]);248 newTokens = ruleToken[2];249 allTokens.push(ruleToken);250 levels.push(level);251 level = Level.RULE;252 buffer = [];253 } else if (character == Marker.OPEN_CURLY_BRACKET && level == Level.RULE && seekingValue) {254 // open brace opening rule at rule level, e.g. div{--variable:{<--255 ruleTokens.push(ruleToken);256 ruleToken = [Token.PROPERTY_BLOCK, []];257 propertyToken.push(ruleToken);258 newTokens = ruleToken[1];259 levels.push(level);260 level = Level.RULE;261 seekingValue = false;262 } else if (character == Marker.OPEN_CURLY_BRACKET && level == Level.RULE && isPageMarginBox(buffer)) {263 // open brace opening page-margin box at rule level, e.g. @page{@top-center{<--264 serializedBuffer = buffer.join('').trim();265 ruleTokens.push(ruleToken);266 ruleToken = [Token.AT_RULE_BLOCK, [], []];267 ruleToken[1].push([Token.AT_RULE_BLOCK_SCOPE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);268 newTokens.push(ruleToken);269 newTokens = ruleToken[2];270 levels.push(level);271 level = Level.RULE;272 buffer = [];273 } else if (character == Marker.COLON && level == Level.RULE && !seekingValue) {274 // colon at rule level, e.g. a{color:<--275 serializedBuffer = buffer.join('').trim();276 propertyToken = [Token.PROPERTY, [Token.PROPERTY_NAME, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]];277 newTokens.push(propertyToken);278 seekingValue = true;279 buffer = [];280 } else if (character == Marker.SEMICOLON && level == Level.RULE && propertyToken && ruleTokens.length > 0 && buffer.length > 0 && buffer[0] == Marker.AT) {281 // semicolon at rule level for at-rule, e.g. a{--color:{@apply(--other-color);<--282 serializedBuffer = buffer.join('').trim();283 ruleToken[1].push([Token.AT_RULE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);284 buffer = [];285 } else if (character == Marker.SEMICOLON && level == Level.RULE && propertyToken && buffer.length > 0) {286 // semicolon at rule level, e.g. a{color:red;<--287 serializedBuffer = buffer.join('').trim();288 propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);289 propertyToken = null;290 seekingValue = false;291 buffer = [];292 } else if (character == Marker.SEMICOLON && level == Level.RULE && propertyToken && buffer.length === 0) {293 // semicolon after bracketed value at rule level, e.g. a{color:rgb(...);<--294 propertyToken = null;295 seekingValue = false;296 } else if (character == Marker.SEMICOLON && level == Level.RULE && buffer.length > 0 && buffer[0] == Marker.AT) {297 // semicolon for at-rule at rule level, e.g. a{@apply(--variable);<--298 serializedBuffer = buffer.join('');299 newTokens.push([Token.AT_RULE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);300 seekingValue = false;301 buffer = [];302 } else if (character == Marker.SEMICOLON && level == Level.RULE && seekingPropertyBlockClosing) {303 // close brace after a property block at rule level, e.g. a{--custom:{color:red;};<--304 seekingPropertyBlockClosing = false;305 buffer = [];306 } else if (character == Marker.SEMICOLON && level == Level.RULE && buffer.length === 0) {307 // stray semicolon at rule level, e.g. a{;<--308 // noop309 } else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.RULE && propertyToken && seekingValue && buffer.length > 0 && ruleTokens.length > 0) {310 // close brace at rule level, e.g. a{--color:{color:red}<--311 serializedBuffer = buffer.join('');312 propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);313 propertyToken = null;314 ruleToken = ruleTokens.pop();315 newTokens = ruleToken[2];316 level = levels.pop();317 seekingValue = false;318 buffer = [];319 } else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.RULE && propertyToken && buffer.length > 0 && buffer[0] == Marker.AT && ruleTokens.length > 0) {320 // close brace at rule level for at-rule, e.g. a{--color:{@apply(--other-color)}<--321 serializedBuffer = buffer.join('');322 ruleToken[1].push([Token.AT_RULE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);323 propertyToken = null;324 ruleToken = ruleTokens.pop();325 newTokens = ruleToken[2];326 level = levels.pop();327 seekingValue = false;328 buffer = [];329 } else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.RULE && propertyToken && ruleTokens.length > 0) {330 // close brace at rule level after space, e.g. a{--color:{color:red }<--331 propertyToken = null;332 ruleToken = ruleTokens.pop();333 newTokens = ruleToken[2];334 level = levels.pop();335 seekingValue = false;336 } else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.RULE && propertyToken && buffer.length > 0) {337 // close brace at rule level, e.g. a{color:red}<--338 serializedBuffer = buffer.join('');339 propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);340 propertyToken = null;341 ruleToken = ruleTokens.pop();342 newTokens = allTokens;343 level = levels.pop();344 seekingValue = false;345 buffer = [];346 } else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.RULE && buffer.length > 0 && buffer[0] == Marker.AT) {347 // close brace after at-rule at rule level, e.g. a{@apply(--variable)}<--348 propertyToken = null;349 ruleToken = null;350 serializedBuffer = buffer.join('').trim();351 newTokens.push([Token.AT_RULE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);352 newTokens = allTokens;353 level = levels.pop();354 seekingValue = false;355 buffer = [];356 } else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.RULE && levels[levels.length - 1] == Level.RULE) {357 // close brace after a property block at rule level, e.g. a{--custom:{color:red;}<--358 propertyToken = null;359 ruleToken = ruleTokens.pop();360 newTokens = ruleToken[2];361 level = levels.pop();362 seekingValue = false;363 seekingPropertyBlockClosing = true;364 buffer = [];365 } else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.RULE) {366 // close brace after a rule, e.g. a{color:red;}<--367 propertyToken = null;368 ruleToken = null;369 newTokens = allTokens;370 level = levels.pop();371 seekingValue = false;372 } else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.BLOCK && !isNested && position.index <= source.length - 1) {373 // stray close brace at block level, e.g. a{color:red}color:blue}<--374 externalContext.warnings.push('Unexpected \'}\' at ' + formatPosition([position.line, position.column, position.source]) + '.');375 buffer.push(character);376 } else if (character == Marker.CLOSE_CURLY_BRACKET && level == Level.BLOCK) {377 // close brace at block level, e.g. @media screen {...}<--378 break;379 } else if (character == Marker.OPEN_ROUND_BRACKET && level == Level.RULE && seekingValue) {380 // round open bracket, e.g. a{color:hsla(<--381 buffer.push(character);382 roundBracketLevel++;383 } else if (character == Marker.CLOSE_ROUND_BRACKET && level == Level.RULE && seekingValue && roundBracketLevel == 1) {384 // round close bracket, e.g. a{color:hsla(0,0%,0%)<--385 buffer.push(character);386 serializedBuffer = buffer.join('').trim();387 propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);388 roundBracketLevel--;389 buffer = [];390 } else if (character == Marker.CLOSE_ROUND_BRACKET && level == Level.RULE && seekingValue) {391 // round close bracket within other brackets, e.g. a{width:calc((10rem / 2)<--392 buffer.push(character);393 roundBracketLevel--;394 } else if (character == Marker.FORWARD_SLASH && source[position.index + 1] != Marker.ASTERISK && level == Level.RULE && seekingValue && buffer.length > 0) {395 // forward slash within a property, e.g. a{background:url(image.png) 0 0/<--396 serializedBuffer = buffer.join('').trim();397 propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);398 propertyToken.push([Token.PROPERTY_VALUE, character, [[position.line, position.column, position.source]]]);399 buffer = [];400 } else if (character == Marker.FORWARD_SLASH && source[position.index + 1] != Marker.ASTERISK && level == Level.RULE && seekingValue) {401 // forward slash within a property after space, e.g. a{background:url(image.png) 0 0 /<--402 propertyToken.push([Token.PROPERTY_VALUE, character, [[position.line, position.column, position.source]]]);403 buffer = [];404 } else if (character == Marker.COMMA && level == Level.RULE && seekingValue && buffer.length > 0) {405 // comma within a property, e.g. a{background:url(image.png),<--406 serializedBuffer = buffer.join('').trim();407 propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);408 propertyToken.push([Token.PROPERTY_VALUE, character, [[position.line, position.column, position.source]]]);409 buffer = [];410 } else if (character == Marker.COMMA && level == Level.RULE && seekingValue) {411 // comma within a property after space, e.g. a{background:url(image.png) ,<--412 propertyToken.push([Token.PROPERTY_VALUE, character, [[position.line, position.column, position.source]]]);413 buffer = [];414 } else if (character == Marker.CLOSE_SQUARE_BRACKET && propertyToken && propertyToken.length > 1 && buffer.length > 0 && isRepeatToken(buffer)) {415 buffer.push(character);416 serializedBuffer = buffer.join('').trim();417 propertyToken[propertyToken.length - 1][1] += serializedBuffer;418 buffer = [];419 } else if ((isSpace || (isNewLineNix && !isNewLineWin)) && level == Level.RULE && seekingValue && propertyToken && buffer.length > 0) {420 // space or *nix newline within property, e.g. a{margin:0 <--421 serializedBuffer = buffer.join('').trim();422 propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);423 buffer = [];424 } else if (isNewLineWin && level == Level.RULE && seekingValue && propertyToken && buffer.length > 1) {425 // win newline within property, e.g. a{margin:0\r\n<--426 serializedBuffer = buffer.join('').trim();427 propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);428 buffer = [];429 } else if (isNewLineWin && level == Level.RULE && seekingValue) {430 // win newline431 buffer = [];432 } else if (buffer.length == 1 && isNewLineWin) {433 // ignore windows newline which is composed of two characters434 buffer.pop();435 } else if (buffer.length > 0 || !isSpace && !isNewLineNix && !isNewLineWin && !isCarriageReturn) {436 // any character437 buffer.push(character);438 }439 wasEscaped = isEscaped;440 isEscaped = !wasEscaped && character == Marker.BACK_SLASH;441 wasCommentStart = isCommentStart;442 wasCommentEnd = isCommentEnd;443 position.line = (isNewLineWin || isNewLineNix || isCarriageReturn) ? position.line + 1 : position.line;444 position.column = (isNewLineWin || isNewLineNix || isCarriageReturn) ? 0 : position.column + 1;445 }446 if (seekingValue) {447 externalContext.warnings.push('Missing \'}\' at ' + formatPosition([position.line, position.column, position.source]) + '.');448 }449 if (seekingValue && buffer.length > 0) {450 serializedBuffer = buffer.join('').replace(TAIL_BROKEN_VALUE_PATTERN, '');451 propertyToken.push([Token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]);452 buffer = [];453 }454 if (buffer.length > 0) {455 externalContext.warnings.push('Invalid character(s) \'' + buffer.join('') + '\' at ' + formatPosition(metadata) + '. Ignoring.');456 }457 return allTokens;458}459function isIgnoreStartComment(buffer) {460 return IGNORE_START_COMMENT_PATTERN.test(buffer.join('') + Marker.FORWARD_SLASH);461}462function isIgnoreEndComment(buffer) {463 return IGNORE_END_COMMENT_PATTERN.test(buffer.join('') + Marker.FORWARD_SLASH);464}465function originalMetadata(metadata, value, externalContext, selectorFallbacks) {466 var source = metadata[2];467 return externalContext.inputSourceMapTracker.isTracking(source) ?468 externalContext.inputSourceMapTracker.originalPositionFor(metadata, value.length, selectorFallbacks) :469 metadata;470}471function tokenTypeFrom(buffer) {472 var isAtRule = buffer[0] == Marker.AT || buffer[0] == Marker.UNDERSCORE;473 var ruleWord = buffer.join('').split(RULE_WORD_SEPARATOR_PATTERN)[0];474 if (isAtRule && BLOCK_RULES.indexOf(ruleWord) > -1) {475 return Token.NESTED_BLOCK;476 } else if (isAtRule && AT_RULES.indexOf(ruleWord) > -1) {477 return Token.AT_RULE;478 } else if (isAtRule) {479 return Token.AT_RULE_BLOCK;480 } else {481 return Token.RULE;482 }483}484function tokenScopeFrom(tokenType) {485 if (tokenType == Token.RULE) {486 return Token.RULE_SCOPE;487 } else if (tokenType == Token.NESTED_BLOCK) {488 return Token.NESTED_BLOCK_SCOPE;489 } else if (tokenType == Token.AT_RULE_BLOCK) {490 return Token.AT_RULE_BLOCK_SCOPE;491 }492}493function isPageMarginBox(buffer) {494 var serializedBuffer = buffer.join('').trim();495 return PAGE_MARGIN_BOXES.indexOf(serializedBuffer) > -1 || EXTRA_PAGE_BOXES.indexOf(serializedBuffer) > -1;496}497function isRepeatToken(buffer) {498 return REPEAT_PATTERN.test(buffer.join('') + Marker.CLOSE_SQUARE_BRACKET);499}...

Full Screen

Full Screen

tests.js

Source:tests.js Github

copy

Full Screen

1/* eslint-disable node/no-deprecated-api */2'use strict'3var test = require('tape')4var buffer = require('buffer')5var index = require('./')6var safer = require('./safer')7var dangerous = require('./dangerous')8/* Inheritance tests */9test('Default is Safer', function (t) {10 t.equal(index, safer)11 t.notEqual(safer, dangerous)12 t.notEqual(index, dangerous)13 t.end()14})15test('Is not a function', function (t) {16 [index, safer, dangerous].forEach(function (impl) {17 t.equal(typeof impl, 'object')18 t.equal(typeof impl.Buffer, 'object')19 });20 [buffer].forEach(function (impl) {21 t.equal(typeof impl, 'object')22 t.equal(typeof impl.Buffer, 'function')23 })24 t.end()25})26test('Constructor throws', function (t) {27 [index, safer, dangerous].forEach(function (impl) {28 t.throws(function () { impl.Buffer() })29 t.throws(function () { impl.Buffer(0) })30 t.throws(function () { impl.Buffer('a') })31 t.throws(function () { impl.Buffer('a', 'utf-8') })32 t.throws(function () { return new impl.Buffer() })33 t.throws(function () { return new impl.Buffer(0) })34 t.throws(function () { return new impl.Buffer('a') })35 t.throws(function () { return new impl.Buffer('a', 'utf-8') })36 })37 t.end()38})39test('Safe methods exist', function (t) {40 [index, safer, dangerous].forEach(function (impl) {41 t.equal(typeof impl.Buffer.alloc, 'function', 'alloc')42 t.equal(typeof impl.Buffer.from, 'function', 'from')43 })44 t.end()45})46test('Unsafe methods exist only in Dangerous', function (t) {47 [index, safer].forEach(function (impl) {48 t.equal(typeof impl.Buffer.allocUnsafe, 'undefined')49 t.equal(typeof impl.Buffer.allocUnsafeSlow, 'undefined')50 });51 [dangerous].forEach(function (impl) {52 t.equal(typeof impl.Buffer.allocUnsafe, 'function')53 t.equal(typeof impl.Buffer.allocUnsafeSlow, 'function')54 })55 t.end()56})57test('Generic methods/properties are defined and equal', function (t) {58 ['poolSize', 'isBuffer', 'concat', 'byteLength'].forEach(function (method) {59 [index, safer, dangerous].forEach(function (impl) {60 t.equal(impl.Buffer[method], buffer.Buffer[method], method)61 t.notEqual(typeof impl.Buffer[method], 'undefined', method)62 })63 })64 t.end()65})66test('Built-in buffer static methods/properties are inherited', function (t) {67 Object.keys(buffer).forEach(function (method) {68 if (method === 'SlowBuffer' || method === 'Buffer') return;69 [index, safer, dangerous].forEach(function (impl) {70 t.equal(impl[method], buffer[method], method)71 t.notEqual(typeof impl[method], 'undefined', method)72 })73 })74 t.end()75})76test('Built-in Buffer static methods/properties are inherited', function (t) {77 Object.keys(buffer.Buffer).forEach(function (method) {78 if (method === 'allocUnsafe' || method === 'allocUnsafeSlow') return;79 [index, safer, dangerous].forEach(function (impl) {80 t.equal(impl.Buffer[method], buffer.Buffer[method], method)81 t.notEqual(typeof impl.Buffer[method], 'undefined', method)82 })83 })84 t.end()85})86test('.prototype property of Buffer is inherited', function (t) {87 [index, safer, dangerous].forEach(function (impl) {88 t.equal(impl.Buffer.prototype, buffer.Buffer.prototype, 'prototype')89 t.notEqual(typeof impl.Buffer.prototype, 'undefined', 'prototype')90 })91 t.end()92})93test('All Safer methods are present in Dangerous', function (t) {94 Object.keys(safer).forEach(function (method) {95 if (method === 'Buffer') return;96 [index, safer, dangerous].forEach(function (impl) {97 t.equal(impl[method], safer[method], method)98 if (method !== 'kStringMaxLength') {99 t.notEqual(typeof impl[method], 'undefined', method)100 }101 })102 })103 Object.keys(safer.Buffer).forEach(function (method) {104 [index, safer, dangerous].forEach(function (impl) {105 t.equal(impl.Buffer[method], safer.Buffer[method], method)106 t.notEqual(typeof impl.Buffer[method], 'undefined', method)107 })108 })109 t.end()110})111test('Safe methods from Dangerous methods are present in Safer', function (t) {112 Object.keys(dangerous).forEach(function (method) {113 if (method === 'Buffer') return;114 [index, safer, dangerous].forEach(function (impl) {115 t.equal(impl[method], dangerous[method], method)116 if (method !== 'kStringMaxLength') {117 t.notEqual(typeof impl[method], 'undefined', method)118 }119 })120 })121 Object.keys(dangerous.Buffer).forEach(function (method) {122 if (method === 'allocUnsafe' || method === 'allocUnsafeSlow') return;123 [index, safer, dangerous].forEach(function (impl) {124 t.equal(impl.Buffer[method], dangerous.Buffer[method], method)125 t.notEqual(typeof impl.Buffer[method], 'undefined', method)126 })127 })128 t.end()129})130/* Behaviour tests */131test('Methods return Buffers', function (t) {132 [index, safer, dangerous].forEach(function (impl) {133 t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0)))134 t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0, 10)))135 t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0, 'a')))136 t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(10)))137 t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(10, 'x')))138 t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(9, 'ab')))139 t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('')))140 t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('string')))141 t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('string', 'utf-8')))142 t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64')))143 t.ok(buffer.Buffer.isBuffer(impl.Buffer.from([0, 42, 3])))144 t.ok(buffer.Buffer.isBuffer(impl.Buffer.from(new Uint8Array([0, 42, 3]))))145 t.ok(buffer.Buffer.isBuffer(impl.Buffer.from([])))146 });147 ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) {148 t.ok(buffer.Buffer.isBuffer(dangerous.Buffer[method](0)))149 t.ok(buffer.Buffer.isBuffer(dangerous.Buffer[method](10)))150 })151 t.end()152})153test('Constructor is buffer.Buffer', function (t) {154 [index, safer, dangerous].forEach(function (impl) {155 t.equal(impl.Buffer.alloc(0).constructor, buffer.Buffer)156 t.equal(impl.Buffer.alloc(0, 10).constructor, buffer.Buffer)157 t.equal(impl.Buffer.alloc(0, 'a').constructor, buffer.Buffer)158 t.equal(impl.Buffer.alloc(10).constructor, buffer.Buffer)159 t.equal(impl.Buffer.alloc(10, 'x').constructor, buffer.Buffer)160 t.equal(impl.Buffer.alloc(9, 'ab').constructor, buffer.Buffer)161 t.equal(impl.Buffer.from('').constructor, buffer.Buffer)162 t.equal(impl.Buffer.from('string').constructor, buffer.Buffer)163 t.equal(impl.Buffer.from('string', 'utf-8').constructor, buffer.Buffer)164 t.equal(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64').constructor, buffer.Buffer)165 t.equal(impl.Buffer.from([0, 42, 3]).constructor, buffer.Buffer)166 t.equal(impl.Buffer.from(new Uint8Array([0, 42, 3])).constructor, buffer.Buffer)167 t.equal(impl.Buffer.from([]).constructor, buffer.Buffer)168 });169 [0, 10, 100].forEach(function (arg) {170 t.equal(dangerous.Buffer.allocUnsafe(arg).constructor, buffer.Buffer)171 t.equal(dangerous.Buffer.allocUnsafeSlow(arg).constructor, buffer.SlowBuffer(0).constructor)172 })173 t.end()174})175test('Invalid calls throw', function (t) {176 [index, safer, dangerous].forEach(function (impl) {177 t.throws(function () { impl.Buffer.from(0) })178 t.throws(function () { impl.Buffer.from(10) })179 t.throws(function () { impl.Buffer.from(10, 'utf-8') })180 t.throws(function () { impl.Buffer.from('string', 'invalid encoding') })181 t.throws(function () { impl.Buffer.from(-10) })182 t.throws(function () { impl.Buffer.from(1e90) })183 t.throws(function () { impl.Buffer.from(Infinity) })184 t.throws(function () { impl.Buffer.from(-Infinity) })185 t.throws(function () { impl.Buffer.from(NaN) })186 t.throws(function () { impl.Buffer.from(null) })187 t.throws(function () { impl.Buffer.from(undefined) })188 t.throws(function () { impl.Buffer.from() })189 t.throws(function () { impl.Buffer.from({}) })190 t.throws(function () { impl.Buffer.alloc('') })191 t.throws(function () { impl.Buffer.alloc('string') })192 t.throws(function () { impl.Buffer.alloc('string', 'utf-8') })193 t.throws(function () { impl.Buffer.alloc('b25ldHdvdGhyZWU=', 'base64') })194 t.throws(function () { impl.Buffer.alloc(-10) })195 t.throws(function () { impl.Buffer.alloc(1e90) })196 t.throws(function () { impl.Buffer.alloc(2 * (1 << 30)) })197 t.throws(function () { impl.Buffer.alloc(Infinity) })198 t.throws(function () { impl.Buffer.alloc(-Infinity) })199 t.throws(function () { impl.Buffer.alloc(null) })200 t.throws(function () { impl.Buffer.alloc(undefined) })201 t.throws(function () { impl.Buffer.alloc() })202 t.throws(function () { impl.Buffer.alloc([]) })203 t.throws(function () { impl.Buffer.alloc([0, 42, 3]) })204 t.throws(function () { impl.Buffer.alloc({}) })205 });206 ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) {207 t.throws(function () { dangerous.Buffer[method]('') })208 t.throws(function () { dangerous.Buffer[method]('string') })209 t.throws(function () { dangerous.Buffer[method]('string', 'utf-8') })210 t.throws(function () { dangerous.Buffer[method](2 * (1 << 30)) })211 t.throws(function () { dangerous.Buffer[method](Infinity) })212 if (dangerous.Buffer[method] === buffer.Buffer.allocUnsafe) {213 t.skip('Skipping, older impl of allocUnsafe coerced negative sizes to 0')214 } else {215 t.throws(function () { dangerous.Buffer[method](-10) })216 t.throws(function () { dangerous.Buffer[method](-1e90) })217 t.throws(function () { dangerous.Buffer[method](-Infinity) })218 }219 t.throws(function () { dangerous.Buffer[method](null) })220 t.throws(function () { dangerous.Buffer[method](undefined) })221 t.throws(function () { dangerous.Buffer[method]() })222 t.throws(function () { dangerous.Buffer[method]([]) })223 t.throws(function () { dangerous.Buffer[method]([0, 42, 3]) })224 t.throws(function () { dangerous.Buffer[method]({}) })225 })226 t.end()227})228test('Buffers have appropriate lengths', function (t) {229 [index, safer, dangerous].forEach(function (impl) {230 t.equal(impl.Buffer.alloc(0).length, 0)231 t.equal(impl.Buffer.alloc(10).length, 10)232 t.equal(impl.Buffer.from('').length, 0)233 t.equal(impl.Buffer.from('string').length, 6)234 t.equal(impl.Buffer.from('string', 'utf-8').length, 6)235 t.equal(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64').length, 11)236 t.equal(impl.Buffer.from([0, 42, 3]).length, 3)237 t.equal(impl.Buffer.from(new Uint8Array([0, 42, 3])).length, 3)238 t.equal(impl.Buffer.from([]).length, 0)239 });240 ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) {241 t.equal(dangerous.Buffer[method](0).length, 0)242 t.equal(dangerous.Buffer[method](10).length, 10)243 })244 t.end()245})246test('Buffers have appropriate lengths (2)', function (t) {247 t.equal(index.Buffer.alloc, safer.Buffer.alloc)248 t.equal(index.Buffer.alloc, dangerous.Buffer.alloc)249 var ok = true;250 [ safer.Buffer.alloc,251 dangerous.Buffer.allocUnsafe,252 dangerous.Buffer.allocUnsafeSlow253 ].forEach(function (method) {254 for (var i = 0; i < 1e2; i++) {255 var length = Math.round(Math.random() * 1e5)256 var buf = method(length)257 if (!buffer.Buffer.isBuffer(buf)) ok = false258 if (buf.length !== length) ok = false259 }260 })261 t.ok(ok)262 t.end()263})264test('.alloc(size) is zero-filled and has correct length', function (t) {265 t.equal(index.Buffer.alloc, safer.Buffer.alloc)266 t.equal(index.Buffer.alloc, dangerous.Buffer.alloc)267 var ok = true268 for (var i = 0; i < 1e2; i++) {269 var length = Math.round(Math.random() * 2e6)270 var buf = index.Buffer.alloc(length)271 if (!buffer.Buffer.isBuffer(buf)) ok = false272 if (buf.length !== length) ok = false273 var j274 for (j = 0; j < length; j++) {275 if (buf[j] !== 0) ok = false276 }277 buf.fill(1)278 for (j = 0; j < length; j++) {279 if (buf[j] !== 1) ok = false280 }281 }282 t.ok(ok)283 t.end()284})285test('.allocUnsafe / .allocUnsafeSlow are fillable and have correct lengths', function (t) {286 ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) {287 var ok = true288 for (var i = 0; i < 1e2; i++) {289 var length = Math.round(Math.random() * 2e6)290 var buf = dangerous.Buffer[method](length)291 if (!buffer.Buffer.isBuffer(buf)) ok = false292 if (buf.length !== length) ok = false293 buf.fill(0, 0, length)294 var j295 for (j = 0; j < length; j++) {296 if (buf[j] !== 0) ok = false297 }298 buf.fill(1, 0, length)299 for (j = 0; j < length; j++) {300 if (buf[j] !== 1) ok = false301 }302 }303 t.ok(ok, method)304 })305 t.end()306})307test('.alloc(size, fill) is `fill`-filled', function (t) {308 t.equal(index.Buffer.alloc, safer.Buffer.alloc)309 t.equal(index.Buffer.alloc, dangerous.Buffer.alloc)310 var ok = true311 for (var i = 0; i < 1e2; i++) {312 var length = Math.round(Math.random() * 2e6)313 var fill = Math.round(Math.random() * 255)314 var buf = index.Buffer.alloc(length, fill)315 if (!buffer.Buffer.isBuffer(buf)) ok = false316 if (buf.length !== length) ok = false317 for (var j = 0; j < length; j++) {318 if (buf[j] !== fill) ok = false319 }320 }321 t.ok(ok)322 t.end()323})324test('.alloc(size, fill) is `fill`-filled', function (t) {325 t.equal(index.Buffer.alloc, safer.Buffer.alloc)326 t.equal(index.Buffer.alloc, dangerous.Buffer.alloc)327 var ok = true328 for (var i = 0; i < 1e2; i++) {329 var length = Math.round(Math.random() * 2e6)330 var fill = Math.round(Math.random() * 255)331 var buf = index.Buffer.alloc(length, fill)332 if (!buffer.Buffer.isBuffer(buf)) ok = false333 if (buf.length !== length) ok = false334 for (var j = 0; j < length; j++) {335 if (buf[j] !== fill) ok = false336 }337 }338 t.ok(ok)339 t.deepEqual(index.Buffer.alloc(9, 'a'), index.Buffer.alloc(9, 97))340 t.notDeepEqual(index.Buffer.alloc(9, 'a'), index.Buffer.alloc(9, 98))341 var tmp = new buffer.Buffer(2)342 tmp.fill('ok')343 if (tmp[1] === tmp[0]) {344 // Outdated Node.js345 t.deepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('ooooo'))346 } else {347 t.deepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('okoko'))348 }349 t.notDeepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('kokok'))350 t.end()351})352test('safer.Buffer.from returns results same as Buffer constructor', function (t) {353 [index, safer, dangerous].forEach(function (impl) {354 t.deepEqual(impl.Buffer.from(''), new buffer.Buffer(''))355 t.deepEqual(impl.Buffer.from('string'), new buffer.Buffer('string'))356 t.deepEqual(impl.Buffer.from('string', 'utf-8'), new buffer.Buffer('string', 'utf-8'))357 t.deepEqual(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64'), new buffer.Buffer('b25ldHdvdGhyZWU=', 'base64'))358 t.deepEqual(impl.Buffer.from([0, 42, 3]), new buffer.Buffer([0, 42, 3]))359 t.deepEqual(impl.Buffer.from(new Uint8Array([0, 42, 3])), new buffer.Buffer(new Uint8Array([0, 42, 3])))360 t.deepEqual(impl.Buffer.from([]), new buffer.Buffer([]))361 })362 t.end()363})364test('safer.Buffer.from returns consistent results', function (t) {365 [index, safer, dangerous].forEach(function (impl) {366 t.deepEqual(impl.Buffer.from(''), impl.Buffer.alloc(0))367 t.deepEqual(impl.Buffer.from([]), impl.Buffer.alloc(0))368 t.deepEqual(impl.Buffer.from(new Uint8Array([])), impl.Buffer.alloc(0))369 t.deepEqual(impl.Buffer.from('string', 'utf-8'), impl.Buffer.from('string'))370 t.deepEqual(impl.Buffer.from('string'), impl.Buffer.from([115, 116, 114, 105, 110, 103]))371 t.deepEqual(impl.Buffer.from('string'), impl.Buffer.from(impl.Buffer.from('string')))372 t.deepEqual(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64'), impl.Buffer.from('onetwothree'))373 t.notDeepEqual(impl.Buffer.from('b25ldHdvdGhyZWU='), impl.Buffer.from('onetwothree'))374 })375 t.end()...

Full Screen

Full Screen

Buffer.js

Source:Buffer.js Github

copy

Full Screen

1/*global define*/2define([3 '../Core/defaultValue',4 '../Core/defined',5 '../Core/defineProperties',6 '../Core/destroyObject',7 '../Core/DeveloperError',8 '../Core/IndexDatatype',9 '../Core/WebGLConstants',10 './BufferUsage'11 ], function(12 defaultValue,13 defined,14 defineProperties,15 destroyObject,16 DeveloperError,17 IndexDatatype,18 WebGLConstants,19 BufferUsage) {20 'use strict';21 /**22 * @private23 */24 function Buffer(options) {25 options = defaultValue(options, defaultValue.EMPTY_OBJECT);26 //>>includeStart('debug', pragmas.debug);27 if (!defined(options.context)) {28 throw new DeveloperError('options.context is required.');29 }30 if (!defined(options.typedArray) && !defined(options.sizeInBytes)) {31 throw new DeveloperError('Either options.sizeInBytes or options.typedArray is required.');32 }33 if (defined(options.typedArray) && defined(options.sizeInBytes)) {34 throw new DeveloperError('Cannot pass in both options.sizeInBytes and options.typedArray.');35 }36 if (defined(options.typedArray) && !(typeof options.typedArray === 'object' && typeof options.typedArray.byteLength === 'number')) {37 throw new DeveloperError('options.typedArray must be a typed array');38 }39 if (!BufferUsage.validate(options.usage)) {40 throw new DeveloperError('usage is invalid.');41 }42 //>>includeEnd('debug');43 var gl = options.context._gl;44 var bufferTarget = options.bufferTarget;45 var typedArray = options.typedArray;46 var sizeInBytes = options.sizeInBytes;47 var usage = options.usage;48 var hasArray = defined(typedArray);49 if (hasArray) {50 sizeInBytes = typedArray.byteLength;51 }52 //>>includeStart('debug', pragmas.debug);53 if (sizeInBytes <= 0) {54 throw new DeveloperError('Buffer size must be greater than zero.');55 }56 //>>includeEnd('debug');57 var buffer = gl.createBuffer();58 gl.bindBuffer(bufferTarget, buffer);59 gl.bufferData(bufferTarget, hasArray ? typedArray : sizeInBytes, usage);60 gl.bindBuffer(bufferTarget, null);61 this._gl = gl;62 this._bufferTarget = bufferTarget;63 this._sizeInBytes = sizeInBytes;64 this._usage = usage;65 this._buffer = buffer;66 this.vertexArrayDestroyable = true;67 }68 /**69 * Creates a vertex buffer, which contains untyped vertex data in GPU-controlled memory.70 * <br /><br />71 * A vertex array defines the actual makeup of a vertex, e.g., positions, normals, texture coordinates,72 * etc., by interpreting the raw data in one or more vertex buffers.73 *74 * @param {Object} options An object containing the following properties:75 * @param {Context} options.context The context in which to create the buffer76 * @param {ArrayBufferView} [options.typedArray] A typed array containing the data to copy to the buffer.77 * @param {Number} [options.sizeInBytes] A <code>Number</code> defining the size of the buffer in bytes. Required if options.typedArray is not given.78 * @param {BufferUsage} options.usage Specifies the expected usage pattern of the buffer. On some GL implementations, this can significantly affect performance. See {@link BufferUsage}.79 * @returns {VertexBuffer} The vertex buffer, ready to be attached to a vertex array.80 *81 * @exception {DeveloperError} Must specify either <options.typedArray> or <options.sizeInBytes>, but not both.82 * @exception {DeveloperError} The buffer size must be greater than zero.83 * @exception {DeveloperError} Invalid <code>usage</code>.84 *85 *86 * @example87 * // Example 1. Create a dynamic vertex buffer 16 bytes in size.88 * var buffer = Buffer.createVertexBuffer({89 * context : context,90 * sizeInBytes : 16,91 * usage : BufferUsage.DYNAMIC_DRAW92 * });93 *94 * @example95 * // Example 2. Create a dynamic vertex buffer from three floating-point values.96 * // The data copied to the vertex buffer is considered raw bytes until it is97 * // interpreted as vertices using a vertex array.98 * var positionBuffer = buffer.createVertexBuffer({99 * context : context,100 * typedArray : new Float32Array([0, 0, 0]),101 * usage : BufferUsage.STATIC_DRAW102 * });103 *104 * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGenBuffer.xml|glGenBuffer}105 * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glBindBuffer.xml|glBindBuffer} with <code>ARRAY_BUFFER</code>106 * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glBufferData.xml|glBufferData} with <code>ARRAY_BUFFER</code>107 */108 Buffer.createVertexBuffer = function(options) {109 //>>includeStart('debug', pragmas.debug);110 if (!defined(options.context)) {111 throw new DeveloperError('options.context is required.');112 }113 //>>includeEnd('debug');114 return new Buffer({115 context: options.context,116 bufferTarget: WebGLConstants.ARRAY_BUFFER,117 typedArray: options.typedArray,118 sizeInBytes: options.sizeInBytes,119 usage: options.usage120 });121 };122 /**123 * Creates an index buffer, which contains typed indices in GPU-controlled memory.124 * <br /><br />125 * An index buffer can be attached to a vertex array to select vertices for rendering.126 * <code>Context.draw</code> can render using the entire index buffer or a subset127 * of the index buffer defined by an offset and count.128 *129 * @param {Object} options An object containing the following properties:130 * @param {Context} options.context The context in which to create the buffer131 * @param {ArrayBufferView} [options.typedArray] A typed array containing the data to copy to the buffer.132 * @param {Number} [options.sizeInBytes] A <code>Number</code> defining the size of the buffer in bytes. Required if options.typedArray is not given.133 * @param {BufferUsage} options.usage Specifies the expected usage pattern of the buffer. On some GL implementations, this can significantly affect performance. See {@link BufferUsage}.134 * @param {IndexDatatype} options.indexDatatype The datatype of indices in the buffer.135 * @returns {IndexBuffer} The index buffer, ready to be attached to a vertex array.136 *137 * @exception {DeveloperError} Must specify either <options.typedArray> or <options.sizeInBytes>, but not both.138 * @exception {DeveloperError} IndexDatatype.UNSIGNED_INT requires OES_element_index_uint, which is not supported on this system. Check context.elementIndexUint.139 * @exception {DeveloperError} The size in bytes must be greater than zero.140 * @exception {DeveloperError} Invalid <code>usage</code>.141 * @exception {DeveloperError} Invalid <code>indexDatatype</code>.142 *143 *144 * @example145 * // Example 1. Create a stream index buffer of unsigned shorts that is146 * // 16 bytes in size.147 * var buffer = Buffer.createIndexBuffer({148 * context : context,149 * sizeInBytes : 16,150 * usage : BufferUsage.STREAM_DRAW,151 * indexDatatype : IndexDatatype.UNSIGNED_SHORT152 * });153 *154 * @example155 * // Example 2. Create a static index buffer containing three unsigned shorts.156 * var buffer = Buffer.createIndexBuffer({157 * context : context,158 * typedArray : new Uint16Array([0, 1, 2]),159 * usage : BufferUsage.STATIC_DRAW,160 * indexDatatype : IndexDatatype.UNSIGNED_SHORT161 * });162 *163 * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGenBuffer.xml|glGenBuffer}164 * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glBindBuffer.xml|glBindBuffer} with <code>ELEMENT_ARRAY_BUFFER</code>165 * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glBufferData.xml|glBufferData} with <code>ELEMENT_ARRAY_BUFFER</code>166 */167 Buffer.createIndexBuffer = function(options) {168 //>>includeStart('debug', pragmas.debug);169 if (!defined(options.context)) {170 throw new DeveloperError('options.context is required.');171 }172 if (!IndexDatatype.validate(options.indexDatatype)) {173 throw new DeveloperError('Invalid indexDatatype.');174 }175 if ((options.indexDatatype === IndexDatatype.UNSIGNED_INT) && !options.context.elementIndexUint) {176 throw new DeveloperError('IndexDatatype.UNSIGNED_INT requires OES_element_index_uint, which is not supported on this system. Check context.elementIndexUint.');177 }178 //>>includeEnd('debug');179 var context = options.context;180 var indexDatatype = options.indexDatatype;181 var bytesPerIndex = IndexDatatype.getSizeInBytes(indexDatatype);182 var buffer = new Buffer({183 context : context,184 bufferTarget : WebGLConstants.ELEMENT_ARRAY_BUFFER,185 typedArray : options.typedArray,186 sizeInBytes : options.sizeInBytes,187 usage : options.usage188 });189 var numberOfIndices = buffer.sizeInBytes / bytesPerIndex;190 defineProperties(buffer, {191 indexDatatype: {192 get : function() {193 return indexDatatype;194 }195 },196 bytesPerIndex : {197 get : function() {198 return bytesPerIndex;199 }200 },201 numberOfIndices : {202 get : function() {203 return numberOfIndices;204 }205 }206 });207 return buffer;208 };209 defineProperties(Buffer.prototype, {210 sizeInBytes : {211 get : function() {212 return this._sizeInBytes;213 }214 },215 usage: {216 get : function() {217 return this._usage;218 }219 }220 });221 Buffer.prototype._getBuffer = function() {222 return this._buffer;223 };224 Buffer.prototype.copyFromArrayView = function(arrayView, offsetInBytes) {225 offsetInBytes = defaultValue(offsetInBytes, 0);226 //>>includeStart('debug', pragmas.debug);227 if (!arrayView) {228 throw new DeveloperError('arrayView is required.');229 }230 if (offsetInBytes + arrayView.byteLength > this._sizeInBytes) {231 throw new DeveloperError('This buffer is not large enough.');232 }233 //>>includeEnd('debug');234 var gl = this._gl;235 var target = this._bufferTarget;236 gl.bindBuffer(target, this._buffer);237 gl.bufferSubData(target, offsetInBytes, arrayView);238 gl.bindBuffer(target, null);239 };240 Buffer.prototype.isDestroyed = function() {241 return false;242 };243 Buffer.prototype.destroy = function() {244 this._gl.deleteBuffer(this._buffer);245 return destroyObject(this);246 };247 return Buffer;...

Full Screen

Full Screen

BufferSpec.js

Source:BufferSpec.js Github

copy

Full Screen

1/*global defineSuite*/2defineSuite([3 'Renderer/Buffer',4 'Core/IndexDatatype',5 'Renderer/BufferUsage',6 'Specs/createContext'7 ], function(8 Buffer,9 IndexDatatype,10 BufferUsage,11 createContext) {12 'use strict';13 var context;14 var buffer;15 beforeAll(function() {16 context = createContext();17 });18 afterAll(function() {19 context.destroyForSpecs();20 });21 afterEach(function() {22 if (buffer) {23 buffer = buffer.destroy();24 }25 });26 it('throws when creating a vertex buffer with no context', function() {27 expect(function() {28 buffer = Buffer.createVertexBuffer({29 sizeInBytes : 4,30 usage : BufferUsage.STATIC_DRAW31 });32 }).toThrowDeveloperError();33 });34 it('throws when creating a vertex buffer with an invalid typed array', function() {35 expect(function() {36 buffer = Buffer.createVertexBuffer({37 context : context,38 typedArray : {},39 usage : BufferUsage.STATIC_DRAW40 });41 }).toThrowDeveloperError();42 });43 it('throws when creating a vertex buffer with both a typed array and size in bytes', function() {44 expect(function() {45 buffer = Buffer.createVertexBuffer({46 context : context,47 typedArray : new Float32Array([0, 0, 0, 1]),48 sizeInBytes : 16,49 usage : BufferUsage.STATIC_DRAW50 });51 }).toThrowDeveloperError();52 });53 it('throws when creating a vertex buffer without a typed array or size in bytes', function() {54 expect(function() {55 buffer = Buffer.createVertexBuffer({56 context : context,57 usage : BufferUsage.STATIC_DRAW58 });59 }).toThrowDeveloperError();60 });61 it('throws when creating a vertex buffer with invalid usage', function() {62 expect(function() {63 buffer = Buffer.createVertexBuffer({64 context : context,65 sizeInBytes : 16,66 usage : 067 });68 }).toThrowDeveloperError();69 });70 it('throws when creating a vertex buffer with size of zero', function() {71 expect(function() {72 buffer = Buffer.createVertexBuffer({73 context : context,74 sizeInBytes : 0,75 usage : BufferUsage.STATIC_DRAW76 });77 }).toThrowDeveloperError();78 });79 it('creates vertex buffer', function() {80 buffer = Buffer.createVertexBuffer({81 context : context,82 sizeInBytes : 16,83 usage : BufferUsage.STATIC_DRAW84 });85 expect(buffer.sizeInBytes).toEqual(16);86 expect(buffer.usage).toEqual(BufferUsage.STATIC_DRAW);87 });88 it('copies array to a vertex buffer', function() {89 var sizeInBytes = 3 * Float32Array.BYTES_PER_ELEMENT;90 var vertices = new ArrayBuffer(sizeInBytes);91 var positions = new Float32Array(vertices);92 positions[0] = 1.0;93 positions[1] = 2.0;94 positions[2] = 3.0;95 buffer = Buffer.createVertexBuffer({96 context : context,97 sizeInBytes : sizeInBytes,98 usage : BufferUsage.STATIC_DRAW99 });100 buffer.copyFromArrayView(vertices);101 });102 it('can create a vertex buffer from a typed array', function() {103 var typedArray = new Float32Array(3 * Float32Array.BYTES_PER_ELEMENT);104 typedArray[0] = 1.0;105 typedArray[1] = 2.0;106 typedArray[2] = 3.0;107 buffer = Buffer.createVertexBuffer({108 context : context,109 typedArray : typedArray,110 usage : BufferUsage.STATIC_DRAW111 });112 expect(buffer.sizeInBytes).toEqual(typedArray.byteLength);113 expect(buffer.usage).toEqual(BufferUsage.STATIC_DRAW);114 });115 it('can create a vertex buffer from a size in bytes', function() {116 buffer = Buffer.createVertexBuffer({117 context : context,118 sizeInBytes : 4,119 usage : BufferUsage.STATIC_DRAW120 });121 expect(buffer.sizeInBytes).toEqual(4);122 expect(buffer.usage).toEqual(BufferUsage.STATIC_DRAW);123 });124 it('throws when creating an index buffer with no context', function() {125 expect(function() {126 buffer = Buffer.createIndexBuffer({127 sizeInBytes : 4,128 usage : BufferUsage.STATIC_DRAW,129 indexDatatype : IndexDatatype.UNSIGNED_SHORT130 });131 }).toThrowDeveloperError();132 });133 it('throws when creating an index buffer with an invalid typed array', function() {134 expect(function() {135 buffer = Buffer.createIndexBuffer({136 context : context,137 typedArray : {},138 usage : BufferUsage.STATIC_DRAW,139 indexDatatype : IndexDatatype.UNSIGNED_SHORT140 });141 }).toThrowDeveloperError();142 });143 it('throws when creating an index buffer with both a typed array and size in bytes', function() {144 expect(function() {145 buffer = Buffer.createIndexBuffer({146 context : context,147 typedArray : new Uint16Array([0, 1, 2, 0, 2, 3]),148 sizeInBytes : 12,149 usage : BufferUsage.STATIC_DRAW,150 indexDatatype : IndexDatatype.UNSIGNED_SHORT151 });152 }).toThrowDeveloperError();153 });154 it('throws when creating an index buffer without a typed array or size in bytes', function() {155 expect(function() {156 buffer = Buffer.createIndexBuffer({157 context : context,158 usage : BufferUsage.STATIC_DRAW,159 indexDatatype : IndexDatatype.UNSIGNED_SHORT160 });161 }).toThrowDeveloperError();162 });163 it('throws when creating an index buffer with invalid usage', function() {164 expect(function() {165 buffer = Buffer.createIndexBuffer({166 context : context,167 sizeInBytes : 16,168 usage : "invalid",169 indexDatatype : IndexDatatype.UNSIGNED_SHORT170 });171 }).toThrowDeveloperError();172 });173 it('throws when creating an index buffer with invalid index data type', function() {174 expect(function() {175 buffer = Buffer.createIndexBuffer({176 context : context,177 sizeInBytes : 16,178 usage : BufferUsage.STATIC_DRAW,179 indexDatatype : 'invalid'180 });181 }).toThrowDeveloperError();182 });183 it('throws when creating an index buffer with size of zero', function() {184 expect(function() {185 buffer = Buffer.createIndexBuffer({186 context : context,187 sizeInBytes : 0,188 usage : BufferUsage.STATIC_DRAW,189 indexDatatype : IndexDatatype.UNSIGNED_SHORT190 });191 }).toThrowDeveloperError();192 });193 it('creates index buffer', function() {194 buffer = Buffer.createIndexBuffer({195 context : context,196 sizeInBytes : 6,197 usage : BufferUsage.STREAM_DRAW,198 indexDatatype : IndexDatatype.UNSIGNED_SHORT199 });200 expect(buffer.sizeInBytes).toEqual(6);201 expect(buffer.usage).toEqual(BufferUsage.STREAM_DRAW);202 expect(buffer.indexDatatype).toEqual(IndexDatatype.UNSIGNED_SHORT);203 expect(buffer.bytesPerIndex).toEqual(2);204 expect(buffer.numberOfIndices).toEqual(3);205 });206 it('copies array to an index buffer', function() {207 var sizeInBytes = 3 * Uint16Array.BYTES_PER_ELEMENT;208 var elements = new ArrayBuffer(sizeInBytes);209 var indices = new Uint16Array(elements);210 indices[0] = 1;211 indices[1] = 2;212 indices[2] = 3;213 buffer = Buffer.createIndexBuffer({214 context : context,215 sizeInBytes : sizeInBytes,216 usage : BufferUsage.STATIC_DRAW,217 indexDatatype : IndexDatatype.UNSIGNED_SHORT218 });219 buffer.copyFromArrayView(elements);220 });221 it('can create an index buffer from a typed array', function() {222 var typedArray = new Uint16Array(3 * Uint16Array.BYTES_PER_ELEMENT);223 typedArray[0] = 1;224 typedArray[1] = 2;225 typedArray[2] = 3;226 buffer = Buffer.createIndexBuffer({227 context : context,228 typedArray : typedArray,229 usage : BufferUsage.STATIC_DRAW,230 indexDatatype : IndexDatatype.UNSIGNED_SHORT231 });232 expect(buffer.sizeInBytes).toEqual(typedArray.byteLength);233 expect(buffer.usage).toEqual(BufferUsage.STATIC_DRAW);234 expect(buffer.indexDatatype).toEqual(IndexDatatype.UNSIGNED_SHORT);235 });236 it('can create an index buffer from a size in bytes', function() {237 buffer = Buffer.createIndexBuffer({238 context : context,239 sizeInBytes : 6,240 usage : BufferUsage.STATIC_DRAW,241 indexDatatype : IndexDatatype.UNSIGNED_SHORT242 });243 expect(buffer.sizeInBytes).toEqual(6);244 expect(buffer.usage).toEqual(BufferUsage.STATIC_DRAW);245 expect(buffer.indexDatatype).toEqual(IndexDatatype.UNSIGNED_SHORT);246 });247 it('destroys', function() {248 var b = Buffer.createIndexBuffer({249 context : context,250 sizeInBytes : 3,251 usage : BufferUsage.STATIC_DRAW,252 indexDatatype : IndexDatatype.UNSIGNED_BYTE253 });254 expect(b.isDestroyed()).toEqual(false);255 b.destroy();256 expect(b.isDestroyed()).toEqual(true);257 });258 it('fails to provide an array view', function() {259 buffer = Buffer.createVertexBuffer({260 context : context,261 sizeInBytes : 3,262 usage : BufferUsage.STATIC_DRAW263 });264 expect(function() {265 buffer.copyFromArrayView();266 }).toThrowDeveloperError();267 });268 it('fails to copy a large array view', function() {269 buffer = Buffer.createVertexBuffer({270 context : context,271 sizeInBytes : 3,272 usage : BufferUsage.STATIC_DRAW273 });274 var elements = new ArrayBuffer(3);275 expect(function() {276 buffer.copyFromArrayView(elements, 1);277 }).toThrowDeveloperError();278 });279 it('fails to destroy', function() {280 var b = Buffer.createIndexBuffer({281 context : context,282 sizeInBytes : 3,283 usage : BufferUsage.STATIC_DRAW,284 indexDatatype : IndexDatatype.UNSIGNED_BYTE285 });286 b.destroy();287 expect(function() {288 b.destroy();289 }).toThrowDeveloperError();290 });...

Full Screen

Full Screen

webgl-demo.js

Source:webgl-demo.js Github

copy

Full Screen

1var canvas;2var gl;34var mvMatrix;5var shaderProgram;6var vertexPositionAttribute;7var vertexColorAttribute;8var textureCoordAttribute;9var perspectiveMatrix;10var _totalIndices;1112var baseTime = false;13var mode = 0;1415var nBuffers = 3;16var buffers = [];17var bufLength = 2;18var tunnelTexture;19var tfrom = -1, tto = -1;2021function trajectory(t)22{23 var q = t/200*Math.PI*2;24 var mul = 1.5;25 q /= mul;2627 var x = Math.cos(q)*4;28 var y = Math.sin(q)*4+Math.cos(q*2)*2;29 var z = Math.cos(q*3)*5;30 var r = Math.cos(q*2)*0.2+0.5;31 return {v:$V([x*mul, y*mul, z*mul]), r:r};32}3334function dvec(v) { return !v? "NULL" : (v.e(1).toFixed(2) + " " + v.e(2).toFixed(2) + " " + v.e(3).toFixed(2));}3536function buildWormhole(detail, y0, y1, func)37{38 var data = [];39 if ( typeof(globCircle) == "undefined" || globCircle.length != detail )40 {41 console.log("Calculating circle");42 globCircle = new Array(detail);43 for ( var x=0; x<detail; x++)44 globCircle[x] = [Math.cos(x/detail*2*Math.PI), Math.sin(x/detail*2*Math.PI)];45 }4647 var prev = func(y0);48 for (var y=y0; y<y1; y++)49 {50 var center = prev; //func(y);51 var newCenter = func(y+1);52 prev = newCenter;5354 var vect = newCenter.v.subtract(center.v);5556 vect1 = center.v.cross(newCenter.v).toUnitVector();57 vect2 = vect.cross(vect1).toUnitVector();5859 data[y-y0] = [];60 for (var x=0; x<detail; x++)61 {62 var _cos = globCircle[x][0]*center.r;63 var _sin = globCircle[x][1]*center.r;64 var pt = $V([65 vect1.e(1)*_cos + vect2.e(1)*_sin,66 vect1.e(2)*_cos + vect2.e(2)*_sin,67 vect1.e(3)*_cos + vect2.e(3)*_sin68 ]);69 data[y-y0][x] = center.v.add(pt);//{x: center.x + pt.e(1), y: center.y + pt.e(2), z: center.z + pt.e(3)};70 }71 }72 return data;73}7475function createBuffer(_from, _to) 76{77 var w = 8, h = _to - _from;7879 var wormhole = buildWormhole(w, _from, _to, trajectory);8081 var vertices = new Array(h*w*3);82 var colors = new Array(h*w*4);83 var indices = new Array((h-1)*w*6);84 var coords = new Array(h*w*2);8586 var vertexi = 0, colori = 0, indexi = 0, coordi = 0;8788 for (var y=0; y<h; y++)89 for (var x=0; x<w; x++) 90 {91 var vertex = wormhole[y][x];92 vertices[vertexi++] = vertex.e(1);93 vertices[vertexi++] = vertex.e(2);94 vertices[vertexi++] = vertex.e(3);9596 var color = [0.8 + Math.random(), 0.8 + Math.random(), 0.8 + Math.random(), 1];97 if ( x == 0 ) color = [0, 1, 0, 1];98 if ( x == Math.floor(w/2) ) color = [0, 0, 1, 1];99100 colors[colori++] = color[0];101 colors[colori++] = color[1];102 colors[colori++] = color[2];103 colors[colori++] = color[3];104105 coords[coordi++] = x/w;106 coords[coordi++] = y/8;107 }108109 for ( var y=0; y<h-1; y++)110 {111 var base0 = y*w;112 var base1 = y*w+w;113 for ( var x=0; x<w; x++)114 {115 indices[indexi++] = base0 + x;116 indices[indexi++] = base0 + (x+1)%w;117 indices[indexi++] = base1 + x;118119 indices[indexi++] = base1 + x;120 indices[indexi++] = base0 + (x+1)%w;121 indices[indexi++] = base1 + (x+1)%w;122 }123 }124125 var cubeVerticesBuffer = gl.createBuffer();126 gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesBuffer);127 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);128129 var cubeVerticesColorBuffer = gl.createBuffer();130 gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesColorBuffer);131 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);132133 var cubeVerticesIndexBuffer = gl.createBuffer();134 gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVerticesIndexBuffer);135 gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);136137 var cubeVertexTextureCoordBuffer = gl.createBuffer();138 gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexTextureCoordBuffer);139 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(coords), gl.STATIC_DRAW);140141 return {142 vertexBuffer:cubeVerticesBuffer, 143 colorBuffer:cubeVerticesColorBuffer, 144 indexBuffer:cubeVerticesIndexBuffer, 145 coordBuffer:cubeVertexTextureCoordBuffer,146 indices:indices.length,147 range:{from:_from, to:_to}148 };149}150151function buildVbo(data)152{153 var result = {};154 if ( data.vertexBuffer )155 {156 result.vertexBuffer = gl.createBuffer();157 gl.bindBuffer(gl.ARRAY_BUFFER, result.vertexBuffer);158 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(data.vertexBuffer), gl.STATIC_DRAW);159 }160161 if ( data.colorBuffer )162 {163 result.colorBuffer = gl.createBuffer();164 gl.bindBuffer(gl.ARRAY_BUFFER, result.colorBuffer);165 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(data.colorBuffer), gl.STATIC_DRAW);166 }167168 if ( data.indexBuffer )169 {170 result.indices = data.indexBuffer.length;171 result.indexBuffer = gl.createBuffer();172 gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, result.indexBuffer);173 gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(data.indexBuffer), gl.STATIC_DRAW);174 }175176 if ( data.coordBuffer )177 {178 result.coordBuffer = gl.createBuffer();179 gl.bindBuffer(gl.ARRAY_BUFFER, result.coordBuffer);180 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(data.coordBuffer), gl.STATIC_DRAW);181 }182 return result;183}184185function drawBuffer(buf)186{187 if ( !buf || !buf.vertexBuffer )188 return;189190 gl.bindBuffer(gl.ARRAY_BUFFER, buf.vertexBuffer);191 gl.vertexAttribPointer(vertexPositionAttribute, 3, gl.FLOAT, false, 0, 0);192193 gl.bindBuffer(gl.ARRAY_BUFFER, buf.colorBuffer);194 gl.vertexAttribPointer(vertexColorAttribute, 4, gl.FLOAT, false, 0, 0);195196 gl.bindBuffer(gl.ARRAY_BUFFER, buf.coordBuffer);197 gl.vertexAttribPointer(textureCoordAttribute, 2, gl.FLOAT, false, 0, 0);198 199 gl.activeTexture(gl.TEXTURE0);200 gl.bindTexture(gl.TEXTURE_2D, tunnelTexture);201 gl.uniform1i(shaderProgram.samplerUniform, 0);202 203 gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buf.indexBuffer);204 setMatrixUniforms();205206 gl.drawElements(gl.TRIANGLES, buf.indices, gl.UNSIGNED_SHORT, 0);207}208209function handleTextureLoad(image, texture)210{211 gl.bindTexture(gl.TEXTURE_2D, texture);212 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);213 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);214 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);215 gl.generateMipmap(gl.TEXTURE_2D);216 gl.bindTexture(gl.TEXTURE_2D, null);217}218219function isInRange(buf, t)220{221 if ( !buf || !buf.range )222 return false;223 return ( t <= buf.range.to );224}225226function traceForward(base, dist)227{228 // todo: optimize!229 var len = 0, t = 0;230 var cur = trajectory(base);231 do {232 t += 0.1;233 var next = trajectory(base+t);234 var curdist = cur.v.distanceFrom(next.v);235 len += curdist;236 cur = next;237 } while (len < dist);238 return cur;239}240241function drawScene() 242{ 243 var currentTime = (new Date).getTime();244 if ( !baseTime )245 {246 baseTime = currentTime;247248 tunnelTexture = gl.createTexture();249 tunnelTexture.image = new Image();250 tunnelTexture.image.onload = function() { handleTextureLoad(tunnelTexture.image, tunnelTexture); }251 tunnelTexture.image.src = "texture.jpg"; // NOTE: chrome, firefox won't load local textures!252253 gl.uniform1f(shaderProgram.enableFog, 1*1.0);254255 vboBall = createBall(0.05);256 vboBigBall = createBall(1);257 vboPlane = createPlane();258 }259 currentTime -= baseTime;260261262 gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);263 perspectiveMatrix = makePerspective(45, 960.0/540.0, 0.1, 100.0);264 loadIdentity();265266// gl.enable(gl.SCISSOR_TEST);267268 // generate VBOs269 var speed = 1/250/2;270 var t = currentTime*speed;271 var len = bufLength * 8;272273 while ( buffers.length < nBuffers )274 {275 var last = (buffers.length == 0) ? Math.floor(t) : buffers[buffers.length-1].range.to-1;276 buffers[buffers.length] = createBuffer(last, last+len+1);277 }278279 while ( buffers.length > 0 && buffers[0].range.to < t )280 buffers.shift();281282283 var pt0 = trajectory(t);284 var pt1 = traceForward(t, 1);285 var pt2 = traceForward(t, 2);286 var maxup = (pt1.v.subtract(pt0.v).subtract(pt2.v.subtract(pt1.v))).toUnitVector().multiply(-1); 287 var up = pt0.v.cross(pt2.v).toUnitVector();288 289 var forw = pt1.v.subtract(pt2.v).toUnitVector();290 var stra1 = forw.cross(up).multiply(+0.05);291 var stra2 = forw.cross(up).multiply(-0.05);292293 mvPushMatrix();294 multMatrix(makeLookAt(295 pt0.v.e(1), pt0.v.e(2), pt0.v.e(3), 296 pt1.v.e(1), pt1.v.e(2), pt1.v.e(3),297 up.e(1), up.e(2), up.e(3)));298299 mvTranslate([stra1.e(1), stra1.e(2), stra1.e(3)]);300 301302// gl.scissor(0,0,960/2,540);303 gl.viewport(0,0,960,540/2);304305 for ( buf in buffers )306 drawBuffer(buffers[buf]);307308 mvTranslate([-stra1.e(1), -stra1.e(2), -stra1.e(3)]);309 mvTranslate([stra2.e(1), stra2.e(2), stra2.e(3)]);310311// gl.scissor(960/2,0,960/2,540);312 gl.viewport(0,540/2,960,540/2);313314 for ( buf in buffers )315 drawBuffer(buffers[buf]);316317}318319document.onkeypress=function(e){320 var e=window.event || e321 if ( ++mode >= 3 ) mode = 0;322 gl.uniform1f(shaderProgram.enableFog, mode == 2 ? 0 : 1); ...

Full Screen

Full Screen

classtlx_1_1RingBuffer.js

Source:classtlx_1_1RingBuffer.js Github

copy

Full Screen

1var classtlx_1_1RingBuffer =2[3 [ "alloc_traits", "classtlx_1_1RingBuffer.html#afa4e55910e087a8c2393c8e09eb78b4f", null ],4 [ "allocator_type", "classtlx_1_1RingBuffer.html#a1b9340a5b56dce81fa182aee8c64e363", null ],5 [ "const_pointer", "classtlx_1_1RingBuffer.html#a942671c3bf981a9c6aed99563af3ae3f", null ],6 [ "const_reference", "classtlx_1_1RingBuffer.html#a19b0fa325e3dfdd4d732bb52c8f20e93", null ],7 [ "difference_type", "classtlx_1_1RingBuffer.html#a4db1526a7432629938f1aba3203accaa", null ],8 [ "pointer", "classtlx_1_1RingBuffer.html#a1eb349cbe5db02193774b9026a90df1c", null ],9 [ "reference", "classtlx_1_1RingBuffer.html#a3386b4404c6a6b493b35ff08e1b57217", null ],10 [ "size_type", "classtlx_1_1RingBuffer.html#adc178afcc34fc9f6a71f60f1c305084d", null ],11 [ "value_type", "classtlx_1_1RingBuffer.html#af0f70ef64d23e2379bacb63968e68b45", null ],12 [ "RingBuffer", "classtlx_1_1RingBuffer.html#ad76f5f87b217dab7b48ea7dff1871900", null ],13 [ "RingBuffer", "classtlx_1_1RingBuffer.html#a9e3a80a04841d98f044cf2cb67c04d0f", null ],14 [ "RingBuffer", "classtlx_1_1RingBuffer.html#aba418f11115fef12dd9f6a7ce017614a", null ],15 [ "RingBuffer", "classtlx_1_1RingBuffer.html#a3737f2f41c869f2c49b56f11ebf33f1e", null ],16 [ "~RingBuffer", "classtlx_1_1RingBuffer.html#a0fff6182d30d785358c6a3ef7db0931f", null ],17 [ "allocate", "classtlx_1_1RingBuffer.html#a3bb82abc6851598063f31094a69bac5e", null ],18 [ "back", "classtlx_1_1RingBuffer.html#a9870425783540b4ca3fe8052772fcaa8", null ],19 [ "back", "classtlx_1_1RingBuffer.html#afc77f0e3f44c6712f6bf4aa5f452a99f", null ],20 [ "capacity", "classtlx_1_1RingBuffer.html#a260442ef344f843c480ff1f6aefd6db3", null ],21 [ "clear", "classtlx_1_1RingBuffer.html#ac8bb3912a3ce86b15842e79d0b421204", null ],22 [ "copy_to", "classtlx_1_1RingBuffer.html#a4712b32d7697035eb2dfd864bfbaeab6", null ],23 [ "deallocate", "classtlx_1_1RingBuffer.html#a2d68be4fd20ffdd7f7a9b51579eacc2f", null ],24 [ "emplace_back", "classtlx_1_1RingBuffer.html#ac294eba73765b9a72a7399d64e8ecd9a", null ],25 [ "emplace_front", "classtlx_1_1RingBuffer.html#a7587ef607434c3fe91f80c45d5c0d8da", null ],26 [ "empty", "classtlx_1_1RingBuffer.html#a3f6fc5de06a318920d84f3c3742db07f", null ],27 [ "front", "classtlx_1_1RingBuffer.html#aa688f5c7b1552245701b0d16d6b95ec6", null ],28 [ "front", "classtlx_1_1RingBuffer.html#af6ce9aca34b12f7e9794186afdbd8025", null ],29 [ "load", "classtlx_1_1RingBuffer.html#a27f4b372d3515f81ee63062814c2bbe9", null ],30 [ "max_size", "classtlx_1_1RingBuffer.html#aa77c5677e96e956feccbd5a7abbf8fe2", null ],31 [ "move_to", "classtlx_1_1RingBuffer.html#ac4eb8f7058fc153a56de3da92a8f4817", null ],32 [ "operator=", "classtlx_1_1RingBuffer.html#a07e35b4118f1356c1b2745d60273fcfe", null ],33 [ "operator=", "classtlx_1_1RingBuffer.html#a0176d9303b082e74cc33cc7c8bfd1e2f", null ],34 [ "operator[]", "classtlx_1_1RingBuffer.html#aab6af54d683011c8da699fd13cf22b56", null ],35 [ "operator[]", "classtlx_1_1RingBuffer.html#a7d4e17439baa2cdfd0be4cca86577251", null ],36 [ "pop_back", "classtlx_1_1RingBuffer.html#a058bda4957df6a97b1ea6c9fd783f672", null ],37 [ "pop_front", "classtlx_1_1RingBuffer.html#a56f4ffbc6fd414b3c02a6c368e99594f", null ],38 [ "push_back", "classtlx_1_1RingBuffer.html#a6fc9f02cb6de7b518120ccd2bce5302a", null ],39 [ "push_back", "classtlx_1_1RingBuffer.html#a8671f30ba2b80ddb4b309dfa13f0600d", null ],40 [ "push_front", "classtlx_1_1RingBuffer.html#a7b05c0ba4868fafcd6306cb22602ee87", null ],41 [ "push_front", "classtlx_1_1RingBuffer.html#a0ad98831bee02df314496ffab4500536", null ],42 [ "save", "classtlx_1_1RingBuffer.html#ad719b5a03421363e973983b4e088ecb3", null ],43 [ "size", "classtlx_1_1RingBuffer.html#a0801762a3fe36fe32dca5f16e515478d", null ],44 [ "alloc_", "classtlx_1_1RingBuffer.html#af8ef2a35aadec4f191c273973f1304a6", null ],45 [ "begin_", "classtlx_1_1RingBuffer.html#a6f51da5125ced58697d7f8b51640bf74", null ],46 [ "capacity_", "classtlx_1_1RingBuffer.html#aa3099a4c2b0b3ab5ba4188b4a8f59b26", null ],47 [ "data_", "classtlx_1_1RingBuffer.html#a98e4560adae148e80c54e8f07b59685f", null ],48 [ "end_", "classtlx_1_1RingBuffer.html#a70f45a20b6aebf0123d92011c045ad50", null ],49 [ "mask_", "classtlx_1_1RingBuffer.html#a7b17e9608c37b08dc3312f2ce0611f59", null ],50 [ "max_size_", "classtlx_1_1RingBuffer.html#a6c71cd8b63dbd5e33c81719592b68977", null ]...

Full Screen

Full Screen

test-buffer-bytelength.js

Source:test-buffer-bytelength.js Github

copy

Full Screen

1'use strict';2var Buffer = require('../../').Buffer;3var assert = require('assert');4var Buffer = require('../../').Buffer;5var SlowBuffer = require('../../').SlowBuffer;6// coerce values to string7assert.equal(Buffer.byteLength(32, 'latin1'), 2);8assert.equal(Buffer.byteLength(NaN, 'utf8'), 3);9assert.equal(Buffer.byteLength({}, 'latin1'), 15);10assert.equal(Buffer.byteLength(), 9);11var buff = new Buffer(10);12assert(ArrayBuffer.isView(buff));13var slowbuff = new SlowBuffer(10);14assert(ArrayBuffer.isView(slowbuff));15// buffer16var incomplete = Buffer.from([0xe4, 0xb8, 0xad, 0xe6, 0x96]);17assert.equal(Buffer.byteLength(incomplete), 5);18var ascii = Buffer.from('abc');19assert.equal(Buffer.byteLength(ascii), 3);20// ArrayBuffer21var buffer = new ArrayBuffer(8);22assert.equal(Buffer.byteLength(buffer), 8);23// TypedArray24var int8 = new Int8Array(8);25assert.equal(Buffer.byteLength(int8), 8);26var uint8 = new Uint8Array(8);27assert.equal(Buffer.byteLength(uint8), 8);28var uintc8 = new Uint8ClampedArray(2);29assert.equal(Buffer.byteLength(uintc8), 2);30var int16 = new Int16Array(8);31assert.equal(Buffer.byteLength(int16), 16);32var uint16 = new Uint16Array(8);33assert.equal(Buffer.byteLength(uint16), 16);34var int32 = new Int32Array(8);35assert.equal(Buffer.byteLength(int32), 32);36var uint32 = new Uint32Array(8);37assert.equal(Buffer.byteLength(uint32), 32);38var float32 = new Float32Array(8);39assert.equal(Buffer.byteLength(float32), 32);40var float64 = new Float64Array(8);41assert.equal(Buffer.byteLength(float64), 64);42// DataView43var dv = new DataView(new ArrayBuffer(2));44assert.equal(Buffer.byteLength(dv), 2);45// special case: zero length string46assert.equal(Buffer.byteLength('', 'ascii'), 0);47assert.equal(Buffer.byteLength('', 'HeX'), 0);48// utf849assert.equal(Buffer.byteLength('∑éllö wørl∂!', 'utf-8'), 19);50assert.equal(Buffer.byteLength('κλμνξο', 'utf8'), 12);51assert.equal(Buffer.byteLength('挵挶挷挸挹', 'utf-8'), 15);52assert.equal(Buffer.byteLength('𠝹𠱓𠱸', 'UTF8'), 12);53// without an encoding, utf8 should be assumed54assert.equal(Buffer.byteLength('hey there'), 9);55assert.equal(Buffer.byteLength('𠱸挶νξ#xx :)'), 17);56assert.equal(Buffer.byteLength('hello world', ''), 11);57// it should also be assumed with unrecognized encoding58assert.equal(Buffer.byteLength('hello world', 'abc'), 11);59assert.equal(Buffer.byteLength('ßœ∑≈', 'unkn0wn enc0ding'), 10);60// base6461assert.equal(Buffer.byteLength('aGVsbG8gd29ybGQ=', 'base64'), 11);62assert.equal(Buffer.byteLength('bm9kZS5qcyByb2NrcyE=', 'base64'), 14);63assert.equal(Buffer.byteLength('aGkk', 'base64'), 3);64assert.equal(Buffer.byteLength('bHNrZGZsa3NqZmtsc2xrZmFqc2RsZmtqcw==',65 'base64'), 25);66// special padding67assert.equal(Buffer.byteLength('aaa=', 'base64'), 2);68assert.equal(Buffer.byteLength('aaaa==', 'base64'), 3);69assert.equal(Buffer.byteLength('Il était tué'), 14);70assert.equal(Buffer.byteLength('Il était tué', 'utf8'), 14);71assert.equal(Buffer.byteLength('Il était tué', 'ascii'), 12);72assert.equal(Buffer.byteLength('Il était tué', 'latin1'), 12);73assert.equal(Buffer.byteLength('Il était tué', 'binary'), 12);74['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) {75 assert.equal(24, Buffer.byteLength('Il était tué', encoding));...

Full Screen

Full Screen

buffer-util.js

Source:buffer-util.js Github

copy

Full Screen

1'use strict';2const { EMPTY_BUFFER } = require('./constants');3/**4 * Merges an array of buffers into a new buffer.5 *6 * @param {Buffer[]} list The array of buffers to concat7 * @param {Number} totalLength The total length of buffers in the list8 * @return {Buffer} The resulting buffer9 * @public10 */11function concat(list, totalLength) {12 if (list.length === 0) return EMPTY_BUFFER;13 if (list.length === 1) return list[0];14 const target = Buffer.allocUnsafe(totalLength);15 var offset = 0;16 for (var i = 0; i < list.length; i++) {17 const buf = list[i];18 buf.copy(target, offset);19 offset += buf.length;20 }21 return target;22}23/**24 * Masks a buffer using the given mask.25 *26 * @param {Buffer} source The buffer to mask27 * @param {Buffer} mask The mask to use28 * @param {Buffer} output The buffer where to store the result29 * @param {Number} offset The offset at which to start writing30 * @param {Number} length The number of bytes to mask.31 * @public32 */33function _mask(source, mask, output, offset, length) {34 for (var i = 0; i < length; i++) {35 output[offset + i] = source[i] ^ mask[i & 3];36 }37}38/**39 * Unmasks a buffer using the given mask.40 *41 * @param {Buffer} buffer The buffer to unmask42 * @param {Buffer} mask The mask to use43 * @public44 */45function _unmask(buffer, mask) {46 // Required until https://github.com/nodejs/node/issues/9006 is resolved.47 const length = buffer.length;48 for (var i = 0; i < length; i++) {49 buffer[i] ^= mask[i & 3];50 }51}52/**53 * Converts a buffer to an `ArrayBuffer`.54 *55 * @param {Buffer} buf The buffer to convert56 * @return {ArrayBuffer} Converted buffer57 * @public58 */59function toArrayBuffer(buf) {60 if (buf.byteLength === buf.buffer.byteLength) {61 return buf.buffer;62 }63 return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);64}65/**66 * Converts `data` to a `Buffer`.67 *68 * @param {*} data The data to convert69 * @return {Buffer} The buffer70 * @throws {TypeError}71 * @public72 */73function toBuffer(data) {74 toBuffer.readOnly = true;75 if (Buffer.isBuffer(data)) return data;76 var buf;77 if (data instanceof ArrayBuffer) {78 buf = Buffer.from(data);79 } else if (ArrayBuffer.isView(data)) {80 buf = viewToBuffer(data);81 } else {82 buf = Buffer.from(data);83 toBuffer.readOnly = false;84 }85 return buf;86}87/**88 * Converts an `ArrayBuffer` view into a buffer.89 *90 * @param {(DataView|TypedArray)} view The view to convert91 * @return {Buffer} Converted view92 * @private93 */94function viewToBuffer(view) {95 const buf = Buffer.from(view.buffer);96 if (view.byteLength !== view.buffer.byteLength) {97 return buf.slice(view.byteOffset, view.byteOffset + view.byteLength);98 }99 return buf;100}101try {102 const bufferUtil = require('bufferutil');103 const bu = bufferUtil.BufferUtil || bufferUtil;104 module.exports = {105 concat,106 mask(source, mask, output, offset, length) {107 if (length < 48) _mask(source, mask, output, offset, length);108 else bu.mask(source, mask, output, offset, length);109 },110 toArrayBuffer,111 toBuffer,112 unmask(buffer, mask) {113 if (buffer.length < 32) _unmask(buffer, mask);114 else bu.unmask(buffer, mask);115 }116 };117} catch (e) /* istanbul ignore next */ {118 module.exports = {119 concat,120 mask: _mask,121 toArrayBuffer,122 toBuffer,123 unmask: _unmask124 };...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1 * @param {number[]} prices2 * @return {number}3var maxProfit = function(prices) {4 var min = prices[0];5 var max = 0;6 for (var i = 0; i < prices.length; i++) {7 if (prices[i] < min) {8 min = prices[i];9 }10 else if (prices[i] - min > max) {11 max = prices[i] - min;12 }13 }14 return max;15};

Full Screen

Using AI Code Generation

copy

Full Screen

1var fs = require('fs');2var bestFit = require('./bestFit.js');3var worstFit = require('./worstFit.js');4var firstFit = require('./firstFit.js');5var nextFit = require('./nextFit.js');6var data = fs.readFileSync('input.txt');7var input = data.toString().split("\n");8var inputNum = input[0].split(" ");9var inputNum = inputNum.map(Number);10var inputArr = input[1].split(" ");11var inputArr = inputArr.map(Number);12var inputMem = input[2].split(" ");13var inputMem = inputMem.map(Number);14var inputHoles = input[3].split(" ");15var inputHoles = inputHoles.map(Number);16var inputHoleSize = input[4].split(" ");17var inputHoleSize = inputHoleSize.map(Number);18var inputHoleStart = input[5].split(" ");19var inputHoleStart = inputHoleStart.map(Number);20var inputHoleEnd = input[6].split(" ");21var inputHoleEnd = inputHoleEnd.map(Number);22var inputMemSize = input[7].split(" ");23var inputMemSize = inputMemSize.map(Number);24var output = "";25var output1 = "";26var output2 = "";27var output3 = "";28var output4 = "";29for (var i = 0; i < inputNum[1]; i++) {30 output1 += bestFit.bestFit(inputMem, inputArr[i], inputHoles, inputHoleSize, inputHoleStart, inputHoleEnd, inputMemSize);31 output1 += "\n";32}33for (var i = 0; i < inputNum[1]; i++) {34 output2 += worstFit.worstFit(inputMem, inputArr[i], inputHoles, inputHoleSize, inputHoleStart, inputHoleEnd, inputMemSize);35 output2 += "\n";36}37for (var i = 0; i < inputNum[1]; i++) {38 output3 += firstFit.firstFit(inputMem, inputArr[i], inputHoles, inputHoleSize,

Full Screen

Using AI Code Generation

copy

Full Screen

1var BestMatch = require('./BestMatch');2var fs = require('fs');3var file = fs.readFileSync('test4.txt');4var str = file.toString();5var bestMatch = new BestMatch(str);6var result = bestMatch.getBestMatch();7console.log(result);

Full Screen

Using AI Code Generation

copy

Full Screen

1var bestMatch = require('./bestMatch');2 {3 },4 {5 },6 {7 },8 {9 },10 {11 },12 {13 },14 {15 },16 {17 },18 {19 },20 {21 },22 {23 },24 {25 },26 {27 },28 {29 },30 {31 },32 {33 },34 {35 },36 {37 },38 {39 },40 {41 },42 {43 },44 {45 },46 {47 },48 {49 },50 {51 },52 {

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Best automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful