Created
October 1, 2010 07:08
-
-
Save rjungemann/605866 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// parse the FUDI networking protocol used by PureData and Max/MSP | |
// http://wiki.puredata.info/en/FUDI | |
// usable in any CommonJS environment including in-browser or in node.js | |
// still requires TCP/UDP JS client/server implementations | |
var fudi = { | |
tokenize: function(string) { | |
var tokens = []; | |
for(var i = 0; i < string.length; i++) { | |
var c = string[i]; | |
if(c.match(/\n/)) { | |
tokens.push(["whitespace", "\\n"]); | |
} else if(c.match(/\t/)) { | |
tokens.push(["whitespace", "\\t"]); | |
} else if(c.match(/ /)) { | |
tokens.push(["whitespace", " "]); | |
} else if(c.match(/;/)) { | |
tokens.push(["semicolon", c]); | |
} else if(c == "\\") { | |
tokens.push(["backslash", c]); | |
} else { | |
tokens.push(["char", c]); | |
} | |
} | |
for(var i = 0; i < tokens.length; i++) { | |
if( | |
tokens[i][0] == "whitespace" && | |
tokens[i - 1][0] == "backslash" | |
) { | |
tokens[i][0] = "char"; | |
tokens.splice(i - 1, 1); | |
} | |
} | |
for(var i = 0; i < tokens.length; void(0)) { | |
if(tokens[i][0] == "char") { | |
var buffer = ""; | |
loop: | |
for(var j = i; j < tokens.length; j++) { | |
if(tokens[j][0] != "char") { | |
break loop; | |
} else { | |
buffer += tokens[j][1]; | |
} | |
} | |
tokens[i][0] = "atom", tokens[i][1] = buffer; | |
tokens.splice(i + 1, j - i - 1); | |
} else { i++; } | |
} | |
return tokens; | |
}, | |
parse: function(string) { | |
var tokens = fudi.tokenize(string), messages = []; | |
for(var i = 0; i < tokens.length; void(0)) { | |
if(tokens[i][0] == "atom") { | |
var message = []; | |
loop: | |
for(var j = i; j < tokens.length; j++) { | |
if(tokens[j][0] == "atom") { | |
message.push(tokens[j][1]); | |
} else if(tokens[j][0] == "semicolon") { | |
break loop; | |
} | |
} | |
messages.push(message); | |
if(i == j) { i++; } else { i = j + 1; } | |
} else { i++; } | |
} | |
return messages; | |
} | |
} | |
module.exports = fudi; | |
//console.log(fudi.parse("test/blah 123.45314;")); | |
//console.log(fudi.parse("my-slider 12;")); | |
//console.log(fudi.parse("this message continues\nin the following\nline;")) | |
//console.log(fudi.parse("hello this is a message;")); | |
//console.log(fudi.parse("you; can; send; multiple messages; in a line;")); | |
//console.log(fudi.parse("this_atom_contains_a\\\nnewline_character_in_it;")); | |
//console.log(fudi.parse("this\\ is\\ one\\ whole\\ atom;")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment